Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/plugin-sdk/src/index.test.ts
T
2026-07-08 16:15:37 +02:00

638 lines
22 KiB
TypeScript

import { afterEach, describe, expect, expectTypeOf, test, vi } from "vitest";
import {
createPluginSettingsClient,
defineHook,
type HookHandler,
type PluginContext,
type PluginHookEntityPayload,
type PluginHookPayloads,
type PluginHookWorkflowDefinitionPayload,
type PluginHookWorkflowExecutedPayload,
type PluginHookWorkflowFailedPayload,
type PluginSettingsClientMessageEvent,
type PluginSettingsClientMessageTarget,
PluginSettingsClientError,
PluginSettingsClientTimeoutError,
type PluginSettingsFrameGetMessage,
type PluginSettingsFrameMessage,
type PluginSettingsFrameReadyMessage,
type PluginSettingsFrameResultMessage,
type PluginSettingsFrameSetMessage,
type TypedHookHandler,
PLUGIN_PAYLOAD_ABI_IMPORTS,
PLUGIN_PAYLOAD_ABI_VERSION,
PLUGIN_SETTINGS_FRAME_CHANNEL_META_NAME,
PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
PLUGIN_SDK_PACKAGE_VERSION,
} from "./index.js";
function makeContext(overrides: Partial<PluginContext> = {}): PluginContext {
const log = {
info: () => undefined,
warn: () => undefined,
error: () => undefined,
};
return {
pluginId: "de.hivegrid.test",
pluginVersion: "1.0.0",
tenantId: "t-1",
hookName: "ping",
capabilities: ["log"],
log,
audit: { record: async () => undefined },
...overrides,
};
}
function makeSettingsFrameWindow() {
const posted: Array<{ message: PluginSettingsFrameMessage; targetOrigin: string }> = [];
const listeners = new Set<(event: PluginSettingsClientMessageEvent) => void>();
const parent: PluginSettingsClientMessageTarget = {
postMessage: (message, targetOrigin) => {
posted.push({ message, targetOrigin });
},
};
return {
parent,
posted,
emit: (event: PluginSettingsClientMessageEvent) => {
for (const listener of listeners) {
listener(event);
}
},
listenerCount: () => listeners.size,
addEventListener: (type: "message", listener: (event: PluginSettingsClientMessageEvent) => void) => {
expect(type).toBe("message");
listeners.add(listener);
},
removeEventListener: (type: "message", listener: (event: PluginSettingsClientMessageEvent) => void) => {
expect(type).toBe("message");
listeners.delete(listener);
},
};
}
describe("@hivegrid/plugin-sdk", () => {
test("exports a stable version constant", () => {
expect(PLUGIN_SDK_PACKAGE_VERSION).toBe("0.0.0");
});
test("exports the structured payload ABI contract", () => {
expect(PLUGIN_PAYLOAD_ABI_VERSION).toBe(1);
expect(PLUGIN_PAYLOAD_ABI_IMPORTS).toEqual(["env.hivegrid_payload_len", "env.hivegrid_payload_byte"]);
});
test("exports the settings iframe postMessage protocol contract", () => {
expect(PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION).toBe(1);
expect(PLUGIN_SETTINGS_FRAME_CHANNEL_META_NAME).toBe("plugin-settings-channel");
const getMessage: PluginSettingsFrameGetMessage = {
type: "plugin.settings.get",
version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
pluginId: "de.hivegrid.test",
channelId: "channel-1",
requestId: "get-1",
key: "theme",
};
const setMessage: PluginSettingsFrameSetMessage = {
type: "plugin.settings.set",
version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
pluginId: "de.hivegrid.test",
channelId: "channel-1",
requestId: "set-1",
key: "theme",
value: { mode: "dark", compact: true },
};
const resultMessage: PluginSettingsFrameResultMessage = {
type: "plugin.settings.result",
version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
pluginId: "de.hivegrid.test",
channelId: "channel-1",
requestId: "get-1",
ok: true,
key: "theme",
value: "dark",
};
expectTypeOf<PluginSettingsFrameMessage>().toEqualTypeOf<
PluginSettingsFrameReadyMessage | typeof getMessage | typeof setMessage
>();
expectTypeOf<PluginSettingsFrameResultMessage>().toEqualTypeOf<typeof resultMessage | Extract<PluginSettingsFrameResultMessage, { ok: false }>>();
expect(getMessage.type).toBe("plugin.settings.get");
expect(setMessage.value).toEqual({ mode: "dark", compact: true });
expect(resultMessage.ok).toBe(true);
});
test("createPluginSettingsClient posts ready, get, and set messages", async () => {
const frameWindow = makeSettingsFrameWindow();
const client = createPluginSettingsClient({
pluginId: "de.hivegrid.test",
channelId: "channel-1",
targetOrigin: "https://app.example.test",
requestId: () => "request-1",
window: frameWindow,
});
client.ready({ requestId: "ready-1" });
const getPromise = client.get("theme");
const setPromise = client.set("mode", "dark", { requestId: "set-1" });
expect(frameWindow.posted).toEqual([
{
targetOrigin: "https://app.example.test",
message: {
type: "plugin.settings.ready",
version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
pluginId: "de.hivegrid.test",
channelId: "channel-1",
requestId: "ready-1",
},
},
{
targetOrigin: "https://app.example.test",
message: {
type: "plugin.settings.get",
version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
pluginId: "de.hivegrid.test",
channelId: "channel-1",
requestId: "request-1",
key: "theme",
},
},
{
targetOrigin: "https://app.example.test",
message: {
type: "plugin.settings.set",
version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
pluginId: "de.hivegrid.test",
channelId: "channel-1",
requestId: "set-1",
key: "mode",
value: "dark",
},
},
]);
frameWindow.emit({
source: frameWindow.parent,
data: {
type: "plugin.settings.result",
version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
pluginId: "de.hivegrid.test",
channelId: "channel-1",
requestId: "request-1",
ok: true,
key: "theme",
value: { mode: "dark" },
},
});
frameWindow.emit({
source: frameWindow.parent,
data: {
type: "plugin.settings.result",
version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
pluginId: "de.hivegrid.test",
channelId: "channel-1",
requestId: "set-1",
ok: true,
key: "mode",
value: "dark",
},
});
await expect(getPromise).resolves.toEqual({ mode: "dark" });
await expect(setPromise).resolves.toBe("dark");
client.destroy();
expect(frameWindow.listenerCount()).toBe(0);
});
test("createPluginSettingsClient reads the injected channel meta tag", () => {
const frameWindow = makeSettingsFrameWindow();
const client = createPluginSettingsClient({
pluginId: "de.hivegrid.test",
window: frameWindow,
document: {
querySelector: (selector) => {
expect(selector).toBe(`meta[name="${PLUGIN_SETTINGS_FRAME_CHANNEL_META_NAME}"]`);
return { getAttribute: () => "channel-from-meta" };
},
},
});
expect(client.channelId).toBe("channel-from-meta");
client.destroy();
});
test("createPluginSettingsClient ignores result messages that do not match the parent and request scope", async () => {
const frameWindow = makeSettingsFrameWindow();
const client = createPluginSettingsClient({
pluginId: "de.hivegrid.test",
channelId: "channel-1",
timeoutMs: 0,
window: frameWindow,
});
const promise = client.get("theme", { requestId: "get-1" });
for (const data of [
{ version: 2, pluginId: "de.hivegrid.test", channelId: "channel-1", requestId: "get-1" },
{ version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION, pluginId: "other", channelId: "channel-1", requestId: "get-1" },
{ version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION, pluginId: "de.hivegrid.test", channelId: "other", requestId: "get-1" },
{ version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION, pluginId: "de.hivegrid.test", channelId: "channel-1", requestId: "other" },
]) {
frameWindow.emit({
source: frameWindow.parent,
data: {
type: "plugin.settings.result",
ok: true,
key: "theme",
value: "spoofed",
...data,
},
});
}
frameWindow.emit({
source: { postMessage: () => undefined },
data: {
type: "plugin.settings.result",
version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
pluginId: "de.hivegrid.test",
channelId: "channel-1",
requestId: "get-1",
ok: true,
key: "theme",
value: "spoofed-source",
},
});
frameWindow.emit({
source: frameWindow.parent,
data: {
type: "plugin.settings.result",
version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
pluginId: "de.hivegrid.test",
channelId: "channel-1",
requestId: "get-1",
ok: true,
key: "theme",
value: "dark",
},
});
await expect(promise).resolves.toBe("dark");
client.destroy();
});
test("createPluginSettingsClient rejects host errors and mismatched response keys", async () => {
const frameWindow = makeSettingsFrameWindow();
const client = createPluginSettingsClient({
pluginId: "de.hivegrid.test",
channelId: "channel-1",
timeoutMs: 0,
window: frameWindow,
});
const failed = client.set("theme", "dark", { requestId: "set-1" });
frameWindow.emit({
source: frameWindow.parent,
data: {
type: "plugin.settings.result",
version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
pluginId: "de.hivegrid.test",
channelId: "channel-1",
requestId: "set-1",
ok: false,
error: "settings_update_failed",
message: "Write failed",
},
});
await expect(failed).rejects.toBeInstanceOf(PluginSettingsClientError);
await expect(failed).rejects.toMatchObject({ code: "settings_update_failed", message: "Write failed" });
const mismatched = client.get("theme", { requestId: "get-1" });
frameWindow.emit({
source: frameWindow.parent,
data: {
type: "plugin.settings.result",
version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
pluginId: "de.hivegrid.test",
channelId: "channel-1",
requestId: "get-1",
ok: true,
key: "other",
value: "dark",
},
});
await expect(mismatched).rejects.toThrow("Plugin settings response key mismatch");
client.destroy();
});
test("createPluginSettingsClient rejects timed out requests", async () => {
const frameWindow = makeSettingsFrameWindow();
const client = createPluginSettingsClient({
pluginId: "de.hivegrid.test",
channelId: "channel-1",
timeoutMs: 1,
window: frameWindow,
});
await expect(client.get("theme", { requestId: "get-1" })).rejects.toBeInstanceOf(PluginSettingsClientTimeoutError);
client.destroy();
});
test("defineHook preserves the typed handler", async () => {
const handler = defineHook<{ name: string }, { greeting: string }>((input) => ({
greeting: `Hello, ${input.name}!`,
}));
const result = await handler({ name: "World" }, makeContext());
expect(result.greeting).toBe("Hello, World!");
});
test("HookHandler accepts async handlers", async () => {
const handler: HookHandler<number, number> = async (n) => n * 2;
expect(await handler(21, makeContext())).toBe(42);
});
test("TypedHookHandler exposes canonical entity hook payloads", async () => {
expectTypeOf<PluginHookPayloads["entity.updated"]>().toEqualTypeOf<PluginHookEntityPayload>();
const handler: TypedHookHandler<"entity.updated", { target: string }> = (input) => ({
target: `${input.entityType}:${input.entityId}`,
});
const result = await handler(
{
entityType: "contact",
entityId: "row_1",
tenantId: "tenant_1",
userId: "user_1",
changedFields: ["email"],
occurredAt: "2026-05-27T12:00:00.000Z",
},
makeContext({ hookName: "entity.updated" })
);
expect(result).toEqual({ target: "contact:row_1" });
});
test("TypedHookHandler exposes workflow.executed metadata without raw execution bodies", async () => {
expectTypeOf<PluginHookPayloads["workflow.executed"]>().toEqualTypeOf<PluginHookWorkflowExecutedPayload>();
expectTypeOf<PluginHookWorkflowExecutedPayload>().not.toHaveProperty("input");
expectTypeOf<PluginHookWorkflowExecutedPayload>().not.toHaveProperty("output");
expectTypeOf<PluginHookWorkflowExecutedPayload>().not.toHaveProperty("error");
const handler: TypedHookHandler<"workflow.executed", { terminal: true }> = (input) => {
expect(input.status).toBe("success");
expect(input.errorCode).toBeNull();
return { terminal: true };
};
const result = await handler(
{
tenantId: "tenant_1",
workflowId: "workflow_1",
workflowExecutionId: "execution_1",
userId: "user_1",
type: "trigger",
status: "success",
durationMs: 42,
errorCode: null,
appliesToAllTenants: false,
occurredAt: "2026-05-27T12:00:00.000Z",
},
makeContext({ hookName: "workflow.executed" })
);
expect(result).toEqual({ terminal: true });
});
test("TypedHookHandler exposes workflow.failed failure-only metadata", async () => {
expectTypeOf<PluginHookPayloads["workflow.failed"]>().toEqualTypeOf<PluginHookWorkflowFailedPayload>();
expectTypeOf<PluginHookWorkflowFailedPayload>().not.toHaveProperty("input");
expectTypeOf<PluginHookWorkflowFailedPayload>().not.toHaveProperty("output");
expectTypeOf<PluginHookWorkflowFailedPayload>().not.toHaveProperty("error");
const handler: TypedHookHandler<"workflow.failed", { failureCode: string }> = (input) => ({
failureCode: input.errorCode,
});
const result = await handler(
{
tenantId: "tenant_1",
workflowId: "workflow_1",
workflowExecutionId: "execution_1",
userId: null,
type: "trigger",
status: "error",
durationMs: 42,
errorCode: "workflow_execution_failed",
appliesToAllTenants: false,
occurredAt: "2026-05-27T12:00:00.000Z",
},
makeContext({ hookName: "workflow.failed" })
);
expect(result).toEqual({ failureCode: "workflow_execution_failed" });
});
test("TypedHookHandler exposes workflow definition metadata without workflow bodies", async () => {
expectTypeOf<PluginHookPayloads["workflow.updated"]>().toEqualTypeOf<PluginHookWorkflowDefinitionPayload>();
expectTypeOf<PluginHookWorkflowDefinitionPayload>().not.toHaveProperty("blocks");
expectTypeOf<PluginHookWorkflowDefinitionPayload>().not.toHaveProperty("credentials");
expectTypeOf<PluginHookWorkflowDefinitionPayload>().not.toHaveProperty("input");
const handler: TypedHookHandler<"workflow.updated", { changed: number }> = (input) => ({
changed: input.changedFields?.length ?? 0,
});
const result = await handler(
{
tenantId: "tenant_1",
workflowId: "workflow_1",
userId: "user_1",
status: "live",
appliesToAllTenants: false,
changedFields: ["status"],
occurredAt: "2026-05-27T12:00:00.000Z",
},
makeContext({ hookName: "workflow.updated" })
);
expect(result).toEqual({ changed: 1 });
});
});
describe("createPluginSettingsClient default-environment + lifecycle coverage", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
test("throws when the default window has no parent postMessage target", () => {
vi.stubGlobal("window", undefined);
expect(() => createPluginSettingsClient({ pluginId: "de.hivegrid.test", channelId: "channel-1" })).toThrow(
"Plugin settings client requires a window with a parent postMessage target"
);
});
test("ignores a default window that is missing a parent", () => {
vi.stubGlobal("window", { addEventListener: () => undefined, removeEventListener: () => undefined });
expect(() => createPluginSettingsClient({ pluginId: "de.hivegrid.test", channelId: "channel-1" })).toThrow(
"Plugin settings client requires a window with a parent postMessage target"
);
});
test("ignores a default window whose parent is present but lacks addEventListener", () => {
vi.stubGlobal("window", { parent: { postMessage: () => undefined }, removeEventListener: () => undefined });
expect(() => createPluginSettingsClient({ pluginId: "de.hivegrid.test", channelId: "channel-1" })).toThrow(
"Plugin settings client requires a window with a parent postMessage target"
);
});
test("ignores a default window that lacks removeEventListener", () => {
vi.stubGlobal("window", { parent: { postMessage: () => undefined }, addEventListener: () => undefined });
expect(() => createPluginSettingsClient({ pluginId: "de.hivegrid.test", channelId: "channel-1" })).toThrow(
"Plugin settings client requires a window with a parent postMessage target"
);
});
test("falls back to the default window when no window option is given", () => {
const frameWindow = makeSettingsFrameWindow();
vi.stubGlobal("window", frameWindow);
const client = createPluginSettingsClient({ pluginId: "de.hivegrid.test", channelId: "channel-1" });
expect(frameWindow.listenerCount()).toBe(1);
client.ready();
expect(frameWindow.posted).toHaveLength(1);
client.destroy();
expect(frameWindow.listenerCount()).toBe(0);
});
test("reads the channel id from the default document meta tag", () => {
const frameWindow = makeSettingsFrameWindow();
vi.stubGlobal("document", {
querySelector: (selector: string) => {
expect(selector).toBe(`meta[name="${PLUGIN_SETTINGS_FRAME_CHANNEL_META_NAME}"]`);
return { getAttribute: () => "default-doc-channel" };
},
});
const client = createPluginSettingsClient({ pluginId: "de.hivegrid.test", window: frameWindow });
expect(client.channelId).toBe("default-doc-channel");
client.destroy();
});
test("throws on a missing channel when the default document has no matching meta tag", () => {
const frameWindow = makeSettingsFrameWindow();
vi.stubGlobal("document", { querySelector: () => null });
expect(() => createPluginSettingsClient({ pluginId: "de.hivegrid.test", window: frameWindow })).toThrow(
"Missing plugin settings channel"
);
});
test("ignores a default document without a querySelector and throws on the missing channel", () => {
const frameWindow = makeSettingsFrameWindow();
vi.stubGlobal("document", {});
expect(() => createPluginSettingsClient({ pluginId: "de.hivegrid.test", window: frameWindow })).toThrow(
"Missing plugin settings channel"
);
});
test("ignores an absent default document and throws on the missing channel", () => {
const frameWindow = makeSettingsFrameWindow();
vi.stubGlobal("document", undefined);
expect(() => createPluginSettingsClient({ pluginId: "de.hivegrid.test", window: frameWindow })).toThrow(
"Missing plugin settings channel"
);
});
test("throws when the channel meta tag is present but empty", () => {
const frameWindow = makeSettingsFrameWindow();
expect(() =>
createPluginSettingsClient({
pluginId: "de.hivegrid.test",
window: frameWindow,
document: { querySelector: () => ({ getAttribute: () => null }) },
})
).toThrow("Missing plugin settings channel");
});
test("throws when the channel meta tag is absent", () => {
const frameWindow = makeSettingsFrameWindow();
expect(() =>
createPluginSettingsClient({
pluginId: "de.hivegrid.test",
window: frameWindow,
document: { querySelector: () => null },
})
).toThrow("Missing plugin settings channel");
});
test("generates sequential request ids when none are provided", async () => {
const frameWindow = makeSettingsFrameWindow();
const client = createPluginSettingsClient({
pluginId: "de.hivegrid.test",
channelId: "channel-1",
timeoutMs: 0,
window: frameWindow,
});
const first = client.get("a");
const second = client.set("b", 7);
const ids = frameWindow.posted.map((entry) => (entry.message as { requestId?: string }).requestId);
expect(ids).toEqual(["plugin-settings-1", "plugin-settings-2"]);
for (const [requestId, key, value] of [
["plugin-settings-1", "a", 1],
["plugin-settings-2", "b", 7],
] as const) {
frameWindow.emit({
source: frameWindow.parent,
data: {
type: "plugin.settings.result",
version: PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
pluginId: "de.hivegrid.test",
channelId: "channel-1",
requestId,
ok: true,
key,
value,
},
});
}
await expect(first).resolves.toBe(1);
await expect(second).resolves.toBe(7);
client.destroy();
});
test("destroy rejects pending requests and clears their active timeouts", async () => {
const frameWindow = makeSettingsFrameWindow();
const client = createPluginSettingsClient({
pluginId: "de.hivegrid.test",
channelId: "channel-1",
timeoutMs: 60_000,
window: frameWindow,
});
const pending = client.get("theme", { requestId: "get-1" });
client.destroy();
await expect(pending).rejects.toThrow("Plugin settings client destroyed before response: get-1");
expect(frameWindow.listenerCount()).toBe(0);
});
test("destroy rejects pending requests that were created without an active timeout", async () => {
const frameWindow = makeSettingsFrameWindow();
const client = createPluginSettingsClient({
pluginId: "de.hivegrid.test",
channelId: "channel-1",
timeoutMs: 0,
window: frameWindow,
});
const pending = client.set("theme", "dark", { requestId: "set-1" });
client.destroy();
await expect(pending).rejects.toThrow("Plugin settings client destroyed before response: set-1");
});
});