openk8s 1.0.1 → 1.0.3

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.
Files changed (48) hide show
  1. package/README.md +1 -1
  2. package/package.json +5 -2
  3. package/src/app/__tests__/app-state.test.ts +376 -0
  4. package/src/app/__tests__/components/inspector-tokens.test.ts +101 -0
  5. package/src/app/__tests__/utils.test.ts +358 -0
  6. package/src/app/app-actions.ts +262 -0
  7. package/src/app/app-state.ts +16 -263
  8. package/src/app/app.tsx +22 -170
  9. package/src/app/components/detail-sections.tsx +131 -0
  10. package/src/app/components/footer.tsx +52 -0
  11. package/src/app/components/header.tsx +37 -0
  12. package/src/app/components/inspector-tokens.ts +93 -0
  13. package/src/app/components/inspector.tsx +3 -239
  14. package/src/app/components/resource-rows.tsx +5 -1
  15. package/src/app/hooks/keyboard/filter-handlers.ts +40 -0
  16. package/src/app/hooks/keyboard/global-handlers.ts +134 -0
  17. package/src/app/hooks/keyboard/helm-handlers.ts +104 -0
  18. package/src/app/hooks/keyboard/logs-handlers.ts +80 -0
  19. package/src/app/hooks/keyboard/navigation-handlers.ts +103 -0
  20. package/src/app/hooks/keyboard/overlay-handlers.ts +138 -0
  21. package/src/app/hooks/keyboard/port-forward-handlers.ts +71 -0
  22. package/src/app/hooks/keyboard/shell-edit-handlers.ts +253 -0
  23. package/src/app/hooks/use-app-keyboard.ts +56 -621
  24. package/src/app/hooks/use-app-side-effects.ts +1 -1
  25. package/src/app/hooks/use-clipboard.ts +1 -1
  26. package/src/app/hooks/use-data-fetching.ts +2 -11
  27. package/src/app/hooks/use-log-stream.ts +1 -1
  28. package/src/app/hooks/use-port-forward.ts +1 -1
  29. package/src/app/use-footer-hints.ts +107 -0
  30. package/src/index.tsx +4 -0
  31. package/src/lib/k8s/__tests__/k8s-format.test.ts +42 -0
  32. package/src/lib/k8s/__tests__/resource-detail-builder.test.ts +215 -0
  33. package/src/lib/k8s/__tests__/resource-parser.test.ts +455 -0
  34. package/src/lib/k8s/detail-builders/event-builder.ts +21 -0
  35. package/src/lib/k8s/detail-builders/hpa-cronjob-builder.ts +63 -0
  36. package/src/lib/k8s/detail-builders/node-builder.ts +41 -0
  37. package/src/lib/k8s/detail-builders/overview-builder.ts +103 -0
  38. package/src/lib/k8s/detail-builders/pod-builder.ts +140 -0
  39. package/src/lib/k8s/detail-builders/rbac-builder.ts +57 -0
  40. package/src/lib/k8s/resource-detail-builder.ts +22 -502
  41. package/src/lib/kubectl/__tests__/kubectl-helpers.test.ts +343 -0
  42. package/src/lib/kubectl/__tests__/metrics-utils.test.ts +84 -0
  43. package/src/lib/kubectl/__tests__/spawn-utils.test.ts +56 -0
  44. package/src/lib/kubectl/kubectl-helpers.ts +246 -0
  45. package/src/lib/kubectl/kubectl-service.ts +77 -565
  46. package/src/lib/kubectl/kubectl-types.ts +248 -0
  47. package/src/lib/kubectl/metrics-utils.ts +33 -0
  48. package/src/lib/kubectl/spawn-utils.ts +27 -0
@@ -1,7 +1,7 @@
1
1
  import { useEffect } from "react";
2
2
  import type { ChildProcess } from "node:child_process";
3
3
 
4
- import type { AppAction } from "../app-state";
4
+ import type { AppAction } from "../app-actions";
5
5
  import type { AppState } from "../../lib/k8s/types";
6
6
  import type { ResourceRef } from "../../lib/k8s/types";
7
7
  import { savePersistedState } from "../persistence";
@@ -1,7 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { useCallback } from "react";
3
3
 
4
- import type { AppAction } from "../app-state";
4
+ import type { AppAction } from "../app-actions";
5
5
  import type { NotificationTone } from "../../lib/k8s/types";
6
6
  import { loadError } from "../utils";
7
7
 
@@ -1,7 +1,7 @@
1
1
  import { useEffect, useRef } from "react";
2
2
  import type { Dispatch, SetStateAction } from "react";
3
3
 
4
- import type { AppAction } from "../app-state";
4
+ import type { AppAction } from "../app-actions";
5
5
  import type { AppState } from "../../lib/k8s/types";
6
6
  import type { ResourceKind, ResourceListItem, ResourceRef } from "../../lib/k8s/types";
7
7
  import { defaultNamespace, loadError, nextVisibleResourceName } from "../utils";
@@ -28,8 +28,6 @@ export function useDataFetching(
28
28
  selectedResourceDetailRef.current = state.selectedResourceDetail;
29
29
  const eventsLengthRef = useRef(state.events.length);
30
30
  eventsLengthRef.current = state.events.length;
31
- const lastLoadedResourceKeyRef = useRef<string | undefined>(undefined);
32
-
33
31
  // Clamp visible selection to the filtered list when filter changes
34
32
  useEffect(() => {
35
33
  const nextSelection = nextVisibleResourceName({
@@ -168,8 +166,6 @@ export function useDataFetching(
168
166
  state.kubectlAvailable,
169
167
  clusterPollTick,
170
168
  manualRefreshNonce,
171
- state.activeNamespace,
172
- state.selectedKind,
173
169
  ]);
174
170
 
175
171
  // Load the resource list. Bug-fix: removed state.resources.length and state.selectedResourceName
@@ -187,10 +183,7 @@ export function useDataFetching(
187
183
  let cancelled = false;
188
184
 
189
185
  async function loadResources(): Promise<void> {
190
- const resourceKey = `${activeContext}:${activeNamespace}:${activeKind.name}`;
191
- if (lastLoadedResourceKeyRef.current !== resourceKey && resourcesLengthRef.current > 0) {
192
- dispatch({ type: "setResourcesStatus", status: "loading" });
193
- }
186
+ dispatch({ type: "setResourcesStatus", status: "loading" });
194
187
 
195
188
  try {
196
189
  const resources = await kubectl.listResources({
@@ -203,8 +196,6 @@ export function useDataFetching(
203
196
  return;
204
197
  }
205
198
 
206
- lastLoadedResourceKeyRef.current = resourceKey;
207
-
208
199
  const preservedSelection = resources.find(
209
200
  (resource) => resource.ref.name === selectedResourceNameRef.current,
210
201
  )?.ref.name;
@@ -1,7 +1,7 @@
1
1
  import { useEffect, useRef } from "react";
2
2
  import type { ChildProcess } from "node:child_process";
3
3
 
4
- import type { AppAction } from "../app-state";
4
+ import type { AppAction } from "../app-actions";
5
5
  import type { AppState, LoadStatus } from "../../lib/k8s/types";
6
6
  import { loadError } from "../utils";
7
7
  import { KubectlService } from "../../lib/kubectl/kubectl-service";
@@ -1,7 +1,7 @@
1
1
  import { useRef } from "react";
2
2
  import type { ChildProcess } from "node:child_process";
3
3
 
4
- import type { AppAction } from "../app-state";
4
+ import type { AppAction } from "../app-actions";
5
5
  import type { ActivePortForward, ResourceDetail, ResourceRef } from "../../lib/k8s/types";
6
6
  import type { StartPortForwardLifecycleOptions } from "../utils";
7
7
  import { portForwardId, statusLine } from "../utils";
@@ -0,0 +1,107 @@
1
+ import { useMemo } from "react";
2
+
3
+ import { GLYPHS, KEY_HINT, TEXT_MUTED, TEXT_SUBTLE } from "./theme";
4
+ import type { AppState, ActivePortForward, ResourceDetail, ResourceRef } from "../lib/k8s/types";
5
+ import { KubectlService } from "../lib/kubectl/kubectl-service";
6
+
7
+ export function useFooterHints(
8
+ filterMode: boolean,
9
+ state: AppState,
10
+ activeResourceRef: ResourceRef | undefined,
11
+ activeDetail: ResourceDetail | undefined,
12
+ selectedResourcePortForwards: ActivePortForward[],
13
+ deleteTargets: { length: number },
14
+ kubectl: KubectlService,
15
+ ): [string, string][] {
16
+ return useMemo((): [string, string][] => {
17
+ if (filterMode) {
18
+ return [
19
+ [GLYPHS.enter, "confirm"],
20
+ [GLYPHS.esc, "cancel"],
21
+ ["^U", "clear"],
22
+ ];
23
+ }
24
+
25
+ const isHelm = activeResourceRef?.kind.toLowerCase() === "helmreleases";
26
+ const hasResource = Boolean(activeResourceRef);
27
+ const hasPortForwards =
28
+ (activeDetail?.portForwards?.length ?? 0) > 0 || selectedResourcePortForwards.length > 0;
29
+
30
+ if (state.activePane === "clusters") {
31
+ return [
32
+ [GLYPHS.tab, "panes"],
33
+ ["↑↓", "kinds"],
34
+ ["R", "refresh"],
35
+ ];
36
+ }
37
+
38
+ if (state.activePane === "inspector") {
39
+ return [
40
+ [GLYPHS.tab, "panes"],
41
+ ["←", "back"],
42
+ ["R", "refresh"],
43
+ ];
44
+ }
45
+
46
+ const hints: [string, string][] = [
47
+ [GLYPHS.tab, "panes"],
48
+ ["↑↓", "navigate"],
49
+ ["/", "filter"],
50
+ ["R", "refresh"],
51
+ ];
52
+
53
+ if (!hasResource) return hints;
54
+
55
+ if (isHelm) {
56
+ hints.push(
57
+ ["E", "edit values"],
58
+ ...(deleteTargets.length > 0 ? [["D", "delete"] as [string, string]] : []),
59
+ ["B", "rollback"],
60
+ ["U", "upgrade"],
61
+ );
62
+ } else {
63
+ hints.push(["L", "logs"], ["E", "edit"], ["X", "shell"]);
64
+ if (hasPortForwards) hints.push(["F", "forward"]);
65
+ if (deleteTargets.length > 0) hints.push(["D", "delete"]);
66
+ if (activeResourceRef && kubectl.canScale(activeResourceRef)) hints.push(["⇧S", "scale"]);
67
+ if (activeResourceRef && kubectl.canRolloutRestart(activeResourceRef)) hints.push(["⇧R", "restart"]);
68
+ }
69
+
70
+ return hints;
71
+ }, [
72
+ filterMode,
73
+ state.activePane,
74
+ activeResourceRef,
75
+ activeDetail,
76
+ selectedResourcePortForwards,
77
+ deleteTargets,
78
+ ]);
79
+ }
80
+
81
+ export function useFooterHintRows(
82
+ footerHints: [string, string][],
83
+ terminalWidth: number,
84
+ ): { footerHintsRow1: [string, string][]; footerHintsRow2: [string, string][] } {
85
+ return useMemo(() => {
86
+ const innerWidth = terminalWidth - 4;
87
+ const row1: [string, string][] = [];
88
+ const row2: [string, string][] = [];
89
+ let used1 = 0;
90
+ let used2 = 0;
91
+
92
+ for (const [key, label] of footerHints) {
93
+ const w = key.length + label.length + 3;
94
+ const gap1 = row1.length === 0 ? 0 : 2;
95
+ const gap2 = row2.length === 0 ? 0 : 2;
96
+ if (used1 + gap1 + w <= innerWidth) {
97
+ used1 += gap1 + w;
98
+ row1.push([key, label]);
99
+ } else if (used2 + gap2 + w <= innerWidth) {
100
+ used2 += gap2 + w;
101
+ row2.push([key, label]);
102
+ }
103
+ }
104
+
105
+ return { footerHintsRow1: row1, footerHintsRow2: row2 };
106
+ }, [footerHints, terminalWidth]);
107
+ }
package/src/index.tsx CHANGED
@@ -1,7 +1,11 @@
1
1
  import { createCliRenderer } from "@opentui/core";
2
2
  import { createRoot } from "@opentui/react";
3
+ import { setAbortController } from "./lib/kubectl/spawn-utils";
3
4
  import { App } from "./app/app";
4
5
 
6
+ const abortController = new AbortController();
7
+ setAbortController(abortController);
8
+
5
9
  const renderer = await createCliRenderer({
6
10
  useMouse: true,
7
11
  });
@@ -0,0 +1,42 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { formatAge } from "../k8s-format";
3
+
4
+ describe("formatAge", () => {
5
+ test("returns '-' for undefined", () => {
6
+ expect(formatAge(undefined)).toBe("-");
7
+ });
8
+
9
+ test("returns '-' for empty string", () => {
10
+ expect(formatAge("")).toBe("-");
11
+ });
12
+
13
+ test("returns 'now' for very recent timestamp", () => {
14
+ const result = formatAge(new Date().toISOString());
15
+ expect(result).toBe("now");
16
+ });
17
+
18
+ test("formats minutes", () => {
19
+ const past = new Date(Date.now() - 5 * 60_000).toISOString();
20
+ expect(formatAge(past)).toMatch(/^\d+m$/);
21
+ });
22
+
23
+ test("formats hours", () => {
24
+ const past = new Date(Date.now() - 3 * 3600_000).toISOString();
25
+ expect(formatAge(past)).toMatch(/^\d+h$/);
26
+ });
27
+
28
+ test("formats days", () => {
29
+ const past = new Date(Date.now() - 5 * 86400_000).toISOString();
30
+ expect(formatAge(past)).toMatch(/^\d+d$/);
31
+ });
32
+
33
+ test("handles RFC3339 timestamps from Kubernetes", () => {
34
+ const result = formatAge("2024-01-15T10:30:00Z");
35
+ expect(typeof result).toBe("string");
36
+ expect(result).toMatch(/^\d+[mhd]$/);
37
+ });
38
+
39
+ test("returns '-' for invalid date", () => {
40
+ expect(formatAge("not-a-date")).toBe("-");
41
+ });
42
+ });
@@ -0,0 +1,215 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { buildResourceDetail } from "../resource-detail-builder";
3
+ import type { ResourceKind } from "../types";
4
+
5
+ const defaultKind: ResourceKind = { name: "pods", namespaced: true, shortNames: ["po"] };
6
+
7
+ const metadata = { name: "test-pod", namespace: "default", creationTimestamp: "2024-01-01T00:00:00Z", labels: { app: "test" } };
8
+
9
+ describe("buildResourceDetail", () => {
10
+ test("builds overview section for any resource", () => {
11
+ const detail = buildResourceDetail({
12
+ resourceKind: defaultKind,
13
+ resource: { apiVersion: "v1", kind: "Pod", metadata },
14
+ yaml: "apiVersion: v1\nkind: Pod",
15
+ describe: "Name: test-pod",
16
+ });
17
+
18
+ expect(detail.ref.kind).toBe("Pod");
19
+ expect(detail.ref.name).toBe("test-pod");
20
+ expect(detail.yaml).toContain("apiVersion: v1");
21
+ expect(detail.describe).toContain("Name: test-pod");
22
+ expect(detail.summarySections[0]?.title).toBe("Overview");
23
+ });
24
+
25
+ test("builds pod sections", () => {
26
+ const detail = buildResourceDetail({
27
+ resourceKind: defaultKind,
28
+ resource: {
29
+ apiVersion: "v1",
30
+ kind: "Pod",
31
+ metadata,
32
+ spec: {
33
+ containers: [
34
+ { name: "nginx", image: "nginx:1.25", ports: [{ containerPort: 80 }] },
35
+ ],
36
+ },
37
+ status: { phase: "Running", containerStatuses: [{ name: "nginx", ready: true, restartCount: 0, state: { running: {} } }] },
38
+ },
39
+ yaml: "",
40
+ });
41
+
42
+ expect(detail.containers).toEqual(["nginx"]);
43
+ expect(detail.summarySections.some((s) => s.title === "Containers")).toBe(true);
44
+ expect(detail.summarySections.some((s) => s.title === "Ports")).toBe(true);
45
+ });
46
+
47
+ test("builds HPA sections", () => {
48
+ const detail = buildResourceDetail({
49
+ resourceKind: { name: "horizontalpodautoscalers", namespaced: true, shortNames: ["hpa"] },
50
+ resource: {
51
+ apiVersion: "autoscaling/v2",
52
+ kind: "HorizontalPodAutoscaler",
53
+ metadata,
54
+ spec: { scaleTargetRef: { kind: "Deployment", name: "web" }, minReplicas: 1, maxReplicas: 10 },
55
+ status: { currentReplicas: 3, desiredReplicas: 5 },
56
+ },
57
+ yaml: "",
58
+ });
59
+
60
+ expect(detail.summarySections.some((s) => s.title === "HPA")).toBe(true);
61
+ expect(detail.summaryLines.some((l) => l.includes("minReplicas: 1"))).toBe(true);
62
+ expect(detail.summaryLines.some((l) => l.includes("maxReplicas: 10"))).toBe(true);
63
+ });
64
+
65
+ test("builds CronJob sections", () => {
66
+ const detail = buildResourceDetail({
67
+ resourceKind: { name: "cronjobs", namespaced: true, shortNames: ["cj"] },
68
+ resource: {
69
+ apiVersion: "batch/v1",
70
+ kind: "CronJob",
71
+ metadata,
72
+ spec: { schedule: "*/5 * * * *" },
73
+ status: {},
74
+ },
75
+ yaml: "",
76
+ });
77
+
78
+ expect(detail.summarySections.some((s) => s.title === "CronJob")).toBe(true);
79
+ expect(detail.summaryLines.some((l) => l.includes("schedule"))).toBe(true);
80
+ });
81
+
82
+ test("builds Node sections", () => {
83
+ const detail = buildResourceDetail({
84
+ resourceKind: { name: "nodes", namespaced: false, shortNames: ["no"] },
85
+ resource: {
86
+ apiVersion: "v1",
87
+ kind: "Node",
88
+ metadata: { name: "node-1", creationTimestamp: "2024-01-01T00:00:00Z", labels: {} },
89
+ status: {
90
+ nodeInfo: { kubeletVersion: "v1.28" },
91
+ capacity: { cpu: "4", memory: "16Gi" },
92
+ allocatable: { cpu: "3", memory: "14Gi" },
93
+ },
94
+ spec: {},
95
+ },
96
+ yaml: "",
97
+ });
98
+
99
+ expect(detail.summarySections.some((s) => s.title === "Node Info")).toBe(true);
100
+ expect(detail.summarySections.some((s) => s.title === "Capacity / Allocatable")).toBe(true);
101
+ });
102
+
103
+ test("builds Event sections", () => {
104
+ const detail = buildResourceDetail({
105
+ resourceKind: { name: "events", namespaced: false, shortNames: ["ev"] },
106
+ resource: {
107
+ apiVersion: "v1",
108
+ kind: "Event",
109
+ metadata: { name: "test-event", creationTimestamp: "2024-01-01T00:00:00Z" },
110
+ type: "Warning",
111
+ reason: "BackOff",
112
+ message: "Back-off restarting",
113
+ involvedObject: { kind: "Pod", name: "web", namespace: "default" },
114
+ },
115
+ yaml: "",
116
+ });
117
+
118
+ expect(detail.summarySections.some((s) => s.title === "Event")).toBe(true);
119
+ expect(detail.summaryLines.some((l) => l.includes("BackOff"))).toBe(true);
120
+ });
121
+
122
+ test("builds Role sections", () => {
123
+ const detail = buildResourceDetail({
124
+ resourceKind: { name: "roles", namespaced: true, shortNames: [] },
125
+ resource: {
126
+ apiVersion: "rbac.authorization.k8s.io/v1",
127
+ kind: "Role",
128
+ metadata: { name: "pod-reader", namespace: "default", creationTimestamp: "2024-01-01T00:00:00Z" },
129
+ rules: [
130
+ { apiGroups: [""], resources: ["pods"], verbs: ["get", "watch", "list"] },
131
+ ],
132
+ },
133
+ yaml: "",
134
+ });
135
+
136
+ expect(detail.summarySections.some((s) => s.title === "Rules")).toBe(true);
137
+ });
138
+
139
+ test("builds RoleBinding sections", () => {
140
+ const detail = buildResourceDetail({
141
+ resourceKind: { name: "rolebindings", namespaced: true, shortNames: [] },
142
+ resource: {
143
+ apiVersion: "rbac.authorization.k8s.io/v1",
144
+ kind: "RoleBinding",
145
+ metadata: { name: "admin-binding", namespace: "default", creationTimestamp: "2024-01-01T00:00:00Z" },
146
+ roleRef: { kind: "Role", name: "admin" },
147
+ subjects: [{ kind: "User", name: "jane" }],
148
+ },
149
+ yaml: "",
150
+ });
151
+
152
+ expect(detail.summarySections.some((s) => s.title === "RoleRef")).toBe(true);
153
+ expect(detail.summarySections.some((s) => s.title === "Subjects")).toBe(true);
154
+ });
155
+
156
+ test("builds ServiceAccount sections", () => {
157
+ const detail = buildResourceDetail({
158
+ resourceKind: { name: "serviceaccounts", namespaced: true, shortNames: ["sa"] },
159
+ resource: {
160
+ apiVersion: "v1",
161
+ kind: "ServiceAccount",
162
+ metadata: { name: "default", namespace: "default", creationTimestamp: "2024-01-01T00:00:00Z" },
163
+ secrets: [{ name: "default-token-abc" }],
164
+ },
165
+ yaml: "",
166
+ });
167
+
168
+ expect(detail.summarySections.some((s) => s.title === "Secrets")).toBe(true);
169
+ });
170
+
171
+ test("handles unknown kind gracefully", () => {
172
+ const detail = buildResourceDetail({
173
+ resourceKind: { name: "configmaps", namespaced: true, shortNames: ["cm"] },
174
+ resource: {
175
+ apiVersion: "v1",
176
+ kind: "ConfigMap",
177
+ metadata: { name: "my-config", namespace: "default", creationTimestamp: "2024-01-01T00:00:00Z", labels: {} },
178
+ },
179
+ yaml: "",
180
+ });
181
+
182
+ expect(detail.ref.kind).toBe("ConfigMap");
183
+ expect(detail.summarySections).toHaveLength(1);
184
+ expect(detail.summarySections[0]?.title).toBe("Overview");
185
+ });
186
+
187
+ test("includes port forwards for pod resources", () => {
188
+ const detail = buildResourceDetail({
189
+ resourceKind: defaultKind,
190
+ resource: {
191
+ apiVersion: "v1",
192
+ kind: "Pod",
193
+ metadata,
194
+ spec: { containers: [{ name: "nginx", ports: [{ containerPort: 80 }] }] },
195
+ status: { phase: "Running" },
196
+ },
197
+ yaml: "",
198
+ });
199
+
200
+ expect(detail.portForwards).toBeDefined();
201
+ expect(detail.portForwards).toHaveLength(1);
202
+ expect(detail.portForwards![0]?.remotePort).toBe(80);
203
+ });
204
+
205
+ test("handles missing metadata gracefully", () => {
206
+ const detail = buildResourceDetail({
207
+ resourceKind: defaultKind,
208
+ resource: { kind: "Pod" },
209
+ yaml: "",
210
+ });
211
+
212
+ expect(detail.ref.name).toBe("unknown");
213
+ expect(detail.ref.namespace).toBeUndefined();
214
+ });
215
+ });