first commit

This commit is contained in:
Matt Kane
2026-04-01 10:44:22 +01:00
commit 43fcb9a131
1789 changed files with 395041 additions and 0 deletions

View File

@@ -0,0 +1,403 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { BlockRenderer } from "../src/renderer.js";
import type { BlockInteraction, FormBlock } from "../src/types.js";
// ── Mocks ────────────────────────────────────────────────────────────────────
vi.mock("@cloudflare/kumo", () => ({
Button: ({ children, onClick, variant, type }: any) => (
<button onClick={onClick} data-variant={variant} type={type || "button"}>
{children}
</button>
),
Badge: ({ children }: any) => <span data-testid="badge">{children}</span>,
Input: ({ label, value, defaultValue, onChange, onBlur, placeholder, type, min, max }: any) => (
<div>
<label>{label}</label>
<input
type={type || "text"}
defaultValue={defaultValue}
value={value}
placeholder={placeholder}
min={min}
max={max}
onChange={onChange}
onBlur={onBlur}
/>
</div>
),
InputArea: ({ label, defaultValue, onChange, onBlur, placeholder }: any) => (
<div>
<label>{label}</label>
<textarea
defaultValue={defaultValue}
placeholder={placeholder}
onChange={onChange}
onBlur={onBlur}
/>
</div>
),
Select: Object.assign(
({ children, label, defaultValue, onValueChange }: any) => (
<div>
<label>{label}</label>
<select defaultValue={defaultValue} onChange={(e: any) => onValueChange?.(e.target.value)}>
{children}
</select>
</div>
),
{
Option: ({ children, value }: any) => <option value={value}>{children}</option>,
},
),
Switch: ({ label, checked, onCheckedChange }: any) => (
<div>
<label>
<input
type="checkbox"
checked={checked}
onChange={(e: any) => onCheckedChange?.(e.target.checked)}
/>
{label}
</label>
</div>
),
SensitiveInput: ({
label,
value,
onValueChange,
readOnly,
onFocus,
onBlur,
placeholder,
}: any) => (
<div>
<label>{label}</label>
<input
type="password"
value={value}
readOnly={readOnly}
onFocus={onFocus}
onBlur={onBlur}
placeholder={placeholder}
onChange={(e: any) => onValueChange?.(e.target.value)}
/>
</div>
),
Dialog: ({ children }: any) => <div data-testid="dialog">{children}</div>,
DialogRoot: ({ children, open }: any) =>
open ? <div data-testid="dialog-root">{children}</div> : null,
Banner: ({ title, description, variant, icon }: any) => (
<div data-testid="banner" data-variant={variant}>
{icon}
{title && <strong>{title}</strong>}
{description && <p>{description}</p>}
</div>
),
Meter: ({ label, value, max, min, customValue }: any) => (
<div data-testid="meter" data-value={value} data-max={max} data-min={min}>
<span>{label}</span>
{customValue && <span>{customValue}</span>}
</div>
),
CodeBlock: ({ code, lang }: any) => (
<pre data-testid="code-block" data-lang={lang}>
<code>{code}</code>
</pre>
),
Checkbox: {
Group: ({ children, legend }: any) => (
<fieldset data-testid="checkbox-group">
<legend>{legend}</legend>
{children}
</fieldset>
),
Item: ({ label, value }: any) => (
<label>
<input type="checkbox" value={value} />
{label}
</label>
),
},
Radio: {
Group: ({ children, legend }: any) => (
<fieldset data-testid="radio-group">
<legend>{legend}</legend>
{children}
</fieldset>
),
Item: ({ label, value }: any) => (
<label>
<input type="radio" value={value} />
{label}
</label>
),
},
Combobox: Object.assign(
({ children, label }: any) => (
<div data-testid="combobox">
<label>{label}</label>
{children}
</div>
),
{
TriggerInput: ({ placeholder }: any) => <input placeholder={placeholder} />,
Content: ({ children }: any) => <div>{children}</div>,
List: ({ children }: any) => <div>{typeof children === "function" ? null : children}</div>,
Item: ({ children, value }: any) => <div data-value={value}>{children}</div>,
Empty: ({ children }: any) => <div>{children}</div>,
},
),
}));
vi.mock("@cloudflare/kumo/components/chart", () => ({
TimeseriesChart: (props: any) => (
<div data-testid="timeseries-chart" data-height={props.height} />
),
Chart: (props: any) => <div data-testid="custom-chart" data-height={props.height} />,
ChartPalette: { color: (i: number) => `#color${i}` },
}));
// eslint-disable-next-line unicorn/consistent-function-scoping -- vi.mock is hoisted; cannot reference outer scope
vi.mock("echarts/core", () => {
const noop = () => {};
return { __esModule: true, default: { use: noop }, use: noop };
});
vi.mock("echarts/charts", () => ({
BarChart: {},
LineChart: {},
PieChart: {},
}));
vi.mock("echarts/components", () => ({
AriaComponent: {},
AxisPointerComponent: {},
GridComponent: {},
TooltipComponent: {},
}));
vi.mock("echarts/renderers", () => ({
CanvasRenderer: {},
}));
vi.mock("@phosphor-icons/react", () => ({
ArrowUp: () => <span data-testid="arrow-up" />,
ArrowDown: () => <span data-testid="arrow-down" />,
Minus: () => <span data-testid="minus" />,
Info: () => <span data-testid="icon-info" />,
Warning: () => <span data-testid="icon-warning" />,
WarningCircle: () => <span data-testid="icon-warning-circle" />,
}));
afterEach(cleanup);
// ── Helpers ──────────────────────────────────────────────────────────────────
function renderForm(form: FormBlock, onAction?: (i: BlockInteraction) => void) {
const handler = onAction ?? vi.fn();
return {
...render(<BlockRenderer blocks={[form]} onAction={handler} />),
onAction: handler,
};
}
// ── Tests ────────────────────────────────────────────────────────────────────
describe("form conditional fields", () => {
it("condition eq: field shown when condition met", () => {
renderForm({
type: "form",
fields: [
{
type: "toggle",
action_id: "enable",
label: "Enable",
initial_value: true,
},
{
type: "text_input",
action_id: "name",
label: "Name",
condition: { field: "enable", eq: true },
},
],
submit: { label: "Save", action_id: "save" },
});
// Toggle is true → Name field should be visible
expect(screen.getByText("Name")).toBeTruthy();
});
it("condition eq: field hidden when condition not met", () => {
renderForm({
type: "form",
fields: [
{
type: "toggle",
action_id: "enable",
label: "Enable",
initial_value: false,
},
{
type: "text_input",
action_id: "name",
label: "Name",
condition: { field: "enable", eq: true },
},
],
submit: { label: "Save", action_id: "save" },
});
// Toggle is false → Name field should not be rendered
expect(screen.queryByText("Name")).toBeNull();
});
it("condition neq: field shown when value differs", () => {
renderForm({
type: "form",
fields: [
{
type: "select",
action_id: "status",
label: "Status",
options: [
{ label: "Active", value: "active" },
{ label: "Disabled", value: "disabled" },
],
initial_value: "active",
},
{
type: "text_input",
action_id: "reason",
label: "Reason",
condition: { field: "status", neq: "disabled" },
},
],
submit: { label: "Save", action_id: "save" },
});
// Status is "active" which is != "disabled" → Reason field visible
expect(screen.getByText("Reason")).toBeTruthy();
});
it("condition reacts to changes", () => {
renderForm({
type: "form",
fields: [
{
type: "toggle",
action_id: "show_extra",
label: "Show extra",
initial_value: false,
},
{
type: "text_input",
action_id: "extra",
label: "Extra field",
condition: { field: "show_extra", eq: true },
},
],
submit: { label: "Save", action_id: "save" },
});
// Initially hidden
expect(screen.queryByText("Extra field")).toBeNull();
// Click toggle to enable
const toggle = screen.getByRole("checkbox");
fireEvent.click(toggle);
// Now visible
expect(screen.getByText("Extra field")).toBeTruthy();
});
it("hidden field values are included in submit payload", () => {
const onAction = vi.fn();
renderForm(
{
type: "form",
fields: [
{
type: "toggle",
action_id: "show_name",
label: "Show name",
initial_value: true,
},
{
type: "text_input",
action_id: "name",
label: "Name",
initial_value: "Alice",
condition: { field: "show_name", eq: true },
},
],
submit: { label: "Save", action_id: "save" },
},
onAction,
);
// Field is visible, then hide it by toggling off
const toggle = screen.getByRole("checkbox");
fireEvent.click(toggle);
// Name field is now hidden
expect(screen.queryByText("Name")).toBeNull();
// Submit — hidden field's last known value should still be in payload
fireEvent.click(screen.getByText("Save"));
expect(onAction).toHaveBeenCalledWith(
expect.objectContaining({
type: "form_submit",
action_id: "save",
values: expect.objectContaining({
show_name: false,
name: "Alice",
}),
}),
);
});
it("multiple conditional fields evaluate independently", () => {
renderForm({
type: "form",
fields: [
{
type: "toggle",
action_id: "toggle_a",
label: "Toggle A",
initial_value: true,
},
{
type: "toggle",
action_id: "toggle_b",
label: "Toggle B",
initial_value: false,
},
{
type: "text_input",
action_id: "field_a",
label: "Field A",
condition: { field: "toggle_a", eq: true },
},
{
type: "text_input",
action_id: "field_b",
label: "Field B",
condition: { field: "toggle_b", eq: true },
},
],
submit: { label: "Save", action_id: "save" },
});
// Toggle A is true → Field A visible
expect(screen.getByText("Field A")).toBeTruthy();
// Toggle B is false → Field B hidden
expect(screen.queryByText("Field B")).toBeNull();
});
});

View File

@@ -0,0 +1,494 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { BlockRenderer } from "../src/renderer.js";
import type { Block, BlockInteraction } from "../src/types.js";
// ── Mocks ────────────────────────────────────────────────────────────────────
vi.mock("@cloudflare/kumo", () => ({
Button: ({ children, onClick, variant, type }: any) => (
<button onClick={onClick} data-variant={variant} type={type || "button"}>
{children}
</button>
),
Badge: ({ children }: any) => <span data-testid="badge">{children}</span>,
Input: ({ label, value, defaultValue, onChange, onBlur, placeholder, type, min, max }: any) => (
<div>
<label>{label}</label>
<input
type={type || "text"}
defaultValue={defaultValue}
value={value}
placeholder={placeholder}
min={min}
max={max}
onChange={onChange}
onBlur={onBlur}
/>
</div>
),
InputArea: ({ label, defaultValue, onChange, onBlur, placeholder }: any) => (
<div>
<label>{label}</label>
<textarea
defaultValue={defaultValue}
placeholder={placeholder}
onChange={onChange}
onBlur={onBlur}
/>
</div>
),
Select: Object.assign(
({ children, label, defaultValue, onValueChange }: any) => (
<div>
<label>{label}</label>
<select defaultValue={defaultValue} onChange={(e: any) => onValueChange?.(e.target.value)}>
{children}
</select>
</div>
),
{
Option: ({ children, value }: any) => <option value={value}>{children}</option>,
},
),
Switch: ({ label, checked, onCheckedChange }: any) => (
<div>
<label>
<input
type="checkbox"
checked={checked}
onChange={(e: any) => onCheckedChange?.(e.target.checked)}
/>
{label}
</label>
</div>
),
SensitiveInput: ({
label,
value,
onValueChange,
readOnly,
onFocus,
onBlur,
placeholder,
}: any) => (
<div>
<label>{label}</label>
<input
type="password"
value={value}
readOnly={readOnly}
onFocus={onFocus}
onBlur={onBlur}
placeholder={placeholder}
onChange={(e: any) => onValueChange?.(e.target.value)}
/>
</div>
),
Dialog: ({ children }: any) => <div data-testid="dialog">{children}</div>,
DialogRoot: ({ children, open }: any) =>
open ? <div data-testid="dialog-root">{children}</div> : null,
Banner: ({ title, description, variant, icon }: any) => (
<div data-testid="banner" data-variant={variant}>
{icon}
{title && <strong>{title}</strong>}
{description && <p>{description}</p>}
</div>
),
Meter: ({ label, value, max, min, customValue }: any) => (
<div data-testid="meter" data-value={value} data-max={max} data-min={min}>
<span>{label}</span>
{customValue && <span>{customValue}</span>}
</div>
),
CodeBlock: ({ code, lang }: any) => (
<pre data-testid="code-block" data-lang={lang}>
<code>{code}</code>
</pre>
),
Checkbox: {
Group: ({ children, legend }: any) => (
<fieldset data-testid="checkbox-group">
<legend>{legend}</legend>
{children}
</fieldset>
),
Item: ({ label, value }: any) => (
<label>
<input type="checkbox" value={value} />
{label}
</label>
),
},
Radio: {
Group: ({ children, legend }: any) => (
<fieldset data-testid="radio-group">
<legend>{legend}</legend>
{children}
</fieldset>
),
Item: ({ label, value }: any) => (
<label>
<input type="radio" value={value} />
{label}
</label>
),
},
Combobox: Object.assign(
({ children, label }: any) => (
<div data-testid="combobox">
<label>{label}</label>
{children}
</div>
),
{
TriggerInput: ({ placeholder }: any) => <input placeholder={placeholder} />,
Content: ({ children }: any) => <div>{children}</div>,
List: ({ children }: any) => <div>{typeof children === "function" ? null : children}</div>,
Item: ({ children, value }: any) => <div data-value={value}>{children}</div>,
Empty: ({ children }: any) => <div>{children}</div>,
},
),
}));
vi.mock("@cloudflare/kumo/components/chart", () => ({
TimeseriesChart: (props: any) => (
<div data-testid="timeseries-chart" data-height={props.height} />
),
Chart: (props: any) => <div data-testid="custom-chart" data-height={props.height} />,
ChartPalette: { color: (i: number) => `#color${i}` },
}));
// eslint-disable-next-line unicorn/consistent-function-scoping -- vi.mock is hoisted; cannot reference outer scope
vi.mock("echarts/core", () => {
const noop = () => {};
return { __esModule: true, default: { use: noop }, use: noop };
});
vi.mock("echarts/charts", () => ({
BarChart: {},
LineChart: {},
PieChart: {},
}));
vi.mock("echarts/components", () => ({
AriaComponent: {},
AxisPointerComponent: {},
GridComponent: {},
TooltipComponent: {},
}));
vi.mock("echarts/renderers", () => ({
CanvasRenderer: {},
}));
vi.mock("@phosphor-icons/react", () => ({
ArrowUp: () => <span data-testid="arrow-up" />,
ArrowDown: () => <span data-testid="arrow-down" />,
Minus: () => <span data-testid="minus" />,
Info: () => <span data-testid="icon-info" />,
Warning: () => <span data-testid="icon-warning" />,
WarningCircle: () => <span data-testid="icon-warning-circle" />,
}));
afterEach(cleanup);
// ── Helpers ──────────────────────────────────────────────────────────────────
function renderBlocks(blocks: Block[], onAction?: (i: BlockInteraction) => void) {
const handler = onAction ?? vi.fn();
return { ...render(<BlockRenderer blocks={blocks} onAction={handler} />), onAction: handler };
}
// ── Tests ────────────────────────────────────────────────────────────────────
describe("BlockRenderer", () => {
it("header block renders h2 with text", () => {
renderBlocks([{ type: "header", text: "Settings" }]);
const heading = screen.getByText("Settings");
expect(heading.tagName).toBe("H2");
});
it("section block renders text", () => {
renderBlocks([{ type: "section", text: "Configure your integration." }]);
expect(screen.getByText("Configure your integration.")).toBeTruthy();
});
it("section block renders accessory button", () => {
renderBlocks([
{
type: "section",
text: "Webhook endpoint",
accessory: { type: "button", action_id: "edit", label: "Edit" },
},
]);
expect(screen.getByText("Webhook endpoint")).toBeTruthy();
expect(screen.getByText("Edit")).toBeTruthy();
});
it("divider block renders hr", () => {
const { container } = renderBlocks([{ type: "divider" }]);
expect(container.querySelector("hr")).toBeTruthy();
});
it("fields block renders labels and values in grid", () => {
renderBlocks([
{
type: "fields",
fields: [
{ label: "Status", value: "Active" },
{ label: "Plan", value: "Pro" },
],
},
]);
expect(screen.getByText("Status")).toBeTruthy();
expect(screen.getByText("Active")).toBeTruthy();
expect(screen.getByText("Plan")).toBeTruthy();
expect(screen.getByText("Pro")).toBeTruthy();
});
it("table block renders column headers and row data", () => {
renderBlocks([
{
type: "table",
columns: [
{ key: "name", label: "Name" },
{ key: "role", label: "Role" },
],
rows: [{ name: "Alice", role: "Admin" }],
page_action_id: "page",
},
]);
expect(screen.getByText("Name")).toBeTruthy();
expect(screen.getByText("Role")).toBeTruthy();
expect(screen.getByText("Alice")).toBeTruthy();
expect(screen.getByText("Admin")).toBeTruthy();
});
it("table block shows empty_text when rows empty", () => {
renderBlocks([
{
type: "table",
columns: [{ key: "name", label: "Name" }],
rows: [],
page_action_id: "page",
empty_text: "No items found",
},
]);
expect(screen.getByText("No items found")).toBeTruthy();
});
it("table badge format renders Badge component", () => {
renderBlocks([
{
type: "table",
columns: [{ key: "status", label: "Status", format: "badge" as const }],
rows: [{ status: "Active" }],
page_action_id: "page",
},
]);
expect(screen.getByTestId("badge")).toBeTruthy();
expect(screen.getByTestId("badge").textContent).toBe("Active");
});
it("actions block renders buttons horizontally", () => {
renderBlocks([
{
type: "actions",
elements: [
{ type: "button", action_id: "a1", label: "Save" },
{ type: "button", action_id: "a2", label: "Cancel" },
],
},
]);
expect(screen.getByText("Save")).toBeTruthy();
expect(screen.getByText("Cancel")).toBeTruthy();
});
it("stats block renders stat cards with values", () => {
renderBlocks([
{
type: "stats",
items: [
{ label: "Posts", value: 120 },
{ label: "Users", value: "5k" },
],
},
]);
expect(screen.getByText("Posts")).toBeTruthy();
expect(screen.getByText("120")).toBeTruthy();
expect(screen.getByText("Users")).toBeTruthy();
expect(screen.getByText("5k")).toBeTruthy();
});
it("stats block renders trend arrows", () => {
renderBlocks([
{
type: "stats",
items: [
{ label: "Revenue", value: 100, trend: "up" },
{ label: "Errors", value: 3, trend: "down" },
{ label: "Latency", value: "50ms", trend: "neutral" },
],
},
]);
expect(screen.getByTestId("arrow-up")).toBeTruthy();
expect(screen.getByTestId("arrow-down")).toBeTruthy();
expect(screen.getByTestId("minus")).toBeTruthy();
});
it("form block renders fields and submit button", () => {
renderBlocks([
{
type: "form",
fields: [{ type: "text_input", action_id: "title", label: "Title" }],
submit: { label: "Create", action_id: "create" },
},
]);
expect(screen.getByText("Title")).toBeTruthy();
expect(screen.getByText("Create")).toBeTruthy();
});
it("form onAction fires form_submit with collected values", () => {
const onAction = vi.fn();
renderBlocks(
[
{
type: "form",
block_id: "my_form",
fields: [
{
type: "text_input",
action_id: "title",
label: "Title",
initial_value: "Hello",
},
{
type: "toggle",
action_id: "published",
label: "Published",
initial_value: true,
},
],
submit: { label: "Save", action_id: "save_post" },
},
],
onAction,
);
// Submit the form
const submitBtn = screen.getByText("Save");
fireEvent.click(submitBtn);
expect(onAction).toHaveBeenCalledWith({
type: "form_submit",
action_id: "save_post",
block_id: "my_form",
values: { title: "Hello", published: true },
});
});
it("image block renders img with src and alt", () => {
renderBlocks([
{
type: "image",
url: "https://example.com/photo.jpg",
alt: "A photo",
},
]);
const img = screen.getByAltText("A photo") as HTMLImageElement;
expect(img.src).toBe("https://example.com/photo.jpg");
});
it("context block renders small muted text", () => {
renderBlocks([{ type: "context", text: "Updated just now" }]);
const el = screen.getByText("Updated just now");
expect(el.tagName).toBe("P");
expect(el.className).toContain("text-sm");
});
it("columns block renders blocks in columns", () => {
renderBlocks([
{
type: "columns",
columns: [[{ type: "header", text: "Left" }], [{ type: "header", text: "Right" }]],
},
]);
expect(screen.getByText("Left")).toBeTruthy();
expect(screen.getByText("Right")).toBeTruthy();
});
it("button click fires onAction with block_action", () => {
const onAction = vi.fn();
renderBlocks(
[
{
type: "actions",
elements: [
{
type: "button",
action_id: "do_thing",
label: "Do thing",
value: { id: 42 },
},
],
},
],
onAction,
);
fireEvent.click(screen.getByText("Do thing"));
expect(onAction).toHaveBeenCalledWith({
type: "block_action",
action_id: "do_thing",
value: { id: 42 },
});
});
it("button with confirm shows dialog, confirm fires action", () => {
const onAction = vi.fn();
renderBlocks(
[
{
type: "actions",
elements: [
{
type: "button",
action_id: "delete_item",
label: "Delete",
style: "danger",
value: "item_1",
confirm: {
title: "Delete item?",
text: "This cannot be undone.",
confirm: "Yes, delete",
deny: "Cancel",
},
},
],
},
],
onAction,
);
// Initially no dialog
expect(screen.queryByTestId("dialog-root")).toBeNull();
// Click button — dialog appears
fireEvent.click(screen.getByText("Delete"));
expect(screen.getByTestId("dialog-root")).toBeTruthy();
expect(screen.getByText("Delete item?")).toBeTruthy();
expect(screen.getByText("This cannot be undone.")).toBeTruthy();
// Click confirm — fires action
fireEvent.click(screen.getByText("Yes, delete"));
expect(onAction).toHaveBeenCalledWith({
type: "block_action",
action_id: "delete_item",
value: "item_1",
});
});
});

View File

@@ -0,0 +1,434 @@
import { describe, expect, it } from "vitest";
import { validateBlocks } from "../src/validation.js";
describe("validateBlocks", () => {
// ── Valid blocks ─────────────────────────────────────────────────────────
describe("valid blocks", () => {
it("header", () => {
const result = validateBlocks([{ type: "header", text: "Hello" }]);
expect(result).toEqual({ valid: true, errors: [] });
});
it("section", () => {
const result = validateBlocks([{ type: "section", text: "Body text" }]);
expect(result).toEqual({ valid: true, errors: [] });
});
it("divider", () => {
const result = validateBlocks([{ type: "divider" }]);
expect(result).toEqual({ valid: true, errors: [] });
});
it("fields", () => {
const result = validateBlocks([
{
type: "fields",
fields: [{ label: "Status", value: "Active" }],
},
]);
expect(result).toEqual({ valid: true, errors: [] });
});
it("table", () => {
const result = validateBlocks([
{
type: "table",
columns: [{ key: "name", label: "Name" }],
rows: [{ name: "Alice" }],
page_action_id: "load_page",
},
]);
expect(result).toEqual({ valid: true, errors: [] });
});
it("actions", () => {
const result = validateBlocks([
{
type: "actions",
elements: [{ type: "button", action_id: "btn1", label: "Click me" }],
},
]);
expect(result).toEqual({ valid: true, errors: [] });
});
it("stats", () => {
const result = validateBlocks([
{
type: "stats",
items: [{ label: "Users", value: 42 }],
},
]);
expect(result).toEqual({ valid: true, errors: [] });
});
it("form", () => {
const result = validateBlocks([
{
type: "form",
fields: [{ type: "text_input", action_id: "name", label: "Name" }],
submit: { label: "Save", action_id: "save" },
},
]);
expect(result).toEqual({ valid: true, errors: [] });
});
it("image", () => {
const result = validateBlocks([
{ type: "image", url: "https://example.com/img.png", alt: "Photo" },
]);
expect(result).toEqual({ valid: true, errors: [] });
});
it("context", () => {
const result = validateBlocks([{ type: "context", text: "Last updated 5m ago" }]);
expect(result).toEqual({ valid: true, errors: [] });
});
it("columns", () => {
const result = validateBlocks([
{
type: "columns",
columns: [[{ type: "header", text: "Left" }], [{ type: "header", text: "Right" }]],
},
]);
expect(result).toEqual({ valid: true, errors: [] });
});
});
// ── Invalid blocks ───────────────────────────────────────────────────────
describe("invalid blocks", () => {
it("not an array", () => {
const result = validateBlocks("not an array");
expect(result.valid).toBe(false);
expect(result.errors).toEqual([{ path: "blocks", message: "Blocks must be an array" }]);
});
it("block without type", () => {
const result = validateBlocks([{ text: "hello" }]);
expect(result.valid).toBe(false);
expect(result.errors[0]!.path).toBe("blocks[0].type");
expect(result.errors[0]!.message).toContain("Unknown block type");
});
it("block with unknown type", () => {
const result = validateBlocks([{ type: "foobar" }]);
expect(result.valid).toBe(false);
expect(result.errors[0]!.path).toBe("blocks[0].type");
expect(result.errors[0]!.message).toContain("Unknown block type 'foobar'");
});
it("header missing text", () => {
const result = validateBlocks([{ type: "header" }]);
expect(result.valid).toBe(false);
expect(result.errors).toEqual([
{
path: "blocks[0].text",
message: "Required field 'text' must be a string",
},
]);
});
it("section missing text", () => {
const result = validateBlocks([{ type: "section" }]);
expect(result.valid).toBe(false);
expect(result.errors[0]!.path).toBe("blocks[0].text");
});
it("table missing required fields", () => {
const result = validateBlocks([{ type: "table" }]);
expect(result.valid).toBe(false);
const paths = result.errors.map((e) => e.path);
expect(paths).toContain("blocks[0].columns");
expect(paths).toContain("blocks[0].rows");
expect(paths).toContain("blocks[0].page_action_id");
});
it("table column missing key or label", () => {
const result = validateBlocks([
{
type: "table",
columns: [{ format: "text" }],
rows: [],
page_action_id: "p",
},
]);
expect(result.valid).toBe(false);
const paths = result.errors.map((e) => e.path);
expect(paths).toContain("blocks[0].columns[0].key");
expect(paths).toContain("blocks[0].columns[0].label");
});
it("table column with invalid format", () => {
const result = validateBlocks([
{
type: "table",
columns: [{ key: "k", label: "K", format: "html" }],
rows: [],
page_action_id: "p",
},
]);
expect(result.valid).toBe(false);
expect(result.errors[0]!.path).toBe("blocks[0].columns[0].format");
expect(result.errors[0]!.message).toContain("format");
});
it("form missing fields or submit", () => {
const result = validateBlocks([{ type: "form" }]);
expect(result.valid).toBe(false);
const paths = result.errors.map((e) => e.path);
expect(paths).toContain("blocks[0].fields");
expect(paths).toContain("blocks[0].submit");
});
it("form submit missing action_id", () => {
const result = validateBlocks([
{
type: "form",
fields: [],
submit: { label: "Save" },
},
]);
expect(result.valid).toBe(false);
expect(result.errors[0]!.path).toBe("blocks[0].submit.action_id");
});
it("actions with invalid elements", () => {
const result = validateBlocks([
{
type: "actions",
elements: [{ type: "invalid_type" }],
},
]);
expect(result.valid).toBe(false);
expect(result.errors[0]!.path).toBe("blocks[0].elements[0].type");
expect(result.errors[0]!.message).toContain("Unknown element type");
});
it("select with empty options array", () => {
const result = validateBlocks([
{
type: "actions",
elements: [
{
type: "select",
action_id: "sel",
label: "Pick",
options: [],
},
],
},
]);
expect(result.valid).toBe(false);
expect(result.errors[0]!.path).toBe("blocks[0].elements[0].options");
expect(result.errors[0]!.message).toContain("must not be empty");
});
it("select option missing label/value", () => {
const result = validateBlocks([
{
type: "actions",
elements: [
{
type: "select",
action_id: "sel",
label: "Pick",
options: [{ foo: "bar" }],
},
],
},
]);
expect(result.valid).toBe(false);
const paths = result.errors.map((e) => e.path);
expect(paths).toContain("blocks[0].elements[0].options[0].label");
expect(paths).toContain("blocks[0].elements[0].options[0].value");
});
it("button with invalid style", () => {
const result = validateBlocks([
{
type: "actions",
elements: [
{
type: "button",
action_id: "btn",
label: "Go",
style: "bold",
},
],
},
]);
expect(result.valid).toBe(false);
expect(result.errors[0]!.path).toBe("blocks[0].elements[0].style");
});
it("confirm dialog missing required fields", () => {
const result = validateBlocks([
{
type: "actions",
elements: [
{
type: "button",
action_id: "btn",
label: "Delete",
confirm: {},
},
],
},
]);
expect(result.valid).toBe(false);
const paths = result.errors.map((e) => e.path);
expect(paths).toContain("blocks[0].elements[0].confirm.title");
expect(paths).toContain("blocks[0].elements[0].confirm.text");
expect(paths).toContain("blocks[0].elements[0].confirm.confirm");
expect(paths).toContain("blocks[0].elements[0].confirm.deny");
});
it("image missing url or alt", () => {
const result = validateBlocks([{ type: "image" }]);
expect(result.valid).toBe(false);
const paths = result.errors.map((e) => e.path);
expect(paths).toContain("blocks[0].url");
expect(paths).toContain("blocks[0].alt");
});
it("columns with less than 2 arrays", () => {
const result = validateBlocks([
{
type: "columns",
columns: [[{ type: "divider" }]],
},
]);
expect(result.valid).toBe(false);
expect(result.errors[0]!.path).toBe("blocks[0].columns");
expect(result.errors[0]!.message).toContain("2-3 column arrays");
});
it("columns with more than 3 arrays", () => {
const result = validateBlocks([
{
type: "columns",
columns: [
[{ type: "divider" }],
[{ type: "divider" }],
[{ type: "divider" }],
[{ type: "divider" }],
],
},
]);
expect(result.valid).toBe(false);
expect(result.errors[0]!.message).toContain("2-3 column arrays");
});
it("columns with invalid nested blocks reports correct path", () => {
const result = validateBlocks([
{
type: "columns",
columns: [
[{ type: "header", text: "OK" }],
[{ type: "header" }], // missing text
],
},
]);
expect(result.valid).toBe(false);
expect(result.errors[0]!.path).toBe("blocks[0].columns[1][0].text");
});
it("stats item missing label or value", () => {
const result = validateBlocks([
{
type: "stats",
items: [{ description: "desc" }],
},
]);
expect(result.valid).toBe(false);
const paths = result.errors.map((e) => e.path);
expect(paths).toContain("blocks[0].items[0].label");
expect(paths).toContain("blocks[0].items[0].value");
});
it("stats item with invalid trend", () => {
const result = validateBlocks([
{
type: "stats",
items: [{ label: "Users", value: 10, trend: "sideways" }],
},
]);
expect(result.valid).toBe(false);
expect(result.errors[0]!.path).toBe("blocks[0].items[0].trend");
});
it("form field with invalid condition (no eq/neq)", () => {
const result = validateBlocks([
{
type: "form",
fields: [
{
type: "text_input",
action_id: "name",
label: "Name",
condition: { field: "toggle" },
},
],
submit: { label: "Save", action_id: "save" },
},
]);
expect(result.valid).toBe(false);
expect(result.errors[0]!.path).toBe("blocks[0].fields[0].condition");
expect(result.errors[0]!.message).toContain("either 'eq' or 'neq'");
});
});
// ── Edge cases ───────────────────────────────────────────────────────────
describe("edge cases", () => {
it("empty blocks array is valid", () => {
const result = validateBlocks([]);
expect(result).toEqual({ valid: true, errors: [] });
});
it("deeply nested columns validate recursively", () => {
const result = validateBlocks([
{
type: "columns",
columns: [
[
{
type: "columns",
columns: [
[{ type: "header", text: "Deep left" }],
[{ type: "header" }], // missing text
],
},
],
[{ type: "divider" }],
],
},
]);
expect(result.valid).toBe(false);
expect(result.errors[0]!.path).toBe("blocks[0].columns[0][0].columns[1][0].text");
});
it("multiple errors in one block are all reported", () => {
const result = validateBlocks([
{
type: "table",
columns: [{ format: "invalid" }], // missing key, label, bad format
rows: "not an array",
// missing page_action_id
},
]);
expect(result.valid).toBe(false);
// Should have errors for key, label, format, rows, and page_action_id
expect(result.errors.length).toBeGreaterThanOrEqual(4);
const paths = result.errors.map((e) => e.path);
expect(paths).toContain("blocks[0].columns[0].key");
expect(paths).toContain("blocks[0].columns[0].label");
expect(paths).toContain("blocks[0].columns[0].format");
expect(paths).toContain("blocks[0].rows");
expect(paths).toContain("blocks[0].page_action_id");
});
});
});