@omniviewdev/runtime 0.4.0 → 0.4.1

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.
@@ -0,0 +1,41 @@
1
+ type UseDependencyTreeOptions = {
2
+ /**
3
+ * The ID of the plugin responsible for this resource
4
+ * @example "kubernetes"
5
+ */
6
+ pluginID?: string;
7
+ /** The connection ID the resource belongs to */
8
+ connectionID: string;
9
+ /**
10
+ * The resource key of the root resource
11
+ * @example "apps::v1::Deployment"
12
+ */
13
+ resourceKey: string;
14
+ /** The ID of the root resource */
15
+ resourceID: string;
16
+ /** Namespace of the root resource, if the backend has namespaces */
17
+ namespace?: string;
18
+ /** How many edges deep to follow. The host caps this at 5. */
19
+ maxDepth?: number;
20
+ /** Whether to enable the query */
21
+ enabled?: boolean;
22
+ /**
23
+ * How often to refetch, in milliseconds. The graph does not notify the
24
+ * frontend of changes, so it is polled. Pass false to disable.
25
+ */
26
+ refetchInterval?: number | false;
27
+ };
28
+ /**
29
+ * useDependencyTree returns the tree of resources reachable from one resource
30
+ * by following outgoing relationship edges (for example Deployment →
31
+ * ReplicaSet → Pods → Node, ConfigMaps, PVCs). A resource reachable by more
32
+ * than one path appears once.
33
+ */
34
+ export declare const useDependencyTree: ({ pluginID: explicitPluginID, connectionID, resourceKey, resourceID, namespace, maxDepth, enabled, refetchInterval, }: UseDependencyTreeOptions) => {
35
+ tree: import('../../models').DependencyTree | null;
36
+ isLoading: boolean;
37
+ isFetching: boolean;
38
+ error: Error | null;
39
+ refetch: (options?: import('@tanstack/react-query').RefetchOptions) => Promise<import('@tanstack/react-query').QueryObserverResult<import('../../models').DependencyTree | null, Error>>;
40
+ };
41
+ export default useDependencyTree;
@@ -0,0 +1,82 @@
1
+ import { GraphEdge, GraphNode } from '../../bindings/github.com/omniviewdev/omniview/backend/pkg/plugin/resource/graph/models';
2
+ /** Which side of the relationship the viewed resource is on. */
3
+ export type RelationshipDirection = 'outgoing' | 'incoming';
4
+ /** A resource linked to the viewed resource by one relationship edge. */
5
+ export type RelatedResource = {
6
+ /** The resource at the other end of the edge. */
7
+ resource: GraphNode;
8
+ /** Relationship type, e.g. "owns", "runs_on", "uses", "selects". */
9
+ type: string;
10
+ /**
11
+ * "outgoing" when the viewed resource is the edge source (a Pod that runs
12
+ * on a Node), "incoming" when it is the target (the Node).
13
+ */
14
+ direction: RelationshipDirection;
15
+ /**
16
+ * The label the plugin declared. It is written from the declaring
17
+ * resource's point of view, so it can read backwards here (an owner edge
18
+ * declared by a Pod is labelled "owned by"). Use relationshipLabel() for
19
+ * display.
20
+ */
21
+ label: string;
22
+ };
23
+ type UseRelatedResourcesOptions = {
24
+ /**
25
+ * The ID of the plugin responsible for this resource
26
+ * @example "kubernetes"
27
+ */
28
+ pluginID?: string;
29
+ /** The connection ID the resource belongs to */
30
+ connectionID: string;
31
+ /**
32
+ * The resource key of the viewed resource
33
+ * @example "core::v1::Pod"
34
+ */
35
+ resourceKey: string;
36
+ /** The ID of the viewed resource */
37
+ resourceID: string;
38
+ /** Namespace of the viewed resource, if the backend has namespaces */
39
+ namespace?: string;
40
+ /** Which edges to return. Defaults to both directions. */
41
+ direction?: RelationshipDirection | 'both';
42
+ /** Only return edges of this relationship type */
43
+ relationshipType?: string;
44
+ /** Whether to enable the query */
45
+ enabled?: boolean;
46
+ /**
47
+ * How often to refetch, in milliseconds. The graph is rebuilt in the
48
+ * background from watch events and does not notify the frontend, so it is
49
+ * polled. Pass false to disable.
50
+ */
51
+ refetchInterval?: number | false;
52
+ };
53
+ /**
54
+ * relationshipLabel returns a display label for a relationship type, read
55
+ * from the viewed resource's side: ("owns", "incoming") is "Owned by".
56
+ * Unknown types fall back to the type name.
57
+ */
58
+ export declare function relationshipLabel(type: string, direction: RelationshipDirection): string;
59
+ /**
60
+ * toRelatedResources converts graph edges around `self` into one entry per
61
+ * edge, keyed by the resource at the other end.
62
+ */
63
+ export declare function toRelatedResources(self: GraphNode, edges: GraphEdge[]): RelatedResource[];
64
+ /**
65
+ * useRelatedResources returns the resources linked to one resource in the
66
+ * relationship graph the host builds from the plugin's relationship
67
+ * declarations (owner references, node assignment, volumes, selectors, ...).
68
+ *
69
+ * Only resources the host is watching are indexed. Targets referenced by
70
+ * name (a Secret a Pod mounts) are returned even if they do not exist.
71
+ */
72
+ export declare const useRelatedResources: ({ pluginID: explicitPluginID, connectionID, resourceKey, resourceID, namespace, direction, relationshipType, enabled, refetchInterval, }: UseRelatedResourcesOptions) => {
73
+ /** One entry per edge, from the viewed resource's side. */
74
+ related: RelatedResource[];
75
+ /** The raw graph edges. */
76
+ edges: GraphEdge[];
77
+ isLoading: boolean;
78
+ isFetching: boolean;
79
+ error: Error | null;
80
+ refetch: (options?: import('@tanstack/react-query').RefetchOptions) => Promise<import('@tanstack/react-query').QueryObserverResult<GraphEdge[], Error>>;
81
+ };
82
+ export default useRelatedResources;
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Ze=Object.defineProperty;var Xe=(t,e,n)=>e in t?Ze(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var M=(t,e,n)=>Xe(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O=require("react/jsx-runtime"),l=require("react"),B=require("react-router-dom"),g=require("./servicewrapper-dDhyC68C.cjs"),A=require("./models-DdAWPDgz.cjs"),S=require("@tanstack/react-query"),Ve=require("@omniviewdev/base-ui");require("./index-D_aIcqH0.cjs");const D=require("./events-BTiuwc-0.cjs"),et=require("./legacyEnum-DkV5yRdA.cjs"),X=l.createContext(void 0),U={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",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",CONNECTION_NOT_FOUND:"omniview:connection/not-found",CONNECTION_FAILED:"omniview:connection/failed",RESOURCE_CONNECTION_ERROR:"omniview:resource/connection-error",RESOURCE_CERTIFICATE_ERROR:"omniview:resource/certificate-error",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"};function tt(t){switch(t){case"NOT_FOUND":return{typeUri:U.RESOURCE_NOT_FOUND,status:404};case"FORBIDDEN":return{typeUri:U.RESOURCE_FORBIDDEN,status:403};case"UNAUTHORIZED":return{typeUri:U.RESOURCE_UNAUTHORIZED,status:401};case"CONFLICT":case"ALREADY_EXISTS":return{typeUri:U.RESOURCE_CONFLICT,status:409};case"TIMEOUT":return{typeUri:U.RESOURCE_TIMEOUT,status:408};case"CONNECTION_ERROR":return{typeUri:U.RESOURCE_CONNECTION_ERROR,status:503};case"CERTIFICATE_ERROR":return{typeUri:U.RESOURCE_CERTIFICATE_ERROR,status:502};default:return{typeUri:U.INTERNAL,status:500}}}function q(t){if(t==null)return{type:U.INTERNAL,title:"Unknown error",status:500,detail:"An unknown error occurred."};let e;if(typeof t=="string"?e=t:t instanceof Error?e=t.message:e=String(t),e.startsWith("{"))try{const n=JSON.parse(e);if(typeof n.type=="string"&&typeof n.title=="string"&&typeof n.status=="number"&&typeof n.detail=="string")return n;if(typeof n.code=="string"&&typeof n.title=="string"&&typeof n.message=="string"){const{typeUri:r,status:s}=tt(n.code);return{type:r,title:n.title,status:s,detail:n.message,suggestions:Array.isArray(n.suggestions)?n.suggestions:void 0}}}catch{}return{type:U.INTERNAL,title:"Error",status:500,detail:e}}function ue(t){return t==null?!1:(typeof t=="string"?t:t instanceof Error?t.message:String(t))==="cancelled"?!0:q(t).type===U.CANCELLED}function ve(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 be(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(ve)}}function Q(t,e,n){if(ue(e))return;const r=q(e);t(be(r,n))}function N(t,e){return n=>{if(ue(n))return;const r=q(n);t(be(r,r.title!=="Error"?r.title:e))}}function nt(t){const{children:e,pluginId:n}=t,[r,s]=l.useState({}),[i,o]=l.useState(new A.PluginMeta),[a,c]=l.useState(!1),[d,u]=l.useState(null);console.debug("[PluginContextProvider] render",{pluginId:n,metaLoaded:a,metaError:!!d});const h=()=>{n===void 0||n===""||(console.debug(`[PluginContextProvider] fetching settings for "${n}"`),g.PluginValues(n).then(f=>{console.debug(`[PluginContextProvider] settings loaded for "${n}"`,Object.keys(f)),s(f)}).catch(f=>{const y=q(f);console.error(`[PluginContextProvider] error fetching settings for "${n}":`,y.detail)}))},p=()=>{if(n===void 0||n===""){console.debug("[PluginContextProvider] skipping meta fetch — empty pluginId");return}console.debug(`[PluginContextProvider] fetching meta for "${n}"`),u(null),g.GetPluginMeta(n).then(f=>{console.debug(`[PluginContextProvider] meta loaded for "${n}"`,{name:f==null?void 0:f.name,version:f==null?void 0:f.version}),o(f),c(!0)}).catch(f=>{const y=q(f);console.error(`[PluginContextProvider] error fetching meta for "${n}":`,y.detail),u(y.detail),c(!1)})};return l.useEffect(()=>{console.debug(`[PluginContextProvider] useEffect — pluginId changed to "${n}"`),h(),p()},[n]),d?O.jsx("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center",padding:24},children:O.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:[O.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12},children:[O.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"#EF4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[O.jsx("circle",{cx:"12",cy:"12",r:"10"}),O.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),O.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),O.jsx("span",{style:{fontSize:14,fontWeight:600,color:"#FECACA"},children:"Plugin failed to load"})]}),O.jsx("p",{style:{fontSize:13,color:"#A1A1AA",margin:"0 0 16px"},children:d}),O.jsx("button",{onClick:()=>p(),style:{background:"transparent",color:"#F87171",border:"1px solid #7F1D1D",borderRadius:6,padding:"6px 14px",fontSize:13,fontWeight:500,cursor:"pointer"},children:"Retry"})]})}):a?O.jsx(X.Provider,{value:{pluginId:n,settings:r,meta:i},children:e}):O.jsxs("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center"},children:[O.jsx("div",{style:{width:24,height:24,border:"2px solid #3F3F46",borderTopColor:"#A1A1AA",borderRadius:"50%",animation:"plugin-spin 0.8s linear infinite"}}),O.jsx("style",{children:"@keyframes plugin-spin { to { transform: rotate(360deg); } }"})]})}function V(){const t=l.useContext(X);if(!t)throw new Error("usePluginContext must be used within a PluginContextProvider");return t}function rt(){return V().settings}const le=l.createContext(void 0),st=({children:t})=>{const[e,n]=l.useState({}),r=()=>{g.Values().then(i=>{console.log("Fetched settings:",i),n(i)}).catch(i=>{console.error("Error fetching settings:",i)})};l.useEffect(()=>{r()},[]);const s=()=>{r()};return O.jsx(le.Provider,{value:{settings:e,reload:s},children:t})},Re={height:32,focused:0,tabs:[],createTab:()=>{},createTabs:()=>{},updateTab:()=>{},focusTab:()=>{},reorderTab:()=>{},closeTab:()=>{},closeTabs:()=>{},resizeDrawer:()=>{},closeDrawer:()=>{},fullscreenDrawer:()=>{}},xe=l.createContext(Re),Pe=l.createContext(void 0),Ie=l.createContext(void 0),de=l.createContext(void 0),ot=3e4,it=({children:t})=>{const[e,n]=l.useState([]),r=l.useCallback(a=>{n(c=>[a,...c])},[]),s=l.useCallback((a,c)=>{n(d=>d.map(u=>u.id===a?{...u,...c}:u))},[]),i=l.useCallback(a=>{n(c=>c.filter(d=>d.id!==a))},[]);l.useEffect(()=>{const a=[];for(const c of e)if(c.status==="completed"||c.status==="error"){const d=Date.now()-(c.completedAt??c.startedAt),u=Math.max(0,ot-d);a.push(setTimeout(()=>i(c.id),u))}return()=>a.forEach(clearTimeout)},[e,i]);const o=l.useMemo(()=>({operations:e,addOperation:r,updateOperation:s,removeOperation:i}),[e,r,s,i]);return O.jsx(de.Provider,{value:o,children:t})};var ie=function(t,e){return ie=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])},ie(t,e)};function at(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ie(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var re="Invariant Violation",Se=Object.setPrototypeOf,ct=Se===void 0?function(t,e){return t.__proto__=e,t}:Se,ut=function(t){at(e,t);function e(n){n===void 0&&(n=re);var r=t.call(this,typeof n=="number"?re+": "+n+" (see https://github.com/apollographql/invariant-packages)":n)||this;return r.framesToPop=1,r.name=re,ct(r,e.prototype),r}return e}(Error);function ae(t,e){if(!t)throw new ut(e)}var Fe=["debug","log","warn","error","silent"],lt=Fe.indexOf("log");function z(t){return function(){if(Fe.indexOf(t)>=lt){var e=console[t]||console.log;return e.apply(console,arguments)}}}(function(t){t.debug=z("debug"),t.log=z("log"),t.warn=z("warn"),t.error=z("error")})(ae||(ae={}));const Oe=l.createContext(void 0),De=()=>l.useContext(Oe);function dt(t){const e=De(),n=l.useRef(null),r=e==null?void 0:e.getExtensionPoint(t),s=l.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=l.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 d={};return n.current={store:void 0,version:-1,sentinel:d},d}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 l.useSyncExternalStore(s,i),e==null?void 0:e.getExtensionPoint(t)}const ft=({registry:t,children:e})=>{const n=l.useRef(t);return ae(n.current===t,"You can't change the extension registry after it has been rendered"),O.jsx(Oe.Provider,{value:n.current,children:e})},se=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 Te{constructor(e){M(this,"id");M(this,"mode");M(this,"_pluginId");M(this,"_version",0);M(this,"_contributions",new Map);M(this,"_lookupCache",new Map);M(this,"_matcher");M(this,"_select");M(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 pt{constructor(e){M(this,"_stores",new Map);M(this,"_storeUnsubs",new Map);M(this,"_listeners",new Set);if(e!=null&&e.initialStores)for(const n of e.initialStores)this.addExtensionPoint(n)}addExtensionPoint(e){const n=se(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 Te({...e,id:n});this._stores.set(n,r),this._storeUnsubs.set(n,r.subscribe(()=>this._notify())),this._notify()}getExtensionPoint(e){const n=se(e);return this._stores.get(n)}hasExtensionPoint(e){const n=se(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 Ae=l.createContext(void 0),yt={default:"info",info:"info",success:"success",warning:"warning",error:"danger"},ht=({children:t})=>{const{toast:e}=Ve.useToast(),[n,r]=l.useState([]),s=o=>{r(a=>[...a,o])},i=(o,a,c)=>{const d=typeof o=="object";let u="",h="info",p,f=5e3,y;if(d){if(u=o.message,o.showOnce){if(n.includes(u))return;s(u)}h=o.status,p=o.details,f=o.autoHideDuration??5e3,y=o.actions}else u=o,h=a,p=c;e(p??u,{severity:yt[h]??"info",title:p?u:void 0,duration:f,action:y==null?void 0:y[0]})};return O.jsx(Ae.Provider,{value:{showSnackbar:i},children:t})},$=()=>{const t=l.useContext(Ae);if(t===void 0)throw new Error("useCustomSnackbar must be used within a CustomSnackbarProvider");return t};function T(t){const e=l.useContext(X),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 gt=({pluginID:t,connectionID:e})=>{const n=T(t),r=S.useQueryClient(),{showSnackbar:s}=$(),i=[n,"connection","detail",e],{mutateAsync:o}=S.useMutation({mutationFn:async()=>g.StartConnection(n,e),onSuccess(h){r.setQueryData(i,h),r.invalidateQueries({queryKey:["EDITOR_SCHEMAS",n,e]})},onError:N(s,"Failed to start connection")}),{mutateAsync:a}=S.useMutation({mutationFn:async()=>g.StopConnection(n,e),onSuccess(h){r.setQueryData(i,h)},onError:N(s,"Failed to stop connection")}),{mutateAsync:c}=S.useMutation({mutationFn:async h=>g.UpdateConnection(n,h),onSuccess(h,{name:p}){s({message:`Connection ${p} successfully updated`,status:"success"}),r.setQueryData(i,h),r.setQueriesData({queryKey:[n,"connection","list"]},f=>f==null?void 0:f.map(y=>y.id===e?h:y))},onError:N(s,"Failed to update connection")}),{mutateAsync:d}=S.useMutation({mutationFn:async()=>g.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(p=>p.id!==e))},onError:N(s,"Failed to remove connection")});return{connection:S.useQuery({queryKey:i,queryFn:async()=>g.GetConnection(n,e)}),startConnection:o,stopConnection:a,updateConnection:c,deleteConnection:d}},Me=t=>[t,"connection","list"],mt=({plugin:t})=>{const e=T(t),n=S.useQueryClient(),{showSnackbar:r}=$(),s=Me(e),{mutateAsync:i}=S.useMutation({mutationFn:async d=>g.StartConnectionWatch(e,d.id),onError:N(r,"Failed to start connection watch")}),{mutateAsync:o}=S.useMutation({mutationFn:async d=>g.StopConnectionWatch(e,d.id),onError:N(r,"Failed to stop connection watch")}),a=l.useCallback(d=>{const u=d.data;console.log("got update to connections",u),n.setQueryData(s,u)},[n,s]);return l.useEffect(()=>{const d=D.On(`${e}/connection/sync`,a);return()=>{d()}},[e,a]),{connections:S.useQuery({queryKey:s,queryFn:async()=>{try{return await g.ListConnections(e)}catch(d){console.log(d),N(r,"Failed to load connections")(d)}return[]},staleTime:3e4,placeholderData:S.keepPreviousData}),startWatch:i,stopWatch:o}},St=({pluginID:t,connectionID:e})=>{const n=T(t),r=[n,"connection","namespaces",e];return{namespaces:S.useQuery({queryKey:r,queryFn:async()=>g.GetConnectionNamespaces(n,e)})}},I=et.withLegacyNames(A.WatchState,"WatchState");function ce(t){const e=Object.values(t.states),n=e.length;let r=0,s=0,i=0,o=0;for(const u of e)u===I.WatchStateSynced&&r++,(u===I.WatchStateError||u===I.WatchStateFailed)&&s++,u===I.WatchStateForbidden&&i++,u===I.WatchStateSkipped&&o++;const a=n-o,c=e.filter(u=>u===I.WatchStateSynced||u===I.WatchStateError||u===I.WatchStateStopped||u===I.WatchStateFailed||u===I.WatchStateForbidden).length,d=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:d}}function Z(t){return t.watchedTotal>0&&t.doneCount>=t.watchedTotal}function Ne(t){return t.some(e=>!Z(e))}function ke(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 fe(t){return`${t.pluginId}/${t.connection}`}function Le(t,e){const n=fe(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 Ct(){const[t,e]=l.useState(new Set),[n,r]=l.useState({}),[s,i]=l.useState(new Map),o=l.useRef(new Map),[a,c]=l.useState(new Map);l.useEffect(()=>{const m=D.On("plugin/crash_recovery_failed",P=>{const v=P.data,w=v==null?void 0:v.pluginID;w&&c(b=>{const F=new Map(b);return F.set(w,v.error??"Crash recovery failed"),F})}),x=D.On("plugin/recovered",P=>{const v=P.data,w=v==null?void 0:v.pluginID;w&&c(b=>{if(!b.has(w))return b;const F=new Map(b);return F.delete(w),F})});return()=>{m(),x()}},[]),l.useEffect(()=>{g.GetAllConnectionStates().then(m=>{if(!m)return;const x={},P=new Set,v=new Map;for(const[w,b]of Object.entries(m))if(b){x[w]=b.map(F=>F.connection);for(const F of b){if(!F.started)continue;const L=`${w}/${F.connection.id}`;P.add(L);const k={pluginID:w,connectionID:F.connection.id,states:{}};if(F.resources)for(const[ne,Je]of Object.entries(F.resources))k.states[ne]=Je;o.current.set(L,k),v.set(L,ce(k))}}r(x),e(P),i(v)}).catch(()=>{})},[]),l.useEffect(()=>D.On("connection/status",x=>{const P=x.data,v=`${P.pluginID}/${P.connectionID}`;P.status==="DISCONNECTED"?(e(w=>{const b=new Set(w);return b.delete(v),b}),i(w=>{const b=new Map(w);return b.delete(v),b}),o.current.delete(v)):e(w=>{const b=new Set(w);return b.add(v),b}),g.ListAllConnections().then(w=>{if(!w)return;const b={};for(const[F,L]of Object.entries(w))L!=null&&(b[F]=L);r(b)}).catch(()=>{})}),[]);const d=l.useCallback(m=>{const x=m.data,P=fe(x);e(b=>{if(b.has(P))return b;const F=new Set(b);return F.add(P),F});const v=Le(o.current,x),w=ce(v);i(b=>{const F=new Map(b);return F.set(P,w),F})},[]);l.useEffect(()=>D.On("watch/STATE",d),[d]);const u=l.useCallback(async(m,x)=>{await g.StopConnection(m,x)},[]),h=l.useCallback(async(m,x)=>{await g.StartConnectionWatch(m,x)},[]),p=l.useCallback(async m=>{const x=a.get(m);c(P=>{if(!P.has(m))return P;const v=new Map(P);return v.delete(m),v});try{await g.RetryFailedPlugin(m)}catch(P){throw c(v=>{const w=new Map(v);return w.set(m,x??"Reload failed"),w}),P}},[a]),f=[];for(const m of t){const[x,P]=m.split("/",2),w=(n[x]??[]).find(ne=>ne.id===P),b=s.get(m),F=b!=null&&!Z(b),L=b!=null&&b.errorCount>0,k=a.get(x);f.push({pluginID:x,connectionID:P,name:(w==null?void 0:w.name)??P,avatar:(w==null?void 0:w.avatar)??"",isStarted:!0,sync:b,isSyncing:F,hasErrors:L||k!=null,pluginFailed:k!=null,pluginError:k})}const y=new Map;for(const m of f){const x=y.get(m.pluginID)??[];x.push(m),y.set(m.pluginID,x)}const _=Array.from(s.values()),R=f.filter(m=>m.isSyncing),C=f.filter(m=>m.hasErrors),E=f.filter(m=>m.pluginFailed);return{entries:f,grouped:y,connectedCount:f.length,syncingCount:R.length,errorCount:C.length,failedCount:E.length,hasSyncing:Ne(_),aggregateProgress:ke(_),disconnect:u,retryWatch:h,retryPlugin:p}}function Et(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 wt(t,e,n){const r=T(t),s=S.useQueryClient(),i=[r,"data",e],o=S.useQuery({queryKey:i,queryFn:async()=>{const c=await g.Get(r,e);return c==null?n:Et(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=S.useMutation({mutationFn:async c=>{await g.Set(r,e,c)},onMutate:async c=>{await s.cancelQueries({queryKey:i});const d=s.getQueryData(i);return s.setQueryData(i,c),{previous:d}},onError:(c,d,u)=>{(u==null?void 0:u.previous)!==void 0&&s.setQueryData(i,u.previous)},onSettled:()=>{s.invalidateQueries({queryKey:i})}});return{data:o.data??n,update:async c=>{await a.mutateAsync(c)},isLoading:o.isLoading}}const _t=()=>{const t=l.useContext(Pe);if(!t)throw new Error("useRightDrawer must be used within a RightDrawerProvider");return t},pe=()=>{const t=l.useContext(xe);if(t===void 0)throw new Error("useBottomDrawer must be used within a BottomDrawerProvider");return t},vt=({pluginID:t})=>{const e=T(t),{showSnackbar:n}=$(),{createTab:r,updateTab:s}=pe();return{createSession:S.useMutation({mutationFn:async({connectionID:o,icon:a,label:c,opts:d})=>{const u=`pending-${crypto.randomUUID()}`;r({id:u,title:c??"Connecting...",variant:"terminal",icon:a??"LuSquareTerminal",properties:{status:"connecting",pluginID:e,connectionID:o,opts:{...d}}});const h=A.SessionOptions.createFrom({command:["/bin/bash"],tty:!0,...d});try{const p=await g.CreateSession(e,o,h);if(!p)throw new Error("Failed to create session: null response");s({id:u},{id:p.id,title:c??`Session ${p.id.substring(0,8)}`,properties:{status:"connected",pluginID:e,connectionID:o,opts:{...d}}})}catch(p){const f=q(p);s({id:u},{properties:{status:"error",error:f.detail,pluginID:e,connectionID:o,opts:{...d}}}),Q(n,p,"Failed to start session")}}}).mutateAsync}},bt=({pluginID:t})=>{const e=T(t),{showSnackbar:n}=$(),{createTab:r}=pe(),s=S.useMutation({mutationFn:async({connectionID:o,resourceKey:a,resourceID:c,resourceData:d,icon:u,label:h,target:p,follow:f=!0,tailLines:y=1e3,params:_})=>{const R=A.CreateSessionOptions.createFrom({resource_key:a,resource_id:c,resource_data:d,options:A.LogSessionOptions.createFrom({target:p??"",follow:f,include_previous:!1,include_timestamps:!0,tail_lines:y,since_seconds:0,limit_bytes:0,include_source_events:!0,params:_??{}})}),C=await g.CreateSession$1(e,o,R);if(!C)throw new Error("Failed to create log session: null response");return r({id:C.id,title:h??`Logs ${C.id.substring(0,8)}`,variant:"logs",icon:u??"LuLogs"}),C},onError:N(n,"Failed to start log session")}),i=S.useMutation({mutationFn:async o=>{await g.CloseSession(o)},onError:N(n,"Failed to close log session")});return{createLogSession:s.mutateAsync,closeLogSession:i.mutateAsync}},Rt=()=>S.useQuery({queryKey:["metric","providers"],queryFn:g.GetProviders,staleTime:3e4}),Ue=t=>S.useQuery({queryKey:["metric","providers",t],queryFn:()=>g.GetProvidersForResource(t),enabled:!!t,staleTime:3e4}),xt=t=>{var R,C;const{connectionID:e,resourceKey:n,resourceID:r,resourceNamespace:s="",resourceData:i={},metricIDs:o=[],shape:a=0,timeRange:c,refreshInterval:d=0,enabled:u=!0}=t,{data:h,isLoading:p}=Ue(n),f=h??[],y=c?Math.max(Math.floor((c.end.getTime()-c.start.getTime())/250),15e3)*1e6:0,_=S.useQuery({queryKey:["metric","query",e,n,r,s,o,a,(R=c==null?void 0:c.start)==null?void 0:R.getTime(),(C=c==null?void 0:c.end)==null?void 0:C.getTime()],queryFn:async()=>{const E=await g.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(),y),m={};for(const[x,P]of Object.entries(E))P!=null&&(m[x]=P);return m},enabled:u&&!!e&&!!n&&(n.startsWith("cluster::")||!!r)&&f.length>0,refetchInterval:d>0?d:void 0,staleTime:5e3,placeholderData:S.keepPreviousData});return{data:_.data??void 0,providers:f,isLoading:p||_.isLoading,error:_.error,refetch:_.refetch}},Pt=t=>{const{pluginID:e,connectionID:n,resourceKey:r,resourceID:s,resourceNamespace:i="",resourceData:o={},metricIDs:a=[],interval:c=1e4,enabled:d=!0}=t,u=T(e),[h,p]=l.useState(null),[f,y]=l.useState(null),[_,R]=l.useState(!1),[C,E]=l.useState(null),m=l.useRef(null),x=l.useCallback(async()=>{if(!(!d||!u||!n||!r||!s))try{const v=await g.Subscribe(u,n,{resource_key:r,resource_id:s,resource_namespace:i,resource_data:o,metric_ids:a,interval:c*1e6});y(v),R(!0),E(null);const w=D.On(`core/metrics/data/${v}`,F=>{const L=F.data;try{const k=JSON.parse(L);k.results&&p(k.results)}catch(k){console.error("Failed to parse metric stream data:",k)}}),b=D.On(`core/metrics/error/${v}`,F=>{const L=F.data;try{const k=JSON.parse(L);E(k.error||"Unknown error")}catch{E("Failed to parse metric stream error")}});m.current=()=>{w(),b()}}catch(v){E(v instanceof Error?v.message:String(v))}},[u,n,r,s,i,a,c,d]),P=l.useCallback(async()=>{if(f)try{await g.Unsubscribe(f)}catch(v){console.error("Failed to unsubscribe:",v)}m.current&&(m.current(),m.current=null),y(null),R(!1)},[f]);return l.useEffect(()=>()=>{f&&g.Unsubscribe(f).catch(console.error),m.current&&m.current()},[f]),{data:h,subscriptionID:f,isStreaming:_,error:C,start:x,stop:P}},j=["networker","portforward","all-sessions"];function It(){const{showSnackbar:t}=$(),e=S.useQueryClient(),n=S.useQuery({queryKey:[...j],queryFn:async()=>g.ListAllPortForwardSessions().catch(i=>{if(q(i).detail.includes("not found"))return[];throw i}),retry:!1});l.useEffect(()=>{const i=D.On("core/networker/portforward/created",()=>{e.invalidateQueries({queryKey:[...j]})}),o=D.On("core/networker/portforward/closed",()=>{e.invalidateQueries({queryKey:[...j]})});return()=>{i(),o()}},[e]);const r=n.data??[],s=S.useMutation({mutationFn:async i=>g.ClosePortForwardSession(i),onError:N(t,"Failed to close port forwarding session"),onSuccess:async()=>{await e.invalidateQueries({queryKey:[...j]})}});return{sessions:n,activeSessions:r,closeSession:s.mutateAsync,openInBrowser:i=>D.OpenURL(`http://localhost:${i}`)}}function Ft({pluginID:t,connectionID:e,resourceID:n}){const r=T(t),s=["networker","portforward","sessions",r,e,n],{showSnackbar:i}=$(),o=S.useQueryClient(),a=S.useQuery({queryKey:s,queryFn:async()=>g.FindPortForwardSessions(r,e,A.FindPortForwardSessionRequest.createFrom({resource_id:n,connection_id:e})).catch(u=>{const h=q(u);return h.detail.includes("not found")?[]:(i({message:"Failed to fetch port forward sessions",status:"error",details:h.detail}),[])}),retry:!1}),c=S.useMutation({mutationFn:async({opts:u})=>{const h=A.PortForwardSessionOptions.createFrom({local_port:u.localPort||0,remote_port:u.remotePort,protocol:u.protocol||"TCP",connection_type:"RESOURCE",connection:{resource_data:u.resource,connection_id:e,plugin_id:r,resource_id:u.resourceId,resource_key:u.resourceKey},labels:u.labels??{},params:u.parameters??{}}),p=await g.StartResourcePortForwardingSession(r,e,h);if(!p)throw new Error("Failed to start port forwarding: null response");return u.openInBrowser&&D.OpenURL(`http://localhost:${p.local_port}`),p},onError:N(i,"Failed to start port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...j]})])}}),d=S.useMutation({mutationFn:async({opts:u})=>g.ClosePortForwardSession(u.sessionID),onError:N(i,"Failed to close port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...j]})])}});return{sessions:a,forward:c.mutateAsync,close:d.mutateAsync}}const Ot=()=>{const t=l.useContext(Ie);if(!t)throw new Error("useConfirmationModal must be used within a ConfirmationModalProvider");return t},Dt=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s=""})=>{const i=T(t),o=S.useQueryClient(),{showSnackbar:a}=$(),c=["RESOURCE",i,e,n,r,s],{mutateAsync:d}=S.useMutation({mutationFn:async p=>g.Update(i,e,n,A.UpdateInput.createFrom({input:p.input,id:r,namespace:s})),onSuccess:async()=>{a(`Resource ${r} updated`,"success"),await o.invalidateQueries({queryKey:c})},onError:N(a,`Failed to update resource ${r}`)}),{mutateAsync:u}=S.useMutation({mutationFn:async(p={})=>g.Delete(i,e,n,A.DeleteInput.createFrom({id:r,namespace:s,gracePeriodSeconds:p.gracePeriodSeconds})),onSuccess:async()=>{a(`Resource ${r} deleted`,"success"),await o.invalidateQueries({queryKey:c})},onError:N(a,`Failed to delete resource ${r}`)});return{resource:S.useQuery({queryKey:c,queryFn:async()=>g.Get$1(i,e,n,A.GetInput.createFrom({id:r,namespace:s})),retry:!1}),update:d,remove:u}},Tt=t=>{const e=["component",t.plugin,t.resource,t.area];return{component:S.useQuery({queryKey:e,queryFn:async()=>g.GetResourceAreaComponent(t)})}},At=({pluginID:t,connectionID:e})=>{const n=T(t),r=[n,"resource_groups","list"];return{groups:S.useQuery({queryKey:r,queryFn:async()=>g.GetResourceGroups(n,e),retry:!1})}},Mt=({pluginID:t,connectionID:e,searches:n})=>{const r=T(t),s=o=>[r,e,o.key,o.namespaces,"list"];return S.useQueries({queries:n.map(o=>({queryKey:s(o),queryFn:async()=>g.List(r,e,o.key,A.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}))})},Nt=({pluginID:t,resourceKey:e})=>{const n=T(t),r=[n,"resources",e];return{resourceType:S.useQuery({queryKey:r,queryFn:async()=>g.GetResourceType(n,e),retry:!1})}},kt=({pluginID:t,connectionID:e})=>{const n=T(t),r=[n,"resources","list",e];return{types:S.useQuery({queryKey:r,queryFn:async()=>g.GetResourceTypes(n,e),retry:!1})}};var Y=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Lt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ut="Expected a function",$e="__lodash_hash_undefined__",$t="[object Function]",qt="[object GeneratorFunction]",jt="[object Symbol]",Qt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Wt=/^\w*$/,Gt=/^\./,Kt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Bt=/[\\^$.*+?()[\]{}|]/g,Ht=/\\(\\)?/g,zt=/^\[object .+?Constructor\]$/,Yt=typeof Y=="object"&&Y&&Y.Object===Object&&Y,Jt=typeof self=="object"&&self&&self.Object===Object&&self,ye=Yt||Jt||Function("return this")();function Zt(t,e){return t==null?void 0:t[e]}function Xt(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch{}return e}var Vt=Array.prototype,en=Function.prototype,qe=Object.prototype,oe=ye["__core-js_shared__"],Ce=function(){var t=/[^.]+$/.exec(oe&&oe.keys&&oe.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),je=en.toString,he=qe.hasOwnProperty,Qe=qe.toString,tn=RegExp("^"+je.call(he).replace(Bt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ee=ye.Symbol,nn=Vt.splice,rn=We(ye,"Map"),H=We(Object,"create"),we=Ee?Ee.prototype:void 0,_e=we?we.toString:void 0;function W(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 sn(){this.__data__=H?H(null):{}}function on(t){return this.has(t)&&delete this.__data__[t]}function an(t){var e=this.__data__;if(H){var n=e[t];return n===$e?void 0:n}return he.call(e,t)?e[t]:void 0}function cn(t){var e=this.__data__;return H?e[t]!==void 0:he.call(e,t)}function un(t,e){var n=this.__data__;return n[t]=H&&e===void 0?$e:e,this}W.prototype.clear=sn;W.prototype.delete=on;W.prototype.get=an;W.prototype.has=cn;W.prototype.set=un;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 ln(){this.__data__=[]}function dn(t){var e=this.__data__,n=ee(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():nn.call(e,n,1),!0}function fn(t){var e=this.__data__,n=ee(e,t);return n<0?void 0:e[n][1]}function pn(t){return ee(this.__data__,t)>-1}function yn(t,e){var n=this.__data__,r=ee(n,t);return r<0?n.push([t,e]):n[r][1]=e,this}K.prototype.clear=ln;K.prototype.delete=dn;K.prototype.get=fn;K.prototype.has=pn;K.prototype.set=yn;function G(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 hn(){this.__data__={hash:new W,map:new(rn||K),string:new W}}function gn(t){return te(this,t).delete(t)}function mn(t){return te(this,t).get(t)}function Sn(t){return te(this,t).has(t)}function Cn(t,e){return te(this,t).set(t,e),this}G.prototype.clear=hn;G.prototype.delete=gn;G.prototype.get=mn;G.prototype.has=Sn;G.prototype.set=Cn;function ee(t,e){for(var n=t.length;n--;)if(On(t[n][0],e))return n;return-1}function En(t,e){e=bn(e,t)?[e]:vn(e);for(var n=0,r=e.length;t!=null&&n<r;)t=t[In(e[n++])];return n&&n==r?t:void 0}function wn(t){if(!Ke(t)||xn(t))return!1;var e=Dn(t)||Xt(t)?tn:zt;return e.test(Fn(t))}function _n(t){if(typeof t=="string")return t;if(me(t))return _e?_e.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function vn(t){return Ge(t)?t:Pn(t)}function te(t,e){var n=t.__data__;return Rn(e)?n[typeof e=="string"?"string":"hash"]:n.map}function We(t,e){var n=Zt(t,e);return wn(n)?n:void 0}function bn(t,e){if(Ge(t))return!1;var n=typeof t;return n=="number"||n=="symbol"||n=="boolean"||t==null||me(t)?!0:Wt.test(t)||!Qt.test(t)||e!=null&&t in Object(e)}function Rn(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function xn(t){return!!Ce&&Ce in t}var Pn=ge(function(t){t=An(t);var e=[];return Gt.test(t)&&e.push(""),t.replace(Kt,function(n,r,s,i){e.push(s?i.replace(Ht,"$1"):r||n)}),e});function In(t){if(typeof t=="string"||me(t))return t;var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function Fn(t){if(t!=null){try{return je.call(t)}catch{}try{return t+""}catch{}}return""}function ge(t,e){if(typeof t!="function"||e&&typeof e!="function")throw new TypeError(Ut);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(ge.Cache||G),n}ge.Cache=G;function On(t,e){return t===e||t!==t&&e!==e}var Ge=Array.isArray;function Dn(t){var e=Ke(t)?Qe.call(t):"";return e==$t||e==qt}function Ke(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}function Tn(t){return!!t&&typeof t=="object"}function me(t){return typeof t=="symbol"||Tn(t)&&Qe.call(t)==jt}function An(t){return t==null?"":_n(t)}function Mn(t,e,n){var r=t==null?void 0:En(t,e);return r===void 0?n:r}var Nn=Mn;const J=Lt(Nn);function Be(t,e,n){const r=t??{result:[],success:!0,totalCount:0},s=[...r.result??[]];for(const i of e){const o=J(i.payload.data,n);switch(i.type){case"ADD":{s.findIndex(c=>J(c,n)===o)===-1&&s.push(i.payload.data);break}case"UPDATE":{const a=s.findIndex(c=>J(c,n)===o);a!==-1&&(s[a]=i.payload.data);break}case"DELETE":{const a=s.findIndex(c=>J(c,n)===o);a!==-1&&s.splice(a,1);break}}}return{...r,result:s}}function He(t,e,n,r,s,i){const o=(i==null?void 0:i.syncWindowMs)??500,a=l.useRef([]),c=l.useRef(null),d=l.useRef(null),u=l.useRef(s);u.current=s;const h=l.useCallback(()=>{const f=a.current;if(a.current=[],c.current=null,d.current=null,!(f.length===0||!r)){t.setQueryData(e,y=>Be(y,f,r));for(const y of f)(y.type==="ADD"||y.type==="UPDATE")&&t.setQueryData(n(y.payload.id,y.payload.namespace),{result:y.payload.data})}},[t,e,n,r]),p=l.useCallback(f=>{a.current.push(f),!(c.current!==null||d.current!==null)&&(u.current===1?c.current=setTimeout(h,o):d.current=requestAnimationFrame(h))},[h,o]);return l.useEffect(()=>()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)},[]),p}const kn=({pluginID:t,connectionID:e,resourceKey:n,idAccessor:r,namespaces:s})=>{const i=T(t),o=S.useQueryClient(),{showSnackbar:a}=$(),c=l.useMemo(()=>s??[],[s]),d=l.useMemo(()=>[i,e,n,c,"list"],[i,e,n,c]),u=l.useCallback((R,C)=>[i,e,n,C,R],[i,e,n]),{mutateAsync:h}=S.useMutation({mutationFn:async R=>g.Create(i,e,n,A.CreateInput.createFrom({input:R.input,namespace:R.namespace??(c.length===1?c[0]:"")})),onSuccess:async R=>{var x;const C=R==null?void 0:R.result;let E="";(x=C==null?void 0:C.metadata)!=null&&x.name?E=C.metadata.name:C!=null&&C.id?E=C.id:C!=null&&C.name?E=C.name:C!=null&&C.ID?E=C.ID:C!=null&&C.Name&&(E=C.Name);const m=E?`Resource ${E} created`:"Resource created";a(m,"success"),await o.invalidateQueries({queryKey:d})},onError:N(a,"Failed to create resource")}),p=S.useQuery({queryKey:d,queryFn:async()=>g.List(i,e,n,A.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:c})),placeholderData:(R,C)=>R,retry:!1}),[f,y]=l.useState(I.WatchStateIdle);l.useEffect(()=>D.On(`${i}/${e}/watch/STATE`,C=>{const E=C.data;E.resourceKey===n&&y(E.state)}),[i,e,n]);const _=He(o,d,u,r,f);return l.useEffect(()=>{if(!r)return;g.SubscribeResource(i,e,n);const R=D.On(`${i}/${e}/${n}/ADD`,m=>_({type:"ADD",payload:m.data})),C=D.On(`${i}/${e}/${n}/UPDATE`,m=>_({type:"UPDATE",payload:m.data})),E=D.On(`${i}/${e}/${n}/DELETE`,m=>_({type:"DELETE",payload:m.data}));return()=>{R(),C(),E(),g.UnsubscribeResource(i,e,n)}},[i,e,n,_]),{resources:p,create:h,watchState:f,isSyncing:f===I.WatchStateSyncing,isSynced:f===I.WatchStateSynced,watchError:f===I.WatchStateError}},Ln=({pluginID:t})=>{const e=T(t),{showSnackbar:n}=$(),r=S.useMutation({mutationFn:async({opts:o,input:a})=>g.Create(e,o.connectionID,o.resourceKey,A.CreateInput.createFrom({input:a.input,namespace:a.namespace??o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} created`,"success")},onError(o,{opts:a}){Q(n,o,`Failed to create resource ${a.resourceID}`)}}),s=S.useMutation({mutationFn:async({opts:o,input:a})=>g.Update(e,o.connectionID,o.resourceKey,A.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}){Q(n,o,`Failed to update resource ${a.resourceID}`)}}),i=S.useMutation({mutationFn:async({opts:o,input:a})=>g.Delete(e,o.connectionID,o.resourceKey,A.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}){Q(n,o,`Failed to delete resource ${a.resourceID}`)}});return{create:r.mutateAsync,update:s.mutateAsync,remove:i.mutateAsync}},Un=({pluginID:t,connectionID:e,resourceKey:n,enabled:r=!0})=>{const s=T(t),i=S.useQuery({queryKey:["RESOURCE_ACTIONS",s,e,n],queryFn:()=>g.GetActions(s,e,n),enabled:r&&!!s&&!!e&&!!n,staleTime:5*60*1e3});return{actions:i.data??[],isLoading:i.isLoading,error:i.error}},$n=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=T(t),s=S.useQueryClient(),{showSnackbar:i}=$(),o=S.useMutation({mutationFn:async({actionID:a,id:c="",namespace:d="",params:u={}})=>g.ExecuteAction(r,e,n,a,A.ActionInput.createFrom({id:c,namespace:d,params:u})),onSuccess:a=>{a!=null&&a.message&&i(a.message,"success"),s.invalidateQueries({queryKey:["RESOURCES",r,e,n]})},onError:(a,c)=>{Q(i,a,`Failed to execute action "${c.actionID}"`)}});return{executeAction:o.mutateAsync,isExecuting:o.isPending,error:o.error}},qn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=T(t),s=S.useQuery({queryKey:["EDITOR_SCHEMAS",r,e],queryFn:()=>g.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=T(t),s=S.useQueryClient(),i=[r,e,"watch-state"],o=l.useRef([]),a=l.useRef(!1),c=l.useCallback(p=>{s.setQueryData(i,f=>{if(!f)return f;const y={...f.resources,[p.resourceKey]:p.state},_={...f.resourceCounts,[p.resourceKey]:p.resourceCount};let R=0,C=0;for(const E of Object.values(y))E===I.WatchStateSynced&&R++,(E===I.WatchStateError||E===I.WatchStateFailed)&&C++;return{...f,resources:y,resourceCounts:_,totalResources:Object.keys(y).length,syncedCount:R,errorCount:C}})},[s,r,e]),d=S.useQuery({queryKey:i,queryFn:async()=>{const p=await g.GetWatchState(r,e);if(!p)throw new Error("Failed to get watch state: null response");const f={};let y=0,_=0;for(const[C,E]of Object.entries(p.resources??{}))E!=null&&(f[C]=E,E===I.WatchStateSynced&&y++,E===I.WatchStateError&&_++);const R={};for(const[C,E]of Object.entries(p.resourceCounts??{}))E!=null&&(R[C]=E);return{connection:p.connectionId,resources:f,resourceCounts:R,totalResources:Object.keys(f).length,syncedCount:y,errorCount:_}},enabled:n&&!!r&&!!e,refetchInterval:p=>{const f=p.state.data;if(!f||f.totalResources===0)return 3e3;let y=0;for(const _ of Object.values(f.resources))(_===I.WatchStateSynced||_===I.WatchStateError||_===I.WatchStateStopped||_===I.WatchStateFailed||_===I.WatchStateForbidden||_===I.WatchStateSkipped)&&y++;return y>=f.totalResources?!1:3e3}});l.useEffect(()=>{if(!d.data||a.current)return;a.current=!0;const p=o.current;o.current=[];for(const f of p)c(f)},[d.data,c]),l.useEffect(()=>{if(!n||!r||!e)return;a.current=!1,o.current=[];const p=D.On(`${r}/${e}/watch/STATE`,f=>{const y=f.data;a.current?c(y):o.current.push(y)});return()=>{p(),a.current=!1,o.current=[]}},[r,e,n,c]);const u=d.data;let h=0;if(u!=null&&u.resources)for(const p of Object.values(u.resources))(p===I.WatchStateSynced||p===I.WatchStateError||p===I.WatchStateStopped||p===I.WatchStateFailed||p===I.WatchStateForbidden||p===I.WatchStateSkipped)&&h++;return{summary:d,getResourceState:p=>u==null?void 0:u.resources[p],isFullySynced:u?u.totalResources>0&&h===u.totalResources:!1,syncProgress:u&&u.totalResources>0?h/u.totalResources:0,errorCount:(u==null?void 0:u.errorCount)??0}},Qn=()=>{const[t,e]=l.useState(new Map),n=l.useRef(new Map),r=l.useRef(new Map),s=l.useCallback(d=>{const u=d.data,h=fe(u),p=Le(n.current,u),f=ce(p);if(e(y=>{const _=new Map(y);return _.set(h,f),_}),r.current.has(h)&&(clearTimeout(r.current.get(h)),r.current.delete(h)),Z(f)){const y=setTimeout(()=>{e(_=>{const R=new Map(_);return R.delete(h),R}),n.current.delete(h),r.current.delete(h)},5e3);r.current.set(h,y)}},[]);l.useEffect(()=>{const d=D.On("watch/STATE",s);return()=>{d();for(const u of r.current.values())clearTimeout(u)}},[s]);const i=Array.from(t.values()),o=Ne(i),a=i.find(d=>!Z(d))??i[0]??null,c=ke(i);return{syncs:i,hasSyncing:o,primarySync:a,aggregateProgress:c}},ze=()=>{const t=l.useContext(de);if(!t)throw new Error("useOperations must be used within an OperationsProvider");return t},Wn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=T(t),{showSnackbar:s}=$(),{addOperation:i,updateOperation:o}=ze(),a=l.useRef([]);return l.useEffect(()=>()=>{a.current.forEach(d=>d())},[]),{startStreamAction:l.useCallback(async({actionID:d,id:u,namespace:h,label:p,params:f={}})=>{try{const y=await g.StreamAction(r,e,n,d,A.ActionInput.createFrom({id:u,namespace:h,params:f}));i({id:y,label:p,resourceKey:n,resourceName:u,namespace:h,connectionID:e,status:"running",startedAt:Date.now()});const _=`action/stream/${y}`,R=D.On(_,C=>{var m,x,P,v;const E=C.data;switch(E.type){case"progress":{const w=E.data??{};o(y,{message:w.message,progress:w.ready!==void 0&&w.desired!==void 0?{ready:w.ready,desired:w.desired}:void 0});break}case"complete":o(y,{status:"completed",message:((m=E.data)==null?void 0:m.message)??"Completed",completedAt:Date.now()}),s(((x=E.data)==null?void 0:x.message)??p+" completed","success"),D.Off(_);break;case"error":o(y,{status:"error",message:((P=E.data)==null?void 0:P.message)??"Failed",completedAt:Date.now()}),s(((v=E.data)==null?void 0:v.message)??p+" failed","error"),D.Off(_);break}});return a.current.push(()=>{R(),D.Off(_)}),y}catch(y){throw Q(s,y,`Failed to start "${d}"`),y}},[r,e,n,i,o,s])}},Gn=()=>{const t=l.useContext(le);if(!t)throw new Error("useSettings must be used within a SettingsProvider");return t},Kn=({to:t,withinContext:e,...n})=>{const{pluginId:r}=V();r||console.error("Link used outside of a plugin context");const s=`/_plugin/${r}${t.startsWith("/")?"":"/"}${t}`;return l.useMemo(()=>O.jsx(B.Link,{style:{textDecoration:"none",color:"inherit"},...n,to:s}),[n,s])};function Bn(){const t=B.useNavigate(),e=B.useLocation(),{pluginId:n}=V();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=l.useCallback((o,a)=>{const{...c}=a??{};o.startsWith("/")?t(`${r}${o}`,c):t(o,c)},[t,r]);return l.useMemo(()=>({location:e,navigate:i,pluginPath:s}),[e,i,s])}class Hn{}class zn{constructor(){M(this,"_extensions");M(this,"root");M(this,"pages");M(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 O.jsx(this.root,{});const e=B.createMemoryRouter(this._routes||[]);return O.jsx(B.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 Ye=(t=>(t.MISSING_MANIFEST="MISSING_MANIFEST",t.MISSING_PLUGIN="MISSING_PLUGIN",t.MISSING_ENTRYPOINT="MISSING_ENTRYPOINT",t))(Ye||{});const Yn=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]}},Jn=t=>!t||t==="core"?"Core":t.charAt(0).toUpperCase()+t.slice(1);exports.ALL_SESSIONS_KEY=j;exports.BottomDrawerContext=xe;exports.ConfirmationModalContext=Ie;exports.ErrorTypes=U;exports.ExtensionPointRegistry=pt;exports.ExtensionPointStore=Te;exports.ExtensionProvider=ft;exports.Link=Kn;exports.OperationsContext=de;exports.OperationsProvider=it;exports.PluginContext=X;exports.PluginContextProvider=nt;exports.PluginErrorCode=Ye;exports.PluginWindow=zn;exports.PluginWindowRootProps=Hn;exports.RightDrawerContext=Pe;exports.SettingsContext=le;exports.SettingsProvider=st;exports.SnackbarProvider=ht;exports.WatchState=I;exports.actionToSnackbar=ve;exports.applyBatch=Be;exports.connectionListQueryKey=Me;exports.createErrorHandler=N;exports.defaultState=Re;exports.formatGroup=Jn;exports.isCancelledError=ue;exports.parseAppError=q;exports.parseResourceKey=Yn;exports.showAppError=Q;exports.useActiveSyncs=Qn;exports.useBottomDrawer=pe;exports.useConfirmationModal=Ot;exports.useConnection=gt;exports.useConnectionNamespaces=St;exports.useConnectionStatus=Ct;exports.useConnections=mt;exports.useEditorSchemas=qn;exports.useEventBatcher=He;exports.useExec=vt;exports.useExecuteAction=$n;exports.useExtensionPoint=dt;exports.useExtensionRegistry=De;exports.useLogs=bt;exports.useMetricProviders=Rt;exports.useMetricProvidersForResource=Ue;exports.useMetricStream=Pt;exports.useOperations=ze;exports.usePluginContext=V;exports.usePluginData=wt;exports.usePluginRouter=Bn;exports.usePluginSettings=rt;exports.usePortForwardSessions=It;exports.useResolvedPluginId=T;exports.useResource=Dt;exports.useResourceActions=Un;exports.useResourceAreaComponent=Tt;exports.useResourceGroups=At;exports.useResourceMetrics=xt;exports.useResourceMutations=Ln;exports.useResourcePortForwarder=Ft;exports.useResourceSearch=Mt;exports.useResourceType=Nt;exports.useResourceTypes=kt;exports.useResources=kn;exports.useRightDrawer=_t;exports.useSettings=Gn;exports.useSnackbar=$;exports.useStreamAction=Wn;exports.useWatchState=jn;
1
+ "use strict";var Xe=Object.defineProperty;var Ve=(t,e,n)=>e in t?Xe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var M=(t,e,n)=>Ve(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("react/jsx-runtime"),d=require("react"),B=require("react-router-dom"),h=require("./graphservice-CRRwkBcy.cjs"),A=require("./models-CHycLCM0.cjs"),S=require("@tanstack/react-query"),et=require("@omniviewdev/base-ui");require("./index-D_aIcqH0.cjs");const T=require("./events-BTiuwc-0.cjs"),tt=require("./legacyEnum-DkV5yRdA.cjs"),X=d.createContext(void 0),U={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",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",CONNECTION_NOT_FOUND:"omniview:connection/not-found",CONNECTION_FAILED:"omniview:connection/failed",RESOURCE_CONNECTION_ERROR:"omniview:resource/connection-error",RESOURCE_CERTIFICATE_ERROR:"omniview:resource/certificate-error",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"};function nt(t){switch(t){case"NOT_FOUND":return{typeUri:U.RESOURCE_NOT_FOUND,status:404};case"FORBIDDEN":return{typeUri:U.RESOURCE_FORBIDDEN,status:403};case"UNAUTHORIZED":return{typeUri:U.RESOURCE_UNAUTHORIZED,status:401};case"CONFLICT":case"ALREADY_EXISTS":return{typeUri:U.RESOURCE_CONFLICT,status:409};case"TIMEOUT":return{typeUri:U.RESOURCE_TIMEOUT,status:408};case"CONNECTION_ERROR":return{typeUri:U.RESOURCE_CONNECTION_ERROR,status:503};case"CERTIFICATE_ERROR":return{typeUri:U.RESOURCE_CERTIFICATE_ERROR,status:502};default:return{typeUri:U.INTERNAL,status:500}}}function $(t){if(t==null)return{type:U.INTERNAL,title:"Unknown error",status:500,detail:"An unknown error occurred."};let e;if(typeof t=="string"?e=t:t instanceof Error?e=t.message:e=String(t),e.startsWith("{"))try{const n=JSON.parse(e);if(typeof n.type=="string"&&typeof n.title=="string"&&typeof n.status=="number"&&typeof n.detail=="string")return n;if(typeof n.code=="string"&&typeof n.title=="string"&&typeof n.message=="string"){const{typeUri:r,status:s}=nt(n.code);return{type:r,title:n.title,status:s,detail:n.message,suggestions:Array.isArray(n.suggestions)?n.suggestions:void 0}}}catch{}return{type:U.INTERNAL,title:"Error",status:500,detail:e}}function ue(t){return t==null?!1:(typeof t=="string"?t:t instanceof Error?t.message:String(t))==="cancelled"?!0:$(t).type===U.CANCELLED}function be(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 ve(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(be)}}function j(t,e,n){if(ue(e))return;const r=$(e);t(ve(r,n))}function N(t,e){return n=>{if(ue(n))return;const r=$(n);t(ve(r,r.title!=="Error"?r.title:e))}}function rt(t){const{children:e,pluginId:n}=t,[r,s]=d.useState({}),[i,o]=d.useState(new A.PluginMeta),[a,c]=d.useState(!1),[l,u]=d.useState(null);console.debug("[PluginContextProvider] render",{pluginId:n,metaLoaded:a,metaError:!!l});const g=()=>{n===void 0||n===""||(console.debug(`[PluginContextProvider] fetching settings for "${n}"`),h.PluginValues(n).then(f=>{console.debug(`[PluginContextProvider] settings loaded for "${n}"`,Object.keys(f)),s(f)}).catch(f=>{const y=$(f);console.error(`[PluginContextProvider] error fetching settings for "${n}":`,y.detail)}))},p=()=>{if(n===void 0||n===""){console.debug("[PluginContextProvider] skipping meta fetch — empty pluginId");return}console.debug(`[PluginContextProvider] fetching meta for "${n}"`),u(null),h.GetPluginMeta(n).then(f=>{console.debug(`[PluginContextProvider] meta loaded for "${n}"`,{name:f==null?void 0:f.name,version:f==null?void 0:f.version}),o(f),c(!0)}).catch(f=>{const y=$(f);console.error(`[PluginContextProvider] error fetching meta for "${n}":`,y.detail),u(y.detail),c(!1)})};return d.useEffect(()=>{console.debug(`[PluginContextProvider] useEffect — pluginId changed to "${n}"`),g(),p()},[n]),l?D.jsx("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center",padding:24},children:D.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:[D.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12},children:[D.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"#EF4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[D.jsx("circle",{cx:"12",cy:"12",r:"10"}),D.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),D.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),D.jsx("span",{style:{fontSize:14,fontWeight:600,color:"#FECACA"},children:"Plugin failed to load"})]}),D.jsx("p",{style:{fontSize:13,color:"#A1A1AA",margin:"0 0 16px"},children:l}),D.jsx("button",{onClick:()=>p(),style:{background:"transparent",color:"#F87171",border:"1px solid #7F1D1D",borderRadius:6,padding:"6px 14px",fontSize:13,fontWeight:500,cursor:"pointer"},children:"Retry"})]})}):a?D.jsx(X.Provider,{value:{pluginId:n,settings:r,meta:i},children:e}):D.jsxs("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center"},children:[D.jsx("div",{style:{width:24,height:24,border:"2px solid #3F3F46",borderTopColor:"#A1A1AA",borderRadius:"50%",animation:"plugin-spin 0.8s linear infinite"}}),D.jsx("style",{children:"@keyframes plugin-spin { to { transform: rotate(360deg); } }"})]})}function V(){const t=d.useContext(X);if(!t)throw new Error("usePluginContext must be used within a PluginContextProvider");return t}function st(){return V().settings}const le=d.createContext(void 0),ot=({children:t})=>{const[e,n]=d.useState({}),r=()=>{h.Values().then(i=>{console.log("Fetched settings:",i),n(i)}).catch(i=>{console.error("Error fetching settings:",i)})};d.useEffect(()=>{r()},[]);const s=()=>{r()};return D.jsx(le.Provider,{value:{settings:e,reload:s},children:t})},Re={height:32,focused:0,tabs:[],createTab:()=>{},createTabs:()=>{},updateTab:()=>{},focusTab:()=>{},reorderTab:()=>{},closeTab:()=>{},closeTabs:()=>{},resizeDrawer:()=>{},closeDrawer:()=>{},fullscreenDrawer:()=>{}},xe=d.createContext(Re),Fe=d.createContext(void 0),Pe=d.createContext(void 0),de=d.createContext(void 0),it=3e4,at=({children:t})=>{const[e,n]=d.useState([]),r=d.useCallback(a=>{n(c=>[a,...c])},[]),s=d.useCallback((a,c)=>{n(l=>l.map(u=>u.id===a?{...u,...c}:u))},[]),i=d.useCallback(a=>{n(c=>c.filter(l=>l.id!==a))},[]);d.useEffect(()=>{const a=[];for(const c of e)if(c.status==="completed"||c.status==="error"){const l=Date.now()-(c.completedAt??c.startedAt),u=Math.max(0,it-l);a.push(setTimeout(()=>i(c.id),u))}return()=>a.forEach(clearTimeout)},[e,i]);const o=d.useMemo(()=>({operations:e,addOperation:r,updateOperation:s,removeOperation:i}),[e,r,s,i]);return D.jsx(de.Provider,{value:o,children:t})};var ie=function(t,e){return ie=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])},ie(t,e)};function ct(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ie(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var re="Invariant Violation",Se=Object.setPrototypeOf,ut=Se===void 0?function(t,e){return t.__proto__=e,t}:Se,lt=function(t){ct(e,t);function e(n){n===void 0&&(n=re);var r=t.call(this,typeof n=="number"?re+": "+n+" (see https://github.com/apollographql/invariant-packages)":n)||this;return r.framesToPop=1,r.name=re,ut(r,e.prototype),r}return e}(Error);function ae(t,e){if(!t)throw new lt(e)}var Ie=["debug","log","warn","error","silent"],dt=Ie.indexOf("log");function z(t){return function(){if(Ie.indexOf(t)>=dt){var e=console[t]||console.log;return e.apply(console,arguments)}}}(function(t){t.debug=z("debug"),t.log=z("log"),t.warn=z("warn"),t.error=z("error")})(ae||(ae={}));const Oe=d.createContext(void 0),De=()=>d.useContext(Oe);function ft(t){const e=De(),n=d.useRef(null),r=e==null?void 0:e.getExtensionPoint(t),s=d.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=d.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 l={};return n.current={store:void 0,version:-1,sentinel:l},l}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 d.useSyncExternalStore(s,i),e==null?void 0:e.getExtensionPoint(t)}const pt=({registry:t,children:e})=>{const n=d.useRef(t);return ae(n.current===t,"You can't change the extension registry after it has been rendered"),D.jsx(Oe.Provider,{value:n.current,children:e})},se=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 Te{constructor(e){M(this,"id");M(this,"mode");M(this,"_pluginId");M(this,"_version",0);M(this,"_contributions",new Map);M(this,"_lookupCache",new Map);M(this,"_matcher");M(this,"_select");M(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 yt{constructor(e){M(this,"_stores",new Map);M(this,"_storeUnsubs",new Map);M(this,"_listeners",new Set);if(e!=null&&e.initialStores)for(const n of e.initialStores)this.addExtensionPoint(n)}addExtensionPoint(e){const n=se(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 Te({...e,id:n});this._stores.set(n,r),this._storeUnsubs.set(n,r.subscribe(()=>this._notify())),this._notify()}getExtensionPoint(e){const n=se(e);return this._stores.get(n)}hasExtensionPoint(e){const n=se(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 Ae=d.createContext(void 0),gt={default:"info",info:"info",success:"success",warning:"warning",error:"danger"},ht=({children:t})=>{const{toast:e}=et.useToast(),[n,r]=d.useState([]),s=o=>{r(a=>[...a,o])},i=(o,a,c)=>{const l=typeof o=="object";let u="",g="info",p,f=5e3,y;if(l){if(u=o.message,o.showOnce){if(n.includes(u))return;s(u)}g=o.status,p=o.details,f=o.autoHideDuration??5e3,y=o.actions}else u=o,g=a,p=c;e(p??u,{severity:gt[g]??"info",title:p?u:void 0,duration:f,action:y==null?void 0:y[0]})};return D.jsx(Ae.Provider,{value:{showSnackbar:i},children:t})},q=()=>{const t=d.useContext(Ae);if(t===void 0)throw new Error("useCustomSnackbar must be used within a CustomSnackbarProvider");return t};function O(t){const e=d.useContext(X),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 mt=({pluginID:t,connectionID:e})=>{const n=O(t),r=S.useQueryClient(),{showSnackbar:s}=q(),i=[n,"connection","detail",e],{mutateAsync:o}=S.useMutation({mutationFn:async()=>h.StartConnection(n,e),onSuccess(g){r.setQueryData(i,g),r.invalidateQueries({queryKey:["EDITOR_SCHEMAS",n,e]})},onError:N(s,"Failed to start connection")}),{mutateAsync:a}=S.useMutation({mutationFn:async()=>h.StopConnection(n,e),onSuccess(g){r.setQueryData(i,g)},onError:N(s,"Failed to stop connection")}),{mutateAsync:c}=S.useMutation({mutationFn:async g=>h.UpdateConnection(n,g),onSuccess(g,{name:p}){s({message:`Connection ${p} successfully updated`,status:"success"}),r.setQueryData(i,g),r.setQueriesData({queryKey:[n,"connection","list"]},f=>f==null?void 0:f.map(y=>y.id===e?g:y))},onError:N(s,"Failed to update connection")}),{mutateAsync:l}=S.useMutation({mutationFn:async()=>h.RemoveConnection(n,e),onSuccess(){s({message:"Connection successfully removed",status:"success"}),r.setQueryData(i,void 0),r.setQueriesData({queryKey:[n,"connection","list"]},g=>g==null?void 0:g.filter(p=>p.id!==e))},onError:N(s,"Failed to remove connection")});return{connection:S.useQuery({queryKey:i,queryFn:async()=>h.GetConnection(n,e)}),startConnection:o,stopConnection:a,updateConnection:c,deleteConnection:l}},Me=t=>[t,"connection","list"],St=({plugin:t})=>{const e=O(t),n=S.useQueryClient(),{showSnackbar:r}=q(),s=Me(e),{mutateAsync:i}=S.useMutation({mutationFn:async l=>h.StartConnectionWatch(e,l.id),onError:N(r,"Failed to start connection watch")}),{mutateAsync:o}=S.useMutation({mutationFn:async l=>h.StopConnectionWatch(e,l.id),onError:N(r,"Failed to stop connection watch")}),a=d.useCallback(l=>{const u=l.data;console.log("got update to connections",u),n.setQueryData(s,u)},[n,s]);return d.useEffect(()=>{const l=T.On(`${e}/connection/sync`,a);return()=>{l()}},[e,a]),{connections:S.useQuery({queryKey:s,queryFn:async()=>{try{return await h.ListConnections(e)}catch(l){console.log(l),N(r,"Failed to load connections")(l)}return[]},staleTime:3e4,placeholderData:S.keepPreviousData}),startWatch:i,stopWatch:o}},Et=({pluginID:t,connectionID:e})=>{const n=O(t),r=[n,"connection","namespaces",e];return{namespaces:S.useQuery({queryKey:r,queryFn:async()=>h.GetConnectionNamespaces(n,e)})}},P=tt.withLegacyNames(A.WatchState,"WatchState");function ce(t){const e=Object.values(t.states),n=e.length;let r=0,s=0,i=0,o=0;for(const u of e)u===P.WatchStateSynced&&r++,(u===P.WatchStateError||u===P.WatchStateFailed)&&s++,u===P.WatchStateForbidden&&i++,u===P.WatchStateSkipped&&o++;const a=n-o,c=e.filter(u=>u===P.WatchStateSynced||u===P.WatchStateError||u===P.WatchStateStopped||u===P.WatchStateFailed||u===P.WatchStateForbidden).length,l=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:l}}function Z(t){return t.watchedTotal>0&&t.doneCount>=t.watchedTotal}function Ne(t){return t.some(e=>!Z(e))}function ke(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 fe(t){return`${t.pluginId}/${t.connection}`}function Le(t,e){const n=fe(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 Ct(){const[t,e]=d.useState(new Set),[n,r]=d.useState({}),[s,i]=d.useState(new Map),o=d.useRef(new Map),[a,c]=d.useState(new Map);d.useEffect(()=>{const m=T.On("plugin/crash_recovery_failed",F=>{const b=F.data,_=b==null?void 0:b.pluginID;_&&c(v=>{const I=new Map(v);return I.set(_,b.error??"Crash recovery failed"),I})}),x=T.On("plugin/recovered",F=>{const b=F.data,_=b==null?void 0:b.pluginID;_&&c(v=>{if(!v.has(_))return v;const I=new Map(v);return I.delete(_),I})});return()=>{m(),x()}},[]),d.useEffect(()=>{h.GetAllConnectionStates().then(m=>{if(!m)return;const x={},F=new Set,b=new Map;for(const[_,v]of Object.entries(m))if(v){x[_]=v.map(I=>I.connection);for(const I of v){if(!I.started)continue;const L=`${_}/${I.connection.id}`;F.add(L);const k={pluginID:_,connectionID:I.connection.id,states:{}};if(I.resources)for(const[ne,Ze]of Object.entries(I.resources))k.states[ne]=Ze;o.current.set(L,k),b.set(L,ce(k))}}r(x),e(F),i(b)}).catch(()=>{})},[]),d.useEffect(()=>T.On("connection/status",x=>{const F=x.data,b=`${F.pluginID}/${F.connectionID}`;F.status==="DISCONNECTED"?(e(_=>{const v=new Set(_);return v.delete(b),v}),i(_=>{const v=new Map(_);return v.delete(b),v}),o.current.delete(b)):e(_=>{const v=new Set(_);return v.add(b),v}),h.ListAllConnections().then(_=>{if(!_)return;const v={};for(const[I,L]of Object.entries(_))L!=null&&(v[I]=L);r(v)}).catch(()=>{})}),[]);const l=d.useCallback(m=>{const x=m.data,F=fe(x);e(v=>{if(v.has(F))return v;const I=new Set(v);return I.add(F),I});const b=Le(o.current,x),_=ce(b);i(v=>{const I=new Map(v);return I.set(F,_),I})},[]);d.useEffect(()=>T.On("watch/STATE",l),[l]);const u=d.useCallback(async(m,x)=>{await h.StopConnection(m,x)},[]),g=d.useCallback(async(m,x)=>{await h.StartConnectionWatch(m,x)},[]),p=d.useCallback(async m=>{const x=a.get(m);c(F=>{if(!F.has(m))return F;const b=new Map(F);return b.delete(m),b});try{await h.RetryFailedPlugin(m)}catch(F){throw c(b=>{const _=new Map(b);return _.set(m,x??"Reload failed"),_}),F}},[a]),f=[];for(const m of t){const[x,F]=m.split("/",2),_=(n[x]??[]).find(ne=>ne.id===F),v=s.get(m),I=v!=null&&!Z(v),L=v!=null&&v.errorCount>0,k=a.get(x);f.push({pluginID:x,connectionID:F,name:(_==null?void 0:_.name)??F,avatar:(_==null?void 0:_.avatar)??"",isStarted:!0,sync:v,isSyncing:I,hasErrors:L||k!=null,pluginFailed:k!=null,pluginError:k})}const y=new Map;for(const m of f){const x=y.get(m.pluginID)??[];x.push(m),y.set(m.pluginID,x)}const w=Array.from(s.values()),R=f.filter(m=>m.isSyncing),E=f.filter(m=>m.hasErrors),C=f.filter(m=>m.pluginFailed);return{entries:f,grouped:y,connectedCount:f.length,syncingCount:R.length,errorCount:E.length,failedCount:C.length,hasSyncing:Ne(w),aggregateProgress:ke(w),disconnect:u,retryWatch:g,retryPlugin:p}}function _t(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 wt(t,e,n){const r=O(t),s=S.useQueryClient(),i=[r,"data",e],o=S.useQuery({queryKey:i,queryFn:async()=>{const c=await h.Get(r,e);return c==null?n:_t(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=S.useMutation({mutationFn:async c=>{await h.Set(r,e,c)},onMutate:async c=>{await s.cancelQueries({queryKey:i});const l=s.getQueryData(i);return s.setQueryData(i,c),{previous:l}},onError:(c,l,u)=>{(u==null?void 0:u.previous)!==void 0&&s.setQueryData(i,u.previous)},onSettled:()=>{s.invalidateQueries({queryKey:i})}});return{data:o.data??n,update:async c=>{await a.mutateAsync(c)},isLoading:o.isLoading}}const bt=()=>{const t=d.useContext(Fe);if(!t)throw new Error("useRightDrawer must be used within a RightDrawerProvider");return t},pe=()=>{const t=d.useContext(xe);if(t===void 0)throw new Error("useBottomDrawer must be used within a BottomDrawerProvider");return t},vt=({pluginID:t})=>{const e=O(t),{showSnackbar:n}=q(),{createTab:r,updateTab:s}=pe();return{createSession:S.useMutation({mutationFn:async({connectionID:o,icon:a,label:c,opts:l})=>{const u=`pending-${crypto.randomUUID()}`;r({id:u,title:c??"Connecting...",variant:"terminal",icon:a??"LuSquareTerminal",properties:{status:"connecting",pluginID:e,connectionID:o,opts:{...l}}});const g=A.SessionOptions.createFrom({command:["/bin/bash"],tty:!0,...l});try{const p=await h.CreateSession(e,o,g);if(!p)throw new Error("Failed to create session: null response");s({id:u},{id:p.id,title:c??`Session ${p.id.substring(0,8)}`,properties:{status:"connected",pluginID:e,connectionID:o,opts:{...l}}})}catch(p){const f=$(p);s({id:u},{properties:{status:"error",error:f.detail,pluginID:e,connectionID:o,opts:{...l}}}),j(n,p,"Failed to start session")}}}).mutateAsync}},Rt=({pluginID:t})=>{const e=O(t),{showSnackbar:n}=q(),{createTab:r}=pe(),s=S.useMutation({mutationFn:async({connectionID:o,resourceKey:a,resourceID:c,resourceData:l,icon:u,label:g,target:p,follow:f=!0,tailLines:y=1e3,params:w})=>{const R=A.CreateSessionOptions.createFrom({resource_key:a,resource_id:c,resource_data:l,options:A.LogSessionOptions.createFrom({target:p??"",follow:f,include_previous:!1,include_timestamps:!0,tail_lines:y,since_seconds:0,limit_bytes:0,include_source_events:!0,params:w??{}})}),E=await h.CreateSession$1(e,o,R);if(!E)throw new Error("Failed to create log session: null response");return r({id:E.id,title:g??`Logs ${E.id.substring(0,8)}`,variant:"logs",icon:u??"LuLogs"}),E},onError:N(n,"Failed to start log session")}),i=S.useMutation({mutationFn:async o=>{await h.CloseSession(o)},onError:N(n,"Failed to close log session")});return{createLogSession:s.mutateAsync,closeLogSession:i.mutateAsync}},xt=()=>S.useQuery({queryKey:["metric","providers"],queryFn:h.GetProviders,staleTime:3e4}),Ue=t=>S.useQuery({queryKey:["metric","providers",t],queryFn:()=>h.GetProvidersForResource(t),enabled:!!t,staleTime:3e4}),Ft=t=>{var R,E;const{connectionID:e,resourceKey:n,resourceID:r,resourceNamespace:s="",resourceData:i={},metricIDs:o=[],shape:a=0,timeRange:c,refreshInterval:l=0,enabled:u=!0}=t,{data:g,isLoading:p}=Ue(n),f=g??[],y=c?Math.max(Math.floor((c.end.getTime()-c.start.getTime())/250),15e3)*1e6:0,w=S.useQuery({queryKey:["metric","query",e,n,r,s,o,a,(R=c==null?void 0:c.start)==null?void 0:R.getTime(),(E=c==null?void 0:c.end)==null?void 0:E.getTime()],queryFn:async()=>{const C=await h.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(),y),m={};for(const[x,F]of Object.entries(C))F!=null&&(m[x]=F);return m},enabled:u&&!!e&&!!n&&(n.startsWith("cluster::")||!!r)&&f.length>0,refetchInterval:l>0?l:void 0,staleTime:5e3,placeholderData:S.keepPreviousData});return{data:w.data??void 0,providers:f,isLoading:p||w.isLoading,error:w.error,refetch:w.refetch}},Pt=t=>{const{pluginID:e,connectionID:n,resourceKey:r,resourceID:s,resourceNamespace:i="",resourceData:o={},metricIDs:a=[],interval:c=1e4,enabled:l=!0}=t,u=O(e),[g,p]=d.useState(null),[f,y]=d.useState(null),[w,R]=d.useState(!1),[E,C]=d.useState(null),m=d.useRef(null),x=d.useCallback(async()=>{if(!(!l||!u||!n||!r||!s))try{const b=await h.Subscribe(u,n,{resource_key:r,resource_id:s,resource_namespace:i,resource_data:o,metric_ids:a,interval:c*1e6});y(b),R(!0),C(null);const _=T.On(`core/metrics/data/${b}`,I=>{const L=I.data;try{const k=JSON.parse(L);k.results&&p(k.results)}catch(k){console.error("Failed to parse metric stream data:",k)}}),v=T.On(`core/metrics/error/${b}`,I=>{const L=I.data;try{const k=JSON.parse(L);C(k.error||"Unknown error")}catch{C("Failed to parse metric stream error")}});m.current=()=>{_(),v()}}catch(b){C(b instanceof Error?b.message:String(b))}},[u,n,r,s,i,a,c,l]),F=d.useCallback(async()=>{if(f)try{await h.Unsubscribe(f)}catch(b){console.error("Failed to unsubscribe:",b)}m.current&&(m.current(),m.current=null),y(null),R(!1)},[f]);return d.useEffect(()=>()=>{f&&h.Unsubscribe(f).catch(console.error),m.current&&m.current()},[f]),{data:g,subscriptionID:f,isStreaming:w,error:E,start:x,stop:F}},Q=["networker","portforward","all-sessions"];function It(){const{showSnackbar:t}=q(),e=S.useQueryClient(),n=S.useQuery({queryKey:[...Q],queryFn:async()=>h.ListAllPortForwardSessions().catch(i=>{if($(i).detail.includes("not found"))return[];throw i}),retry:!1});d.useEffect(()=>{const i=T.On("core/networker/portforward/created",()=>{e.invalidateQueries({queryKey:[...Q]})}),o=T.On("core/networker/portforward/closed",()=>{e.invalidateQueries({queryKey:[...Q]})});return()=>{i(),o()}},[e]);const r=n.data??[],s=S.useMutation({mutationFn:async i=>h.ClosePortForwardSession(i),onError:N(t,"Failed to close port forwarding session"),onSuccess:async()=>{await e.invalidateQueries({queryKey:[...Q]})}});return{sessions:n,activeSessions:r,closeSession:s.mutateAsync,openInBrowser:i=>T.OpenURL(`http://localhost:${i}`)}}function Ot({pluginID:t,connectionID:e,resourceID:n}){const r=O(t),s=["networker","portforward","sessions",r,e,n],{showSnackbar:i}=q(),o=S.useQueryClient(),a=S.useQuery({queryKey:s,queryFn:async()=>h.FindPortForwardSessions(r,e,A.FindPortForwardSessionRequest.createFrom({resource_id:n,connection_id:e})).catch(u=>{const g=$(u);return g.detail.includes("not found")?[]:(i({message:"Failed to fetch port forward sessions",status:"error",details:g.detail}),[])}),retry:!1}),c=S.useMutation({mutationFn:async({opts:u})=>{const g=A.PortForwardSessionOptions.createFrom({local_port:u.localPort||0,remote_port:u.remotePort,protocol:u.protocol||"TCP",connection_type:"RESOURCE",connection:{resource_data:u.resource,connection_id:e,plugin_id:r,resource_id:u.resourceId,resource_key:u.resourceKey},labels:u.labels??{},params:u.parameters??{}}),p=await h.StartResourcePortForwardingSession(r,e,g);if(!p)throw new Error("Failed to start port forwarding: null response");return u.openInBrowser&&T.OpenURL(`http://localhost:${p.local_port}`),p},onError:N(i,"Failed to start port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...Q]})])}}),l=S.useMutation({mutationFn:async({opts:u})=>h.ClosePortForwardSession(u.sessionID),onError:N(i,"Failed to close port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...Q]})])}});return{sessions:a,forward:c.mutateAsync,close:l.mutateAsync}}const Dt=()=>{const t=d.useContext(Pe);if(!t)throw new Error("useConfirmationModal must be used within a ConfirmationModalProvider");return t},Tt=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s=""})=>{const i=O(t),o=S.useQueryClient(),{showSnackbar:a}=q(),c=["RESOURCE",i,e,n,r,s],{mutateAsync:l}=S.useMutation({mutationFn:async p=>h.Update(i,e,n,A.UpdateInput.createFrom({input:p.input,id:r,namespace:s})),onSuccess:async()=>{a(`Resource ${r} updated`,"success"),await o.invalidateQueries({queryKey:c})},onError:N(a,`Failed to update resource ${r}`)}),{mutateAsync:u}=S.useMutation({mutationFn:async(p={})=>h.Delete(i,e,n,A.DeleteInput.createFrom({id:r,namespace:s,gracePeriodSeconds:p.gracePeriodSeconds})),onSuccess:async()=>{a(`Resource ${r} deleted`,"success"),await o.invalidateQueries({queryKey:c})},onError:N(a,`Failed to delete resource ${r}`)});return{resource:S.useQuery({queryKey:c,queryFn:async()=>h.Get$1(i,e,n,A.GetInput.createFrom({id:r,namespace:s})),retry:!1}),update:l,remove:u}},At=t=>{const e=["component",t.plugin,t.resource,t.area];return{component:S.useQuery({queryKey:e,queryFn:async()=>h.GetResourceAreaComponent(t)})}},Mt=({pluginID:t,connectionID:e})=>{const n=O(t),r=[n,"resource_groups","list"];return{groups:S.useQuery({queryKey:r,queryFn:async()=>h.GetResourceGroups(n,e),retry:!1})}},Nt=({pluginID:t,connectionID:e,searches:n})=>{const r=O(t),s=o=>[r,e,o.key,o.namespaces,"list"];return S.useQueries({queries:n.map(o=>({queryKey:s(o),queryFn:async()=>h.List(r,e,o.key,A.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}))})},kt=({pluginID:t,resourceKey:e})=>{const n=O(t),r=[n,"resources",e];return{resourceType:S.useQuery({queryKey:r,queryFn:async()=>h.GetResourceType(n,e),retry:!1})}},Lt=({pluginID:t,connectionID:e})=>{const n=O(t),r=[n,"resources","list",e];return{types:S.useQuery({queryKey:r,queryFn:async()=>h.GetResourceTypes(n,e),retry:!1})}};var Y=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ut(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var qt="Expected a function",qe="__lodash_hash_undefined__",$t="[object Function]",Qt="[object GeneratorFunction]",jt="[object Symbol]",Wt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Gt=/^\w*$/,Kt=/^\./,Bt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Ht=/[\\^$.*+?()[\]{}|]/g,zt=/\\(\\)?/g,Yt=/^\[object .+?Constructor\]$/,Jt=typeof Y=="object"&&Y&&Y.Object===Object&&Y,Zt=typeof self=="object"&&self&&self.Object===Object&&self,ye=Jt||Zt||Function("return this")();function Xt(t,e){return t==null?void 0:t[e]}function Vt(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch{}return e}var en=Array.prototype,tn=Function.prototype,$e=Object.prototype,oe=ye["__core-js_shared__"],Ee=function(){var t=/[^.]+$/.exec(oe&&oe.keys&&oe.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Qe=tn.toString,ge=$e.hasOwnProperty,je=$e.toString,nn=RegExp("^"+Qe.call(ge).replace(Ht,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ce=ye.Symbol,rn=en.splice,sn=We(ye,"Map"),H=We(Object,"create"),_e=Ce?Ce.prototype:void 0,we=_e?_e.toString:void 0;function W(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 on(){this.__data__=H?H(null):{}}function an(t){return this.has(t)&&delete this.__data__[t]}function cn(t){var e=this.__data__;if(H){var n=e[t];return n===qe?void 0:n}return ge.call(e,t)?e[t]:void 0}function un(t){var e=this.__data__;return H?e[t]!==void 0:ge.call(e,t)}function ln(t,e){var n=this.__data__;return n[t]=H&&e===void 0?qe:e,this}W.prototype.clear=on;W.prototype.delete=an;W.prototype.get=cn;W.prototype.has=un;W.prototype.set=ln;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 dn(){this.__data__=[]}function fn(t){var e=this.__data__,n=ee(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():rn.call(e,n,1),!0}function pn(t){var e=this.__data__,n=ee(e,t);return n<0?void 0:e[n][1]}function yn(t){return ee(this.__data__,t)>-1}function gn(t,e){var n=this.__data__,r=ee(n,t);return r<0?n.push([t,e]):n[r][1]=e,this}K.prototype.clear=dn;K.prototype.delete=fn;K.prototype.get=pn;K.prototype.has=yn;K.prototype.set=gn;function G(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 hn(){this.__data__={hash:new W,map:new(sn||K),string:new W}}function mn(t){return te(this,t).delete(t)}function Sn(t){return te(this,t).get(t)}function En(t){return te(this,t).has(t)}function Cn(t,e){return te(this,t).set(t,e),this}G.prototype.clear=hn;G.prototype.delete=mn;G.prototype.get=Sn;G.prototype.has=En;G.prototype.set=Cn;function ee(t,e){for(var n=t.length;n--;)if(Dn(t[n][0],e))return n;return-1}function _n(t,e){e=Rn(e,t)?[e]:vn(e);for(var n=0,r=e.length;t!=null&&n<r;)t=t[In(e[n++])];return n&&n==r?t:void 0}function wn(t){if(!Ke(t)||Fn(t))return!1;var e=Tn(t)||Vt(t)?nn:Yt;return e.test(On(t))}function bn(t){if(typeof t=="string")return t;if(me(t))return we?we.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function vn(t){return Ge(t)?t:Pn(t)}function te(t,e){var n=t.__data__;return xn(e)?n[typeof e=="string"?"string":"hash"]:n.map}function We(t,e){var n=Xt(t,e);return wn(n)?n:void 0}function Rn(t,e){if(Ge(t))return!1;var n=typeof t;return n=="number"||n=="symbol"||n=="boolean"||t==null||me(t)?!0:Gt.test(t)||!Wt.test(t)||e!=null&&t in Object(e)}function xn(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Fn(t){return!!Ee&&Ee in t}var Pn=he(function(t){t=Mn(t);var e=[];return Kt.test(t)&&e.push(""),t.replace(Bt,function(n,r,s,i){e.push(s?i.replace(zt,"$1"):r||n)}),e});function In(t){if(typeof t=="string"||me(t))return t;var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function On(t){if(t!=null){try{return Qe.call(t)}catch{}try{return t+""}catch{}}return""}function he(t,e){if(typeof t!="function"||e&&typeof e!="function")throw new TypeError(qt);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(he.Cache||G),n}he.Cache=G;function Dn(t,e){return t===e||t!==t&&e!==e}var Ge=Array.isArray;function Tn(t){var e=Ke(t)?je.call(t):"";return e==$t||e==Qt}function Ke(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}function An(t){return!!t&&typeof t=="object"}function me(t){return typeof t=="symbol"||An(t)&&je.call(t)==jt}function Mn(t){return t==null?"":bn(t)}function Nn(t,e,n){var r=t==null?void 0:_n(t,e);return r===void 0?n:r}var kn=Nn;const J=Ut(kn);function Be(t,e,n){const r=t??{result:[],success:!0,totalCount:0},s=[...r.result??[]];for(const i of e){const o=J(i.payload.data,n);switch(i.type){case"ADD":{s.findIndex(c=>J(c,n)===o)===-1&&s.push(i.payload.data);break}case"UPDATE":{const a=s.findIndex(c=>J(c,n)===o);a!==-1&&(s[a]=i.payload.data);break}case"DELETE":{const a=s.findIndex(c=>J(c,n)===o);a!==-1&&s.splice(a,1);break}}}return{...r,result:s}}function He(t,e,n,r,s,i){const o=(i==null?void 0:i.syncWindowMs)??500,a=d.useRef([]),c=d.useRef(null),l=d.useRef(null),u=d.useRef(s);u.current=s;const g=d.useCallback(()=>{const f=a.current;if(a.current=[],c.current=null,l.current=null,!(f.length===0||!r)){t.setQueryData(e,y=>Be(y,f,r));for(const y of f)(y.type==="ADD"||y.type==="UPDATE")&&t.setQueryData(n(y.payload.id,y.payload.namespace),{result:y.payload.data})}},[t,e,n,r]),p=d.useCallback(f=>{a.current.push(f),!(c.current!==null||l.current!==null)&&(u.current===1?c.current=setTimeout(g,o):l.current=requestAnimationFrame(g))},[g,o]);return d.useEffect(()=>()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),l.current!==null&&(cancelAnimationFrame(l.current),l.current=null)},[]),p}const Ln=({pluginID:t,connectionID:e,resourceKey:n,idAccessor:r,namespaces:s})=>{const i=O(t),o=S.useQueryClient(),{showSnackbar:a}=q(),c=d.useMemo(()=>s??[],[s]),l=d.useMemo(()=>[i,e,n,c,"list"],[i,e,n,c]),u=d.useCallback((R,E)=>[i,e,n,E,R],[i,e,n]),{mutateAsync:g}=S.useMutation({mutationFn:async R=>h.Create(i,e,n,A.CreateInput.createFrom({input:R.input,namespace:R.namespace??(c.length===1?c[0]:"")})),onSuccess:async R=>{var x;const E=R==null?void 0:R.result;let C="";(x=E==null?void 0:E.metadata)!=null&&x.name?C=E.metadata.name:E!=null&&E.id?C=E.id:E!=null&&E.name?C=E.name:E!=null&&E.ID?C=E.ID:E!=null&&E.Name&&(C=E.Name);const m=C?`Resource ${C} created`:"Resource created";a(m,"success"),await o.invalidateQueries({queryKey:l})},onError:N(a,"Failed to create resource")}),p=S.useQuery({queryKey:l,queryFn:async()=>h.List(i,e,n,A.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:c})),placeholderData:(R,E)=>R,retry:!1}),[f,y]=d.useState(P.WatchStateIdle);d.useEffect(()=>T.On(`${i}/${e}/watch/STATE`,E=>{const C=E.data;C.resourceKey===n&&y(C.state)}),[i,e,n]);const w=He(o,l,u,r,f);return d.useEffect(()=>{if(!r)return;h.SubscribeResource(i,e,n);const R=T.On(`${i}/${e}/${n}/ADD`,m=>w({type:"ADD",payload:m.data})),E=T.On(`${i}/${e}/${n}/UPDATE`,m=>w({type:"UPDATE",payload:m.data})),C=T.On(`${i}/${e}/${n}/DELETE`,m=>w({type:"DELETE",payload:m.data}));return()=>{R(),E(),C(),h.UnsubscribeResource(i,e,n)}},[i,e,n,w]),{resources:p,create:g,watchState:f,isSyncing:f===P.WatchStateSyncing,isSynced:f===P.WatchStateSynced,watchError:f===P.WatchStateError}},Un=({pluginID:t})=>{const e=O(t),{showSnackbar:n}=q(),r=S.useMutation({mutationFn:async({opts:o,input:a})=>h.Create(e,o.connectionID,o.resourceKey,A.CreateInput.createFrom({input:a.input,namespace:a.namespace??o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} created`,"success")},onError(o,{opts:a}){j(n,o,`Failed to create resource ${a.resourceID}`)}}),s=S.useMutation({mutationFn:async({opts:o,input:a})=>h.Update(e,o.connectionID,o.resourceKey,A.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}){j(n,o,`Failed to update resource ${a.resourceID}`)}}),i=S.useMutation({mutationFn:async({opts:o,input:a})=>h.Delete(e,o.connectionID,o.resourceKey,A.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}){j(n,o,`Failed to delete resource ${a.resourceID}`)}});return{create:r.mutateAsync,update:s.mutateAsync,remove:i.mutateAsync}},qn=({pluginID:t,connectionID:e,resourceKey:n,enabled:r=!0})=>{const s=O(t),i=S.useQuery({queryKey:["RESOURCE_ACTIONS",s,e,n],queryFn:()=>h.GetActions(s,e,n),enabled:r&&!!s&&!!e&&!!n,staleTime:5*60*1e3});return{actions:i.data??[],isLoading:i.isLoading,error:i.error}},$n=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=O(t),s=S.useQueryClient(),{showSnackbar:i}=q(),o=S.useMutation({mutationFn:async({actionID:a,id:c="",namespace:l="",params:u={}})=>h.ExecuteAction(r,e,n,a,A.ActionInput.createFrom({id:c,namespace:l,params:u})),onSuccess:a=>{a!=null&&a.message&&i(a.message,"success"),s.invalidateQueries({queryKey:["RESOURCES",r,e,n]})},onError:(a,c)=>{j(i,a,`Failed to execute action "${c.actionID}"`)}});return{executeAction:o.mutateAsync,isExecuting:o.isPending,error:o.error}},Qn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=O(t),s=S.useQuery({queryKey:["EDITOR_SCHEMAS",r,e],queryFn:()=>h.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=O(t),s=S.useQueryClient(),i=[r,e,"watch-state"],o=d.useRef([]),a=d.useRef(!1),c=d.useCallback(p=>{s.setQueryData(i,f=>{if(!f)return f;const y={...f.resources,[p.resourceKey]:p.state},w={...f.resourceCounts,[p.resourceKey]:p.resourceCount};let R=0,E=0;for(const C of Object.values(y))C===P.WatchStateSynced&&R++,(C===P.WatchStateError||C===P.WatchStateFailed)&&E++;return{...f,resources:y,resourceCounts:w,totalResources:Object.keys(y).length,syncedCount:R,errorCount:E}})},[s,r,e]),l=S.useQuery({queryKey:i,queryFn:async()=>{const p=await h.GetWatchState(r,e);if(!p)throw new Error("Failed to get watch state: null response");const f={};let y=0,w=0;for(const[E,C]of Object.entries(p.resources??{}))C!=null&&(f[E]=C,C===P.WatchStateSynced&&y++,C===P.WatchStateError&&w++);const R={};for(const[E,C]of Object.entries(p.resourceCounts??{}))C!=null&&(R[E]=C);return{connection:p.connectionId,resources:f,resourceCounts:R,totalResources:Object.keys(f).length,syncedCount:y,errorCount:w}},enabled:n&&!!r&&!!e,refetchInterval:p=>{const f=p.state.data;if(!f||f.totalResources===0)return 3e3;let y=0;for(const w of Object.values(f.resources))(w===P.WatchStateSynced||w===P.WatchStateError||w===P.WatchStateStopped||w===P.WatchStateFailed||w===P.WatchStateForbidden||w===P.WatchStateSkipped)&&y++;return y>=f.totalResources?!1:3e3}});d.useEffect(()=>{if(!l.data||a.current)return;a.current=!0;const p=o.current;o.current=[];for(const f of p)c(f)},[l.data,c]),d.useEffect(()=>{if(!n||!r||!e)return;a.current=!1,o.current=[];const p=T.On(`${r}/${e}/watch/STATE`,f=>{const y=f.data;a.current?c(y):o.current.push(y)});return()=>{p(),a.current=!1,o.current=[]}},[r,e,n,c]);const u=l.data;let g=0;if(u!=null&&u.resources)for(const p of Object.values(u.resources))(p===P.WatchStateSynced||p===P.WatchStateError||p===P.WatchStateStopped||p===P.WatchStateFailed||p===P.WatchStateForbidden||p===P.WatchStateSkipped)&&g++;return{summary:l,getResourceState:p=>u==null?void 0:u.resources[p],isFullySynced:u?u.totalResources>0&&g===u.totalResources:!1,syncProgress:u&&u.totalResources>0?g/u.totalResources:0,errorCount:(u==null?void 0:u.errorCount)??0}},Wn=()=>{const[t,e]=d.useState(new Map),n=d.useRef(new Map),r=d.useRef(new Map),s=d.useCallback(l=>{const u=l.data,g=fe(u),p=Le(n.current,u),f=ce(p);if(e(y=>{const w=new Map(y);return w.set(g,f),w}),r.current.has(g)&&(clearTimeout(r.current.get(g)),r.current.delete(g)),Z(f)){const y=setTimeout(()=>{e(w=>{const R=new Map(w);return R.delete(g),R}),n.current.delete(g),r.current.delete(g)},5e3);r.current.set(g,y)}},[]);d.useEffect(()=>{const l=T.On("watch/STATE",s);return()=>{l();for(const u of r.current.values())clearTimeout(u)}},[s]);const i=Array.from(t.values()),o=Ne(i),a=i.find(l=>!Z(l))??i[0]??null,c=ke(i);return{syncs:i,hasSyncing:o,primarySync:a,aggregateProgress:c}},ze=()=>{const t=d.useContext(de);if(!t)throw new Error("useOperations must be used within an OperationsProvider");return t},Gn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=O(t),{showSnackbar:s}=q(),{addOperation:i,updateOperation:o}=ze(),a=d.useRef([]);return d.useEffect(()=>()=>{a.current.forEach(l=>l())},[]),{startStreamAction:d.useCallback(async({actionID:l,id:u,namespace:g,label:p,params:f={}})=>{try{const y=await h.StreamAction(r,e,n,l,A.ActionInput.createFrom({id:u,namespace:g,params:f}));i({id:y,label:p,resourceKey:n,resourceName:u,namespace:g,connectionID:e,status:"running",startedAt:Date.now()});const w=`action/stream/${y}`,R=T.On(w,E=>{var m,x,F,b;const C=E.data;switch(C.type){case"progress":{const _=C.data??{};o(y,{message:_.message,progress:_.ready!==void 0&&_.desired!==void 0?{ready:_.ready,desired:_.desired}:void 0});break}case"complete":o(y,{status:"completed",message:((m=C.data)==null?void 0:m.message)??"Completed",completedAt:Date.now()}),s(((x=C.data)==null?void 0:x.message)??p+" completed","success"),T.Off(w);break;case"error":o(y,{status:"error",message:((F=C.data)==null?void 0:F.message)??"Failed",completedAt:Date.now()}),s(((b=C.data)==null?void 0:b.message)??p+" failed","error"),T.Off(w);break}});return a.current.push(()=>{R(),T.Off(w)}),y}catch(y){throw j(s,y,`Failed to start "${l}"`),y}},[r,e,n,i,o,s])}},Kn=1e4,Bn={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 Hn(t,e){const n=Bn[t];if(n)return n[e];const r=t.replace(/_/g," ");return e==="outgoing"?r:`${r} (incoming)`}function zn(t,e){return t.pluginId===e.pluginId&&t.connectionId===e.connectionId&&t.resourceKey===e.resourceKey&&t.id===e.id&&(t.namespace??"")===(e.namespace??"")}function Ye(t,e){return e.map(n=>{const r=zn(n.source,t);return{resource:r?n.target:n.source,type:n.type,direction:r?"outgoing":"incoming",label:n.label}})}const Yn=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",direction:i="both",relationshipType:o,enabled:a=!0,refetchInterval:c=Kn})=>{const l=O(t),u=S.useQuery({queryKey:["RESOURCE_RELATED",l,e,n,s,r,i,o??null],queryFn:async()=>h.GetRelated(l,e,n,s,r,i,o??null),enabled:a&&!!l&&!!e&&!!n&&!!r,refetchInterval:c}),g={pluginId:l,connectionId:e,resourceKey:n,id:r,namespace:s},p=u.data??[];return{related:Ye(g,p),edges:p,isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch}},Jn=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",maxDepth:i=3,enabled:o=!0,refetchInterval:a=1e4})=>{const c=O(t),l=S.useQuery({queryKey:["RESOURCE_DEPENDENCY_TREE",c,e,n,s,r,i],queryFn:async()=>h.GetDependencyTree(c,e,n,s,r,i),enabled:o&&!!c&&!!e&&!!n&&!!r,refetchInterval:a});return{tree:l.data??null,isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}},Zn=()=>{const t=d.useContext(le);if(!t)throw new Error("useSettings must be used within a SettingsProvider");return t},Xn=({to:t,withinContext:e,...n})=>{const{pluginId:r}=V();r||console.error("Link used outside of a plugin context");const s=`/_plugin/${r}${t.startsWith("/")?"":"/"}${t}`;return d.useMemo(()=>D.jsx(B.Link,{style:{textDecoration:"none",color:"inherit"},...n,to:s}),[n,s])};function Vn(){const t=B.useNavigate(),e=B.useLocation(),{pluginId:n}=V();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=d.useCallback((o,a)=>{const{...c}=a??{};o.startsWith("/")?t(`${r}${o}`,c):t(o,c)},[t,r]);return d.useMemo(()=>({location:e,navigate:i,pluginPath:s}),[e,i,s])}class er{}class tr{constructor(){M(this,"_extensions");M(this,"root");M(this,"pages");M(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 D.jsx(this.root,{});const e=B.createMemoryRouter(this._routes||[]);return D.jsx(B.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 Je=(t=>(t.MISSING_MANIFEST="MISSING_MANIFEST",t.MISSING_PLUGIN="MISSING_PLUGIN",t.MISSING_ENTRYPOINT="MISSING_ENTRYPOINT",t))(Je||{});const nr=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]}},rr=t=>!t||t==="core"?"Core":t.charAt(0).toUpperCase()+t.slice(1);exports.ALL_SESSIONS_KEY=Q;exports.BottomDrawerContext=xe;exports.ConfirmationModalContext=Pe;exports.ErrorTypes=U;exports.ExtensionPointRegistry=yt;exports.ExtensionPointStore=Te;exports.ExtensionProvider=pt;exports.Link=Xn;exports.OperationsContext=de;exports.OperationsProvider=at;exports.PluginContext=X;exports.PluginContextProvider=rt;exports.PluginErrorCode=Je;exports.PluginWindow=tr;exports.PluginWindowRootProps=er;exports.RightDrawerContext=Fe;exports.SettingsContext=le;exports.SettingsProvider=ot;exports.SnackbarProvider=ht;exports.WatchState=P;exports.actionToSnackbar=be;exports.applyBatch=Be;exports.connectionListQueryKey=Me;exports.createErrorHandler=N;exports.defaultState=Re;exports.formatGroup=rr;exports.isCancelledError=ue;exports.parseAppError=$;exports.parseResourceKey=nr;exports.relationshipLabel=Hn;exports.showAppError=j;exports.toRelatedResources=Ye;exports.useActiveSyncs=Wn;exports.useBottomDrawer=pe;exports.useConfirmationModal=Dt;exports.useConnection=mt;exports.useConnectionNamespaces=Et;exports.useConnectionStatus=Ct;exports.useConnections=St;exports.useDependencyTree=Jn;exports.useEditorSchemas=Qn;exports.useEventBatcher=He;exports.useExec=vt;exports.useExecuteAction=$n;exports.useExtensionPoint=ft;exports.useExtensionRegistry=De;exports.useLogs=Rt;exports.useMetricProviders=xt;exports.useMetricProvidersForResource=Ue;exports.useMetricStream=Pt;exports.useOperations=ze;exports.usePluginContext=V;exports.usePluginData=wt;exports.usePluginRouter=Vn;exports.usePluginSettings=st;exports.usePortForwardSessions=It;exports.useRelatedResources=Yn;exports.useResolvedPluginId=O;exports.useResource=Tt;exports.useResourceActions=qn;exports.useResourceAreaComponent=At;exports.useResourceGroups=Mt;exports.useResourceMetrics=Ft;exports.useResourceMutations=Un;exports.useResourcePortForwarder=Ot;exports.useResourceSearch=Nt;exports.useResourceType=kt;exports.useResourceTypes=Lt;exports.useResources=Ln;exports.useRightDrawer=bt;exports.useSettings=Zn;exports.useSnackbar=q;exports.useStreamAction=Gn;exports.useWatchState=jn;