@omniviewdev/runtime 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.cjs +1 -1
- package/dist/api.d.ts +1 -0
- package/dist/api.js +28 -27
- package/dist/bindings/github.com/omniviewdev/omniview/backend/pkg/plugin/index.d.ts +1 -1
- package/dist/bindings/github.com/omniviewdev/omniview/backend/pkg/plugin/models.d.ts +27 -0
- package/dist/bindings/github.com/omniviewdev/omniview/backend/pkg/plugin/resource/graph/index.d.ts +1 -1
- package/dist/bindings/github.com/omniviewdev/omniview/backend/pkg/plugin/resource/graph/models.d.ts +36 -0
- package/dist/bindings/github.com/omniviewdev/omniview/backend/pkg/plugin/resource/graphservice.d.ts +6 -0
- package/dist/graphservice-2kgAuCnt.cjs +1 -0
- package/dist/graphservice-5kuEPkCT.js +731 -0
- package/dist/hooks/resource/index.d.ts +4 -0
- package/dist/hooks/resource/useDependencyTree.d.ts +41 -0
- package/dist/hooks/resource/useRefetchOnGraphChange.d.ts +11 -0
- package/dist/hooks/resource/useRelatedResources.d.ts +81 -0
- package/dist/hooks/resource/useResourceGraph.d.ts +46 -0
- package/dist/index.cjs +2 -2
- package/dist/index.js +787 -647
- package/dist/{models-B8OVRhdT.js → models-3V1aa9YT.js} +1 -1
- package/dist/{models-BVKsY9u1.js → models-B97zjrHu.js} +565 -452
- package/dist/{models-CExSuVU2.cjs → models-BPmIMpct.cjs} +1 -1
- package/dist/models-sJV1iQbd.cjs +1 -0
- package/dist/models.cjs +1 -1
- package/dist/models.d.ts +1 -0
- package/dist/models.js +90 -84
- package/package.json +1 -1
- package/dist/models-DdAWPDgz.cjs +0 -1
- package/dist/servicewrapper-BH5omp-N.js +0 -708
- package/dist/servicewrapper-dDhyC68C.cjs +0 -1
|
@@ -12,3 +12,7 @@ export * from './useWatchState';
|
|
|
12
12
|
export * from './useActiveSyncs';
|
|
13
13
|
export * from './useStreamAction';
|
|
14
14
|
export * from './useEventBatcher';
|
|
15
|
+
export * from './useRelatedResources';
|
|
16
|
+
export * from './useDependencyTree';
|
|
17
|
+
export * from './useRefetchOnGraphChange';
|
|
18
|
+
export * from './useResourceGraph';
|
|
@@ -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
|
+
* Also refetch on this interval, in milliseconds. Not needed normally: the
|
|
24
|
+
* query refetches when the host reports a graph change for the connection.
|
|
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,11 @@
|
|
|
1
|
+
import { QueryKey } from '@tanstack/react-query';
|
|
2
|
+
/**
|
|
3
|
+
* graphChangedEvent is the event the host emits, at most about once a second,
|
|
4
|
+
* when relationship edges touching a connection change.
|
|
5
|
+
*/
|
|
6
|
+
export declare function graphChangedEvent(pluginID: string, connectionID: string): string;
|
|
7
|
+
/**
|
|
8
|
+
* useRefetchOnGraphChange invalidates one query whenever the host reports a
|
|
9
|
+
* relationship graph change for the connection.
|
|
10
|
+
*/
|
|
11
|
+
export declare function useRefetchOnGraphChange(pluginID: string, connectionID: string, queryKey: QueryKey, enabled: boolean): void;
|
|
@@ -0,0 +1,81 @@
|
|
|
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
|
+
* Also refetch on this interval, in milliseconds. Not needed normally: the
|
|
48
|
+
* query refetches when the host reports a graph change for the connection.
|
|
49
|
+
*/
|
|
50
|
+
refetchInterval?: number | false;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* relationshipLabel returns a display label for a relationship type, read
|
|
54
|
+
* from the viewed resource's side: ("owns", "incoming") is "Owned by".
|
|
55
|
+
* Unknown types fall back to the type name.
|
|
56
|
+
*/
|
|
57
|
+
export declare function relationshipLabel(type: string, direction: RelationshipDirection): string;
|
|
58
|
+
/**
|
|
59
|
+
* toRelatedResources converts graph edges around `self` into one entry per
|
|
60
|
+
* edge, keyed by the resource at the other end.
|
|
61
|
+
*/
|
|
62
|
+
export declare function toRelatedResources(self: GraphNode, edges: GraphEdge[]): RelatedResource[];
|
|
63
|
+
/**
|
|
64
|
+
* useRelatedResources returns the resources linked to one resource in the
|
|
65
|
+
* relationship graph the host builds from the plugin's relationship
|
|
66
|
+
* declarations (owner references, node assignment, volumes, selectors, ...).
|
|
67
|
+
*
|
|
68
|
+
* Only resources the host is watching are indexed. Targets referenced by
|
|
69
|
+
* name (a Secret a Pod mounts) are returned even if they do not exist.
|
|
70
|
+
*/
|
|
71
|
+
export declare const useRelatedResources: ({ pluginID: explicitPluginID, connectionID, resourceKey, resourceID, namespace, direction, relationshipType, enabled, refetchInterval, }: UseRelatedResourcesOptions) => {
|
|
72
|
+
/** One entry per edge, from the viewed resource's side. */
|
|
73
|
+
related: RelatedResource[];
|
|
74
|
+
/** The raw graph edges. */
|
|
75
|
+
edges: GraphEdge[];
|
|
76
|
+
isLoading: boolean;
|
|
77
|
+
isFetching: boolean;
|
|
78
|
+
error: Error | null;
|
|
79
|
+
refetch: (options?: import('@tanstack/react-query').RefetchOptions) => Promise<import('@tanstack/react-query').QueryObserverResult<GraphEdge[], Error>>;
|
|
80
|
+
};
|
|
81
|
+
export default useRelatedResources;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
type UseResourceGraphOptions = {
|
|
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 "core::v1::Pod"
|
|
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
|
+
/**
|
|
19
|
+
* How many hops to follow against edge direction: owners, selectors and
|
|
20
|
+
* other resources pointing at the root. The host caps this at 5.
|
|
21
|
+
*/
|
|
22
|
+
upDepth?: number;
|
|
23
|
+
/**
|
|
24
|
+
* How many hops to follow along edge direction: resources the root
|
|
25
|
+
* depends on. The host caps this at 5.
|
|
26
|
+
*/
|
|
27
|
+
downDepth?: number;
|
|
28
|
+
/** Whether to enable the query */
|
|
29
|
+
enabled?: boolean;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* useResourceGraph returns the neighbourhood of one resource as a graph:
|
|
33
|
+
* every node reached within upDepth/downDepth hops, with its signed distance
|
|
34
|
+
* from the root (negative upstream, positive downstream), and every edge
|
|
35
|
+
* between them. Unlike useDependencyTree, a resource reached by several
|
|
36
|
+
* paths keeps all of its edges. Refetches when the host reports a graph
|
|
37
|
+
* change for the connection.
|
|
38
|
+
*/
|
|
39
|
+
export declare const useResourceGraph: ({ pluginID: explicitPluginID, connectionID, resourceKey, resourceID, namespace, upDepth, downDepth, enabled, }: UseResourceGraphOptions) => {
|
|
40
|
+
graph: import('../../models').Subgraph | null;
|
|
41
|
+
isLoading: boolean;
|
|
42
|
+
isFetching: boolean;
|
|
43
|
+
error: Error | null;
|
|
44
|
+
refetch: (options?: import('@tanstack/react-query').RefetchOptions) => Promise<import('@tanstack/react-query').QueryObserverResult<import('../../models').Subgraph | null, Error>>;
|
|
45
|
+
};
|
|
46
|
+
export default useResourceGraph;
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
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 et=Object.defineProperty;var tt=(t,e,n)=>e in t?et(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var M=(t,e,n)=>tt(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("react/jsx-runtime"),d=require("react"),B=require("react-router-dom"),h=require("./graphservice-2kgAuCnt.cjs"),D=require("./models-sJV1iQbd.cjs"),m=require("@tanstack/react-query"),nt=require("@omniviewdev/base-ui");require("./index-D_aIcqH0.cjs");const T=require("./events-BTiuwc-0.cjs"),rt=require("./legacyEnum-DkV5yRdA.cjs"),X=d.createContext(void 0),q={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 st(t){switch(t){case"NOT_FOUND":return{typeUri:q.RESOURCE_NOT_FOUND,status:404};case"FORBIDDEN":return{typeUri:q.RESOURCE_FORBIDDEN,status:403};case"UNAUTHORIZED":return{typeUri:q.RESOURCE_UNAUTHORIZED,status:401};case"CONFLICT":case"ALREADY_EXISTS":return{typeUri:q.RESOURCE_CONFLICT,status:409};case"TIMEOUT":return{typeUri:q.RESOURCE_TIMEOUT,status:408};case"CONNECTION_ERROR":return{typeUri:q.RESOURCE_CONNECTION_ERROR,status:503};case"CERTIFICATE_ERROR":return{typeUri:q.RESOURCE_CERTIFICATE_ERROR,status:502};default:return{typeUri:q.INTERNAL,status:500}}}function $(t){if(t==null)return{type:q.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}=st(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:q.INTERNAL,title:"Error",status:500,detail:e}}function le(t){return t==null?!1:(typeof t=="string"?t:t instanceof Error?t.message:String(t))==="cancelled"?!0:$(t).type===q.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 Re(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 j(t,e,n){if(le(e))return;const r=$(e);t(Re(r,n))}function N(t,e){return n=>{if(le(n))return;const r=$(n);t(Re(r,r.title!=="Error"?r.title:e))}}function ot(t){const{children:e,pluginId:n}=t,[r,s]=d.useState({}),[i,o]=d.useState(new D.PluginMeta),[a,c]=d.useState(!1),[l,u]=d.useState(null);console.debug("[PluginContextProvider] render",{pluginId:n,metaLoaded:a,metaError:!!l});const y=()=>{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 g=$(f);console.error(`[PluginContextProvider] error fetching settings for "${n}":`,g.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 g=$(f);console.error(`[PluginContextProvider] error fetching meta for "${n}":`,g.detail),u(g.detail),c(!1)})};return d.useEffect(()=>{console.debug(`[PluginContextProvider] useEffect — pluginId changed to "${n}"`),y(),p()},[n]),l?A.jsx("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center",padding:24},children:A.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:[A.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12},children:[A.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"#EF4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[A.jsx("circle",{cx:"12",cy:"12",r:"10"}),A.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),A.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),A.jsx("span",{style:{fontSize:14,fontWeight:600,color:"#FECACA"},children:"Plugin failed to load"})]}),A.jsx("p",{style:{fontSize:13,color:"#A1A1AA",margin:"0 0 16px"},children:l}),A.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?A.jsx(X.Provider,{value:{pluginId:n,settings:r,meta:i},children:e}):A.jsxs("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center"},children:[A.jsx("div",{style:{width:24,height:24,border:"2px solid #3F3F46",borderTopColor:"#A1A1AA",borderRadius:"50%",animation:"plugin-spin 0.8s linear infinite"}}),A.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 it(){return V().settings}const de=d.createContext(void 0),at=({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 A.jsx(de.Provider,{value:{settings:e,reload:s},children:t})},xe={height:32,focused:0,tabs:[],createTab:()=>{},createTabs:()=>{},updateTab:()=>{},focusTab:()=>{},reorderTab:()=>{},closeTab:()=>{},closeTabs:()=>{},resizeDrawer:()=>{},closeDrawer:()=>{},fullscreenDrawer:()=>{}},Fe=d.createContext(xe),Pe=d.createContext(void 0),Oe=d.createContext(void 0),fe=d.createContext(void 0),ct=3e4,ut=({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,ct-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 A.jsx(fe.Provider,{value:o,children:t})};var ae=function(t,e){return ae=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])},ae(t,e)};function lt(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ae(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var se="Invariant Violation",Ce=Object.setPrototypeOf,dt=Ce===void 0?function(t,e){return t.__proto__=e,t}:Ce,ft=function(t){lt(e,t);function e(n){n===void 0&&(n=se);var r=t.call(this,typeof n=="number"?se+": "+n+" (see https://github.com/apollographql/invariant-packages)":n)||this;return r.framesToPop=1,r.name=se,dt(r,e.prototype),r}return e}(Error);function ce(t,e){if(!t)throw new ft(e)}var Ie=["debug","log","warn","error","silent"],pt=Ie.indexOf("log");function z(t){return function(){if(Ie.indexOf(t)>=pt){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")})(ce||(ce={}));const Te=d.createContext(void 0),Ae=()=>d.useContext(Te);function yt(t){const e=Ae(),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 gt=({registry:t,children:e})=>{const n=d.useRef(t);return ce(n.current===t,"You can't change the extension registry after it has been rendered"),A.jsx(Te.Provider,{value:n.current,children:e})},oe=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 De{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 ht{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=oe(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 De({...e,id:n});this._stores.set(n,r),this._storeUnsubs.set(n,r.subscribe(()=>this._notify())),this._notify()}getExtensionPoint(e){const n=oe(e);return this._stores.get(n)}hasExtensionPoint(e){const n=oe(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 Me=d.createContext(void 0),mt={default:"info",info:"info",success:"success",warning:"warning",error:"danger"},St=({children:t})=>{const{toast:e}=nt.useToast(),[n,r]=d.useState([]),s=o=>{r(a=>[...a,o])},i=(o,a,c)=>{const l=typeof o=="object";let u="",y="info",p,f=5e3,g;if(l){if(u=o.message,o.showOnce){if(n.includes(u))return;s(u)}y=o.status,p=o.details,f=o.autoHideDuration??5e3,g=o.actions}else u=o,y=a,p=c;e(p??u,{severity:mt[y]??"info",title:p?u:void 0,duration:f,action:g==null?void 0:g[0]})};return A.jsx(Me.Provider,{value:{showSnackbar:i},children:t})},U=()=>{const t=d.useContext(Me);if(t===void 0)throw new Error("useCustomSnackbar must be used within a CustomSnackbarProvider");return t};function I(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 Ct=({pluginID:t,connectionID:e})=>{const n=I(t),r=m.useQueryClient(),{showSnackbar:s}=U(),i=[n,"connection","detail",e],{mutateAsync:o}=m.useMutation({mutationFn:async()=>h.StartConnection(n,e),onSuccess(y){r.setQueryData(i,y),r.invalidateQueries({queryKey:["EDITOR_SCHEMAS",n,e]})},onError:N(s,"Failed to start connection")}),{mutateAsync:a}=m.useMutation({mutationFn:async()=>h.StopConnection(n,e),onSuccess(y){r.setQueryData(i,y)},onError:N(s,"Failed to stop connection")}),{mutateAsync:c}=m.useMutation({mutationFn:async y=>h.UpdateConnection(n,y),onSuccess(y,{name:p}){s({message:`Connection ${p} successfully updated`,status:"success"}),r.setQueryData(i,y),r.setQueriesData({queryKey:[n,"connection","list"]},f=>f==null?void 0:f.map(g=>g.id===e?y:g))},onError:N(s,"Failed to update connection")}),{mutateAsync:l}=m.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"]},y=>y==null?void 0:y.filter(p=>p.id!==e))},onError:N(s,"Failed to remove connection")});return{connection:m.useQuery({queryKey:i,queryFn:async()=>h.GetConnection(n,e)}),startConnection:o,stopConnection:a,updateConnection:c,deleteConnection:l}},Ne=t=>[t,"connection","list"],Et=({plugin:t})=>{const e=I(t),n=m.useQueryClient(),{showSnackbar:r}=U(),s=Ne(e),{mutateAsync:i}=m.useMutation({mutationFn:async l=>h.StartConnectionWatch(e,l.id),onError:N(r,"Failed to start connection watch")}),{mutateAsync:o}=m.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:m.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:m.keepPreviousData}),startWatch:i,stopWatch:o}},_t=({pluginID:t,connectionID:e})=>{const n=I(t),r=[n,"connection","namespaces",e];return{namespaces:m.useQuery({queryKey:r,queryFn:async()=>h.GetConnectionNamespaces(n,e)})}},P=rt.withLegacyNames(D.WatchState,"WatchState");function ue(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 ke(t){return t.some(e=>!Z(e))}function Le(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 pe(t){return`${t.pluginId}/${t.connection}`}function qe(t,e){const n=pe(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 wt(){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 S=T.On("plugin/crash_recovery_failed",F=>{const b=F.data,_=b==null?void 0:b.pluginID;_&&c(v=>{const O=new Map(v);return O.set(_,b.error??"Crash recovery failed"),O})}),x=T.On("plugin/recovered",F=>{const b=F.data,_=b==null?void 0:b.pluginID;_&&c(v=>{if(!v.has(_))return v;const O=new Map(v);return O.delete(_),O})});return()=>{S(),x()}},[]),d.useEffect(()=>{h.GetAllConnectionStates().then(S=>{if(!S)return;const x={},F=new Set,b=new Map;for(const[_,v]of Object.entries(S))if(v){x[_]=v.map(O=>O.connection);for(const O of v){if(!O.started)continue;const L=`${_}/${O.connection.id}`;F.add(L);const k={pluginID:_,connectionID:O.connection.id,states:{}};if(O.resources)for(const[re,Ve]of Object.entries(O.resources))k.states[re]=Ve;o.current.set(L,k),b.set(L,ue(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[O,L]of Object.entries(_))L!=null&&(v[O]=L);r(v)}).catch(()=>{})}),[]);const l=d.useCallback(S=>{const x=S.data,F=pe(x);e(v=>{if(v.has(F))return v;const O=new Set(v);return O.add(F),O});const b=qe(o.current,x),_=ue(b);i(v=>{const O=new Map(v);return O.set(F,_),O})},[]);d.useEffect(()=>T.On("watch/STATE",l),[l]);const u=d.useCallback(async(S,x)=>{await h.StopConnection(S,x)},[]),y=d.useCallback(async(S,x)=>{await h.StartConnectionWatch(S,x)},[]),p=d.useCallback(async S=>{const x=a.get(S);c(F=>{if(!F.has(S))return F;const b=new Map(F);return b.delete(S),b});try{await h.RetryFailedPlugin(S)}catch(F){throw c(b=>{const _=new Map(b);return _.set(S,x??"Reload failed"),_}),F}},[a]),f=[];for(const S of t){const[x,F]=S.split("/",2),_=(n[x]??[]).find(re=>re.id===F),v=s.get(S),O=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:O,hasErrors:L||k!=null,pluginFailed:k!=null,pluginError:k})}const g=new Map;for(const S of f){const x=g.get(S.pluginID)??[];x.push(S),g.set(S.pluginID,x)}const w=Array.from(s.values()),R=f.filter(S=>S.isSyncing),C=f.filter(S=>S.hasErrors),E=f.filter(S=>S.pluginFailed);return{entries:f,grouped:g,connectedCount:f.length,syncingCount:R.length,errorCount:C.length,failedCount:E.length,hasSyncing:ke(w),aggregateProgress:Le(w),disconnect:u,retryWatch:y,retryPlugin:p}}function bt(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 vt(t,e,n){const r=I(t),s=m.useQueryClient(),i=[r,"data",e],o=m.useQuery({queryKey:i,queryFn:async()=>{const c=await h.Get(r,e);return c==null?n:bt(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=m.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 Rt=()=>{const t=d.useContext(Pe);if(!t)throw new Error("useRightDrawer must be used within a RightDrawerProvider");return t},ye=()=>{const t=d.useContext(Fe);if(t===void 0)throw new Error("useBottomDrawer must be used within a BottomDrawerProvider");return t},xt=({pluginID:t})=>{const e=I(t),{showSnackbar:n}=U(),{createTab:r,updateTab:s}=ye();return{createSession:m.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 y=D.SessionOptions.createFrom({command:["/bin/bash"],tty:!0,...l});try{const p=await h.CreateSession(e,o,y);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}},Ft=({pluginID:t})=>{const e=I(t),{showSnackbar:n}=U(),{createTab:r}=ye(),s=m.useMutation({mutationFn:async({connectionID:o,resourceKey:a,resourceID:c,resourceData:l,icon:u,label:y,target:p,follow:f=!0,tailLines:g=1e3,params:w})=>{const R=D.CreateSessionOptions.createFrom({resource_key:a,resource_id:c,resource_data:l,options:D.LogSessionOptions.createFrom({target:p??"",follow:f,include_previous:!1,include_timestamps:!0,tail_lines:g,since_seconds:0,limit_bytes:0,include_source_events:!0,params:w??{}})}),C=await h.CreateSession$1(e,o,R);if(!C)throw new Error("Failed to create log session: null response");return r({id:C.id,title:y??`Logs ${C.id.substring(0,8)}`,variant:"logs",icon:u??"LuLogs"}),C},onError:N(n,"Failed to start log session")}),i=m.useMutation({mutationFn:async o=>{await h.CloseSession(o)},onError:N(n,"Failed to close log session")});return{createLogSession:s.mutateAsync,closeLogSession:i.mutateAsync}},Pt=()=>m.useQuery({queryKey:["metric","providers"],queryFn:h.GetProviders,staleTime:3e4}),Ue=t=>m.useQuery({queryKey:["metric","providers",t],queryFn:()=>h.GetProvidersForResource(t),enabled:!!t,staleTime:3e4}),Ot=t=>{var R,C;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:y,isLoading:p}=Ue(n),f=y??[],g=c?Math.max(Math.floor((c.end.getTime()-c.start.getTime())/250),15e3)*1e6:0,w=m.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 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(),g),S={};for(const[x,F]of Object.entries(E))F!=null&&(S[x]=F);return S},enabled:u&&!!e&&!!n&&(n.startsWith("cluster::")||!!r)&&f.length>0,refetchInterval:l>0?l:void 0,staleTime:5e3,placeholderData:m.keepPreviousData});return{data:w.data??void 0,providers:f,isLoading:p||w.isLoading,error:w.error,refetch:w.refetch}},It=t=>{const{pluginID:e,connectionID:n,resourceKey:r,resourceID:s,resourceNamespace:i="",resourceData:o={},metricIDs:a=[],interval:c=1e4,enabled:l=!0}=t,u=I(e),[y,p]=d.useState(null),[f,g]=d.useState(null),[w,R]=d.useState(!1),[C,E]=d.useState(null),S=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});g(b),R(!0),E(null);const _=T.On(`core/metrics/data/${b}`,O=>{const L=O.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}`,O=>{const L=O.data;try{const k=JSON.parse(L);E(k.error||"Unknown error")}catch{E("Failed to parse metric stream error")}});S.current=()=>{_(),v()}}catch(b){E(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)}S.current&&(S.current(),S.current=null),g(null),R(!1)},[f]);return d.useEffect(()=>()=>{f&&h.Unsubscribe(f).catch(console.error),S.current&&S.current()},[f]),{data:y,subscriptionID:f,isStreaming:w,error:C,start:x,stop:F}},Q=["networker","portforward","all-sessions"];function Tt(){const{showSnackbar:t}=U(),e=m.useQueryClient(),n=m.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=m.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 At({pluginID:t,connectionID:e,resourceID:n}){const r=I(t),s=["networker","portforward","sessions",r,e,n],{showSnackbar:i}=U(),o=m.useQueryClient(),a=m.useQuery({queryKey:s,queryFn:async()=>h.FindPortForwardSessions(r,e,D.FindPortForwardSessionRequest.createFrom({resource_id:n,connection_id:e})).catch(u=>{const y=$(u);return y.detail.includes("not found")?[]:(i({message:"Failed to fetch port forward sessions",status:"error",details:y.detail}),[])}),retry:!1}),c=m.useMutation({mutationFn:async({opts:u})=>{const y=D.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,y);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=m.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(Oe);if(!t)throw new Error("useConfirmationModal must be used within a ConfirmationModalProvider");return t},Mt=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s=""})=>{const i=I(t),o=m.useQueryClient(),{showSnackbar:a}=U(),c=["RESOURCE",i,e,n,r,s],{mutateAsync:l}=m.useMutation({mutationFn:async p=>h.Update(i,e,n,D.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}=m.useMutation({mutationFn:async(p={})=>h.Delete(i,e,n,D.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:m.useQuery({queryKey:c,queryFn:async()=>h.Get$1(i,e,n,D.GetInput.createFrom({id:r,namespace:s})),retry:!1}),update:l,remove:u}},Nt=t=>{const e=["component",t.plugin,t.resource,t.area];return{component:m.useQuery({queryKey:e,queryFn:async()=>h.GetResourceAreaComponent(t)})}},kt=({pluginID:t,connectionID:e})=>{const n=I(t),r=[n,"resource_groups","list"];return{groups:m.useQuery({queryKey:r,queryFn:async()=>h.GetResourceGroups(n,e),retry:!1})}},Lt=({pluginID:t,connectionID:e,searches:n})=>{const r=I(t),s=o=>[r,e,o.key,o.namespaces,"list"];return m.useQueries({queries:n.map(o=>({queryKey:s(o),queryFn:async()=>h.List(r,e,o.key,D.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}))})},qt=({pluginID:t,resourceKey:e})=>{const n=I(t),r=[n,"resources",e];return{resourceType:m.useQuery({queryKey:r,queryFn:async()=>h.GetResourceType(n,e),retry:!1})}},Ut=({pluginID:t,connectionID:e})=>{const n=I(t),r=[n,"resources","list",e];return{types:m.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 $t(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Qt="Expected a function",$e="__lodash_hash_undefined__",jt="[object Function]",Wt="[object GeneratorFunction]",Gt="[object Symbol]",Kt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Bt=/^\w*$/,Ht=/^\./,zt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Yt=/[\\^$.*+?()[\]{}|]/g,Jt=/\\(\\)?/g,Zt=/^\[object .+?Constructor\]$/,Xt=typeof Y=="object"&&Y&&Y.Object===Object&&Y,Vt=typeof self=="object"&&self&&self.Object===Object&&self,ge=Xt||Vt||Function("return this")();function en(t,e){return t==null?void 0:t[e]}function tn(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch{}return e}var nn=Array.prototype,rn=Function.prototype,Qe=Object.prototype,ie=ge["__core-js_shared__"],Ee=function(){var t=/[^.]+$/.exec(ie&&ie.keys&&ie.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),je=rn.toString,he=Qe.hasOwnProperty,We=Qe.toString,sn=RegExp("^"+je.call(he).replace(Yt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),_e=ge.Symbol,on=nn.splice,an=Ge(ge,"Map"),H=Ge(Object,"create"),we=_e?_e.prototype:void 0,be=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 cn(){this.__data__=H?H(null):{}}function un(t){return this.has(t)&&delete this.__data__[t]}function ln(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 dn(t){var e=this.__data__;return H?e[t]!==void 0:he.call(e,t)}function fn(t,e){var n=this.__data__;return n[t]=H&&e===void 0?$e:e,this}W.prototype.clear=cn;W.prototype.delete=un;W.prototype.get=ln;W.prototype.has=dn;W.prototype.set=fn;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 pn(){this.__data__=[]}function yn(t){var e=this.__data__,n=ee(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():on.call(e,n,1),!0}function gn(t){var e=this.__data__,n=ee(e,t);return n<0?void 0:e[n][1]}function hn(t){return ee(this.__data__,t)>-1}function mn(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=pn;K.prototype.delete=yn;K.prototype.get=gn;K.prototype.has=hn;K.prototype.set=mn;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 Sn(){this.__data__={hash:new W,map:new(an||K),string:new W}}function Cn(t){return te(this,t).delete(t)}function En(t){return te(this,t).get(t)}function _n(t){return te(this,t).has(t)}function wn(t,e){return te(this,t).set(t,e),this}G.prototype.clear=Sn;G.prototype.delete=Cn;G.prototype.get=En;G.prototype.has=_n;G.prototype.set=wn;function ee(t,e){for(var n=t.length;n--;)if(Dn(t[n][0],e))return n;return-1}function bn(t,e){e=Fn(e,t)?[e]:xn(e);for(var n=0,r=e.length;t!=null&&n<r;)t=t[Tn(e[n++])];return n&&n==r?t:void 0}function vn(t){if(!Be(t)||On(t))return!1;var e=Mn(t)||tn(t)?sn:Zt;return e.test(An(t))}function Rn(t){if(typeof t=="string")return t;if(Se(t))return be?be.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function xn(t){return Ke(t)?t:In(t)}function te(t,e){var n=t.__data__;return Pn(e)?n[typeof e=="string"?"string":"hash"]:n.map}function Ge(t,e){var n=en(t,e);return vn(n)?n:void 0}function Fn(t,e){if(Ke(t))return!1;var n=typeof t;return n=="number"||n=="symbol"||n=="boolean"||t==null||Se(t)?!0:Bt.test(t)||!Kt.test(t)||e!=null&&t in Object(e)}function Pn(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function On(t){return!!Ee&&Ee in t}var In=me(function(t){t=kn(t);var e=[];return Ht.test(t)&&e.push(""),t.replace(zt,function(n,r,s,i){e.push(s?i.replace(Jt,"$1"):r||n)}),e});function Tn(t){if(typeof t=="string"||Se(t))return t;var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function An(t){if(t!=null){try{return je.call(t)}catch{}try{return t+""}catch{}}return""}function me(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(me.Cache||G),n}me.Cache=G;function Dn(t,e){return t===e||t!==t&&e!==e}var Ke=Array.isArray;function Mn(t){var e=Be(t)?We.call(t):"";return e==jt||e==Wt}function Be(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}function Nn(t){return!!t&&typeof t=="object"}function Se(t){return typeof t=="symbol"||Nn(t)&&We.call(t)==Gt}function kn(t){return t==null?"":Rn(t)}function Ln(t,e,n){var r=t==null?void 0:bn(t,e);return r===void 0?n:r}var qn=Ln;const J=$t(qn);function He(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 ze(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 y=d.useCallback(()=>{const f=a.current;if(a.current=[],c.current=null,l.current=null,!(f.length===0||!r)){t.setQueryData(e,g=>He(g,f,r));for(const g of f)(g.type==="ADD"||g.type==="UPDATE")&&t.setQueryData(n(g.payload.id,g.payload.namespace),{result:g.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(y,o):l.current=requestAnimationFrame(y))},[y,o]);return d.useEffect(()=>()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),l.current!==null&&(cancelAnimationFrame(l.current),l.current=null)},[]),p}const Un=({pluginID:t,connectionID:e,resourceKey:n,idAccessor:r,namespaces:s})=>{const i=I(t),o=m.useQueryClient(),{showSnackbar:a}=U(),c=d.useMemo(()=>s??[],[s]),l=d.useMemo(()=>[i,e,n,c,"list"],[i,e,n,c]),u=d.useCallback((R,C)=>[i,e,n,C,R],[i,e,n]),{mutateAsync:y}=m.useMutation({mutationFn:async R=>h.Create(i,e,n,D.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 S=E?`Resource ${E} created`:"Resource created";a(S,"success"),await o.invalidateQueries({queryKey:l})},onError:N(a,"Failed to create resource")}),p=m.useQuery({queryKey:l,queryFn:async()=>h.List(i,e,n,D.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:c})),placeholderData:(R,C)=>R,retry:!1}),[f,g]=d.useState(P.WatchStateIdle);d.useEffect(()=>T.On(`${i}/${e}/watch/STATE`,C=>{const E=C.data;E.resourceKey===n&&g(E.state)}),[i,e,n]);const w=ze(o,l,u,r,f);return d.useEffect(()=>{if(!r)return;h.SubscribeResource(i,e,n);const R=T.On(`${i}/${e}/${n}/ADD`,S=>w({type:"ADD",payload:S.data})),C=T.On(`${i}/${e}/${n}/UPDATE`,S=>w({type:"UPDATE",payload:S.data})),E=T.On(`${i}/${e}/${n}/DELETE`,S=>w({type:"DELETE",payload:S.data}));return()=>{R(),C(),E(),h.UnsubscribeResource(i,e,n)}},[i,e,n,w]),{resources:p,create:y,watchState:f,isSyncing:f===P.WatchStateSyncing,isSynced:f===P.WatchStateSynced,watchError:f===P.WatchStateError}},$n=({pluginID:t})=>{const e=I(t),{showSnackbar:n}=U(),r=m.useMutation({mutationFn:async({opts:o,input:a})=>h.Create(e,o.connectionID,o.resourceKey,D.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=m.useMutation({mutationFn:async({opts:o,input:a})=>h.Update(e,o.connectionID,o.resourceKey,D.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=m.useMutation({mutationFn:async({opts:o,input:a})=>h.Delete(e,o.connectionID,o.resourceKey,D.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=I(t),i=m.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}},jn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=I(t),s=m.useQueryClient(),{showSnackbar:i}=U(),o=m.useMutation({mutationFn:async({actionID:a,id:c="",namespace:l="",params:u={}})=>h.ExecuteAction(r,e,n,a,D.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}},Wn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=I(t),s=m.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}},Gn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=I(t),s=m.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 g={...f.resources,[p.resourceKey]:p.state},w={...f.resourceCounts,[p.resourceKey]:p.resourceCount};let R=0,C=0;for(const E of Object.values(g))E===P.WatchStateSynced&&R++,(E===P.WatchStateError||E===P.WatchStateFailed)&&C++;return{...f,resources:g,resourceCounts:w,totalResources:Object.keys(g).length,syncedCount:R,errorCount:C}})},[s,r,e]),l=m.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 g=0,w=0;for(const[C,E]of Object.entries(p.resources??{}))E!=null&&(f[C]=E,E===P.WatchStateSynced&&g++,E===P.WatchStateError&&w++);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:g,errorCount:w}},enabled:n&&!!r&&!!e,refetchInterval:p=>{const f=p.state.data;if(!f||f.totalResources===0)return 3e3;let g=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)&&g++;return g>=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 g=f.data;a.current?c(g):o.current.push(g)});return()=>{p(),a.current=!1,o.current=[]}},[r,e,n,c]);const u=l.data;let y=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)&&y++;return{summary:l,getResourceState:p=>u==null?void 0:u.resources[p],isFullySynced:u?u.totalResources>0&&y===u.totalResources:!1,syncProgress:u&&u.totalResources>0?y/u.totalResources:0,errorCount:(u==null?void 0:u.errorCount)??0}},Kn=()=>{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,y=pe(u),p=qe(n.current,u),f=ue(p);if(e(g=>{const w=new Map(g);return w.set(y,f),w}),r.current.has(y)&&(clearTimeout(r.current.get(y)),r.current.delete(y)),Z(f)){const g=setTimeout(()=>{e(w=>{const R=new Map(w);return R.delete(y),R}),n.current.delete(y),r.current.delete(y)},5e3);r.current.set(y,g)}},[]);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=ke(i),a=i.find(l=>!Z(l))??i[0]??null,c=Le(i);return{syncs:i,hasSyncing:o,primarySync:a,aggregateProgress:c}},Ye=()=>{const t=d.useContext(fe);if(!t)throw new Error("useOperations must be used within an OperationsProvider");return t},Bn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=I(t),{showSnackbar:s}=U(),{addOperation:i,updateOperation:o}=Ye(),a=d.useRef([]);return d.useEffect(()=>()=>{a.current.forEach(l=>l())},[]),{startStreamAction:d.useCallback(async({actionID:l,id:u,namespace:y,label:p,params:f={}})=>{try{const g=await h.StreamAction(r,e,n,l,D.ActionInput.createFrom({id:u,namespace:y,params:f}));i({id:g,label:p,resourceKey:n,resourceName:u,namespace:y,connectionID:e,status:"running",startedAt:Date.now()});const w=`action/stream/${g}`,R=T.On(w,C=>{var S,x,F,b;const E=C.data;switch(E.type){case"progress":{const _=E.data??{};o(g,{message:_.message,progress:_.ready!==void 0&&_.desired!==void 0?{ready:_.ready,desired:_.desired}:void 0});break}case"complete":o(g,{status:"completed",message:((S=E.data)==null?void 0:S.message)??"Completed",completedAt:Date.now()}),s(((x=E.data)==null?void 0:x.message)??p+" completed","success"),T.Off(w);break;case"error":o(g,{status:"error",message:((F=E.data)==null?void 0:F.message)??"Failed",completedAt:Date.now()}),s(((b=E.data)==null?void 0:b.message)??p+" failed","error"),T.Off(w);break}});return a.current.push(()=>{R(),T.Off(w)}),g}catch(g){throw j(s,g,`Failed to start "${l}"`),g}},[r,e,n,i,o,s])}};function Je(t,e){return`${t}/${e}/graph/CHANGED`}function ne(t,e,n,r){const s=m.useQueryClient(),i=d.useRef(n);i.current=n;const o=JSON.stringify(n);d.useEffect(()=>{if(!r||!t||!e)return;const a=T.On(Je(t,e),()=>{s.invalidateQueries({queryKey:i.current,exact:!0})});return()=>{a()}},[s,t,e,o,r])}const Hn={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 zn(t,e){const n=Hn[t];if(n)return n[e];const r=t.replace(/_/g," ");return e==="outgoing"?r:`${r} (incoming)`}function Yn(t,e){return t.pluginId===e.pluginId&&t.connectionId===e.connectionId&&t.resourceKey===e.resourceKey&&t.id===e.id&&(t.namespace??"")===(e.namespace??"")}function Ze(t,e){return e.map(n=>{const r=Yn(n.source,t);return{resource:r?n.target:n.source,type:n.type,direction:r?"outgoing":"incoming",label:n.label}})}const Jn=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",direction:i="both",relationshipType:o,enabled:a=!0,refetchInterval:c=!1})=>{const l=I(t),u=["RESOURCE_RELATED",l,e,n,s,r,i,o??null],y=a&&!!l&&!!e&&!!n&&!!r;ne(l,e,u,y);const p=m.useQuery({queryKey:u,queryFn:async()=>h.GetRelated(l,e,n,s,r,i,o??null),enabled:y,refetchInterval:c}),f={pluginId:l,connectionId:e,resourceKey:n,id:r,namespace:s},g=p.data??[];return{related:Ze(f,g),edges:g,isLoading:p.isLoading,isFetching:p.isFetching,error:p.error,refetch:p.refetch}},Zn=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",maxDepth:i=3,enabled:o=!0,refetchInterval:a=!1})=>{const c=I(t),l=["RESOURCE_DEPENDENCY_TREE",c,e,n,s,r,i],u=o&&!!c&&!!e&&!!n&&!!r;ne(c,e,l,u);const y=m.useQuery({queryKey:l,queryFn:async()=>h.GetDependencyTree(c,e,n,s,r,i),enabled:u,refetchInterval:a});return{tree:y.data??null,isLoading:y.isLoading,isFetching:y.isFetching,error:y.error,refetch:y.refetch}},Xn=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",upDepth:i=2,downDepth:o=3,enabled:a=!0})=>{const c=I(t),l=["RESOURCE_GRAPH",c,e,n,s,r,i,o],u=a&&!!c&&!!e&&!!n&&!!r;ne(c,e,l,u);const y=m.useQuery({queryKey:l,queryFn:async()=>h.GetSubgraph(c,e,n,s,r,i,o),enabled:u});return{graph:y.data??null,isLoading:y.isLoading,isFetching:y.isFetching,error:y.error,refetch:y.refetch}},Vn=()=>{const t=d.useContext(de);if(!t)throw new Error("useSettings must be used within a SettingsProvider");return t},er=({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(()=>A.jsx(B.Link,{style:{textDecoration:"none",color:"inherit"},...n,to:s}),[n,s])};function tr(){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 nr{}class rr{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 A.jsx(this.root,{});const e=B.createMemoryRouter(this._routes||[]);return A.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 Xe=(t=>(t.MISSING_MANIFEST="MISSING_MANIFEST",t.MISSING_PLUGIN="MISSING_PLUGIN",t.MISSING_ENTRYPOINT="MISSING_ENTRYPOINT",t))(Xe||{});const sr=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]}},or=t=>!t||t==="core"?"Core":t.charAt(0).toUpperCase()+t.slice(1);exports.ALL_SESSIONS_KEY=Q;exports.BottomDrawerContext=Fe;exports.ConfirmationModalContext=Oe;exports.ErrorTypes=q;exports.ExtensionPointRegistry=ht;exports.ExtensionPointStore=De;exports.ExtensionProvider=gt;exports.Link=er;exports.OperationsContext=fe;exports.OperationsProvider=ut;exports.PluginContext=X;exports.PluginContextProvider=ot;exports.PluginErrorCode=Xe;exports.PluginWindow=rr;exports.PluginWindowRootProps=nr;exports.RightDrawerContext=Pe;exports.SettingsContext=de;exports.SettingsProvider=at;exports.SnackbarProvider=St;exports.WatchState=P;exports.actionToSnackbar=ve;exports.applyBatch=He;exports.connectionListQueryKey=Ne;exports.createErrorHandler=N;exports.defaultState=xe;exports.formatGroup=or;exports.graphChangedEvent=Je;exports.isCancelledError=le;exports.parseAppError=$;exports.parseResourceKey=sr;exports.relationshipLabel=zn;exports.showAppError=j;exports.toRelatedResources=Ze;exports.useActiveSyncs=Kn;exports.useBottomDrawer=ye;exports.useConfirmationModal=Dt;exports.useConnection=Ct;exports.useConnectionNamespaces=_t;exports.useConnectionStatus=wt;exports.useConnections=Et;exports.useDependencyTree=Zn;exports.useEditorSchemas=Wn;exports.useEventBatcher=ze;exports.useExec=xt;exports.useExecuteAction=jn;exports.useExtensionPoint=yt;exports.useExtensionRegistry=Ae;exports.useLogs=Ft;exports.useMetricProviders=Pt;exports.useMetricProvidersForResource=Ue;exports.useMetricStream=It;exports.useOperations=Ye;exports.usePluginContext=V;exports.usePluginData=vt;exports.usePluginRouter=tr;exports.usePluginSettings=it;exports.usePortForwardSessions=Tt;exports.useRefetchOnGraphChange=ne;exports.useRelatedResources=Jn;exports.useResolvedPluginId=I;exports.useResource=Mt;exports.useResourceActions=Qn;exports.useResourceAreaComponent=Nt;exports.useResourceGraph=Xn;exports.useResourceGroups=kt;exports.useResourceMetrics=Ot;exports.useResourceMutations=$n;exports.useResourcePortForwarder=At;exports.useResourceSearch=Lt;exports.useResourceType=qt;exports.useResourceTypes=Ut;exports.useResources=Un;exports.useRightDrawer=Rt;exports.useSettings=Vn;exports.useSnackbar=U;exports.useStreamAction=Bn;exports.useWatchState=Gn;
|