The Open Standard for Generative UI
feat(react-lang): expand parser validation with rule-tagged errors (#350)
Abhine483dadd33c2
diff --git a/docs/content/docs/api-reference/react-lang.mdx b/docs/content/docs/api-reference/react-lang.mdxindex 29eae24b8..0069c127d 100644--- a/docs/content/docs/api-reference/react-lang.mdx+++ b/docs/content/docs/api-reference/react-lang.mdx@@ -152,19 +152,42 @@ interface ElementNode {partial: boolean;}-interface ValidationError {+/**+ * Validation error codes for schema-related issues.+ *+ * - missing-required — required prop absent with no default+ * - null-required — required prop explicitly null with no default+ * - unknown-component — PascalCase name not in the library schema+ * - excess-args — more positional args than the schema defines+ */+type ValidationErrorCode =+ | "missing-required"+ | "null-required"+ | "unknown-component"+ | "excess-args";++/**+ * Structured error from the parser.+ * Use `type` to distinguish error categories and `code` to filter+ * or categorize errors on the consumer side.+ */+type OpenUIError = {+ type: "validation";+ code: ValidationErrorCode;component: string;+ /** JSON Pointer path within props, e.g. "/title". Empty string for structural errors. */path: string;message: string;-}+};interface ParseResult {root: ElementNode | null;meta: {incomplete: boolean;+ /** Identifiers referenced but not yet defined. Check after streaming completes. */unresolved: string[];statementCount: number;- validationErrors: ValidationError[];+ errors: OpenUIError[];};}```diff --git a/packages/react-lang/README.md b/packages/react-lang/README.mdindex b1dcd3d86..0a0e70531 100644--- a/packages/react-lang/README.md+++ b/packages/react-lang/README.md@@ -119,6 +119,43 @@ function AssistantMessage({ response, isStreaming }) {| `createParser(library)` | Create a one-shot parser for complete OpenUI Lang text || `createStreamingParser(library)` | Create an incremental parser for streaming input |+The streaming parser exposes two methods:++| Method | Description |+| :--- | :--- |+| `push(chunk)` | Feed the next chunk; returns the latest `ParseResult` |+| `getResult()` | Get the latest result without consuming new data |++After the stream ends, check `meta.unresolved` for any identifiers that were referenced but never defined. During streaming these are expected (forward refs) and are not treated as errors.++#### Errors++`ParseResult.meta.errors` contains structured `OpenUIError` objects. Each error has a `type` discriminant (currently always `"validation"`) and a `code` for consumer-side filtering:++| Code | Meaning |+| :--- | :--- |+| `missing-required` | Required prop absent with no default |+| `null-required` | Required prop explicitly null with no default |+| `unknown-component` | Component name not found in the library schema |+| `excess-args` | More positional args passed than the schema defines |++Errors do not affect rendering — the parser stays permissive and renders what it can. Use `code` to decide how to surface or log errors:++```ts+const result = parser.parse(output);+const critical = result.meta.errors.filter(+ (e) => e.code === "unknown-component"+);+```++To check for unresolved references after streaming, inspect `meta.unresolved`:++```ts+if (result.meta.unresolved.length > 0) {+ console.warn("Unresolved refs:", result.meta.unresolved);+}+```+### Context HooksUse these inside component renderers to interact with the rendering context:@@ -157,6 +194,8 @@ import type {ActionEvent,ElementNode,ParseResult,+ OpenUIError,+ ValidationErrorCode,LibraryJSONSchema,} from "@openuidev/react-lang";```diff --git a/packages/react-lang/eslint.config.cjs b/packages/react-lang/eslint.config.cjsindex 0df857619..4e9c2056b 100644--- a/packages/react-lang/eslint.config.cjs+++ b/packages/react-lang/eslint.config.cjs@@ -6,9 +6,24 @@ const unusedImports = require("eslint-plugin-unused-imports");const eslintPluginPrettier = require("eslint-plugin-prettier");module.exports = [+ {+ files: ["**/__tests__/**/*.{ts,tsx}", "**/*.test.{ts,tsx}", "**/*.spec.{ts,tsx}"],+ languageOptions: {+ parser: typescript,+ parserOptions: {+ project: "./tsconfig.test.json",+ sourceType: "module",+ },+ },+ },{files: ["**/*.{ts,tsx}"],- ignores: ["**/*.stories.tsx"],+ ignores: [+ "**/*.stories.tsx",+ "**/__tests__/**/*.{ts,tsx}",+ "**/*.test.{ts,tsx}",+ "**/*.spec.{ts,tsx}",+ ],languageOptions: {parser: typescript,parserOptions: {diff --git a/packages/react-lang/package.json b/packages/react-lang/package.jsonindex 53434cae6..08c1c5f5c 100644--- a/packages/react-lang/package.json+++ b/packages/react-lang/package.json@@ -18,6 +18,7 @@}},"scripts": {+ "test": "vitest run","build": "tsc -p .","watch": "tsc -p . --watch","lint:check": "eslint ./src",@@ -60,6 +61,7 @@"react": ">=19.0.0"},"devDependencies": {- "@types/react": "^19.0.0"+ "@types/react": "^19.0.0",+ "vitest": "^4.0.18"}}diff --git a/packages/react-lang/src/parser/__tests__/parser.test.ts b/packages/react-lang/src/parser/__tests__/parser.test.tsnew file mode 100644index 000000000..bd91ede82--- /dev/null+++ b/packages/react-lang/src/parser/__tests__/parser.test.ts@@ -0,0 +1,160 @@+import { describe, expect, it } from "vitest";+import type { ParamMap } from "../parser";+import { createStreamParser, parse } from "../parser";++// ── Test schema ──────────────────────────────────────────────────────────────++/**+ * Minimal schema used across tests.+ *+ * Stack takes one param (children), Title takes one (text),+ * Table takes two (columns, rows). These cover the common test cases.+ */+const schema: ParamMap = new Map([+ ["Stack", { params: [{ name: "children", required: true }] }],+ ["Title", { params: [{ name: "text", required: true }] }],+ [+ "Table",+ {+ params: [+ { name: "columns", required: true },+ { name: "rows", required: true },+ ],+ },+ ],+]);++// ── Helpers ───────────────────────────────────────────────────────────────────++const errors = (input: string) => parse(input, schema).meta.errors;+const codes = (input: string) => errors(input).map((e) => e.code);++// ── unknown-component ────────────────────────────────────────────────────────++describe("unknown-component", () => {+ it("reports when component name is not in schema", () => {+ const result = parse('root = DataTable("col")', schema);+ expect(result.meta.errors).toHaveLength(1);+ expect(result.meta.errors[0]).toMatchObject({+ type: "validation",+ code: "unknown-component",+ component: "DataTable",+ path: "",+ });+ });++ it("still renders the element with _args when unknown", () => {+ const result = parse('root = DataTable("col")', schema);+ expect(result.root).not.toBeNull();+ expect(result.root?.typeName).toBe("DataTable");+ expect((result.root?.props as any)._args).toEqual(["col"]);+ });++ it("reports all unknown components in a tree", () => {+ const r = codes('root = Stack([Ghost("a")])\n');+ expect(r).toContain("unknown-component");+ });++ it("does not report for known component names", () => {+ const result = parse('root = Stack(["hello"])', schema);+ expect(codes('root = Stack(["hello"])')).not.toContain("unknown-component");+ expect(result.meta.errors).toHaveLength(0);+ });+});++// ── excess-args ───────────────────────────────────────────────────────────────++describe("excess-args", () => {+ it("reports when more args are passed than params", () => {+ const result = parse('root = Title("hello", "extra")', schema);+ expect(result.meta.errors).toHaveLength(1);+ expect(result.meta.errors[0]).toMatchObject({+ type: "validation",+ code: "excess-args",+ component: "Title",+ path: "",+ });+ expect(result.meta.errors[0].message).toMatch(/takes 1 arg/);+ });++ it("still renders the component despite excess args", () => {+ const result = parse('root = Title("hello", "extra")', schema);+ expect(result.root).not.toBeNull();+ expect(result.root?.props.text).toBe("hello");+ });++ it("does not report when arg count matches param count", () => {+ expect(codes('root = Title("hello")')).not.toContain("excess-args");+ });++ it("does not report when fewer args than params (handled by missing-required)", () => {+ expect(codes("root = Table([], [])")).not.toContain("excess-args");+ });+});++// ── unresolved references ────────────────────────────────────────────────────++describe("unresolved references", () => {+ it("tracks unresolved refs in meta.unresolved (one-shot)", () => {+ const result = parse("root = Stack([tbl])", schema);+ expect(result.meta.unresolved).toContain("tbl");+ });++ it("does not produce errors for unresolved refs", () => {+ const result = parse("root = Stack([tbl])", schema);+ expect(result.meta.errors).toHaveLength(0);+ });++ it("clears unresolved when ref is defined", () => {+ const result = parse('root = Stack([tbl])\ntbl = Title("hello")', schema);+ expect(result.meta.unresolved).toHaveLength(0);+ });+});++// ── unresolved references (streaming) ─────────────────────────────────────────++describe("unresolved references (streaming)", () => {+ it("tracks unresolved refs mid-stream without errors", () => {+ const parser = createStreamParser(schema);+ const midResult = parser.push("root = Stack([tbl])\n");+ expect(midResult.meta.unresolved).toContain("tbl");+ expect(midResult.meta.errors).toHaveLength(0);+ });++ it("resolves automatically when ref is defined in a later chunk", () => {+ const parser = createStreamParser(schema);+ parser.push("root = Stack([tbl])\n");+ const result = parser.push('tbl = Title("hello")\n');+ expect(result.meta.unresolved).toHaveLength(0);+ });++ it("keeps unresolved refs in meta.unresolved at end of stream", () => {+ const parser = createStreamParser(schema);+ parser.push("root = Stack([tbl])\n");+ const result = parser.getResult();+ expect(result.meta.unresolved).toContain("tbl");+ expect(result.meta.errors).toHaveLength(0);+ });+});++// ── existing error rules ──────────────────────────────────────────────────────++describe("existing errors carry type and code", () => {+ it("missing-required has correct shape", () => {+ const result = parse("root = Stack()", schema);+ expect(result.meta.errors).toHaveLength(1);+ expect(result.meta.errors[0]).toMatchObject({+ type: "validation",+ code: "missing-required",+ });+ });++ it("null-required has correct shape", () => {+ const result = parse("root = Stack(null)", schema);+ expect(result.meta.errors).toHaveLength(1);+ expect(result.meta.errors[0]).toMatchObject({+ type: "validation",+ code: "null-required",+ });+ });+});diff --git a/packages/react-lang/src/parser/index.ts b/packages/react-lang/src/parser/index.tsindex 7cab53b1a..1dc9018ee 100644--- a/packages/react-lang/src/parser/index.ts+++ b/packages/react-lang/src/parser/index.ts@@ -1,5 +1,11 @@export { BuiltinActionType } from "./types";-export type { ActionEvent, ElementNode, ParseResult, ValidationError } from "./types";+export type {+ ActionEvent,+ ElementNode,+ OpenUIError,+ ParseResult,+ ValidationErrorCode,+} from "./types";export { createParser, createStreamingParser, parse } from "./parser";export type { LibraryJSONSchema, Parser, StreamParser } from "./parser";diff --git a/packages/react-lang/src/parser/parser.ts b/packages/react-lang/src/parser/parser.tsindex 3134d2d03..de99071b9 100644--- a/packages/react-lang/src/parser/parser.ts+++ b/packages/react-lang/src/parser/parser.ts@@ -499,7 +499,7 @@ type JsonVal = string | number | boolean | null | JsonVal[] | { [k: string]: Jsofunction toJson(node: ASTNode,partial: boolean,- errors: ParseResult["meta"]["validationErrors"],+ errors: ParseResult["meta"]["errors"],cat: ParamMap | undefined,): JsonVal {if (node.k === "Str") return node.v;@@ -531,7 +531,7 @@ function toJson(function mapNode(node: ASTNode,partial: boolean,- errors: ParseResult["meta"]["validationErrors"],+ errors: ParseResult["meta"]["errors"],cat: ParamMap | undefined,): ParseResult["root"] {if (node.k === "Ph") return null;@@ -546,6 +546,17 @@ function mapNode(for (let i = 0; i < def.params.length && i < args.length; i++)props[def.params[i].name] = toJson(args[i], partial, errors, cat);+ // Report extra positional args that have no corresponding param+ if (args.length > def.params.length) {+ errors.push({+ type: "validation",+ code: "excess-args",+ component: name,+ path: "",+ message: `${name} takes ${def.params.length} arg(s), got ${args.length}`,+ });+ }+// Validate required props — try defaultValue first before droppingconst missingRequired = def.params.filter((p) => p.required && (!(p.name in props) || props[p.name] === null),@@ -561,6 +572,8 @@ function mapNode(if (stillInvalid.length) {for (const p of stillInvalid)errors.push({+ type: "validation",+ code: p.name in props ? "null-required" : "missing-required",component: name,path: `/${p.name}`,message:@@ -572,7 +585,14 @@ function mapNode(}}} else {- // No library entry for this component — preserve all args under _args+ // Component name not found in schema — report and preserve args for debugging+ errors.push({+ type: "validation",+ code: "unknown-component",+ component: name,+ path: "",+ message: `unknown component "${name}"`,+ });props._args = args.map((a) => toJson(a, partial, errors, cat));}@@ -586,7 +606,7 @@ function emptyResult(incomplete = true): ParseResult {incomplete,unresolved: [],statementCount: 0,- validationErrors: [],+ errors: [],},};}@@ -602,7 +622,7 @@ function buildResult(const unres: string[] = [];const resolved = resolveNode(syms.get(firstId)!, syms, unres, new Set());- const errors: ParseResult["meta"]["validationErrors"] = [];+ const errors: ParseResult["meta"]["errors"] = [];const root = mapNode(resolved, wasIncomplete, errors, cat);return {@@ -611,7 +631,7 @@ function buildResult(incomplete: wasIncomplete,unresolved: unres,statementCount: stmtCount,- validationErrors: errors,+ errors,},};}diff --git a/packages/react-lang/src/parser/types.ts b/packages/react-lang/src/parser/types.tsindex b3754d0f6..9c20c8a45 100644--- a/packages/react-lang/src/parser/types.ts+++ b/packages/react-lang/src/parser/types.ts@@ -19,18 +19,36 @@ export interface ElementNode {}/**- * A prop validation error from the Rust parser.- * When a component has missing required props, it is redacted from the- * output tree (dropped as null) and errors are recorded here.+ * Validation error codes for schema-related issues.+ *+ * - `missing-required` — a required prop was absent and has no default value+ * - `null-required` — a required prop was explicitly null with no default+ * - `unknown-component` — the component name is not in the library schema+ * - `excess-args` — more positional args were passed than the schema defines+ */+export type ValidationErrorCode =+ | "missing-required"+ | "null-required"+ | "unknown-component"+ | "excess-args";++/**+ * Structured error from the parser.+ *+ * Currently only `type: "validation"` exists; future versions may add+ * `type: "parser"` for diagnostics like incomplete input.*/-export interface ValidationError {+export type OpenUIError = {+ type: "validation";+ /** Which validation rule produced this error. */+ code: ValidationErrorCode;/** Component type name, e.g. "Header", "BarChart". */component: string;/** JSON Pointer path within the props object, e.g. "/title", "". */path: string;/** Human-readable error message. */message: string;-}+};/*** Built-in action types for interactive components.@@ -74,9 +92,9 @@ export interface ParseResult {/** Total number of `identifier = Expression` statements parsed. */statementCount: number;/**- * Prop validation errors. Components with missing required props are- * redacted (dropped as null) and listed here.+ * Structured errors from the parser. Components with missing required+ * props are redacted (dropped as null) and listed here.*/- validationErrors: ValidationError[];+ errors: OpenUIError[];};}diff --git a/packages/react-lang/tsconfig.test.json b/packages/react-lang/tsconfig.test.jsonnew file mode 100644index 000000000..60b3001d5--- /dev/null+++ b/packages/react-lang/tsconfig.test.json@@ -0,0 +1,9 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "noEmit": true+ },+ "include": ["src/**/*"],+ "exclude": ["dist", "node_modules"]+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2da2e98dd..c6eddd5f3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -538,6 +538,9 @@ importers:'@types/react':specifier: ^19.0.0version: 19.2.14+ vitest:+ specifier: ^4.0.18+ version: 4.0.18(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/react-ui:dependencies: