An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): finalize doc-authoring API (component/function/generic factories) (#4045)
EJ Hammondeb23da710a0b
diff --git a/.changeset/cli-create-doc-factory.md b/.changeset/cli-create-doc-factory.mdnew file mode 100644index 0000000000..53f69091bb--- /dev/null+++ b/.changeset/cli-create-doc-factory.md@@ -0,0 +1,6 @@+---+'@astryxdesign/cli': patch+---++[feat] Add the finalized doc-authoring API to `@astryxdesign/cli/doc`: `createComponentDoc`, `createFunctionDoc` (any function, including hooks), and `createDoc` (generic reference/topic docs). Each factory stamps a `type` discriminant and is validated at the load boundary against a matching per-kind schema. The legacy loose `export const docs = {...}` format keeps loading unchanged, and `.ts`-authored hook/function sources now derive their import path to a tree-shakeable subpath instead of the bare package root.+@ejhammonddiff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 5339aeffcf..5b036a5dda 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -47,6 +47,10 @@"types": "./src/types/integration.d.ts","import": "./src/integration.mjs"},+ "./doc": {+ "types": "./src/types/doc.d.ts",+ "import": "./src/doc.mjs"+ },"./template": {"types": "./src/types/template-api.d.ts","import": "./src/template.mjs"diff --git a/packages/cli/src/doc.mjs b/packages/cli/src/doc.mjsnew file mode 100644index 0000000000..0207917a12--- /dev/null+++ b/packages/cli/src/doc.mjs@@ -0,0 +1,271 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Public doc-authoring API.+ *+ * A doc describes a documentable unit of the design system so the CLI and docs+ * surfaces can list, search, and render it. There are three kinds, each a tiny+ * runtime identity helper that stamps a `type` discriminant (mirroring how+ * `createPageTemplate`/`createBlockTemplate` stamp `type`):+ *+ * - `createComponentDoc` -> `type: 'component'` — a component (or a family).+ * - `createFunctionDoc` -> `type: 'function'` — any function, including+ * hooks: an "inputs + outputs" surface (`params` + `returns`).+ * - `createDoc` -> `type: 'generic'` — reference/topic docs.+ *+ * Like `createConfig`/`createIntegration`/`createBlockTemplate`, these factories+ * do NOT validate. Validation happens at the LOAD boundary, where doc discovery+ * runs the loaded value through {@link ComponentDocSchema}. That schema handles+ * BOTH the new stamped formats and the legacy loose `export const docs = {...}`+ * shape, so existing docs keep loading unchanged (a later PR migrates them).+ */++import {z} from 'zod';++/**+ * A single documented prop. Mirrors `PropDoc` from+ * `@astryxdesign/core/docs-types`. Only `name`, `type`, and `description` are+ * required; everything else is optional. Extra fields (e.g. `slotElements`)+ * pass through so the schema does not have to track every evolution of the+ * rich playground/element surface.+ */+const PropSchema = z+ .object({+ name: z.string().min(1, 'prop name is required'),+ type: z.string().min(1, 'prop type is required'),+ description: z.string(),+ default: z.string().optional(),+ required: z.boolean().optional(),+ })+ .passthrough();++/** A single documented function/hook parameter (mirrors `HookParamDoc`). */+const ParamSchema = z+ .object({+ name: z.string().min(1, 'param name is required'),+ type: z.string().min(1, 'param type is required'),+ description: z.string(),+ default: z.string().optional(),+ required: z.boolean().optional(),+ })+ .passthrough();++/** A single documented function/hook return field (mirrors `HookReturnDoc`). */+const ReturnSchema = z+ .object({+ name: z.string().min(1, 'return name is required'),+ type: z.string().min(1, 'return type is required'),+ description: z.string(),+ })+ .passthrough();++/**+ * Fields shared by every doc kind. Deliberately permissive on the rich blobs+ * (usage/theming/playground) — those are large and still evolving, so they are+ * `z.unknown()` passthrough rather than enumerated.+ *+ * `group` vs `parent` are distinct concepts and intentionally separate fields:+ * - `group` is a FLAT sidebar bucket label. Many docs can share a group; it+ * is not an inheritance key.+ * - `parent` is a DIRECTED inheritance/composition pointer — a doc naming the+ * doc it belongs to (e.g. a sub-component naming its parent component). The+ * legacy `subComponentOf` field is a synonym; both map to the same concept.+ *+ * `relatedDocs` is a single flat curated cross-reference list. It replaces the+ * legacy split `relatedComponents` + `relatedHooks`; a downstream reader can+ * merge the legacy pair into it.+ */+const BaseDocFields = {+ /** Name of the documented unit, without any prefix. Required. */+ name: z.string().min(1, 'name is required'),+ /** Human-readable display name for gallery/sidebar. */+ displayName: z.string().optional(),+ /** One-line/short description. */+ description: z.string().optional(),+ /** Usage documentation (description, best practices, anatomy, slotElements). */+ usage: z.unknown().optional(),+ /** Flat sidebar grouping label (not an inheritance key). */+ group: z.string().optional(),+ /** Overview-page functional category. */+ category: z.string().optional(),+ /** CLI fuzzy-search keywords. */+ keywords: z.array(z.string()).optional(),+ /** Directed inheritance/composition pointer to the doc this belongs to. */+ parent: z.string().optional(),+ /** Flat curated cross-reference list of related doc names. */+ relatedDocs: z.array(z.string()).optional(),+ /** Hide the whole doc from human-facing UI (stays importable/discoverable). */+ hidden: z.boolean().optional(),+ /** Exclude from the categorized overview page (kept in sidebar/CLI). */+ isHiddenFromOverview: z.boolean().optional(),+};++/**+ * New-format schema for a stamped component doc (`type: 'component'`). The+ * top-level component keys are enumerated, but nested blobs stay loose so real+ * docs are not rejected. `.passthrough()` keeps unknown top-level fields+ * (translations, element descriptors, ...) flowing through.+ */+export const ComponentDocKindSchema = z+ .object({+ ...BaseDocFields,+ type: z.literal('component'),+ props: z.array(PropSchema),+ theming: z.unknown().optional(),+ playground: z.unknown().optional(),+ examples: z.array(z.unknown()).optional(),+ })+ .passthrough();++/**+ * New-format schema for a stamped function doc (`type: 'function'`). Covers any+ * function, including hooks: an inputs (`params`) + outputs (`returns`) surface.+ */+export const FunctionDocKindSchema = z+ .object({+ ...BaseDocFields,+ type: z.literal('function'),+ params: z.array(ParamSchema),+ returns: z.array(ReturnSchema),+ })+ .passthrough();++/**+ * New-format schema for a stamped generic doc (`type: 'generic'`) — reference+ * and topic docs. Just the shared base plus the discriminant.+ */+export const GenericDocKindSchema = z+ .object({+ ...BaseDocFields,+ type: z.literal('generic'),+ })+ .passthrough();++/**+ * The stamped-doc contract: one of the three new per-kind schemas, discriminated+ * by the injected `type`. Used when a loaded doc carries a `type` field.+ */+export const StampedDocSchema = z.discriminatedUnion('type', [+ ComponentDocKindSchema,+ FunctionDocKindSchema,+ GenericDocKindSchema,+]);++// ── Legacy loose format (unchanged, kept for back-compat) ─────────────+//+// The pre-factory docs are authored as a loose, untyped object with no `type`+// discriminant and validated by shape. Enumerated top-level fields observed+// across the existing loose docs:+// name, displayName, description, group, category, keywords,+// isHiddenFromOverview, hidden, hiddenComponents, usage, props, components,+// subComponentOf, playground, theming, examples, params, returns,+// relatedComponents, relatedHooks, relatedDocs, parent, importPath.++const LegacyBaseDocSchema = z.object({+ name: z.string().min(1, 'name is required'),+ displayName: z.string().optional(),+ description: z.string().optional(),+ group: z.string().optional(),+ category: z.string().optional(),+ keywords: z.array(z.string()).optional(),+ isHiddenFromOverview: z.boolean().optional(),+ hidden: z.boolean().optional(),+ hiddenComponents: z.array(z.string()).optional(),+ usage: z.unknown().optional(),+ playground: z.unknown().optional(),+ theming: z.unknown().optional(),+ examples: z.array(z.unknown()).optional(),+ showcase: z.unknown().optional(),+ // `parent` and legacy `subComponentOf` are synonyms; both accepted here so a+ // parent-based doc that omits a stamped `type` still validates.+ parent: z.string().optional(),+ relatedDocs: z.array(z.string()).optional(),+ relatedComponents: z.array(z.string()).optional(),+ relatedHooks: z.array(z.string()).optional(),+});++/** Legacy: directory exporting a single primary component (props inline). */+const LegacySingleComponentDocSchema = LegacyBaseDocSchema.extend({+ props: z.array(PropSchema),+}).passthrough();++/** Legacy: directory exporting multiple components (props on each entry). */+const LegacyMultiComponentDocSchema = LegacyBaseDocSchema.extend({+ components: z.array(z.unknown()),+}).passthrough();++/** Legacy: a standalone hook doc — inputs (`params`) + outputs (`returns`). */+const LegacyHookDocSchema = LegacyBaseDocSchema.extend({+ params: z.array(ParamSchema),+ returns: z.array(ReturnSchema),+}).passthrough();++/** Legacy: a sub-component doc parented via `subComponentOf`. */+const LegacySubComponentDocSchema = LegacyBaseDocSchema.extend({+ subComponentOf: z.string().min(1, 'subComponentOf is required'),+ description: z.string(),+ props: z.array(PropSchema),+}).passthrough();++/**+ * The permissive legacy union. `subComponentOf` is listed first so a doc that+ * carries both `subComponentOf` and `props` is validated as a sub-component+ * (the more specific shape); hook (`params`/`returns`) before multi/single.+ */+export const LegacyDocSchema = z.union([+ LegacySubComponentDocSchema,+ LegacyHookDocSchema,+ LegacyMultiComponentDocSchema,+ LegacySingleComponentDocSchema,+]);++/**+ * The LOAD-boundary contract for a doc. Handles BOTH formats:+ * - NEW: a stamped doc (`type: 'component' | 'function' | 'generic'`,+ * produced by the factories below) is validated against the matching+ * per-kind schema in {@link StampedDocSchema}.+ * - OLD: a loose, unstamped doc is validated against the permissive+ * {@link LegacyDocSchema} union (the three legacy shapes + standalone hook).+ *+ * Discovery validates the SHAPE, not "was it made by the factory". This PR does+ * NOT migrate real docs; a later PR does. Both formats normalize into the same+ * internal shape consumers already expect.+ */+export const ComponentDocSchema = z.union([StampedDocSchema, LegacyDocSchema]);++/**+ * Author a component doc. Stamp-only: returns the def with `type: 'component'`+ * injected. Validation happens at the load boundary.+ *+ * @template {import('./types/doc').AstryxComponentDocInput} T+ * @param {T} def+ * @returns {T & {type: 'component'}}+ */+export function createComponentDoc(def) {+ return /** @type {T & {type: 'component'}} */ ({...def, type: 'component'});+}++/**+ * Author a function doc (covers any function, including hooks). Stamp-only:+ * returns the def with `type: 'function'` injected. Validation happens at the+ * load boundary.+ *+ * @template {import('./types/doc').AstryxFunctionDocInput} T+ * @param {T} def+ * @returns {T & {type: 'function'}}+ */+export function createFunctionDoc(def) {+ return /** @type {T & {type: 'function'}} */ ({...def, type: 'function'});+}++/**+ * Author a generic reference/topic doc. Stamp-only: returns the def with+ * `type: 'generic'` injected. Validation happens at the load boundary.+ *+ * @template {import('./types/doc').AstryxGenericDocInput} T+ * @param {T} def+ * @returns {T & {type: 'generic'}}+ */+export function createDoc(def) {+ return /** @type {T & {type: 'generic'}} */ ({...def, type: 'generic'});+}diff --git a/packages/cli/src/doc.test.mjs b/packages/cli/src/doc.test.mjsnew file mode 100644index 0000000000..531c37ac12--- /dev/null+++ b/packages/cli/src/doc.test.mjs@@ -0,0 +1,383 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ createComponentDoc,+ createFunctionDoc,+ createDoc,+ ComponentDocSchema,+ ComponentDocKindSchema,+ FunctionDocKindSchema,+ GenericDocKindSchema,+} from './doc.mjs';+import {loadComponentDoc} from './lib/component-loader.mjs';++// The factories are stamp-only (like createConfig / createBlockTemplate): they+// inject a `type` discriminant and are otherwise identity, performing NO+// runtime validation. Validation happens at the LOAD boundary+// (loadComponentDoc runs the loaded value through ComponentDocSchema), so the+// rejection cases assert the schema rejects rather than the factory throwing.++const goodComponent = {+ name: 'Widget',+ displayName: 'Widget',+ description: 'A small widget.',+ props: [+ {name: 'label', type: 'string', description: 'Visible label.', required: true},+ {name: 'size', type: "'sm' | 'md'", description: 'Control size.', default: "'md'"},+ ],+};++const goodFunction = {+ name: 'useThing',+ displayName: 'useThing',+ description: 'A thing hook.',+ params: [{name: 'input', type: 'string', description: 'The input.', required: true}],+ returns: [{name: 'value', type: 'string', description: 'The result.'}],+};++const goodGeneric = {+ name: 'Theming',+ displayName: 'Theming',+ description: 'How theming works.',+};++describe('doc factories (stamp-only)', () => {+ it('createComponentDoc stamps type: component and is otherwise identity', () => {+ const doc = createComponentDoc(goodComponent);+ expect(doc.type).toBe('component');+ const {type, ...rest} = doc;+ expect(rest).toEqual(goodComponent);+ });++ it('createFunctionDoc stamps type: function and is otherwise identity', () => {+ const doc = createFunctionDoc(goodFunction);+ expect(doc.type).toBe('function');+ const {type, ...rest} = doc;+ expect(rest).toEqual(goodFunction);+ });++ it('createDoc stamps type: generic and is otherwise identity', () => {+ const doc = createDoc(goodGeneric);+ expect(doc.type).toBe('generic');+ const {type, ...rest} = doc;+ expect(rest).toEqual(goodGeneric);+ });++ it('does NOT validate — stamps invalid shapes unchanged', () => {+ const bogus = {group: 'Buttons'}; // no name+ expect(createComponentDoc(bogus)).toEqual({...bogus, type: 'component'});+ });+});++describe('per-kind schemas (new stamped format)', () => {+ it('ComponentDocKindSchema accepts a valid component doc', () => {+ expect(() =>+ ComponentDocKindSchema.parse(createComponentDoc(goodComponent)),+ ).not.toThrow();+ });++ it('ComponentDocKindSchema rejects a missing name with a readable message', () => {+ expect(() =>+ ComponentDocKindSchema.parse({type: 'component', name: '', props: []}),+ ).toThrow(/name is required/);+ });++ it('ComponentDocKindSchema rejects a prop missing its type with a readable message', () => {+ expect(() =>+ ComponentDocKindSchema.parse({+ type: 'component',+ name: 'Widget',+ props: [{name: 'label', description: 'no type'}],+ }),+ ).toThrow(/type/);+ });++ it('ComponentDocKindSchema surfaces the custom message for an empty prop type', () => {+ expect(() =>+ ComponentDocKindSchema.parse({+ type: 'component',+ name: 'Widget',+ props: [{name: 'label', type: '', description: 'empty type'}],+ }),+ ).toThrow(/prop type is required/);+ });++ it('FunctionDocKindSchema accepts a valid function doc', () => {+ expect(() =>+ FunctionDocKindSchema.parse(createFunctionDoc(goodFunction)),+ ).not.toThrow();+ });++ it('FunctionDocKindSchema rejects a function doc missing returns', () => {+ expect(() =>+ FunctionDocKindSchema.parse({+ type: 'function',+ name: 'useThing',+ params: [],+ }),+ ).toThrow();+ });++ it('GenericDocKindSchema accepts a valid generic doc', () => {+ expect(() =>+ GenericDocKindSchema.parse(createDoc(goodGeneric)),+ ).not.toThrow();+ });++ it('keeps nested rich blobs loose (usage/theming/playground passthrough)', () => {+ const doc = createComponentDoc({+ ...goodComponent,+ usage: {description: 'Use it.', anatomy: [{name: 'root'}]},+ theming: {targets: [{className: 'astryx-widget'}]},+ playground: {defaults: {label: 'Hi'}},+ examples: [{title: 'Basic', code: '<Widget />'}],+ });+ expect(() => ComponentDocKindSchema.parse(doc)).not.toThrow();+ });++ it('accepts parent + relatedDocs on the shared base', () => {+ const doc = createComponentDoc({+ ...goodComponent,+ parent: 'WidgetGroup',+ relatedDocs: ['Gauge', 'useThing'],+ group: 'Widgets',+ });+ const parsed = ComponentDocKindSchema.parse(doc);+ expect(parsed.parent).toBe('WidgetGroup');+ expect(parsed.relatedDocs).toEqual(['Gauge', 'useThing']);+ });+});++describe('ComponentDocSchema (load-boundary, both formats)', () => {+ it('accepts a stamped component doc via the per-kind schema', () => {+ expect(() =>+ ComponentDocSchema.parse(createComponentDoc(goodComponent)),+ ).not.toThrow();+ });++ it('accepts a stamped function doc', () => {+ expect(() =>+ ComponentDocSchema.parse(createFunctionDoc(goodFunction)),+ ).not.toThrow();+ });++ it('accepts a stamped generic doc', () => {+ expect(() =>+ ComponentDocSchema.parse(createDoc(goodGeneric)),+ ).not.toThrow();+ });++ it('accepts the OLD loose single-component shape (no type)', () => {+ expect(() => ComponentDocSchema.parse(goodComponent)).not.toThrow();+ });++ it('accepts the OLD loose multi-component shape (components[])', () => {+ const multi = {+ name: 'Table',+ displayName: 'Table',+ components: [{name: 'TableRow', displayName: 'Table Row', description: 'A row.'}],+ };+ expect(() => ComponentDocSchema.parse(multi)).not.toThrow();+ });++ it('accepts the OLD loose sub-component shape (subComponentOf)', () => {+ const sub = {+ name: 'GaugeItem',+ subComponentOf: 'Gauge',+ displayName: 'Gauge Item',+ description: 'A gauge item.',+ props: [{name: 'item', type: 'Item', description: 'The item.'}],+ };+ expect(() => ComponentDocSchema.parse(sub)).not.toThrow();+ });++ it('accepts the OLD loose standalone-hook shape (params + returns, no type)', () => {+ const hook = {+ name: 'useThing',+ displayName: 'useThing',+ params: [{name: 'q', type: 'string', description: 'query'}],+ returns: [{name: 'value', type: 'boolean', description: 'match'}],+ };+ expect(() => ComponentDocSchema.parse(hook)).not.toThrow();+ });++ it('accepts BOTH parent and legacy subComponentOf', () => {+ const withParent = {name: 'A', parent: 'B', props: []};+ const withSubComponentOf = {+ name: 'A',+ subComponentOf: 'B',+ description: 'sub',+ props: [],+ };+ expect(() => ComponentDocSchema.parse(withParent)).not.toThrow();+ expect(() => ComponentDocSchema.parse(withSubComponentOf)).not.toThrow();+ });++ it('accepts BOTH relatedDocs and legacy relatedComponents/relatedHooks', () => {+ const legacy = {+ name: 'useThing',+ displayName: 'useThing',+ params: [],+ returns: [],+ relatedComponents: ['Gauge'],+ relatedHooks: ['useOther'],+ };+ const modern = {...goodComponent, relatedDocs: ['Gauge', 'useThing']};+ expect(() => ComponentDocSchema.parse(legacy)).not.toThrow();+ expect(() =>+ ComponentDocSchema.parse(createComponentDoc(modern)),+ ).not.toThrow();+ });++ it('passes through loose extras (usage, playground, theming, importPath, showcase)', () => {+ const loose = {+ ...goodComponent,+ usage: {description: 'Use it wisely.'},+ playground: {defaults: {label: 'Hi'}},+ theming: {targets: [{className: 'astryx-widget'}]},+ keywords: ['widget', 'thing'],+ category: 'Content',+ isHiddenFromOverview: true,+ importPath: '@astryxdesign/core/Widget',+ showcase: 'WidgetHero',+ };+ const parsed = ComponentDocSchema.parse(loose);+ expect(parsed.importPath).toBe('@astryxdesign/core/Widget');+ expect(parsed.showcase).toBe('WidgetHero');+ });++ it('rejects a doc with no name', () => {+ expect(() => ComponentDocSchema.parse({props: []})).toThrow();+ });++ it('rejects an empty name with a readable message', () => {+ expect(() => ComponentDocSchema.parse({name: '', props: []})).toThrow(+ /name is required/,+ );+ });+});++describe('loadComponentDoc (load boundary)', () => {+ let tmpDir;++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-doc-test-'));+ });++ afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+ });++ const docModule = () => JSON.stringify(path.resolve(import.meta.dirname, 'doc.mjs'));++ it('loads a .doc.ts fixture via jiti (createComponentDoc default export)', async () => {+ const file = path.join(tmpDir, 'Widget.doc.ts');+ fs.writeFileSync(+ file,+ [+ `import {createComponentDoc} from ${docModule()};`,+ 'export default createComponentDoc({',+ " name: 'Widget',",+ " displayName: 'Widget',",+ " description: 'A small widget.',",+ ' props: [',+ " {name: 'label', type: 'string', description: 'Visible label.', required: true},",+ ' ],',+ '});',+ ].join('\n'),+ );+ const docs = await loadComponentDoc(file);+ expect(docs.type).toBe('component');+ expect(docs.name).toBe('Widget');+ expect(docs.props).toHaveLength(1);+ });++ it('loads a .doc.ts fixture via jiti (createFunctionDoc default export)', async () => {+ const file = path.join(tmpDir, 'useThing.doc.ts');+ fs.writeFileSync(+ file,+ [+ `import {createFunctionDoc} from ${docModule()};`,+ 'export default createFunctionDoc({',+ " name: 'useThing',",+ " displayName: 'useThing',",+ " params: [{name: 'input', type: 'string', description: 'The input.'}],",+ " returns: [{name: 'value', type: 'string', description: 'The result.'}],",+ '});',+ ].join('\n'),+ );+ const docs = await loadComponentDoc(file);+ expect(docs.type).toBe('function');+ expect(docs.params).toHaveLength(1);+ expect(docs.returns).toHaveLength(1);+ });++ it('loads a .doc.ts fixture via jiti (createDoc generic default export)', async () => {+ const file = path.join(tmpDir, 'Theming.doc.ts');+ fs.writeFileSync(+ file,+ [+ `import {createDoc} from ${docModule()};`,+ 'export default createDoc({',+ " name: 'Theming',",+ " displayName: 'Theming',",+ " description: 'How theming works.',",+ '});',+ ].join('\n'),+ );+ const docs = await loadComponentDoc(file);+ expect(docs.type).toBe('generic');+ expect(docs.name).toBe('Theming');+ });++ it('REGRESSION: loads the OLD loose `export const docs = {}` format', async () => {+ const file = path.join(tmpDir, 'Legacy.doc.mjs');+ fs.writeFileSync(+ file,+ [+ 'export const docs = {',+ " name: 'Legacy',",+ " displayName: 'Legacy',",+ " description: 'A loose named-export doc.',",+ " relatedComponents: ['Gauge'],",+ " relatedHooks: ['useThing'],",+ " importPath: '@astryxdesign/core/Legacy',",+ " props: [{name: 'value', type: 'string', description: 'A value.'}],",+ '};',+ ].join('\n'),+ );+ const docs = await loadComponentDoc(file);+ expect(docs.name).toBe('Legacy');+ expect(docs.props[0].name).toBe('value');+ expect(docs.relatedComponents).toEqual(['Gauge']);+ expect(docs.importPath).toBe('@astryxdesign/core/Legacy');+ });++ it('REGRESSION: loads the OLD loose standalone-hook `docs` format', async () => {+ const file = path.join(tmpDir, 'useLegacy.doc.mjs');+ fs.writeFileSync(+ file,+ [+ 'export const docs = {',+ " name: 'useLegacy',",+ " displayName: 'useLegacy',",+ " params: [{name: 'q', type: 'string', description: 'query'}],",+ " returns: [{name: 'value', type: 'boolean', description: 'match'}],",+ " relatedHooks: ['useThing'],",+ '};',+ ].join('\n'),+ );+ const docs = await loadComponentDoc(file);+ expect(docs.name).toBe('useLegacy');+ expect(docs.returns[0].name).toBe('value');+ });++ it('throws a readable error for an invalid doc', async () => {+ const file = path.join(tmpDir, 'Bad.doc.mjs');+ fs.writeFileSync(file, 'export default {group: "Buttons"};\n');+ await expect(loadComponentDoc(file)).rejects.toThrow(/is invalid|name/);+ });+});diff --git a/packages/cli/src/lib/component-discovery.importpath.test.mjs b/packages/cli/src/lib/component-discovery.importpath.test.mjsnew file mode 100644index 0000000000..e78b3ce7e3--- /dev/null+++ b/packages/cli/src/lib/component-discovery.importpath.test.mjs@@ -0,0 +1,59 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Verifies that `.ts`-authored sources (hooks and other functions) are+ * found by `findComponentSource`, so `resolveImportPath` derives a+ * tree-shakeable subpath instead of falling back to the bare package root.+ *+ * Runs against the real packages/core source, not mocks.+ */++import {describe, it, expect} from 'vitest';+import {+ findComponentSource,+ resolveImportPath,+} from './component-discovery.mjs';+import {findCoreDir} from '../utils/paths.mjs';++describe('findComponentSource resolves .ts-authored sources', () => {+ const coreDir = findCoreDir();++ it('finds a hook authored as a .ts file (not just .tsx)', () => {+ const src = findComponentSource(coreDir, 'useMediaQuery');+ expect(src).toBeTruthy();+ expect(src.endsWith('useMediaQuery.ts')).toBe(true);+ });++ it('still finds a component authored as .tsx', () => {+ const src = findComponentSource(coreDir, 'Button');+ expect(src).toBeTruthy();+ expect(src.endsWith('.tsx')).toBe(true);+ });+});++describe('resolveImportPath reproduces authored hook importPaths', () => {+ const coreDir = findCoreDir();++ // Representative sample of core hooks whose sources are `.ts` files. Before+ // the `.ts` fix these fell back to bare `@astryxdesign/core`; the derived+ // subpath must now match the value each hook's doc currently authors.+ const cases = [+ ['useMediaQuery', '@astryxdesign/core/hooks'],+ ['useResizable', '@astryxdesign/core/Resizable'],+ ['useTheme', '@astryxdesign/core/theme'],+ ['useFocusTrap', '@astryxdesign/core/hooks'],+ ['useOverflow', '@astryxdesign/core/hooks'],+ ];++ for (const [name, expected] of cases) {+ it(`${name} derives ${expected}`, () => {+ expect(resolveImportPath(coreDir, name)).toBe(expected);+ });+ }++ it('never falls back to the bare package root for a .ts hook', () => {+ for (const [name] of cases) {+ expect(resolveImportPath(coreDir, name)).not.toBe('@astryxdesign/core');+ }+ });+});diff --git a/packages/cli/src/lib/component-discovery.mjs b/packages/cli/src/lib/component-discovery.mjsindex f3cf425f8d..019172294d 100644--- a/packages/cli/src/lib/component-discovery.mjs+++ b/packages/cli/src/lib/component-discovery.mjs@@ -273,14 +273,24 @@ export function findComponentReadme(coreDir, name) {* For "Button" finds src/Button/XDSButton.tsx* For "Layout" finds src/Layout/XDSLayout/XDSLayout.tsx* For "Card" finds src/Layout/Container/XDSCard.tsx (deep search fallback)+ *+ * Hooks and other functions are authored as `.ts` (e.g. `useMediaQuery.ts`,+ * `useResizable.ts`), so `.ts` candidates are searched alongside `.tsx`. Without+ * this, deriving the import path for a `.ts`-authored function falls back to the+ * bare `@astryxdesign/core` root instead of its tree-shakeable subpath.*/export function findComponentSource(coreDir, name) {const srcDir = path.join(coreDir, 'src');- // Try the prefixed form (`XDSButton.tsx`) first since that is the current- // on-disk convention, then the bare form (`Button.tsx`) that the Astryx-prefix- // migration (P4) renames to. Listing the prefixed name first keeps behavior- // identical until files are actually renamed.- const candidateFiles = [`XDS${name}.tsx`, `${name}.tsx`];+ // Try the prefixed forms (`XDSButton.tsx`) first since that is the current+ // on-disk convention, then the bare forms (`Button.tsx`) that the Astryx-prefix+ // migration (P4) renames to. `.tsx` before `.ts` within each so a component's+ // `.tsx` wins over a same-named `.ts` helper; `.ts` covers hooks/functions.+ const candidateFiles = [+ `XDS${name}.tsx`,+ `${name}.tsx`,+ `XDS${name}.ts`,+ `${name}.ts`,+ ];function searchDir(dirPath) {if (!fs.existsSync(dirPath)) return null;diff --git a/packages/cli/src/lib/component-loader.mjs b/packages/cli/src/lib/component-loader.mjsindex 848a4cc7d0..032a1d3f23 100644--- a/packages/cli/src/lib/component-loader.mjs+++ b/packages/cli/src/lib/component-loader.mjs@@ -5,6 +5,59 @@*/import {pathToFileURL} from 'node:url';+import {importUserModule} from './module-loader.mjs';+import {formatZodError} from './config-schema.mjs';+import {ComponentDocSchema} from '../doc.mjs';++/**+ * Load a component doc through the shared load/validation boundary.+ *+ * This is the typed counterpart to {@link loadDocs}: it loads `.doc.ts` via+ * jiti (and `.doc.mjs`/`.doc.js` via native import) and validates against+ * {@link ComponentDocSchema}. That schema accepts BOTH formats, so this loader+ * reads whichever the file uses:+ * - NEW: the factory default export+ * (`export default createComponentDoc({...})` / `createFunctionDoc` /+ * `createDoc`) — the same single-export convention+ * {@link loadModuleWithSchema} uses for config/integration/template. These+ * carry a stamped `type` and validate against the matching per-kind schema.+ * - OLD: the legacy loose `export const docs = {...}` (no `type`), validated+ * against the permissive legacy union.+ * The default export wins when both are present. Throws a readable+ * `formatZodError`-style message on failure. Translations (`docsZh`/+ * `docsDense`) are merged exactly as {@link loadDocs} does so callers see+ * identical output.+ *+ * @param {string} docPath absolute path to a `.doc.{ts,mjs,js}` file+ * @param {{zh?: boolean, dense?: boolean, lang?: string}} [opts]+ * @returns {Promise<object>} the validated (and optionally translated) doc+ */+export async function loadComponentDoc(+ docPath,+ {zh = false, dense = false, lang} = {},+) {+ const mod = await importUserModule(docPath);+ const authored = mod?.default ?? mod?.docs;++ const result = ComponentDocSchema.safeParse(authored);+ if (!result.success) {+ throw new Error(formatZodError(docPath, result.error));+ }+ const docs = authored;++ const locale = lang || (dense ? 'dense' : zh ? 'zh' : null);+ if (!locale) return docs;++ const translationKey =+ locale === 'zh' ? 'docsZh' : locale === 'dense' ? 'docsDense' : null;+ if (!translationKey || !mod[translationKey]) return docs;++ const translation = mod[translationKey];+ if (translation.props || translation.components?.some(c => c.props)) {+ return translation;+ }+ return mergeTranslation(docs, translation);+}export function mergeTranslation(docs, translation) {if (!translation) return docs;diff --git a/packages/cli/src/types/doc.d.ts b/packages/cli/src/types/doc.d.tsnew file mode 100644index 0000000000..bcd3dbf949--- /dev/null+++ b/packages/cli/src/types/doc.d.ts@@ -0,0 +1,139 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Authoring surface for Astryx docs, exported from `@astryxdesign/cli/doc`.+ *+ * A doc lives in a `{Name}.doc.{ts,mjs,js}` file. Authors default-export a+ * factory result (`createComponentDoc`/`createFunctionDoc`/`createDoc`) —+ * preferred — or, for the current loose docs, name-export `docs`. The doc's+ * shape is validated at the load boundary against `ComponentDocSchema` (see+ * `doc.mjs`), which accepts BOTH the new stamped formats and the legacy loose+ * shape.+ *+ * The factories inject the `type` discriminant, so authors never write it. The+ * inputs are kept as broad records so authoring never fails to typecheck when a+ * richer core type surface is not resolvable; the precise per-field guidance+ * lives on the doc types in `@astryxdesign/core/docs-types`.+ */++/**+ * Fields shared by every doc kind (component + function + generic).+ *+ * `group` vs `parent` are distinct:+ * - `group` is a FLAT sidebar bucket label; many docs can share it and it is+ * NOT an inheritance key.+ * - `parent` is a DIRECTED inheritance/composition pointer — a doc naming the+ * doc it belongs to (e.g. a sub-component naming its parent component). The+ * legacy `subComponentOf` field is a synonym.+ *+ * `relatedDocs` is a single flat curated cross-reference list; it replaces the+ * legacy split `relatedComponents` + `relatedHooks`.+ */+export interface AstryxBaseDocInput {+ /** Name of the documented unit, without any prefix, PascalCase. Required. */+ name: string;+ /** Human-readable display name for gallery/sidebar. */+ displayName?: string;+ /** Short description. */+ description?: string;+ /** Usage documentation (description, best practices, anatomy, slotElements). */+ usage?: unknown;+ /** Flat sidebar grouping label (not an inheritance key). */+ group?: string;+ /** Overview-page functional category. */+ category?: string;+ /** CLI fuzzy-search keywords. */+ keywords?: string[];+ /** Directed inheritance/composition pointer to the doc this belongs to. */+ parent?: string;+ /** Flat curated cross-reference list of related doc names. */+ relatedDocs?: string[];+ /** Hide the whole doc from human-facing UI (stays importable/discoverable). */+ hidden?: boolean;+ /** Exclude from the categorized overview page (kept in sidebar/CLI). */+ isHiddenFromOverview?: boolean;+ /** Any additional fields the rich doc surface carries. */+ [key: string]: unknown;+}++/** A single documented prop (mirrors `PropDoc` from core docs-types). */+export interface AstryxPropInput {+ name: string;+ type: string;+ description: string;+ default?: string;+ required?: boolean;+ [key: string]: unknown;+}++/** A single documented param (mirrors `HookParamDoc`). */+export interface AstryxParamInput {+ name: string;+ type: string;+ description: string;+ default?: string;+ required?: boolean;+ [key: string]: unknown;+}++/** A single documented return field (mirrors `HookReturnDoc`). */+export interface AstryxReturnInput {+ name: string;+ type: string;+ description: string;+ [key: string]: unknown;+}++/**+ * Input accepted by {@link createComponentDoc}. A component (or a family). The+ * `type` discriminant is injected by the factory. `anatomy`/`slotElements` live+ * inside `usage`; `importPath` is DERIVED (never authored).+ */+export interface AstryxComponentDocInput extends AstryxBaseDocInput {+ /** All public props for the component. */+ props: AstryxPropInput[];+ /** Theming/selector-surface metadata. */+ theming?: unknown;+ /** Interactive-preview playground configuration. */+ playground?: unknown;+ /** Short code examples rendered after the props table. */+ examples?: unknown[];+}++/**+ * Input accepted by {@link createFunctionDoc}. Covers any function, including+ * hooks: an inputs (`params`) + outputs (`returns`) surface. The `type`+ * discriminant is injected by the factory; `importPath` is DERIVED.+ */+export interface AstryxFunctionDocInput extends AstryxBaseDocInput {+ /** Function/hook parameters or options-object fields. */+ params: AstryxParamInput[];+ /** Return value documentation. One entry per field (or a single primitive). */+ returns: AstryxReturnInput[];+}++/**+ * Input accepted by {@link createDoc}. A generic reference/topic doc — just the+ * shared base. The `type` discriminant is injected by the factory.+ */+export type AstryxGenericDocInput = AstryxBaseDocInput;++/**+ * Back-compat alias. Previously `createDoc` accepted a broad component-doc+ * record; the union of the three input kinds preserves that permissiveness for+ * any code referring to the old name.+ */+export type AstryxComponentDoc =+ AstryxComponentDocInput | AstryxFunctionDocInput | AstryxGenericDocInput;++export declare function createComponentDoc<T extends AstryxComponentDocInput>(+ def: T,+): T & {type: 'component'};++export declare function createFunctionDoc<T extends AstryxFunctionDocInput>(+ def: T,+): T & {type: 'function'};++export declare function createDoc<T extends AstryxGenericDocInput>(+ def: T,+): T & {type: 'generic'};