Skip to content

Commit 32907ae

Browse files
fix(spec): check:variant-docs reads a z.enum discriminator arm's members into the union key (#29531)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ898KToLEMsyis22XxZA8ZTu)_ Fixes #29412 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:`check:variant-docs` 现在把 `z.enum` 判别臂的全部成员读进联合的台账键;唯一受影响的条目从 `kind:nav` 改键为 `kind:field|flow|nav`,并在 `api/metadata-api.mdx` 补一句点名 `field` / `flow` 两个 kind。 - 为什么改:旧的遍历只读字面量臂,枚举臂整个不进键,枚举增删成员时键不动,门禁就不会把作者送回文档。 - 风险与回滚:只动门禁脚本、它的台账和一句文档,不发布任何包;回滚即 revert 本 PR。 - 先看:`packages/spec/scripts/check-variant-docs.mts` 的 `armVariants()`;再看 `packages/spec/scripts/check-variant-docs.test.ts`;最后 `packages/spec/variant-docs.json` 的改键。 - 两分钟验证:`pnpm --filter @objectstack/spec check:variant-docs`,预期打印 24 个联合全部通过;`--list` 里 contributions 的键是 `kind:field|flow|nav`。 - 需要你做的:无,席位落地。 ## What changes - `packages/spec/scripts/check-variant-docs.mts`: a new exported `armVariants()` reads the values one arm's discriminator matches. A literal keeps them in the def's `values`; a zod 4 `z.enum` keeps its members in `entries`, and the walker never read that field, so an enum arm was left out of the key entirely. `armVariants()` now reads zod's own parse set (`_zod.values`, which drops a numeric TypeScript enum's reverse-mapping keys) and falls back to the entries' values. The per-union key building moved into an exported `unionKey()`. The sweep moved into `main()` and runs only when the file is invoked as a script, so the test can import the two helpers without sweeping `src/` or setting `OS_EAGER_SCHEMAS` in its worker. - `packages/spec/variant-docs.json`: re-keyed the one entry this moves, `kind:nav` to `kind:field|flow|nav` (GetPackageCustomizationsResponseSchema `contributions`). Its note is kept, with the sentence saying the walker cannot read the enum arm replaced by one saying it now does. - `content/docs/api/metadata-api.mdx` (bounded in-place fix, file surface amended in Claim amendment 6582783172): once re-keyed, the gate found that the bound doc never mentions `field`, and that `flow` passed only through an unrelated row (the `type` column at line 33). That is the doc owing a re-read, which this change is what surfaces. One sentence now names the kinds: "the fields (kind `field`) and flows (kind `flow`) other installed packages contribute to `hotcrm`'s objects". - `packages/spec/scripts/check-variant-docs.test.ts` (new): pins a fixture union with one enum arm and one literal arm, keyed on all three members; adding a member to the enum arm moves the key; a literal-only control keys as before; non-discriminated schemas answer null; an object-built enum reads its values, not its keys. ## Why A discriminated union's ledger key exists so that adding or dropping a variant changes the key and sends the author back to the bound doc. An enum arm's members were never in the key, so a `page` kind added to the `field` / `flow` enum would have left the key at `kind:nav` and the gate green. ## Tests - `check:variant-docs --list` on `origin/main` 94d3e25 vs this head: 24 discriminated unions both times; exactly one key differs (`kind:nav` became `kind:field|flow|nav`). Measured, not assumed: no other union in `src/` has an enum arm. - New `scripts/check-variant-docs.test.ts`: 7/7 pass. - `pnpm --filter @objectstack/spec test` (local project) at 314f4b3: Test Files 793 passed (793), Tests 23526 passed, 1 todo. - `pnpm --filter @objectstack/spec typecheck` at 314f4b3 (tsc, `check:scripts-typecheck`, `check:test-typecheck`): exit 0. - No ablation: the diff changes a gate script, which os-dev does not ablate. The before/after `--list` reading above is the evidence that the reading changed. ## Acceptance notes - No changeset, `skip-changeset`: `@objectstack/spec`'s `files[]` ships `dist`, `json-schema`, `src/**/*.zod.ts` and others, not `scripts/` or `variant-docs.json`; `content/docs/` is no package. - No `packages/spec/src/**/*.zod.ts` file and no strictness-ledger file is touched. - The match for a variant in a doc stays as loose as before; the gate still proves only that the page says the word. ## Verification <details><summary>dispatch-gates at 314f4b3: 86 derived, 86 run, all exit 0</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 86 families. 76 exited 0 on the first run; 10 exited 3 (PREREQUISITE NOT MET) on the fresh worktree, the one `check:docs` exit 1 being the missing `json-schema` tree, a prerequisite and not a finding. After `git fetch origin 621a487` and `turbo run build --filter='@objectstack/lint...' --filter=@objectstack/objectql --filter=@objectstack/formula --filter='@objectstack/client-react...' --filter=@objectstack/spec`, all ten re-ran to exit 0, `check:variant-docs` among them on the first run. Reconciliation: "dispatch-gates --ran: 86 derived famil(ies) accounted for — 86 run, 0 NOT-MEASURED". </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes (eslint on the two changed scripts files: exit 0; the repo-wide run is CI's). - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset (nothing publishes here). - [x] 6. `packages/spec` touched: no generated artifact moves (`check:docs` green). - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. Dispatched by `domain:spec#3 · os-warren · session_01JQwxbahe4v7GBD94QeSnir`; dev = card thread `session_01JQwxbZYuv4NM4LDCUNP3cK`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbZYuv4NM4LDCUNP3cK --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbZYuv4NM4LDCUNP3cK)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent f966f01 commit 32907ae

4 files changed

Lines changed: 215 additions & 107 deletions

File tree

‎content/docs/api/metadata-api.mdx‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,9 +109,10 @@ never overridden; it is copied under a new name. What the reads then serve is in
109109
[Metadata lifecycle](/docs/concepts/metadata-lifecycle#customizing-an-installed-package-the-paired-custom-override-adr-0146).
110110
`POST /packages/hotcrm/ensure-customization` creates the pair when absent (Studio calls
111111
it on the first change), and `GET /packages/hotcrm/customizations` lists its overrides,
112-
extensions and switched-off items in one read, beside `contributions`: the fields and flows
113-
other installed packages contribute to `hotcrm`, each entry naming its package. Its `nav` kind
114-
(a navigation item another package contributes to a `hotcrm` app) is declared and not yet served.
112+
extensions and switched-off items in one read, beside `contributions`: the fields (kind `field`)
113+
and flows (kind `flow`) other installed packages contribute to `hotcrm`'s objects, each entry
114+
naming its package. Its `nav` kind (a navigation item another package contributes to a
115+
`hotcrm` app) is declared and not yet served.
115116

116117
**Body**: `{ type: "object", name: "account", item: { ... } }`
117118
**Response**: `{ success: true }`

‎packages/spec/scripts/check-variant-docs.mts‎

Lines changed: 139 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,15 @@
2525
// — and from there to the doc. An unknown key (new union) and an orphaned key (deleted or
2626
// renamed union) both fail: no new undeclared surface, no stale claims.
2727
//
28+
// AN ARM'S VARIANTS ARE EVERY VALUE ITS DISCRIMINATOR MATCHES — a literal arm
29+
// (`kind: z.literal('nav')`) contributes its one value, an enum arm
30+
// (`kind: z.enum(['field', 'flow'])`) contributes every member. zod 4 keeps a literal's
31+
// values in the def's `values` and an enum's members in its `entries`; reading only the
32+
// first left an enum arm out of the key altogether, so a member added to or dropped from
33+
// that enum never moved the key and the gate never sent anyone back to the doc. The
34+
// reading lives in `armVariants()`, exported with `unionKey()` so the fixture test pins
35+
// both arm shapes without running the sweep.
36+
//
2837
// WHAT "MENTIONED" MEANS — and what this gate does NOT prove. A variant counts as
2938
// documented if the bound doc contains any of three forms:
3039
//
@@ -54,12 +63,6 @@ import fs from 'node:fs';
5463
import path from 'node:path';
5564
import url from 'node:url';
5665

57-
// Safe to set here despite ESM hoisting: the only static imports above are node
58-
// built-ins, and every schema module is pulled in via dynamic `await import()`
59-
// below — i.e. after this line runs. Keeps the script correct when invoked
60-
// directly (`tsx scripts/check-variant-docs.mts`), not just via the pnpm script.
61-
process.env.OS_EAGER_SCHEMAS ??= '1';
62-
6366
const HERE = path.dirname(url.fileURLToPath(import.meta.url));
6467
const SPEC = path.resolve(HERE, '..');
6568
const REPO = path.resolve(SPEC, '../..');
@@ -74,6 +77,40 @@ type Entry = {
7477

7578
const defOf = (s: any) => s?._zod?.def ?? s?._def;
7679

80+
/**
81+
* The discriminator values one arm matches, read off the arm's discriminator field.
82+
* A literal carries them in `values` (zod 3: one `value`); an enum carries its members
83+
* in `entries`, and zod's own parse set for it is `_zod.values`, which drops a numeric
84+
* TypeScript enum's reverse-mapping keys — so that set is read first.
85+
*/
86+
export function armVariants(field: any): string[] {
87+
const dd = defOf(field);
88+
if (!dd) return [];
89+
if (dd.entries && typeof dd.entries === 'object') {
90+
const parsed = field?._zod?.values;
91+
return [...(parsed instanceof Set ? parsed : Object.values(dd.entries))].map(String);
92+
}
93+
const vals = dd.values ?? (dd.value !== undefined ? [dd.value] : []);
94+
return [...vals].map(String);
95+
}
96+
97+
/**
98+
* A discriminated union's ledger key and the variants it was built from, or null when the
99+
* schema is not a discriminated union or none of its arms yields a value.
100+
*/
101+
export function unionKey(s: any): { disc: string; variants: string[]; key: string } | null {
102+
const d = defOf(s);
103+
if (!d || d.type !== 'union' || !d.discriminator) return null;
104+
const variants: string[] = [];
105+
for (const o of d.options ?? []) {
106+
const od = defOf(o);
107+
const shape = typeof od?.shape === 'function' ? od.shape() : od?.shape;
108+
variants.push(...armVariants(shape?.[d.discriminator]));
109+
}
110+
if (!variants.length) return null;
111+
return { disc: d.discriminator, variants, key: `${d.discriminator}:${[...variants].sort().join('|')}` };
112+
}
113+
77114
function zodFiles(dir: string, acc: string[] = []): string[] {
78115
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
79116
const p = path.join(dir, e.name);
@@ -92,20 +129,8 @@ function walk(s: any, p: string, depth: number): void {
92129
const d = defOf(s);
93130
if (!d) return;
94131

95-
if (d.type === 'union' && d.discriminator) {
96-
const variants: string[] = [];
97-
for (const o of d.options ?? []) {
98-
const od = defOf(o);
99-
const shape = typeof od?.shape === 'function' ? od.shape() : od?.shape;
100-
const dd = defOf(shape?.[d.discriminator]);
101-
const vals = dd?.values ?? (dd?.value !== undefined ? [dd.value] : []);
102-
for (const v of vals) variants.push(String(v));
103-
}
104-
if (variants.length) {
105-
const key = `${d.discriminator}:${[...variants].sort().join('|')}`;
106-
if (!found.has(key)) found.set(key, { disc: d.discriminator, variants, path: p });
107-
}
108-
}
132+
const u = unionKey(s);
133+
if (u && !found.has(u.key)) found.set(u.key, { disc: u.disc, variants: u.variants, path: p });
109134

110135
// Structural recursion. Wrapped in try/catch because a lazy getter can reference a
111136
// module that is still initialising mid-import; an unresolvable branch must not abort
@@ -126,99 +151,111 @@ function walk(s: any, p: string, depth: number): void {
126151
} catch { /* unresolvable branch — reached via another path if it matters */ }
127152
}
128153

129-
const files = zodFiles(SRC).sort();
130-
for (const f of files) {
131-
let mod: Record<string, unknown>;
132-
try { mod = await import(url.pathToFileURL(f).href); } catch { continue; }
133-
const rel = path.relative(SRC, f).replace(/\.zod\.ts$/, '');
134-
for (const [name, val] of Object.entries(mod)) {
135-
if (val && typeof val === 'object' && defOf(val)) walk(val, `${rel}#${name}`, 0);
154+
async function main(): Promise<void> {
155+
// Set before the first dynamic `import()` below, so every schema module loads eagerly.
156+
// It lives inside `main()` so that the fixture test, which imports this module for
157+
// `unionKey()`, neither sweeps `src/` nor leaves the variable set in its worker.
158+
process.env.OS_EAGER_SCHEMAS ??= '1';
159+
160+
const files = zodFiles(SRC).sort();
161+
for (const f of files) {
162+
let mod: Record<string, unknown>;
163+
try { mod = await import(url.pathToFileURL(f).href); } catch { continue; }
164+
const rel = path.relative(SRC, f).replace(/\.zod\.ts$/, '');
165+
for (const [name, val] of Object.entries(mod)) {
166+
if (val && typeof val === 'object' && defOf(val)) walk(val, `${rel}#${name}`, 0);
167+
}
136168
}
137-
}
138169

139-
if (LIST) {
140-
const rows = [...found.entries()].sort((a, b) => a[1].path.localeCompare(b[1].path));
141-
console.log(`${rows.length} discriminated union(s):\n`);
142-
for (const [key, v] of rows) console.log(`${v.path}\n key: ${key}\n ${v.variants.join(', ')}\n`);
143-
process.exit(0);
144-
}
170+
if (LIST) {
171+
const rows = [...found.entries()].sort((a, b) => a[1].path.localeCompare(b[1].path));
172+
console.log(`${rows.length} discriminated union(s):\n`);
173+
for (const [key, v] of rows) console.log(`${v.path}\n key: ${key}\n ${v.variants.join(', ')}\n`);
174+
process.exit(0);
175+
}
145176

146-
const ledger: { entries: Entry[] } = JSON.parse(fs.readFileSync(LEDGER, 'utf-8'));
147-
const byKey = new Map(ledger.entries.map((e) => [e.key, e]));
148-
const errors: string[] = [];
149-
150-
// Duplicate keys in the ledger would let one entry silently shadow another.
151-
const dupes = ledger.entries.map((e) => e.key).filter((k, i, a) => a.indexOf(k) !== i);
152-
for (const k of new Set(dupes)) errors.push(`duplicate ledger key: ${k}`);
153-
154-
// Ratchet A — every discovered union must be declared.
155-
for (const [key, v] of found) {
156-
if (byKey.has(key)) continue;
157-
errors.push(
158-
`undeclared discriminated union at ${v.path}\n` +
159-
` key: ${key}\n` +
160-
` variants (${v.variants.length}): ${v.variants.join(', ')}\n` +
161-
` → add it to packages/spec/variant-docs.json: bind \`docs\` (and make sure each variant\n` +
162-
` is mentioned there), or declare \`exempt\` with a reason.`,
163-
);
164-
}
177+
const ledger: { entries: Entry[] } = JSON.parse(fs.readFileSync(LEDGER, 'utf-8'));
178+
const byKey = new Map(ledger.entries.map((e) => [e.key, e]));
179+
const errors: string[] = [];
180+
181+
// Duplicate keys in the ledger would let one entry silently shadow another.
182+
const dupes = ledger.entries.map((e) => e.key).filter((k, i, a) => a.indexOf(k) !== i);
183+
for (const k of new Set(dupes)) errors.push(`duplicate ledger key: ${k}`);
165184

166-
// Ratchet B — every ledger entry must still correspond to a real union. A changed
167-
// variant set surfaces here as an orphan plus an undeclared entry above.
168-
for (const e of ledger.entries) {
169-
if (!found.has(e.key)) {
185+
// Ratchet A — every discovered union must be declared.
186+
for (const [key, v] of found) {
187+
if (byKey.has(key)) continue;
170188
errors.push(
171-
`orphaned ledger entry "${e.label}"\n` +
172-
` key: ${e.key}\n` +
173-
` → no union with this discriminator/variant set exists any more. If variants changed,\n` +
174-
` update the key AND re-check the bound doc; if the union is gone, delete the entry.`,
189+
`undeclared discriminated union at ${v.path}\n` +
190+
` key: ${key}\n` +
191+
` variants (${v.variants.length}): ${v.variants.join(', ')}\n` +
192+
` → add it to packages/spec/variant-docs.json: bind \`docs\` (and make sure each variant\n` +
193+
` is mentioned there), or declare \`exempt\` with a reason.`,
175194
);
176195
}
177-
}
178196

179-
// Coverage — every variant of a governed union must be mentioned in a bound doc.
180-
const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
181-
let governed = 0, exempt = 0;
182-
for (const e of ledger.entries) {
183-
const u = found.get(e.key);
184-
if (!u) continue;
185-
if (e.exempt) { exempt++; continue; }
186-
if (!e.docs?.length) {
187-
errors.push(`ledger entry "${e.label}" declares neither \`docs\` nor \`exempt\`.`);
188-
continue;
197+
// Ratchet B — every ledger entry must still correspond to a real union. A changed
198+
// variant set surfaces here as an orphan plus an undeclared entry above.
199+
for (const e of ledger.entries) {
200+
if (!found.has(e.key)) {
201+
errors.push(
202+
`orphaned ledger entry "${e.label}"\n` +
203+
` key: ${e.key}\n` +
204+
` → no union with this discriminator/variant set exists any more. If variants changed,\n` +
205+
` update the key AND re-check the bound doc; if the union is gone, delete the entry.`,
206+
);
207+
}
189208
}
190-
governed++;
191209

192-
const missingDocs = e.docs.filter((d) => !fs.existsSync(path.join(REPO, d)));
193-
if (missingDocs.length) {
194-
errors.push(`ledger entry "${e.label}" binds doc(s) that do not exist: ${missingDocs.join(', ')}`);
195-
continue;
210+
// Coverage — every variant of a governed union must be mentioned in a bound doc.
211+
const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
212+
let governed = 0, exempt = 0;
213+
for (const e of ledger.entries) {
214+
const u = found.get(e.key);
215+
if (!u) continue;
216+
if (e.exempt) { exempt++; continue; }
217+
if (!e.docs?.length) {
218+
errors.push(`ledger entry "${e.label}" declares neither \`docs\` nor \`exempt\`.`);
219+
continue;
220+
}
221+
governed++;
222+
223+
const missingDocs = e.docs.filter((d) => !fs.existsSync(path.join(REPO, d)));
224+
if (missingDocs.length) {
225+
errors.push(`ledger entry "${e.label}" binds doc(s) that do not exist: ${missingDocs.join(', ')}`);
226+
continue;
227+
}
228+
const blob = e.docs.map((d) => fs.readFileSync(path.join(REPO, d), 'utf-8')).join('\n');
229+
const undocumented = u.variants.filter((v) => {
230+
const anchored = new RegExp(`${esc(u.disc)}\\s*:\\s*['"\`]${esc(v)}['"\`]`);
231+
const token = new RegExp('`' + esc(v) + '`');
232+
// YAML mapping line: unquoted scalar, so it must be anchored to the whole
233+
// line (trailing `# comment` allowed) to stay as tight as the quoted form.
234+
const yaml = new RegExp(`^\\s*${esc(u.disc)}\\s*:\\s*${esc(v)}\\s*(#.*)?$`, 'm');
235+
return !anchored.test(blob) && !token.test(blob) && !yaml.test(blob);
236+
});
237+
if (undocumented.length) {
238+
errors.push(
239+
`"${e.label}" — ${undocumented.length} variant(s) the schema declares but the doc never mentions:\n` +
240+
` ${undocumented.join(', ')}\n` +
241+
` doc(s): ${e.docs.join(', ')}\n` +
242+
` → document them, or if they are genuinely not author-facing, re-classify the entry.`,
243+
);
244+
}
196245
}
197-
const blob = e.docs.map((d) => fs.readFileSync(path.join(REPO, d), 'utf-8')).join('\n');
198-
const undocumented = u.variants.filter((v) => {
199-
const anchored = new RegExp(`${esc(u.disc)}\\s*:\\s*['"\`]${esc(v)}['"\`]`);
200-
const token = new RegExp('`' + esc(v) + '`');
201-
// YAML mapping line: unquoted scalar, so it must be anchored to the whole
202-
// line (trailing `# comment` allowed) to stay as tight as the quoted form.
203-
const yaml = new RegExp(`^\\s*${esc(u.disc)}\\s*:\\s*${esc(v)}\\s*(#.*)?$`, 'm');
204-
return !anchored.test(blob) && !token.test(blob) && !yaml.test(blob);
205-
});
206-
if (undocumented.length) {
207-
errors.push(
208-
`"${e.label}" — ${undocumented.length} variant(s) the schema declares but the doc never mentions:\n` +
209-
` ${undocumented.join(', ')}\n` +
210-
` doc(s): ${e.docs.join(', ')}\n` +
211-
` → document them, or if they are genuinely not author-facing, re-classify the entry.`,
212-
);
246+
247+
if (errors.length) {
248+
console.error(`\n✗ variant/doc gate: ${errors.length} problem(s)\n`);
249+
for (const e of errors) console.error(` ${e}\n`);
250+
process.exit(1);
213251
}
252+
console.log(
253+
`✓ variant/doc gate: ${found.size} discriminated union(s) — ` +
254+
`${governed} governed (every variant mentioned in a bound doc), ${exempt} exempt.`,
255+
);
214256
}
215257

216-
if (errors.length) {
217-
console.error(`\n✗ variant/doc gate: ${errors.length} problem(s)\n`);
218-
for (const e of errors) console.error(` ${e}\n`);
219-
process.exit(1);
220-
}
221-
console.log(
222-
`✓ variant/doc gate: ${found.size} discriminated union(s) — ` +
223-
`${governed} governed (every variant mentioned in a bound doc), ${exempt} exempt.`,
224-
);
258+
// Run the sweep only when invoked as a script (`tsx scripts/check-variant-docs.mts`, or the
259+
// pnpm script); an import — the fixture test — gets the exports and nothing else.
260+
const invokedDirectly = process.argv[1] !== undefined && url.fileURLToPath(import.meta.url) === path.resolve(process.argv[1]);
261+
if (invokedDirectly) await main();
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The variant/doc gate's ledger key, pinned on fixture unions.
5+
*
6+
* The gate's end-to-end verdict runs as `check:variant-docs` against the real
7+
* schemas. What that run cannot show is whether the key still MOVES when an
8+
* arm's variants move: a walker that silently skipped one arm shape keys the
9+
* union on the arms it can read, stays green, and never sends anyone back to
10+
* the doc. A `z.enum` arm was that shape — its members sit in the def's
11+
* `entries`, not in `values` where a literal keeps its one value.
12+
*
13+
* So the assertions are about DISCRIMINATION: a union with one enum arm and one
14+
* literal arm keys on every member of both, and adding a member to the enum
15+
* arm gives a different key.
16+
*/
17+
18+
import { describe, expect, it } from 'vitest';
19+
import { z } from 'zod';
20+
import { armVariants, unionKey } from './check-variant-docs.mts';
21+
22+
const enumAndLiteral = (members: [string, ...string[]]) =>
23+
z.discriminatedUnion('kind', [
24+
z.object({ kind: z.enum(members), object: z.string() }),
25+
z.object({ kind: z.literal('nav'), app: z.string() }),
26+
]);
27+
28+
describe('check-variant-docs unionKey', () => {
29+
it('keys a union with an enum arm on every enum member plus the literal arm', () => {
30+
const u = unionKey(enumAndLiteral(['field', 'flow']));
31+
expect(u?.disc).toBe('kind');
32+
expect(u?.key).toBe('kind:field|flow|nav');
33+
expect([...(u?.variants ?? [])].sort()).toEqual(['field', 'flow', 'nav']);
34+
});
35+
36+
it('moves the key when the enum arm gains a member', () => {
37+
const before = unionKey(enumAndLiteral(['field', 'flow']))?.key;
38+
const after = unionKey(enumAndLiteral(['field', 'flow', 'page']))?.key;
39+
expect(after).toBe('kind:field|flow|nav|page');
40+
expect(after).not.toBe(before);
41+
});
42+
43+
it('keys a literal-only union as before (control)', () => {
44+
const u = unionKey(z.discriminatedUnion('type', [
45+
z.object({ type: z.literal('b') }),
46+
z.object({ type: z.literal('a') }),
47+
]));
48+
expect(u?.key).toBe('type:a|b');
49+
});
50+
51+
it('answers null for a schema that is not a discriminated union', () => {
52+
expect(unionKey(z.object({ kind: z.enum(['a', 'b']) }))).toBeNull();
53+
expect(unionKey(z.union([z.string(), z.number()]))).toBeNull();
54+
});
55+
});
56+
57+
describe('check-variant-docs armVariants', () => {
58+
it('reads an enum built from an object by its values, not its keys', () => {
59+
expect(armVariants(z.enum({ Field: 'field', Flow: 'flow' })).sort()).toEqual(['field', 'flow']);
60+
});
61+
62+
it('reads a literal arm by its value', () => {
63+
expect(armVariants(z.literal('nav'))).toEqual(['nav']);
64+
});
65+
66+
it('answers no values for a field that is neither a literal nor an enum', () => {
67+
expect(armVariants(z.string())).toEqual([]);
68+
expect(armVariants(undefined)).toEqual([]);
69+
});
70+
});

‎packages/spec/variant-docs.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,12 +196,12 @@
196196
"reason": "Wire response of GET /auth/me/permissions (#28508): the server answers the anonymous or the authenticated body from the session, and nobody writes either into metadata. content/docs/references/api/auth.mdx is generated from MePermissionsResponseSchema."
197197
},
198198
{
199-
"key": "kind:nav",
199+
"key": "kind:field|flow|nav",
200200
"label": "customizations read contribution entry",
201201
"docs": [
202202
"content/docs/api/metadata-api.mdx"
203203
],
204-
"note": "The per-kind entry of GET /packages/:id/customizations `contributions` (#27928, ruling 6566915346 letter E). Not authored (the server answers it), but GOVERNED rather than exempt, as the flow registration verdict is: Studio draws each kind differently, and api/metadata-api.mdx names the list and its `nav` kind. The key holds only `nav` because the `field` / `flow` arm discriminates by a `z.enum`, which this walker does not read as variants."
204+
"note": "The per-kind entry of GET /packages/:id/customizations `contributions` (#27928, ruling 6566915346 letter E). Not authored (the server answers it), but GOVERNED rather than exempt, as the flow registration verdict is: Studio draws each kind differently, and api/metadata-api.mdx names the list and its `nav` kind. The `field` / `flow` arm discriminates by a `z.enum`; the walker reads its members into the key, so adding or dropping a kind there moves the key and sends the author back to that doc."
205205
}
206206
]
207207
}

0 commit comments

Comments
 (0)