@astryxdesign/cli 0.1.6-canary.e8d4c3f → 0.1.6-canary.eb23da7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,120 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- import {describe, it, expect} from 'vitest';
4
-
5
- async function applyTransform(source) {
6
- const {default: transform} = await import(
7
- '../migrate-table-tableprops-to-direct-props.mjs'
8
- );
9
- const jscodeshift = (await import('jscodeshift')).default;
10
- const j = jscodeshift.withParser('tsx');
11
- const api = {jscodeshift: j, stats: () => {}, report: () => {}};
12
- const file = {source, path: 'test.tsx'};
13
- const result = transform(file, api);
14
- return result ?? source;
15
- }
16
-
17
- const TODO = 'TODO(astryx): tableProps is deprecated';
18
-
19
- describe('migrate-table-tableprops-to-direct-props', () => {
20
- it('lifts className and style to sibling props', async () => {
21
- const input = `import {Table} from '@astryxdesign/core';
22
- const x = <Table tableProps={{className: 'striped', style: {width: 400}}} columns={cols} />;`;
23
- const output = await applyTransform(input);
24
- expect(output).toContain(`className='striped'`);
25
- expect(output).toContain('style={{width: 400}}');
26
- expect(output).not.toContain('tableProps');
27
- });
28
-
29
- it(`lifts 'aria-label' and 'data-testid' string keys to hyphenated props`, async () => {
30
- const input = `import {Table} from '@astryxdesign/core/Table';
31
- const x = <Table tableProps={{'aria-label': 'Users', 'data-testid': 'users-table'}} />;`;
32
- const output = await applyTransform(input);
33
- expect(output).toContain(`aria-label='Users'`);
34
- expect(output).toContain(`data-testid='users-table'`);
35
- expect(output).not.toContain('tableProps');
36
- });
37
-
38
- it('lifts id and an onClick handler', async () => {
39
- const input = `import {Table} from '@xds/core';
40
- const x = <Table tableProps={{id: 'users', onClick: (e) => handle(e)}} />;`;
41
- const output = await applyTransform(input);
42
- expect(output).toContain(`id='users'`);
43
- expect(output).toContain('onClick={(e) => handle(e)}');
44
- expect(output).not.toContain('tableProps');
45
- });
46
-
47
- it('keeps colliding keys in a shrunken tableProps with a TODO comment', async () => {
48
- const input = `import {Table} from '@astryxdesign/core';
49
- const x = <Table className='mine' tableProps={{className: 'theirs', id: 'users'}} />;`;
50
- const output = await applyTransform(input);
51
- // Non-colliding key lifted
52
- expect(output).toContain(`id='users'`);
53
- // Existing sibling wins; colliding key stays inside tableProps
54
- expect(output).toContain(`className='mine'`);
55
- expect(output).toContain('tableProps={{');
56
- expect(output).toContain(`className: 'theirs'`);
57
- expect(output).not.toContain('id: ');
58
- expect(output).toContain(TODO);
59
- });
60
-
61
- it('leaves a dynamic tableProps={identifier} untouched with a TODO comment', async () => {
62
- const input = `import {Table} from '@astryxdesign/core';
63
- const x = <Table tableProps={props} />;`;
64
- const output = await applyTransform(input);
65
- expect(output).toContain('tableProps={props}');
66
- expect(output).toContain(TODO);
67
- });
68
-
69
- it('leaves an object containing a spread untouched with a TODO comment (no partial lift)', async () => {
70
- const input = `import {Table} from '@astryxdesign/core';
71
- const x = <Table tableProps={{className: 'x', ...rest}} />;`;
72
- const output = await applyTransform(input);
73
- expect(output).toContain(`tableProps={{className: 'x', ...rest}}`);
74
- expect(output).not.toContain(`<Table className=`);
75
- expect(output).toContain(TODO);
76
- });
77
-
78
- it('transforms aliased Table imports', async () => {
79
- const input = `import {Table as DataTable} from '@astryxdesign/core';
80
- const x = <DataTable tableProps={{className: 'x'}} />;`;
81
- const output = await applyTransform(input);
82
- expect(output).toContain(`<DataTable className='x' />`);
83
- expect(output).not.toContain('tableProps');
84
- });
85
-
86
- it('does not touch other components with a tableProps attribute', async () => {
87
- const input = `import {Table} from '@astryxdesign/core';
88
- const a = <Table tableProps={{id: 'users'}} />;
89
- const b = <OtherComponent tableProps={{className: 'x'}} />;`;
90
- const output = await applyTransform(input);
91
- expect(output).toContain(`<Table id='users' />`);
92
- expect(output).toContain(`<OtherComponent tableProps={{className: 'x'}} />`);
93
- });
94
-
95
- it('returns undefined for files without a Table import', async () => {
96
- const {default: transform} = await import(
97
- '../migrate-table-tableprops-to-direct-props.mjs'
98
- );
99
- const jscodeshift = (await import('jscodeshift')).default;
100
- const j = jscodeshift.withParser('tsx');
101
- const api = {jscodeshift: j, stats: () => {}, report: () => {}};
102
- const source = `import {Grid} from '@astryxdesign/core';
103
- const x = <Table tableProps={{className: 'x'}} />;`;
104
- const result = transform({source, path: 'test.tsx'}, api);
105
- expect(result).toBeUndefined();
106
- });
107
-
108
- it('returns undefined for already-migrated files (no tableProps)', async () => {
109
- const {default: transform} = await import(
110
- '../migrate-table-tableprops-to-direct-props.mjs'
111
- );
112
- const jscodeshift = (await import('jscodeshift')).default;
113
- const j = jscodeshift.withParser('tsx');
114
- const api = {jscodeshift: j, stats: () => {}, report: () => {}};
115
- const source = `import {Table} from '@astryxdesign/core';
116
- const x = <Table className='x' />;`;
117
- const result = transform({source, path: 'test.tsx'}, api);
118
- expect(result).toBeUndefined();
119
- });
120
- });
@@ -1,19 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- /**
4
- * @file v0.1.7 transform manifest
5
- *
6
- * Lists all codemods for the v0.1.7 release in the order they should run.
7
- */
8
-
9
- import migrateTableTablePropsToDirectProps, {
10
- meta as migrateTableTablePropsToDirectPropsMeta,
11
- } from './migrate-table-tableprops-to-direct-props.mjs';
12
-
13
- export default [
14
- {
15
- name: 'migrate-table-tableprops-to-direct-props',
16
- transform: migrateTableTablePropsToDirectProps,
17
- meta: migrateTableTablePropsToDirectPropsMeta,
18
- },
19
- ];
@@ -1,188 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- /**
4
- * @file Codemod: Migrate Table tableProps to direct root props
5
- * @see https://github.com/facebook/astryx/issues/3679
6
- *
7
- * `tableProps` (typed HTMLAttributes<HTMLTableElement>, nesting HTML
8
- * attributes one level deep) is deprecated. As of v0.1.7, <Table> honors
9
- * className/style/xstyle directly and spreads all other BaseProps
10
- * (id, aria-*, data-*, event handlers, ...) onto the root <table>, with
11
- * direct props taking precedence over tableProps.
12
- *
13
- * This codemod lifts object-literal `tableProps` keys into sibling JSX
14
- * props:
15
- *
16
- * - tableProps={{className: 'x', style: s}} → className="x" style={s}
17
- * - String-literal keys ('aria-label', 'data-testid') become hyphenated
18
- * JSX attributes.
19
- * - Keys that collide with an existing sibling attribute (or fail the
20
- * attribute-name guard) are kept inside a shrunken tableProps with a
21
- * trailing TODO comment for manual migration.
22
- * - Dynamic values (tableProps={props}, tableProps={fn()}, objects with
23
- * spreads/computed keys/methods) are left untouched with a TODO comment.
24
- *
25
- * Only elements whose name resolves to a `Table` import (alias-aware)
26
- * from an Astryx core source are rewritten. No import changes are needed.
27
- */
28
-
29
- export const meta = {
30
- title: 'Migrate Table tableProps to direct root props',
31
- description:
32
- 'Lifts object-literal `tableProps` keys on <Table> into sibling JSX props ' +
33
- '(className, style, id, aria-*, data-*, event handlers). Dynamic or ' +
34
- 'colliding entries are kept and annotated with a TODO comment.',
35
- pr: '#3679',
36
- };
37
-
38
- /** Import sources that provide the Astryx Table component. */
39
- const TABLE_IMPORT_SOURCES = new Set([
40
- '@astryxdesign/core',
41
- '@astryxdesign/core/Table',
42
- '@xds/core',
43
- '@xds/core/Table',
44
- ]);
45
-
46
- /** Keys must be valid JSX attribute names to be lifted. */
47
- const LIFTABLE_KEY_RE = /^[a-zA-Z_][a-zA-Z0-9_-]*$/;
48
-
49
- const TODO_COMMENT =
50
- ' TODO(astryx): tableProps is deprecated — merge these into direct props manually ';
51
-
52
- /**
53
- * Extract the static key name from an object property, or null when the
54
- * property is not a simple liftable entry (spread, computed key, method,
55
- * getter/setter, non-string literal key).
56
- */
57
- function getPropertyKeyName(prop) {
58
- if (prop.type !== 'ObjectProperty' && prop.type !== 'Property') return null;
59
- // espree-style Property nodes: skip methods and accessors
60
- if (prop.method || (prop.kind != null && prop.kind !== 'init')) return null;
61
- if (prop.computed) return null;
62
- const key = prop.key;
63
- if (key.type === 'Identifier') return key.name;
64
- if (
65
- (key.type === 'StringLiteral' || key.type === 'Literal') &&
66
- typeof key.value === 'string'
67
- ) {
68
- return key.value;
69
- }
70
- return null;
71
- }
72
-
73
- export default function transformer(file, api) {
74
- const j = api.jscodeshift;
75
- const root = j(file.source);
76
- let hasChanges = false;
77
-
78
- // --- 1. Track local names for the Table import (alias-aware) ---
79
- const tableLocals = new Set();
80
- root.find(j.ImportDeclaration).forEach((path) => {
81
- if (!TABLE_IMPORT_SOURCES.has(path.node.source.value)) return;
82
- for (const spec of path.node.specifiers ?? []) {
83
- if (spec.type === 'ImportSpecifier' && spec.imported.name === 'Table') {
84
- tableLocals.add(spec.local.name);
85
- }
86
- }
87
- });
88
-
89
- if (tableLocals.size === 0) return undefined;
90
-
91
- function attachTodo(attr) {
92
- if (!attr.comments) attr.comments = [];
93
- if (attr.comments.some((c) => c.value === TODO_COMMENT)) return;
94
- attr.comments.push(j.commentBlock(TODO_COMMENT, false, true));
95
- hasChanges = true;
96
- }
97
-
98
- function buildAttributeValue(valueNode) {
99
- if (
100
- valueNode.type === 'StringLiteral' ||
101
- (valueNode.type === 'Literal' && typeof valueNode.value === 'string')
102
- ) {
103
- return j.stringLiteral(valueNode.value);
104
- }
105
- return j.jsxExpressionContainer(valueNode);
106
- }
107
-
108
- // --- 2. Rewrite tableProps on tracked <Table> elements ---
109
- root.find(j.JSXOpeningElement).forEach((path) => {
110
- const name = path.node.name;
111
- const componentName = name.type === 'JSXIdentifier' ? name.name : null;
112
- if (!componentName || !tableLocals.has(componentName)) return;
113
-
114
- const attrs = path.node.attributes;
115
- const tablePropsAttr = attrs.find(
116
- (a) => a.type === 'JSXAttribute' && a.name?.name === 'tableProps',
117
- );
118
- if (!tablePropsAttr) return;
119
-
120
- const value = tablePropsAttr.value;
121
- const isObjectLiteral =
122
- value?.type === 'JSXExpressionContainer' &&
123
- value.expression.type === 'ObjectExpression';
124
-
125
- // Dynamic case: tableProps={identifier}, tableProps={fn()}, ... —
126
- // leave the attribute untouched and warn via a trailing comment
127
- // (api.report is a stub; comments are the only warning channel).
128
- if (!isObjectLiteral) {
129
- attachTodo(tablePropsAttr);
130
- return;
131
- }
132
-
133
- const obj = value.expression;
134
-
135
- // Objects containing spreads, computed keys, or methods are treated
136
- // as dynamic: no partial lift, just the TODO comment.
137
- const allSimple = obj.properties.every(
138
- (prop) => getPropertyKeyName(prop) !== null,
139
- );
140
- if (!allSimple) {
141
- attachTodo(tablePropsAttr);
142
- return;
143
- }
144
-
145
- const lifted = [];
146
- const kept = [];
147
- for (const prop of obj.properties) {
148
- const keyName = getPropertyKeyName(prop);
149
- const collidesWithSibling = attrs.some(
150
- (a) => a.type === 'JSXAttribute' && a.name?.name === keyName,
151
- );
152
- const collidesWithLifted = lifted.some(
153
- (a) => a.name.name === keyName,
154
- );
155
- if (
156
- !LIFTABLE_KEY_RE.test(keyName) ||
157
- collidesWithSibling ||
158
- collidesWithLifted
159
- ) {
160
- kept.push(prop);
161
- continue;
162
- }
163
- lifted.push(
164
- j.jsxAttribute(
165
- j.jsxIdentifier(keyName),
166
- buildAttributeValue(prop.value),
167
- ),
168
- );
169
- }
170
-
171
- const tablePropsIdx = attrs.indexOf(tablePropsAttr);
172
- if (kept.length === 0) {
173
- // All keys lifted — replace tableProps with the sibling attributes.
174
- attrs.splice(tablePropsIdx, 1, ...lifted);
175
- hasChanges = true;
176
- } else {
177
- // Some keys collide or fail the name guard — keep only those in a
178
- // shrunken tableProps and flag it for manual migration.
179
- attrs.splice(tablePropsIdx, 0, ...lifted);
180
- obj.properties = kept;
181
- attachTodo(tablePropsAttr);
182
- if (lifted.length > 0) hasChanges = true;
183
- }
184
- });
185
-
186
- if (!hasChanges) return undefined;
187
- return root.toSource({quote: 'single'});
188
- }
@@ -1,111 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- /**
4
- * @file Guards translated/compressed component docs against dropping props.
5
- * @input packages/core/src/{Name}/{Name}.doc.mjs — its `docs`, `docsZh`, `docsDense`.
6
- * @output Vitest failures naming every prop that exists in `docs` but vanishes
7
- * from a translated view.
8
- * @position Regression gate for component-loader.mjs.
9
- *
10
- * A `docsZh` that carries its own `props` array used to REPLACE the base doc
11
- * wholesale, so any prop the translation had not caught up with simply ceased
12
- * to exist: `astryx component Button --zh` silently omitted `isInterruptible`
13
- * and `isIconOnly`. A reader of the translated docs cannot discover a prop that
14
- * is not there, and CLAUDE.md tells every AI agent to read these docs.
15
- *
16
- * Translations are now an overlay: a prop the translation does not cover falls
17
- * back to its English entry rather than disappearing. Same principle as the
18
- * reference-doc overlays in #2182 — an overlay covering a subset must not
19
- * destroy what it does not cover.
20
- */
21
-
22
- import {describe, it, expect} from 'vitest';
23
- import * as fs from 'node:fs';
24
- import * as path from 'node:path';
25
- import {pathToFileURL} from 'node:url';
26
- import {loadDocs} from './component-loader.mjs';
27
-
28
- const CORE_SRC = path.join(
29
- import.meta.dirname,
30
- '..',
31
- '..',
32
- '..',
33
- 'core',
34
- 'src',
35
- );
36
-
37
- /** Component dirs that ship a doc file. */
38
- function componentDocs() {
39
- const out = [];
40
- for (const dir of fs.readdirSync(CORE_SRC)) {
41
- const docPath = path.join(CORE_SRC, dir, `${dir}.doc.mjs`);
42
- if (!fs.existsSync(docPath)) continue;
43
- if (!fs.readdirSync(path.join(CORE_SRC, dir)).includes(`${dir}.doc.mjs`)) {
44
- continue; // case-exact match only
45
- }
46
- out.push({name: dir, docPath});
47
- }
48
- return out;
49
- }
50
-
51
- /** Prop names on a doc, across single- and multi-component shapes. */
52
- function propNames(doc) {
53
- const names = new Set();
54
- for (const p of doc?.props ?? []) names.add(p.name);
55
- for (const c of doc?.components ?? []) {
56
- for (const p of c.props ?? []) names.add(`${c.name ?? '?'}.${p.name}`);
57
- }
58
- return names;
59
- }
60
-
61
- describe('translated component docs never drop a prop', () => {
62
- const comps = componentDocs();
63
-
64
- it('finds component docs to check', () => {
65
- expect(comps.length).toBeGreaterThan(0);
66
- });
67
-
68
- for (const {name, docPath} of comps) {
69
- for (const locale of ['zh', 'dense']) {
70
- it(`${name} --${locale}: documents every prop the English doc documents`, async () => {
71
- const mod = await import(pathToFileURL(docPath).href);
72
- const key = locale === 'zh' ? 'docsZh' : 'docsDense';
73
- if (!mod[key]) return; // no overlay, nothing to drift
74
-
75
- const english = propNames(mod.docs);
76
- const translated = propNames(
77
- await loadDocs(docPath, {[locale]: true}),
78
- );
79
-
80
- const dropped = [...english].filter(p => !translated.has(p));
81
- expect(
82
- dropped,
83
- `${name}.doc.mjs ${key} drops ${dropped.length} prop(s) from the ` +
84
- `--${locale} view: ${dropped.join(', ')}. A reader of the ` +
85
- `translated docs cannot discover a prop that is not there. An ` +
86
- `untranslated prop must fall back to its English entry, not vanish.`,
87
- ).toEqual([]);
88
- });
89
- }
90
- }
91
- });
92
-
93
- describe('the reported symptom', () => {
94
- it('astryx component Button --zh still lists isInterruptible and isIconOnly', async () => {
95
- const docPath = path.join(CORE_SRC, 'Button', 'Button.doc.mjs');
96
- const zh = await loadDocs(docPath, {zh: true});
97
- const names = propNames(zh);
98
- expect(names.has('isInterruptible')).toBe(true);
99
- expect(names.has('isIconOnly')).toBe(true);
100
- });
101
-
102
- it('keeps the translated descriptions it does have', async () => {
103
- const docPath = path.join(CORE_SRC, 'Button', 'Button.doc.mjs');
104
- const mod = await import(pathToFileURL(docPath).href);
105
- const zh = await loadDocs(docPath, {zh: true});
106
-
107
- const translated = mod.docsZh.props.find(p => p.name === 'variant');
108
- const merged = zh.props.find(p => p.name === 'variant');
109
- expect(merged.description).toBe(translated.description);
110
- });
111
- });
@@ -1,226 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- /**
4
- * @file Doc load-boundary schemas.
5
- *
6
- * The Zod schemas doc discovery runs a loaded doc value through (see
7
- * `loadComponentDoc`). {@link ComponentDocSchema} accepts BOTH the new stamped
8
- * formats and the legacy loose `export const docs = {...}` shape, so existing
9
- * docs keep loading unchanged. Kept free of any `@astryxdesign/core` import so
10
- * the hot path that loads them (doc discovery, `astryx init`) does not require
11
- * core's built `dist/`. The authoring factories live in
12
- * `@astryxdesign/core/authoring` and are re-exported from `../doc.mjs` for the
13
- * public `@astryxdesign/cli/doc` surface.
14
- */
15
-
16
- import {z} from 'zod';
17
-
18
- /**
19
- * A single documented prop. Mirrors `PropDoc` from
20
- * `@astryxdesign/core/docs-types`. Only `name`, `type`, and `description` are
21
- * required; everything else is optional. Extra fields (e.g. `slotElements`)
22
- * pass through so the schema does not have to track every evolution of the
23
- * rich playground/element surface.
24
- */
25
- const PropSchema = z
26
- .object({
27
- name: z.string().min(1, 'prop name is required'),
28
- type: z.string().min(1, 'prop type is required'),
29
- description: z.string(),
30
- default: z.string().optional(),
31
- required: z.boolean().optional(),
32
- })
33
- .passthrough();
34
-
35
- /** A single documented function/hook parameter (mirrors `HookParamDoc`). */
36
- const ParamSchema = z
37
- .object({
38
- name: z.string().min(1, 'param name is required'),
39
- type: z.string().min(1, 'param type is required'),
40
- description: z.string(),
41
- default: z.string().optional(),
42
- required: z.boolean().optional(),
43
- })
44
- .passthrough();
45
-
46
- /** A single documented function/hook return field (mirrors `HookReturnDoc`). */
47
- const ReturnSchema = z
48
- .object({
49
- name: z.string().min(1, 'return name is required'),
50
- type: z.string().min(1, 'return type is required'),
51
- description: z.string(),
52
- })
53
- .passthrough();
54
-
55
- /**
56
- * Fields shared by every doc kind. Deliberately permissive on the rich blobs
57
- * (usage/theming/playground) — those are large and still evolving, so they are
58
- * `z.unknown()` passthrough rather than enumerated.
59
- *
60
- * `group` vs `parent` are distinct concepts and intentionally separate fields:
61
- * - `group` is a FLAT sidebar bucket label. Many docs can share a group; it
62
- * is not an inheritance key.
63
- * - `parent` is a DIRECTED inheritance/composition pointer — a doc naming the
64
- * doc it belongs to (e.g. a sub-component naming its parent component). The
65
- * legacy `subComponentOf` field is a synonym; both map to the same concept.
66
- *
67
- * `relatedDocs` is a single flat curated cross-reference list. It replaces the
68
- * legacy split `relatedComponents` + `relatedHooks`; a downstream reader can
69
- * merge the legacy pair into it.
70
- */
71
- const BaseDocFields = {
72
- /** Name of the documented unit, without any prefix. Required. */
73
- name: z.string().min(1, 'name is required'),
74
- /** Human-readable display name for gallery/sidebar. */
75
- displayName: z.string().optional(),
76
- /** One-line/short description. */
77
- description: z.string().optional(),
78
- /** Usage documentation (description, best practices, anatomy, slotElements). */
79
- usage: z.unknown().optional(),
80
- /** Flat sidebar grouping label (not an inheritance key). */
81
- group: z.string().optional(),
82
- /** Overview-page functional category. */
83
- category: z.string().optional(),
84
- /** CLI fuzzy-search keywords. */
85
- keywords: z.array(z.string()).optional(),
86
- /** Directed inheritance/composition pointer to the doc this belongs to. */
87
- parent: z.string().optional(),
88
- /** Flat curated cross-reference list of related doc names. */
89
- relatedDocs: z.array(z.string()).optional(),
90
- /** Hide the whole doc from human-facing UI (stays importable/discoverable). */
91
- hidden: z.boolean().optional(),
92
- /** Exclude from the categorized overview page (kept in sidebar/CLI). */
93
- isHiddenFromOverview: z.boolean().optional(),
94
- };
95
-
96
- /**
97
- * New-format schema for a stamped component doc (`type: 'component'`). The
98
- * top-level component keys are enumerated, but nested blobs stay loose so real
99
- * docs are not rejected. `.passthrough()` keeps unknown top-level fields
100
- * (translations, element descriptors, ...) flowing through.
101
- */
102
- export const ComponentDocKindSchema = z
103
- .object({
104
- ...BaseDocFields,
105
- type: z.literal('component'),
106
- props: z.array(PropSchema),
107
- theming: z.unknown().optional(),
108
- playground: z.unknown().optional(),
109
- examples: z.array(z.unknown()).optional(),
110
- })
111
- .passthrough();
112
-
113
- /**
114
- * New-format schema for a stamped function doc (`type: 'function'`). Covers any
115
- * function, including hooks: an inputs (`params`) + outputs (`returns`) surface.
116
- */
117
- export const FunctionDocKindSchema = z
118
- .object({
119
- ...BaseDocFields,
120
- type: z.literal('function'),
121
- params: z.array(ParamSchema),
122
- returns: z.array(ReturnSchema),
123
- })
124
- .passthrough();
125
-
126
- /**
127
- * New-format schema for a stamped generic doc (`type: 'generic'`) — reference
128
- * and topic docs. Just the shared base plus the discriminant.
129
- */
130
- export const GenericDocKindSchema = z
131
- .object({
132
- ...BaseDocFields,
133
- type: z.literal('generic'),
134
- })
135
- .passthrough();
136
-
137
- /**
138
- * The stamped-doc contract: one of the three new per-kind schemas, discriminated
139
- * by the injected `type`. Used when a loaded doc carries a `type` field.
140
- */
141
- export const StampedDocSchema = z.discriminatedUnion('type', [
142
- ComponentDocKindSchema,
143
- FunctionDocKindSchema,
144
- GenericDocKindSchema,
145
- ]);
146
-
147
- // ── Legacy loose format (unchanged, kept for back-compat) ─────────────
148
- //
149
- // The pre-factory docs are authored as a loose, untyped object with no `type`
150
- // discriminant and validated by shape. Enumerated top-level fields observed
151
- // across the existing loose docs:
152
- // name, displayName, description, group, category, keywords,
153
- // isHiddenFromOverview, hidden, hiddenComponents, usage, props, components,
154
- // subComponentOf, playground, theming, examples, params, returns,
155
- // relatedComponents, relatedHooks, relatedDocs, parent, importPath.
156
-
157
- const LegacyBaseDocSchema = z.object({
158
- name: z.string().min(1, 'name is required'),
159
- displayName: z.string().optional(),
160
- description: z.string().optional(),
161
- group: z.string().optional(),
162
- category: z.string().optional(),
163
- keywords: z.array(z.string()).optional(),
164
- isHiddenFromOverview: z.boolean().optional(),
165
- hidden: z.boolean().optional(),
166
- hiddenComponents: z.array(z.string()).optional(),
167
- usage: z.unknown().optional(),
168
- playground: z.unknown().optional(),
169
- theming: z.unknown().optional(),
170
- examples: z.array(z.unknown()).optional(),
171
- showcase: z.unknown().optional(),
172
- // `parent` and legacy `subComponentOf` are synonyms; both accepted here so a
173
- // parent-based doc that omits a stamped `type` still validates.
174
- parent: z.string().optional(),
175
- relatedDocs: z.array(z.string()).optional(),
176
- relatedComponents: z.array(z.string()).optional(),
177
- relatedHooks: z.array(z.string()).optional(),
178
- });
179
-
180
- /** Legacy: directory exporting a single primary component (props inline). */
181
- const LegacySingleComponentDocSchema = LegacyBaseDocSchema.extend({
182
- props: z.array(PropSchema),
183
- }).passthrough();
184
-
185
- /** Legacy: directory exporting multiple components (props on each entry). */
186
- const LegacyMultiComponentDocSchema = LegacyBaseDocSchema.extend({
187
- components: z.array(z.unknown()),
188
- }).passthrough();
189
-
190
- /** Legacy: a standalone hook doc — inputs (`params`) + outputs (`returns`). */
191
- const LegacyHookDocSchema = LegacyBaseDocSchema.extend({
192
- params: z.array(ParamSchema),
193
- returns: z.array(ReturnSchema),
194
- }).passthrough();
195
-
196
- /** Legacy: a sub-component doc parented via `subComponentOf`. */
197
- const LegacySubComponentDocSchema = LegacyBaseDocSchema.extend({
198
- subComponentOf: z.string().min(1, 'subComponentOf is required'),
199
- description: z.string(),
200
- props: z.array(PropSchema),
201
- }).passthrough();
202
-
203
- /**
204
- * The permissive legacy union. `subComponentOf` is listed first so a doc that
205
- * carries both `subComponentOf` and `props` is validated as a sub-component
206
- * (the more specific shape); hook (`params`/`returns`) before multi/single.
207
- */
208
- export const LegacyDocSchema = z.union([
209
- LegacySubComponentDocSchema,
210
- LegacyHookDocSchema,
211
- LegacyMultiComponentDocSchema,
212
- LegacySingleComponentDocSchema,
213
- ]);
214
-
215
- /**
216
- * The LOAD-boundary contract for a doc. Handles BOTH formats:
217
- * - NEW: a stamped doc (`type: 'component' | 'function' | 'generic'`,
218
- * produced by the factories) is validated against the matching per-kind
219
- * schema in {@link StampedDocSchema}.
220
- * - OLD: a loose, unstamped doc is validated against the permissive
221
- * {@link LegacyDocSchema} union (the three legacy shapes + standalone hook).
222
- *
223
- * Discovery validates the SHAPE, not "was it made by the factory". Both formats
224
- * normalize into the same internal shape consumers already expect.
225
- */
226
- export const ComponentDocSchema = z.union([StampedDocSchema, LegacyDocSchema]);