From 807f98ed1ba92ecd147979c92a9012c4a5438c09 Mon Sep 17 00:00:00 2001 From: Sebastian Malton Date: Wed, 5 Apr 2023 10:56:23 -0400 Subject: [PATCH] Persist apiVersion when editing resources in monaco (#4406) * Persist apiVersion when editing resources in monaco - Use a new custom k8slens prefixed label - Means that users aren't surprised when they use lens to update a resource to a new apiVersionWithGroup - Doesn't touch the versions in the stores Signed-off-by: Sebastian Malton * Fix lint Signed-off-by: Sebastian Malton * fix: Fix lint issues Signed-off-by: Sebastian Malton * chore: make lint not bail on failure Signed-off-by: Sebastian Malton * chore: Run lint:fix on all files Signed-off-by: Sebastian Malton --------- Signed-off-by: Sebastian Malton --- package.json | 2 +- .../src/invoke-shortcut.injectable.ts | 39 +++--- .../src/keyboard-shortcut-listener.tsx | 5 +- .../src/keyboard-shortcuts.test.tsx | 3 +- .../core/src/common/k8s-api/kube-api-parse.ts | 20 ++- packages/core/src/common/k8s-api/kube-api.ts | 2 +- .../core/src/common/k8s-api/kube-object.ts | 42 ++----- .../edit-namespace-from-new-tab.test.tsx.snap | 2 + .../edit-namespace-from-new-tab.test.tsx | 41 +++++-- ...ls.test.tsx.snap => details.test.tsx.snap} | 0 .../{hpa-details.scss => details.scss} | 1 + ...{hpa-details.test.tsx => details.test.tsx} | 28 ++--- .../{hpa-details.tsx => details.tsx} | 10 +- ...-hpa-metric-name.ts => get-metric-name.ts} | 0 ...njectable.ts => get-metrics.injectable.ts} | 6 +- .../index.ts | 4 +- .../{hpa.scss => list-view.scss} | 0 .../{hpa.tsx => list-view.tsx} | 4 +- ...1-metric-parser.ts => metric-parser-v1.ts} | 0 ...2-metric-parser.ts => metric-parser-v2.ts} | 0 ...-metrics.test.ts => metric-parser.test.ts} | 12 +- ...table.ts => route-component.injectable.ts} | 2 +- ...table.tsx => sidebar-items.injectable.tsx} | 0 .../call-for-resource.injectable.ts | 27 ++-- .../edit-resource-model.injectable.tsx | 116 ++++++++++++------ .../components/dock/edit-resource/view.tsx | 6 +- ...l-pod-autoscaler-detail-item.injectable.ts | 4 +- .../monaco-editor/monaco-editor.tsx | 8 +- .../eslint-config/prettier-config.json | 2 +- .../start-application.injectable.ts | 4 +- .../start-electron-application.injectable.ts | 7 +- ...rting-of-electron-main-application.test.ts | 5 +- .../feature-core/src/deregister-feature.ts | 12 +- .../src/feature-dependencies.test.ts | 16 +-- .../feature-core/src/register-feature.ts | 10 +- .../agnostic/src/features/actual/index.ts | 10 +- .../listening-of-channels.injectable.ts | 12 +- ...essage-channel-listener-injection-token.ts | 16 +-- ...essage-channel-listener-injection-token.ts | 9 +- ...equest-channel-listener-injection-token.ts | 12 +- .../actual/request/get-request-channel.ts | 4 +- ...equest-channel-listener-injection-token.ts | 5 +- .../request-from-channel-injection-token.ts | 10 +- .../src/listening-of-requests.test.ts | 4 +- .../messaging/computed-channel/index.ts | 5 +- .../computed-channel.injectable.ts | 14 +-- .../computed-channel.test.tsx | 51 ++------ .../enlist-message-channel-listener.test.ts | 5 +- .../request-from-channel.injectable.ts | 10 +- ...allow-communication-listener.injectable.ts | 4 +- ...llow-communication-to-iframe.injectable.ts | 4 +- .../enlist-message-channel-listener.test.ts | 5 +- .../get-message-bridge-fake.test.ts | 38 ++---- .../get-message-bridge-fake.ts | 6 +- .../react-application/react-application.tsx | 4 +- .../react-testing-library-discovery/index.ts | 7 +- .../src/discovery-of-html-elements.ts | 20 +-- 57 files changed, 295 insertions(+), 400 deletions(-) rename packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/__snapshots__/{hpa-details.test.tsx.snap => details.test.tsx.snap} (100%) rename packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/{hpa-details.scss => details.scss} (99%) rename packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/{hpa-details.test.tsx => details.test.tsx} (92%) rename packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/{hpa-details.tsx => details.tsx} (93%) rename packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/{get-hpa-metric-name.ts => get-metric-name.ts} (100%) rename packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/{get-hpa-metrics.injectable.ts => get-metrics.injectable.ts} (93%) rename packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/{hpa.scss => list-view.scss} (100%) rename packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/{hpa.tsx => list-view.tsx} (97%) rename packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/{hpa-v1-metric-parser.ts => metric-parser-v1.ts} (100%) rename packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/{hpa-v2-metric-parser.ts => metric-parser-v2.ts} (100%) rename packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/{horizontal-pod-autoscaler-metrics.test.ts => metric-parser.test.ts} (99%) rename packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/{horizontal-pod-autoscalers-route-component.injectable.ts => route-component.injectable.ts} (94%) rename packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/{horizontal-pod-auto-scalers-sidebar-items.injectable.tsx => sidebar-items.injectable.tsx} (100%) diff --git a/package.json b/package.json index 3bbf863063..2f9a957217 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,7 @@ "postdev": "lerna watch -- lerna run build --stream --scope \\$LERNA_PACKAGE_NAME", "prestart-dev": "cd packages/open-lens && rimraf static/build/ && npm run build:tray-icons && npm run download:binaries", "start-dev": "lerna run start", - "lint": "lerna run lint --stream", + "lint": "lerna run lint --stream --no-bail", "lint:fix": "lerna run lint:fix --stream", "mkdocs:serve-local": "docker build -t mkdocs-serve-local:latest mkdocs/ && docker run --rm -it -p 8000:8000 -v ${PWD}:/docs mkdocs-serve-local:latest", "mkdocs:verify": "docker build -t mkdocs-serve-local:latest mkdocs/ && docker run --rm -v ${PWD}:/docs mkdocs-serve-local:latest build --strict", diff --git a/packages/business-features/keyboard-shortcuts/src/invoke-shortcut.injectable.ts b/packages/business-features/keyboard-shortcuts/src/invoke-shortcut.injectable.ts index 5b0c324203..ecab52138b 100644 --- a/packages/business-features/keyboard-shortcuts/src/invoke-shortcut.injectable.ts +++ b/packages/business-features/keyboard-shortcuts/src/invoke-shortcut.injectable.ts @@ -1,11 +1,7 @@ import { pipeline } from "@ogre-tools/fp"; import { filter, isString } from "lodash/fp"; import { getInjectable } from "@ogre-tools/injectable"; -import { - Binding, - KeyboardShortcut, - keyboardShortcutInjectionToken, -} from "./keyboard-shortcut-injection-token"; +import { Binding, KeyboardShortcut, keyboardShortcutInjectionToken } from "./keyboard-shortcut-injection-token"; import platformInjectable from "./platform.injectable"; export type InvokeShortcut = (event: KeyboardEvent) => void; @@ -46,29 +42,26 @@ const toBindingWithDefaults = (binding: Binding) => ...binding, }; -const toShortcutsWithMatchingBinding = - (event: KeyboardEvent, platform: string) => (shortcut: KeyboardShortcut) => { - const binding = toBindingWithDefaults(shortcut.binding); +const toShortcutsWithMatchingBinding = (event: KeyboardEvent, platform: string) => (shortcut: KeyboardShortcut) => { + const binding = toBindingWithDefaults(shortcut.binding); - const shiftModifierMatches = binding.shift === event.shiftKey; - const altModifierMatches = binding.altOrOption === event.altKey; + const shiftModifierMatches = binding.shift === event.shiftKey; + const altModifierMatches = binding.altOrOption === event.altKey; - const isMac = platform === "darwin"; + const isMac = platform === "darwin"; - const ctrlModifierMatches = - binding.ctrl === event.ctrlKey || (!isMac && binding.ctrlOrCommand === event.ctrlKey); + const ctrlModifierMatches = binding.ctrl === event.ctrlKey || (!isMac && binding.ctrlOrCommand === event.ctrlKey); - const metaModifierMatches = - binding.meta === event.metaKey || (isMac && binding.ctrlOrCommand === event.metaKey); + const metaModifierMatches = binding.meta === event.metaKey || (isMac && binding.ctrlOrCommand === event.metaKey); - return ( - event.code === binding.code && - shiftModifierMatches && - ctrlModifierMatches && - altModifierMatches && - metaModifierMatches - ); - }; + return ( + event.code === binding.code && + shiftModifierMatches && + ctrlModifierMatches && + altModifierMatches && + metaModifierMatches + ); +}; const invokeShortcutInjectable = getInjectable({ id: "invoke-shortcut", diff --git a/packages/business-features/keyboard-shortcuts/src/keyboard-shortcut-listener.tsx b/packages/business-features/keyboard-shortcuts/src/keyboard-shortcut-listener.tsx index 5f2479d059..5dad663129 100644 --- a/packages/business-features/keyboard-shortcuts/src/keyboard-shortcut-listener.tsx +++ b/packages/business-features/keyboard-shortcuts/src/keyboard-shortcut-listener.tsx @@ -26,10 +26,7 @@ const NonInjectedKeyboardShortcutListener = ({ return <>{children}; }; -export const KeyboardShortcutListener = withInjectables< - Dependencies, - KeyboardShortcutListenerProps ->( +export const KeyboardShortcutListener = withInjectables( NonInjectedKeyboardShortcutListener, { diff --git a/packages/business-features/keyboard-shortcuts/src/keyboard-shortcuts.test.tsx b/packages/business-features/keyboard-shortcuts/src/keyboard-shortcuts.test.tsx index d2bbfb85a4..3631a4fa98 100644 --- a/packages/business-features/keyboard-shortcuts/src/keyboard-shortcuts.test.tsx +++ b/packages/business-features/keyboard-shortcuts/src/keyboard-shortcuts.test.tsx @@ -175,8 +175,7 @@ describe("keyboard-shortcuts", () => { shouldCallCallback: true, }, { - scenario: - "given shortcut with shift modifier, when shortcut is pressed, calls the callback", + scenario: "given shortcut with shift modifier, when shortcut is pressed, calls the callback", binding: { shift: true, code: "F1" }, keyboard: "{Shift>}[F1]", diff --git a/packages/core/src/common/k8s-api/kube-api-parse.ts b/packages/core/src/common/k8s-api/kube-api-parse.ts index 2bb397a8be..522e2812b8 100644 --- a/packages/core/src/common/k8s-api/kube-api-parse.ts +++ b/packages/core/src/common/k8s-api/kube-api-parse.ts @@ -109,7 +109,25 @@ export function parseKubeApi(path: string): IKubeApiParsed { }; } -export function createKubeApiURL({ apiPrefix = "/apis", resource, apiVersion, name, namespace }: IKubeApiLinkRef): string { +function isIKubeApiParsed(refOrParsed: IKubeApiLinkRef | IKubeApiParsed): refOrParsed is IKubeApiParsed { + return "apiGroup" in refOrParsed; +} + +export function createKubeApiURL(linkRef: IKubeApiLinkRef): string; +export function createKubeApiURL(linkParsed: IKubeApiParsed): string; + +export function createKubeApiURL(ref: IKubeApiLinkRef | IKubeApiParsed): string { + if (isIKubeApiParsed(ref)) { + return createKubeApiURL({ + apiPrefix: ref.apiPrefix, + resource: ref.resource, + name: ref.name, + namespace: ref.namespace, + apiVersion: `${ref.apiGroup}/${ref.apiVersion}`, + }); + } + + const { apiPrefix = "/apis", resource, apiVersion, name, namespace } = ref; const parts = [apiPrefix, apiVersion]; if (namespace) { diff --git a/packages/core/src/common/k8s-api/kube-api.ts b/packages/core/src/common/k8s-api/kube-api.ts index c5ed03abad..cf9d8f15a7 100644 --- a/packages/core/src/common/k8s-api/kube-api.ts +++ b/packages/core/src/common/k8s-api/kube-api.ts @@ -193,7 +193,7 @@ export interface KubeApiWatchOptions = { +export const patchTypeHeaders: Record = { "merge": "application/merge-patch+json", "json": "application/json-patch+json", "strategic": "application/strategic-merge-patch+json", diff --git a/packages/core/src/common/k8s-api/kube-object.ts b/packages/core/src/common/k8s-api/kube-object.ts index 1feb028aff..a45d5c415f 100644 --- a/packages/core/src/common/k8s-api/kube-object.ts +++ b/packages/core/src/common/k8s-api/kube-object.ts @@ -437,6 +437,19 @@ const resourceApplierAnnotationsForFiltering = [ const filterOutResourceApplierAnnotations = (label: string) => !resourceApplierAnnotationsForFiltering.some(key => label.startsWith(key)); +export interface RawKubeObject< + Metadata extends KubeObjectMetadata = KubeObjectMetadata, + Status = Record, + Spec = Record, +> { + apiVersion: string; + kind: string; + metadata: Metadata; + status?: Status; + spec?: Spec; + managedFields?: any; +} + export class KubeObject< Metadata extends KubeObjectMetadata = KubeObjectMetadata, Status = unknown, @@ -538,23 +551,6 @@ export class KubeObject< return Object.entries(labels).map(([name, value]) => `${name}=${value}`); } - /** - * These must be RFC6902 compliant paths - */ - private static readonly nonEditablePathPrefixes = [ - "/metadata/managedFields", - "/status", - ]; - private static readonly nonEditablePaths = new Set([ - "/apiVersion", - "/kind", - "/metadata/name", - "/metadata/selfLink", - "/metadata/resourceVersion", - "/metadata/uid", - ...KubeObject.nonEditablePathPrefixes, - ]); - constructor(data: KubeJsonApiData) { if (typeof data !== "object") { throw new TypeError(`Cannot create a KubeObject from ${typeof data}`); @@ -684,18 +680,6 @@ export class KubeObject< * @deprecated use KubeApi.patch instead */ async patch(patch: Patch): Promise { - for (const op of patch) { - if (KubeObject.nonEditablePaths.has(op.path)) { - throw new Error(`Failed to update ${this.kind}: JSON pointer ${op.path} has been modified`); - } - - for (const pathPrefix of KubeObject.nonEditablePathPrefixes) { - if (op.path.startsWith(`${pathPrefix}/`)) { - throw new Error(`Failed to update ${this.kind}: Child JSON pointer of ${op.path} has been modified`); - } - } - } - const di = getLegacyGlobalDiForExtensionApi(); const requestKubeObjectPatch = di.inject(requestKubeObjectPatchInjectable); const result = await requestKubeObjectPatch(this.getName(), this.kind, this.getNs(), patch); diff --git a/packages/core/src/features/cluster/namespaces/__snapshots__/edit-namespace-from-new-tab.test.tsx.snap b/packages/core/src/features/cluster/namespaces/__snapshots__/edit-namespace-from-new-tab.test.tsx.snap index 832ee400c8..266fef88c4 100644 --- a/packages/core/src/features/cluster/namespaces/__snapshots__/edit-namespace-from-new-tab.test.tsx.snap +++ b/packages/core/src/features/cluster/namespaces/__snapshots__/edit-namespace-from-new-tab.test.tsx.snap @@ -7469,6 +7469,8 @@ metadata: selfLink: /apis/some-api-version/namespaces/some-uid somePropertyToBeRemoved: some-value somePropertyToBeChanged: some-old-value + labels: + k8slens-edit-resource-version: some-api-version diff --git a/packages/core/src/features/cluster/namespaces/edit-namespace-from-new-tab.test.tsx b/packages/core/src/features/cluster/namespaces/edit-namespace-from-new-tab.test.tsx index 96ced30199..8480da45e3 100644 --- a/packages/core/src/features/cluster/namespaces/edit-namespace-from-new-tab.test.tsx +++ b/packages/core/src/features/cluster/namespaces/edit-namespace-from-new-tab.test.tsx @@ -12,8 +12,6 @@ import createEditResourceTabInjectable from "../../../renderer/components/dock/e import getRandomIdForEditResourceTabInjectable from "../../../renderer/components/dock/edit-resource/get-random-id-for-edit-resource-tab.injectable"; import type { AsyncFnMock } from "@async-fn/jest"; import asyncFn from "@async-fn/jest"; -import type { CallForResource } from "../../../renderer/components/dock/edit-resource/edit-resource-model/call-for-resource/call-for-resource.injectable"; -import callForResourceInjectable from "../../../renderer/components/dock/edit-resource/edit-resource-model/call-for-resource/call-for-resource.injectable"; import type { CallForPatchResource } from "../../../renderer/components/dock/edit-resource/edit-resource-model/call-for-patch-resource/call-for-patch-resource.injectable"; import callForPatchResourceInjectable from "../../../renderer/components/dock/edit-resource/edit-resource-model/call-for-patch-resource/call-for-patch-resource.injectable"; import dockStoreInjectable from "../../../renderer/components/dock/dock/store.injectable"; @@ -23,6 +21,8 @@ import showErrorNotificationInjectable from "../../../renderer/components/notifi import readJsonFileInjectable from "../../../common/fs/read-json-file.injectable"; import directoryForLensLocalStorageInjectable from "../../../common/directory-for-lens-local-storage/directory-for-lens-local-storage.injectable"; import hostedClusterIdInjectable from "../../../renderer/cluster-frame-context/hosted-cluster-id.injectable"; +import type { CallForResource } from "../../../renderer/components/dock/edit-resource/edit-resource-model/call-for-resource/call-for-resource.injectable"; +import callForResourceInjectable from "../../../renderer/components/dock/edit-resource/edit-resource-model/call-for-resource/call-for-resource.injectable"; describe("cluster/namespaces - edit namespace from new tab", () => { let builder: ApplicationBuilder; @@ -225,10 +225,16 @@ metadata: expect(rendered.baseElement).toMatchSnapshot(); }); - it("calls for save with empty values", () => { + it("calls for save with just the adding version label", () => { expect(callForPatchResourceMock).toHaveBeenCalledWith( someNamespace, - [], + [{ + op: "add", + path: "/metadata/labels", + value: { + "k8slens-edit-resource-version": "some-api-version", + }, + }], ); }); @@ -532,6 +538,13 @@ metadata: path: "/metadata/someAddedProperty", value: "some-new-value", }, + { + op: "add", + path: "/metadata/labels", + value: { + "k8slens-edit-resource-version": "some-api-version", + }, + }, { op: "replace", path: "/metadata/somePropertyToBeChanged", @@ -759,7 +772,7 @@ metadata: `); }); - it("when selecting to save, calls for save of second namespace", () => { + it("when selecting to save, calls for save of second namespace with just the add edit version label", () => { callForPatchResourceMock.mockClear(); const saveButton = rendered.getByTestId( @@ -770,7 +783,13 @@ metadata: expect(callForPatchResourceMock).toHaveBeenCalledWith( someOtherNamespace, - [], + [{ + op: "add", + path: "/metadata/labels", + value: { + "k8slens-edit-resource-version": "some-api-version", + }, + }], ); }); @@ -826,7 +845,7 @@ metadata: `); }); - it("when selecting to save, calls for save of first namespace", () => { + it("when selecting to save, calls for save of first namespace with just the new edit version label", () => { callForPatchResourceMock.mockClear(); const saveButton = rendered.getByTestId( @@ -837,7 +856,13 @@ metadata: expect(callForPatchResourceMock).toHaveBeenCalledWith( someNamespace, - [], + [ { + op: "add", + path: "/metadata/labels", + value: { + "k8slens-edit-resource-version": "some-api-version", + }, + }], ); }); }); diff --git a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/__snapshots__/hpa-details.test.tsx.snap b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/__snapshots__/details.test.tsx.snap similarity index 100% rename from packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/__snapshots__/hpa-details.test.tsx.snap rename to packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/__snapshots__/details.test.tsx.snap diff --git a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa-details.scss b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/details.scss similarity index 99% rename from packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa-details.scss rename to packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/details.scss index 571d988b11..d422451583 100644 --- a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa-details.scss +++ b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/details.scss @@ -16,6 +16,7 @@ .TableCell { word-break: break-word; + &:first-child { margin-left: $margin * 2; } diff --git a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa-details.test.tsx b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/details.test.tsx similarity index 92% rename from packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa-details.test.tsx rename to packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/details.test.tsx index 3190be6edd..79f96c28cb 100644 --- a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa-details.test.tsx +++ b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/details.test.tsx @@ -13,7 +13,7 @@ import { getDiForUnitTesting } from "../../getDiForUnitTesting"; import storesAndApisCanBeCreatedInjectable from "../../stores-apis-can-be-created.injectable"; import type { DiRender } from "../test-utils/renderFor"; import { renderFor } from "../test-utils/renderFor"; -import { HpaDetails } from "./hpa-details"; +import { HorizontalPodAutoscalerDetails } from "./details"; jest.mock("react-router-dom", () => ({ Link: ({ children }: { children: React.ReactNode }) => children, @@ -62,7 +62,7 @@ describe("", () => { const hpa = new HorizontalPodAutoscaler(hpaV2); result = render( - , + , ); expect(result.baseElement).toMatchSnapshot(); @@ -72,7 +72,7 @@ describe("", () => { const hpa = new HorizontalPodAutoscaler(hpaV2); result = render( - , + , ); expect(result.queryByTestId("hpa-metrics")).toBeNull(); @@ -101,7 +101,7 @@ describe("", () => { }); result = render( - , + , ); expect(result.getByText("CPU Utilization percentage")).toBeInTheDocument(); @@ -131,7 +131,7 @@ describe("", () => { ); result = render( - , + , ); expect(result.getByText("Resource cpu on Pods")).toBeInTheDocument(); @@ -160,7 +160,7 @@ describe("", () => { ); result = render( - , + , ); expect(result.getByText("Resource cpu on Pods")).toBeInTheDocument(); @@ -191,7 +191,7 @@ describe("", () => { ); result = render( - , + , ); expect(result.getByText("packets-per-second on Pods")).toBeInTheDocument(); @@ -216,7 +216,7 @@ describe("", () => { ); result = render( - , + , ); expect(result.getByText("packets-per-second on Pods")).toBeInTheDocument(); @@ -252,7 +252,7 @@ describe("", () => { ); result = render( - , + , ); expect(result.getByText(/requests-per-second/)).toHaveTextContent("requests-per-second onService/nginx"); @@ -277,7 +277,7 @@ describe("", () => { ); result = render( - , + , ); expect(result.getByText("requests-per-second")).toBeInTheDocument(); @@ -311,7 +311,7 @@ describe("", () => { ); result = render( - , + , ); expect(result.getByText("queue_messages_ready on {\"matchLabels\":{\"queue\":\"worker_tasks\"}}")).toBeInTheDocument(); @@ -339,7 +339,7 @@ describe("", () => { ); result = render( - , + , ); expect(result.getByText("queue_messages_ready on {\"matchLabels\":{\"queue\":\"worker_tasks\"}}")).toBeInTheDocument(); @@ -368,7 +368,7 @@ describe("", () => { ); result = render( - , + , ); expect(result.baseElement).toMatchSnapshot(); @@ -398,7 +398,7 @@ describe("", () => { ); result = render( - , + , ); expect(result.baseElement).toMatchSnapshot(); diff --git a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa-details.tsx b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/details.tsx similarity index 93% rename from packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa-details.tsx rename to packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/details.tsx index d57c8a3323..f4d675fa3d 100644 --- a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa-details.tsx +++ b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/details.tsx @@ -3,7 +3,7 @@ * Licensed under MIT License. See LICENSE in root directory for more information. */ -import "./hpa-details.scss"; +import "./details.scss"; import React from "react"; import { observer } from "mobx-react"; @@ -22,8 +22,8 @@ import { withInjectables } from "@ogre-tools/injectable-react"; import apiManagerInjectable from "../../../common/k8s-api/api-manager/manager.injectable"; import getDetailsUrlInjectable from "../kube-detail-params/get-details-url.injectable"; import loggerInjectable from "../../../common/logger.injectable"; -import getHorizontalPodAutoscalerMetrics from "./get-hpa-metrics.injectable"; -import { getMetricName } from "./get-hpa-metric-name"; +import getHorizontalPodAutoscalerMetrics from "./get-metrics.injectable"; +import { getMetricName } from "./get-metric-name"; export interface HpaDetailsProps extends KubeObjectDetailsProps { } @@ -36,7 +36,7 @@ interface Dependencies { } @observer -class NonInjectedHpaDetails extends React.Component { +class NonInjectedHorizontalPodAutoscalerDetails extends React.Component { private renderTargetLink(target: HorizontalPodAutoscalerMetricTarget | undefined) { if (!target) { return null; @@ -177,7 +177,7 @@ class NonInjectedHpaDetails extends React.Component(NonInjectedHpaDetails, { +export const HorizontalPodAutoscalerDetails = withInjectables(NonInjectedHorizontalPodAutoscalerDetails, { getProps: (di, props) => ({ ...props, apiManager: di.inject(apiManagerInjectable), diff --git a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/get-hpa-metric-name.ts b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/get-metric-name.ts similarity index 100% rename from packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/get-hpa-metric-name.ts rename to packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/get-metric-name.ts diff --git a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/get-hpa-metrics.injectable.ts b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/get-metrics.injectable.ts similarity index 93% rename from packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/get-hpa-metrics.injectable.ts rename to packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/get-metrics.injectable.ts index ac524f0cd5..8872fbf5fd 100644 --- a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/get-hpa-metrics.injectable.ts +++ b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/get-metrics.injectable.ts @@ -5,9 +5,9 @@ import { getInjectable } from "@ogre-tools/injectable"; import type { HorizontalPodAutoscaler, HorizontalPodAutoscalerMetricSpec, HorizontalPodAutoscalerMetricStatus } from "../../../common/k8s-api/endpoints"; import { HpaMetricType } from "../../../common/k8s-api/endpoints"; -import { getMetricName } from "./get-hpa-metric-name"; -import { HorizontalPodAutoscalerV1MetricParser } from "./hpa-v1-metric-parser"; -import { HorizontalPodAutoscalerV2MetricParser } from "./hpa-v2-metric-parser"; +import { getMetricName } from "./get-metric-name"; +import { HorizontalPodAutoscalerV1MetricParser } from "./metric-parser-v1"; +import { HorizontalPodAutoscalerV2MetricParser } from "./metric-parser-v2"; type Parser = HorizontalPodAutoscalerV1MetricParser | HorizontalPodAutoscalerV2MetricParser; diff --git a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/index.ts b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/index.ts index a0b5231b2e..73bb54532e 100644 --- a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/index.ts +++ b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/index.ts @@ -3,5 +3,5 @@ * Licensed under MIT License. See LICENSE in root directory for more information. */ -export * from "./hpa"; -export * from "./hpa-details"; +export * from "./list-view"; +export * from "./details"; diff --git a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa.scss b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/list-view.scss similarity index 100% rename from packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa.scss rename to packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/list-view.scss diff --git a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa.tsx b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/list-view.tsx similarity index 97% rename from packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa.tsx rename to packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/list-view.tsx index 68ee6671d7..ae536410e3 100644 --- a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa.tsx +++ b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/list-view.tsx @@ -3,7 +3,7 @@ * Licensed under MIT License. See LICENSE in root directory for more information. */ -import "./hpa.scss"; +import "./list-view.scss"; import React from "react"; import { observer } from "mobx-react"; @@ -17,7 +17,7 @@ import { KubeObjectAge } from "../kube-object/age"; import type { HorizontalPodAutoscalerStore } from "./store"; import { withInjectables } from "@ogre-tools/injectable-react"; import horizontalPodAutoscalerStoreInjectable from "./store.injectable"; -import getHorizontalPodAutoscalerMetrics from "./get-hpa-metrics.injectable"; +import getHorizontalPodAutoscalerMetrics from "./get-metrics.injectable"; import { NamespaceSelectBadge } from "../+namespaces/namespace-select-badge"; enum columnId { diff --git a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa-v1-metric-parser.ts b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/metric-parser-v1.ts similarity index 100% rename from packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa-v1-metric-parser.ts rename to packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/metric-parser-v1.ts diff --git a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa-v2-metric-parser.ts b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/metric-parser-v2.ts similarity index 100% rename from packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/hpa-v2-metric-parser.ts rename to packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/metric-parser-v2.ts diff --git a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/horizontal-pod-autoscaler-metrics.test.ts b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/metric-parser.test.ts similarity index 99% rename from packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/horizontal-pod-autoscaler-metrics.test.ts rename to packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/metric-parser.test.ts index 5f1c1d7183..2168da52ad 100644 --- a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/horizontal-pod-autoscaler-metrics.test.ts +++ b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/metric-parser.test.ts @@ -3,7 +3,7 @@ * Licensed under MIT License. See LICENSE in root directory for more information. */ import type { DiContainer } from "@ogre-tools/injectable"; -import getHorizontalPodAutoscalerMetrics from "./get-hpa-metrics.injectable"; +import getHorizontalPodAutoscalerMetrics from "./get-metrics.injectable"; import { getDiForUnitTesting } from "../../getDiForUnitTesting"; import { HorizontalPodAutoscaler, HpaMetricType } from "../../../common/k8s-api/endpoints"; @@ -658,10 +658,10 @@ describe("getHorizontalPodAutoscalerMetrics", () => { ], }, }); - + expect(getMetrics(hpa)[0]).toEqual("10% / 50%"); }); - + it("should return correct resource metrics with current value", () => { const hpa = new HorizontalPodAutoscaler({ ...hpaV2Beta1, @@ -691,7 +691,7 @@ describe("getHorizontalPodAutoscalerMetrics", () => { ], }, }); - + expect(getMetrics(hpa)[0]).toEqual("500m / 100m"); }); @@ -787,7 +787,7 @@ describe("getHorizontalPodAutoscalerMetrics", () => { type: HpaMetricType.Pods, pods: { metricName: "packets-per-second", - + targetAverageValue: "1k", }, }, @@ -1038,7 +1038,7 @@ describe("getHorizontalPodAutoscalerMetrics", () => { ], }, }); - + expect(getMetrics(hpa)[0]).toEqual("unknown / 50%"); }); }); diff --git a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/horizontal-pod-autoscalers-route-component.injectable.ts b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/route-component.injectable.ts similarity index 94% rename from packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/horizontal-pod-autoscalers-route-component.injectable.ts rename to packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/route-component.injectable.ts index 991f6cab1b..a8b81ae0b1 100644 --- a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/horizontal-pod-autoscalers-route-component.injectable.ts +++ b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/route-component.injectable.ts @@ -5,7 +5,7 @@ import { getInjectable } from "@ogre-tools/injectable"; import { routeSpecificComponentInjectionToken } from "../../routes/route-specific-component-injection-token"; import horizontalPodAutoscalersRouteInjectable from "../../../common/front-end-routing/routes/cluster/config/horizontal-pod-autoscalers/horizontal-pod-autoscalers-route.injectable"; -import { HorizontalPodAutoscalers } from "./hpa"; +import { HorizontalPodAutoscalers } from "./list-view"; const horizontalPodAutoscalersRouteComponentInjectable = getInjectable({ id: "horizontal-pod-autoscalers-route-component", diff --git a/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/horizontal-pod-auto-scalers-sidebar-items.injectable.tsx b/packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/sidebar-items.injectable.tsx similarity index 100% rename from packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/horizontal-pod-auto-scalers-sidebar-items.injectable.tsx rename to packages/core/src/renderer/components/+config-horizontal-pod-autoscalers/sidebar-items.injectable.tsx diff --git a/packages/core/src/renderer/components/dock/edit-resource/edit-resource-model/call-for-resource/call-for-resource.injectable.ts b/packages/core/src/renderer/components/dock/edit-resource/edit-resource-model/call-for-resource/call-for-resource.injectable.ts index af9fd15a26..42ffa28946 100644 --- a/packages/core/src/renderer/components/dock/edit-resource/edit-resource-model/call-for-resource/call-for-resource.injectable.ts +++ b/packages/core/src/renderer/components/dock/edit-resource/edit-resource-model/call-for-resource/call-for-resource.injectable.ts @@ -3,44 +3,35 @@ * Licensed under MIT License. See LICENSE in root directory for more information. */ import { getInjectable } from "@ogre-tools/injectable"; -import type { KubeObject } from "../../../../../../common/k8s-api/kube-object"; +import { KubeObject } from "../../../../../../common/k8s-api/kube-object"; import { parseKubeApi } from "../../../../../../common/k8s-api/kube-api-parse"; import type { AsyncResult } from "@k8slens/utilities"; import { getErrorMessage } from "../../../../../../common/utils/get-error-message"; -import apiManagerInjectable from "../../../../../../common/k8s-api/api-manager/manager.injectable"; -import { waitUntilDefined } from "@k8slens/utilities"; +import apiKubeInjectable from "../../../../../k8s/api-kube.injectable"; -export type CallForResource = ( - selfLink: string -) => AsyncResult; +export type CallForResource = (selfLink: string) => AsyncResult; const callForResourceInjectable = getInjectable({ id: "call-for-resource", instantiate: (di): CallForResource => { - const apiManager = di.inject(apiManagerInjectable); + const apiKube = di.inject(apiKubeInjectable); return async (apiPath: string) => { - const api = await waitUntilDefined(() => apiManager.getApi(apiPath)); - const parsed = parseKubeApi(apiPath); - if (!api || !parsed.name) { + if (!parsed.name) { return { callWasSuccessful: false, error: "Invalid API path" }; } - let resource: KubeObject | null; - try { - resource = await api.get({ - name: parsed.name, - namespace: parsed.namespace, - }); + return { + callWasSuccessful: true, + response: new KubeObject(await apiKube.get(apiPath)), + }; } catch (e) { return { callWasSuccessful: false, error: getErrorMessage(e) }; } - - return { callWasSuccessful: true, response: resource || undefined }; }; }, diff --git a/packages/core/src/renderer/components/dock/edit-resource/edit-resource-model/edit-resource-model.injectable.tsx b/packages/core/src/renderer/components/dock/edit-resource/edit-resource-model/edit-resource-model.injectable.tsx index 7b2386e189..e1f8eca988 100644 --- a/packages/core/src/renderer/components/dock/edit-resource/edit-resource-model/edit-resource-model.injectable.tsx +++ b/packages/core/src/renderer/components/dock/edit-resource/edit-resource-model/edit-resource-model.injectable.tsx @@ -7,9 +7,9 @@ import type { CallForResource } from "./call-for-resource/call-for-resource.inje import callForResourceInjectable from "./call-for-resource/call-for-resource.injectable"; import { waitUntilDefined } from "@k8slens/utilities"; import editResourceTabStoreInjectable from "../store.injectable"; -import type { EditResourceTabStore } from "../store"; -import { action, computed, makeObservable, observable, runInAction } from "mobx"; -import type { KubeObject } from "../../../../../common/k8s-api/kube-object"; +import type { EditingResource, EditResourceTabStore } from "../store"; +import { action, computed, observable, runInAction } from "mobx"; +import type { KubeObject, RawKubeObject } from "../../../../../common/k8s-api/kube-object"; import yaml from "js-yaml"; import assert from "assert"; import type { CallForPatchResource } from "./call-for-patch-resource/call-for-patch-resource.injectable"; @@ -19,18 +19,22 @@ import type { ShowNotification } from "../../../notifications"; import showSuccessNotificationInjectable from "../../../notifications/show-success-notification.injectable"; import React from "react"; import showErrorNotificationInjectable from "../../../notifications/show-error-notification.injectable"; +import { createKubeApiURL, parseKubeApi } from "../../../../../common/k8s-api/kube-api-parse"; const editResourceModelInjectable = getInjectable({ id: "edit-resource-model", instantiate: async (di, tabId: string) => { + const store = di.inject(editResourceTabStoreInjectable); + const model = new EditResourceModel({ callForResource: di.inject(callForResourceInjectable), callForPatchResource: di.inject(callForPatchResourceInjectable), showSuccessNotification: di.inject(showSuccessNotificationInjectable), showErrorNotification: di.inject(showErrorNotificationInjectable), - store: di.inject(editResourceTabStoreInjectable), + store, tabId, + waitForEditingResource: () => waitUntilDefined(() => store.getData(tabId)), }); await model.load(); @@ -48,19 +52,42 @@ export default editResourceModelInjectable; interface Dependencies { callForResource: CallForResource; callForPatchResource: CallForPatchResource; + waitForEditingResource: () => Promise; showSuccessNotification: ShowNotification; showErrorNotification: ShowNotification; readonly store: EditResourceTabStore; readonly tabId: string; } -export class EditResourceModel { - constructor(private readonly dependencies: Dependencies) { - makeObservable(this); +function getEditSelfLinkFor(object: RawKubeObject): string { + const lensVersionLabel = object.metadata.labels?.[EditResourceLabelName]; + + if (lensVersionLabel) { + const { apiVersionWithGroup, ...parsedApi } = parseKubeApi(object.metadata.selfLink); + + parsedApi.apiVersion = lensVersionLabel; + + return createKubeApiURL({ + ...parsedApi, + apiVersion: `${parsedApi.apiGroup}/${parsedApi.apiVersion}`, + }); } + return object.metadata.selfLink; +} + +/** + * The label name that Lens uses to receive the desired api version + */ +export const EditResourceLabelName = "k8slens-edit-resource-version"; + +export class EditResourceModel { + constructor(protected readonly dependencies: Dependencies) {} + readonly configuration = { - value: computed(() => this.editingResource.draft || this.editingResource.firstDraft || ""), + value: computed( + () => this.editingResource.draft || this.editingResource.firstDraft || "", + ), onChange: action((value: string) => { this.editingResource.draft = value; @@ -100,27 +127,39 @@ export class EditResourceModel { return this.editingResource.resource; } - load = async () => { - await waitUntilDefined(() => this.dependencies.store.getData(this.dependencies.tabId)); + load = async (): Promise => { + await this.dependencies.waitForEditingResource(); - const result = await this.dependencies.callForResource(this.selfLink); + let result = await this.dependencies.callForResource(this.selfLink); if (!result.callWasSuccessful) { - this.dependencies.showErrorNotification( - `Loading resource failed: ${result.error}`, - ); + return void this.dependencies.showErrorNotification(`Loading resource failed: ${result.error}`); + } + if (result?.response?.metadata.labels?.[EditResourceLabelName]) { + const parsed = parseKubeApi(this.selfLink); + + parsed.apiVersion = result.response.metadata.labels[EditResourceLabelName]; + + result = await this.dependencies.callForResource(createKubeApiURL(parsed)); + } + + if (!result.callWasSuccessful) { + return void this.dependencies.showErrorNotification(`Loading resource failed: ${result.error}`); + } + + const resource = result.response; + + runInAction(() => { + this._resource = resource; + }); + + if (!resource) { return; } runInAction(() => { - this._resource = result.response; - - if (this._resource) { - this.editingResource.firstDraft = yaml.dump( - this._resource.toPlainObject(), - ); - } + this.editingResource.firstDraft = yaml.dump(resource.toPlainObject()); }); }; @@ -138,16 +177,16 @@ export class EditResourceModel { save = async () => { const currentValue = this.configuration.value.get(); - const currentVersion = yaml.load(currentValue); - const firstVersion = yaml.load( - this.editingResource.firstDraft ?? currentValue, - ); - const patches = createPatch(firstVersion, currentVersion); + const currentVersion = yaml.load(currentValue) as RawKubeObject; + const firstVersion = yaml.load(this.editingResource.firstDraft ?? currentValue); - const result = await this.dependencies.callForPatchResource( - this.resource, - patches, - ); + // Make sure we save this label so that we can use it in the future + currentVersion.metadata.labels ??= {}; + currentVersion.metadata.labels[EditResourceLabelName] = currentVersion.apiVersion.split("/").pop(); + + const patches = createPatch(firstVersion, currentVersion); + const selfLink = getEditSelfLinkFor(currentVersion); + const result = await this.dependencies.callForPatchResource(this.resource, patches); if (!result.callWasSuccessful) { this.dependencies.showErrorNotification(( @@ -158,23 +197,26 @@ export class EditResourceModel {

)); - return; + return null; } const { kind, name } = result.response; - this.dependencies.showSuccessNotification(( + this.dependencies.showSuccessNotification(

- {`${kind} `} + {kind} + {" "} {name} {" updated."} -

- )); +

, + ); runInAction(() => { - this.editingResource.firstDraft = currentValue; + this.editingResource.firstDraft = yaml.dump(currentVersion); + this.editingResource.resource = selfLink; }); - return result.response.toString(); + // NOTE: This is required for `saveAndClose` to work correctly + return []; }; } diff --git a/packages/core/src/renderer/components/dock/edit-resource/view.tsx b/packages/core/src/renderer/components/dock/edit-resource/view.tsx index 0465f80c93..107728e81d 100644 --- a/packages/core/src/renderer/components/dock/edit-resource/view.tsx +++ b/packages/core/src/renderer/components/dock/edit-resource/view.tsx @@ -56,12 +56,14 @@ const NonInjectedEditResource = observer(({ Namespace: - )} /> + )} + /> + onError={model.configuration.error.onChange} + /> ) } diff --git a/packages/core/src/renderer/components/kube-object-details/kube-object-detail-items/implementations/horizontal-pod-autoscaler-detail-item.injectable.ts b/packages/core/src/renderer/components/kube-object-details/kube-object-detail-items/implementations/horizontal-pod-autoscaler-detail-item.injectable.ts index 8fe4b7da38..449feac7ea 100644 --- a/packages/core/src/renderer/components/kube-object-details/kube-object-detail-items/implementations/horizontal-pod-autoscaler-detail-item.injectable.ts +++ b/packages/core/src/renderer/components/kube-object-details/kube-object-detail-items/implementations/horizontal-pod-autoscaler-detail-item.injectable.ts @@ -4,7 +4,7 @@ */ import { getInjectable } from "@ogre-tools/injectable"; import { kubeObjectDetailItemInjectionToken } from "../kube-object-detail-item-injection-token"; -import { HpaDetails } from "../../../+config-horizontal-pod-autoscalers"; +import { HorizontalPodAutoscalerDetails } from "../../../+config-horizontal-pod-autoscalers"; import { computed } from "mobx"; import { kubeObjectMatchesToKindAndApiVersion } from "../kube-object-matches-to-kind-and-api-version"; import currentKubeObjectInDetailsInjectable from "../../current-kube-object-in-details.injectable"; @@ -16,7 +16,7 @@ const horizontalPodAutoscalerDetailItemInjectable = getInjectable({ const kubeObject = di.inject(currentKubeObjectInDetailsInjectable); return { - Component: HpaDetails, + Component: HorizontalPodAutoscalerDetails, enabled: computed(() => isHorizontalPodAutoscaler(kubeObject.value.get()?.object)), orderNumber: 10, }; diff --git a/packages/core/src/renderer/components/monaco-editor/monaco-editor.tsx b/packages/core/src/renderer/components/monaco-editor/monaco-editor.tsx index 7e36639c41..592d288e13 100644 --- a/packages/core/src/renderer/components/monaco-editor/monaco-editor.tsx +++ b/packages/core/src/renderer/components/monaco-editor/monaco-editor.tsx @@ -246,12 +246,10 @@ class NonInjectedMonacoEditor extends React.Component this.model, this.onModelChange), - reaction(() => this.theme, theme => { - if (theme) { - editor.setTheme(theme); - } + reaction(() => this.theme, editor.setTheme), + reaction(() => this.props.value, value => this.setValue(value), { + fireImmediately: true, }), - reaction(() => this.props.value, value => this.setValue(value)), reaction(() => this.options, opts => this.editor.updateOptions(opts)), () => onDidLayoutChangeDisposer.dispose(), diff --git a/packages/infrastructure/eslint-config/prettier-config.json b/packages/infrastructure/eslint-config/prettier-config.json index c9f2606a59..7c1cbfc0a5 100644 --- a/packages/infrastructure/eslint-config/prettier-config.json +++ b/packages/infrastructure/eslint-config/prettier-config.json @@ -1,5 +1,5 @@ { - "printWidth": 100, + "printWidth": 120, "tabWidth": 2, "useTabs": false, "semi": true, diff --git a/packages/technical-features/application/agnostic/src/start-application/start-application.injectable.ts b/packages/technical-features/application/agnostic/src/start-application/start-application.injectable.ts index 87f6d1f7db..ea2f4f8a5b 100644 --- a/packages/technical-features/application/agnostic/src/start-application/start-application.injectable.ts +++ b/packages/technical-features/application/agnostic/src/start-application/start-application.injectable.ts @@ -13,9 +13,7 @@ const startApplicationInjectable = getInjectable({ instantiate: (di): StartApplication => { const runManyAsync = runManyFor(di); - const beforeApplicationIsLoading = runManyAsync( - timeSlots.beforeApplicationIsLoadingInjectionToken, - ); + const beforeApplicationIsLoading = runManyAsync(timeSlots.beforeApplicationIsLoadingInjectionToken); const onLoadOfApplication = runManyAsync(timeSlots.onLoadOfApplicationInjectionToken); const afterApplicationIsLoaded = runManyAsync(timeSlots.afterApplicationIsLoadedInjectionToken); diff --git a/packages/technical-features/application/electron-main/src/start-application/start-electron-application.injectable.ts b/packages/technical-features/application/electron-main/src/start-application/start-electron-application.injectable.ts index 495f75ec27..bd17d85991 100644 --- a/packages/technical-features/application/electron-main/src/start-application/start-electron-application.injectable.ts +++ b/packages/technical-features/application/electron-main/src/start-application/start-electron-application.injectable.ts @@ -1,9 +1,4 @@ -import { - DiContainer, - getInjectable, - instantiationDecoratorToken, - lifecycleEnum, -} from "@ogre-tools/injectable"; +import { DiContainer, getInjectable, instantiationDecoratorToken, lifecycleEnum } from "@ogre-tools/injectable"; import { startApplicationInjectionToken } from "@k8slens/application"; import whenAppIsReadyInjectable from "./when-app-is-ready.injectable"; import { beforeAnythingInjectionToken, beforeElectronIsReadyInjectionToken } from "./time-slots"; diff --git a/packages/technical-features/application/electron-main/src/starting-of-electron-main-application.test.ts b/packages/technical-features/application/electron-main/src/starting-of-electron-main-application.test.ts index d64cec3bc5..ec4ae1a836 100644 --- a/packages/technical-features/application/electron-main/src/starting-of-electron-main-application.test.ts +++ b/packages/technical-features/application/electron-main/src/starting-of-electron-main-application.test.ts @@ -1,10 +1,7 @@ import { createContainer, DiContainer, getInjectable } from "@ogre-tools/injectable"; import { registerFeature } from "@k8slens/feature-core"; import { applicationFeatureForElectronMain } from "./feature"; -import { - beforeApplicationIsLoadingInjectionToken, - startApplicationInjectionToken, -} from "@k8slens/application"; +import { beforeApplicationIsLoadingInjectionToken, startApplicationInjectionToken } from "@k8slens/application"; import asyncFn, { AsyncFnMock } from "@async-fn/jest"; import whenAppIsReadyInjectable from "./start-application/when-app-is-ready.injectable"; import * as timeSlots from "./start-application/time-slots"; diff --git a/packages/technical-features/feature-core/src/deregister-feature.ts b/packages/technical-features/feature-core/src/deregister-feature.ts index 4476120ab7..8bd08e9077 100644 --- a/packages/technical-features/feature-core/src/deregister-feature.ts +++ b/packages/technical-features/feature-core/src/deregister-feature.ts @@ -2,9 +2,7 @@ import type { DiContainer } from "@ogre-tools/injectable"; import type { Feature } from "./feature"; import { featureContextMapInjectable } from "./feature-context-map-injectable"; -const getDependingFeaturesFor = ( - featureContextMap: Map }>, -) => { +const getDependingFeaturesFor = (featureContextMap: Map }>) => { const getDependingFeaturesForRecursion = (feature: Feature, atRoot = true): string[] => { const context = featureContextMap.get(feature); @@ -36,11 +34,9 @@ const deregisterFeatureRecursed = (di: DiContainer, feature: Feature, dependedBy const dependingFeatures = getDependingFeatures(feature); if (!dependedBy && dependingFeatures.length) { - throw new Error( - `Tried to deregister Feature "${ - feature.id - }", but it is the dependency of Features "${dependingFeatures.join(", ")}"`, - ); + const names = dependingFeatures.join(", "); + + throw new Error(`Tried to deregister Feature "${feature.id}", but it is the dependency of Features "${names}"`); } if (dependedBy) { diff --git a/packages/technical-features/feature-core/src/feature-dependencies.test.ts b/packages/technical-features/feature-core/src/feature-dependencies.test.ts index 8ddf6e11b8..8fb69fe33f 100644 --- a/packages/technical-features/feature-core/src/feature-dependencies.test.ts +++ b/packages/technical-features/feature-core/src/feature-dependencies.test.ts @@ -59,9 +59,7 @@ describe("feature-dependencies", () => { expect(() => { deregisterFeature(di, someDependencyFeature); - }).toThrow( - 'Tried to deregister feature "some-dependency-feature", but it was not registered.', - ); + }).toThrow('Tried to deregister feature "some-dependency-feature", but it was not registered.'); }); it("given the parent Feature is deregistered, when injecting an injectable from the dependency Feature, throws", () => { @@ -104,9 +102,7 @@ describe("feature-dependencies", () => { it("when the first Feature is deregistered, throws", () => { expect(() => { deregisterFeature(di, someFeature1); - }).toThrow( - 'Tried to deregister Feature "some-feature-1", but it is the dependency of Features "some-feature-2"', - ); + }).toThrow('Tried to deregister Feature "some-feature-1", but it is the dependency of Features "some-feature-2"'); }); it("given the second Feature is deregistered, when injecting an injectable from the first Feature, still does so", () => { @@ -180,9 +176,7 @@ describe("feature-dependencies", () => { expect(() => { di.inject(someInjectableInDependencyFeature); - }).toThrow( - 'Tried to inject non-registered injectable "irrelevant" -> "some-injectable-in-dependency-feature".', - ); + }).toThrow('Tried to inject non-registered injectable "irrelevant" -> "some-injectable-in-dependency-feature".'); }); }); @@ -256,9 +250,7 @@ describe("feature-dependencies", () => { expect(() => { di.inject(someInjectableInDependencyFeature); - }).toThrow( - 'Tried to inject non-registered injectable "irrelevant" -> "some-injectable-in-dependency-feature".', - ); + }).toThrow('Tried to inject non-registered injectable "irrelevant" -> "some-injectable-in-dependency-feature".'); }); }); }); diff --git a/packages/technical-features/feature-core/src/register-feature.ts b/packages/technical-features/feature-core/src/register-feature.ts index f02b050002..535a93bf18 100644 --- a/packages/technical-features/feature-core/src/register-feature.ts +++ b/packages/technical-features/feature-core/src/register-feature.ts @@ -1,10 +1,7 @@ import type { DiContainer } from "@ogre-tools/injectable"; import { getInjectable } from "@ogre-tools/injectable"; import type { Feature } from "./feature"; -import { - featureContextMapInjectable, - featureContextMapInjectionToken, -} from "./feature-context-map-injectable"; +import { featureContextMapInjectable, featureContextMapInjectionToken } from "./feature-context-map-injectable"; const createFeatureContext = (feature: Feature, di: DiContainer) => { const featureContextInjectable = getInjectable({ @@ -58,10 +55,9 @@ const registerFeatureRecursed = (di: DiContainer, feature: Feature, dependedBy?: if (dependedBy) { const oldNumberOfDependents = featureContext.dependedBy.get(dependedBy) || 0; + const newNumberOfDependents = oldNumberOfDependents + 1; - const newNumberOfDependants = oldNumberOfDependents + 1; - - featureContext.dependedBy.set(dependedBy, newNumberOfDependants); + featureContext.dependedBy.set(dependedBy, newNumberOfDependents); } if (!existingFeatureContext) { diff --git a/packages/technical-features/messaging/agnostic/src/features/actual/index.ts b/packages/technical-features/messaging/agnostic/src/features/actual/index.ts index f85542c954..f0acf5ee1c 100644 --- a/packages/technical-features/messaging/agnostic/src/features/actual/index.ts +++ b/packages/technical-features/messaging/agnostic/src/features/actual/index.ts @@ -21,15 +21,9 @@ export { getMessageChannelListenerInjectable, } from "./message/message-channel-listener-injection-token"; -export type { - RequestChannel, - RequestChannelHandler, -} from "./request/request-channel-listener-injection-token"; +export type { RequestChannel, RequestChannelHandler } from "./request/request-channel-listener-injection-token"; -export type { - RequestFromChannel, - ChannelRequester, -} from "./request/request-from-channel-injection-token"; +export type { RequestFromChannel, ChannelRequester } from "./request/request-from-channel-injection-token"; export type { EnlistMessageChannelListener } from "./message/enlist-message-channel-listener-injection-token"; export { enlistMessageChannelListenerInjectionToken } from "./message/enlist-message-channel-listener-injection-token"; diff --git a/packages/technical-features/messaging/agnostic/src/features/actual/listening-of-channels/listening-of-channels.injectable.ts b/packages/technical-features/messaging/agnostic/src/features/actual/listening-of-channels/listening-of-channels.injectable.ts index 9040939f06..6d65621f12 100644 --- a/packages/technical-features/messaging/agnostic/src/features/actual/listening-of-channels/listening-of-channels.injectable.ts +++ b/packages/technical-features/messaging/agnostic/src/features/actual/listening-of-channels/listening-of-channels.injectable.ts @@ -21,9 +21,7 @@ export const listeningOfChannelsInjectionToken = getInjectionToken | RequestChannel }, ->( +const listening = | RequestChannel }>( channelListeners: IComputedValue, enlistChannelListener: (listener: T) => () => void, getId: (listener: T) => string, @@ -33,9 +31,7 @@ const listening = < const reactionDisposer = reaction( () => channelListeners.get(), (newValues, oldValues = []) => { - const addedListeners = newValues.filter( - (newValue) => !oldValues.some((oldValue) => oldValue.id === newValue.id), - ); + const addedListeners = newValues.filter((newValue) => !oldValues.some((oldValue) => oldValue.id === newValue.id)); const removedListeners = oldValues.filter( (oldValue) => !newValues.some((newValue) => newValue.id === oldValue.id), @@ -45,9 +41,7 @@ const listening = < const id = getId(listener); if (listenerDisposers.has(id)) { - throw new Error( - `Tried to add listener for channel "${listener.channel.id}" but listener already exists.`, - ); + throw new Error(`Tried to add listener for channel "${listener.channel.id}" but listener already exists.`); } const disposer = enlistChannelListener(listener); diff --git a/packages/technical-features/messaging/agnostic/src/features/actual/message/enlist-message-channel-listener-injection-token.ts b/packages/technical-features/messaging/agnostic/src/features/actual/message/enlist-message-channel-listener-injection-token.ts index 1bb114ca09..19f4b32df6 100644 --- a/packages/technical-features/messaging/agnostic/src/features/actual/message/enlist-message-channel-listener-injection-token.ts +++ b/packages/technical-features/messaging/agnostic/src/features/actual/message/enlist-message-channel-listener-injection-token.ts @@ -1,16 +1,10 @@ import type { Disposer } from "@k8slens/utilities"; import { getInjectionToken } from "@ogre-tools/injectable"; -import type { - MessageChannel, - MessageChannelListener, -} from "./message-channel-listener-injection-token"; +import type { MessageChannel, MessageChannelListener } from "./message-channel-listener-injection-token"; -export type EnlistMessageChannelListener = ( - listener: MessageChannelListener>, -) => Disposer; +export type EnlistMessageChannelListener = (listener: MessageChannelListener>) => Disposer; -export const enlistMessageChannelListenerInjectionToken = - getInjectionToken({ - id: "listening-to-a-message-channel", - }); +export const enlistMessageChannelListenerInjectionToken = getInjectionToken({ + id: "listening-to-a-message-channel", +}); diff --git a/packages/technical-features/messaging/agnostic/src/features/actual/message/message-channel-listener-injection-token.ts b/packages/technical-features/messaging/agnostic/src/features/actual/message/message-channel-listener-injection-token.ts index 0558bf6598..0e2ee20a64 100644 --- a/packages/technical-features/messaging/agnostic/src/features/actual/message/message-channel-listener-injection-token.ts +++ b/packages/technical-features/messaging/agnostic/src/features/actual/message/message-channel-listener-injection-token.ts @@ -18,9 +18,7 @@ export interface MessageChannelListener { handler: MessageChannelHandler; } -export const messageChannelListenerInjectionToken = getInjectionToken< - MessageChannelListener> ->({ +export const messageChannelListenerInjectionToken = getInjectionToken>>({ id: "message-channel-listener", }); @@ -31,10 +29,7 @@ export interface GetMessageChannelListenerInfo, - Message, ->( +export const getMessageChannelListenerInjectable = , Message>( info: GetMessageChannelListenerInfo, ) => getInjectable({ diff --git a/packages/technical-features/messaging/agnostic/src/features/actual/request/enlist-request-channel-listener-injection-token.ts b/packages/technical-features/messaging/agnostic/src/features/actual/request/enlist-request-channel-listener-injection-token.ts index 7f2a04a78d..8f2d6c2c81 100644 --- a/packages/technical-features/messaging/agnostic/src/features/actual/request/enlist-request-channel-listener-injection-token.ts +++ b/packages/technical-features/messaging/agnostic/src/features/actual/request/enlist-request-channel-listener-injection-token.ts @@ -1,16 +1,12 @@ import type { Disposer } from "@k8slens/utilities/index"; import { getInjectionToken } from "@ogre-tools/injectable"; -import type { - RequestChannel, - RequestChannelListener, -} from "./request-channel-listener-injection-token"; +import type { RequestChannel, RequestChannelListener } from "./request-channel-listener-injection-token"; export type EnlistRequestChannelListener = ( listener: RequestChannelListener>, ) => Disposer; -export const enlistRequestChannelListenerInjectionToken = - getInjectionToken({ - id: "listening-to-a-request-channel", - }); +export const enlistRequestChannelListenerInjectionToken = getInjectionToken({ + id: "listening-to-a-request-channel", +}); diff --git a/packages/technical-features/messaging/agnostic/src/features/actual/request/get-request-channel.ts b/packages/technical-features/messaging/agnostic/src/features/actual/request/get-request-channel.ts index c0ee40bcf4..e89f8a8d0e 100644 --- a/packages/technical-features/messaging/agnostic/src/features/actual/request/get-request-channel.ts +++ b/packages/technical-features/messaging/agnostic/src/features/actual/request/get-request-channel.ts @@ -1,7 +1,5 @@ import type { RequestChannel } from "./request-channel-listener-injection-token"; -export const getRequestChannel = ( - id: string, -): RequestChannel => ({ +export const getRequestChannel = (id: string): RequestChannel => ({ id, }); diff --git a/packages/technical-features/messaging/agnostic/src/features/actual/request/request-channel-listener-injection-token.ts b/packages/technical-features/messaging/agnostic/src/features/actual/request/request-channel-listener-injection-token.ts index 2ec76ff546..4491b14fe1 100644 --- a/packages/technical-features/messaging/agnostic/src/features/actual/request/request-channel-listener-injection-token.ts +++ b/packages/technical-features/messaging/agnostic/src/features/actual/request/request-channel-listener-injection-token.ts @@ -7,10 +7,7 @@ export interface RequestChannel { _responseSignature?: Response; } -export type RequestChannelHandler = Channel extends RequestChannel< - infer Request, - infer Response -> +export type RequestChannelHandler = Channel extends RequestChannel ? (req: Request) => Promise | Response : never; diff --git a/packages/technical-features/messaging/agnostic/src/features/actual/request/request-from-channel-injection-token.ts b/packages/technical-features/messaging/agnostic/src/features/actual/request/request-from-channel-injection-token.ts index 194091b588..f15dc97614 100644 --- a/packages/technical-features/messaging/agnostic/src/features/actual/request/request-from-channel-injection-token.ts +++ b/packages/technical-features/messaging/agnostic/src/features/actual/request/request-from-channel-injection-token.ts @@ -2,17 +2,11 @@ import { getInjectionToken } from "@ogre-tools/injectable"; import type { RequestChannel } from "./request-channel-listener-injection-token"; export interface RequestFromChannel { - ( - channel: RequestChannel, - request: Request, - ): Promise; + (channel: RequestChannel, request: Request): Promise; (channel: RequestChannel): Promise; } -export type ChannelRequester = Channel extends RequestChannel< - infer Request, - infer Response -> +export type ChannelRequester = Channel extends RequestChannel ? (req: Request) => Promise> : never; diff --git a/packages/technical-features/messaging/agnostic/src/listening-of-requests.test.ts b/packages/technical-features/messaging/agnostic/src/listening-of-requests.test.ts index e708c983c8..6432ac1376 100644 --- a/packages/technical-features/messaging/agnostic/src/listening-of-requests.test.ts +++ b/packages/technical-features/messaging/agnostic/src/listening-of-requests.test.ts @@ -121,9 +121,7 @@ describe("listening-of-requests", () => { runInAction(() => { di.register(someConflictingListenerInjectable); }); - }).toThrow( - 'Tried to add listener for channel "some-channel-id" but listener already exists.', - ); + }).toThrow('Tried to add listener for channel "some-channel-id" but listener already exists.'); }); describe("when another listener gets registered", () => { diff --git a/packages/technical-features/messaging/computed-channel/index.ts b/packages/technical-features/messaging/computed-channel/index.ts index dd72ecf71b..ba98df8cca 100644 --- a/packages/technical-features/messaging/computed-channel/index.ts +++ b/packages/technical-features/messaging/computed-channel/index.ts @@ -3,7 +3,4 @@ export { computedChannelObserverInjectionToken, } from "./src/computed-channel/computed-channel.injectable"; -export type { - ChannelObserver, - ComputedChannelFactory, -} from "./src/computed-channel/computed-channel.injectable"; +export type { ChannelObserver, ComputedChannelFactory } from "./src/computed-channel/computed-channel.injectable"; diff --git a/packages/technical-features/messaging/computed-channel/src/computed-channel/computed-channel.injectable.ts b/packages/technical-features/messaging/computed-channel/src/computed-channel/computed-channel.injectable.ts index b652a0c795..99d5d18fec 100644 --- a/packages/technical-features/messaging/computed-channel/src/computed-channel/computed-channel.injectable.ts +++ b/packages/technical-features/messaging/computed-channel/src/computed-channel/computed-channel.injectable.ts @@ -1,23 +1,13 @@ import { getInjectable, getInjectionToken } from "@ogre-tools/injectable"; -import { - computed, - IComputedValue, - observable, - onBecomeObserved, - onBecomeUnobserved, - runInAction, -} from "mobx"; +import { computed, IComputedValue, observable, onBecomeObserved, onBecomeUnobserved, runInAction } from "mobx"; import type { MessageChannel } from "@k8slens/messaging"; import { getMessageChannelListenerInjectable } from "@k8slens/messaging"; import { sendMessageToChannelInjectionToken } from "@k8slens/messaging"; import { computedChannelAdministrationChannel } from "./computed-channel-administration-channel.injectable"; -export type ComputedChannelFactory = ( - channel: MessageChannel, - pendingValue: T, -) => IComputedValue; +export type ComputedChannelFactory = (channel: MessageChannel, pendingValue: T) => IComputedValue; export const computedChannelInjectionToken = getInjectionToken({ id: "computed-channel-injection-token", diff --git a/packages/technical-features/messaging/computed-channel/src/computed-channel/computed-channel.test.tsx b/packages/technical-features/messaging/computed-channel/src/computed-channel/computed-channel.test.tsx index 6bea2ca76d..abab064191 100644 --- a/packages/technical-features/messaging/computed-channel/src/computed-channel/computed-channel.test.tsx +++ b/packages/technical-features/messaging/computed-channel/src/computed-channel/computed-channel.test.tsx @@ -3,23 +3,13 @@ import { act } from "@testing-library/react"; import { createContainer, DiContainer, getInjectable } from "@ogre-tools/injectable"; import { getMessageBridgeFake, MessageBridgeFake } from "@k8slens/messaging-fake-bridge"; import { startApplicationInjectionToken } from "@k8slens/application"; -import { - computed, - IComputedValue, - IObservableValue, - observable, - reaction, - runInAction, -} from "mobx"; +import { computed, IComputedValue, IObservableValue, observable, reaction, runInAction } from "mobx"; import type { MessageChannel } from "@k8slens/messaging"; import { getMessageChannelListenerInjectable } from "@k8slens/messaging"; import { registerMobX } from "@ogre-tools/injectable-extension-for-mobx"; import { registerFeature } from "@k8slens/feature-core"; import { testUtils } from "@k8slens/messaging"; -import { - computedChannelInjectionToken, - computedChannelObserverInjectionToken, -} from "./computed-channel.injectable"; +import { computedChannelInjectionToken, computedChannelObserverInjectionToken } from "./computed-channel.injectable"; import { runWithThrownMobxReactions, renderFor } from "@k8slens/test-utils"; import { observer } from "mobx-react"; import { @@ -36,9 +26,7 @@ const TestComponent = observer(({ someComputed }: { someComputed: IComputedValue )); [{ scenarioIsAsync: true }, { scenarioIsAsync: false }].forEach(({ scenarioIsAsync }) => - describe(`computed-channel, given running message bridge fake as ${ - scenarioIsAsync ? "async" : "sync" - }`, () => { + describe(`computed-channel, given running message bridge fake as ${scenarioIsAsync ? "async" : "sync"}`, () => { describe("given multiple dis and a message channel and a channel observer and application has started", () => { let di1: DiContainer; let di2: DiContainer; @@ -87,10 +75,7 @@ const TestComponent = observer(({ someComputed }: { someComputed: IComputedValue messageBridgeFake.setAsync(scenarioIsAsync); messageBridgeFake.involve(di1, di2); - await Promise.all([ - di1.inject(startApplicationInjectionToken)(), - di2.inject(startApplicationInjectionToken)(), - ]); + await Promise.all([di1.inject(startApplicationInjectionToken)(), di2.inject(startApplicationInjectionToken)()]); }); describe("given a channel observer and matching computed channel for the channel in di-2", () => { @@ -175,9 +160,7 @@ const TestComponent = observer(({ someComputed }: { someComputed: IComputedValue expect(observedValue).toBe("some-pending-value"); }); - const scenarioName = scenarioIsAsync - ? "when admin messages are propagated" - : "immediately"; + const scenarioName = scenarioIsAsync ? "when admin messages are propagated" : "immediately"; // eslint-disable-next-line jest/valid-title describe(scenarioName, () => { @@ -196,9 +179,7 @@ const TestComponent = observer(({ someComputed }: { someComputed: IComputedValue }); }); - const scenarioName = scenarioIsAsync - ? "when returning value-messages propagate" - : "immediately"; + const scenarioName = scenarioIsAsync ? "when returning value-messages propagate" : "immediately"; // eslint-disable-next-line jest/valid-title describe(scenarioName, () => { @@ -227,9 +208,7 @@ const TestComponent = observer(({ someComputed }: { someComputed: IComputedValue }); }); - const scenarioName = scenarioIsAsync - ? "when value-messages propagate" - : "immediately"; + const scenarioName = scenarioIsAsync ? "when value-messages propagate" : "immediately"; // eslint-disable-next-line jest/valid-title describe(scenarioName, () => { @@ -258,9 +237,7 @@ const TestComponent = observer(({ someComputed }: { someComputed: IComputedValue stopObserving(); }); - const scenarioName = scenarioIsAsync - ? "when admin-messages propagate" - : "immediately"; + const scenarioName = scenarioIsAsync ? "when admin-messages propagate" : "immediately"; // eslint-disable-next-line jest/valid-title describe(scenarioName, () => { @@ -317,9 +294,7 @@ const TestComponent = observer(({ someComputed }: { someComputed: IComputedValue expect(observedValue).toBe("some-pending-value"); }); - const scenarioName = scenarioIsAsync - ? "when admin messages propagate" - : "immediately"; + const scenarioName = scenarioIsAsync ? "when admin messages propagate" : "immediately"; // eslint-disable-next-line jest/valid-title describe(scenarioName, () => { @@ -345,9 +320,7 @@ const TestComponent = observer(({ someComputed }: { someComputed: IComputedValue expect(observedValue).toBe("some-pending-value"); }); - const scenarioTitle = scenarioIsAsync - ? "when value-messages propagate back" - : "immediately"; + const scenarioTitle = scenarioIsAsync ? "when value-messages propagate back" : "immediately"; // eslint-disable-next-line jest/valid-title describe(scenarioTitle, () => { @@ -466,9 +439,7 @@ const TestComponent = observer(({ someComputed }: { someComputed: IComputedValue expect(nonReactiveValue).toBe("some-initial-value"); }); - const scenarioName = scenarioIsAsync - ? "when messages would be propagated" - : "immediately"; + const scenarioName = scenarioIsAsync ? "when messages would be propagated" : "immediately"; // eslint-disable-next-line jest/valid-title describe(scenarioName, () => { diff --git a/packages/technical-features/messaging/electron/main/src/channel-listeners/enlist-message-channel-listener.test.ts b/packages/technical-features/messaging/electron/main/src/channel-listeners/enlist-message-channel-listener.test.ts index c4385246cd..898efdf3f1 100644 --- a/packages/technical-features/messaging/electron/main/src/channel-listeners/enlist-message-channel-listener.test.ts +++ b/packages/technical-features/messaging/electron/main/src/channel-listeners/enlist-message-channel-listener.test.ts @@ -1,9 +1,6 @@ import ipcMainInjectable from "../ipc-main/ipc-main.injectable"; import type { IpcMain, IpcMainEvent } from "electron"; -import { - EnlistMessageChannelListener, - enlistMessageChannelListenerInjectionToken, -} from "@k8slens/messaging"; +import { EnlistMessageChannelListener, enlistMessageChannelListenerInjectionToken } from "@k8slens/messaging"; import { createContainer } from "@ogre-tools/injectable"; import { registerFeature } from "@k8slens/feature-core"; import { messagingFeatureForMain } from "../feature"; diff --git a/packages/technical-features/messaging/electron/main/src/request-from-channel/request-from-channel.injectable.ts b/packages/technical-features/messaging/electron/main/src/request-from-channel/request-from-channel.injectable.ts index 220daf9fc7..94ce8c89be 100644 --- a/packages/technical-features/messaging/electron/main/src/request-from-channel/request-from-channel.injectable.ts +++ b/packages/technical-features/messaging/electron/main/src/request-from-channel/request-from-channel.injectable.ts @@ -1,19 +1,13 @@ /* c8 ignore start */ import { getInjectable } from "@ogre-tools/injectable"; -import { - RequestChannel, - RequestFromChannel, - requestFromChannelInjectionToken, -} from "@k8slens/messaging"; +import { RequestChannel, RequestFromChannel, requestFromChannelInjectionToken } from "@k8slens/messaging"; const requestFromChannelInjectable = getInjectable({ id: "request-from-channel", instantiate: () => ((channel: RequestChannel) => { - throw new Error( - `Tried to request from channel "${channel.id}" but requesting in "main" it's not supported yet`, - ); + throw new Error(`Tried to request from channel "${channel.id}" but requesting in "main" it's not supported yet`); }) as unknown as RequestFromChannel, injectionToken: requestFromChannelInjectionToken, diff --git a/packages/technical-features/messaging/electron/main/src/send-message-to-channel/allow-communication-listener.injectable.ts b/packages/technical-features/messaging/electron/main/src/send-message-to-channel/allow-communication-listener.injectable.ts index af74d7a810..7b80adabc0 100644 --- a/packages/technical-features/messaging/electron/main/src/send-message-to-channel/allow-communication-listener.injectable.ts +++ b/packages/technical-features/messaging/electron/main/src/send-message-to-channel/allow-communication-listener.injectable.ts @@ -1,9 +1,7 @@ import { getMessageChannel, getMessageChannelListenerInjectable } from "@k8slens/messaging"; import frameIdsInjectable from "./frameIds.injectable"; -const frameCommunicationAdminChannel = getMessageChannel( - "frame-communication-admin-channel", -); +const frameCommunicationAdminChannel = getMessageChannel("frame-communication-admin-channel"); const allowCommunicationListenerInjectable = getMessageChannelListenerInjectable({ id: "allow-communication", diff --git a/packages/technical-features/messaging/electron/renderer/src/allow-communication-to-iframe.injectable.ts b/packages/technical-features/messaging/electron/renderer/src/allow-communication-to-iframe.injectable.ts index 59abe7f931..fe8928caca 100644 --- a/packages/technical-features/messaging/electron/renderer/src/allow-communication-to-iframe.injectable.ts +++ b/packages/technical-features/messaging/electron/renderer/src/allow-communication-to-iframe.injectable.ts @@ -2,9 +2,7 @@ import { getInjectable } from "@ogre-tools/injectable"; import { onLoadOfApplicationInjectionToken } from "@k8slens/application"; import { getMessageChannel, sendMessageToChannelInjectionToken } from "@k8slens/messaging"; -export const frameCommunicationAdminChannel = getMessageChannel( - "frame-communication-admin-channel", -); +export const frameCommunicationAdminChannel = getMessageChannel("frame-communication-admin-channel"); const allowCommunicationToIframeInjectable = getInjectable({ id: "allow-communication-to-iframe-injectable", diff --git a/packages/technical-features/messaging/electron/renderer/src/listening-of-messages/enlist-message-channel-listener.test.ts b/packages/technical-features/messaging/electron/renderer/src/listening-of-messages/enlist-message-channel-listener.test.ts index dc89c7b3e7..a325821b91 100644 --- a/packages/technical-features/messaging/electron/renderer/src/listening-of-messages/enlist-message-channel-listener.test.ts +++ b/packages/technical-features/messaging/electron/renderer/src/listening-of-messages/enlist-message-channel-listener.test.ts @@ -1,9 +1,6 @@ import type { IpcRendererEvent, IpcRenderer } from "electron"; import ipcRendererInjectable from "../ipc/ipc-renderer.injectable"; -import { - EnlistMessageChannelListener, - enlistMessageChannelListenerInjectionToken, -} from "@k8slens/messaging"; +import { EnlistMessageChannelListener, enlistMessageChannelListenerInjectionToken } from "@k8slens/messaging"; import { createContainer } from "@ogre-tools/injectable"; import { registerFeature } from "@k8slens/feature-core"; import { messagingFeatureForRenderer } from "../feature"; diff --git a/packages/technical-features/messaging/message-bridge-fake/src/get-message-bridge-fake/get-message-bridge-fake.test.ts b/packages/technical-features/messaging/message-bridge-fake/src/get-message-bridge-fake/get-message-bridge-fake.test.ts index e91109df10..a3a3c86ad3 100644 --- a/packages/technical-features/messaging/message-bridge-fake/src/get-message-bridge-fake/get-message-bridge-fake.test.ts +++ b/packages/technical-features/messaging/message-bridge-fake/src/get-message-bridge-fake/get-message-bridge-fake.test.ts @@ -32,9 +32,7 @@ const someRequestChannelWithoutListeners: SomeRequestChannel = { }; [{ scenarioIsAsync: true }, { scenarioIsAsync: false }].forEach(({ scenarioIsAsync }) => - describe(`get-message-bridge-fake, given running as ${ - scenarioIsAsync ? "async" : "sync" - }`, () => { + describe(`get-message-bridge-fake, given running as ${scenarioIsAsync ? "async" : "sync"}`, () => { let messageBridgeFake: any; beforeEach(() => { @@ -135,9 +133,7 @@ const someRequestChannelWithoutListeners: SomeRequestChannel = { describe("given a message is sent in di-1", () => { beforeEach(() => { - const sendMessageToChannelFromDi1 = someDi1.inject( - sendMessageToChannelInjectionToken, - ); + const sendMessageToChannelFromDi1 = someDi1.inject(sendMessageToChannelInjectionToken); sendMessageToChannelFromDi1(someMessageChannel, "some-message"); }); @@ -161,13 +157,10 @@ const someRequestChannelWithoutListeners: SomeRequestChannel = { }); it("the response gets handled in di-1", () => { - expect(someHandler1MockInDi1).toHaveBeenCalledWith( - "some-response-to: some-message", - { - frameId: 42, - processId: 42, - }, - ); + expect(someHandler1MockInDi1).toHaveBeenCalledWith("some-response-to: some-message", { + frameId: 42, + processId: 42, + }); }); scenarioIsAsync && @@ -191,13 +184,10 @@ const someRequestChannelWithoutListeners: SomeRequestChannel = { }); it("the response gets handled in di-1", () => { - expect(someHandler1MockInDi1).toHaveBeenCalledWith( - "some-response-to: some-message", - { - frameId: 42, - processId: 42, - }, - ); + expect(someHandler1MockInDi1).toHaveBeenCalledWith("some-response-to: some-message", { + frameId: 42, + processId: 42, + }); }); }); }); @@ -375,9 +365,7 @@ const someRequestChannelWithoutListeners: SomeRequestChannel = { const requestFromChannelFromDi2 = someDi2.inject(requestFromChannelInjectionToken); - return expect(() => - requestFromChannelFromDi2(someRequestChannel, "irrelevant"), - ).rejects.toThrow( + return expect(() => requestFromChannelFromDi2(someRequestChannel, "irrelevant")).rejects.toThrow( 'Tried to make a request but multiple listeners were discovered for channel "some-request-channel" in multiple DIs.', ); }); @@ -385,9 +373,7 @@ const someRequestChannelWithoutListeners: SomeRequestChannel = { it("when requesting from channel without listener, throws", () => { const requestFromChannel = someDi1.inject(requestFromChannelInjectionToken); - return expect(() => - requestFromChannel(someRequestChannelWithoutListeners, "irrelevant"), - ).rejects.toThrow( + return expect(() => requestFromChannel(someRequestChannelWithoutListeners, "irrelevant")).rejects.toThrow( 'Tried to make a request but no listeners for channel "some-request-channel-without-listeners" was discovered in any DIs', ); }); diff --git a/packages/technical-features/messaging/message-bridge-fake/src/get-message-bridge-fake/get-message-bridge-fake.ts b/packages/technical-features/messaging/message-bridge-fake/src/get-message-bridge-fake/get-message-bridge-fake.ts index 8feb31dcd2..3e7efea5f9 100644 --- a/packages/technical-features/messaging/message-bridge-fake/src/get-message-bridge-fake/get-message-bridge-fake.ts +++ b/packages/technical-features/messaging/message-bridge-fake/src/get-message-bridge-fake/get-message-bridge-fake.ts @@ -22,7 +22,7 @@ import asyncFn, { AsyncFnMock } from "@async-fn/jest"; export type MessageBridgeFake = { involve: (...dis: DiContainer[]) => void; messagePropagation: () => Promise; - messagePropagationRecursive: (callback: any) => any; + messagePropagationRecursive: (callback: () => any) => any; setAsync: (value: boolean) => void; }; @@ -167,9 +167,7 @@ export const getMessageBridgeFake = (): MessageBridgeFake => { await Promise.all(oldMessages.map((x) => wrapper(x.resolve))); }; - const messagePropagationRecursive = async ( - wrapper: (callback: any) => any = (callback) => callback(), - ) => { + const messagePropagationRecursive = async (wrapper = (callback: () => any) => callback()) => { while (messagePropagationBuffer.size) { await messagePropagation(wrapper); } diff --git a/packages/technical-features/react-application/src/react-application/react-application.tsx b/packages/technical-features/react-application/src/react-application/react-application.tsx index 933d0ad389..982a49a3c1 100644 --- a/packages/technical-features/react-application/src/react-application/react-application.tsx +++ b/packages/technical-features/react-application/src/react-application/react-application.tsx @@ -27,9 +27,7 @@ const render = (components: ReactApplicationHigherOrderComponent[]) => { export const ReactApplication = observer(({ di }: ReactApplicationProps) => { const computedInjectMany = di.inject(computedInjectManyInjectable); - const higherOrderComponents = computedInjectMany( - reactApplicationHigherOrderComponentInjectionToken, - ); + const higherOrderComponents = computedInjectMany(reactApplicationHigherOrderComponentInjectionToken); const Components = [...higherOrderComponents.get(), ReactApplicationContent]; diff --git a/packages/utility-features/react-testing-library-discovery/index.ts b/packages/utility-features/react-testing-library-discovery/index.ts index 109c6af90f..92e817512c 100644 --- a/packages/utility-features/react-testing-library-discovery/index.ts +++ b/packages/utility-features/react-testing-library-discovery/index.ts @@ -5,9 +5,4 @@ export type { QuerySingleElement, } from "./src/discovery-of-html-elements"; -export { - discoverFor, - getSingleElement, - queryAllElements, - querySingleElement, -} from "./src/discovery-of-html-elements"; +export { discoverFor, getSingleElement, queryAllElements, querySingleElement } from "./src/discovery-of-html-elements"; diff --git a/packages/utility-features/react-testing-library-discovery/src/discovery-of-html-elements.ts b/packages/utility-features/react-testing-library-discovery/src/discovery-of-html-elements.ts index 0df7d9202d..0722c74732 100644 --- a/packages/utility-features/react-testing-library-discovery/src/discovery-of-html-elements.ts +++ b/packages/utility-features/react-testing-library-discovery/src/discovery-of-html-elements.ts @@ -26,8 +26,7 @@ export interface Discover { getSingleElement: GetSingleElement; } -const getBaseElement = (source: DiscoverySourceTypes) => - "baseElement" in source ? source.baseElement : source; +const getBaseElement = (source: DiscoverySourceTypes) => ("baseElement" in source ? source.baseElement : source); export function querySingleElement(getSource: () => DiscoverySourceTypes): QuerySingleElement { return (attributeName, attributeValue) => { @@ -35,9 +34,7 @@ export function querySingleElement(getSource: () => DiscoverySourceTypes): Query const dataAttribute = `data-${attributeName}-test`; - const selector = attributeValue - ? `[${dataAttribute}="${attributeValue}"]` - : `[${dataAttribute}]`; + const selector = attributeValue ? `[${dataAttribute}="${attributeValue}"]` : `[${dataAttribute}]`; const discovered = getBaseElement(source).querySelector(selector); @@ -78,10 +75,7 @@ export function getSingleElement(getSource: () => DiscoverySourceTypes): GetSing return (attributeName, attributeValue) => { const dataAttribute = `data-${attributeName}-test`; - const { discovered, ...nestedDiscover } = querySingleElement(getSource)( - attributeName, - attributeValue, - ); + const { discovered, ...nestedDiscover } = querySingleElement(getSource)(attributeName, attributeValue); if (!discovered) { // eslint-disable-next-line xss/no-mixed-html @@ -97,18 +91,14 @@ export function getSingleElement(getSource: () => DiscoverySourceTypes): GetSing ); } - throw new Error( - `Couldn't find HTML-element with attribute "${dataAttribute}"\n\nHTML is:\n\n${html}`, - ); + throw new Error(`Couldn't find HTML-element with attribute "${dataAttribute}"\n\nHTML is:\n\n${html}`); } const click = () => { if ("click" in discovered && typeof discovered.click === "function") { discovered.click(); } else { - throw new Error( - `Tried to click something that was not clickable:\n\n${prettyDom(discovered)}`, - ); + throw new Error(`Tried to click something that was not clickable:\n\n${prettyDom(discovered)}`); } };