@omniviewdev/runtime 0.8.0 → 0.8.2

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.
@@ -72,12 +72,13 @@ export type DrawerComponentAction<T = any> = {
72
72
  enabled?: ((ctx: DrawerContext<T>) => boolean) | boolean;
73
73
  /**
74
74
  * The function to run for the drawer component on click.
75
+ * Async actions return a promise so renderers can report rejected operations.
75
76
  *
76
77
  * When a plugin is extending with an action, the component may choose to
77
78
  * pass data about what is inside the component. This is typically the case
78
79
  * with drawers that display resource information.
79
80
  */
80
- action?: (ctx: DrawerContext<T>) => void;
81
+ action?: (ctx: DrawerContext<T>) => void | Promise<unknown>;
81
82
  /**
82
83
  * Have the action provide a list of actions underneath when clicked rather than
83
84
  * initiation the action directly on click.
@@ -103,7 +104,7 @@ export type DrawerComponentActionListItem<T = any> = {
103
104
  * pass data about what is inside the component. This is typically the case
104
105
  * with drawers that display resource information.
105
106
  */
106
- action: (ctx: DrawerContext<T>) => void;
107
+ action: (ctx: DrawerContext<T>) => void | Promise<unknown>;
107
108
  };
108
109
  /**
109
110
  * Context that can be passed to the drawer instantiation
@@ -11,11 +11,21 @@ type CreateSessionOptions = {
11
11
  icon?: string | React.ReactNode;
12
12
  label?: string;
13
13
  opts: Partial<SessionOptions>;
14
+ /** UI-only explicit recovery; never serialized into session options. */
15
+ recovery?: {
16
+ label: string;
17
+ canRecover: (error: {
18
+ title: string;
19
+ suggestion: string;
20
+ raw: string;
21
+ }) => boolean;
22
+ run: () => Promise<void>;
23
+ };
14
24
  };
15
25
  /**
16
26
  * Create or manage sessions from throughout the app
17
27
  */
18
28
  export declare const useExec: ({ pluginID: explicitPluginID }: UseResourceMutationsOptions) => {
19
- createSession: import('@tanstack/react-query').UseMutateAsyncFunction<void, Error, CreateSessionOptions, unknown>;
29
+ createSession: import('@tanstack/react-query').UseMutateAsyncFunction<import('../../models').Session | null, Error, CreateSessionOptions, unknown>;
20
30
  };
21
31
  export default useExec;
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var dt=Object.defineProperty;var ft=(t,e,n)=>e in t?dt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var F=(t,e,n)=>ft(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("react/jsx-runtime"),u=require("react"),V=require("react-router-dom");require("./index-D_aIcqH0.cjs");const S=require("./graphservice-1J8q3eeL.cjs"),k=require("./models-BQsuB2Lj.cjs"),D=require("./events-CtgYnKmS.cjs"),v=require("@tanstack/react-query"),L=require("@omniviewdev/base-ui"),pt=require("./legacyEnum-DkV5yRdA.cjs"),se=u.createContext(void 0),N={PLUGIN_NOT_FOUND:"omniview:plugin/not-found",PLUGIN_NOT_LOADED:"omniview:plugin/not-loaded",PLUGIN_ALREADY_LOADED:"omniview:plugin/already-loaded",PLUGIN_INSTALL_FAILED:"omniview:plugin/install-failed",PLUGIN_LOAD_FAILED:"omniview:plugin/load-failed",PLUGIN_BUILD_FAILED:"omniview:plugin/build-failed",PLUGIN_COMMITTED_CLEANUP_PENDING:"omniview:plugin/committed-cleanup-pending",PLUGIN_COMMIT_UNCERTAIN:"omniview:plugin/commit-uncertain",SETTINGS_MISSING_CONFIG:"omniview:settings/missing-config",SETTINGS_INVALID_CONFIG:"omniview:settings/invalid-config",RESOURCE_NOT_FOUND:"omniview:resource/not-found",RESOURCE_FORBIDDEN:"omniview:resource/forbidden",RESOURCE_UNAUTHORIZED:"omniview:resource/unauthorized",RESOURCE_CONFLICT:"omniview:resource/conflict",RESOURCE_TIMEOUT:"omniview:resource/timeout",RESOURCE_LIMIT:"omniview:resource/limit",RESOURCE_CONTINUATION_EXPIRED:"omniview:resource/continuation-expired",RESOURCE_RESET_REQUIRED:"omniview:resource/reset-required",RESOURCE_PARTIAL:"omniview:resource/partial",RESOURCE_PROVIDER_ERROR:"omniview:resource/provider-error",CONNECTION_NOT_FOUND:"omniview:connection/not-found",CONNECTION_FAILED:"omniview:connection/failed",SESSION_NOT_FOUND:"omniview:session/not-found",SESSION_FAILED:"omniview:session/failed",CANCELLED:"omniview:cancelled",INTERNAL:"omniview:internal",VALIDATION:"omniview:validation",NOT_IMPLEMENTED:"omniview:not-implemented"},xe={INVALID_REQUEST:[N.VALIDATION,400,"correctRequest"],UNSUPPORTED:[N.NOT_IMPLEMENTED,501,"refreshContract"],FORBIDDEN:[N.RESOURCE_FORBIDDEN,403,"none"],UNAUTHORIZED:[N.RESOURCE_UNAUTHORIZED,401,"none"],NOT_FOUND:[N.RESOURCE_NOT_FOUND,404,"none"],CONFLICT:[N.RESOURCE_CONFLICT,409,"refreshContract"],ALREADY_EXISTS:[N.RESOURCE_CONFLICT,409,"refreshContract"],CANCELLED:[N.CANCELLED,499,"none"],TIMEOUT:[N.RESOURCE_TIMEOUT,408,"none"],UNAVAILABLE:[N.CONNECTION_FAILED,503,"reconnect"],CONNECTION_ERROR:[N.CONNECTION_FAILED,503,"reconnect"],CERTIFICATE_ERROR:[N.CONNECTION_FAILED,502,"reconnect"],RESOURCE_LIMIT:[N.RESOURCE_LIMIT,429,"correctRequest"],CONTINUATION_EXPIRED:[N.RESOURCE_CONTINUATION_EXPIRED,410,"restartQuery"],RESET_REQUIRED:[N.RESOURCE_RESET_REQUIRED,409,"restartQuery"],PARTIAL_RESULT:[N.RESOURCE_PARTIAL,422,"none"],PROVIDER_ERROR:[N.RESOURCE_PROVIDER_ERROR,502,"none"],INTERNAL:[N.INTERNAL,500,"none"]};function le(t){return typeof t=="object"&&t!==null?t:void 0}function Q(t,e){return typeof t=="string"&&t.length>0&&t.length<=e}function de(){return{type:N.CANCELLED,code:"CANCELLED",title:"Cancelled",status:499,detail:"The operation was cancelled.",recovery:"none"}}function te(t,e){if(e>4)return;if(t==="cancelled")return de();if(typeof t=="string"){const r=t.trim();if(!r.startsWith("{"))return;try{return te(JSON.parse(r),e+1)}catch{return}}const n=le(t);if(n){if(n.name==="AbortError"||n.name==="CancelError")return de();if(Q(n.type,256)&&Q(n.title,256)&&typeof n.status=="number"&&Number.isInteger(n.status)&&n.status>=100&&n.status<=599&&typeof n.detail=="string"&&n.detail.length<=4096){const r={type:n.type,title:n.title,status:n.status,detail:n.detail};Q(n.code,64)&&(r.code=n.code),Q(n.requestId,256)&&(r.requestId=n.requestId),Q(n.instance,512)&&(r.instance=n.instance),Array.isArray(n.suggestions)&&(r.suggestions=n.suggestions.filter(i=>Q(i,512)).slice(0,8)),Array.isArray(n.actions)&&(r.actions=n.actions.filter(i=>{const o=le(i);return!!o&&["navigate","retry","open-url","copy"].includes(String(o.type))&&Q(o.label,256)&&(o.target===void 0||Q(o.target,4096))}).slice(0,8)),["correctRequest","refreshContract","restartQuery","reconnect","none"].includes(String(n.recovery))&&(r.recovery=n.recovery);const s=le(n.location);return(s==null?void 0:s.unit)==="utf8-byte"&&typeof s.start=="number"&&typeof s.end=="number"&&Number.isSafeInteger(s.start)&&Number.isSafeInteger(s.end)&&s.start>=0&&s.end>=s.start&&(r.location={start:s.start,end:s.end,unit:"utf8-byte"}),r}if(typeof n.code=="string"&&typeof n.title=="string"&&typeof n.message=="string"){let r=n.code;if(r==="PERMISSION_DENIED"&&(r="FORBIDDEN"),["INVALID_INPUT","FILTER_UNKNOWN_FIELD","FILTER_INVALID_OPERATOR"].includes(r)&&(r="INVALID_REQUEST"),Object.prototype.hasOwnProperty.call(xe,r)||(r="INTERNAL"),r==="CANCELLED")return de();const[s,i,o]=xe[r],a=r==="FORBIDDEN"||r==="UNAUTHORIZED"||r==="INTERNAL"||r==="PROVIDER_ERROR";return{type:s,status:i,code:r,recovery:o,title:a?r==="FORBIDDEN"?"Access denied":r==="UNAUTHORIZED"?"Authentication required":"Operation failed":Q(n.title,256)?n.title:"Operation failed",detail:a?"The operation could not be completed.":Q(n.message,4096)?n.message:"The operation could not be completed.",...!a&&Array.isArray(n.suggestions)?{suggestions:n.suggestions.filter(c=>Q(c,512)).slice(0,8)}:{}}}return te(n.message,e+1)??te(n.cause,e+1)}}function W(t){return te(t,0)??{type:N.INTERNAL,title:t==null?"Unknown error":"Error",status:500,detail:t==null?"An unknown error occurred.":"The operation could not be completed."}}function Y(t){return W(t).type===N.CANCELLED}function De(t){switch(t.type){case"navigate":return{label:t.label,onClick:()=>{window.location.hash=t.target??""}};case"open-url":return{label:t.label,onClick:()=>{window.open(t.target,"_blank")}};case"copy":return{label:t.label,onClick:()=>{navigator.clipboard.writeText(t.target??"")}};case"retry":return{label:t.label,onClick:()=>{}};default:return{label:t.label,onClick:()=>{}}}}function Ne(t,e){var s,i;const n=[t.detail,...((s=t.suggestions)==null?void 0:s.map(o=>`• ${o}`))??[]].join(`
2
- `);return{message:e||(t.title!=="Error"?t.title:"Operation failed"),status:"error",details:n,actions:(i=t.actions)==null?void 0:i.map(De)}}function G(t,e,n){if(Y(e))return;const r=W(e);t(Ne(r,n))}function j(t,e){return n=>{if(Y(n))return;const r=W(n);t(Ne(r,r.title!=="Error"?r.title:e))}}function ht(t){const{children:e,pluginId:n,headless:r=!1}=t,[s,i]=u.useState({}),[o,a]=u.useState(new k.PluginMeta),[c,p]=u.useState(!1),[l,h]=u.useState(null),g=u.useRef(0),y=u.useRef(0);console.debug("[PluginContextProvider] render",{pluginId:n,metaLoaded:c,metaError:!!l});const C=u.useCallback(()=>{if(n===void 0||n==="")return;const d=++g.current;console.debug(`[PluginContextProvider] fetching settings for "${n}"`),S.PluginValues(n).then(f=>{d===g.current&&(console.debug(`[PluginContextProvider] settings loaded for "${n}"`,Object.keys(f)),i(f))}).catch(f=>{if(d!==g.current)return;const _=W(f);console.error(`[PluginContextProvider] error fetching settings for "${n}":`,_.detail)})},[n]),R=u.useCallback(()=>{if(n===void 0||n===""){console.debug("[PluginContextProvider] skipping meta fetch — empty pluginId");return}const d=++y.current;console.debug(`[PluginContextProvider] fetching meta for "${n}"`),h(null),S.GetPluginMeta(n).then(f=>{d===y.current&&(console.debug(`[PluginContextProvider] meta loaded for "${n}"`,{name:f==null?void 0:f.name,version:f==null?void 0:f.version}),a(f),p(!0))}).catch(f=>{if(d!==y.current)return;const _=W(f);console.error(`[PluginContextProvider] error fetching meta for "${n}":`,_.detail),h(_.detail),p(!1)})},[n]);if(u.useEffect(()=>{if(c)return;const d=()=>{C(),R()},f=[D.On("plugin/init_complete",d),D.On("plugin/dev_install_complete",_=>{var E;((E=_.data)==null?void 0:E.id)===n&&d()}),D.On("plugin/inventory_changed",d)];return()=>{for(const _ of f)_()}},[n,c,C,R]),u.useEffect(()=>(console.debug(`[PluginContextProvider] useEffect — pluginId changed to "${n}"`),p(!1),h(null),i({}),C(),R(),()=>{++g.current,++y.current}),[n,C,R]),l){if(r)throw new Error(l);return m.jsx("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center",padding:24},children:m.jsxs("div",{style:{maxWidth:480,width:"100%",border:"1px solid #7F1D1D",borderRadius:8,backgroundColor:"#1C1917",padding:20,fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'},children:[m.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12},children:[m.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"#EF4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[m.jsx("circle",{cx:"12",cy:"12",r:"10"}),m.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),m.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),m.jsx("span",{style:{fontSize:14,fontWeight:600,color:"#FECACA"},children:"Plugin failed to load"})]}),m.jsx("p",{style:{fontSize:13,color:"#A1A1AA",margin:"0 0 16px"},children:l}),m.jsx("button",{onClick:()=>R(),style:{background:"transparent",color:"#F87171",border:"1px solid #7F1D1D",borderRadius:6,padding:"6px 14px",fontSize:13,fontWeight:500,cursor:"pointer"},children:"Retry"})]})})}return c?m.jsx(se.Provider,{value:{pluginId:n,settings:s,meta:o},children:e}):r?null:m.jsxs("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center"},children:[m.jsx("div",{style:{width:24,height:24,border:"2px solid #3F3F46",borderTopColor:"#A1A1AA",borderRadius:"50%",animation:"plugin-spin 0.8s linear infinite"}}),m.jsx("style",{children:"@keyframes plugin-spin { to { transform: rotate(360deg); } }"})]})}function oe(){const t=u.useContext(se);if(!t)throw new Error("usePluginContext must be used within a PluginContextProvider");return t}function gt(){return oe().settings}const Ee=u.createContext(void 0),yt=({children:t})=>{const[e,n]=u.useState({}),r=u.useRef(0),s=u.useCallback(()=>{const o=r.current+1;r.current=o,S.Values().then(a=>{o===r.current&&n(a)}).catch(a=>{o===r.current&&console.error("Error fetching settings:",a)})},[]);u.useEffect(()=>{const o=D.On("settings/changed",()=>s());return s(),()=>{r.current+=1,o()}},[s]);const i=u.useCallback(()=>{s()},[s]);return m.jsx(Ee.Provider,{value:{settings:e,reload:i},children:t})},Fe={height:32,focused:0,tabs:[],createTab:()=>{},createTabs:()=>{},updateTab:()=>{},focusTab:()=>{},reorderTab:()=>{},closeTab:()=>{},closeTabs:()=>{},resizeDrawer:()=>{},closeDrawer:()=>{},fullscreenDrawer:()=>{}},Le=u.createContext(Fe),ke=u.createContext(void 0),Me=u.createContext(void 0),Se=u.createContext(void 0),mt=3e4,Et=({children:t})=>{const[e,n]=u.useState([]),r=u.useCallback(a=>{n(c=>[a,...c])},[]),s=u.useCallback((a,c)=>{n(p=>p.map(l=>l.id===a?{...l,...c}:l))},[]),i=u.useCallback(a=>{n(c=>c.filter(p=>p.id!==a))},[]);u.useEffect(()=>{const a=[];for(const c of e)if(c.status!=="running"){const p=Date.now()-(c.completedAt??c.startedAt),l=Math.max(0,mt-p);a.push(setTimeout(()=>i(c.id),l))}return()=>a.forEach(clearTimeout)},[e,i]);const o=u.useMemo(()=>({operations:e,addOperation:r,updateOperation:s,removeOperation:i}),[e,r,s,i]);return m.jsx(Se.Provider,{value:o,children:t})};var ge=function(t,e){return ge=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},ge(t,e)};function St(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ge(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var fe="Invariant Violation",Ie=Object.setPrototypeOf,Ct=Ie===void 0?function(t,e){return t.__proto__=e,t}:Ie,vt=function(t){St(e,t);function e(n){n===void 0&&(n=fe);var r=t.call(this,typeof n=="number"?fe+": "+n+" (see https://github.com/apollographql/invariant-packages)":n)||this;return r.framesToPop=1,r.name=fe,Ct(r,e.prototype),r}return e}(Error);function ye(t,e){if(!t)throw new vt(e)}var je=["debug","log","warn","error","silent"],_t=je.indexOf("log");function J(t){return function(){if(je.indexOf(t)>=_t){var e=console[t]||console.log;return e.apply(console,arguments)}}}(function(t){t.debug=J("debug"),t.log=J("log"),t.warn=J("warn"),t.error=J("error")})(ye||(ye={}));const qe=u.createContext(void 0),Ue=()=>u.useContext(qe);function $e(t){const e=Ue(),n=u.useRef(null),r=e==null?void 0:e.getExtensionPoint(t),s=u.useCallback(o=>{const a=[];return e&&a.push(e.subscribe(o)),r&&a.push(r.subscribe(o)),()=>{for(const c of a)c()}},[e,t,r]),i=u.useCallback(()=>{const o=e==null?void 0:e.getExtensionPoint(t);if(!o){if(n.current&&n.current.store===void 0)return n.current.sentinel;const p={};return n.current={store:void 0,version:-1,sentinel:p},p}const a=n.current;if(a&&a.store===o&&a.version===o.version)return a.sentinel;const c={};return n.current={store:o,version:o.version,sentinel:c},c},[e,t]);return u.useSyncExternalStore(s,i),e==null?void 0:e.getExtensionPoint(t)}const wt=({registry:t,children:e})=>{const n=u.useRef(t);return ye(n.current===t,"You can't change the extension registry after it has been rendered"),m.jsx(qe.Provider,{value:n.current,children:e})},pe=t=>{if(!t||typeof t!="string")throw new TypeError(`extensionName is required to be a string and can't be: "${t}" (${typeof t})`);return t.trim()};class Qe{constructor(e){F(this,"id");F(this,"mode");F(this,"_pluginId");F(this,"_version",0);F(this,"_contributions",new Map);F(this,"_lookupCache",new Map);F(this,"_matcher");F(this,"_select");F(this,"_listeners",new Set);this.id=e.id,this.mode=e.mode??"multiple",this._pluginId=e.pluginId,this._matcher=e.matcher,this._select=e.select}get pluginId(){return this._pluginId}get version(){return this._version}register(e){if(this._contributions.has(e.id))throw new Error(`Contribution with id "${e.id}" already exists in extension point "${this.id}"`);this._contributions.set(e.id,e),this._invalidateCache(),this._notify()}unregister(e){this._contributions.delete(e)&&(this._invalidateCache(),this._notify())}provide(e){return this._getMatched(e).map(r=>r.value)}list(e){return this._getMatched(e)}listAll(){return Array.from(this._contributions.values())}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}removeContributionsByPlugin(e){let n=!1;for(const[r,s]of this._contributions)s.plugin===e&&(this._contributions.delete(r),n=!0);n&&(this._invalidateCache(),this._notify())}_getMatched(e){const n=this._getCacheKey(e);if(n!=null){const s=this._lookupCache.get(n);if(s){const i=s.map(o=>this._contributions.get(o)).filter(o=>o!=null);return this._applyMode(i,e)}}let r=this._sortDeterministic(Array.from(this._contributions.values()));return this._matcher&&e!==void 0&&(r=r.filter(s=>this._matcher(s,e))),n!=null&&this._lookupCache.set(n,r.map(s=>s.id)),this._applyMode(r,e)}_applyMode(e,n){if(this.mode==="single"){if(this._select){const r=this._select(e,n);return r?[r]:[]}return e.length>0?[e[0]]:[]}return e}_sortDeterministic(e){return[...e].sort((n,r)=>{const s=n.plugin.localeCompare(r.plugin);return s!==0?s:n.id.localeCompare(r.id)})}_getCacheKey(e){if(e!=null&&typeof e=="object"&&"getCacheKey"in e){const n=e.getCacheKey;if(typeof n=="function")return n()}}_invalidateCache(){this._lookupCache.clear()}_notify(){this._version++;for(const e of this._listeners)e()}}class bt{constructor(e){F(this,"_stores",new Map);F(this,"_storeUnsubs",new Map);F(this,"_listeners",new Set);if(e!=null&&e.initialStores)for(const n of e.initialStores)this.addExtensionPoint(n)}addExtensionPoint(e){const n=pe(e.id);if(this._stores.has(n)){const s=this._stores.get(n);throw new Error(`Extension point "${n}" already exists (owned by "${s.pluginId??"unknown"}")`)}const r=new Qe({...e,id:n});this._stores.set(n,r),this._storeUnsubs.set(n,r.subscribe(()=>this._notify())),this._notify()}getExtensionPoint(e){const n=pe(e);return this._stores.get(n)}hasExtensionPoint(e){const n=pe(e);return this._stores.has(n)}listExtensionPoints(){return Array.from(this._stores.keys())}removeExtensionPoints(e){var r;let n=!1;for(const[s,i]of this._stores)i.pluginId===e&&((r=this._storeUnsubs.get(s))==null||r(),this._storeUnsubs.delete(s),this._stores.delete(s),n=!0);n&&this._notify()}removeContributions(e){for(const n of this._stores.values())n.removeContributionsByPlugin(e);this._notify()}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}_notify(){for(const e of this._listeners)e()}}const U={Panel:{position:"fixed",right:"var(--ov-space-3)",bottom:36,zIndex:"calc(var(--ov-z-toast, 9999) + 1)",width:"min(480px, calc(100vw - 24px))",minWidth:0,maxHeight:"min(560px, calc(100dvh - 64px))",display:"flex",flexDirection:"column",overflow:"hidden",padding:0},Header:{flex:"none",gap:"var(--ov-space-2)",paddingInline:"var(--ov-space-3)",background:"var(--ov-color-bg-surface-raised)",borderBottom:"1px solid var(--ov-color-border-muted)"},HeaderActions:{marginLeft:"auto"},List:{minHeight:0,overflowY:"auto",overscrollBehavior:"contain"},Notice:{borderTop:"1px solid var(--ov-color-border-muted)"},Row:{display:"flex",alignItems:"center",gap:"var(--ov-space-1)",padding:"var(--ov-space-2) var(--ov-space-2) var(--ov-space-2) var(--ov-space-3)"},ErrorIcon:{flex:"none",color:"var(--ov-color-danger)"},Message:{flex:1,minWidth:0,justifyContent:"flex-start",textAlign:"left"},MessageText:{minWidth:0,overflowWrap:"anywhere"},Details:{padding:"0 var(--ov-space-3) var(--ov-space-3) 36px"},Code:{display:"block",margin:"var(--ov-space-2) 0",padding:"var(--ov-space-3)",maxHeight:240,overflow:"auto",whiteSpace:"pre-wrap",overflowWrap:"anywhere",lineHeight:1.5,userSelect:"text"},Actions:{display:"flex",flexWrap:"wrap",gap:"var(--ov-space-2)"},CopyError:{margin:0,padding:"var(--ov-space-3)",borderTop:"1px solid var(--ov-color-border-muted)"}},We=u.createContext(void 0),Rt={default:"info",info:"info",success:"success",warning:"warning",error:"danger"},xt=({children:t})=>{const{toast:e}=L.useToast(),[n,r]=u.useState([]),[s,i]=u.useState([]),[o,a]=u.useState(!1),[c,p]=u.useState(),[l,h]=u.useState(""),g=u.useRef(Date.now()),y=u.useRef(null);u.useEffect(()=>{var _;if(!o)return;const d=document.activeElement;(_=y.current)==null||_.focus();const f=E=>{E.key==="Escape"&&(E.stopPropagation(),a(!1))};return document.addEventListener("keydown",f),()=>{document.removeEventListener("keydown",f),d instanceof HTMLElement&&d.isConnected&&d.focus()}},[o]);const C=d=>{r(f=>[...f,d])},R=(d,f,_)=>{const E=typeof d=="object";let w="",x="info",b,I=5e3,O;if(E){if(w=d.message,d.showOnce){if(n.includes(w))return;C(w)}x=d.status,b=d.details,I=d.autoHideDuration??5e3,O=d.actions}else w=d,x=f,b=_;let P;if(x==="error"){const q={id:++g.current,message:w,details:b,created:new Date().toISOString(),actions:O};i(M=>[...M,q].slice(-20)),P={label:"Details",onClick:()=>{p(q.id),a(!0)}}}e(x==="error"?w:b??w,{severity:Rt[x]??"info",title:x!=="error"&&b?w:void 0,duration:I,action:P??(O==null?void 0:O[0])})};return m.jsxs(We.Provider,{value:{showSnackbar:R,openNotifications:()=>{a(!0)},notificationCount:s.length},children:[t,o&&m.jsxs(L.Card,{ref:y,style:U.Panel,size:"sm",variant:"outline",surface:"overlay",elevation:3,"aria-label":"Notifications",tabIndex:-1,children:[m.jsxs(L.Toolbar,{size:"sm",style:U.Header,children:[m.jsx(L.Text,{size:"sm",weight:"semibold",children:"Notifications"}),m.jsx(L.Text,{size:"xs",tone:"muted",children:s.length}),m.jsxs(L.Toolbar.Group,{style:U.HeaderActions,children:[m.jsx(L.IconButton,{size:"sm",variant:"ghost","aria-label":"Clear history",title:"Clear history",disabled:s.length===0,onClick:()=>{i([]),p(void 0),h("")},children:m.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-hidden":"true",children:m.jsx("path",{d:"m3 3 6 6m0-6L3 9M13 6h8M3 14h18M3 20h18"})})}),m.jsx(L.IconButton,{size:"sm",variant:"ghost","aria-label":"Close notifications",title:"Close notifications",onClick:()=>{a(!1)},children:m.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-hidden":"true",children:m.jsx("path",{d:"m6 9 6 6 6-6"})})})]})]}),m.jsxs("div",{style:U.List,children:[s.length===0&&m.jsx(L.EmptyState,{size:"sm",title:"No recent errors",description:"Error details will appear here."}),s.slice().reverse().map(d=>{var _,E;const f=c===d.id;return m.jsxs("div",{style:U.Notice,children:[m.jsxs("div",{style:U.Row,children:[m.jsxs("svg",{style:U.ErrorIcon,width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-label":"Error",role:"img",children:[m.jsx("circle",{cx:"12",cy:"12",r:"9"}),m.jsx("path",{d:"m9 9 6 6m0-6-6 6"})]}),m.jsx(L.Button,{size:"sm",variant:"ghost",style:U.Message,"aria-expanded":f,"aria-controls":`notification-${d.id}`,title:d.message,onClick:()=>{p(f?void 0:d.id),h("")},children:m.jsx(L.Text,{size:"sm",style:U.MessageText,truncate:!f,children:d.message})}),m.jsx(L.IconButton,{size:"sm",variant:"ghost","aria-label":f?"Collapse details":"Expand details",title:f?"Collapse details":"Expand details","aria-expanded":f,"aria-controls":`notification-${d.id}`,onClick:()=>{p(f?void 0:d.id),h("")},children:m.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-hidden":"true",children:m.jsx("path",{d:f?"m6 15 6-6 6 6":"m6 9 6 6 6-6"})})}),m.jsx(L.IconButton,{size:"sm",variant:"ghost","aria-label":`Dismiss ${d.message}`,title:"Dismiss notification",onClick:()=>{i(w=>w.filter(x=>x.id!==d.id)),f&&(p(void 0),h(""))},children:m.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-hidden":"true",children:m.jsx("path",{d:"m6 6 12 12m0-12L6 18"})})})]}),m.jsx("div",{id:`notification-${d.id}`,hidden:!f,style:U.Details,children:f&&m.jsxs(m.Fragment,{children:[m.jsx(L.Text,{size:"xs",tone:"muted",children:m.jsx("time",{dateTime:d.created,children:new Date(d.created).toLocaleString()})}),m.jsx(L.Code,{size:"sm",style:U.Code,children:(_=d.details)!=null&&_.length?d.details:d.message}),m.jsxs("div",{style:U.Actions,children:[m.jsx(L.Button,{size:"sm",variant:"ghost",onClick:async()=>{h("");try{await navigator.clipboard.writeText(`${d.message}
1
+ "use strict";var dt=Object.defineProperty;var ft=(t,e,n)=>e in t?dt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var F=(t,e,n)=>ft(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("react/jsx-runtime"),u=require("react"),V=require("react-router-dom");require("./index-D_aIcqH0.cjs");const C=require("./graphservice-1J8q3eeL.cjs"),k=require("./models-BQsuB2Lj.cjs"),D=require("./events-CtgYnKmS.cjs"),v=require("@tanstack/react-query"),L=require("@omniviewdev/base-ui"),pt=require("./legacyEnum-DkV5yRdA.cjs"),se=u.createContext(void 0),N={PLUGIN_NOT_FOUND:"omniview:plugin/not-found",PLUGIN_NOT_LOADED:"omniview:plugin/not-loaded",PLUGIN_ALREADY_LOADED:"omniview:plugin/already-loaded",PLUGIN_INSTALL_FAILED:"omniview:plugin/install-failed",PLUGIN_LOAD_FAILED:"omniview:plugin/load-failed",PLUGIN_BUILD_FAILED:"omniview:plugin/build-failed",PLUGIN_COMMITTED_CLEANUP_PENDING:"omniview:plugin/committed-cleanup-pending",PLUGIN_COMMIT_UNCERTAIN:"omniview:plugin/commit-uncertain",SETTINGS_MISSING_CONFIG:"omniview:settings/missing-config",SETTINGS_INVALID_CONFIG:"omniview:settings/invalid-config",RESOURCE_NOT_FOUND:"omniview:resource/not-found",RESOURCE_FORBIDDEN:"omniview:resource/forbidden",RESOURCE_UNAUTHORIZED:"omniview:resource/unauthorized",RESOURCE_CONFLICT:"omniview:resource/conflict",RESOURCE_TIMEOUT:"omniview:resource/timeout",RESOURCE_LIMIT:"omniview:resource/limit",RESOURCE_CONTINUATION_EXPIRED:"omniview:resource/continuation-expired",RESOURCE_RESET_REQUIRED:"omniview:resource/reset-required",RESOURCE_PARTIAL:"omniview:resource/partial",RESOURCE_PROVIDER_ERROR:"omniview:resource/provider-error",CONNECTION_NOT_FOUND:"omniview:connection/not-found",CONNECTION_FAILED:"omniview:connection/failed",SESSION_NOT_FOUND:"omniview:session/not-found",SESSION_FAILED:"omniview:session/failed",CANCELLED:"omniview:cancelled",INTERNAL:"omniview:internal",VALIDATION:"omniview:validation",NOT_IMPLEMENTED:"omniview:not-implemented"},xe={INVALID_REQUEST:[N.VALIDATION,400,"correctRequest"],UNSUPPORTED:[N.NOT_IMPLEMENTED,501,"refreshContract"],FORBIDDEN:[N.RESOURCE_FORBIDDEN,403,"none"],UNAUTHORIZED:[N.RESOURCE_UNAUTHORIZED,401,"none"],NOT_FOUND:[N.RESOURCE_NOT_FOUND,404,"none"],CONFLICT:[N.RESOURCE_CONFLICT,409,"refreshContract"],ALREADY_EXISTS:[N.RESOURCE_CONFLICT,409,"refreshContract"],CANCELLED:[N.CANCELLED,499,"none"],TIMEOUT:[N.RESOURCE_TIMEOUT,408,"none"],UNAVAILABLE:[N.CONNECTION_FAILED,503,"reconnect"],CONNECTION_ERROR:[N.CONNECTION_FAILED,503,"reconnect"],CERTIFICATE_ERROR:[N.CONNECTION_FAILED,502,"reconnect"],RESOURCE_LIMIT:[N.RESOURCE_LIMIT,429,"correctRequest"],CONTINUATION_EXPIRED:[N.RESOURCE_CONTINUATION_EXPIRED,410,"restartQuery"],RESET_REQUIRED:[N.RESOURCE_RESET_REQUIRED,409,"restartQuery"],PARTIAL_RESULT:[N.RESOURCE_PARTIAL,422,"none"],PROVIDER_ERROR:[N.RESOURCE_PROVIDER_ERROR,502,"none"],INTERNAL:[N.INTERNAL,500,"none"]};function le(t){return typeof t=="object"&&t!==null?t:void 0}function Q(t,e){return typeof t=="string"&&t.length>0&&t.length<=e}function de(){return{type:N.CANCELLED,code:"CANCELLED",title:"Cancelled",status:499,detail:"The operation was cancelled.",recovery:"none"}}function te(t,e){if(e>4)return;if(t==="cancelled")return de();if(typeof t=="string"){const r=t.trim();if(!r.startsWith("{"))return;try{return te(JSON.parse(r),e+1)}catch{return}}const n=le(t);if(n){if(n.name==="AbortError"||n.name==="CancelError")return de();if(Q(n.type,256)&&Q(n.title,256)&&typeof n.status=="number"&&Number.isInteger(n.status)&&n.status>=100&&n.status<=599&&typeof n.detail=="string"&&n.detail.length<=4096){const r={type:n.type,title:n.title,status:n.status,detail:n.detail};Q(n.code,64)&&(r.code=n.code),Q(n.requestId,256)&&(r.requestId=n.requestId),Q(n.instance,512)&&(r.instance=n.instance),Array.isArray(n.suggestions)&&(r.suggestions=n.suggestions.filter(i=>Q(i,512)).slice(0,8)),Array.isArray(n.actions)&&(r.actions=n.actions.filter(i=>{const o=le(i);return!!o&&["navigate","retry","open-url","copy"].includes(String(o.type))&&Q(o.label,256)&&(o.target===void 0||Q(o.target,4096))}).slice(0,8)),["correctRequest","refreshContract","restartQuery","reconnect","none"].includes(String(n.recovery))&&(r.recovery=n.recovery);const s=le(n.location);return(s==null?void 0:s.unit)==="utf8-byte"&&typeof s.start=="number"&&typeof s.end=="number"&&Number.isSafeInteger(s.start)&&Number.isSafeInteger(s.end)&&s.start>=0&&s.end>=s.start&&(r.location={start:s.start,end:s.end,unit:"utf8-byte"}),r}if(typeof n.code=="string"&&typeof n.title=="string"&&typeof n.message=="string"){let r=n.code;if(r==="PERMISSION_DENIED"&&(r="FORBIDDEN"),["INVALID_INPUT","FILTER_UNKNOWN_FIELD","FILTER_INVALID_OPERATOR"].includes(r)&&(r="INVALID_REQUEST"),Object.prototype.hasOwnProperty.call(xe,r)||(r="INTERNAL"),r==="CANCELLED")return de();const[s,i,o]=xe[r],a=r==="FORBIDDEN"||r==="UNAUTHORIZED"||r==="INTERNAL"||r==="PROVIDER_ERROR";return{type:s,status:i,code:r,recovery:o,title:a?r==="FORBIDDEN"?"Access denied":r==="UNAUTHORIZED"?"Authentication required":"Operation failed":Q(n.title,256)?n.title:"Operation failed",detail:a?"The operation could not be completed.":Q(n.message,4096)?n.message:"The operation could not be completed.",...!a&&Array.isArray(n.suggestions)?{suggestions:n.suggestions.filter(c=>Q(c,512)).slice(0,8)}:{}}}return te(n.message,e+1)??te(n.cause,e+1)}}function W(t){return te(t,0)??{type:N.INTERNAL,title:t==null?"Unknown error":"Error",status:500,detail:t==null?"An unknown error occurred.":"The operation could not be completed."}}function Y(t){return W(t).type===N.CANCELLED}function De(t){switch(t.type){case"navigate":return{label:t.label,onClick:()=>{window.location.hash=t.target??""}};case"open-url":return{label:t.label,onClick:()=>{window.open(t.target,"_blank")}};case"copy":return{label:t.label,onClick:()=>{navigator.clipboard.writeText(t.target??"")}};case"retry":return{label:t.label,onClick:()=>{}};default:return{label:t.label,onClick:()=>{}}}}function Ne(t,e){var s,i;const n=[t.detail,...((s=t.suggestions)==null?void 0:s.map(o=>`• ${o}`))??[]].join(`
2
+ `);return{message:e||(t.title!=="Error"?t.title:"Operation failed"),status:"error",details:n,actions:(i=t.actions)==null?void 0:i.map(De)}}function G(t,e,n){if(Y(e))return;const r=W(e);t(Ne(r,n))}function j(t,e){return n=>{if(Y(n))return;const r=W(n);t(Ne(r,r.title!=="Error"?r.title:e))}}function ht(t){const{children:e,pluginId:n,headless:r=!1}=t,[s,i]=u.useState({}),[o,a]=u.useState(new k.PluginMeta),[c,p]=u.useState(!1),[l,h]=u.useState(null),y=u.useRef(0),g=u.useRef(0);console.debug("[PluginContextProvider] render",{pluginId:n,metaLoaded:c,metaError:!!l});const E=u.useCallback(()=>{if(n===void 0||n==="")return;const d=++y.current;console.debug(`[PluginContextProvider] fetching settings for "${n}"`),C.PluginValues(n).then(f=>{d===y.current&&(console.debug(`[PluginContextProvider] settings loaded for "${n}"`,Object.keys(f)),i(f))}).catch(f=>{if(d!==y.current)return;const _=W(f);console.error(`[PluginContextProvider] error fetching settings for "${n}":`,_.detail)})},[n]),R=u.useCallback(()=>{if(n===void 0||n===""){console.debug("[PluginContextProvider] skipping meta fetch — empty pluginId");return}const d=++g.current;console.debug(`[PluginContextProvider] fetching meta for "${n}"`),h(null),C.GetPluginMeta(n).then(f=>{d===g.current&&(console.debug(`[PluginContextProvider] meta loaded for "${n}"`,{name:f==null?void 0:f.name,version:f==null?void 0:f.version}),a(f),p(!0))}).catch(f=>{if(d!==g.current)return;const _=W(f);console.error(`[PluginContextProvider] error fetching meta for "${n}":`,_.detail),h(_.detail),p(!1)})},[n]);if(u.useEffect(()=>{if(c)return;const d=()=>{E(),R()},f=[D.On("plugin/init_complete",d),D.On("plugin/dev_install_complete",_=>{var S;((S=_.data)==null?void 0:S.id)===n&&d()}),D.On("plugin/inventory_changed",d)];return()=>{for(const _ of f)_()}},[n,c,E,R]),u.useEffect(()=>(console.debug(`[PluginContextProvider] useEffect — pluginId changed to "${n}"`),p(!1),h(null),i({}),E(),R(),()=>{++y.current,++g.current}),[n,E,R]),l){if(r)throw new Error(l);return m.jsx("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center",padding:24},children:m.jsxs("div",{style:{maxWidth:480,width:"100%",border:"1px solid #7F1D1D",borderRadius:8,backgroundColor:"#1C1917",padding:20,fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'},children:[m.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12},children:[m.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"#EF4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[m.jsx("circle",{cx:"12",cy:"12",r:"10"}),m.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),m.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),m.jsx("span",{style:{fontSize:14,fontWeight:600,color:"#FECACA"},children:"Plugin failed to load"})]}),m.jsx("p",{style:{fontSize:13,color:"#A1A1AA",margin:"0 0 16px"},children:l}),m.jsx("button",{onClick:()=>R(),style:{background:"transparent",color:"#F87171",border:"1px solid #7F1D1D",borderRadius:6,padding:"6px 14px",fontSize:13,fontWeight:500,cursor:"pointer"},children:"Retry"})]})})}return c?m.jsx(se.Provider,{value:{pluginId:n,settings:s,meta:o},children:e}):r?null:m.jsxs("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center"},children:[m.jsx("div",{style:{width:24,height:24,border:"2px solid #3F3F46",borderTopColor:"#A1A1AA",borderRadius:"50%",animation:"plugin-spin 0.8s linear infinite"}}),m.jsx("style",{children:"@keyframes plugin-spin { to { transform: rotate(360deg); } }"})]})}function oe(){const t=u.useContext(se);if(!t)throw new Error("usePluginContext must be used within a PluginContextProvider");return t}function gt(){return oe().settings}const Ee=u.createContext(void 0),yt=({children:t})=>{const[e,n]=u.useState({}),r=u.useRef(0),s=u.useCallback(()=>{const o=r.current+1;r.current=o,C.Values().then(a=>{o===r.current&&n(a)}).catch(a=>{o===r.current&&console.error("Error fetching settings:",a)})},[]);u.useEffect(()=>{const o=D.On("settings/changed",()=>s());return s(),()=>{r.current+=1,o()}},[s]);const i=u.useCallback(()=>{s()},[s]);return m.jsx(Ee.Provider,{value:{settings:e,reload:i},children:t})},Fe={height:32,focused:0,tabs:[],createTab:()=>{},createTabs:()=>{},updateTab:()=>{},focusTab:()=>{},reorderTab:()=>{},closeTab:()=>{},closeTabs:()=>{},resizeDrawer:()=>{},closeDrawer:()=>{},fullscreenDrawer:()=>{}},Le=u.createContext(Fe),ke=u.createContext(void 0),Me=u.createContext(void 0),Se=u.createContext(void 0),mt=3e4,Et=({children:t})=>{const[e,n]=u.useState([]),r=u.useCallback(a=>{n(c=>[a,...c])},[]),s=u.useCallback((a,c)=>{n(p=>p.map(l=>l.id===a?{...l,...c}:l))},[]),i=u.useCallback(a=>{n(c=>c.filter(p=>p.id!==a))},[]);u.useEffect(()=>{const a=[];for(const c of e)if(c.status!=="running"){const p=Date.now()-(c.completedAt??c.startedAt),l=Math.max(0,mt-p);a.push(setTimeout(()=>i(c.id),l))}return()=>a.forEach(clearTimeout)},[e,i]);const o=u.useMemo(()=>({operations:e,addOperation:r,updateOperation:s,removeOperation:i}),[e,r,s,i]);return m.jsx(Se.Provider,{value:o,children:t})};var ge=function(t,e){return ge=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},ge(t,e)};function St(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ge(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var fe="Invariant Violation",Ie=Object.setPrototypeOf,Ct=Ie===void 0?function(t,e){return t.__proto__=e,t}:Ie,vt=function(t){St(e,t);function e(n){n===void 0&&(n=fe);var r=t.call(this,typeof n=="number"?fe+": "+n+" (see https://github.com/apollographql/invariant-packages)":n)||this;return r.framesToPop=1,r.name=fe,Ct(r,e.prototype),r}return e}(Error);function ye(t,e){if(!t)throw new vt(e)}var je=["debug","log","warn","error","silent"],_t=je.indexOf("log");function J(t){return function(){if(je.indexOf(t)>=_t){var e=console[t]||console.log;return e.apply(console,arguments)}}}(function(t){t.debug=J("debug"),t.log=J("log"),t.warn=J("warn"),t.error=J("error")})(ye||(ye={}));const qe=u.createContext(void 0),Ue=()=>u.useContext(qe);function $e(t){const e=Ue(),n=u.useRef(null),r=e==null?void 0:e.getExtensionPoint(t),s=u.useCallback(o=>{const a=[];return e&&a.push(e.subscribe(o)),r&&a.push(r.subscribe(o)),()=>{for(const c of a)c()}},[e,t,r]),i=u.useCallback(()=>{const o=e==null?void 0:e.getExtensionPoint(t);if(!o){if(n.current&&n.current.store===void 0)return n.current.sentinel;const p={};return n.current={store:void 0,version:-1,sentinel:p},p}const a=n.current;if(a&&a.store===o&&a.version===o.version)return a.sentinel;const c={};return n.current={store:o,version:o.version,sentinel:c},c},[e,t]);return u.useSyncExternalStore(s,i),e==null?void 0:e.getExtensionPoint(t)}const wt=({registry:t,children:e})=>{const n=u.useRef(t);return ye(n.current===t,"You can't change the extension registry after it has been rendered"),m.jsx(qe.Provider,{value:n.current,children:e})},pe=t=>{if(!t||typeof t!="string")throw new TypeError(`extensionName is required to be a string and can't be: "${t}" (${typeof t})`);return t.trim()};class Qe{constructor(e){F(this,"id");F(this,"mode");F(this,"_pluginId");F(this,"_version",0);F(this,"_contributions",new Map);F(this,"_lookupCache",new Map);F(this,"_matcher");F(this,"_select");F(this,"_listeners",new Set);this.id=e.id,this.mode=e.mode??"multiple",this._pluginId=e.pluginId,this._matcher=e.matcher,this._select=e.select}get pluginId(){return this._pluginId}get version(){return this._version}register(e){if(this._contributions.has(e.id))throw new Error(`Contribution with id "${e.id}" already exists in extension point "${this.id}"`);this._contributions.set(e.id,e),this._invalidateCache(),this._notify()}unregister(e){this._contributions.delete(e)&&(this._invalidateCache(),this._notify())}provide(e){return this._getMatched(e).map(r=>r.value)}list(e){return this._getMatched(e)}listAll(){return Array.from(this._contributions.values())}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}removeContributionsByPlugin(e){let n=!1;for(const[r,s]of this._contributions)s.plugin===e&&(this._contributions.delete(r),n=!0);n&&(this._invalidateCache(),this._notify())}_getMatched(e){const n=this._getCacheKey(e);if(n!=null){const s=this._lookupCache.get(n);if(s){const i=s.map(o=>this._contributions.get(o)).filter(o=>o!=null);return this._applyMode(i,e)}}let r=this._sortDeterministic(Array.from(this._contributions.values()));return this._matcher&&e!==void 0&&(r=r.filter(s=>this._matcher(s,e))),n!=null&&this._lookupCache.set(n,r.map(s=>s.id)),this._applyMode(r,e)}_applyMode(e,n){if(this.mode==="single"){if(this._select){const r=this._select(e,n);return r?[r]:[]}return e.length>0?[e[0]]:[]}return e}_sortDeterministic(e){return[...e].sort((n,r)=>{const s=n.plugin.localeCompare(r.plugin);return s!==0?s:n.id.localeCompare(r.id)})}_getCacheKey(e){if(e!=null&&typeof e=="object"&&"getCacheKey"in e){const n=e.getCacheKey;if(typeof n=="function")return n()}}_invalidateCache(){this._lookupCache.clear()}_notify(){this._version++;for(const e of this._listeners)e()}}class bt{constructor(e){F(this,"_stores",new Map);F(this,"_storeUnsubs",new Map);F(this,"_listeners",new Set);if(e!=null&&e.initialStores)for(const n of e.initialStores)this.addExtensionPoint(n)}addExtensionPoint(e){const n=pe(e.id);if(this._stores.has(n)){const s=this._stores.get(n);throw new Error(`Extension point "${n}" already exists (owned by "${s.pluginId??"unknown"}")`)}const r=new Qe({...e,id:n});this._stores.set(n,r),this._storeUnsubs.set(n,r.subscribe(()=>this._notify())),this._notify()}getExtensionPoint(e){const n=pe(e);return this._stores.get(n)}hasExtensionPoint(e){const n=pe(e);return this._stores.has(n)}listExtensionPoints(){return Array.from(this._stores.keys())}removeExtensionPoints(e){var r;let n=!1;for(const[s,i]of this._stores)i.pluginId===e&&((r=this._storeUnsubs.get(s))==null||r(),this._storeUnsubs.delete(s),this._stores.delete(s),n=!0);n&&this._notify()}removeContributions(e){for(const n of this._stores.values())n.removeContributionsByPlugin(e);this._notify()}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}_notify(){for(const e of this._listeners)e()}}const U={Panel:{position:"fixed",right:"var(--ov-space-3)",bottom:36,zIndex:"calc(var(--ov-z-toast, 9999) + 1)",width:"min(480px, calc(100vw - 24px))",minWidth:0,maxHeight:"min(560px, calc(100dvh - 64px))",display:"flex",flexDirection:"column",overflow:"hidden",padding:0},Header:{flex:"none",gap:"var(--ov-space-2)",paddingInline:"var(--ov-space-3)",background:"var(--ov-color-bg-surface-raised)",borderBottom:"1px solid var(--ov-color-border-muted)"},HeaderActions:{marginLeft:"auto"},List:{minHeight:0,overflowY:"auto",overscrollBehavior:"contain"},Notice:{borderTop:"1px solid var(--ov-color-border-muted)"},Row:{display:"flex",alignItems:"center",gap:"var(--ov-space-1)",padding:"var(--ov-space-2) var(--ov-space-2) var(--ov-space-2) var(--ov-space-3)"},ErrorIcon:{flex:"none",color:"var(--ov-color-danger)"},Message:{flex:1,minWidth:0,justifyContent:"flex-start",textAlign:"left"},MessageText:{minWidth:0,overflowWrap:"anywhere"},Details:{padding:"0 var(--ov-space-3) var(--ov-space-3) 36px"},Code:{display:"block",margin:"var(--ov-space-2) 0",padding:"var(--ov-space-3)",maxHeight:240,overflow:"auto",whiteSpace:"pre-wrap",overflowWrap:"anywhere",lineHeight:1.5,userSelect:"text"},Actions:{display:"flex",flexWrap:"wrap",gap:"var(--ov-space-2)"},CopyError:{margin:0,padding:"var(--ov-space-3)",borderTop:"1px solid var(--ov-color-border-muted)"}},We=u.createContext(void 0),Rt={default:"info",info:"info",success:"success",warning:"warning",error:"danger"},xt=({children:t})=>{const{toast:e}=L.useToast(),[n,r]=u.useState([]),[s,i]=u.useState([]),[o,a]=u.useState(!1),[c,p]=u.useState(),[l,h]=u.useState(""),y=u.useRef(Date.now()),g=u.useRef(null);u.useEffect(()=>{var _;if(!o)return;const d=document.activeElement;(_=g.current)==null||_.focus();const f=S=>{S.key==="Escape"&&(S.stopPropagation(),a(!1))};return document.addEventListener("keydown",f),()=>{document.removeEventListener("keydown",f),d instanceof HTMLElement&&d.isConnected&&d.focus()}},[o]);const E=d=>{r(f=>[...f,d])},R=(d,f,_)=>{const S=typeof d=="object";let w="",x="info",b,I=5e3,O;if(S){if(w=d.message,d.showOnce){if(n.includes(w))return;E(w)}x=d.status,b=d.details,I=d.autoHideDuration??5e3,O=d.actions}else w=d,x=f,b=_;let P;if(x==="error"){const q={id:++y.current,message:w,details:b,created:new Date().toISOString(),actions:O};i(M=>[...M,q].slice(-20)),P={label:"Details",onClick:()=>{p(q.id),a(!0)}}}e(x==="error"?w:b??w,{severity:Rt[x]??"info",title:x!=="error"&&b?w:void 0,duration:I,action:P??(O==null?void 0:O[0])})};return m.jsxs(We.Provider,{value:{showSnackbar:R,openNotifications:()=>{a(!0)},notificationCount:s.length},children:[t,o&&m.jsxs(L.Card,{ref:g,style:U.Panel,size:"sm",variant:"outline",surface:"overlay",elevation:3,"aria-label":"Notifications",tabIndex:-1,children:[m.jsxs(L.Toolbar,{size:"sm",style:U.Header,children:[m.jsx(L.Text,{size:"sm",weight:"semibold",children:"Notifications"}),m.jsx(L.Text,{size:"xs",tone:"muted",children:s.length}),m.jsxs(L.Toolbar.Group,{style:U.HeaderActions,children:[m.jsx(L.IconButton,{size:"sm",variant:"ghost","aria-label":"Clear history",title:"Clear history",disabled:s.length===0,onClick:()=>{i([]),p(void 0),h("")},children:m.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-hidden":"true",children:m.jsx("path",{d:"m3 3 6 6m0-6L3 9M13 6h8M3 14h18M3 20h18"})})}),m.jsx(L.IconButton,{size:"sm",variant:"ghost","aria-label":"Close notifications",title:"Close notifications",onClick:()=>{a(!1)},children:m.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-hidden":"true",children:m.jsx("path",{d:"m6 9 6 6 6-6"})})})]})]}),m.jsxs("div",{style:U.List,children:[s.length===0&&m.jsx(L.EmptyState,{size:"sm",title:"No recent errors",description:"Error details will appear here."}),s.slice().reverse().map(d=>{var _,S;const f=c===d.id;return m.jsxs("div",{style:U.Notice,children:[m.jsxs("div",{style:U.Row,children:[m.jsxs("svg",{style:U.ErrorIcon,width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-label":"Error",role:"img",children:[m.jsx("circle",{cx:"12",cy:"12",r:"9"}),m.jsx("path",{d:"m9 9 6 6m0-6-6 6"})]}),m.jsx(L.Button,{size:"sm",variant:"ghost",style:U.Message,"aria-expanded":f,"aria-controls":`notification-${d.id}`,title:d.message,onClick:()=>{p(f?void 0:d.id),h("")},children:m.jsx(L.Text,{size:"sm",style:U.MessageText,truncate:!f,children:d.message})}),m.jsx(L.IconButton,{size:"sm",variant:"ghost","aria-label":f?"Collapse details":"Expand details",title:f?"Collapse details":"Expand details","aria-expanded":f,"aria-controls":`notification-${d.id}`,onClick:()=>{p(f?void 0:d.id),h("")},children:m.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-hidden":"true",children:m.jsx("path",{d:f?"m6 15 6-6 6 6":"m6 9 6 6 6-6"})})}),m.jsx(L.IconButton,{size:"sm",variant:"ghost","aria-label":`Dismiss ${d.message}`,title:"Dismiss notification",onClick:()=>{i(w=>w.filter(x=>x.id!==d.id)),f&&(p(void 0),h(""))},children:m.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-hidden":"true",children:m.jsx("path",{d:"m6 6 12 12m0-12L6 18"})})})]}),m.jsx("div",{id:`notification-${d.id}`,hidden:!f,style:U.Details,children:f&&m.jsxs(m.Fragment,{children:[m.jsx(L.Text,{size:"xs",tone:"muted",children:m.jsx("time",{dateTime:d.created,children:new Date(d.created).toLocaleString()})}),m.jsx(L.Code,{size:"sm",style:U.Code,children:(_=d.details)!=null&&_.length?d.details:d.message}),m.jsxs("div",{style:U.Actions,children:[m.jsx(L.Button,{size:"sm",variant:"ghost",onClick:async()=>{h("");try{await navigator.clipboard.writeText(`${d.message}
3
3
  ${d.created}
4
- ${d.details??""}`)}catch{h("Copy failed. Select the diagnostic text and copy it manually.")}},children:"Copy details"}),(E=d.actions)==null?void 0:E.map((w,x)=>m.jsx(L.Button,{size:"sm",variant:"outline",onClick:w.onClick,children:w.label},`${w.label}-${x}`))]})]})})]},d.id)})]}),l&&m.jsx(L.Text,{as:"p",size:"sm",role:"status",style:U.CopyError,children:l})]})]})},$=()=>{const t=u.useContext(We);if(t===void 0)throw new Error("useCustomSnackbar must be used within a CustomSnackbarProvider");return t};function A(t){const e=u.useContext(se),n=(e==null?void 0:e.pluginId)??t;if(!n)throw new Error("pluginID must be provided either via PluginContext or as an explicit parameter");return n}const It=({pluginID:t,connectionID:e})=>{const n=A(t),r=v.useQueryClient(),{showSnackbar:s}=$(),i=[n,"connection","detail",e],{mutateAsync:o}=v.useMutation({mutationFn:async()=>S.StartConnection(n,e),onSuccess(h){r.setQueryData(i,h),r.invalidateQueries({queryKey:["EDITOR_SCHEMAS",n,e]})},onError:j(s,"Failed to start connection")}),{mutateAsync:a}=v.useMutation({mutationFn:async()=>S.StopConnection(n,e),onSuccess(h){r.setQueryData(i,h)},onError:j(s,"Failed to stop connection")}),{mutateAsync:c}=v.useMutation({mutationFn:async h=>S.UpdateConnection(n,h),onSuccess(h,{name:g}){s({message:`Connection ${g} successfully updated`,status:"success"}),r.setQueryData(i,h),r.setQueriesData({queryKey:[n,"connection","list"]},y=>y==null?void 0:y.map(C=>C.id===e?h:C))},onError:j(s,"Failed to update connection")}),{mutateAsync:p}=v.useMutation({mutationFn:async()=>S.RemoveConnection(n,e),onSuccess(){s({message:"Connection successfully removed",status:"success"}),r.setQueryData(i,void 0),r.setQueriesData({queryKey:[n,"connection","list"]},h=>h==null?void 0:h.filter(g=>g.id!==e))},onError:j(s,"Failed to remove connection")});return{connection:v.useQuery({queryKey:i,queryFn:async()=>S.GetConnection(n,e)}),startConnection:o,stopConnection:a,updateConnection:c,deleteConnection:p}},Ge=t=>[t,"connection","list"],Ot=({plugin:t})=>{const e=A(t),n=v.useQueryClient(),{showSnackbar:r}=$(),s=Ge(e),{mutateAsync:i}=v.useMutation({mutationFn:async p=>S.StartConnectionWatch(e,p.id),onError:j(r,"Failed to start connection watch")}),{mutateAsync:o}=v.useMutation({mutationFn:async p=>S.StopConnectionWatch(e,p.id),onError:j(r,"Failed to stop connection watch")}),a=u.useCallback(p=>{const l=p.data;console.log("got update to connections",l),n.setQueryData(s,l)},[n,s]);return u.useEffect(()=>{const p=D.On(`${e}/connection/sync`,a);return()=>{p()}},[e,a]),{connections:v.useQuery({queryKey:s,queryFn:async()=>{try{return await S.ListConnections(e)}catch(p){console.log(p),j(r,"Failed to load connections")(p)}return[]},staleTime:3e4,placeholderData:v.keepPreviousData}),startWatch:i,stopWatch:o}},Tt=({pluginID:t,connectionID:e})=>{const n=A(t),r=[n,"connection","namespaces",e];return{namespaces:v.useQuery({queryKey:r,queryFn:async()=>S.GetConnectionNamespaces(n,e)})}},T=pt.withLegacyNames(k.WatchState,"WatchState");function me(t){const e=Object.values(t.states),n=e.length;let r=0,s=0,i=0,o=0;for(const l of e)l===T.WatchStateSynced&&r++,(l===T.WatchStateError||l===T.WatchStateFailed)&&s++,l===T.WatchStateForbidden&&i++,l===T.WatchStateSkipped&&o++;const a=n-o,c=e.filter(l=>l===T.WatchStateSynced||l===T.WatchStateError||l===T.WatchStateStopped||l===T.WatchStateFailed||l===T.WatchStateForbidden).length,p=a>0?c/a:0;return{pluginID:t.pluginID,connectionID:t.connectionID,totalResources:n,watchedTotal:a,syncedCount:r,errorCount:s,forbiddenCount:i,skippedCount:o,doneCount:c,progress:p}}function ne(t){return t.watchedTotal>0&&t.doneCount>=t.watchedTotal}function Be(t){return t.some(e=>!ne(e))}function He(t){const e=t.reduce((r,s)=>r+s.watchedTotal,0);return e===0?0:t.reduce((r,s)=>r+s.doneCount,0)/e}function Ce(t){return`${t.pluginId}/${t.connection}`}function Ke(t,e){const n=Ce(e);t.has(n)||t.set(n,{states:{},pluginID:e.pluginId,connectionID:e.connection});const r=t.get(n);return r.states[e.resourceKey]=e.state,r}function Pt(){const[t,e]=u.useState(new Set),[n,r]=u.useState({}),[s,i]=u.useState(new Map),o=u.useRef(new Map),[a,c]=u.useState(new Map);u.useEffect(()=>{const E=D.On("plugin/crash_recovery_failed",x=>{const b=x.data,I=b==null?void 0:b.pluginID;I&&c(O=>{const P=new Map(O);return P.set(I,b.error??"Crash recovery failed"),P})}),w=D.On("plugin/recovered",x=>{const b=x.data,I=b==null?void 0:b.pluginID;I&&c(O=>{if(!O.has(I))return O;const P=new Map(O);return P.delete(I),P})});return()=>{E(),w()}},[]),u.useEffect(()=>{S.GetAllConnectionStates().then(E=>{if(!E)return;const w={},x=new Set,b=new Map;for(const[I,O]of Object.entries(E))if(O){w[I]=O.map(P=>P.connection);for(const P of O){if(!P.started)continue;const q=`${I}/${P.connection.id}`;x.add(q);const M={pluginID:I,connectionID:P.connection.id,states:{}};if(P.resources)for(const[ue,lt]of Object.entries(P.resources))M.states[ue]=lt;o.current.set(q,M),b.set(q,me(M))}}r(w),e(x),i(b)}).catch(()=>{})},[]),u.useEffect(()=>D.On("connection/status",w=>{const x=w.data,b=`${x.pluginID}/${x.connectionID}`;x.status==="DISCONNECTED"?(e(I=>{const O=new Set(I);return O.delete(b),O}),i(I=>{const O=new Map(I);return O.delete(b),O}),o.current.delete(b)):e(I=>{const O=new Set(I);return O.add(b),O}),S.ListAllConnections().then(I=>{if(!I)return;const O={};for(const[P,q]of Object.entries(I))q!=null&&(O[P]=q);r(O)}).catch(()=>{})}),[]);const p=u.useCallback(E=>{const w=E.data,x=Ce(w);e(O=>{if(O.has(x))return O;const P=new Set(O);return P.add(x),P});const b=Ke(o.current,w),I=me(b);i(O=>{const P=new Map(O);return P.set(x,I),P})},[]);u.useEffect(()=>D.On("watch/STATE",p),[p]);const l=u.useCallback(async(E,w)=>{await S.StopConnection(E,w)},[]),h=u.useCallback(async(E,w)=>{await S.StartConnectionWatch(E,w)},[]),g=u.useCallback(async E=>{const w=a.get(E);c(x=>{if(!x.has(E))return x;const b=new Map(x);return b.delete(E),b});try{await S.RetryFailedPlugin(E)}catch(x){throw c(b=>{const I=new Map(b);return I.set(E,w??"Reload failed"),I}),x}},[a]),y=[];for(const E of t){const[w,x]=E.split("/",2),I=(n[w]??[]).find(ue=>ue.id===x),O=s.get(E),P=O!=null&&!ne(O),q=O!=null&&O.errorCount>0,M=a.get(w);y.push({pluginID:w,connectionID:x,name:(I==null?void 0:I.name)??x,avatar:(I==null?void 0:I.avatar)??"",isStarted:!0,sync:O,isSyncing:P,hasErrors:q||M!=null,pluginFailed:M!=null,pluginError:M})}const C=new Map;for(const E of y){const w=C.get(E.pluginID)??[];w.push(E),C.set(E.pluginID,w)}const R=Array.from(s.values()),d=y.filter(E=>E.isSyncing),f=y.filter(E=>E.hasErrors),_=y.filter(E=>E.pluginFailed);return{entries:y,grouped:C,connectedCount:y.length,syncingCount:d.length,errorCount:f.length,failedCount:_.length,hasSyncing:Be(R),aggregateProgress:He(R),disconnect:l,retryWatch:h,retryPlugin:g}}function At(t,e){return e===null?t===null:Array.isArray(e)?Array.isArray(t):typeof e=="object"?typeof t=="object"&&t!==null&&!Array.isArray(t):typeof t==typeof e}function Dt(t,e,n){const r=A(t),s=v.useQueryClient(),i=[r,"data",e],o=v.useQuery({queryKey:i,queryFn:async()=>{const c=await S.Get(r,e);return c==null?n:At(c,n)?c:(console.warn(`[usePluginData] stored value for "${e}" has unexpected type (expected ${Array.isArray(n)?"array":typeof n}, got ${Array.isArray(c)?"array":typeof c}). Using default.`),n)}}),a=v.useMutation({mutationFn:async c=>{await S.Set(r,e,c)},onMutate:async c=>{await s.cancelQueries({queryKey:i});const p=s.getQueryData(i);return s.setQueryData(i,c),{previous:p}},onError:(c,p,l)=>{(l==null?void 0:l.previous)!==void 0&&s.setQueryData(i,l.previous)},onSettled:()=>{s.invalidateQueries({queryKey:i})}});return{data:o.data??n,update:async c=>{await a.mutateAsync(c)},isLoading:o.isLoading}}const Nt=()=>{const t=u.useContext(ke);if(!t)throw new Error("useRightDrawer must be used within a RightDrawerProvider");return t},ve=()=>{const t=u.useContext(Le);if(t===void 0)throw new Error("useBottomDrawer must be used within a BottomDrawerProvider");return t},Ft=({pluginID:t})=>{const e=A(t),{showSnackbar:n}=$(),{createTab:r,updateTab:s}=ve();return{createSession:v.useMutation({mutationFn:async({connectionID:o,icon:a,label:c,opts:p})=>{const l=`pending-${crypto.randomUUID()}`;r({id:l,title:c??"Connecting...",variant:"terminal",icon:a??"LuSquareTerminal",properties:{status:"connecting",pluginID:e,connectionID:o,opts:{...p}}});const h=k.SessionOptions.createFrom({command:["/bin/bash"],tty:!0,...p});try{const g=await S.CreateSession(e,o,h);if(!g)throw new Error("Failed to create session: null response");s({id:l},{id:g.id,title:c??`Session ${g.id.substring(0,8)}`,properties:{status:"connected",pluginID:e,connectionID:o,opts:{...p}}})}catch(g){const y=W(g);s({id:l},{properties:{status:"error",error:y.detail,pluginID:e,connectionID:o,opts:{...p}}}),G(n,g,"Failed to start session")}}}).mutateAsync}},Lt=({pluginID:t})=>{const e=A(t),{showSnackbar:n}=$(),{createTab:r}=ve(),s=v.useMutation({mutationFn:async({connectionID:o,resourceKey:a,resourceID:c,resourceData:p,icon:l,label:h,target:g,follow:y=!0,tailLines:C=1e3,params:R})=>{const d=k.CreateSessionOptions.createFrom({resource_key:a,resource_id:c,resource_data:p,options:k.LogSessionOptions.createFrom({target:g??"",follow:y,include_previous:!1,include_timestamps:!0,tail_lines:C,since_seconds:0,limit_bytes:0,include_source_events:!0,params:R??{}})}),f=await S.CreateSession$1(e,o,d);if(!f)throw new Error("Failed to create log session: null response");return r({id:f.id,title:h??`Logs ${f.id.substring(0,8)}`,variant:"logs",icon:l??"LuLogs"}),f},onError:j(n,"Failed to start log session")}),i=v.useMutation({mutationFn:async o=>{await S.CloseSession(o)},onError:j(n,"Failed to close log session")});return{createLogSession:s.mutateAsync,closeLogSession:i.mutateAsync}},kt=()=>v.useQuery({queryKey:["metric","providers"],queryFn:S.GetProviders,staleTime:3e4}),ze=t=>v.useQuery({queryKey:["metric","providers",t],queryFn:()=>S.GetProvidersForResource(t),enabled:!!t,staleTime:3e4}),Mt=t=>{var d,f;const{connectionID:e,resourceKey:n,resourceID:r,resourceNamespace:s="",resourceData:i={},metricIDs:o=[],shape:a=0,timeRange:c,refreshInterval:p=0,enabled:l=!0}=t,{data:h,isLoading:g}=ze(n),y=h??[],C=c?Math.max(Math.floor((c.end.getTime()-c.start.getTime())/250),15e3)*1e6:0,R=v.useQuery({queryKey:["metric","query",e,n,r,s,o,a,(d=c==null?void 0:c.start)==null?void 0:d.getTime(),(f=c==null?void 0:c.end)==null?void 0:f.getTime()],queryFn:async()=>{const _=await S.QueryAll(e,n,r,s,i,o,a,((c==null?void 0:c.start)??new Date(0)).toISOString(),((c==null?void 0:c.end)??new Date(0)).toISOString(),C),E={};for(const[w,x]of Object.entries(_))x!=null&&(E[w]=x);return E},enabled:l&&!!e&&!!n&&(n.startsWith("cluster::")||!!r)&&y.length>0,refetchInterval:p>0?p:void 0,staleTime:5e3,placeholderData:v.keepPreviousData});return{data:R.data??void 0,providers:y,isLoading:g||R.isLoading,error:R.error,refetch:R.refetch}},jt=t=>{const{pluginID:e,connectionID:n,resourceKey:r,resourceID:s,resourceNamespace:i="",resourceData:o={},metricIDs:a=[],interval:c=1e4,enabled:p=!0}=t,l=A(e),[h,g]=u.useState(null),[y,C]=u.useState(null),[R,d]=u.useState(!1),[f,_]=u.useState(null),E=u.useRef(null),w=u.useCallback(async()=>{if(!(!p||!l||!n||!r||!s))try{const b=await S.Subscribe(l,n,{resource_key:r,resource_id:s,resource_namespace:i,resource_data:o,metric_ids:a,interval:c*1e6});C(b),d(!0),_(null);const I=D.On(`core/metrics/data/${b}`,P=>{const q=P.data;try{const M=JSON.parse(q);M.results&&g(M.results)}catch(M){console.error("Failed to parse metric stream data:",M)}}),O=D.On(`core/metrics/error/${b}`,P=>{const q=P.data;try{const M=JSON.parse(q);_(M.error||"Unknown error")}catch{_("Failed to parse metric stream error")}});E.current=()=>{I(),O()}}catch(b){_(b instanceof Error?b.message:String(b))}},[l,n,r,s,i,a,c,p]),x=u.useCallback(async()=>{if(y)try{await S.Unsubscribe(y)}catch(b){console.error("Failed to unsubscribe:",b)}E.current&&(E.current(),E.current=null),C(null),d(!1)},[y]);return u.useEffect(()=>()=>{y&&S.Unsubscribe(y).catch(console.error),E.current&&E.current()},[y]),{data:h,subscriptionID:y,isStreaming:R,error:f,start:w,stop:x}},B=["networker","portforward","all-sessions"];function qt(){const{showSnackbar:t}=$(),e=v.useQueryClient(),n=v.useQuery({queryKey:[...B],queryFn:async()=>S.ListAllPortForwardSessions().catch(i=>{if(W(i).detail.includes("not found"))return[];throw i}),retry:!1});u.useEffect(()=>{const i=D.On("core/networker/portforward/created",()=>{e.invalidateQueries({queryKey:[...B]})}),o=D.On("core/networker/portforward/closed",()=>{e.invalidateQueries({queryKey:[...B]})});return()=>{i(),o()}},[e]);const r=n.data??[],s=v.useMutation({mutationFn:async i=>S.ClosePortForwardSession(i),onError:j(t,"Failed to close port forwarding session"),onSuccess:async()=>{await e.invalidateQueries({queryKey:[...B]})}});return{sessions:n,activeSessions:r,closeSession:s.mutateAsync,openInBrowser:i=>D.OpenURL(`http://localhost:${i}`)}}function Ut({pluginID:t,connectionID:e,resourceID:n}){const r=A(t),s=["networker","portforward","sessions",r,e,n],{showSnackbar:i}=$(),o=v.useQueryClient(),a=v.useQuery({queryKey:s,queryFn:async()=>S.FindPortForwardSessions(r,e,k.FindPortForwardSessionRequest.createFrom({resource_id:n,connection_id:e})).catch(l=>{const h=W(l);return h.detail.includes("not found")?[]:(i({message:"Failed to fetch port forward sessions",status:"error",details:h.detail}),[])}),retry:!1}),c=v.useMutation({mutationFn:async({opts:l})=>{const h=k.PortForwardSessionOptions.createFrom({local_port:l.localPort||0,remote_port:l.remotePort,protocol:l.protocol||"TCP",connection_type:"RESOURCE",connection:{resource_data:l.resource,connection_id:e,plugin_id:r,resource_id:l.resourceId,resource_key:l.resourceKey},labels:l.labels??{},params:l.parameters??{}}),g=await S.StartResourcePortForwardingSession(r,e,h);if(!g)throw new Error("Failed to start port forwarding: null response");return l.openInBrowser&&D.OpenURL(`http://localhost:${g.local_port}`),g},onError:j(i,"Failed to start port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...B]})])}}),p=v.useMutation({mutationFn:async({opts:l})=>S.ClosePortForwardSession(l.sessionID),onError:j(i,"Failed to close port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...B]})])}});return{sessions:a,forward:c.mutateAsync,close:p.mutateAsync}}const $t=()=>{const t=u.useContext(Me);if(!t)throw new Error("useConfirmationModal must be used within a ConfirmationModalProvider");return t},re={scope:(t,e,n)=>[t,e,n],list:(t,e,n,r=[])=>[t,e,n,r,"list"],resource:(t,e,n,r,s="")=>[t,e,n,s,r]},Qt=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s=""})=>{const i=A(t),o=v.useQueryClient(),{showSnackbar:a}=$(),c=re.resource(i,e,n,r,s),{mutateAsync:p}=v.useMutation({mutationFn:async g=>S.Update(i,e,n,k.UpdateInput.createFrom({input:g.input,id:r,namespace:s})),onSuccess:async()=>{a(`Resource ${r} updated`,"success"),await o.invalidateQueries({queryKey:c})},onError:j(a,`Failed to update resource ${r}`)}),{mutateAsync:l}=v.useMutation({mutationFn:async(g={})=>S.Delete(i,e,n,k.DeleteInput.createFrom({id:r,namespace:s,gracePeriodSeconds:g.gracePeriodSeconds})),onSuccess:async()=>{a(`Resource ${r} deleted`,"success"),await o.invalidateQueries({queryKey:c})},onError:j(a,`Failed to delete resource ${r}`)});return{resource:v.useQuery({queryKey:c,queryFn:async()=>S.Get$1(i,e,n,k.GetInput.createFrom({id:r,namespace:s})),retry:!1}),update:p,remove:l}},Wt=t=>{const e=["component",t.plugin,t.resource,t.area];return{component:v.useQuery({queryKey:e,queryFn:async()=>S.GetResourceAreaComponent(t)})}},Gt=({pluginID:t,connectionID:e})=>{const n=A(t),r=[n,"resource_groups","list"];return{groups:v.useQuery({queryKey:r,queryFn:async()=>S.GetResourceGroups(n,e),retry:!1})}},Bt=({pluginID:t,connectionID:e,searches:n})=>{const r=A(t),s=o=>[r,e,o.key,o.namespaces,"list"];return v.useQueries({queries:n.map(o=>({queryKey:s(o),queryFn:async()=>S.List(r,e,o.key,k.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:o.namespaces})).then(a=>a?(console.log(a.result),a.result&&o.postFilter?Object.values(a.result).filter(o.postFilter):Object.values(a.result||{})):[]),retry:!1}))})},Ht=({pluginID:t,resourceKey:e})=>{const n=A(t),r=[n,"resources",e];return{resourceType:v.useQuery({queryKey:r,queryFn:async()=>S.GetResourceType(n,e),retry:!1})}},Kt=({pluginID:t,connectionID:e})=>{const n=A(t),r=[n,"resources","list",e];return{types:v.useQuery({queryKey:r,queryFn:async()=>S.GetResourceTypes(n,e),retry:!1})}};var Z=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function zt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Vt="Expected a function",Ve="__lodash_hash_undefined__",Yt="[object Function]",Xt="[object GeneratorFunction]",Jt="[object Symbol]",Zt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,en=/^\w*$/,tn=/^\./,nn=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,rn=/[\\^$.*+?()[\]{}|]/g,sn=/\\(\\)?/g,on=/^\[object .+?Constructor\]$/,an=typeof Z=="object"&&Z&&Z.Object===Object&&Z,cn=typeof self=="object"&&self&&self.Object===Object&&self,_e=an||cn||Function("return this")();function un(t,e){return t==null?void 0:t[e]}function ln(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch{}return e}var dn=Array.prototype,fn=Function.prototype,Ye=Object.prototype,he=_e["__core-js_shared__"],Oe=function(){var t=/[^.]+$/.exec(he&&he.keys&&he.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Xe=fn.toString,we=Ye.hasOwnProperty,Je=Ye.toString,pn=RegExp("^"+Xe.call(we).replace(rn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Te=_e.Symbol,hn=dn.splice,gn=Ze(_e,"Map"),X=Ze(Object,"create"),Pe=Te?Te.prototype:void 0,Ae=Pe?Pe.toString:void 0;function H(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function yn(){this.__data__=X?X(null):{}}function mn(t){return this.has(t)&&delete this.__data__[t]}function En(t){var e=this.__data__;if(X){var n=e[t];return n===Ve?void 0:n}return we.call(e,t)?e[t]:void 0}function Sn(t){var e=this.__data__;return X?e[t]!==void 0:we.call(e,t)}function Cn(t,e){var n=this.__data__;return n[t]=X&&e===void 0?Ve:e,this}H.prototype.clear=yn;H.prototype.delete=mn;H.prototype.get=En;H.prototype.has=Sn;H.prototype.set=Cn;function z(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function vn(){this.__data__=[]}function _n(t){var e=this.__data__,n=ie(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():hn.call(e,n,1),!0}function wn(t){var e=this.__data__,n=ie(e,t);return n<0?void 0:e[n][1]}function bn(t){return ie(this.__data__,t)>-1}function Rn(t,e){var n=this.__data__,r=ie(n,t);return r<0?n.push([t,e]):n[r][1]=e,this}z.prototype.clear=vn;z.prototype.delete=_n;z.prototype.get=wn;z.prototype.has=bn;z.prototype.set=Rn;function K(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function xn(){this.__data__={hash:new H,map:new(gn||z),string:new H}}function In(t){return ae(this,t).delete(t)}function On(t){return ae(this,t).get(t)}function Tn(t){return ae(this,t).has(t)}function Pn(t,e){return ae(this,t).set(t,e),this}K.prototype.clear=xn;K.prototype.delete=In;K.prototype.get=On;K.prototype.has=Tn;K.prototype.set=Pn;function ie(t,e){for(var n=t.length;n--;)if($n(t[n][0],e))return n;return-1}function An(t,e){e=Ln(e,t)?[e]:Fn(e);for(var n=0,r=e.length;t!=null&&n<r;)t=t[qn(e[n++])];return n&&n==r?t:void 0}function Dn(t){if(!tt(t)||Mn(t))return!1;var e=Qn(t)||ln(t)?pn:on;return e.test(Un(t))}function Nn(t){if(typeof t=="string")return t;if(Re(t))return Ae?Ae.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function Fn(t){return et(t)?t:jn(t)}function ae(t,e){var n=t.__data__;return kn(e)?n[typeof e=="string"?"string":"hash"]:n.map}function Ze(t,e){var n=un(t,e);return Dn(n)?n:void 0}function Ln(t,e){if(et(t))return!1;var n=typeof t;return n=="number"||n=="symbol"||n=="boolean"||t==null||Re(t)?!0:en.test(t)||!Zt.test(t)||e!=null&&t in Object(e)}function kn(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Mn(t){return!!Oe&&Oe in t}var jn=be(function(t){t=Gn(t);var e=[];return tn.test(t)&&e.push(""),t.replace(nn,function(n,r,s,i){e.push(s?i.replace(sn,"$1"):r||n)}),e});function qn(t){if(typeof t=="string"||Re(t))return t;var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function Un(t){if(t!=null){try{return Xe.call(t)}catch{}try{return t+""}catch{}}return""}function be(t,e){if(typeof t!="function"||e&&typeof e!="function")throw new TypeError(Vt);var n=function(){var r=arguments,s=e?e.apply(this,r):r[0],i=n.cache;if(i.has(s))return i.get(s);var o=t.apply(this,r);return n.cache=i.set(s,o),o};return n.cache=new(be.Cache||K),n}be.Cache=K;function $n(t,e){return t===e||t!==t&&e!==e}var et=Array.isArray;function Qn(t){var e=tt(t)?Je.call(t):"";return e==Yt||e==Xt}function tt(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}function Wn(t){return!!t&&typeof t=="object"}function Re(t){return typeof t=="symbol"||Wn(t)&&Je.call(t)==Jt}function Gn(t){return t==null?"":Nn(t)}function Bn(t,e,n){var r=t==null?void 0:An(t,e);return r===void 0?n:r}var Hn=Bn;const ee=zt(Hn);function nt(t,e,n){const r=t??{result:[],success:!0,totalCount:0},s=[...r.result??[]];for(const i of e){const o=ee(i.payload.data,n);switch(i.type){case"ADD":{s.findIndex(c=>ee(c,n)===o)===-1&&s.push(i.payload.data);break}case"UPDATE":{const a=s.findIndex(c=>ee(c,n)===o);a!==-1&&(s[a]=i.payload.data);break}case"DELETE":{const a=s.findIndex(c=>ee(c,n)===o);a!==-1&&s.splice(a,1);break}}}return{...r,result:s}}function rt(t,e,n,r,s,i){const o=(i==null?void 0:i.syncWindowMs)??500,a=u.useRef([]),c=u.useRef(null),p=u.useRef(null),l=u.useRef(s);l.current=s;const h=u.useCallback(()=>{const y=a.current;if(a.current=[],c.current!==null&&(clearTimeout(c.current),c.current=null),p.current!==null&&(cancelAnimationFrame(p.current),p.current=null),!(y.length===0||!r)){t.setQueryData(e,C=>nt(C,y,r));for(const C of y)(C.type==="ADD"||C.type==="UPDATE")&&t.setQueryData(n(C.payload.id,C.payload.namespace),{success:!0,result:C.payload.data})}},[t,e,n,r]),g=u.useCallback(y=>{a.current.push(y),!(c.current!==null||p.current!==null)&&(c.current=setTimeout(h,o),l.current!==1&&(p.current=requestAnimationFrame(h)))},[h,o]);return u.useEffect(()=>()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),p.current!==null&&(cancelAnimationFrame(p.current),p.current=null)},[]),g}const Kn=({pluginID:t,connectionID:e,resourceKey:n,idAccessor:r,namespaces:s})=>{const i=A(t),o=v.useQueryClient(),{showSnackbar:a}=$(),c=u.useMemo(()=>s??[],[s]),p=u.useMemo(()=>re.list(i,e,n,c),[i,e,n,c]),l=u.useCallback((d,f)=>re.resource(i,e,n,d,f),[i,e,n]),{mutateAsync:h}=v.useMutation({mutationFn:async d=>S.Create(i,e,n,k.CreateInput.createFrom({input:d.input,namespace:d.namespace??(c.length===1?c[0]:"")})),onSuccess:async d=>{var w;const f=d==null?void 0:d.result;let _="";(w=f==null?void 0:f.metadata)!=null&&w.name?_=f.metadata.name:f!=null&&f.id?_=f.id:f!=null&&f.name?_=f.name:f!=null&&f.ID?_=f.ID:f!=null&&f.Name&&(_=f.Name);const E=_?`Resource ${_} created`:"Resource created";a(E,"success"),await o.invalidateQueries({queryKey:p})},onError:j(a,"Failed to create resource")}),g=v.useQuery({queryKey:p,queryFn:async()=>S.List(i,e,n,k.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:c})),placeholderData:(d,f)=>d,retry:!1}),[y,C]=u.useState(T.WatchStateIdle);u.useEffect(()=>D.On(`${i}/${e}/watch/STATE`,f=>{const _=f.data;_.resourceKey===n&&C(_.state)}),[i,e,n]);const R=rt(o,p,l,r,y);return u.useEffect(()=>{if(!r)return;S.SubscribeResource(i,e,n);const d=D.On(`${i}/${e}/${n}/ADD`,E=>R({type:"ADD",payload:E.data})),f=D.On(`${i}/${e}/${n}/UPDATE`,E=>R({type:"UPDATE",payload:E.data})),_=D.On(`${i}/${e}/${n}/DELETE`,E=>R({type:"DELETE",payload:E.data}));return()=>{d(),f(),_(),S.UnsubscribeResource(i,e,n)}},[i,e,n,R]),{resources:g,create:h,watchState:y,isSyncing:y===T.WatchStateSyncing,isSynced:y===T.WatchStateSynced,watchError:y===T.WatchStateError}},zn=({pluginID:t})=>{const e=A(t),{showSnackbar:n}=$(),r=v.useMutation({mutationFn:async({opts:o,input:a})=>S.Create(e,o.connectionID,o.resourceKey,k.CreateInput.createFrom({input:a.input,namespace:a.namespace??o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} created`,"success")},onError(o,{opts:a}){G(n,o,`Failed to create resource ${a.resourceID}`)}}),s=v.useMutation({mutationFn:async({opts:o,input:a})=>S.Update(e,o.connectionID,o.resourceKey,k.UpdateInput.createFrom({input:a.input,id:o.resourceID,namespace:o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} updated`,"success")},onError(o,{opts:a}){G(n,o,`Failed to update resource ${a.resourceID}`)}}),i=v.useMutation({mutationFn:async({opts:o,input:a})=>S.Delete(e,o.connectionID,o.resourceKey,k.DeleteInput.createFrom({id:o.resourceID,namespace:o.namespace??"",gracePeriodSeconds:a.gracePeriodSeconds})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} deleted`,"success")},onError(o,{opts:a}){G(n,o,`Failed to delete resource ${a.resourceID}`)}});return{create:r.mutateAsync,update:s.mutateAsync,remove:i.mutateAsync}},Vn=({pluginID:t,connectionID:e,resourceKey:n,enabled:r=!0})=>{const s=A(t),i=v.useQuery({queryKey:["RESOURCE_ACTIONS",s,e,n],queryFn:()=>S.GetActions(s,e,n),enabled:r&&!!s&&!!e&&!!n,staleTime:5*60*1e3});return{actions:i.data??[],isLoading:i.isLoading,error:i.error}},Yn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=A(t),s=v.useQueryClient(),{showSnackbar:i}=$(),o=v.useMutation({mutationFn:async({actionID:a,id:c="",namespace:p="",params:l={}})=>S.ExecuteAction(r,e,n,a,k.ActionInput.createFrom({id:c,namespace:p,params:l})),onSuccess:a=>{a!=null&&a.message&&i(a.message,"success"),s.invalidateQueries({queryKey:["RESOURCES",r,e,n]})},onError:(a,c)=>{G(i,a,`Failed to execute action "${c.actionID}"`)}});return{executeAction:o.mutateAsync,isExecuting:o.isPending,error:o.error}},Xn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=A(t),s=v.useQuery({queryKey:["EDITOR_SCHEMAS",r,e],queryFn:()=>S.GetEditorSchemas(r,e),enabled:n&&!!r&&!!e,staleTime:10*60*1e3,retry:1});return{schemas:s.data??[],isLoading:s.isLoading,error:s.error,refetch:s.refetch}},Jn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=A(t),s=v.useQueryClient(),i=[r,e,"watch-state"],o=u.useRef([]),a=u.useRef(!1),c=u.useCallback(g=>{s.setQueryData(i,y=>{if(!y)return y;const C={...y.resources,[g.resourceKey]:g.state},R={...y.resourceCounts,[g.resourceKey]:g.resourceCount};let d=0,f=0;for(const _ of Object.values(C))_===T.WatchStateSynced&&d++,(_===T.WatchStateError||_===T.WatchStateFailed)&&f++;return{...y,resources:C,resourceCounts:R,totalResources:Object.keys(C).length,syncedCount:d,errorCount:f}})},[s,r,e]),p=v.useQuery({queryKey:i,queryFn:async()=>{const g=await S.GetWatchState(r,e);if(!g)throw new Error("Failed to get watch state: null response");const y={};let C=0,R=0;for(const[f,_]of Object.entries(g.resources??{}))_!=null&&(y[f]=_,_===T.WatchStateSynced&&C++,_===T.WatchStateError&&R++);const d={};for(const[f,_]of Object.entries(g.resourceCounts??{}))_!=null&&(d[f]=_);return{connection:g.connectionId,resources:y,resourceCounts:d,totalResources:Object.keys(y).length,syncedCount:C,errorCount:R}},enabled:n&&!!r&&!!e,refetchInterval:g=>{const y=g.state.data;if(!y||y.totalResources===0)return 3e3;let C=0;for(const R of Object.values(y.resources))(R===T.WatchStateSynced||R===T.WatchStateError||R===T.WatchStateStopped||R===T.WatchStateFailed||R===T.WatchStateForbidden||R===T.WatchStateSkipped)&&C++;return C>=y.totalResources?!1:3e3}});u.useEffect(()=>{if(!p.data||a.current)return;a.current=!0;const g=o.current;o.current=[];for(const y of g)c(y)},[p.data,c]),u.useEffect(()=>{if(!n||!r||!e)return;a.current=!1,o.current=[];const g=D.On(`${r}/${e}/watch/STATE`,y=>{const C=y.data;a.current?c(C):o.current.push(C)});return()=>{g(),a.current=!1,o.current=[]}},[r,e,n,c]);const l=p.data;let h=0;if(l!=null&&l.resources)for(const g of Object.values(l.resources))(g===T.WatchStateSynced||g===T.WatchStateError||g===T.WatchStateStopped||g===T.WatchStateFailed||g===T.WatchStateForbidden||g===T.WatchStateSkipped)&&h++;return{summary:p,getResourceState:g=>l==null?void 0:l.resources[g],isFullySynced:l?l.totalResources>0&&h===l.totalResources:!1,syncProgress:l&&l.totalResources>0?h/l.totalResources:0,errorCount:(l==null?void 0:l.errorCount)??0}},Zn=()=>{const[t,e]=u.useState(new Map),n=u.useRef(new Map),r=u.useRef(new Map),s=u.useCallback(p=>{const l=p.data,h=Ce(l),g=Ke(n.current,l),y=me(g);if(e(C=>{const R=new Map(C);return R.set(h,y),R}),r.current.has(h)&&(clearTimeout(r.current.get(h)),r.current.delete(h)),ne(y)){const C=setTimeout(()=>{e(R=>{const d=new Map(R);return d.delete(h),d}),n.current.delete(h),r.current.delete(h)},5e3);r.current.set(h,C)}},[]);u.useEffect(()=>{const p=D.On("watch/STATE",s);return()=>{p();for(const l of r.current.values())clearTimeout(l)}},[s]);const i=Array.from(t.values()),o=Be(i),a=i.find(p=>!ne(p))??i[0]??null,c=He(i);return{syncs:i,hasSyncing:o,primarySync:a,aggregateProgress:c}},st=()=>{const t=u.useContext(Se);if(!t)throw new Error("useOperations must be used within an OperationsProvider");return t},er=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=A(t),{showSnackbar:s}=$(),{addOperation:i,updateOperation:o}=st(),a=u.useRef(new Set),c=u.useCallback((h,g=!1)=>{var y,C,R;h.disposed||(h.disposed=!0,(y=h.unsubscribe)==null||y.call(h),(C=h.open)==null||C.cancel(),(R=h.attach)==null||R.cancel(),h.handle&&(S.CancelStreamAction(h.handle).catch(()=>{}),g&&o(h.handle,{status:"cancelled",message:"Cancelled",completedAt:Date.now()})),a.current.delete(h))},[o]);u.useEffect(()=>()=>{for(const h of a.current)c(h,!0)},[r,e,n,c]);const p=u.useCallback(async({actionID:h,id:g,namespace:y,label:C,params:R={}})=>{const d={disposed:!1,terminal:!1,sequence:0};a.current.add(d);try{d.open=S.StreamAction(r,e,n,h,k.ActionInput.createFrom({id:g,namespace:y,params:R}));const f=await d.open;if(d.open=void 0,d.disposed)return S.CancelStreamAction(f).catch(()=>{}),f;d.handle=f,i({id:f,label:C,resourceKey:n,resourceName:g,namespace:y,connectionID:e,status:"running",startedAt:Date.now()});const _=w=>{if(d.disposed||!Number.isSafeInteger(w.sequence)||w.sequence<=d.sequence)return;d.sequence=w.sequence;const x=w.event,b=x.data??{};if(x.type==="error"){d.terminal=!0;const I=W(x.error);o(f,{status:Y(I)?"cancelled":"error",message:I.title,completedAt:Date.now()}),G(s,I,C),c(d)}else if(x.type==="complete"){d.terminal=!0;const I=typeof b.message=="string"?b.message:`${C} completed`;o(f,{status:"completed",message:I,completedAt:Date.now()}),s(I,"success"),c(d)}else o(f,{message:typeof b.message=="string"?b.message:void 0,progress:typeof b.ready=="number"&&typeof b.desired=="number"?{ready:b.ready,desired:b.desired}:void 0})};d.unsubscribe=D.On(`action/stream/${f}`,w=>_(w.data)),d.attach=S.AttachStreamAction(f);const E=await d.attach;return d.attach=void 0,_(E),f}catch(f){if(d.terminal&&d.handle)return d.handle;throw d.disposed||(d.handle&&o(d.handle,{status:Y(f)?"cancelled":"error",message:W(f).title,completedAt:Date.now()}),G(s,f,`Failed to start "${h}"`)),c(d),f}},[r,e,n,i,o,s,c]),l=u.useCallback(h=>{for(const g of a.current)if(g.handle===h){c(g,!0);return}},[c]);return{startStreamAction:p,cancelStreamAction:l}};function ot(t,e){return`${t}/${e}/graph/CHANGED`}function ce(t,e,n,r){const s=v.useQueryClient(),i=u.useRef(n);i.current=n;const o=JSON.stringify(n);u.useEffect(()=>{if(!r||!t||!e)return;const a=D.On(ot(t,e),()=>{s.invalidateQueries({queryKey:i.current,exact:!0})});return()=>{a()}},[s,t,e,o,r])}const tr={owns:{outgoing:"Owns",incoming:"Owned by"},runs_on:{outgoing:"Runs on",incoming:"Running here"},uses:{outgoing:"Uses",incoming:"Used by"},exposes:{outgoing:"Exposes",incoming:"Exposed by"},manages:{outgoing:"Manages",incoming:"Managed by"},member_of:{outgoing:"Member of",incoming:"Members"},selects:{outgoing:"Selects",incoming:"Selected by"}};function nr(t,e){const n=tr[t];if(n)return n[e];const r=t.replace(/_/g," ");return e==="outgoing"?r:`${r} (incoming)`}function rr(t,e){return t.pluginId===e.pluginId&&t.connectionId===e.connectionId&&t.resourceKey===e.resourceKey&&t.id===e.id&&(t.namespace??"")===(e.namespace??"")}function it(t,e){return e.map(n=>{const r=rr(n.source,t);return{resource:r?n.target:n.source,type:n.type,direction:r?"outgoing":"incoming",label:n.label}})}const sr=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",direction:i="both",relationshipType:o,enabled:a=!0,refetchInterval:c=!1})=>{const p=A(t),l=["RESOURCE_RELATED",p,e,n,s,r,i,o??null],h=a&&!!p&&!!e&&!!n&&!!r;ce(p,e,l,h);const g=v.useQuery({queryKey:l,queryFn:async()=>S.GetRelated(p,e,n,s,r,i,o??null),enabled:h,refetchInterval:c}),y={pluginId:p,connectionId:e,resourceKey:n,id:r,namespace:s},C=g.data??[];return{related:it(y,C),edges:C,isLoading:g.isLoading,isFetching:g.isFetching,error:g.error,refetch:g.refetch}},or=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",maxDepth:i=3,enabled:o=!0,refetchInterval:a=!1})=>{const c=A(t),p=["RESOURCE_DEPENDENCY_TREE",c,e,n,s,r,i],l=o&&!!c&&!!e&&!!n&&!!r;ce(c,e,p,l);const h=v.useQuery({queryKey:p,queryFn:async()=>S.GetDependencyTree(c,e,n,s,r,i),enabled:l,refetchInterval:a});return{tree:h.data??null,isLoading:h.isLoading,isFetching:h.isFetching,error:h.error,refetch:h.refetch}},ir=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",upDepth:i=2,downDepth:o=3,enabled:a=!0})=>{const c=A(t),p=["RESOURCE_GRAPH",c,e,n,s,r,i,o],l=a&&!!c&&!!e&&!!n&&!!r;ce(c,e,p,l);const h=v.useQuery({queryKey:p,queryFn:async()=>S.GetSubgraph(c,e,n,s,r,i,o),enabled:l});return{graph:h.data??null,isLoading:h.isLoading,isFetching:h.isFetching,error:h.error,refetch:h.refetch}},ar=()=>{const t=u.useContext(Ee);if(!t)throw new Error("useSettings must be used within a SettingsProvider");return t},cr=({to:t,withinContext:e,...n})=>{const{pluginId:r}=oe();r||console.error("Link used outside of a plugin context");const s=`/_plugin/${r}${t.startsWith("/")?"":"/"}${t}`;return u.useMemo(()=>m.jsx(V.Link,{style:{textDecoration:"none",color:"inherit"},...n,to:s}),[n,s])};function ur(){const t=V.useNavigate(),e=V.useLocation(),{pluginId:n}=oe();n||console.error("usePluginRouter used outside of a plugin context");const r=`/_plugin/${n}`,s=e.pathname.startsWith(r)?e.pathname.slice(r.length)||"/":e.pathname,i=u.useCallback((o,a)=>{const{...c}=a??{};o.startsWith("/")?t(`${r}${o}`,c):t(o,c)},[t,r]);return u.useMemo(()=>({location:e,navigate:i,pluginPath:s}),[e,i,s])}class lr{}class dr{constructor(){F(this,"_extensions");F(this,"root");F(this,"pages");F(this,"_routes")}get extensions(){return this._extensions||[]}get Routes(){var e;if(!this._routes&&this.root)return[{path:"",index:!0,Component:this.root}];if(!((e=this._routes)!=null&&e.length))throw new Error("cannot use plugin without a root page or router");return this._routes}get Window(){if(!this._routes&&this.root)return m.jsx(this.root,{});const e=V.createMemoryRouter(this._routes||[]);return m.jsx(V.RouterProvider,{router:e})}registerExtensionPoints(e){return this._extensions=e||[],this}setRootPage(e){return this.root=e,this}withPage(e,n){return this.pages||(this.pages={}),this.pages[e]?(console.warn("Cannot register page with the same name. Please use a different name."),this):(this.pages[e]=n,this)}withRoutes(e){return this._routes=e,this}}var at=(t=>(t.MISSING_MANIFEST="MISSING_MANIFEST",t.MISSING_PLUGIN="MISSING_PLUGIN",t.MISSING_ENTRYPOINT="MISSING_ENTRYPOINT",t))(at||{});const fr=t=>{const e=t.split("::");return e.length===1?{group:"core",version:"",kind:e[0]}:{group:e[0]||"core",version:e[1]||"",kind:e[2]||e[0]}},pr=t=>!t||t==="core"?"Core":t.charAt(0).toUpperCase()+t.slice(1),ct="omniview/global-search/open";function hr(t={}){window.dispatchEvent(new CustomEvent(ct,{detail:t}))}const ut="omniview/resource/icons";class gr extends u.Component{constructor(){super(...arguments);F(this,"state",{failed:!1,resetToken:this.props.resetToken})}static getDerivedStateFromProps(n,r){return n.resetToken!==r.resetToken?{failed:!1,resetToken:n.resetToken}:null}static getDerivedStateFromError(){return{failed:!0}}render(){return this.state.failed?this.props.fallback:this.props.children}}function yr({pluginId:t,resourceKey:e,fallback:n,...r}){const s=$e(ut),i=n===void 0?m.jsx("svg",{width:r.size??16,height:r.size??16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:r.className,"aria-hidden":r["aria-hidden"]??!0,children:m.jsx("path",{d:"m12 3 9 5v8l-9 5-9-5V8l9-5Zm0 9 9-4M12 12 3 8m9 4v9"})}):n;for(const o of(s==null?void 0:s.listAll())??[])if(o.plugin===t)try{const a=o.value;if((a==null?void 0:a.schemaVersion)!==1||typeof a.resolve!="function")continue;const c=a.resolve(e);if(!c)continue;return m.jsx(gr,{resetToken:o,fallback:i,children:m.jsx(u.Suspense,{fallback:i,children:m.jsx(c,{...r,"aria-hidden":r["aria-hidden"]??!0})})},JSON.stringify([t,e,s==null?void 0:s.version,o.id]))}catch{}return m.jsx(m.Fragment,{children:i})}exports.ALL_SESSIONS_KEY=B;exports.BottomDrawerContext=Le;exports.ConfirmationModalContext=Me;exports.ErrorTypes=N;exports.ExtensionPointRegistry=bt;exports.ExtensionPointStore=Qe;exports.ExtensionProvider=wt;exports.GLOBAL_SEARCH_OPEN_EVENT=ct;exports.Link=cr;exports.OperationsContext=Se;exports.OperationsProvider=Et;exports.PluginContext=se;exports.PluginContextProvider=ht;exports.PluginErrorCode=at;exports.PluginWindow=dr;exports.PluginWindowRootProps=lr;exports.RESOURCE_ICON_EXTENSION_POINT_ID=ut;exports.ResourceIcon=yr;exports.RightDrawerContext=ke;exports.SettingsContext=Ee;exports.SettingsProvider=yt;exports.SnackbarProvider=xt;exports.WatchState=T;exports.actionToSnackbar=De;exports.applyBatch=nt;exports.connectionListQueryKey=Ge;exports.createErrorHandler=j;exports.defaultState=Fe;exports.formatGroup=pr;exports.graphChangedEvent=ot;exports.isCancelledError=Y;exports.openGlobalSearch=hr;exports.parseAppError=W;exports.parseResourceKey=fr;exports.relationshipLabel=nr;exports.resourceQueryKeys=re;exports.showAppError=G;exports.toRelatedResources=it;exports.useActiveSyncs=Zn;exports.useBottomDrawer=ve;exports.useConfirmationModal=$t;exports.useConnection=It;exports.useConnectionNamespaces=Tt;exports.useConnectionStatus=Pt;exports.useConnections=Ot;exports.useDependencyTree=or;exports.useEditorSchemas=Xn;exports.useEventBatcher=rt;exports.useExec=Ft;exports.useExecuteAction=Yn;exports.useExtensionPoint=$e;exports.useExtensionRegistry=Ue;exports.useLogs=Lt;exports.useMetricProviders=kt;exports.useMetricProvidersForResource=ze;exports.useMetricStream=jt;exports.useOperations=st;exports.usePluginContext=oe;exports.usePluginData=Dt;exports.usePluginRouter=ur;exports.usePluginSettings=gt;exports.usePortForwardSessions=qt;exports.useRefetchOnGraphChange=ce;exports.useRelatedResources=sr;exports.useResolvedPluginId=A;exports.useResource=Qt;exports.useResourceActions=Vn;exports.useResourceAreaComponent=Wt;exports.useResourceGraph=ir;exports.useResourceGroups=Gt;exports.useResourceMetrics=Mt;exports.useResourceMutations=zn;exports.useResourcePortForwarder=Ut;exports.useResourceSearch=Bt;exports.useResourceType=Ht;exports.useResourceTypes=Kt;exports.useResources=Kn;exports.useRightDrawer=Nt;exports.useSettings=ar;exports.useSnackbar=$;exports.useStreamAction=er;exports.useWatchState=Jn;
4
+ ${d.details??""}`)}catch{h("Copy failed. Select the diagnostic text and copy it manually.")}},children:"Copy details"}),(S=d.actions)==null?void 0:S.map((w,x)=>m.jsx(L.Button,{size:"sm",variant:"outline",onClick:w.onClick,children:w.label},`${w.label}-${x}`))]})]})})]},d.id)})]}),l&&m.jsx(L.Text,{as:"p",size:"sm",role:"status",style:U.CopyError,children:l})]})]})},$=()=>{const t=u.useContext(We);if(t===void 0)throw new Error("useCustomSnackbar must be used within a CustomSnackbarProvider");return t};function A(t){const e=u.useContext(se),n=(e==null?void 0:e.pluginId)??t;if(!n)throw new Error("pluginID must be provided either via PluginContext or as an explicit parameter");return n}const It=({pluginID:t,connectionID:e})=>{const n=A(t),r=v.useQueryClient(),{showSnackbar:s}=$(),i=[n,"connection","detail",e],{mutateAsync:o}=v.useMutation({mutationFn:async()=>C.StartConnection(n,e),onSuccess(h){r.setQueryData(i,h),r.invalidateQueries({queryKey:["EDITOR_SCHEMAS",n,e]})},onError:j(s,"Failed to start connection")}),{mutateAsync:a}=v.useMutation({mutationFn:async()=>C.StopConnection(n,e),onSuccess(h){r.setQueryData(i,h)},onError:j(s,"Failed to stop connection")}),{mutateAsync:c}=v.useMutation({mutationFn:async h=>C.UpdateConnection(n,h),onSuccess(h,{name:y}){s({message:`Connection ${y} successfully updated`,status:"success"}),r.setQueryData(i,h),r.setQueriesData({queryKey:[n,"connection","list"]},g=>g==null?void 0:g.map(E=>E.id===e?h:E))},onError:j(s,"Failed to update connection")}),{mutateAsync:p}=v.useMutation({mutationFn:async()=>C.RemoveConnection(n,e),onSuccess(){s({message:"Connection successfully removed",status:"success"}),r.setQueryData(i,void 0),r.setQueriesData({queryKey:[n,"connection","list"]},h=>h==null?void 0:h.filter(y=>y.id!==e))},onError:j(s,"Failed to remove connection")});return{connection:v.useQuery({queryKey:i,queryFn:async()=>C.GetConnection(n,e)}),startConnection:o,stopConnection:a,updateConnection:c,deleteConnection:p}},Ge=t=>[t,"connection","list"],Ot=({plugin:t})=>{const e=A(t),n=v.useQueryClient(),{showSnackbar:r}=$(),s=Ge(e),{mutateAsync:i}=v.useMutation({mutationFn:async p=>C.StartConnectionWatch(e,p.id),onError:j(r,"Failed to start connection watch")}),{mutateAsync:o}=v.useMutation({mutationFn:async p=>C.StopConnectionWatch(e,p.id),onError:j(r,"Failed to stop connection watch")}),a=u.useCallback(p=>{const l=p.data;console.log("got update to connections",l),n.setQueryData(s,l)},[n,s]);return u.useEffect(()=>{const p=D.On(`${e}/connection/sync`,a);return()=>{p()}},[e,a]),{connections:v.useQuery({queryKey:s,queryFn:async()=>{try{return await C.ListConnections(e)}catch(p){console.log(p),j(r,"Failed to load connections")(p)}return[]},staleTime:3e4,placeholderData:v.keepPreviousData}),startWatch:i,stopWatch:o}},Tt=({pluginID:t,connectionID:e})=>{const n=A(t),r=[n,"connection","namespaces",e];return{namespaces:v.useQuery({queryKey:r,queryFn:async()=>C.GetConnectionNamespaces(n,e)})}},T=pt.withLegacyNames(k.WatchState,"WatchState");function me(t){const e=Object.values(t.states),n=e.length;let r=0,s=0,i=0,o=0;for(const l of e)l===T.WatchStateSynced&&r++,(l===T.WatchStateError||l===T.WatchStateFailed)&&s++,l===T.WatchStateForbidden&&i++,l===T.WatchStateSkipped&&o++;const a=n-o,c=e.filter(l=>l===T.WatchStateSynced||l===T.WatchStateError||l===T.WatchStateStopped||l===T.WatchStateFailed||l===T.WatchStateForbidden).length,p=a>0?c/a:0;return{pluginID:t.pluginID,connectionID:t.connectionID,totalResources:n,watchedTotal:a,syncedCount:r,errorCount:s,forbiddenCount:i,skippedCount:o,doneCount:c,progress:p}}function ne(t){return t.watchedTotal>0&&t.doneCount>=t.watchedTotal}function Be(t){return t.some(e=>!ne(e))}function He(t){const e=t.reduce((r,s)=>r+s.watchedTotal,0);return e===0?0:t.reduce((r,s)=>r+s.doneCount,0)/e}function Ce(t){return`${t.pluginId}/${t.connection}`}function Ke(t,e){const n=Ce(e);t.has(n)||t.set(n,{states:{},pluginID:e.pluginId,connectionID:e.connection});const r=t.get(n);return r.states[e.resourceKey]=e.state,r}function Pt(){const[t,e]=u.useState(new Set),[n,r]=u.useState({}),[s,i]=u.useState(new Map),o=u.useRef(new Map),[a,c]=u.useState(new Map);u.useEffect(()=>{const S=D.On("plugin/crash_recovery_failed",x=>{const b=x.data,I=b==null?void 0:b.pluginID;I&&c(O=>{const P=new Map(O);return P.set(I,b.error??"Crash recovery failed"),P})}),w=D.On("plugin/recovered",x=>{const b=x.data,I=b==null?void 0:b.pluginID;I&&c(O=>{if(!O.has(I))return O;const P=new Map(O);return P.delete(I),P})});return()=>{S(),w()}},[]),u.useEffect(()=>{C.GetAllConnectionStates().then(S=>{if(!S)return;const w={},x=new Set,b=new Map;for(const[I,O]of Object.entries(S))if(O){w[I]=O.map(P=>P.connection);for(const P of O){if(!P.started)continue;const q=`${I}/${P.connection.id}`;x.add(q);const M={pluginID:I,connectionID:P.connection.id,states:{}};if(P.resources)for(const[ue,lt]of Object.entries(P.resources))M.states[ue]=lt;o.current.set(q,M),b.set(q,me(M))}}r(w),e(x),i(b)}).catch(()=>{})},[]),u.useEffect(()=>D.On("connection/status",w=>{const x=w.data,b=`${x.pluginID}/${x.connectionID}`;x.status==="DISCONNECTED"?(e(I=>{const O=new Set(I);return O.delete(b),O}),i(I=>{const O=new Map(I);return O.delete(b),O}),o.current.delete(b)):e(I=>{const O=new Set(I);return O.add(b),O}),C.ListAllConnections().then(I=>{if(!I)return;const O={};for(const[P,q]of Object.entries(I))q!=null&&(O[P]=q);r(O)}).catch(()=>{})}),[]);const p=u.useCallback(S=>{const w=S.data,x=Ce(w);e(O=>{if(O.has(x))return O;const P=new Set(O);return P.add(x),P});const b=Ke(o.current,w),I=me(b);i(O=>{const P=new Map(O);return P.set(x,I),P})},[]);u.useEffect(()=>D.On("watch/STATE",p),[p]);const l=u.useCallback(async(S,w)=>{await C.StopConnection(S,w)},[]),h=u.useCallback(async(S,w)=>{await C.StartConnectionWatch(S,w)},[]),y=u.useCallback(async S=>{const w=a.get(S);c(x=>{if(!x.has(S))return x;const b=new Map(x);return b.delete(S),b});try{await C.RetryFailedPlugin(S)}catch(x){throw c(b=>{const I=new Map(b);return I.set(S,w??"Reload failed"),I}),x}},[a]),g=[];for(const S of t){const[w,x]=S.split("/",2),I=(n[w]??[]).find(ue=>ue.id===x),O=s.get(S),P=O!=null&&!ne(O),q=O!=null&&O.errorCount>0,M=a.get(w);g.push({pluginID:w,connectionID:x,name:(I==null?void 0:I.name)??x,avatar:(I==null?void 0:I.avatar)??"",isStarted:!0,sync:O,isSyncing:P,hasErrors:q||M!=null,pluginFailed:M!=null,pluginError:M})}const E=new Map;for(const S of g){const w=E.get(S.pluginID)??[];w.push(S),E.set(S.pluginID,w)}const R=Array.from(s.values()),d=g.filter(S=>S.isSyncing),f=g.filter(S=>S.hasErrors),_=g.filter(S=>S.pluginFailed);return{entries:g,grouped:E,connectedCount:g.length,syncingCount:d.length,errorCount:f.length,failedCount:_.length,hasSyncing:Be(R),aggregateProgress:He(R),disconnect:l,retryWatch:h,retryPlugin:y}}function At(t,e){return e===null?t===null:Array.isArray(e)?Array.isArray(t):typeof e=="object"?typeof t=="object"&&t!==null&&!Array.isArray(t):typeof t==typeof e}function Dt(t,e,n){const r=A(t),s=v.useQueryClient(),i=[r,"data",e],o=v.useQuery({queryKey:i,queryFn:async()=>{const c=await C.Get(r,e);return c==null?n:At(c,n)?c:(console.warn(`[usePluginData] stored value for "${e}" has unexpected type (expected ${Array.isArray(n)?"array":typeof n}, got ${Array.isArray(c)?"array":typeof c}). Using default.`),n)}}),a=v.useMutation({mutationFn:async c=>{await C.Set(r,e,c)},onMutate:async c=>{await s.cancelQueries({queryKey:i});const p=s.getQueryData(i);return s.setQueryData(i,c),{previous:p}},onError:(c,p,l)=>{(l==null?void 0:l.previous)!==void 0&&s.setQueryData(i,l.previous)},onSettled:()=>{s.invalidateQueries({queryKey:i})}});return{data:o.data??n,update:async c=>{await a.mutateAsync(c)},isLoading:o.isLoading}}const Nt=()=>{const t=u.useContext(ke);if(!t)throw new Error("useRightDrawer must be used within a RightDrawerProvider");return t},ve=()=>{const t=u.useContext(Le);if(t===void 0)throw new Error("useBottomDrawer must be used within a BottomDrawerProvider");return t},Ft=({pluginID:t})=>{const e=A(t),{showSnackbar:n}=$(),{createTab:r,updateTab:s}=ve();return{createSession:v.useMutation({mutationFn:async({connectionID:o,icon:a,label:c,opts:p,recovery:l})=>{const h=`pending-${crypto.randomUUID()}`;r({id:h,title:c??"Connecting...",variant:"terminal",icon:a??"LuSquareTerminal",properties:{status:"connecting",pluginID:e,connectionID:o,opts:{...p},recovery:l}});const y=k.SessionOptions.createFrom({command:["/bin/bash"],tty:!0,...p});try{const g=await C.CreateSession(e,o,y);if(!g)throw new Error("Failed to create session: null response");return s({id:h},{id:g.id,title:c??`Session ${g.id.substring(0,8)}`,properties:{status:"connected",pluginID:e,connectionID:o,opts:{...p},recovery:l}}),g}catch(g){const E=W(g);return s({id:h},{properties:{status:"error",error:E.detail,pluginID:e,connectionID:o,opts:{...p},recovery:l,errorInfo:{title:E.title||"Session error",suggestion:E.detail,raw:E.detail}}}),G(n,g,"Failed to start session"),null}}}).mutateAsync}},Lt=({pluginID:t})=>{const e=A(t),{showSnackbar:n}=$(),{createTab:r}=ve(),s=v.useMutation({mutationFn:async({connectionID:o,resourceKey:a,resourceID:c,resourceData:p,icon:l,label:h,target:y,follow:g=!0,tailLines:E=1e3,params:R})=>{const d=k.CreateSessionOptions.createFrom({resource_key:a,resource_id:c,resource_data:p,options:k.LogSessionOptions.createFrom({target:y??"",follow:g,include_previous:!1,include_timestamps:!0,tail_lines:E,since_seconds:0,limit_bytes:0,include_source_events:!0,params:R??{}})}),f=await C.CreateSession$1(e,o,d);if(!f)throw new Error("Failed to create log session: null response");return r({id:f.id,title:h??`Logs ${f.id.substring(0,8)}`,variant:"logs",icon:l??"LuLogs"}),f},onError:j(n,"Failed to start log session")}),i=v.useMutation({mutationFn:async o=>{await C.CloseSession(o)},onError:j(n,"Failed to close log session")});return{createLogSession:s.mutateAsync,closeLogSession:i.mutateAsync}},kt=()=>v.useQuery({queryKey:["metric","providers"],queryFn:C.GetProviders,staleTime:3e4}),ze=t=>v.useQuery({queryKey:["metric","providers",t],queryFn:()=>C.GetProvidersForResource(t),enabled:!!t,staleTime:3e4}),Mt=t=>{var d,f;const{connectionID:e,resourceKey:n,resourceID:r,resourceNamespace:s="",resourceData:i={},metricIDs:o=[],shape:a=0,timeRange:c,refreshInterval:p=0,enabled:l=!0}=t,{data:h,isLoading:y}=ze(n),g=h??[],E=c?Math.max(Math.floor((c.end.getTime()-c.start.getTime())/250),15e3)*1e6:0,R=v.useQuery({queryKey:["metric","query",e,n,r,s,o,a,(d=c==null?void 0:c.start)==null?void 0:d.getTime(),(f=c==null?void 0:c.end)==null?void 0:f.getTime()],queryFn:async()=>{const _=await C.QueryAll(e,n,r,s,i,o,a,((c==null?void 0:c.start)??new Date(0)).toISOString(),((c==null?void 0:c.end)??new Date(0)).toISOString(),E),S={};for(const[w,x]of Object.entries(_))x!=null&&(S[w]=x);return S},enabled:l&&!!e&&!!n&&(n.startsWith("cluster::")||!!r)&&g.length>0,refetchInterval:p>0?p:void 0,staleTime:5e3,placeholderData:v.keepPreviousData});return{data:R.data??void 0,providers:g,isLoading:y||R.isLoading,error:R.error,refetch:R.refetch}},jt=t=>{const{pluginID:e,connectionID:n,resourceKey:r,resourceID:s,resourceNamespace:i="",resourceData:o={},metricIDs:a=[],interval:c=1e4,enabled:p=!0}=t,l=A(e),[h,y]=u.useState(null),[g,E]=u.useState(null),[R,d]=u.useState(!1),[f,_]=u.useState(null),S=u.useRef(null),w=u.useCallback(async()=>{if(!(!p||!l||!n||!r||!s))try{const b=await C.Subscribe(l,n,{resource_key:r,resource_id:s,resource_namespace:i,resource_data:o,metric_ids:a,interval:c*1e6});E(b),d(!0),_(null);const I=D.On(`core/metrics/data/${b}`,P=>{const q=P.data;try{const M=JSON.parse(q);M.results&&y(M.results)}catch(M){console.error("Failed to parse metric stream data:",M)}}),O=D.On(`core/metrics/error/${b}`,P=>{const q=P.data;try{const M=JSON.parse(q);_(M.error||"Unknown error")}catch{_("Failed to parse metric stream error")}});S.current=()=>{I(),O()}}catch(b){_(b instanceof Error?b.message:String(b))}},[l,n,r,s,i,a,c,p]),x=u.useCallback(async()=>{if(g)try{await C.Unsubscribe(g)}catch(b){console.error("Failed to unsubscribe:",b)}S.current&&(S.current(),S.current=null),E(null),d(!1)},[g]);return u.useEffect(()=>()=>{g&&C.Unsubscribe(g).catch(console.error),S.current&&S.current()},[g]),{data:h,subscriptionID:g,isStreaming:R,error:f,start:w,stop:x}},B=["networker","portforward","all-sessions"];function qt(){const{showSnackbar:t}=$(),e=v.useQueryClient(),n=v.useQuery({queryKey:[...B],queryFn:async()=>C.ListAllPortForwardSessions().catch(i=>{if(W(i).detail.includes("not found"))return[];throw i}),retry:!1});u.useEffect(()=>{const i=D.On("core/networker/portforward/created",()=>{e.invalidateQueries({queryKey:[...B]})}),o=D.On("core/networker/portforward/closed",()=>{e.invalidateQueries({queryKey:[...B]})});return()=>{i(),o()}},[e]);const r=n.data??[],s=v.useMutation({mutationFn:async i=>C.ClosePortForwardSession(i),onError:j(t,"Failed to close port forwarding session"),onSuccess:async()=>{await e.invalidateQueries({queryKey:[...B]})}});return{sessions:n,activeSessions:r,closeSession:s.mutateAsync,openInBrowser:i=>D.OpenURL(`http://localhost:${i}`)}}function Ut({pluginID:t,connectionID:e,resourceID:n}){const r=A(t),s=["networker","portforward","sessions",r,e,n],{showSnackbar:i}=$(),o=v.useQueryClient(),a=v.useQuery({queryKey:s,queryFn:async()=>C.FindPortForwardSessions(r,e,k.FindPortForwardSessionRequest.createFrom({resource_id:n,connection_id:e})).catch(l=>{const h=W(l);return h.detail.includes("not found")?[]:(i({message:"Failed to fetch port forward sessions",status:"error",details:h.detail}),[])}),retry:!1}),c=v.useMutation({mutationFn:async({opts:l})=>{const h=k.PortForwardSessionOptions.createFrom({local_port:l.localPort||0,remote_port:l.remotePort,protocol:l.protocol||"TCP",connection_type:"RESOURCE",connection:{resource_data:l.resource,connection_id:e,plugin_id:r,resource_id:l.resourceId,resource_key:l.resourceKey},labels:l.labels??{},params:l.parameters??{}}),y=await C.StartResourcePortForwardingSession(r,e,h);if(!y)throw new Error("Failed to start port forwarding: null response");return l.openInBrowser&&D.OpenURL(`http://localhost:${y.local_port}`),y},onError:j(i,"Failed to start port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...B]})])}}),p=v.useMutation({mutationFn:async({opts:l})=>C.ClosePortForwardSession(l.sessionID),onError:j(i,"Failed to close port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...B]})])}});return{sessions:a,forward:c.mutateAsync,close:p.mutateAsync}}const $t=()=>{const t=u.useContext(Me);if(!t)throw new Error("useConfirmationModal must be used within a ConfirmationModalProvider");return t},re={scope:(t,e,n)=>[t,e,n],list:(t,e,n,r=[])=>[t,e,n,r,"list"],resource:(t,e,n,r,s="")=>[t,e,n,s,r]},Qt=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s=""})=>{const i=A(t),o=v.useQueryClient(),{showSnackbar:a}=$(),c=re.resource(i,e,n,r,s),{mutateAsync:p}=v.useMutation({mutationFn:async y=>C.Update(i,e,n,k.UpdateInput.createFrom({input:y.input,id:r,namespace:s})),onSuccess:async()=>{a(`Resource ${r} updated`,"success"),await o.invalidateQueries({queryKey:c})},onError:j(a,`Failed to update resource ${r}`)}),{mutateAsync:l}=v.useMutation({mutationFn:async(y={})=>C.Delete(i,e,n,k.DeleteInput.createFrom({id:r,namespace:s,gracePeriodSeconds:y.gracePeriodSeconds})),onSuccess:async()=>{a(`Resource ${r} deleted`,"success"),await o.invalidateQueries({queryKey:c})},onError:j(a,`Failed to delete resource ${r}`)});return{resource:v.useQuery({queryKey:c,queryFn:async()=>C.Get$1(i,e,n,k.GetInput.createFrom({id:r,namespace:s})),retry:!1}),update:p,remove:l}},Wt=t=>{const e=["component",t.plugin,t.resource,t.area];return{component:v.useQuery({queryKey:e,queryFn:async()=>C.GetResourceAreaComponent(t)})}},Gt=({pluginID:t,connectionID:e})=>{const n=A(t),r=[n,"resource_groups","list"];return{groups:v.useQuery({queryKey:r,queryFn:async()=>C.GetResourceGroups(n,e),retry:!1})}},Bt=({pluginID:t,connectionID:e,searches:n})=>{const r=A(t),s=o=>[r,e,o.key,o.namespaces,"list"];return v.useQueries({queries:n.map(o=>({queryKey:s(o),queryFn:async()=>C.List(r,e,o.key,k.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:o.namespaces})).then(a=>a?(console.log(a.result),a.result&&o.postFilter?Object.values(a.result).filter(o.postFilter):Object.values(a.result||{})):[]),retry:!1}))})},Ht=({pluginID:t,resourceKey:e})=>{const n=A(t),r=[n,"resources",e];return{resourceType:v.useQuery({queryKey:r,queryFn:async()=>C.GetResourceType(n,e),retry:!1})}},Kt=({pluginID:t,connectionID:e})=>{const n=A(t),r=[n,"resources","list",e];return{types:v.useQuery({queryKey:r,queryFn:async()=>C.GetResourceTypes(n,e),retry:!1})}};var Z=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function zt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Vt="Expected a function",Ve="__lodash_hash_undefined__",Yt="[object Function]",Xt="[object GeneratorFunction]",Jt="[object Symbol]",Zt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,en=/^\w*$/,tn=/^\./,nn=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,rn=/[\\^$.*+?()[\]{}|]/g,sn=/\\(\\)?/g,on=/^\[object .+?Constructor\]$/,an=typeof Z=="object"&&Z&&Z.Object===Object&&Z,cn=typeof self=="object"&&self&&self.Object===Object&&self,_e=an||cn||Function("return this")();function un(t,e){return t==null?void 0:t[e]}function ln(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch{}return e}var dn=Array.prototype,fn=Function.prototype,Ye=Object.prototype,he=_e["__core-js_shared__"],Oe=function(){var t=/[^.]+$/.exec(he&&he.keys&&he.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Xe=fn.toString,we=Ye.hasOwnProperty,Je=Ye.toString,pn=RegExp("^"+Xe.call(we).replace(rn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Te=_e.Symbol,hn=dn.splice,gn=Ze(_e,"Map"),X=Ze(Object,"create"),Pe=Te?Te.prototype:void 0,Ae=Pe?Pe.toString:void 0;function H(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function yn(){this.__data__=X?X(null):{}}function mn(t){return this.has(t)&&delete this.__data__[t]}function En(t){var e=this.__data__;if(X){var n=e[t];return n===Ve?void 0:n}return we.call(e,t)?e[t]:void 0}function Sn(t){var e=this.__data__;return X?e[t]!==void 0:we.call(e,t)}function Cn(t,e){var n=this.__data__;return n[t]=X&&e===void 0?Ve:e,this}H.prototype.clear=yn;H.prototype.delete=mn;H.prototype.get=En;H.prototype.has=Sn;H.prototype.set=Cn;function z(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function vn(){this.__data__=[]}function _n(t){var e=this.__data__,n=ie(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():hn.call(e,n,1),!0}function wn(t){var e=this.__data__,n=ie(e,t);return n<0?void 0:e[n][1]}function bn(t){return ie(this.__data__,t)>-1}function Rn(t,e){var n=this.__data__,r=ie(n,t);return r<0?n.push([t,e]):n[r][1]=e,this}z.prototype.clear=vn;z.prototype.delete=_n;z.prototype.get=wn;z.prototype.has=bn;z.prototype.set=Rn;function K(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function xn(){this.__data__={hash:new H,map:new(gn||z),string:new H}}function In(t){return ae(this,t).delete(t)}function On(t){return ae(this,t).get(t)}function Tn(t){return ae(this,t).has(t)}function Pn(t,e){return ae(this,t).set(t,e),this}K.prototype.clear=xn;K.prototype.delete=In;K.prototype.get=On;K.prototype.has=Tn;K.prototype.set=Pn;function ie(t,e){for(var n=t.length;n--;)if($n(t[n][0],e))return n;return-1}function An(t,e){e=Ln(e,t)?[e]:Fn(e);for(var n=0,r=e.length;t!=null&&n<r;)t=t[qn(e[n++])];return n&&n==r?t:void 0}function Dn(t){if(!tt(t)||Mn(t))return!1;var e=Qn(t)||ln(t)?pn:on;return e.test(Un(t))}function Nn(t){if(typeof t=="string")return t;if(Re(t))return Ae?Ae.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function Fn(t){return et(t)?t:jn(t)}function ae(t,e){var n=t.__data__;return kn(e)?n[typeof e=="string"?"string":"hash"]:n.map}function Ze(t,e){var n=un(t,e);return Dn(n)?n:void 0}function Ln(t,e){if(et(t))return!1;var n=typeof t;return n=="number"||n=="symbol"||n=="boolean"||t==null||Re(t)?!0:en.test(t)||!Zt.test(t)||e!=null&&t in Object(e)}function kn(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Mn(t){return!!Oe&&Oe in t}var jn=be(function(t){t=Gn(t);var e=[];return tn.test(t)&&e.push(""),t.replace(nn,function(n,r,s,i){e.push(s?i.replace(sn,"$1"):r||n)}),e});function qn(t){if(typeof t=="string"||Re(t))return t;var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function Un(t){if(t!=null){try{return Xe.call(t)}catch{}try{return t+""}catch{}}return""}function be(t,e){if(typeof t!="function"||e&&typeof e!="function")throw new TypeError(Vt);var n=function(){var r=arguments,s=e?e.apply(this,r):r[0],i=n.cache;if(i.has(s))return i.get(s);var o=t.apply(this,r);return n.cache=i.set(s,o),o};return n.cache=new(be.Cache||K),n}be.Cache=K;function $n(t,e){return t===e||t!==t&&e!==e}var et=Array.isArray;function Qn(t){var e=tt(t)?Je.call(t):"";return e==Yt||e==Xt}function tt(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}function Wn(t){return!!t&&typeof t=="object"}function Re(t){return typeof t=="symbol"||Wn(t)&&Je.call(t)==Jt}function Gn(t){return t==null?"":Nn(t)}function Bn(t,e,n){var r=t==null?void 0:An(t,e);return r===void 0?n:r}var Hn=Bn;const ee=zt(Hn);function nt(t,e,n){const r=t??{result:[],success:!0,totalCount:0},s=[...r.result??[]];for(const i of e){const o=ee(i.payload.data,n);switch(i.type){case"ADD":{s.findIndex(c=>ee(c,n)===o)===-1&&s.push(i.payload.data);break}case"UPDATE":{const a=s.findIndex(c=>ee(c,n)===o);a!==-1&&(s[a]=i.payload.data);break}case"DELETE":{const a=s.findIndex(c=>ee(c,n)===o);a!==-1&&s.splice(a,1);break}}}return{...r,result:s}}function rt(t,e,n,r,s,i){const o=(i==null?void 0:i.syncWindowMs)??500,a=u.useRef([]),c=u.useRef(null),p=u.useRef(null),l=u.useRef(s);l.current=s;const h=u.useCallback(()=>{const g=a.current;if(a.current=[],c.current!==null&&(clearTimeout(c.current),c.current=null),p.current!==null&&(cancelAnimationFrame(p.current),p.current=null),!(g.length===0||!r)){t.setQueryData(e,E=>nt(E,g,r));for(const E of g)(E.type==="ADD"||E.type==="UPDATE")&&t.setQueryData(n(E.payload.id,E.payload.namespace),{success:!0,result:E.payload.data})}},[t,e,n,r]),y=u.useCallback(g=>{a.current.push(g),!(c.current!==null||p.current!==null)&&(c.current=setTimeout(h,o),l.current!==1&&(p.current=requestAnimationFrame(h)))},[h,o]);return u.useEffect(()=>()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),p.current!==null&&(cancelAnimationFrame(p.current),p.current=null)},[]),y}const Kn=({pluginID:t,connectionID:e,resourceKey:n,idAccessor:r,namespaces:s})=>{const i=A(t),o=v.useQueryClient(),{showSnackbar:a}=$(),c=u.useMemo(()=>s??[],[s]),p=u.useMemo(()=>re.list(i,e,n,c),[i,e,n,c]),l=u.useCallback((d,f)=>re.resource(i,e,n,d,f),[i,e,n]),{mutateAsync:h}=v.useMutation({mutationFn:async d=>C.Create(i,e,n,k.CreateInput.createFrom({input:d.input,namespace:d.namespace??(c.length===1?c[0]:"")})),onSuccess:async d=>{var w;const f=d==null?void 0:d.result;let _="";(w=f==null?void 0:f.metadata)!=null&&w.name?_=f.metadata.name:f!=null&&f.id?_=f.id:f!=null&&f.name?_=f.name:f!=null&&f.ID?_=f.ID:f!=null&&f.Name&&(_=f.Name);const S=_?`Resource ${_} created`:"Resource created";a(S,"success"),await o.invalidateQueries({queryKey:p})},onError:j(a,"Failed to create resource")}),y=v.useQuery({queryKey:p,queryFn:async()=>C.List(i,e,n,k.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:c})),placeholderData:(d,f)=>d,retry:!1}),[g,E]=u.useState(T.WatchStateIdle);u.useEffect(()=>D.On(`${i}/${e}/watch/STATE`,f=>{const _=f.data;_.resourceKey===n&&E(_.state)}),[i,e,n]);const R=rt(o,p,l,r,g);return u.useEffect(()=>{if(!r)return;C.SubscribeResource(i,e,n);const d=D.On(`${i}/${e}/${n}/ADD`,S=>R({type:"ADD",payload:S.data})),f=D.On(`${i}/${e}/${n}/UPDATE`,S=>R({type:"UPDATE",payload:S.data})),_=D.On(`${i}/${e}/${n}/DELETE`,S=>R({type:"DELETE",payload:S.data}));return()=>{d(),f(),_(),C.UnsubscribeResource(i,e,n)}},[i,e,n,R]),{resources:y,create:h,watchState:g,isSyncing:g===T.WatchStateSyncing,isSynced:g===T.WatchStateSynced,watchError:g===T.WatchStateError}},zn=({pluginID:t})=>{const e=A(t),{showSnackbar:n}=$(),r=v.useMutation({mutationFn:async({opts:o,input:a})=>C.Create(e,o.connectionID,o.resourceKey,k.CreateInput.createFrom({input:a.input,namespace:a.namespace??o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} created`,"success")},onError(o,{opts:a}){G(n,o,`Failed to create resource ${a.resourceID}`)}}),s=v.useMutation({mutationFn:async({opts:o,input:a})=>C.Update(e,o.connectionID,o.resourceKey,k.UpdateInput.createFrom({input:a.input,id:o.resourceID,namespace:o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} updated`,"success")},onError(o,{opts:a}){G(n,o,`Failed to update resource ${a.resourceID}`)}}),i=v.useMutation({mutationFn:async({opts:o,input:a})=>C.Delete(e,o.connectionID,o.resourceKey,k.DeleteInput.createFrom({id:o.resourceID,namespace:o.namespace??"",gracePeriodSeconds:a.gracePeriodSeconds})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} deleted`,"success")},onError(o,{opts:a}){G(n,o,`Failed to delete resource ${a.resourceID}`)}});return{create:r.mutateAsync,update:s.mutateAsync,remove:i.mutateAsync}},Vn=({pluginID:t,connectionID:e,resourceKey:n,enabled:r=!0})=>{const s=A(t),i=v.useQuery({queryKey:["RESOURCE_ACTIONS",s,e,n],queryFn:()=>C.GetActions(s,e,n),enabled:r&&!!s&&!!e&&!!n,staleTime:5*60*1e3});return{actions:i.data??[],isLoading:i.isLoading,error:i.error}},Yn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=A(t),s=v.useQueryClient(),{showSnackbar:i}=$(),o=v.useMutation({mutationFn:async({actionID:a,id:c="",namespace:p="",params:l={}})=>C.ExecuteAction(r,e,n,a,k.ActionInput.createFrom({id:c,namespace:p,params:l})),onSuccess:a=>{a!=null&&a.message&&i(a.message,"success"),s.invalidateQueries({queryKey:["RESOURCES",r,e,n]})},onError:(a,c)=>{G(i,a,`Failed to execute action "${c.actionID}"`)}});return{executeAction:o.mutateAsync,isExecuting:o.isPending,error:o.error}},Xn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=A(t),s=v.useQuery({queryKey:["EDITOR_SCHEMAS",r,e],queryFn:()=>C.GetEditorSchemas(r,e),enabled:n&&!!r&&!!e,staleTime:10*60*1e3,retry:1});return{schemas:s.data??[],isLoading:s.isLoading,error:s.error,refetch:s.refetch}},Jn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=A(t),s=v.useQueryClient(),i=[r,e,"watch-state"],o=u.useRef([]),a=u.useRef(!1),c=u.useCallback(y=>{s.setQueryData(i,g=>{if(!g)return g;const E={...g.resources,[y.resourceKey]:y.state},R={...g.resourceCounts,[y.resourceKey]:y.resourceCount};let d=0,f=0;for(const _ of Object.values(E))_===T.WatchStateSynced&&d++,(_===T.WatchStateError||_===T.WatchStateFailed)&&f++;return{...g,resources:E,resourceCounts:R,totalResources:Object.keys(E).length,syncedCount:d,errorCount:f}})},[s,r,e]),p=v.useQuery({queryKey:i,queryFn:async()=>{const y=await C.GetWatchState(r,e);if(!y)throw new Error("Failed to get watch state: null response");const g={};let E=0,R=0;for(const[f,_]of Object.entries(y.resources??{}))_!=null&&(g[f]=_,_===T.WatchStateSynced&&E++,_===T.WatchStateError&&R++);const d={};for(const[f,_]of Object.entries(y.resourceCounts??{}))_!=null&&(d[f]=_);return{connection:y.connectionId,resources:g,resourceCounts:d,totalResources:Object.keys(g).length,syncedCount:E,errorCount:R}},enabled:n&&!!r&&!!e,refetchInterval:y=>{const g=y.state.data;if(!g||g.totalResources===0)return 3e3;let E=0;for(const R of Object.values(g.resources))(R===T.WatchStateSynced||R===T.WatchStateError||R===T.WatchStateStopped||R===T.WatchStateFailed||R===T.WatchStateForbidden||R===T.WatchStateSkipped)&&E++;return E>=g.totalResources?!1:3e3}});u.useEffect(()=>{if(!p.data||a.current)return;a.current=!0;const y=o.current;o.current=[];for(const g of y)c(g)},[p.data,c]),u.useEffect(()=>{if(!n||!r||!e)return;a.current=!1,o.current=[];const y=D.On(`${r}/${e}/watch/STATE`,g=>{const E=g.data;a.current?c(E):o.current.push(E)});return()=>{y(),a.current=!1,o.current=[]}},[r,e,n,c]);const l=p.data;let h=0;if(l!=null&&l.resources)for(const y of Object.values(l.resources))(y===T.WatchStateSynced||y===T.WatchStateError||y===T.WatchStateStopped||y===T.WatchStateFailed||y===T.WatchStateForbidden||y===T.WatchStateSkipped)&&h++;return{summary:p,getResourceState:y=>l==null?void 0:l.resources[y],isFullySynced:l?l.totalResources>0&&h===l.totalResources:!1,syncProgress:l&&l.totalResources>0?h/l.totalResources:0,errorCount:(l==null?void 0:l.errorCount)??0}},Zn=()=>{const[t,e]=u.useState(new Map),n=u.useRef(new Map),r=u.useRef(new Map),s=u.useCallback(p=>{const l=p.data,h=Ce(l),y=Ke(n.current,l),g=me(y);if(e(E=>{const R=new Map(E);return R.set(h,g),R}),r.current.has(h)&&(clearTimeout(r.current.get(h)),r.current.delete(h)),ne(g)){const E=setTimeout(()=>{e(R=>{const d=new Map(R);return d.delete(h),d}),n.current.delete(h),r.current.delete(h)},5e3);r.current.set(h,E)}},[]);u.useEffect(()=>{const p=D.On("watch/STATE",s);return()=>{p();for(const l of r.current.values())clearTimeout(l)}},[s]);const i=Array.from(t.values()),o=Be(i),a=i.find(p=>!ne(p))??i[0]??null,c=He(i);return{syncs:i,hasSyncing:o,primarySync:a,aggregateProgress:c}},st=()=>{const t=u.useContext(Se);if(!t)throw new Error("useOperations must be used within an OperationsProvider");return t},er=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=A(t),{showSnackbar:s}=$(),{addOperation:i,updateOperation:o}=st(),a=u.useRef(new Set),c=u.useCallback((h,y=!1)=>{var g,E,R;h.disposed||(h.disposed=!0,(g=h.unsubscribe)==null||g.call(h),(E=h.open)==null||E.cancel(),(R=h.attach)==null||R.cancel(),h.handle&&(C.CancelStreamAction(h.handle).catch(()=>{}),y&&o(h.handle,{status:"cancelled",message:"Cancelled",completedAt:Date.now()})),a.current.delete(h))},[o]);u.useEffect(()=>()=>{for(const h of a.current)c(h,!0)},[r,e,n,c]);const p=u.useCallback(async({actionID:h,id:y,namespace:g,label:E,params:R={}})=>{const d={disposed:!1,terminal:!1,sequence:0};a.current.add(d);try{d.open=C.StreamAction(r,e,n,h,k.ActionInput.createFrom({id:y,namespace:g,params:R}));const f=await d.open;if(d.open=void 0,d.disposed)return C.CancelStreamAction(f).catch(()=>{}),f;d.handle=f,i({id:f,label:E,resourceKey:n,resourceName:y,namespace:g,connectionID:e,status:"running",startedAt:Date.now()});const _=w=>{if(d.disposed||!Number.isSafeInteger(w.sequence)||w.sequence<=d.sequence)return;d.sequence=w.sequence;const x=w.event,b=x.data??{};if(x.type==="error"){d.terminal=!0;const I=W(x.error);o(f,{status:Y(I)?"cancelled":"error",message:I.title,completedAt:Date.now()}),G(s,I,E),c(d)}else if(x.type==="complete"){d.terminal=!0;const I=typeof b.message=="string"?b.message:`${E} completed`;o(f,{status:"completed",message:I,completedAt:Date.now()}),s(I,"success"),c(d)}else o(f,{message:typeof b.message=="string"?b.message:void 0,progress:typeof b.ready=="number"&&typeof b.desired=="number"?{ready:b.ready,desired:b.desired}:void 0})};d.unsubscribe=D.On(`action/stream/${f}`,w=>_(w.data)),d.attach=C.AttachStreamAction(f);const S=await d.attach;return d.attach=void 0,_(S),f}catch(f){if(d.terminal&&d.handle)return d.handle;throw d.disposed||(d.handle&&o(d.handle,{status:Y(f)?"cancelled":"error",message:W(f).title,completedAt:Date.now()}),G(s,f,`Failed to start "${h}"`)),c(d),f}},[r,e,n,i,o,s,c]),l=u.useCallback(h=>{for(const y of a.current)if(y.handle===h){c(y,!0);return}},[c]);return{startStreamAction:p,cancelStreamAction:l}};function ot(t,e){return`${t}/${e}/graph/CHANGED`}function ce(t,e,n,r){const s=v.useQueryClient(),i=u.useRef(n);i.current=n;const o=JSON.stringify(n);u.useEffect(()=>{if(!r||!t||!e)return;const a=D.On(ot(t,e),()=>{s.invalidateQueries({queryKey:i.current,exact:!0})});return()=>{a()}},[s,t,e,o,r])}const tr={owns:{outgoing:"Owns",incoming:"Owned by"},runs_on:{outgoing:"Runs on",incoming:"Running here"},uses:{outgoing:"Uses",incoming:"Used by"},exposes:{outgoing:"Exposes",incoming:"Exposed by"},manages:{outgoing:"Manages",incoming:"Managed by"},member_of:{outgoing:"Member of",incoming:"Members"},selects:{outgoing:"Selects",incoming:"Selected by"}};function nr(t,e){const n=tr[t];if(n)return n[e];const r=t.replace(/_/g," ");return e==="outgoing"?r:`${r} (incoming)`}function rr(t,e){return t.pluginId===e.pluginId&&t.connectionId===e.connectionId&&t.resourceKey===e.resourceKey&&t.id===e.id&&(t.namespace??"")===(e.namespace??"")}function it(t,e){return e.map(n=>{const r=rr(n.source,t);return{resource:r?n.target:n.source,type:n.type,direction:r?"outgoing":"incoming",label:n.label}})}const sr=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",direction:i="both",relationshipType:o,enabled:a=!0,refetchInterval:c=!1})=>{const p=A(t),l=["RESOURCE_RELATED",p,e,n,s,r,i,o??null],h=a&&!!p&&!!e&&!!n&&!!r;ce(p,e,l,h);const y=v.useQuery({queryKey:l,queryFn:async()=>C.GetRelated(p,e,n,s,r,i,o??null),enabled:h,refetchInterval:c}),g={pluginId:p,connectionId:e,resourceKey:n,id:r,namespace:s},E=y.data??[];return{related:it(g,E),edges:E,isLoading:y.isLoading,isFetching:y.isFetching,error:y.error,refetch:y.refetch}},or=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",maxDepth:i=3,enabled:o=!0,refetchInterval:a=!1})=>{const c=A(t),p=["RESOURCE_DEPENDENCY_TREE",c,e,n,s,r,i],l=o&&!!c&&!!e&&!!n&&!!r;ce(c,e,p,l);const h=v.useQuery({queryKey:p,queryFn:async()=>C.GetDependencyTree(c,e,n,s,r,i),enabled:l,refetchInterval:a});return{tree:h.data??null,isLoading:h.isLoading,isFetching:h.isFetching,error:h.error,refetch:h.refetch}},ir=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",upDepth:i=2,downDepth:o=3,enabled:a=!0})=>{const c=A(t),p=["RESOURCE_GRAPH",c,e,n,s,r,i,o],l=a&&!!c&&!!e&&!!n&&!!r;ce(c,e,p,l);const h=v.useQuery({queryKey:p,queryFn:async()=>C.GetSubgraph(c,e,n,s,r,i,o),enabled:l});return{graph:h.data??null,isLoading:h.isLoading,isFetching:h.isFetching,error:h.error,refetch:h.refetch}},ar=()=>{const t=u.useContext(Ee);if(!t)throw new Error("useSettings must be used within a SettingsProvider");return t},cr=({to:t,withinContext:e,...n})=>{const{pluginId:r}=oe();r||console.error("Link used outside of a plugin context");const s=`/_plugin/${r}${t.startsWith("/")?"":"/"}${t}`;return u.useMemo(()=>m.jsx(V.Link,{style:{textDecoration:"none",color:"inherit"},...n,to:s}),[n,s])};function ur(){const t=V.useNavigate(),e=V.useLocation(),{pluginId:n}=oe();n||console.error("usePluginRouter used outside of a plugin context");const r=`/_plugin/${n}`,s=e.pathname.startsWith(r)?e.pathname.slice(r.length)||"/":e.pathname,i=u.useCallback((o,a)=>{const{...c}=a??{};o.startsWith("/")?t(`${r}${o}`,c):t(o,c)},[t,r]);return u.useMemo(()=>({location:e,navigate:i,pluginPath:s}),[e,i,s])}class lr{}class dr{constructor(){F(this,"_extensions");F(this,"root");F(this,"pages");F(this,"_routes")}get extensions(){return this._extensions||[]}get Routes(){var e;if(!this._routes&&this.root)return[{path:"",index:!0,Component:this.root}];if(!((e=this._routes)!=null&&e.length))throw new Error("cannot use plugin without a root page or router");return this._routes}get Window(){if(!this._routes&&this.root)return m.jsx(this.root,{});const e=V.createMemoryRouter(this._routes||[]);return m.jsx(V.RouterProvider,{router:e})}registerExtensionPoints(e){return this._extensions=e||[],this}setRootPage(e){return this.root=e,this}withPage(e,n){return this.pages||(this.pages={}),this.pages[e]?(console.warn("Cannot register page with the same name. Please use a different name."),this):(this.pages[e]=n,this)}withRoutes(e){return this._routes=e,this}}var at=(t=>(t.MISSING_MANIFEST="MISSING_MANIFEST",t.MISSING_PLUGIN="MISSING_PLUGIN",t.MISSING_ENTRYPOINT="MISSING_ENTRYPOINT",t))(at||{});const fr=t=>{const e=t.split("::");return e.length===1?{group:"core",version:"",kind:e[0]}:{group:e[0]||"core",version:e[1]||"",kind:e[2]||e[0]}},pr=t=>!t||t==="core"?"Core":t.charAt(0).toUpperCase()+t.slice(1),ct="omniview/global-search/open";function hr(t={}){window.dispatchEvent(new CustomEvent(ct,{detail:t}))}const ut="omniview/resource/icons";class gr extends u.Component{constructor(){super(...arguments);F(this,"state",{failed:!1,resetToken:this.props.resetToken})}static getDerivedStateFromProps(n,r){return n.resetToken!==r.resetToken?{failed:!1,resetToken:n.resetToken}:null}static getDerivedStateFromError(){return{failed:!0}}render(){return this.state.failed?this.props.fallback:this.props.children}}function yr({pluginId:t,resourceKey:e,fallback:n,...r}){const s=$e(ut),i=n===void 0?m.jsx("svg",{width:r.size??16,height:r.size??16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:r.className,"aria-hidden":r["aria-hidden"]??!0,children:m.jsx("path",{d:"m12 3 9 5v8l-9 5-9-5V8l9-5Zm0 9 9-4M12 12 3 8m9 4v9"})}):n;for(const o of(s==null?void 0:s.listAll())??[])if(o.plugin===t)try{const a=o.value;if((a==null?void 0:a.schemaVersion)!==1||typeof a.resolve!="function")continue;const c=a.resolve(e);if(!c)continue;return m.jsx(gr,{resetToken:o,fallback:i,children:m.jsx(u.Suspense,{fallback:i,children:m.jsx(c,{...r,"aria-hidden":r["aria-hidden"]??!0})})},JSON.stringify([t,e,s==null?void 0:s.version,o.id]))}catch{}return m.jsx(m.Fragment,{children:i})}exports.ALL_SESSIONS_KEY=B;exports.BottomDrawerContext=Le;exports.ConfirmationModalContext=Me;exports.ErrorTypes=N;exports.ExtensionPointRegistry=bt;exports.ExtensionPointStore=Qe;exports.ExtensionProvider=wt;exports.GLOBAL_SEARCH_OPEN_EVENT=ct;exports.Link=cr;exports.OperationsContext=Se;exports.OperationsProvider=Et;exports.PluginContext=se;exports.PluginContextProvider=ht;exports.PluginErrorCode=at;exports.PluginWindow=dr;exports.PluginWindowRootProps=lr;exports.RESOURCE_ICON_EXTENSION_POINT_ID=ut;exports.ResourceIcon=yr;exports.RightDrawerContext=ke;exports.SettingsContext=Ee;exports.SettingsProvider=yt;exports.SnackbarProvider=xt;exports.WatchState=T;exports.actionToSnackbar=De;exports.applyBatch=nt;exports.connectionListQueryKey=Ge;exports.createErrorHandler=j;exports.defaultState=Fe;exports.formatGroup=pr;exports.graphChangedEvent=ot;exports.isCancelledError=Y;exports.openGlobalSearch=hr;exports.parseAppError=W;exports.parseResourceKey=fr;exports.relationshipLabel=nr;exports.resourceQueryKeys=re;exports.showAppError=G;exports.toRelatedResources=it;exports.useActiveSyncs=Zn;exports.useBottomDrawer=ve;exports.useConfirmationModal=$t;exports.useConnection=It;exports.useConnectionNamespaces=Tt;exports.useConnectionStatus=Pt;exports.useConnections=Ot;exports.useDependencyTree=or;exports.useEditorSchemas=Xn;exports.useEventBatcher=rt;exports.useExec=Ft;exports.useExecuteAction=Yn;exports.useExtensionPoint=$e;exports.useExtensionRegistry=Ue;exports.useLogs=Lt;exports.useMetricProviders=kt;exports.useMetricProvidersForResource=ze;exports.useMetricStream=jt;exports.useOperations=st;exports.usePluginContext=oe;exports.usePluginData=Dt;exports.usePluginRouter=ur;exports.usePluginSettings=gt;exports.usePortForwardSessions=qt;exports.useRefetchOnGraphChange=ce;exports.useRelatedResources=sr;exports.useResolvedPluginId=A;exports.useResource=Qt;exports.useResourceActions=Vn;exports.useResourceAreaComponent=Wt;exports.useResourceGraph=ir;exports.useResourceGroups=Gt;exports.useResourceMetrics=Mt;exports.useResourceMutations=zn;exports.useResourcePortForwarder=Ut;exports.useResourceSearch=Bt;exports.useResourceType=Ht;exports.useResourceTypes=Kt;exports.useResources=Kn;exports.useRightDrawer=Nt;exports.useSettings=ar;exports.useSnackbar=$;exports.useStreamAction=er;exports.useWatchState=Jn;
package/dist/index.js CHANGED
@@ -191,16 +191,16 @@ function U(t, e) {
191
191
  };
192
192
  }
193
193
  function hs(t) {
194
- const { children: e, pluginId: n, headless: r = !1 } = t, [s, i] = C.useState({}), [o, a] = C.useState(new mn()), [c, f] = C.useState(!1), [u, p] = C.useState(null), h = C.useRef(0), g = C.useRef(0);
194
+ const { children: e, pluginId: n, headless: r = !1 } = t, [s, i] = C.useState({}), [o, a] = C.useState(new mn()), [c, f] = C.useState(!1), [u, p] = C.useState(null), g = C.useRef(0), h = C.useRef(0);
195
195
  console.debug("[PluginContextProvider] render", { pluginId: n, metaLoaded: c, metaError: !!u });
196
- const m = C.useCallback(() => {
196
+ const y = C.useCallback(() => {
197
197
  if (n === void 0 || n === "")
198
198
  return;
199
- const l = ++h.current;
199
+ const l = ++g.current;
200
200
  console.debug(`[PluginContextProvider] fetching settings for "${n}"`), At(n).then((d) => {
201
- l === h.current && (console.debug(`[PluginContextProvider] settings loaded for "${n}"`, Object.keys(d)), i(d));
201
+ l === g.current && (console.debug(`[PluginContextProvider] settings loaded for "${n}"`, Object.keys(d)), i(d));
202
202
  }).catch((d) => {
203
- if (l !== h.current) return;
203
+ if (l !== g.current) return;
204
204
  const E = H(d);
205
205
  console.error(`[PluginContextProvider] error fetching settings for "${n}":`, E.detail);
206
206
  });
@@ -209,11 +209,11 @@ function hs(t) {
209
209
  console.debug("[PluginContextProvider] skipping meta fetch — empty pluginId");
210
210
  return;
211
211
  }
212
- const l = ++g.current;
212
+ const l = ++h.current;
213
213
  console.debug(`[PluginContextProvider] fetching meta for "${n}"`), p(null), Nt(n).then((d) => {
214
- l === g.current && (console.debug(`[PluginContextProvider] meta loaded for "${n}"`, { name: d == null ? void 0 : d.name, version: d == null ? void 0 : d.version }), a(d), f(!0));
214
+ l === h.current && (console.debug(`[PluginContextProvider] meta loaded for "${n}"`, { name: d == null ? void 0 : d.name, version: d == null ? void 0 : d.version }), a(d), f(!0));
215
215
  }).catch((d) => {
216
- if (l !== g.current) return;
216
+ if (l !== h.current) return;
217
217
  const E = H(d);
218
218
  console.error(`[PluginContextProvider] error fetching meta for "${n}":`, E.detail), p(E.detail), f(!1);
219
219
  });
@@ -221,21 +221,21 @@ function hs(t) {
221
221
  if (C.useEffect(() => {
222
222
  if (c) return;
223
223
  const l = () => {
224
- m(), w();
224
+ y(), w();
225
225
  }, d = [
226
226
  D("plugin/init_complete", l),
227
227
  D("plugin/dev_install_complete", (E) => {
228
- var y;
229
- ((y = E.data) == null ? void 0 : y.id) === n && l();
228
+ var m;
229
+ ((m = E.data) == null ? void 0 : m.id) === n && l();
230
230
  }),
231
231
  D("plugin/inventory_changed", l)
232
232
  ];
233
233
  return () => {
234
234
  for (const E of d) E();
235
235
  };
236
- }, [n, c, m, w]), C.useEffect(() => (console.debug(`[PluginContextProvider] useEffect — pluginId changed to "${n}"`), f(!1), p(null), i({}), m(), w(), () => {
237
- ++h.current, ++g.current;
238
- }), [n, m, w]), u) {
236
+ }, [n, c, y, w]), C.useEffect(() => (console.debug(`[PluginContextProvider] useEffect — pluginId changed to "${n}"`), f(!1), p(null), i({}), y(), w(), () => {
237
+ ++g.current, ++h.current;
238
+ }), [n, y, w]), u) {
239
239
  if (r) throw new Error(u);
240
240
  return /* @__PURE__ */ _("div", { style: {
241
241
  display: "flex",
@@ -712,30 +712,30 @@ const $ = {
712
712
  warning: "warning",
713
713
  error: "danger"
714
714
  }, vs = ({ children: t }) => {
715
- const { toast: e } = In(), [n, r] = C.useState([]), [s, i] = C.useState([]), [o, a] = C.useState(!1), [c, f] = C.useState(), [u, p] = C.useState(""), h = C.useRef(Date.now()), g = C.useRef(null);
715
+ const { toast: e } = In(), [n, r] = C.useState([]), [s, i] = C.useState([]), [o, a] = C.useState(!1), [c, f] = C.useState(), [u, p] = C.useState(""), g = C.useRef(Date.now()), h = C.useRef(null);
716
716
  C.useEffect(() => {
717
717
  var E;
718
718
  if (!o)
719
719
  return;
720
720
  const l = document.activeElement;
721
- (E = g.current) == null || E.focus();
722
- const d = (y) => {
723
- y.key === "Escape" && (y.stopPropagation(), a(!1));
721
+ (E = h.current) == null || E.focus();
722
+ const d = (m) => {
723
+ m.key === "Escape" && (m.stopPropagation(), a(!1));
724
724
  };
725
725
  return document.addEventListener("keydown", d), () => {
726
726
  document.removeEventListener("keydown", d), l instanceof HTMLElement && l.isConnected && l.focus();
727
727
  };
728
728
  }, [o]);
729
- const m = (l) => {
729
+ const y = (l) => {
730
730
  r((d) => [...d, l]);
731
731
  }, w = (l, d, E) => {
732
- const y = typeof l == "object";
732
+ const m = typeof l == "object";
733
733
  let S = "", b = "info", v, R = 5e3, I;
734
- if (y) {
734
+ if (m) {
735
735
  if (S = l.message, l.showOnce) {
736
736
  if (n.includes(S))
737
737
  return;
738
- m(S);
738
+ y(S);
739
739
  }
740
740
  b = l.status, v = l.details, R = l.autoHideDuration ?? 5e3, I = l.actions;
741
741
  } else
@@ -743,7 +743,7 @@ const $ = {
743
743
  let O;
744
744
  if (b === "error") {
745
745
  const k = {
746
- id: ++h.current,
746
+ id: ++g.current,
747
747
  message: S,
748
748
  details: v,
749
749
  created: (/* @__PURE__ */ new Date()).toISOString(),
@@ -767,7 +767,7 @@ const $ = {
767
767
  o && /* @__PURE__ */ q(
768
768
  Tn,
769
769
  {
770
- ref: g,
770
+ ref: h,
771
771
  style: $.Panel,
772
772
  size: "sm",
773
773
  variant: "outline",
@@ -812,7 +812,7 @@ const $ = {
812
812
  /* @__PURE__ */ q("div", { style: $.List, children: [
813
813
  s.length === 0 && /* @__PURE__ */ _(On, { size: "sm", title: "No recent errors", description: "Error details will appear here." }),
814
814
  s.slice().reverse().map((l) => {
815
- var E, y;
815
+ var E, m;
816
816
  const d = c === l.id;
817
817
  return /* @__PURE__ */ q("div", { style: $.Notice, children: [
818
818
  /* @__PURE__ */ q("div", { style: $.Row, children: [
@@ -878,7 +878,7 @@ ${l.details ?? ""}`);
878
878
  p("Copy failed. Select the diagnostic text and copy it manually.");
879
879
  }
880
880
  }, children: "Copy details" }),
881
- (y = l.actions) == null ? void 0 : y.map((S, b) => /* @__PURE__ */ _(pe, { size: "sm", variant: "outline", onClick: S.onClick, children: S.label }, `${S.label}-${b}`))
881
+ (m = l.actions) == null ? void 0 : m.map((S, b) => /* @__PURE__ */ _(pe, { size: "sm", variant: "outline", onClick: S.onClick, children: S.label }, `${S.label}-${b}`))
882
882
  ] })
883
883
  ] }) })
884
884
  ] }, l.id);
@@ -920,10 +920,10 @@ const Cs = ({ pluginID: t, connectionID: e }) => {
920
920
  onError: U(s, "Failed to stop connection")
921
921
  }), { mutateAsync: c } = x({
922
922
  mutationFn: async (p) => xt(n, p),
923
- onSuccess(p, { name: h }) {
924
- s({ message: `Connection ${h} successfully updated`, status: "success" }), r.setQueryData(i, p), r.setQueriesData(
923
+ onSuccess(p, { name: g }) {
924
+ s({ message: `Connection ${g} successfully updated`, status: "success" }), r.setQueryData(i, p), r.setQueriesData(
925
925
  { queryKey: [n, "connection", "list"] },
926
- (g) => g == null ? void 0 : g.map((m) => m.id === e ? p : m)
926
+ (h) => h == null ? void 0 : h.map((y) => y.id === e ? p : y)
927
927
  );
928
928
  },
929
929
  onError: U(s, "Failed to update connection")
@@ -932,7 +932,7 @@ const Cs = ({ pluginID: t, connectionID: e }) => {
932
932
  onSuccess() {
933
933
  s({ message: "Connection successfully removed", status: "success" }), r.setQueryData(i, void 0), r.setQueriesData(
934
934
  { queryKey: [n, "connection", "list"] },
935
- (p) => p == null ? void 0 : p.filter((h) => h.id !== e)
935
+ (p) => p == null ? void 0 : p.filter((g) => g.id !== e)
936
936
  );
937
937
  },
938
938
  onError: U(s, "Failed to remove connection")
@@ -1054,7 +1054,7 @@ function ut(t, e) {
1054
1054
  function bs() {
1055
1055
  const [t, e] = B(/* @__PURE__ */ new Set()), [n, r] = B({}), [s, i] = B(/* @__PURE__ */ new Map()), o = W(/* @__PURE__ */ new Map()), [a, c] = B(/* @__PURE__ */ new Map());
1056
1056
  j(() => {
1057
- const y = D("plugin/crash_recovery_failed", (b) => {
1057
+ const m = D("plugin/crash_recovery_failed", (b) => {
1058
1058
  const v = b.data, R = v == null ? void 0 : v.pluginID;
1059
1059
  R && c((I) => {
1060
1060
  const O = new Map(I);
@@ -1069,13 +1069,13 @@ function bs() {
1069
1069
  });
1070
1070
  });
1071
1071
  return () => {
1072
- y(), S();
1072
+ m(), S();
1073
1073
  };
1074
1074
  }, []), j(() => {
1075
- qt().then((y) => {
1076
- if (!y) return;
1075
+ qt().then((m) => {
1076
+ if (!m) return;
1077
1077
  const S = {}, b = /* @__PURE__ */ new Set(), v = /* @__PURE__ */ new Map();
1078
- for (const [R, I] of Object.entries(y))
1078
+ for (const [R, I] of Object.entries(m))
1079
1079
  if (I) {
1080
1080
  S[R] = I.map((O) => O.connection);
1081
1081
  for (const O of I) {
@@ -1116,8 +1116,8 @@ function bs() {
1116
1116
  }).catch(() => {
1117
1117
  });
1118
1118
  }), []);
1119
- const f = M((y) => {
1120
- const S = y.data, b = Re(S);
1119
+ const f = M((m) => {
1120
+ const S = m.data, b = Re(S);
1121
1121
  e((I) => {
1122
1122
  if (I.has(b)) return I;
1123
1123
  const O = new Set(I);
@@ -1130,29 +1130,29 @@ function bs() {
1130
1130
  });
1131
1131
  }, []);
1132
1132
  j(() => D("watch/STATE", f), [f]);
1133
- const u = M(async (y, S) => {
1134
- await We(y, S);
1135
- }, []), p = M(async (y, S) => {
1136
- await Ge(y, S);
1137
- }, []), h = M(async (y) => {
1138
- const S = a.get(y);
1133
+ const u = M(async (m, S) => {
1134
+ await We(m, S);
1135
+ }, []), p = M(async (m, S) => {
1136
+ await Ge(m, S);
1137
+ }, []), g = M(async (m) => {
1138
+ const S = a.get(m);
1139
1139
  c((b) => {
1140
- if (!b.has(y)) return b;
1140
+ if (!b.has(m)) return b;
1141
1141
  const v = new Map(b);
1142
- return v.delete(y), v;
1142
+ return v.delete(m), v;
1143
1143
  });
1144
1144
  try {
1145
- await $t(y);
1145
+ await $t(m);
1146
1146
  } catch (b) {
1147
1147
  throw c((v) => {
1148
1148
  const R = new Map(v);
1149
- return R.set(y, S ?? "Reload failed"), R;
1149
+ return R.set(m, S ?? "Reload failed"), R;
1150
1150
  }), b;
1151
1151
  }
1152
- }, [a]), g = [];
1153
- for (const y of t) {
1154
- const [S, b] = y.split("/", 2), R = (n[S] ?? []).find((fe) => fe.id === b), I = s.get(y), O = I != null && !ce(I), k = I != null && I.errorCount > 0, L = a.get(S);
1155
- g.push({
1152
+ }, [a]), h = [];
1153
+ for (const m of t) {
1154
+ const [S, b] = m.split("/", 2), R = (n[S] ?? []).find((fe) => fe.id === b), I = s.get(m), O = I != null && !ce(I), k = I != null && I.errorCount > 0, L = a.get(S);
1155
+ h.push({
1156
1156
  pluginID: S,
1157
1157
  connectionID: b,
1158
1158
  name: (R == null ? void 0 : R.name) ?? b,
@@ -1165,16 +1165,16 @@ function bs() {
1165
1165
  pluginError: L
1166
1166
  });
1167
1167
  }
1168
- const m = /* @__PURE__ */ new Map();
1169
- for (const y of g) {
1170
- const S = m.get(y.pluginID) ?? [];
1171
- S.push(y), m.set(y.pluginID, S);
1168
+ const y = /* @__PURE__ */ new Map();
1169
+ for (const m of h) {
1170
+ const S = y.get(m.pluginID) ?? [];
1171
+ S.push(m), y.set(m.pluginID, S);
1172
1172
  }
1173
- const w = Array.from(s.values()), l = g.filter((y) => y.isSyncing), d = g.filter((y) => y.hasErrors), E = g.filter((y) => y.pluginFailed);
1173
+ const w = Array.from(s.values()), l = h.filter((m) => m.isSyncing), d = h.filter((m) => m.hasErrors), E = h.filter((m) => m.pluginFailed);
1174
1174
  return {
1175
- entries: g,
1176
- grouped: m,
1177
- connectedCount: g.length,
1175
+ entries: h,
1176
+ grouped: y,
1177
+ connectedCount: h.length,
1178
1178
  syncingCount: l.length,
1179
1179
  errorCount: d.length,
1180
1180
  failedCount: E.length,
@@ -1182,7 +1182,7 @@ function bs() {
1182
1182
  aggregateProgress: ct(w),
1183
1183
  disconnect: u,
1184
1184
  retryWatch: p,
1185
- retryPlugin: h
1185
+ retryPlugin: g
1186
1186
  };
1187
1187
  }
1188
1188
  function Hn(t, e) {
@@ -1234,10 +1234,10 @@ const Is = () => {
1234
1234
  const e = A(t), { showSnackbar: n } = Q(), { createTab: r, updateTab: s } = lt();
1235
1235
  return {
1236
1236
  createSession: x({
1237
- mutationFn: async ({ connectionID: o, icon: a, label: c, opts: f }) => {
1238
- const u = `pending-${crypto.randomUUID()}`;
1237
+ mutationFn: async ({ connectionID: o, icon: a, label: c, opts: f, recovery: u }) => {
1238
+ const p = `pending-${crypto.randomUUID()}`;
1239
1239
  r({
1240
- id: u,
1240
+ id: p,
1241
1241
  title: c ?? "Connecting...",
1242
1242
  variant: "terminal",
1243
1243
  icon: a ?? "LuSquareTerminal",
@@ -1245,33 +1245,42 @@ const Is = () => {
1245
1245
  status: "connecting",
1246
1246
  pluginID: e,
1247
1247
  connectionID: o,
1248
- opts: { ...f }
1248
+ opts: { ...f },
1249
+ recovery: u
1249
1250
  }
1250
1251
  });
1251
- const p = Sn.createFrom({
1252
+ const g = Sn.createFrom({
1252
1253
  command: ["/bin/bash"],
1253
1254
  tty: !0,
1254
1255
  ...f
1255
1256
  });
1256
1257
  try {
1257
- const h = await Qt(e, o, p);
1258
+ const h = await Qt(e, o, g);
1258
1259
  if (!h) throw new Error("Failed to create session: null response");
1259
- s(
1260
- { id: u },
1260
+ return s(
1261
+ { id: p },
1261
1262
  {
1262
1263
  id: h.id,
1263
1264
  title: c ?? `Session ${h.id.substring(0, 8)}`,
1264
- properties: { status: "connected", pluginID: e, connectionID: o, opts: { ...f } }
1265
+ properties: { status: "connected", pluginID: e, connectionID: o, opts: { ...f }, recovery: u }
1265
1266
  }
1266
- );
1267
+ ), h;
1267
1268
  } catch (h) {
1268
- const g = H(h);
1269
- s(
1270
- { id: u },
1269
+ const y = H(h);
1270
+ return s(
1271
+ { id: p },
1271
1272
  {
1272
- properties: { status: "error", error: g.detail, pluginID: e, connectionID: o, opts: { ...f } }
1273
+ properties: {
1274
+ status: "error",
1275
+ error: y.detail,
1276
+ pluginID: e,
1277
+ connectionID: o,
1278
+ opts: { ...f },
1279
+ recovery: u,
1280
+ errorInfo: { title: y.title || "Session error", suggestion: y.detail, raw: y.detail }
1281
+ }
1273
1282
  }
1274
- ), z(n, h, "Failed to start session");
1283
+ ), z(n, h, "Failed to start session"), null;
1275
1284
  }
1276
1285
  }
1277
1286
  }).mutateAsync
@@ -1285,9 +1294,9 @@ const Is = () => {
1285
1294
  resourceData: f,
1286
1295
  icon: u,
1287
1296
  label: p,
1288
- target: h,
1289
- follow: g = !0,
1290
- tailLines: m = 1e3,
1297
+ target: g,
1298
+ follow: h = !0,
1299
+ tailLines: y = 1e3,
1291
1300
  params: w
1292
1301
  }) => {
1293
1302
  const l = vn.createFrom({
@@ -1295,11 +1304,11 @@ const Is = () => {
1295
1304
  resource_id: c,
1296
1305
  resource_data: f,
1297
1306
  options: Cn.createFrom({
1298
- target: h ?? "",
1299
- follow: g,
1307
+ target: g ?? "",
1308
+ follow: h,
1300
1309
  include_previous: !1,
1301
1310
  include_timestamps: !0,
1302
- tail_lines: m,
1311
+ tail_lines: y,
1303
1312
  since_seconds: 0,
1304
1313
  limit_bytes: 0,
1305
1314
  include_source_events: !0,
@@ -1350,8 +1359,8 @@ const Is = () => {
1350
1359
  enabled: u = !0
1351
1360
  } = t, {
1352
1361
  data: p,
1353
- isLoading: h
1354
- } = Kn(n), g = p ?? [], m = c ? Math.max(
1362
+ isLoading: g
1363
+ } = Kn(n), h = p ?? [], y = c ? Math.max(
1355
1364
  Math.floor((c.end.getTime() - c.start.getTime()) / 250),
1356
1365
  15e3
1357
1366
  ) * 1e6 : 0, w = F({
@@ -1378,13 +1387,13 @@ const Is = () => {
1378
1387
  a,
1379
1388
  ((c == null ? void 0 : c.start) ?? /* @__PURE__ */ new Date(0)).toISOString(),
1380
1389
  ((c == null ? void 0 : c.end) ?? /* @__PURE__ */ new Date(0)).toISOString(),
1381
- m
1382
- ), y = {};
1390
+ y
1391
+ ), m = {};
1383
1392
  for (const [S, b] of Object.entries(E))
1384
- b != null && (y[S] = b);
1385
- return y;
1393
+ b != null && (m[S] = b);
1394
+ return m;
1386
1395
  },
1387
- enabled: u && !!e && !!n && (n.startsWith("cluster::") || !!r) && g.length > 0,
1396
+ enabled: u && !!e && !!n && (n.startsWith("cluster::") || !!r) && h.length > 0,
1388
1397
  refetchInterval: f > 0 ? f : void 0,
1389
1398
  staleTime: 5e3,
1390
1399
  // Keep previous data visible while fetching new data (e.g. on time range change)
@@ -1393,8 +1402,8 @@ const Is = () => {
1393
1402
  });
1394
1403
  return {
1395
1404
  data: w.data ?? void 0,
1396
- providers: g,
1397
- isLoading: h || w.isLoading,
1405
+ providers: h,
1406
+ isLoading: g || w.isLoading,
1398
1407
  error: w.error,
1399
1408
  refetch: w.refetch
1400
1409
  };
@@ -1409,7 +1418,7 @@ const Is = () => {
1409
1418
  metricIDs: a = [],
1410
1419
  interval: c = 1e4,
1411
1420
  enabled: f = !0
1412
- } = t, u = A(e), [p, h] = B(null), [g, m] = B(null), [w, l] = B(!1), [d, E] = B(null), y = W(null), S = M(async () => {
1421
+ } = t, u = A(e), [p, g] = B(null), [h, y] = B(null), [w, l] = B(!1), [d, E] = B(null), m = W(null), S = M(async () => {
1413
1422
  if (!(!f || !u || !n || !r || !s))
1414
1423
  try {
1415
1424
  const v = await Yt(u, n, {
@@ -1421,12 +1430,12 @@ const Is = () => {
1421
1430
  interval: c * 1e6
1422
1431
  // ms to nanoseconds for Go time.Duration
1423
1432
  });
1424
- m(v), l(!0), E(null);
1433
+ y(v), l(!0), E(null);
1425
1434
  const R = D(`core/metrics/data/${v}`, (O) => {
1426
1435
  const k = O.data;
1427
1436
  try {
1428
1437
  const L = JSON.parse(k);
1429
- L.results && h(L.results);
1438
+ L.results && g(L.results);
1430
1439
  } catch (L) {
1431
1440
  console.error("Failed to parse metric stream data:", L);
1432
1441
  }
@@ -1439,26 +1448,26 @@ const Is = () => {
1439
1448
  E("Failed to parse metric stream error");
1440
1449
  }
1441
1450
  });
1442
- y.current = () => {
1451
+ m.current = () => {
1443
1452
  R(), I();
1444
1453
  };
1445
1454
  } catch (v) {
1446
1455
  E(v instanceof Error ? v.message : String(v));
1447
1456
  }
1448
1457
  }, [u, n, r, s, i, a, c, f]), b = M(async () => {
1449
- if (g)
1458
+ if (h)
1450
1459
  try {
1451
- await De(g);
1460
+ await De(h);
1452
1461
  } catch (v) {
1453
1462
  console.error("Failed to unsubscribe:", v);
1454
1463
  }
1455
- y.current && (y.current(), y.current = null), m(null), l(!1);
1456
- }, [g]);
1464
+ m.current && (m.current(), m.current = null), y(null), l(!1);
1465
+ }, [h]);
1457
1466
  return j(() => () => {
1458
- g && De(g).catch(console.error), y.current && y.current();
1459
- }, [g]), {
1467
+ h && De(h).catch(console.error), m.current && m.current();
1468
+ }, [h]), {
1460
1469
  data: p,
1461
- subscriptionID: g,
1470
+ subscriptionID: h,
1462
1471
  isStreaming: w,
1463
1472
  error: d,
1464
1473
  start: S,
@@ -1525,9 +1534,9 @@ function xs({ pluginID: t, connectionID: e, resourceID: n }) {
1525
1534
  },
1526
1535
  labels: u.labels ?? {},
1527
1536
  params: u.parameters ?? {}
1528
- }), h = await Zt(r, e, p);
1529
- if (!h) throw new Error("Failed to start port forwarding: null response");
1530
- return u.openInBrowser && Ze(`http://localhost:${h.local_port}`), h;
1537
+ }), g = await Zt(r, e, p);
1538
+ if (!g) throw new Error("Failed to start port forwarding: null response");
1539
+ return u.openInBrowser && Ze(`http://localhost:${g.local_port}`), g;
1531
1540
  },
1532
1541
  onError: U(i, "Failed to start port forwarding session"),
1533
1542
  onSuccess: async () => {
@@ -1568,8 +1577,8 @@ const Ps = () => {
1568
1577
  namespace: s = ""
1569
1578
  }) => {
1570
1579
  const i = A(t), o = K(), { showSnackbar: a } = Q(), c = _e.resource(i, e, n, r, s), { mutateAsync: f } = x({
1571
- mutationFn: async (h) => Qe(i, e, n, ze.createFrom({
1572
- input: h.input,
1580
+ mutationFn: async (g) => Qe(i, e, n, ze.createFrom({
1581
+ input: g.input,
1573
1582
  id: r,
1574
1583
  namespace: s
1575
1584
  })),
@@ -1578,10 +1587,10 @@ const Ps = () => {
1578
1587
  },
1579
1588
  onError: U(a, `Failed to update resource ${r}`)
1580
1589
  }), { mutateAsync: u } = x({
1581
- mutationFn: async (h = {}) => Be(i, e, n, Ve.createFrom({
1590
+ mutationFn: async (g = {}) => Be(i, e, n, Ve.createFrom({
1582
1591
  id: r,
1583
1592
  namespace: s,
1584
- gracePeriodSeconds: h.gracePeriodSeconds
1593
+ gracePeriodSeconds: g.gracePeriodSeconds
1585
1594
  })),
1586
1595
  onSuccess: async () => {
1587
1596
  a(`Resource ${r} deleted`, "success"), await o.invalidateQueries({ queryKey: c });
@@ -1946,27 +1955,27 @@ function Kr(t, e, n, r, s, i) {
1946
1955
  const o = (i == null ? void 0 : i.syncWindowMs) ?? 500, a = W([]), c = W(null), f = W(null), u = W(s);
1947
1956
  u.current = s;
1948
1957
  const p = M(() => {
1949
- const g = a.current;
1950
- if (a.current = [], c.current !== null && (clearTimeout(c.current), c.current = null), f.current !== null && (cancelAnimationFrame(f.current), f.current = null), !(g.length === 0 || !r)) {
1958
+ const h = a.current;
1959
+ if (a.current = [], c.current !== null && (clearTimeout(c.current), c.current = null), f.current !== null && (cancelAnimationFrame(f.current), f.current = null), !(h.length === 0 || !r)) {
1951
1960
  t.setQueryData(
1952
1961
  e,
1953
- (m) => Hr(m, g, r)
1962
+ (y) => Hr(y, h, r)
1954
1963
  );
1955
- for (const m of g)
1956
- (m.type === "ADD" || m.type === "UPDATE") && t.setQueryData(
1957
- n(m.payload.id, m.payload.namespace),
1958
- { success: !0, result: m.payload.data }
1964
+ for (const y of h)
1965
+ (y.type === "ADD" || y.type === "UPDATE") && t.setQueryData(
1966
+ n(y.payload.id, y.payload.namespace),
1967
+ { success: !0, result: y.payload.data }
1959
1968
  );
1960
1969
  }
1961
- }, [t, e, n, r]), h = M(
1962
- (g) => {
1963
- a.current.push(g), !(c.current !== null || f.current !== null) && (c.current = setTimeout(p, o), u.current !== 1 && (f.current = requestAnimationFrame(p)));
1970
+ }, [t, e, n, r]), g = M(
1971
+ (h) => {
1972
+ a.current.push(h), !(c.current !== null || f.current !== null) && (c.current = setTimeout(p, o), u.current !== 1 && (f.current = requestAnimationFrame(p)));
1964
1973
  },
1965
1974
  [p, o]
1966
1975
  );
1967
1976
  return j(() => () => {
1968
1977
  c.current !== null && (clearTimeout(c.current), c.current = null), f.current !== null && (cancelAnimationFrame(f.current), f.current = null);
1969
- }, []), h;
1978
+ }, []), g;
1970
1979
  }
1971
1980
  const Ws = ({
1972
1981
  pluginID: t,
@@ -1991,11 +2000,11 @@ const Ws = ({
1991
2000
  const d = l == null ? void 0 : l.result;
1992
2001
  let E = "";
1993
2002
  (S = d == null ? void 0 : d.metadata) != null && S.name ? E = d.metadata.name : d != null && d.id ? E = d.id : d != null && d.name ? E = d.name : d != null && d.ID ? E = d.ID : d != null && d.Name && (E = d.Name);
1994
- const y = E ? `Resource ${E} created` : "Resource created";
1995
- a(y, "success"), await o.invalidateQueries({ queryKey: f });
2003
+ const m = E ? `Resource ${E} created` : "Resource created";
2004
+ a(m, "success"), await o.invalidateQueries({ queryKey: f });
1996
2005
  },
1997
2006
  onError: U(a, "Failed to create resource")
1998
- }), h = F({
2007
+ }), g = F({
1999
2008
  queryKey: f,
2000
2009
  queryFn: async () => He(i, e, n, Ye.createFrom({
2001
2010
  order: [{ field: "name", descending: !1 }],
@@ -2004,30 +2013,30 @@ const Ws = ({
2004
2013
  })),
2005
2014
  placeholderData: (l, d) => l,
2006
2015
  retry: !1
2007
- }), [g, m] = C.useState(
2016
+ }), [h, y] = C.useState(
2008
2017
  T.WatchStateIdle
2009
2018
  );
2010
2019
  C.useEffect(() => D(
2011
2020
  `${i}/${e}/watch/STATE`,
2012
2021
  (d) => {
2013
2022
  const E = d.data;
2014
- E.resourceKey === n && m(E.state);
2023
+ E.resourceKey === n && y(E.state);
2015
2024
  }
2016
2025
  ), [i, e, n]);
2017
- const w = Kr(o, f, u, r, g);
2026
+ const w = Kr(o, f, u, r, h);
2018
2027
  return C.useEffect(() => {
2019
2028
  if (!r)
2020
2029
  return;
2021
2030
  on(i, e, n);
2022
2031
  const l = D(
2023
2032
  `${i}/${e}/${n}/ADD`,
2024
- (y) => w({ type: "ADD", payload: y.data })
2033
+ (m) => w({ type: "ADD", payload: m.data })
2025
2034
  ), d = D(
2026
2035
  `${i}/${e}/${n}/UPDATE`,
2027
- (y) => w({ type: "UPDATE", payload: y.data })
2036
+ (m) => w({ type: "UPDATE", payload: m.data })
2028
2037
  ), E = D(
2029
2038
  `${i}/${e}/${n}/DELETE`,
2030
- (y) => w({ type: "DELETE", payload: y.data })
2039
+ (m) => w({ type: "DELETE", payload: m.data })
2031
2040
  );
2032
2041
  return () => {
2033
2042
  l(), d(), E(), an(i, e, n);
@@ -2038,7 +2047,7 @@ const Ws = ({
2038
2047
  * when the resources are updated or deleted via the returned create and remove mutation functions, or
2039
2048
  * the per-resource hook mutation functions.
2040
2049
  */
2041
- resources: h,
2050
+ resources: g,
2042
2051
  /**
2043
2052
  * Create a new resource. A set of optional parameters can be passed to customize the create behavior,
2044
2053
  * which if specified, will add additional default behavior set via the hook options.
@@ -2047,13 +2056,13 @@ const Ws = ({
2047
2056
  */
2048
2057
  create: p,
2049
2058
  /** Current watch state for this resource type */
2050
- watchState: g,
2059
+ watchState: h,
2051
2060
  /** Whether the watch is currently syncing */
2052
- isSyncing: g === T.WatchStateSyncing,
2061
+ isSyncing: h === T.WatchStateSyncing,
2053
2062
  /** Whether the watch has fully synced */
2054
- isSynced: g === T.WatchStateSynced,
2063
+ isSynced: h === T.WatchStateSynced,
2055
2064
  /** Whether the watch encountered an error */
2056
- watchError: g === T.WatchStateError
2065
+ watchError: h === T.WatchStateError
2057
2066
  };
2058
2067
  }, Gs = ({ pluginID: t }) => {
2059
2068
  const e = A(t), { showSnackbar: n } = Q(), r = x({
@@ -2181,78 +2190,78 @@ const Ws = ({
2181
2190
  connectionID: e,
2182
2191
  enabled: n = !0
2183
2192
  }) => {
2184
- const r = A(t), s = K(), i = [r, e, "watch-state"], o = W([]), a = W(!1), c = M((h) => {
2185
- s.setQueryData(i, (g) => {
2186
- if (!g) return g;
2187
- const m = { ...g.resources, [h.resourceKey]: h.state }, w = { ...g.resourceCounts, [h.resourceKey]: h.resourceCount };
2193
+ const r = A(t), s = K(), i = [r, e, "watch-state"], o = W([]), a = W(!1), c = M((g) => {
2194
+ s.setQueryData(i, (h) => {
2195
+ if (!h) return h;
2196
+ const y = { ...h.resources, [g.resourceKey]: g.state }, w = { ...h.resourceCounts, [g.resourceKey]: g.resourceCount };
2188
2197
  let l = 0, d = 0;
2189
- for (const E of Object.values(m))
2198
+ for (const E of Object.values(y))
2190
2199
  E === T.WatchStateSynced && l++, (E === T.WatchStateError || E === T.WatchStateFailed) && d++;
2191
- return { ...g, resources: m, resourceCounts: w, totalResources: Object.keys(m).length, syncedCount: l, errorCount: d };
2200
+ return { ...h, resources: y, resourceCounts: w, totalResources: Object.keys(y).length, syncedCount: l, errorCount: d };
2192
2201
  });
2193
2202
  }, [s, r, e]), f = F({
2194
2203
  queryKey: i,
2195
2204
  queryFn: async () => {
2196
- const h = await dn(r, e);
2197
- if (!h) throw new Error("Failed to get watch state: null response");
2198
- const g = {};
2199
- let m = 0, w = 0;
2200
- for (const [d, E] of Object.entries(h.resources ?? {}))
2201
- E != null && (g[d] = E, E === T.WatchStateSynced && m++, E === T.WatchStateError && w++);
2205
+ const g = await dn(r, e);
2206
+ if (!g) throw new Error("Failed to get watch state: null response");
2207
+ const h = {};
2208
+ let y = 0, w = 0;
2209
+ for (const [d, E] of Object.entries(g.resources ?? {}))
2210
+ E != null && (h[d] = E, E === T.WatchStateSynced && y++, E === T.WatchStateError && w++);
2202
2211
  const l = {};
2203
- for (const [d, E] of Object.entries(h.resourceCounts ?? {}))
2212
+ for (const [d, E] of Object.entries(g.resourceCounts ?? {}))
2204
2213
  E != null && (l[d] = E);
2205
2214
  return {
2206
- connection: h.connectionId,
2207
- resources: g,
2215
+ connection: g.connectionId,
2216
+ resources: h,
2208
2217
  resourceCounts: l,
2209
- totalResources: Object.keys(g).length,
2210
- syncedCount: m,
2218
+ totalResources: Object.keys(h).length,
2219
+ syncedCount: y,
2211
2220
  errorCount: w
2212
2221
  };
2213
2222
  },
2214
2223
  enabled: n && !!r && !!e,
2215
- refetchInterval: (h) => {
2216
- const g = h.state.data;
2217
- if (!g || g.totalResources === 0) return 3e3;
2218
- let m = 0;
2219
- for (const w of Object.values(g.resources))
2220
- (w === T.WatchStateSynced || w === T.WatchStateError || w === T.WatchStateStopped || w === T.WatchStateFailed || w === T.WatchStateForbidden || w === T.WatchStateSkipped) && m++;
2221
- return m >= g.totalResources ? !1 : 3e3;
2224
+ refetchInterval: (g) => {
2225
+ const h = g.state.data;
2226
+ if (!h || h.totalResources === 0) return 3e3;
2227
+ let y = 0;
2228
+ for (const w of Object.values(h.resources))
2229
+ (w === T.WatchStateSynced || w === T.WatchStateError || w === T.WatchStateStopped || w === T.WatchStateFailed || w === T.WatchStateForbidden || w === T.WatchStateSkipped) && y++;
2230
+ return y >= h.totalResources ? !1 : 3e3;
2222
2231
  }
2223
2232
  });
2224
2233
  j(() => {
2225
2234
  if (!f.data || a.current) return;
2226
2235
  a.current = !0;
2227
- const h = o.current;
2236
+ const g = o.current;
2228
2237
  o.current = [];
2229
- for (const g of h)
2230
- c(g);
2238
+ for (const h of g)
2239
+ c(h);
2231
2240
  }, [f.data, c]), j(() => {
2232
2241
  if (!n || !r || !e)
2233
2242
  return;
2234
2243
  a.current = !1, o.current = [];
2235
- const h = D(
2244
+ const g = D(
2236
2245
  `${r}/${e}/watch/STATE`,
2237
- (g) => {
2238
- const m = g.data;
2239
- a.current ? c(m) : o.current.push(m);
2246
+ (h) => {
2247
+ const y = h.data;
2248
+ a.current ? c(y) : o.current.push(y);
2240
2249
  }
2241
2250
  );
2242
2251
  return () => {
2243
- h(), a.current = !1, o.current = [];
2252
+ g(), a.current = !1, o.current = [];
2244
2253
  };
2245
2254
  }, [r, e, n, c]);
2246
2255
  const u = f.data;
2247
2256
  let p = 0;
2248
2257
  if (u != null && u.resources)
2249
- for (const h of Object.values(u.resources))
2250
- (h === T.WatchStateSynced || h === T.WatchStateError || h === T.WatchStateStopped || h === T.WatchStateFailed || h === T.WatchStateForbidden || h === T.WatchStateSkipped) && p++;
2258
+ for (const g of Object.values(u.resources))
2259
+ (g === T.WatchStateSynced || g === T.WatchStateError || g === T.WatchStateStopped || g === T.WatchStateFailed || g === T.WatchStateForbidden || g === T.WatchStateSkipped) && p++;
2251
2260
  return {
2252
2261
  /** Full summary query result */
2253
2262
  summary: f,
2254
2263
  /** Get the state of a specific resource type's watch */
2255
- getResourceState: (h) => u == null ? void 0 : u.resources[h],
2264
+ getResourceState: (g) => u == null ? void 0 : u.resources[g],
2256
2265
  /** Whether all registered watches have reached a terminal state */
2257
2266
  isFullySynced: u ? u.totalResources > 0 && p === u.totalResources : !1,
2258
2267
  /** Sync progress as a 0-1 fraction (terminal states / total) */
@@ -2262,18 +2271,18 @@ const Ws = ({
2262
2271
  };
2263
2272
  }, Ks = () => {
2264
2273
  const [t, e] = B(/* @__PURE__ */ new Map()), n = W(/* @__PURE__ */ new Map()), r = W(/* @__PURE__ */ new Map()), s = M((f) => {
2265
- const u = f.data, p = Re(u), h = ut(n.current, u), g = Ce(h);
2266
- if (e((m) => {
2267
- const w = new Map(m);
2268
- return w.set(p, g), w;
2269
- }), r.current.has(p) && (clearTimeout(r.current.get(p)), r.current.delete(p)), ce(g)) {
2270
- const m = setTimeout(() => {
2274
+ const u = f.data, p = Re(u), g = ut(n.current, u), h = Ce(g);
2275
+ if (e((y) => {
2276
+ const w = new Map(y);
2277
+ return w.set(p, h), w;
2278
+ }), r.current.has(p) && (clearTimeout(r.current.get(p)), r.current.delete(p)), ce(h)) {
2279
+ const y = setTimeout(() => {
2271
2280
  e((w) => {
2272
2281
  const l = new Map(w);
2273
2282
  return l.delete(p), l;
2274
2283
  }), n.current.delete(p), r.current.delete(p);
2275
2284
  }, 5e3);
2276
- r.current.set(p, m);
2285
+ r.current.set(p, y);
2277
2286
  }
2278
2287
  }, []);
2279
2288
  j(() => {
@@ -2300,24 +2309,24 @@ const Ws = ({
2300
2309
  if (!t) throw new Error("useOperations must be used within an OperationsProvider");
2301
2310
  return t;
2302
2311
  }, zs = ({ pluginID: t, connectionID: e, resourceKey: n }) => {
2303
- const r = A(t), { showSnackbar: s } = Q(), { addOperation: i, updateOperation: o } = zr(), a = C.useRef(/* @__PURE__ */ new Set()), c = C.useCallback((p, h = !1) => {
2304
- var g, m, w;
2305
- p.disposed || (p.disposed = !0, (g = p.unsubscribe) == null || g.call(p), (m = p.open) == null || m.cancel(), (w = p.attach) == null || w.cancel(), p.handle && (Fe(p.handle).catch(() => {
2306
- }), h && o(p.handle, { status: "cancelled", message: "Cancelled", completedAt: Date.now() })), a.current.delete(p));
2312
+ const r = A(t), { showSnackbar: s } = Q(), { addOperation: i, updateOperation: o } = zr(), a = C.useRef(/* @__PURE__ */ new Set()), c = C.useCallback((p, g = !1) => {
2313
+ var h, y, w;
2314
+ p.disposed || (p.disposed = !0, (h = p.unsubscribe) == null || h.call(p), (y = p.open) == null || y.cancel(), (w = p.attach) == null || w.cancel(), p.handle && (Fe(p.handle).catch(() => {
2315
+ }), g && o(p.handle, { status: "cancelled", message: "Cancelled", completedAt: Date.now() })), a.current.delete(p));
2307
2316
  }, [o]);
2308
2317
  C.useEffect(() => () => {
2309
2318
  for (const p of a.current) c(p, !0);
2310
2319
  }, [r, e, n, c]);
2311
- const f = C.useCallback(async ({ actionID: p, id: h, namespace: g, label: m, params: w = {} }) => {
2320
+ const f = C.useCallback(async ({ actionID: p, id: g, namespace: h, label: y, params: w = {} }) => {
2312
2321
  const l = { disposed: !1, terminal: !1, sequence: 0 };
2313
2322
  a.current.add(l);
2314
2323
  try {
2315
- l.open = fn(r, e, n, p, Xe.createFrom({ id: h, namespace: g, params: w }));
2324
+ l.open = fn(r, e, n, p, Xe.createFrom({ id: g, namespace: h, params: w }));
2316
2325
  const d = await l.open;
2317
2326
  if (l.open = void 0, l.disposed)
2318
2327
  return Fe(d).catch(() => {
2319
2328
  }), d;
2320
- l.handle = d, i({ id: d, label: m, resourceKey: n, resourceName: h, namespace: g, connectionID: e, status: "running", startedAt: Date.now() });
2329
+ l.handle = d, i({ id: d, label: y, resourceKey: n, resourceName: g, namespace: h, connectionID: e, status: "running", startedAt: Date.now() });
2321
2330
  const E = (S) => {
2322
2331
  if (l.disposed || !Number.isSafeInteger(S.sequence) || S.sequence <= l.sequence) return;
2323
2332
  l.sequence = S.sequence;
@@ -2325,10 +2334,10 @@ const Ws = ({
2325
2334
  if (b.type === "error") {
2326
2335
  l.terminal = !0;
2327
2336
  const R = H(b.error);
2328
- o(d, { status: ae(R) ? "cancelled" : "error", message: R.title, completedAt: Date.now() }), z(s, R, m), c(l);
2337
+ o(d, { status: ae(R) ? "cancelled" : "error", message: R.title, completedAt: Date.now() }), z(s, R, y), c(l);
2329
2338
  } else if (b.type === "complete") {
2330
2339
  l.terminal = !0;
2331
- const R = typeof v.message == "string" ? v.message : `${m} completed`;
2340
+ const R = typeof v.message == "string" ? v.message : `${y} completed`;
2332
2341
  o(d, { status: "completed", message: R, completedAt: Date.now() }), s(R, "success"), c(l);
2333
2342
  } else
2334
2343
  o(d, {
@@ -2337,15 +2346,15 @@ const Ws = ({
2337
2346
  });
2338
2347
  };
2339
2348
  l.unsubscribe = D(`action/stream/${d}`, (S) => E(S.data)), l.attach = pn(d);
2340
- const y = await l.attach;
2341
- return l.attach = void 0, E(y), d;
2349
+ const m = await l.attach;
2350
+ return l.attach = void 0, E(m), d;
2342
2351
  } catch (d) {
2343
2352
  if (l.terminal && l.handle) return l.handle;
2344
2353
  throw l.disposed || (l.handle && o(l.handle, { status: ae(d) ? "cancelled" : "error", message: H(d).title, completedAt: Date.now() }), z(s, d, `Failed to start "${p}"`)), c(l), d;
2345
2354
  }
2346
2355
  }, [r, e, n, i, o, s, c]), u = C.useCallback((p) => {
2347
- for (const h of a.current) if (h.handle === p) {
2348
- c(h, !0);
2356
+ for (const g of a.current) if (g.handle === p) {
2357
+ c(g, !0);
2349
2358
  return;
2350
2359
  }
2351
2360
  }, [c]);
@@ -2412,27 +2421,27 @@ const Ys = ({
2412
2421
  }) => {
2413
2422
  const f = A(t), u = ["RESOURCE_RELATED", f, e, n, s, r, i, o ?? null], p = a && !!f && !!e && !!n && !!r;
2414
2423
  Ne(f, e, u, p);
2415
- const h = F({
2424
+ const g = F({
2416
2425
  queryKey: u,
2417
2426
  queryFn: async () => hn(f, e, n, s, r, i, o ?? null),
2418
2427
  enabled: p,
2419
2428
  refetchInterval: c
2420
- }), g = {
2429
+ }), h = {
2421
2430
  pluginId: f,
2422
2431
  connectionId: e,
2423
2432
  resourceKey: n,
2424
2433
  id: r,
2425
2434
  namespace: s
2426
- }, m = h.data ?? [];
2435
+ }, y = g.data ?? [];
2427
2436
  return {
2428
2437
  /** One entry per edge, from the viewed resource's side. */
2429
- related: Xr(g, m),
2438
+ related: Xr(h, y),
2430
2439
  /** The raw graph edges. */
2431
- edges: m,
2432
- isLoading: h.isLoading,
2433
- isFetching: h.isFetching,
2434
- error: h.error,
2435
- refetch: h.refetch
2440
+ edges: y,
2441
+ isLoading: g.isLoading,
2442
+ isFetching: g.isFetching,
2443
+ error: g.error,
2444
+ refetch: g.refetch
2436
2445
  };
2437
2446
  }, Js = ({
2438
2447
  pluginID: t,
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "author": "Omniview",
3
3
  "license": "AGPL-3.0-only",
4
4
  "name": "@omniviewdev/runtime",
5
- "version": "0.8.0",
5
+ "version": "0.8.2",
6
6
  "description": "Runtime shared library for Omniview",
7
7
  "sideEffects": false,
8
8
  "type": "module",