Skip to content

fix(react): include catalog event bindings in JSON Schema - #370

Open
armstrongsam25 wants to merge 1 commit into
vercel-labs:mainfrom
armstrongsam25:fix/catalog-event-schema
Open

armstrongsam25 wants to merge 1 commit into
vercel-labs:mainfrom
armstrongsam25:fix/catalog-event-schema

Conversation

@armstrongsam25

@armstrongsam25 armstrongsam25 commented Oct 1, 2026 •

Copy link
Copy Markdown

Fixes #356.

The React catalog leaves on out of its spec schema. That means jsonSchema() cannot describe event bindings, and validate() drops them from otherwise valid specs.

This adds s.eventsOf() and uses it for the React element's optional on field. Declared events accept a single action or an array. Actions and action callbacks are limited to the catalog and built-ins; nested JSON parameters and dynamic expressions survive validation. Confirmation, navigation, state callbacks, and preventDefault keep their existing format.

Event names are collected across the catalog, rather than narrowed by each element's component type. The existing strict-mode limitation for dynamic-key maps is unchanged. Package docs, API docs, skills, and the affected docs fixture are updated.

Fresh validation on this head: pnpm test --maxWorkers=2 passes 1,245 tests across 82 files (review probe removed), and pnpm type-check passes 60 tasks. Earlier validation on this same head also passed pnpm lint, the production web build, and both API-page content/Markdown parity checks.

Reproducible before/after evidence (October 1, 2026)

Compared base c2600d7 with PR head 11a5d81, using Node 24.19.0, pnpm 11.1.3 and Vitest 4.0.17 on Windows. Rebuilt @json-render/core, @internal/react-state and @json-render/react for each comparison. The base run restores the two changed runtime files from the base commit; all remaining core/React runtime source is identical between those commits. Both runs use the same fixtures and renderer.

The probe follows defineCatalog → jsonSchema() / validate() → JSONUIProvider + Renderer → a DOM button click → real action handlers/state updates. It imports the built packages through their public exports. The input has on.press calling go with name: { "$state": "/name" }; provider state supplies name: "Ada".

Observation Base PR head
Exported element schema contains on No Yes; declares press and catalog/built-in action names
Successful validation preserves on.press No; silently strips it Yes; full input preserved
Click on raw, unvalidated spec Calls go({name: "Ada"}) once Same
Click on validated spec No handler call Calls go({name: "Ada"}) once
Validated chain: setState → go → success callback No calls; saved stays false saved becomes true; go reads the updated value; callback receives nested JSON intact
Unknown event/action, missing action, unknown callback action Validation succeeds after stripping on All four are rejected
Spec without on Accepted Accepted

The raw-spec control confirms that the renderer already handles the event. The failure is introduced by catalog validation dropping the binding. This is a deterministic React/jsdom integration proof; it does not claim a browser deployment or an external-model generation test.

Captured output and test totals

Exact probe output from the two runs (local paths, timings and terminal color codes omitted):

BASE c2600d73908ed505e6d726f5b6f969ba8f597ce7
SINGLE {"schemaHasOn":false,"declaredEvents":[],"allowedActions":[],"validatedOn":null,"rawClickCalls":[{"name":"Ada"}],"validatedClickCalls":[]}
CHAIN {"raw":{"calls":[{"saved":true},{"rows":[{"id":1}],"meta":{"ok":true}}],"state":{"name":"Ada","saved":true}},"validated":{"calls":[],"state":{"name":"Ada","saved":false}}}
VALIDATION {"accepted":{"undeclaredEvent":true,"unknownAction":true,"missingAction":true,"unknownCallback":true},"optional":true}
Test Files  2 failed (2)
Tests       17 failed | 1 passed (18)

HEAD 11a5d81118feb0cd46efadfc85f75f456dbebf83
SINGLE {"schemaHasOn":true,"declaredEvents":["press"],"allowedActions":["go","setState","pushState","removeState","validateForm"],"validatedOn":{"press":{"action":"go","params":{"name":{"$state":"/name"}}}},"rawClickCalls":[{"name":"Ada"}],"validatedClickCalls":[{"name":"Ada"}]}
CHAIN {"raw":{"calls":[{"saved":true},{"rows":[{"id":1}],"meta":{"ok":true}}],"state":{"name":"Ada","saved":true}},"validated":{"calls":[{"saved":true},{"rows":[{"id":1}],"meta":{"ok":true}}],"state":{"name":"Ada","saved":true}}}
VALIDATION {"accepted":{"undeclaredEvent":false,"unknownAction":false,"missingAction":false,"unknownCallback":false},"optional":true}
Test Files  2 passed (2)
Tests       18 passed (18)

Those 18 cases comprise the 15 committed event-schema regressions plus the three review-probe cases below. All three probe cases fail on the base and pass on the head. Of the committed regressions, 14 fail on the base (including the new s.eventsOf API being absent); the optional-on case passes on both. The review probe is supplied here and is not an additional file in the PR diff.

Reproduce with the same inputs and assertions

Use a disposable clone with Node 24 and pnpm 11.1.3:

git clone https://github.com/armstrongsam25/json-render.git json-render-pr370-evidence
cd json-render-pr370-evidence
git checkout --detach 11a5d81118feb0cd46efadfc85f75f456dbebf83
pnpm install --frozen-lockfile

Save the test below as packages/react/src/pr370-evidence.test.tsx, then run the base comparison. The test command is expected to exit 1:

git restore --source=c2600d73908ed505e6d726f5b6f969ba8f597ce7 -- packages/core/src/schema.ts packages/react/src/schema.ts
pnpm --filter @json-render/core build
pnpm --filter @internal/react-state build
pnpm --filter @json-render/react build
pnpm exec vitest run packages/react/src/pr370-evidence.test.tsx packages/core/src/event-schema.test.ts --maxWorkers=1 --reporter=verbose

Restore and rebuild the PR implementation. The same test command now exits 0:

git restore --source=11a5d81118feb0cd46efadfc85f75f456dbebf83 -- packages/core/src/schema.ts packages/react/src/schema.ts
pnpm --filter @json-render/core build
pnpm --filter @internal/react-state build
pnpm --filter @json-render/react build
pnpm exec vitest run packages/react/src/pr370-evidence.test.tsx packages/core/src/event-schema.test.ts --maxWorkers=1 --reporter=verbose
import React from "react";
import { afterEach, expect, it } from "vitest";
import { act, cleanup, fireEvent, render } from "@testing-library/react";
import { z } from "zod";
import { defineCatalog, type Spec } from "@json-render/core";
import { schema } from "@json-render/react/schema";
import {
  JSONUIProvider,
  Renderer,
  useStateStore,
  type ComponentRenderProps,
} from "@json-render/react";

afterEach(cleanup);

const catalog = defineCatalog(schema, {
  components: {
    Button: { props: z.object({ label: z.string() }), events: ["press"] },
  },
  actions: { go: { description: "Record the supplied parameters" } },
});

function makeSpec(on: unknown) {
  return {
    root: "button",
    elements: {
      button: { type: "Button", props: { label: "Go" }, children: [], on },
    },
  };
}

function Button({ element, emit }: ComponentRenderProps<{ label: string }>) {
  return <button onClick={() => emit("press")}>{element.props.label}</button>;
}

function StateProbe() {
  const { state } = useStateStore();
  return <output data-testid="state">{JSON.stringify(state)}</output>;
}

async function clickOnce(spec: Spec) {
  const calls: unknown[] = [];
  const registry = { Button };
  const view = render(
    <JSONUIProvider
      registry={registry}
      initialState={{ name: "Ada", saved: false }}
      handlers={{
        go: async (params) => {
          calls.push(params);
        },
      }}
    >
      <Renderer spec={spec} registry={registry} />
      <StateProbe />
    </JSONUIProvider>,
  );
  await act(async () => {
    fireEvent.click(view.getByRole("button", { name: "Go" }));
  });
  const state = JSON.parse(view.getByTestId("state").textContent!);
  view.unmount();
  return { calls, state };
}

it("exports on and preserves a validated binding through a rendered click", async () => {
  const input = makeSpec({
    press: { action: "go", params: { name: { $state: "/name" } } },
  });
  const exported = catalog.jsonSchema() as any;
  const on = exported.properties.elements.additionalProperties.properties.on;
  const parsed = catalog.validate(input);
  expect(parsed.success).toBe(true);
  if (!parsed.success) throw new Error("Valid input rejected");
  const raw = await clickOnce(input as Spec);
  const validated = await clickOnce(parsed.data as Spec);
  const report = {
    schemaHasOn: !!on,
    declaredEvents: Object.keys(on?.properties ?? {}),
    allowedActions: on?.properties.press.anyOf[0].properties.action.enum ?? [],
    validatedOn: (parsed.data as Spec).elements.button?.on ?? null,
    rawClickCalls: raw.calls,
    validatedClickCalls: validated.calls,
  };
  console.log("SINGLE " + JSON.stringify(report));
  expect(raw.calls).toEqual([{ name: "Ada" }]);
  expect(report.schemaHasOn).toBe(true);
  expect(report.declaredEvents).toEqual(["press"]);
  expect(report.allowedActions).toEqual([
    "go",
    "setState",
    "pushState",
    "removeState",
    "validateForm",
  ]);
  expect(parsed.data).toEqual(input);
  expect(validated.calls).toEqual([{ name: "Ada" }]);
});

it("executes validated built-in/custom action arrays and nested callback parameters", async () => {
  const input = makeSpec({
    press: [
      { action: "setState", params: { statePath: "/saved", value: true } },
      {
        action: "go",
        params: { saved: { $state: "/saved" } },
        onSuccess: {
          action: "go",
          params: { rows: [{ id: 1 }], meta: { ok: true } },
        },
      },
    ],
  });
  const parsed = catalog.validate(input);
  expect(parsed.success).toBe(true);
  if (!parsed.success) throw new Error("Valid input rejected");
  const raw = await clickOnce(input as Spec);
  const validated = await clickOnce(parsed.data as Spec);
  console.log("CHAIN " + JSON.stringify({ raw, validated }));
  const expected = {
    calls: [{ saved: true }, { rows: [{ id: 1 }], meta: { ok: true } }],
    state: { name: "Ada", saved: true },
  };
  expect(raw).toEqual(expected);
  expect(validated).toEqual(expected);
  expect(parsed.data).toEqual(input);
});

it("rejects malformed bindings while keeping on optional", () => {
  const cases = {
    undeclaredEvent: { click: { action: "go" } },
    unknownAction: { press: { action: "missing" } },
    missingAction: { press: {} },
    unknownCallback: {
      press: { action: "go", onSuccess: { action: "missing" } },
    },
  };
  const accepted = Object.fromEntries(
    Object.entries(cases).map(([name, on]) => [
      name,
      catalog.validate(makeSpec(on)).success,
    ]),
  );
  const optional = catalog.validate(makeSpec(undefined)).success;
  console.log("VALIDATION " + JSON.stringify({ accepted, optional }));
  expect(optional).toBe(true);
  expect(Object.values(accepted)).toEqual([false, false, false, false]);
});

Vercel preview deployments still require authorization from a Vercel Labs Team member. The local evidence above does not depend on that deployment gate.

Contributed by @armstrongsam25 with PAIL. AstralDeep already defines and validates component actions in AstralProjection's component model. This adapts that approach to json-render's event bindings; no Astral source was copied.

@vercel

vercel Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

@armstrongsam25 is attempting to deploy a commit to the Vercel Labs Team on Vercel.

A member of the Team first needs to authorize it.

@armstrongsam25
armstrongsam25 marked this pull request as ready for review October 1, 2026 05:03

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

catalog.jsonSchema() does not describe the element-level on field

1 participant