Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.

Commit 67749c7

Browse files
claude[bot]os-salesclaude
authored
fix(types,cli): discriminate AnyComponentSchema on type so a refusal costs one arm, not 106 (#8498) (#8544)
* fix(types,cli): discriminate `AnyComponentSchema` on `type` so a refusal costs one arm `AnyComponentSchema` was a flat `z.union`, so a refusal carried every arm's issue list, and Zod's `$ZodError` initializer stringifies that whole tree into `.message` eagerly — in the constructor, not behind a getter. Measured on zod 4.4.3, a root refusal cost 14,624 chars and grew ~25x per level of nesting until `safeParse` threw `RangeError: Invalid string length` out of `safeValidateSchema`, which is documented as validating "without throwing errors". Discriminating on `type` selects one arm from the authored literal: same document, 164 chars. `ObjectQLComponentSchema` and `CRUDComponentSchema` are discriminated too because zod 4.4.3 refuses a plain `z.union` as a discriminated member. The accept set does not move: the 13 arms declare 107 `type` literals with zero collisions, and flat vs discriminated agree on all 440 example documents. `@object-ui/cli`'s `union-arm-diagnostics` learns the discriminated issue shape, so `objectui validate` still prints the 2026-09-02 maintainer ruling's output — the selected arm alone, or a note plus a capped candidate list. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CZY49skxUBYyJcdnTcYPrE * fix(cli,types): the no-arm note is for `type`-keyed unions only; keep a non-object root its own message Two defects from the in-seat contract review of PR #8544. 1. `noMatchingDiscriminator` routed on `note`/`options`/empty-`errors` alone, so a discriminated union keyed on anything else was summarised as if it were keyed on `type`. `@objectstack/spec`'s `ViewDataSchema` is `discriminatedUnion('provider', ...)` and rides `.data` on `object-grid` and three siblings, so an authored `{ type: 'object-grid', data: { ... } }` printed a confident, ruling-shaped sentence naming the wrong key and offering provider names as component types. The merge base printed nothing there — silent, not wrong — so this was a silent-to-wrong regression. Guarded on both the path's last segment and the `discriminator` field: they establish different facts, and a shape that ever separates them now falls through to silent rather than to wrong. 2. The union's message override was unconditional, so it was scoped to the whole schema and also replaced its `invalid_type`: a non-object root lost "expected object, received number". Narrowed to `invalid_union`. Also corrects stale prose the discriminated root falsified, in the reader's header and in one figure in the new test's header. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CZY49skxUBYyJcdnTcYPrE * docs(cli): restate the two `validate.ts` sentences the discriminated root falsified Comment-only, authorised as the single follow-up to the contract re-review PASS on 42344e9. No code changes. `validate.ts` still described `AnyComponentSchema` as a `z.union` whose every no-arm document yields one top-level issue at `path: []`, and still credited `explainUnionIssue` with selecting the arm. Both went false when the union began discriminating on `type`: zod does the selecting, a matched discriminator yields the arm's own issues as top-level entries at absolute paths, a missed one is judged at `['type']`, and a root path now means the document is not a component object at all. Also corrects a line citation in `union-arm-diagnostics.ts`: zod fills `discriminator` and `path` from the same `def.discriminator` at `schemas.js:1187` and `:1190`, not `:1189`/`:1191`. The cited fact was right, the line numbers were not. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CZY49skxUBYyJcdnTcYPrE --------- Co-authored-by: objectstack-ai <sales@objectstack.ai> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1 parent 1570eac commit 67749c7

9 files changed

Lines changed: 536 additions & 67 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
---
2+
'@object-ui/types': minor
3+
'@object-ui/cli': minor
4+
---
5+
6+
Discriminate `AnyComponentSchema` on `type` (objectui#8498).
7+
8+
The union was flat, so a refusal carried EVERY arm's issue list, and Zod's
9+
`$ZodError` initializer stringifies that whole tree into `.message` eagerly — in the
10+
constructor, not behind a getter. The cost was paid whether or not anyone read the
11+
message, and it compounded per level of nesting: measured on zod 4.4.3, a root
12+
refusal cost 14,624 chars, growing until `RangeError: Invalid string length`, thrown
13+
out of `safeValidateSchema` — documented as validating "without throwing errors".
14+
Discriminated, the same document costs 164. `ObjectQLComponentSchema` and
15+
`CRUDComponentSchema` follow for the same reason: zod refuses a plain `z.union` as a
16+
discriminated member.
17+
18+
**No document changes verdict.** The 13 arms declare 107 `type` literals with zero
19+
collisions, so the arm a literal selects was already the only arm that could accept
20+
it; across 440 example documents, flat and discriminated agree on every one.
21+
22+
**What moves is diagnostics.** A refused document whose `type` selects an arm now
23+
reports that arm's issues as top-level issues at absolute paths, rather than one
24+
`invalid_union` at the root with them nested inside; a `type` no arm claims is
25+
reported at `type` rather than at the root. `objectui validate` prints the same
26+
2026-09-02 ruling output — the selected arm alone, or a note plus a capped candidate
27+
list — read off the new issue shape.

‎packages/cli/src/__tests__/validate-root-path-line.test.ts‎

Lines changed: 53 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,7 @@
1919
* in precisely the case a reader most needs oriented.
2020
*
2121
* That case is the common one, not an edge: `safeValidateSchema` runs
22-
* `AnyComponentSchema`, a `z.union` over every component arm, so any document
23-
* matching no arm yields ONE top-level issue — `invalid_union` · `Invalid
24-
* input` · `path: []`. Measured on the parent commit of this file, a menu
22+
* `AnyComponentSchema`. Measured on the parent commit of this file, a menu
2523
* carrying the retired `{ type: 'separator' }` divider spelling printed:
2624
*
2725
* 1. Invalid input
@@ -30,6 +28,23 @@
3028
* — a bare verdict on a whole document, with nothing saying which node had
3129
* been judged.
3230
*
31+
* ⚠️ WHERE THE ROOT ISSUE COMES FROM MOVED (objectui#8498). This file used to
32+
* say "`AnyComponentSchema` is a `z.union`, so any document matching no arm
33+
* yields ONE top-level issue at `path: []`". That is now false in BOTH halves,
34+
* and the cases below are restated rather than patched:
35+
*
36+
* - the union discriminates on `type`, so a document whose `type` matches
37+
* nothing is judged AT THE DISCRIMINATOR — `invalid_union` at `['type']`,
38+
* printed as `Path: type`, which names the key that actually failed;
39+
* - a document whose `type` DOES select an arm no longer produces a union
40+
* issue at all: the arm's own issues are the top-level ones, already at
41+
* absolute paths.
42+
*
43+
* So the root-path line is now produced by documents that are not component
44+
* objects at all (a bare scalar), and that is the case pinned first below. The
45+
* non-root control is untouched and still load-bearing: a repair that printed
46+
* `(root)` for everything would still be caught by it.
47+
*
3348
* ⚠️ These cases are written against BOTH sides of the guard on purpose. A fix
3449
* that printed `(root)` unconditionally would satisfy a root-only test while
3550
* destroying the real paths authors depend on, so the non-root control below
@@ -65,9 +80,16 @@ const MENU_WITH_RETIRED_DIVIDER = {
6580
items: [{ label: 'New Tab', type: 'separator' }],
6681
};
6782

68-
/** A document from an entirely foreign vocabulary — the other root producer. */
83+
/** A document from an entirely foreign vocabulary — judged at `type`. */
6984
const FOREIGN_DOCUMENT = { type: 'module', main: './index.js' };
7085

86+
/**
87+
* Not a component object at all. `AnyComponentSchema` cannot even look for a
88+
* discriminator here, so the verdict is about the whole document and its path
89+
* is genuinely `[]` — the shape this file exists to keep visible.
90+
*/
91+
const SCALAR_DOCUMENT = 42;
92+
7193
/**
7294
* The non-root control, lifted from `validate-widget-namespace.test.ts` so both
7395
* files pin the same observed path for the same input.
@@ -121,8 +143,8 @@ afterEach(() => {
121143
});
122144

123145
describe('objectui validate — a root-level issue says it is at the root', () => {
124-
it('prints a Path line for the union failure that used to print none', async () => {
125-
await validate(writeSchema('menu.json', MENU_WITH_RETIRED_DIVIDER));
146+
it('prints a Path line for the root issue that used to print none', async () => {
147+
await validate(writeSchema('scalar.json', SCALAR_DOCUMENT));
126148

127149
expect(exitCodes).toEqual([1]);
128150
const text = printed();
@@ -131,14 +153,21 @@ describe('objectui validate — a root-level issue says it is at the root', () =
131153
// adjacent, with nothing between them.
132154
expect(text).toContain('1. Invalid input');
133155
expect(text).toContain('Path: (root)');
134-
expect(text).toContain('Code: invalid_union');
156+
expect(text).toContain('Code: invalid_type');
135157
});
136158

137-
it('does the same for a document from a foreign vocabulary', async () => {
159+
it('names the discriminator, not the root, when no arm claims the type', async () => {
160+
// ⚠️ Was `toContain('Path: (root)')` until objectui#8498. The verdict moved
161+
// to the key it is about, and the `not` half is what keeps this honest: a
162+
// printer that fell back to `(root)` for a union issue would still pass the
163+
// positive half alone.
138164
await validate(writeSchema('package.json', FOREIGN_DOCUMENT));
139165

140166
expect(exitCodes).toEqual([1]);
141-
expect(printed()).toContain('Path: (root)');
167+
const text = printed();
168+
expect(text).toContain('Path: type');
169+
expect(text).toContain('Code: invalid_union');
170+
expect(text).not.toContain('Path: (root)');
142171
});
143172

144173
it('gives EVERY reported issue a Path line, root or not', async () => {
@@ -214,15 +243,20 @@ describe('objectui validate — the arm-selection half, now that it is ruled', (
214243
// rides the per-arm issues, which is exactly why it never reached an author.
215244
expect(text).toContain('RETIRED (objectui#6523)');
216245
expect(text).toContain('Path: items → 0 → type');
217-
// Unchanged, and load-bearing: the top-level entry still carries the root
218-
// path line this file exists for.
219-
expect(text).toContain('Path: (root)');
220-
// Still exactly one NUMBERED issue. Arm entries are `1.1`-shaped, so a
221-
// reader (and this assertion) can still count the top-level failures — an
222-
// arm walk that emitted them as `2.`, `3.` … would have multiplied this.
223-
const numbered = printed()
224-
.split('\n')
225-
.filter((line) => /^\d+\. /.test(line.trim()));
226-
expect(numbered).toHaveLength(1);
246+
// ⚠️ Was `toContain('Path: (root)')` and `toHaveLength(1)` until
247+
// objectui#8498. With the root discriminated, `dropdown-menu` selects its
248+
// arm outright and THAT ARM'S issues are the top-level ones — this document
249+
// has two independent defects (the retired divider, and a missing required
250+
// `trigger`), so it prints two. What must not happen is the multiplication
251+
// this case was written against: entries contributed by arms the document's
252+
// `type` did NOT select.
253+
const numbered = text.split('\n').filter((line) => /^\d+\. /.test(line.trim()));
254+
expect(numbered).toHaveLength(2);
255+
expect(text).toContain('Path: trigger');
256+
// Every top-level entry belongs to `dropdown-menu`. An arm that merely
257+
// disagreed about `type` would show up as a discriminator complaint.
258+
expect(text).not.toContain('Invalid discriminator value');
259+
expect(text).not.toContain('expected "app"');
260+
expect(text).not.toContain('No arm accepts type');
227261
});
228262
});

‎packages/cli/src/__tests__/validate-union-arm-selection.test.ts‎

Lines changed: 92 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,13 @@ const UNTYPED_DOCUMENT = { items: [] };
6868
*/
6969
const OBJECT_GRID_MISSING_OBJECT_NAME = { type: 'object-grid' };
7070

71+
/**
72+
* `.data` here is `@objectstack/spec`'s `ViewDataSchema`, a
73+
* `z.discriminatedUnion('provider', …)` — the one reachable union in this tree
74+
* keyed on something other than `type`.
75+
*/
76+
const GRID_WITH_PROVIDERLESS_DATA = { type: 'object-grid', objectName: 'x', data: { type: 'rest' } };
77+
7178
/** A failure that is not a union at all — the control for "nothing changed". */
7279
const FORM_WITH_UNRESOLVABLE_WIDGET = {
7380
type: 'form',
@@ -137,10 +144,13 @@ describe('objectui validate — the arm the document selected', () => {
137144
// at `['type']`, relative to its own node; printing that raw would name the
138145
// document's own `type` key, which is not what failed.
139146
expect(text).toContain('Path: items → 0 → type');
140-
// The top-level entry is still exactly one numbered issue: the arm lines
141-
// are `1.1`-shaped and cannot be read as separate top-level entries.
147+
// ⚠️ `toHaveLength(1)` until objectui#8498: the root now discriminates, so
148+
// `dropdown-menu`'s OWN issues are the top-level entries — two of them for
149+
// this document, one per real defect (the retired divider at `items → 0`,
150+
// and the required `trigger` it never carried). `MenuItemSchema` is still
151+
// an undiscriminated union, so ITS arms are still `1.k` sub-entries.
142152
const numbered = text.split('\n').filter((line) => /^\d+\. /.test(line.trim()));
143-
expect(numbered).toHaveLength(1);
153+
expect(numbered).toHaveLength(2);
144154
expect(armEntries().length).toBeGreaterThan(0);
145155
});
146156

@@ -204,6 +214,23 @@ describe('objectui validate — when no arm accepts the type', () => {
204214
});
205215
});
206216

217+
describe('objectui validate — a union keyed on something other than `type`', () => {
218+
it('says nothing about arms rather than naming the wrong key', async () => {
219+
// Unguarded this read `data.type` ('rest'), called it unaccepted, and offered
220+
// `ViewDataSchema`'s four PROVIDER names as if they were component types — a
221+
// confident sentence in the ruling's own voice about the wrong key. Silence
222+
// is right: zod's own message already names `provider` and its literals.
223+
await validate(writeSchema('grid.json', GRID_WITH_PROVIDERLESS_DATA));
224+
225+
expect(exitCodes).toEqual([1]);
226+
const text = printed();
227+
expect(text).toContain('Path: data → provider');
228+
expect(text).not.toContain('No arm accepts type');
229+
expect(text).not.toContain('No `type` is declared');
230+
expect(armEntries()).toHaveLength(0);
231+
});
232+
});
233+
207234
describe('objectui validate — the non-union path is untouched', () => {
208235
it('adds no arm entries to an issue that is not a union', async () => {
209236
await validate(writeSchema('form.json', FORM_WITH_UNRESOLVABLE_WIDGET));
@@ -243,6 +270,68 @@ describe('union-arm-diagnostics — the selection itself', () => {
243270
expect(explainUnionIssue({ code: 'invalid_union', path: [], message: 'x' }, {})).toEqual([]);
244271
});
245272

273+
it('reads the ruling\'s note off a DISCRIMINATED union that matched nothing', () => {
274+
// Header fact 2 shape (c), the shape objectui#8498 made the common one:
275+
// no arms at all, the accepted literals in `options`, and the path ending
276+
// at the discriminator key — so the NODE is that path minus its last
277+
// segment, which is what the note must name.
278+
const lines = explainUnionIssue(
279+
{
280+
code: 'invalid_union',
281+
path: ['items', 0, 'type'],
282+
note: 'No matching discriminator',
283+
errors: [],
284+
options: ['dropdown-menu', 'context-menu', 'menubar', 'card', 'grid', 'div'],
285+
message: 'Invalid input',
286+
},
287+
{ items: [{ type: 'dropdwn-menu' }] },
288+
);
289+
expect(lines).toHaveLength(1);
290+
const [note] = lines;
291+
expect(note.kind).toBe('note');
292+
if (note.kind !== 'note') return;
293+
expect(note.path).toEqual(['items', 0]);
294+
expect(note.authoredType).toBe('dropdwn-menu');
295+
expect(note.candidates[0]).toBe('dropdown-menu');
296+
expect(note.candidates.length).toBeLessThanOrEqual(MAX_UNION_ARMS_REPORTED);
297+
expect(note.totalArmNames).toBe(6);
298+
});
299+
300+
it('declines a discriminator that is not `type`, on either field', () => {
301+
// Both conditions exercised, plus the cases that separate them. Zod fills
302+
// path and `discriminator` from one source, so only a hand-built issue can
303+
// disagree — and one that does must land on SILENT, never on a wrong note.
304+
const doc = { data: { type: 'rest' } };
305+
const note = (path: string[], discriminator?: string) => explainUnionIssue(
306+
{ code: 'invalid_union', note: 'No matching discriminator', errors: [], message: 'x',
307+
options: ['object', 'api', 'value', 'schema'], path, discriminator },
308+
doc,
309+
);
310+
expect(note(['data', 'provider'], 'provider')).toEqual([]);
311+
expect(note(['data', 'provider'])).toEqual([]);
312+
expect(note(['data', 'type'], 'provider')).toEqual([]);
313+
// ...and the `type`-keyed shape still routes, or the three above prove nothing.
314+
expect(note(['data', 'type'], 'type')).toHaveLength(1);
315+
});
316+
317+
it('does NOT read that note off a union that still reports arms', () => {
318+
// The guard that keeps shape (c) off the arm-walk path: an `invalid_union`
319+
// carrying real arms is still selected among, not summarised — otherwise a
320+
// stray `options` would silently replace a whole arm diagnosis with a hint.
321+
const lines = explainUnionIssue(
322+
{
323+
code: 'invalid_union',
324+
path: [],
325+
note: 'No matching discriminator',
326+
options: ['div', 'card'],
327+
errors: [[{ code: 'invalid_type', path: ['type'], message: 'arm one' }]],
328+
message: 'Invalid input',
329+
},
330+
{},
331+
);
332+
expect(lines.every((l) => l.kind === 'issue')).toBe(true);
333+
});
334+
246335
it('reports every arm, capped, when a union has no `type` discriminator', () => {
247336
// `MenuItemSchema`'s two arms both declare `type` as a retirement tombstone,
248337
// so neither names a literal and there is no discriminator to select on.

‎packages/cli/src/commands/validate.ts‎

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -108,22 +108,30 @@ export async function validate(schemaPath: string) {
108108
//
109109
// The guard here used to be `issue.path.length > 0`, which dropped the
110110
// line entirely for `path: []` — silent in exactly the case a reader
111-
// most needs oriented. That case is not rare: `safeValidateSchema` runs
112-
// `AnyComponentSchema`, which is a `z.union` of every component arm, so
113-
// ANY document matching no arm reports one top-level issue at the root
114-
// (`invalid_union` · `Invalid input` · `path: []`). Measured before this
115-
// change, a menu carrying the retired `{ type: 'separator' }` divider
116-
// spelling printed `1. Invalid input` and a Code line, and nothing said
117-
// whether the whole document or some node inside it had been judged.
111+
// most needs oriented. Measured before that change, a menu carrying the
112+
// retired `{ type: 'separator' }` divider spelling printed
113+
// `1. Invalid input` and a Code line, and nothing said whether the whole
114+
// document or some node inside it had been judged.
115+
//
116+
// ⚠️ WHERE A ROOT ISSUE COMES FROM MOVED (objectui#8498). This block read
117+
// "`AnyComponentSchema`, a `z.union` of every component arm, so ANY
118+
// document matching no arm reports one top-level issue at the root".
119+
// It discriminates on `type` now and both halves are false: a `type` that
120+
// SELECTS an arm yields that arm's own issues as the top-level entries,
121+
// already absolute, with no union issue at the root; a `type` that matches
122+
// nothing is judged at `['type']`. A root path now means a non-object.
118123
//
119124
// `(root)` is parenthesised so it cannot be read as a real key literally
120125
// named `root` — a genuine path to one would print as `root`.
121126
//
122127
// The ARM-SELECTION half of objectui#7004 landed on the 2026-09-02
123-
// maintainer ruling (option B) and is the block below the three fields:
124-
// when the top-level issue is a failing union, `explainUnionIssue` picks
125-
// the single arm the document's `type` selects and returns ITS issues,
126-
// with their paths rebased to absolute. Everything about WHICH arm lives
128+
// maintainer ruling (option B): print the issues of the arm the authored
129+
// `type` selects, and nothing from the others. Since objectui#8498 ZOD
130+
// does that selecting — a matched discriminator yields the arm's issues
131+
// directly, so there is no union issue here to expand. What
132+
// `explainUnionIssue` still answers is the other half of the ruling: the
133+
// capped candidate note when NO arm accepts, and the undiscriminated
134+
// unions still reached at nested slots. Everything about WHICH arm lives
127135
// in `../utils/union-arm-diagnostics.js`; this file only prints, so it
128136
// stays the repository's only zod-issue printer.
129137
result.error.issues.forEach((issue, index) => {

0 commit comments

Comments
 (0)