ToonUI
Packages

@toon-ui/core

Complete server-safe API reference for ToonUI core: catalog, prompt, parser, validator, events, messages, and runtime helpers.

@toon-ui/core is the server-safe ToonUI package.

Use it to:

  • define the active standard ToonUI catalog for your app
  • generate the model prompt from that catalog
  • parse and validate generated toon-ui blocks
  • convert rendered UI interactions into chat/model messages

It does not import React. Use @toon-ui/react for rendering.

Install

pnpm add @toon-ui/core

Import surface

import {
  createToonProtocol,
  createToonCatalog,
  createRules,
  createPrompt,
  parseToonUI,
  validateToonUI,
  extractToonBlocks,
  extractToonSegments,
} from '@toon-ui/core';
import { createToonProtocol } from '@toon-ui/core';

const toon = createToonProtocol({
  components: ['text', 'card', 'form', 'field', 'button', 'table'],
});

const system = [
  toon.prompt,
  'You are helping users compare products.',
  'Available tools:',
  '- searchProducts(query)',
].join('\n\n');

This is the most important API in core. It creates the prompt and all protocol helpers from one active catalog.

The generated prompt includes the current authoring contract: alert and dialog support description="...", fields must live inside form, and field defaults should be emitted as quoted value="...".

API map

AreaAPIs
ProtocolcreateToonProtocol, createToonCoreRuntime
CatalogcreateToonCatalog, assertToonCatalogCoverage, listToonCatalogComponentKeys, listToonComponentKeys, TOON_CATALOG
PromptcreateRules, createPrompt, prompt fragment helpers
ParsingparseToonUI, ToonSyntaxError
ValidationvalidateToonUI
ExtractionextractToonBlocks, extractToonSegments
EventscreateReplyEvent, createSubmitEvent
MessagestoToonEventContent, toToonDisplayContent, toToonModelMessage, toToonUIMessage
Constantscomponent keys, variants, field types, chart types, sheet sides, separator orientations

Protocol APIs

createToonProtocol(options?)

Creates the main server protocol object.

const toon = createToonProtocol({
  components: ['text', 'button'],
});

Parameters

NameTypeRequiredDescription
options.componentsreadonly ToonCatalogComponentKey[] or component-key mapNoStandard ToonUI components enabled for this app.
options.catalogToonActiveCatalogNoPrebuilt active catalog. If provided, it wins over components.

Returns

type ToonProtocol = {
  prompt: string;
  rules: ToonRules;
  catalog: ToonActiveCatalog;
  events: ToonEventsApi;
  messages: ToonMessagesApi;
};
PropertyDescription
promptFull system-prompt fragment generated from the active catalog.
rulesCompact machine-readable rules: enabled components and variants.
catalogActive catalog used for prompt generation and validation.
events.replyCreates ui_reply payloads.
events.submitCreates ui_submit payloads.
messages.toContentSerializes a payload into compact protocol text.
messages.toDisplayContentCreates human-readable display text.
messages.toModelMessageConverts payload into model-facing chat message.
messages.toUIMessageConverts payload into UI-message-shaped chat entry.

When to use it

Use this in server routes, server actions, workers, or any non-React environment where you need the ToonUI prompt or interaction message helpers.


createToonCoreRuntime(options?)

Creates a non-React runtime that extends the protocol with parser/validator helpers and a generic component registry.

const runtime = createToonCoreRuntime({
  components: {
    text: TextRenderer,
    button: ButtonRenderer,
  },
});

Parameters

NameTypeRequiredDescription
options.componentsToonComponentRegistryNoGeneric component registry. In React apps, prefer @toon-ui/react.
options.catalogToonActiveCatalogNoActive catalog to use instead of deriving one from component keys.

Returns

type ToonRuntime<TComponents> = ToonProtocol & {
  components: TComponents;
  parse: typeof parseToonUI;
  validate: typeof validateToonUI;
  extractBlocks: typeof extractToonBlocks;
};

When to use it

Use it for framework-agnostic runtimes, tests, tooling, or non-React adapters. Most React applications should use createToonReactRuntime from @toon-ui/react.


Catalog APIs

createToonCatalog(options?)

Creates the active catalog used by prompt generation and validation.

const catalog = createToonCatalog({
  components: ['text', 'card', 'button'],
});

Parameters

NameTypeRequiredDescription
options.componentsreadonly ToonCatalogComponentKey[] or partial key mapNoStandard ToonUI component keys to enable. If omitted, returns the full official catalog.

Returns

type ToonActiveCatalog = {
  components: Partial<Record<ToonCatalogComponentKey, ToonCatalogComponent>>;
  variants: ToonCatalog['variants'];
  examples: {
    valid: readonly string[];
    invalid: readonly string[];
  };
};

Important behavior

The catalog is not free-form. It only accepts standard parseable ToonUI components.

Good:

createToonCatalog({ components: ['form', 'field', 'button'] });

Bad:

createToonCatalog({ components: ['delete_product'] as never });

Business actions belong in replies, submits, tools, and application code — not in custom component names.


assertToonCatalogCoverage(keys)

Validates component dependency coverage.

assertToonCatalogCoverage(['form', 'field', 'button']);

Parameters

NameTypeDescription
keysreadonly ToonCatalogComponentKey[]Component keys enabled by the app.

Returns

void. Throws when dependencies are missing.

Example failure

assertToonCatalogCoverage(['form']);
// Error: "form" requires "field", "button"

Dependency rules

Enabled componentRequired components
formfield, button
listitem
tabstab
accordionsection
menuaction
commandaction
chartseries, point
breadcrumbcrumb

listToonCatalogComponentKeys()

Returns all standard ToonUI component keys.

const keys = listToonCatalogComponentKeys();

Returns

Array<ToonComponentKey>

Use it for docs, debug tools, tests, or UI that lets developers inspect available standard components.


listToonComponentKeys()

Backward-compatible alias for listToonCatalogComponentKeys().

const keys = listToonComponentKeys();

Catalog constants

ConstantDescription
TOON_CATALOGFull official standard catalog.
TOON_COMPONENT_KEYSAll standard component keys.
TOON_BUTTON_VARIANTSprimary, secondary, danger, ghost, outline.
TOON_BADGE_VARIANTSsuccess, warning, danger, neutral, info.
TOON_ALERT_VARIANTSinfo, success, warning, danger.
TOON_CONFIRM_VARIANTSneutral, info, warning, danger, success.
TOON_FIELD_TYPESSupported field input types.
TOON_CHART_TYPESbar, line, area, pie.
TOON_SHEET_SIDESleft, right, top, bottom.
TOON_SEPARATOR_ORIENTATIONShorizontal, vertical.

Prompt APIs

createRules(catalog?)

Creates compact rules from an active catalog.

const catalog = createToonCatalog({ components: ['text', 'button'] });
const rules = createRules(catalog);

Parameters

NameTypeRequiredDescription
catalogToonActiveCatalogNoActive catalog. Defaults to the full official catalog.

Returns

type ToonRules = {
  components: readonly ToonComponentKey[];
  buttonVariants: readonly ButtonVariant[];
  badgeVariants: readonly BadgeVariant[];
  alertVariants: readonly AlertVariant[];
  confirmVariants: readonly ConfirmVariant[];
  fieldTypes: readonly FieldType[];
  chartTypes: readonly ChartType[];
};

Use it for custom prompt composition. Most apps should use createToonProtocol instead.


createPrompt(rules, catalog?)

Builds the full ToonUI model instruction string.

const prompt = createPrompt(rules, catalog);

Parameters

NameTypeRequiredDescription
rulesToonRulesYesEnabled components and variants.
catalogToonActiveCatalogNoActive catalog used for overview, syntax, coverage, and examples.

Returns

string — the complete ToonUI prompt fragment.

Prefer this instead

const toon = createToonProtocol({ components });
const prompt = toon.prompt;

Use createPrompt directly only for advanced prompt composition.


Prompt fragment helpers

These helpers return string fragments used by createPrompt.

HelperParametersReturnsPurpose
createComponentPrompt(rules)ToonRulesstringLists allowed components and variants.
createCatalogOverviewPrompt(catalog?)ToonActiveCatalogstringGroups enabled components by catalog group.
createCatalogCoveragePrompt(catalog?)ToonActiveCatalogstringChecklist for enabled components.
createSyntaxPrompt(catalog?)ToonActiveCatalogstringCanonical syntax rules for enabled components.
createFallbackPrompt()nonestringRules for what the model should do when uncertain.
createSafetyPrompt()nonestringHard safety rules.
createCompositionPrompt()nonestringUI composition guidance.
createFormBestPracticesPrompt()nonestringForm/data-capture guidance.
createDecisionPrompt()nonestringWhen to prefer ToonUI over prose.
createSelfCheckPrompt()nonestringFinal syntax self-check instructions.
createExamplesPrompt(catalog?)ToonActiveCatalogstringValid/invalid examples.

Parser and extraction APIs

parseToonUI(source)

Parses raw ToonUI source into an AST.

const document = parseToonUI('text "Hello"');

Parameters

NameTypeDescription
sourcestringRaw ToonUI DSL source, without markdown fences.

Returns

type ToonDocument = {
  type: 'document';
  body: ToonNode[];
};

Throws

Throws ToonSyntaxError for invalid syntax or unknown components.

try {
  parseToonUI('sidebar "No"');
} catch (error) {
  if (error instanceof ToonSyntaxError) {
    console.log(error.code, error.line, error.column);
  }
}

ToonSyntaxError

Structured parser error.

PropertyTypeDescription
name'ToonSyntaxError'Error name.
codeToonErrorCodeMachine-readable error code.
linenumberSource line.
columnnumberSource column.
messagestringHuman-readable message.

extractToonBlocks(content)

Extracts fenced ToonUI blocks from mixed markdown.

const blocks = extractToonBlocks(markdown);

Parameters

NameTypeDescription
contentstringAssistant output containing markdown and optional fenced toon-ui blocks.

Returns

type ToonBlock = {
  raw: string;
  language: 'toon-ui';
  start: number;
  end: number;
  complete: boolean;
};

complete is false for renderable partial blocks while streaming.


extractToonSegments(content)

Splits mixed markdown and ToonUI blocks while preserving order.

const segments = extractToonSegments(content);

Returns

type ToonContentSegment = ToonMarkdownSegment | ToonUIBlockSegment;

Use this when a renderer needs to preserve the sequence of prose, UI, prose, UI.


Validation API

validateToonUI(document, catalog?)

Validates an AST semantically and, optionally, against an active catalog.

const ast = parseToonUI(source);
const result = validateToonUI(ast, toon.catalog);

Parameters

NameTypeRequiredDescription
documentToonDocumentYesParsed AST.
catalogToonActiveCatalogNoActive catalog. Defaults to full official catalog.

Returns

type ValidationResult = {
  ok: boolean;
  errors: ValidationIssue[];
  warnings: ValidationIssue[];
};

Common errors

CodeMeaning
INVALID_COMPONENTComponent exists in grammar but is not enabled in active catalog, or unknown component at parse time.
INVALID_PROPInvalid prop value or invalid structural shape.
INVALID_VARIANTUnsupported variant.
MISSING_REQUIRED_FIELDRequired title, field, button, or value is missing.
INVALID_NESTINGChild node is not allowed in that parent.
INVALID_SYNTAXParser-level syntax problem.
UNSAFE_CONTENTRaw HTML or script-like text was detected.

Event APIs

createReplyEvent(valueOrPayload, metadata?)

Creates a ui_reply payload, usually for button interactions.

const payload = createReplyEvent('Open details', { productId: 123 });

Parameters

NameTypeRequiredDescription
valueOrPayloadstring | ReplyPayloadYesReply value or existing payload to return unchanged.
metadataRecord&lt;string, string | number | boolean&gt;NoExtra context when first argument is a string.

Returns

type ReplyPayload = {
  kind: 'ui_reply';
  eventId: string;
  source: 'button';
  component: 'button';
  value: string;
  line?: number;
  context?: Record<string, SubmitValue>;
};

createSubmitEvent(intentOrPayload, values?)

Creates a ui_submit payload, usually for form interactions.

const payload = createSubmitEvent('create_product', {
  name: 'Coca-Cola',
  price: 2500,
});

Parameters

NameTypeRequiredDescription
intentOrPayloadstring | SubmitPayloadYesSubmit intent or existing payload to return unchanged.
valuesRecord&lt;string, string | number | boolean&gt;NoSubmitted form values when first argument is a string.

Returns

type SubmitPayload = {
  kind: 'ui_submit';
  eventId: string;
  source: 'form';
  intent: string;
  formTitle: string;
  values: Record<string, SubmitValue>;
  line?: number;
};

Message conversion APIs

toToonEventContent(payload)

Serializes a reply or submit payload into compact protocol text.

const content = toToonEventContent(payload);

Returns string.


toToonDisplayContent(payload)

Creates human-readable display content for chat history.

const display = toToonDisplayContent(payload);

Returns string.

For submit payloads, field labels are used when a form node is attached.


toToonModelMessage(payload)

Creates a model-facing message object.

const message = toToonModelMessage(payload);

Returns

type ToonModelMessage<TPayload> = {
  role: 'user';
  kind: TPayload['kind'];
  content: string;
  displayContent: string;
  payload: TPayload;
};

Use it when the next turn goes back to the LLM/model loop.


toToonUIMessage(payload)

Creates a UI-message-shaped object.

const message = toToonUIMessage(payload);

Returns

type ToonUIMessage<TPayload> = {
  id: string;
  role: 'user';
  parts: [{ type: 'text'; text: string }];
  metadata: {
    displayContent: string;
    kind: TPayload['kind'];
  };
};

Use it when your chat state stores UI message objects, such as AI SDK-style message state.


Type exports worth knowing

TypeMeaning
ToonProtocolReturn type of createToonProtocol.
ToonRuntimeProtocol plus parser/validator/runtime helpers.
ToonActiveCatalogActive component subset.
ToonCatalogComponentKeyStandard component key accepted by catalog config.
ToonRulesEnabled components and variants.
ToonDocumentAST root from parseToonUI.
ToonNodeUnion of all AST node types.
ToonNodeByTypeNode lookup map keyed by component type.
ToonBlockExtracted fenced block.
ValidationResultResult from validateToonUI.
ValidationIssueSingle validation error/warning.
ReplyPayloadButton-style interaction payload.
SubmitPayloadForm-style interaction payload.
ToonInteractionPayloadReplyPayload | SubmitPayload.
ToonModelMessageModel-facing interaction message.
ToonUIMessageUI-state-friendly interaction message.

On this page