eui-core 0.7.1

Exponential UI core: the A2UI reducer (core + basic catalog, macros, extensions), runtime themes with recipe resolution, taffy layout with batched measurement, overlay layers and windowed lists — the engine behind the SwiftUI, Compose and gpui painters.
Documentation
//! The host API contract (`catalog/host.json`) as constants, plus the client
//! messages every platform host sends (`tests/host_fixtures.rs` gates the
//! constants against the JSON).

use serde_json::{json, Map, Value};

use crate::catalog::A2UI_VERSION;

pub const HOST_CONTRACT_VERSION: u32 = 3;
/// The four A2UI v0.9 server messages.
pub const A2UI_MESSAGE_KINDS: &[&str] = &["createSurface", "updateComponents", "updateDataModel", "deleteSurface"];
/// The two Exponential UI extensions.
pub const EXTENSION_MESSAGE_KINDS: &[&str] = &["applyTemplate", "bindDataModel"];
/// Every message kind the router takes, A2UI first.
pub const MESSAGE_KINDS: &[&str] = &["createSurface", "updateComponents", "updateDataModel", "deleteSurface", "applyTemplate", "bindDataModel"];
/// What the router turns a message into.
pub const OP_KINDS: &[&str] = &["create", "components", "data", "bind", "delete", "send"];
pub const HOST_ERROR_CODES: &[&str] =
    &["VALIDATION_FAILED", "INVALID_MESSAGE", "UNSUPPORTED_CATALOG", "SURFACE_NOT_FOUND", "TEMPLATE_NOT_FOUND", "FUNCTION_NOT_FOUND", "FUNCTION_DENIED", "SOURCE_DENIED", "RENDER_FAILED", "ACTION_FAILED"];
pub const VALIDATION_FAILED: &str = "VALIDATION_FAILED";
pub const INVALID_MESSAGE: &str = "INVALID_MESSAGE";
pub const UNSUPPORTED_CATALOG: &str = "UNSUPPORTED_CATALOG";
pub const SURFACE_NOT_FOUND: &str = "SURFACE_NOT_FOUND";
pub const TEMPLATE_NOT_FOUND: &str = "TEMPLATE_NOT_FOUND";
pub const FUNCTION_NOT_FOUND: &str = "FUNCTION_NOT_FOUND";
pub const FUNCTION_DENIED: &str = "FUNCTION_DENIED";
/// VAPP-107: a `bindDataModel` outside a package surface's `sources`.
pub const SOURCE_DENIED: &str = "SOURCE_DENIED";
/// A component's painter failed (`paint.errorCode`).
pub const RENDER_FAILED: &str = "RENDER_FAILED";
/// VAPP-194: a package action that landed nothing (a false require, a
/// refused write or call).
pub const ACTION_FAILED: &str = "ACTION_FAILED";
pub const FUNCTION_DECISIONS: &[&str] = &["allow", "ask", "deny", "not_found"];
/// The default function policy's `default`.
pub const DEFAULT_FUNCTION_DECISION: &str = "allow";
pub const DEFAULT_URL_SCHEMES: &[&str] = &["https", "http", "mailto", "tel"];
/// VAPP-107: the hosts `decide_url` denies by default (`urls.privateHosts`,
/// the rule itself is [`super::is_private_host`]).
pub const PRIVATE_HOSTS: &[&str] = &["localhost", "*.localhost", "*.local", "0.0.0.0/8", "10.0.0.0/8", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10", "::", "::1", "fe80::/10", "fc00::/7", "::ffff:<private IPv4>", "::<private IPv4>", "64:ff9b::<private IPv4>", "2002:<private IPv4>::/48"];
pub const URL_REASONS: &[&str] = &["invalid", "scheme", "host", "private"];
pub const MEDIA_RULE_KEYS: &[&str] = &["prefix", "headers"];
pub const MEDIA_OPTION_KEYS: &[&str] = &["baseUrl", "rules", "schemes", "hosts", "allowPrivate"];
/// The media loader's schemes when the host lists none (no `file`).
pub const DEFAULT_MEDIA_SCHEMES: &[&str] = &["https", "http", "data"];
/// `media.limits`: what every image loader enforces.
pub const MEDIA_MAX_BYTES: u64 = 20_971_520;
pub const MEDIA_TIMEOUT_MS: u64 = 30_000;
pub const MEDIA_MAX_PIXELS: u64 = 33_554_432;
/// The renderer → host hook a failed painter calls (`paint.hook`).
pub const PAINT_ERROR_HOOK: &str = "onPaintError";
/// A binding source URI (`<scheme>:<name>[?k=v&…]`).
pub const SOURCE_PATTERN: &str = "^([a-zA-Z][a-zA-Z0-9+.-]*):([^?]+)(?:\\?(.*))?$";
pub const MCP_MIME_TYPES: &[&str] = &["application/json+a2ui", "application/a2ui+json"];
pub const MCP_ACTION_TOOL: &str = "a2ui_event";
pub const SSE_EVENTS: &[&str] = &["message", "a2ui"];
pub const PACKAGE_REQUIRED: &[&str] = &["id", "name", "version", "catalogId", "templates"];
/// Round 2: what a host hands each surface besides messages — the
/// `SurfaceSettings` keys, the host formatter's methods, the commands.
pub const SURFACE_SETTINGS: &[&str] = &["locale", "timeZone", "strings", "mode", "density", "contrast", "theme"];
pub const SURFACE_FORMATTER: &[&str] = &["number", "currency", "percent", "date", "relativeTime", "plural"];
pub const SURFACE_COMMANDS: &[&str] = &["focus", "announce", "scrollIntoView", "scrollToIndex"];

/// VAPP-122: how the `bind` action appends its params (`sources.paramsEncoding`).
pub const SOURCE_PARAMS_ENCODING: &str = "sourceWithParams: keys sorted; key and value percent-encoded (everything but A-Z a-z 0-9 - _ . ! ~ * ' ( )); null skipped; an object or array as JSON; after ? or &";
/// VAPP-122: a record kind's name (`package.records.kindPattern`).
pub const RECORD_KIND_PATTERN: &str = "^[a-z][a-z0-9_]{0,31}$";

/// `catalog/host.json` without its `$comment`s, rebuilt from the constants.
pub fn host_contract() -> Value {
    use super::{actions as act, exposes as ex, record_store as rs, signature as sig, tests as pt, tools};
    json!({
        "version": HOST_CONTRACT_VERSION,
        "a2uiVersion": A2UI_VERSION,
        "messages": {"a2ui": A2UI_MESSAGE_KINDS, "extensions": EXTENSION_MESSAGE_KINDS},
        "ops": {"kinds": OP_KINDS},
        "clientMessages": {"errorCodes": HOST_ERROR_CODES},
        "functions": {"decisions": FUNCTION_DECISIONS, "defaultPolicy": {"allow": [], "ask": [], "deny": [], "default": DEFAULT_FUNCTION_DECISION}},
        "urls": {"defaultSchemes": DEFAULT_URL_SCHEMES, "privateHosts": PRIVATE_HOSTS, "reasons": URL_REASONS},
        "media": {
            "ruleKeys": MEDIA_RULE_KEYS,
            "optionKeys": MEDIA_OPTION_KEYS,
            "defaultSchemes": DEFAULT_MEDIA_SCHEMES,
            "limits": {"maxBytes": MEDIA_MAX_BYTES, "timeoutMs": MEDIA_TIMEOUT_MS, "maxPixels": MEDIA_MAX_PIXELS},
        },
        "sources": {"pattern": SOURCE_PATTERN, "paramsEncoding": SOURCE_PARAMS_ENCODING},
        "transport": {"mcpMimeTypes": MCP_MIME_TYPES, "mcpActionTool": MCP_ACTION_TOOL, "sseEvents": SSE_EVENTS},
        "negotiation": {},
        "package": {
            "required": PACKAGE_REQUIRED,
            "formatVersion": super::package::PACKAGE_FORMAT_VERSION,
            "records": {
                "kindPattern": RECORD_KIND_PATTERN,
                "reserved": super::records::RECORD_RESERVED_KEYS,
                "types": super::records::RECORD_FIELD_TYPES,
                "formats": super::records::RECORD_FORMATS,
                "scheme": rs::RECORDS_SCHEME,
                "functions": rs::RECORDS_FUNCTIONS,
                "query": {"sortDefault": rs::RECORDS_SORT_DEFAULT, "orderDefault": rs::RECORDS_ORDER_DEFAULT, "limitDefault": rs::RECORDS_LIMIT_DEFAULT, "limitMax": rs::RECORDS_LIMIT_MAX, "queryNamePattern": super::package::QUERY_NAME_PATTERN, "reserved": rs::RECORDS_RESERVED_PARAMS},
            },
            "actions": {
                "limits": {"actions": act::ACTION_LIMIT_ACTIONS, "steps": act::ACTION_LIMIT_STEPS, "maxSteps": act::ACTION_LIMIT_MAX_STEPS},
                "namePattern": act::ACTION_NAME_PATTERN,
                "stepKinds": act::ACTION_STEP_KINDS,
                "callPrefix": act::ACTION_CALL_PREFIX,
                "batchFunction": act::RECORDS_BATCH_FUNCTION,
            },
            "tests": {
                "limits": {"tests": pt::PACKAGE_TEST_LIMIT_TESTS, "gotMax": pt::PACKAGE_TEST_LIMIT_GOT_MAX},
                "defaults": {"now": pt::PACKAGE_TEST_DEFAULT_NOW, "as": pt::PACKAGE_TEST_DEFAULT_AS, "role": pt::PACKAGE_TEST_DEFAULT_ROLE},
                "roles": pt::PACKAGE_TEST_ROLES,
                "kinds": pt::PACKAGE_TEST_KINDS,
            },
            "tools": {"idPattern": tools::TOOL_ID_PATTERN, "kinds": tools::TOOL_KINDS, "transports": tools::TOOL_TRANSPORTS, "functionPrefix": tools::TOOL_FUNCTION_PREFIX},
            "exposes": {
                "limits": {"namePattern": ex::EXPOSE_NAME_PATTERN, "nameMax": ex::EXPOSE_NAME_MAX, "titleMax": ex::EXPOSE_TITLE_MAX, "descriptionMax": ex::EXPOSE_DESCRIPTION_MAX, "maxTools": ex::EXPOSE_MAX_TOOLS, "separator": ex::EXPOSE_SEPARATOR},
                "runKinds": ex::EXPOSE_RUN_KINDS,
                "recordOps": ex::EXPOSE_RECORD_OPS,
                "readRecordOps": ex::EXPOSE_READ_RECORD_OPS,
                "readOpWords": ex::EXPOSE_READ_OP_WORDS,
                "destructiveWords": ex::EXPOSE_DESTRUCTIVE_WORDS,
                "actionPattern": ex::EXPOSE_ACTION_PATTERN,
            },
            "extensions": {"versionPattern": super::package::EXTENSION_VERSION_PATTERN},
            "signature": {"alg": sig::PACKAGE_FILE_SIGNATURE_ALG, "context": sig::PACKAGE_FILE_SIGNATURE_CONTEXT, "keyPrefix": sig::AUTHOR_KEY_PREFIX, "nameMax": sig::AUTHOR_NAME_MAX, "statuses": sig::PACKAGE_FILE_STATUSES},
        },
        "paint": {"hook": PAINT_ERROR_HOOK, "errorCode": RENDER_FAILED},
        "surface": {"settings": SURFACE_SETTINGS, "formatter": SURFACE_FORMATTER, "commands": SURFACE_COMMANDS},
    })
}

/// A client error message (A2UI v0.9 `error`); `path` only when given.
pub fn error_message(code: &str, surface_id: &str, message: &str, path: Option<&str>) -> Value {
    let mut error = Map::new();
    error.insert("code".into(), Value::String(code.into()));
    error.insert("surfaceId".into(), Value::String(surface_id.into()));
    error.insert("message".into(), Value::String(message.into()));
    if let Some(path) = path {
        error.insert("path".into(), Value::String(path.into()));
    }
    json!({"version": A2UI_VERSION, "error": error})
}

/// A client action message (A2UI v0.9 `action`). `context` null = `{}`;
/// `payload` only when it has keys (JS `Object.keys(payload).length`).
pub fn action_message(surface_id: &str, component_id: &str, name: &str, context: Value, payload: Option<Value>, timestamp: &str) -> Value {
    let mut action = Map::new();
    action.insert("name".into(), Value::String(name.into()));
    action.insert("surfaceId".into(), Value::String(surface_id.into()));
    action.insert("sourceComponentId".into(), Value::String(component_id.into()));
    action.insert("timestamp".into(), Value::String(timestamp.into()));
    action.insert("context".into(), if context.is_null() { Value::Object(Map::new()) } else { context });
    if let Some(payload) = payload {
        let has_keys = match &payload {
            Value::Object(o) => !o.is_empty(),
            Value::Array(a) => !a.is_empty(),
            Value::String(s) => !s.is_empty(),
            _ => false,
        };
        if has_keys {
            action.insert("payload".into(), payload);
        }
    }
    json!({"version": A2UI_VERSION, "action": action})
}