A2UI icon indicating copy to clipboard operation
A2UI copied to clipboard

[Proposal] Resolve child components based on schema and not on hardcoded 'child'/'children' keywords. Also improve REF: handling

Open josemontespg opened this issue 6 months ago • 8 comments

Make component binders schema-driven for child component resolution (remove hardcoded 'child'/'children' keywords)

Motivation

Currently, both the Angular binder (ComponentBinder) and the Generic Binder (GenericBinder) rely on hardcoded property names (child, trigger, content, children) to identify which properties represent child component references. This introduces a few limitations:

  1. Lack of Flexibility: Custom component definitions cannot use alternative property names for child components (e.g., header, footer, avatar, leftAction).
  2. Boilerplate and Code Duplication: Component implementations (such as TabsComponent in Angular) are forced to manually normalize child properties nested inside objects or arrays because the binder only resolves top-level properties matching the hardcoded names.
  3. Inconsistency: Dynamic child lists template are resolved to {id, basePath} objects but static child lists (which are just arrays of IDs) are returned as raw string arrays, requiring renderers to write custom fallback code.

Proposed Design (Updated)

We propose making both binders fully schema-driven for child component resolution using a combination of Zod runtime metadata, Zod branded types for compile-time safety, recursive binder resolution, and clean JSON Schema reference generation:

1. Tag and Brand Core Schemas via a Custom Helper Function

We define custom decoupled metadata properties on Zod schema definitions (_def objects) to control runtime binding and schema reference generation separately:

  • a2uiType: Declares the binder's runtime mapping behavior (e.g. CHILD, STRUCTURAL, ACTION, DYNAMIC).
  • refPath: Declares the JSON Schema $ref pointer path in the generated client catalog.

Instead of globally mutating Zod's prototype class—which creates side-effects, risks library name collisions, hinders tree-shaking, and introduces temporal coupling—we define a clean, side-effect-free Custom Helper Function inside renderers/web_core/src/v0_9/schema/common-types.ts to attach this metadata to the schemas in a type-safe way:

export interface A2uiTypeDef {
  a2uiType?: 'Dynamic' | 'ComponentId' | 'ChildList' | 'Action';
  refPath?: string;
}

/**
 * Attaches A2UI metadata to a Zod schema's internal definition safely.
 */
export function withA2uiMetadata<T extends z.ZodTypeAny>(
  schema: T,
  metadata: A2uiTypeDef
): T {
  Object.assign(schema._def, metadata);
  return schema;
}

This lets us brand and register schemas cleanly in a functional, declarative style:

export const ComponentIdSchema = withA2uiMetadata(
  z.string().brand<'ComponentId'>().describe('The unique identifier for a component.'),
  {
    a2uiType: 'ComponentId',
    refPath: 'common_types.json#/$defs/ComponentId'
  }
);

export const ChildListSchema = withA2uiMetadata(
  z.union([
    z.array(ComponentIdSchema).describe('A static list of child component IDs.'),
    z.object({
      componentId: ComponentIdSchema,
      path: z.string().describe('The path to the list of component property objects in the data model.'),
    }),
  ]).describe('A static list of child component IDs or a dynamic list template.'),
  {
    a2uiType: 'ChildList',
    refPath: 'common_types.json#/$defs/ChildList'
  }
);

Zod shallow-copies the _def object when wrapper methods (like .optional() or .nullable()) are called, so this metadata automatically survives and propagates down the schema wrappers without any global prototype side-effects.


2. Clean JSON Schema Reference Generation

Instead of encoding reference pointers inside .describe("REF:...") string hacks (which required a post-processing parsing step processRefs), we utilize zod-to-json-schema's override callback inside MessageProcessor.generateInlineCatalog to inspect the refPath metadata directly:

const zodToJsonSchemaOptions = {
  target: 'jsonSchema2019-09' as const,
  override: (def: any) => {
    const a2uiDef = def as A2uiTypeDef;
    if (a2uiDef.refPath) {
      return {
        $ref: a2uiDef.refPath,
        description: (def as any).description, // Preserve clean description
      };
    }
    return ignoreOverride; // Fallback to default converters
  },
};

This generates correct, clean $ref schemas in the catalog JSON, allowing us to delete the MessageProcessor.processRefs post-processing step entirely.


3. Recursive Compile-Time Type Resolution

To avoid complex, hard-to-read chained ternaries in typescript types, we replace the flat type mapping helpers in the binders with recursive type resolvers split into named intermediate helpers.

For example, in renderers/angular/v0_9/core/types.ts:

type UnwrappedDynamic<T> = Exclude<T, DynamicTypes>;

// 1. Recurse nested objects/arrays
type ResolveAngularPropNested<T> = T extends (infer U)[]
  ? ResolveAngularProp<U>[]
  : T extends object
    ? {[K in keyof T]: ResolveAngularProp<T[K]>}
    : T;

// 2. Resolve properties after stripping dynamic value schemas
type ResolveNonComponentProp<T> =
  UnwrappedDynamic<T> extends never ? any : ResolveAngularPropNested<UnwrappedDynamic<T>>;

// 3. Resolve child component references
type ResolveNonNullAngularProp<T> = [T] extends [ChildList]
  ? Child[]
  : [T] extends [ComponentId]
    ? Child
    : ResolveNonComponentProp<T>;

// 4. Handle nullability and distribute unions
export type ResolveAngularProp<T> = T extends null | undefined ? T : ResolveNonNullAngularProp<T>;

This maps nested ComponentId properties (such as Tabs.tabs[].child) to Child ({id, basePath}) and resolves dynamic types to raw literals at compile time with strict type-safety. A similar split helper is implemented for ResolveA2uiProp in the generic binder.


4. Behavior Scraping in Generic Binder

Add a new behavior type CHILD to BehaviorNode in generic-binder.ts. Update getFieldBehavior to return behaviors using explicit a2uiType tag matching by casting Zod _def to A2uiTypeDef:

const a2uiType = (current._def as A2uiTypeDef).a2uiType;
if (a2uiType) {
  switch (a2uiType) {
    case 'ComponentId':
      return {type: 'CHILD'};
    case 'ChildList':
      return {type: 'STRUCTURAL'};
    case 'Action':
      return {type: 'ACTION'};
    case 'Dynamic':
      return {type: 'DYNAMIC'};
  }
}

5. Pass Schema and Implement Recursive Resolution in Angular Binder

  • Update ComponentHostComponent to pass the catalog api.schema to ComponentBinder.bind(context, api.schema).
  • Rewrite ComponentBinder.bind to recursively traverse and resolve properties using a recursive helper resolveNested (matching the Preact resolution in GenericBinder), replacing the hardcoded property name checks:
  private resolveNested(value: any, behavior: BehaviorNode, context: ComponentContext): Signal<any> {
    if (value === undefined || value === null) {
      if (behavior.type === 'STRUCTURAL') return signal([]);
      return signal(value);
    }
    switch (behavior.type) {
      case 'CHILD': // Resolve to Child reference
      case 'STRUCTURAL': // Resolve to Child[]
      case 'DYNAMIC': // Resolve dynamic value path/call
      case 'ARRAY': // Recurse array
      case 'OBJECT': // Recurse object shape
      ...
    }
  }

6. Dart/Flutter (Other Renderers) Support

Since the inline catalog sent over the wire contains standard JSON Schema $ref properties pointing to common_types.json#/$defs/ComponentId and ChildList, non-TypeScript clients (such as Flutter/Dart) can easily identify child component elements at runtime by inspecting the schema, or map them automatically during code generation (using tools like freezed or json_serializable).


7. Resilience and Edge Cases

  • Missing Schemas: Fallback to z.object({}) in ComponentBinder.bind if a component's schema is not defined in the catalog.
  • Null Defaults: Resolve null/undefined children lists to [] for STRUCTURAL behavior to ensure type safety.

josemontespg avatar Jun 03 '26 01:06 josemontespg

@jacobsimionato, @ditman, @andrewkolos Any thoughts on this proposal? I think this would not require a change in the spec, just a change in how we implement the schemas and the binders.

josemontespg avatar Jun 04 '26 22:06 josemontespg

Oh yes definitely!!! I acutally didn't realise we were relying on these magic names - sorry 😂. I intended for it to recognize the schemas for child IDs etc based on structure, but I like your "branding" approach even more.

I think we actually have a similar problem in message processor, where to geneate inline catalogs content, we "detect" subschemas for common types using a magical string in the description, and then replace them with JSON schema references rather than inlined subschemas, e.g. so we can have references to common_types in the catalog document.

See: https://github.com/a2ui-project/a2ui/blob/61d4f02190df0222bde979b9e55c4726aec1ace4/renderers/web_core/src/v0_9/processing/message-processor.ts#L150-L179

And: https://github.com/a2ui-project/a2ui/blob/61d4f02190df0222bde979b9e55c4726aec1ace4/renderers/web_core/src/v0_9/schema/common-types.ts#L94-L98

The branding approach you describe here sounds way better. I wonder if we can also migrate this part of the code to use branding to help us identify specific Zod subschemas.

jacobsimionato avatar Jun 04 '26 23:06 jacobsimionato

This is cool. Please remember to update the renderer_guide.md where appropriate!

Some questions:

  1. There's several instances of the changes required to the angular renderer. Can you expand this design doc with how that'd look like for the other 2 renderers that we support? It'd be nice to see how the solution would look like on the other renderers before comitting to it.
    • type ResolveAngularProp<T> -> 💀 Is there any way that we can define the types better so there's less math? This is 4 ternary operators chained now 💀
  2. Do we foresee needing to add more values to the a2uiType enum? I wonder if this can be modeled as actual class types, instead of us building our own "OOP" for runtime types.
  3. If we go with .a2uiType: We're setting it and accessing it via casting (const a2uiType = (current._def as A2uiTypeDef).a2uiType;). Why don't we just make it part of the class hierarchy so we don't have to "hide" it like this? We can just name it as "private"(-ish) so users don't rely on it for their code.
    • Alternatively, maybe we can "hide" the a2uiType property as a "Well-Known" (to A2UI) Symbol that we don't re-export, but we can use directly without casting?
  4. Is this approach implementable in the other renderers that we maintain? Especifically the Flutter one? We can't do very sophisticated math with types there!

ditman avatar Jun 05 '26 18:06 ditman

Thanks for the fantastic feedback, @jacobsimionato and @ditman!

I worked with my agent to incorporate the feedback into the design, and verified the approach in a draft branch.

Here are the direct answers to your questions and suggestions:


@jacobsimionato:

"I wonder if we can also migrate this part of the code to use branding to help us identify specific Zod subschemas."

Yes, absolutely! By decoupling the metadata (a2uiType for binder behavior and refPath for schema references), we can use zod-to-json-schema's override callback inside MessageProcessor.generateInlineCatalog to inspect the refPath directly.

This completely removes the legacy "REF:..." description string hacks (descriptions can now be pure, user-facing docs) and allows us to delete the recursive processRefs post-processing method entirely:

const zodSchema = zodToJsonSchema(api.schema, {
  target: 'jsonSchema2019-09',
  override: (def) => {
    const a2uiDef = def as A2uiTypeDef;
    if (a2uiDef.refPath) {
      return {
        $ref: a2uiDef.refPath,
        description: (def as any).description, // Preserve clean description
      };
    }
    return ignoreOverride; // Fallback to default converters
  }
});

@ditman:

  1. "type ResolveAngularProp<T> -> 💀 Is there any way that we can define the types better so there's less math? This is 4 ternary operators chained now 💀"

Yes! We split the type-resolution math into smaller, named intermediate helper types. This completely removes chained ternaries and clearly documents the resolution phases:

type UnwrappedDynamic<T> = Exclude<T, DynamicTypes>;

// 1. Recurse into nested structures
type ResolveAngularPropNested<T> = T extends (infer U)[]
  ? ResolveAngularProp<U>[]
  : T extends object
    ? {[K in keyof T]: ResolveAngularProp<T[K]>}
    : T;

// 2. Resolve properties after stripping dynamic types
type ResolveNonComponentProp<T> = UnwrappedDynamic<T> extends never
  ? any
  : ResolveAngularPropNested<UnwrappedDynamic<T>>;

// 3. Resolve child component references
type ResolveNonNullAngularProp<T> = [T] extends [ChildList]
  ? Child[]
  : [T] extends [ComponentId]
    ? Child
    : ResolveNonComponentProp<T>;

// 4. Entry point: handle null & undefined first to preserve strict null-safety
export type ResolveAngularProp<T> = T extends null | undefined
  ? T
  : ResolveNonNullAngularProp<T>;

  1. "If we go with .a2uiType: We're setting it and accessing it via casting. Why don't we just make it part of the class hierarchy so we don't have to "hide" it like this? Alternatively, maybe we can "hide" the a2uiType property as a "Well-Known" (to A2UI) Symbol that we don't re-export..."
  • Class Hierarchy: Zod schemas are instances of external third-party classes (like ZodString, ZodObject), so we cannot modify their class hierarchy directly.
  • Fluent prototype chaining: Instead of Symbol hiding or raw metadata mutations, we chose to extend the ZodType class using TypeScript module augmentation and JavaScript prototype extensions inside common-types.ts:
import { ZodType } from 'zod';

declare module 'zod' {
  interface ZodType {
    setA2uiType(type: 'Dynamic' | 'ComponentId' | 'ChildList' | 'Action'): this;
    setRefPath(path: string): this;
  }
}

(ZodType.prototype as any).setA2uiType = function (type: any) {
  this._def.a2uiType = type;
  return this;
};

(ZodType.prototype as any).setRefPath = function (path: string) {
  this._def.refPath = path;
  return this;
};

This allows us to declare our core schemas using native-feeling method chains, while ensuring the metadata survives Zod's internal shallow copies when wrappers (like .optional() or .nullable()) are called:

export const ComponentIdSchema = z
  .string()
  .brand<'ComponentId'>()
  .describe('The unique identifier for a component.')
  .setA2uiType('ComponentId')
  .setRefPath('common_types.json#/$defs/ComponentId');

  1. "Is this approach implementable in the other renderers that we maintain? Especifically the Flutter one? We can't do very sophisticated math with types there!"

Yes! Since the inline catalog sent over the protocol now contains standard, explicit JSON Schema $ref fields (e.g. "$ref": "common_types.json#/$defs/ComponentId"), non-TypeScript clients (such as Flutter/Dart) do not need to perform complex compile-time type math. At runtime, the client can parse the JSON schema and look up if the field has a $ref pointing to ComponentId or ChildList. Similarly, during code generation (using tools like freezed or json_serializable), the code generator can easily map these references to custom Dart types.

We will document this pattern clearly in the renderer_guide.md

josemontespg avatar Jun 05 '26 20:06 josemontespg

we chose to extend the ZodType class using TypeScript module augmentation and JavaScript prototype extensions inside common-types.ts

Yikesss, I'm not sure this is better than before, we shouldn't be extending what we don't own IMO! I guess we can't use the symbols because resolution happens at compile-time, not run-time?

ditman avatar Jun 05 '26 21:06 ditman

Yikesss, I'm not sure this is better than before, we shouldn't be extending what we don't own IMO! I guess we can't use the symbols because resolution happens at compile-time, not run-time?

Mmm yes good point, extending Zod does have its drawbacks. The benefits are a more friendly syntax, but since this syntax is only needed in renderers/web_core/src/v0_9/schema/common-types.ts which defines the schemas, the syntax is not super important.

I revised the design to instead use a safer withA2uiMetadata helper function approach

josemontespg avatar Jun 05 '26 21:06 josemontespg

@josemontespg @jacobsimionato do you think this may be a good candidate to try the blueprints proposal?

ditman avatar Jun 26 '26 00:06 ditman

A2UI Triage: Assigned P2

gspencergoog avatar Jun 29 '26 18:06 gspencergoog