Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

Make every doc type's published type, load check, and authoring docs agree (#6492)

Joey89c4819a4996
diff --git a/.changeset/authoring-docs-match-types.md b/.changeset/authoring-docs-match-types.md
new file mode 100644
index 0000000000..bf441fcd57
--- /dev/null
+++ b/.changeset/authoring-docs-match-types.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] `astryx docs authoring` now matches the published authoring types field for field, and a test keeps it that way: every field is listed, with its real type and whether it is required. Three entries were wrong: a component doc's `usage` is optional on sub-component docs, a command option's `default` may also be a boolean or a list, and a codemod's `type` is `'code'` or `'config'`.
+
+@josephfarina
diff --git a/.changeset/authoring-types-nodenext.md b/.changeset/authoring-types-nodenext.md
new file mode 100644
index 0000000000..8b4aaf553d
--- /dev/null
+++ b/.changeset/authoring-types-nodenext.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] The published authoring types now type-check in projects that use `"moduleResolution": "nodenext"` or have no Node types installed. Relative imports inside them name their files, and `PostCodemodCommand`'s `env` no longer needs Node's types.
+
+@josephfarina
diff --git a/.changeset/doc-load-contract.md b/.changeset/doc-load-contract.md
new file mode 100644
index 0000000000..579ccf0173
--- /dev/null
+++ b/.changeset/doc-load-contract.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] `astryx docs authoring` now says where loading a doc is looser than its published type (stamped component and function docs, older generic docs, and templates), and which doc kinds accept fields they do not know. Nothing about how docs load has changed.
+
+@josephfarina
diff --git a/.changeset/docs-graph-status.md b/.changeset/docs-graph-status.md
new file mode 100644
index 0000000000..23ed8cfb7d
--- /dev/null
+++ b/.changeset/docs-graph-status.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx docs authoring` now says which docs-graph features are not built yet: the `placement`, `aliases` and `audience` fields, the workflow, collection and reference blocks, namespace docs, and the artifact, doc and instance identities. It had described them as working, but a topic that uses them fails to load. A namespace doc in an integration's docs directory now fails with a message that names it, instead of reporting missing topic fields.
+
+@josephfarina
diff --git a/.changeset/stamped-group-component-docs.md b/.changeset/stamped-group-component-docs.md
new file mode 100644
index 0000000000..83b3219a03
--- /dev/null
+++ b/.changeset/stamped-group-component-docs.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] A stamped component doc (`type: 'component'`) that documents several components with `components` now loads, as the published `ComponentDoc` type allows. It used to fail with "props: expected array". Each entry must name its component; an entry without a `name` fails at load instead of later in a reader.
+
+@josephfarina
diff --git a/.github/scripts/cli-api-types-verify.mjs b/.github/scripts/cli-api-types-verify.mjs
index 2a5a8e4790..e617dcaa21 100644
--- a/.github/scripts/cli-api-types-verify.mjs
+++ b/.github/scripts/cli-api-types-verify.mjs
@@ -92,6 +92,13 @@ if (!fs.existsSync(path.join(pkgDir, 'foundation', 'discovery', 'template-adapte
}
console.log('\u2713 tarball ships the generated foundation declarations');
fs.symlinkSync(CORE_DIR, path.join(nm, 'core'), 'dir');
+// The scratch area sits inside packages/cli, so without a package.json of its
+// own the consumer would resolve `@astryxdesign/cli` through package
+// self-reference to the workspace sources instead of the extracted tarball.
+fs.writeFileSync(
+ path.join(VERIFY_DIR, 'package.json'),
+ JSON.stringify({name: 'packed-cli-consumer', private: true, type: 'module'}),
+);
// 3. Type-check a representative consumer against the packed types.
const scenario = `
@@ -234,4 +241,72 @@ if (errors.length > 0) {
console.log(
'\u2713 packaged @astryxdesign/cli/api + /authoring type-check for a strict consumer',
);
+
+// 4. The authoring surface alone, as an integration package sees it: with
+// `nodenext` resolution (a relative import without its extension does not
+// resolve there) and with no Node types installed. The authoring declarations
+// must need nothing beyond what they ship.
+const authoringScenario = `
+import type {
+ AstryxConfig, AstryxIntegration, ComponentDoc, HookDoc, FunctionDoc,
+ ReferenceDoc, TemplateDoc, SchemaDoc, CommandDoc, EnumDoc, NamespaceDoc,
+} from '@astryxdesign/cli/authoring';
+import {parseDoc, parseConfig, parseIntegration} from '@astryxdesign/cli/authoring';
+import type {BlockTemplateDoc, UsageDoc} from '@astryxdesign/cli/doc';
+import type {PostCodemodCommand} from '@astryxdesign/cli/config';
+import type {AstryxIntegration as SubpathIntegration} from '@astryxdesign/cli/integration';
+import type {AstryxCodemod} from '@astryxdesign/cli/codemod';
+import type {DebugEvent} from '@astryxdesign/cli/debug';
+import type {PageTemplateDoc} from '@astryxdesign/cli/template';
+
+export const component: ComponentDoc = {
+ name: 'Badge', displayName: 'Badge', props: [], usage: {description: 'A badge.'},
+};
+export const block = {
+ type: 'block', name: 'badge-counts', displayName: 'Badge counts', aspectRatio: 1,
+} satisfies BlockTemplateDoc;
+export const page = {type: 'page', name: 'settings', displayName: 'Settings'} satisfies PageTemplateDoc;
+export const command: PostCodemodCommand = {
+ command: 'pnpm', args: ['install'], options: {env: {CI: '1'}},
+};
+const doc = parseDoc({} as unknown);
+if (doc.type === 'enum') void doc.members;
+export type Surface = [
+ AstryxConfig, AstryxIntegration, SubpathIntegration, AstryxCodemod, DebugEvent,
+ HookDoc, FunctionDoc, ReferenceDoc, TemplateDoc, SchemaDoc, CommandDoc, EnumDoc,
+ NamespaceDoc, UsageDoc,
+];
+void [parseConfig, parseIntegration];
+`;
+fs.writeFileSync(path.join(VERIFY_DIR, 'authoring.mts'), authoringScenario);
+for (const [label, options] of [
+ ['nodenext resolution and no Node types', {module: 'nodenext', moduleResolution: 'nodenext'}],
+ ['bundler resolution and no Node types', {module: 'esnext', moduleResolution: 'bundler'}],
+]) {
+ const config = path.join(VERIFY_DIR, 'tsconfig.authoring.json');
+ fs.writeFileSync(
+ config,
+ JSON.stringify(
+ {
+ extends: '../../../tsconfig.json',
+ compilerOptions: {noEmit: true, skipLibCheck: false, types: [], ...options},
+ files: ['authoring.mts'],
+ },
+ null,
+ 2,
+ ),
+ );
+ const run = spawnSync(tsc, ['--project', config], {cwd: ROOT, encoding: 'utf8'});
+ if (run.error) fail('failed to run tsc', String(run.error));
+ const out = `${run.stdout || ''}\n${run.stderr || ''}`;
+ const found = out.split('\n').filter(line => /error TS/.test(line));
+ if (run.status !== 0 || found.length > 0) {
+ fail(
+ `the packaged authoring types do not type-check with ${label}`,
+ (found.length > 0 ? found.join('\n') : out).trim(),
+ );
+ }
+ console.log(`\u2713 packaged authoring types type-check with ${label}`);
+}
+
console.log('\nAll published type-surface checks passed.');
diff --git a/packages/cli/authoring/_shared/contract.ts b/packages/cli/authoring/_shared/contract.ts
index 4f7e615678..d94b103916 100644
--- a/packages/cli/authoring/_shared/contract.ts
+++ b/packages/cli/authoring/_shared/contract.ts
@@ -28,5 +28,27 @@ export type MutuallyAssignable<A, B> = [A] extends [B]
: false
: false;
+/**
+ * `T` without string or number index signatures, at every depth. A
+ * `.passthrough()` schema infers one and a hand-written interface never has
+ * one, so a lock drops them before comparing named fields. Recursive fields
+ * that a schema casts to their public type compare equal by construction.
+ */
+export type NamedFields<T> = T extends readonly (infer U)[]
+ ? NamedFields<U>[]
+ : T extends (...args: never[]) => unknown
+ ? T
+ : T extends object
+ ? {
+ [
+ K in keyof T as string extends K
+ ? never
+ : number extends K
+ ? never
+ : K
+ ]: NamedFields<T[K]>;
+ }
+ : T;
+
/** Compiles only when `T` is exactly `true`; otherwise a type error. */
export type Expect<T extends true> = T;
diff --git a/packages/cli/authoring/codemod/codemod.doc.mjs b/packages/cli/authoring/codemod/codemod.doc.mjs
index ceba650c30..2cdc8cbe9e 100644
--- a/packages/cli/authoring/codemod/codemod.doc.mjs
+++ b/packages/cli/authoring/codemod/codemod.doc.mjs
@@ -63,11 +63,13 @@ export const doc = {
name: 'file.path',
type: 'string',
description: 'Absolute path to the file being transformed.',
+ required: true,
},
{
name: 'file.source',
type: 'string',
description: 'The current source contents of the file.',
+ required: true,
},
],
},
@@ -81,18 +83,21 @@ export const doc = {
type: 'unknown',
description:
'A jscodeshift instance configured with a parser for the file.',
+ required: true,
},
{
name: 'api.stats',
type: '(...args: unknown[]) => void',
description:
'Report a statistic (no-op-friendly; provided for jscodeshift parity).',
+ required: true,
},
{
name: 'api.report',
type: '(...args: unknown[]) => void',
description:
'Report progress (no-op-friendly; provided for jscodeshift parity).',
+ required: true,
},
],
},
@@ -100,7 +105,7 @@ export const doc = {
},
{
name: 'type',
- type: "'code'",
+ type: "'code' | 'config'",
description:
"Discriminant for the file-transforming variant. Use 'config' for a " +
'codemod that rewrites astryx.config.* instead (see notes).',
diff --git a/packages/cli/authoring/codemod/parse.mjs b/packages/cli/authoring/codemod/parse.mjs
index dc2c052585..434e72e87f 100644
--- a/packages/cli/authoring/codemod/parse.mjs
+++ b/packages/cli/authoring/codemod/parse.mjs
@@ -10,12 +10,14 @@
import {z} from 'zod';
import {formatZodError} from '../_shared/errors.mjs';
-/** @typedef {import('./type').AstryxCodemod} AstryxCodemod */
-/** @typedef {import('./type').AstryxConfigCodemod} AstryxConfigCodemod */
-/** @typedef {import('./type').AstryxCodemodTransform} AstryxCodemodTransform */
+/** @typedef {import('./type.js').AstryxCodemod} AstryxCodemod */
+/** @typedef {import('./type.js').AstryxConfigCodemod} AstryxConfigCodemod */
+/** @typedef {import('./type.js').AstryxCodemodTransform} AstryxCodemodTransform */
const transform = /** @type {z.ZodType<AstryxCodemodTransform>} */ (
- z.custom(value => typeof value === 'function', {message: 'Expected a function'})
+ z.custom(value => typeof value === 'function', {
+ message: 'Expected a function',
+ })
);
const codeCodemodSchema = z
@@ -52,8 +54,8 @@ const codemodEnvelopeSchema = z.discriminatedUnion('type', [
* Compile-time drift-lock: sealed envelope must infer exactly the public
* stamped-codemod union.
*
- * @typedef {import('../_shared/contract').Expect<
- * import('../_shared/contract').Equal<
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').Equal<
* z.infer<typeof codemodEnvelopeSchema>,
* AstryxCodemod | AstryxConfigCodemod
* >
diff --git a/packages/cli/authoring/config/parse.mjs b/packages/cli/authoring/config/parse.mjs
index e871968ade..e904ac407e 100644
--- a/packages/cli/authoring/config/parse.mjs
+++ b/packages/cli/authoring/config/parse.mjs
@@ -13,12 +13,12 @@ import {z} from 'zod';
import {formatZodError} from '../_shared/errors.mjs';
import {parseGapReportHandler} from '../gap-report/parse.mjs';
-/** @typedef {import('./type').AstryxConfig} AstryxConfig */
-/** @typedef {import('./type').PostCodemodHook} PostCodemodHook */
-/** @typedef {import('./type').XleComponent} XleComponent */
-/** @typedef {import('./type').DebugConfig} DebugConfig */
-/** @typedef {import('../debug/type').DebugEventHandler} DebugEventHandler */
-/** @typedef {import('../gap-report/type').GapReportHandler} GapReportHandler */
+/** @typedef {import('./type.js').AstryxConfig} AstryxConfig */
+/** @typedef {import('./type.js').PostCodemodHook} PostCodemodHook */
+/** @typedef {import('./type.js').XleComponent} XleComponent */
+/** @typedef {import('./type.js').DebugConfig} DebugConfig */
+/** @typedef {import('../debug/type.js').DebugEventHandler} DebugEventHandler */
+/** @typedef {import('../gap-report/type.js').GapReportHandler} GapReportHandler */
// Typed `z.custom` so `z.infer` reproduces the real function type (not `unknown`).
const buildCommand = /** @type {z.ZodType<PostCodemodHook['buildCommand']>} */ (
@@ -95,8 +95,8 @@ const configSchema = z
* {@link AstryxConfig} type. If they drift, `Equal` becomes `false` and
* `Expect<false>` fails the `tsconfig.authoring-contract.json` typecheck.
*
- * @typedef {import('../_shared/contract').Expect<
- * import('../_shared/contract').MutuallyAssignable<z.infer<typeof configSchema>, AstryxConfig>
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').MutuallyAssignable<z.infer<typeof configSchema>, AstryxConfig>
* >} _ConfigDriftLock
*/
diff --git a/packages/cli/authoring/config/type.ts b/packages/cli/authoring/config/type.ts
index 934b66c635..0df7d08683 100644
--- a/packages/cli/authoring/config/type.ts
+++ b/packages/cli/authoring/config/type.ts
@@ -9,8 +9,8 @@
* boundary; there is no factory to call.
*/
-import type {DebugEventHandler} from '../debug/type';
-import type {GapReportHandler} from '../gap-report/type';
+import type {DebugEventHandler} from '../debug/type.js';
+import type {GapReportHandler} from '../gap-report/type.js';
/**
* A command to run as part of a post-codemod hook. Returned by a hook's
@@ -21,7 +21,7 @@ export interface PostCodemodCommand {
args?: string[];
options?: {
cwd?: string;
- env?: NodeJS.ProcessEnv;
+ env?: Record<string, string | undefined>;
timeout?: number;
};
}
diff --git a/packages/cli/authoring/debug/parse.mjs b/packages/cli/authoring/debug/parse.mjs
index bdb8cc5033..2a7a718095 100644
--- a/packages/cli/authoring/debug/parse.mjs
+++ b/packages/cli/authoring/debug/parse.mjs
@@ -22,7 +22,7 @@
import {z} from 'zod';
import {formatZodError} from '../_shared/errors.mjs';
-/** @typedef {import('./type').DebugEvent} DebugEvent */
+/** @typedef {import('./type.js').DebugEvent} DebugEvent */
const outcomeSchema = z.enum([
'ok',
@@ -169,8 +169,8 @@ const eventSchema = z
* `Expect<false>` fails the `tsconfig.authoring-contract.json` typecheck —
* so a field added to the recorder without being published here breaks CI.
*
- * @typedef {import('../_shared/contract').Expect<
- * import('../_shared/contract').MutuallyAssignable<z.infer<typeof eventSchema>, DebugEvent>
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').MutuallyAssignable<z.infer<typeof eventSchema>, DebugEvent>
* >} _DebugEventDriftLock
*/
diff --git a/packages/cli/authoring/doctypes/_schema.mjs b/packages/cli/authoring/doctypes/_schema.mjs
index 6d789280ba..4cccf0b220 100644
--- a/packages/cli/authoring/doctypes/_schema.mjs
+++ b/packages/cli/authoring/doctypes/_schema.mjs
@@ -11,10 +11,18 @@
import {z} from 'zod';
-/** @typedef {import('./base/type').AuthoredDocGraphFields} AuthoredDocGraphFieldsType */
-/** @typedef {import('./base/type').AuthoredDocKind} AuthoredDocKind */
-/** @typedef {import('./namespace/type').NamespaceDoc} NamespaceDoc */
-/** @typedef {import('./reference/type').ReferenceContentBlock} ReferenceContentBlock */
+/** @typedef {import('./base/type.js').AuthoredDocGraphFields} AuthoredDocGraphFieldsType */
+/** @typedef {import('./base/type.js').AuthoredDocKind} AuthoredDocKind */
+/** @typedef {import('./namespace/type.js').NamespaceDoc} NamespaceDoc */
+/** @typedef {import('./reference/type.js').ReferenceContentBlock} ReferenceContentBlock */
+/** @typedef {import('./reference/type.js').ReferenceDoc} ReferenceDoc */
+/** @typedef {import('./component/type.js').SingleComponentDoc} SingleComponentDoc */
+/** @typedef {import('./base/type.js').ComponentPropDoc} ComponentPropDoc */
+/** @typedef {import('./hook/type.js').HookDoc} HookDoc */
+/** @typedef {import('./function/type.js').FunctionDoc} FunctionDoc */
+/** @typedef {import('./schema/type.js').SchemaDoc} SchemaDoc */
+/** @typedef {import('./command/type.js').CommandDoc} CommandDoc */
+/** @typedef {import('./enum/type.js').EnumDoc} EnumDoc */
const nonEmptyString = z.string().min(1);
@@ -31,6 +39,12 @@ export const AuthoredDocKindSchema = z.enum([
'namespace',
]);
+/**
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').Equal<z.infer<typeof AuthoredDocKindSchema>, AuthoredDocKind>
+ * >} _AuthoredDocKindDriftLock
+ */
+
/** Shared optional graph fields for every authored doc kind. */
export const AuthoredDocGraphFields = {
placement: z
@@ -48,8 +62,8 @@ export const AuthoredDocGraphFields = {
const _AuthoredDocGraphSchema = z.object(AuthoredDocGraphFields).strict();
/**
- * @typedef {import('../_shared/contract').Expect<
- * import('../_shared/contract').MutuallyAssignable<
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').MutuallyAssignable<
* z.infer<typeof _AuthoredDocGraphSchema>,
* AuthoredDocGraphFieldsType
* >
@@ -161,8 +175,8 @@ export const ReferenceContentBlockSchema = z.discriminatedUnion('type', [
]);
/**
- * @typedef {import('../_shared/contract').Expect<
- * import('../_shared/contract').Equal<
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').Equal<
* z.infer<typeof ReferenceContentBlockSchema>,
* ReferenceContentBlock
* >
@@ -245,11 +259,58 @@ const ComponentBaseSchema = z
})
.passthrough();
-/** New-format stamped component doc (`type: 'component'`). */
+/**
+ * One entry in a group doc's `components`: a full ComponentEntry or a
+ * name-only ComponentRef. Readers look every entry up by `name`, so that much
+ * is checked here; the rest passes through, as on an unstamped doc.
+ */
+const ComponentGroupEntrySchema = z
+ .object({name: z.string().min(1, 'component name is required')})
+ .passthrough();
+
+/**
+ * New-format stamped component doc (`type: 'component'`): one component's
+ * `props`, or the `components` a group doc documents together. These are the
+ * shapes the published ComponentDoc type allows, and the ones an unstamped doc
+ * may already take.
+ */
export const ComponentDocKindSchema = ComponentBaseSchema.extend({
- props: z.array(PropSchema),
+ props: z.array(PropSchema).optional(),
+ components: z.array(ComponentGroupEntrySchema).optional(),
+}).superRefine((doc, context) => {
+ if (doc.props == null && doc.components == null) {
+ context.addIssue({
+ code: 'custom',
+ path: ['props'],
+ message:
+ 'expected the props array, or `components` for a doc that groups several components',
+ });
+ }
});
+/**
+ * A stamped component doc as it loads. The loader accepts what the unstamped
+ * format always accepted, so stamping an existing doc never breaks it:
+ * `displayName` may be missing, `category` is any string, `usage`, `theming`,
+ * `playground` and `examples` pass through unchecked, and a doc has `props`,
+ * `components`, or both; each `components` entry needs only a `name`. Every
+ * other field matches the published type.
+ *
+ * @typedef {Omit<SingleComponentDoc,
+ * 'type' | 'displayName' | 'category' | 'usage' | 'theming' | 'examples' | 'playground' | 'props'>
+ * & {type: 'component', displayName?: string, category?: string, usage?: unknown,
+ * theming?: unknown, examples?: unknown[], playground?: unknown,
+ * props?: ComponentPropDoc[], components?: Array<{name: string}>}} LoadedComponentDoc
+ */
+/**
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').MutuallyAssignable<
+ * import('../_shared/contract.js').NamedFields<z.infer<typeof ComponentDocKindSchema>>,
+ * import('../_shared/contract.js').NamedFields<LoadedComponentDoc>
+ * >
+ * >} _ComponentDocDriftLock
+ */
+
/** Return entry for generalized function docs. */
const FunctionReturnSchema = z
.object({
@@ -269,6 +330,28 @@ export const FunctionDocKindSchema = z
})
.passthrough();
+/**
+ * A stamped function doc as it loads: as with components, `displayName` may be
+ * missing and `usage` passes through unchecked.
+ *
+ * @typedef {Omit<FunctionDoc, 'type' | 'displayName' | 'usage'>
+ * & {type: 'function', displayName?: string, usage?: unknown}} LoadedFunctionDoc
+ */
+/**
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').MutuallyAssignable<
+ * import('../_shared/contract.js').NamedFields<z.infer<typeof FunctionDocKindSchema>>,
+ * import('../_shared/contract.js').NamedFields<LoadedFunctionDoc>
+ * >
+ * >} _FunctionDocDriftLock
+ */
+
+/**
+ * Every HookDoc is a FunctionDoc, so the one function schema covers both.
+ *
+ * @typedef {import('../_shared/contract.js').Expect<[HookDoc] extends [FunctionDoc] ? true : false>} _HookDocIsFunctionDocLock
+ */
+
/**
* Stamped generic reference/topic doc (`type: 'generic'`). `title` and
* `sections` stay optional at this parser boundary for docs produced by the
@@ -308,9 +391,30 @@ export const GenericDocKindSchema = z
});
});
+/**
+ * A stamped generic doc as the load check accepts it. `title`, `description`
+ * and `sections` may be missing, as in docs the v0.3.0 factory-removal codemod
+ * produced; `parseReference` then fills them (title from `displayName` or
+ * `name`, an empty description, no sections), so its result is a full
+ * ReferenceDoc. Only a doc with a description and sections is a usable topic
+ * (see `problemsInTopic`).
+ *
+ * @typedef {Omit<ReferenceDoc, 'type' | 'title' | 'description' | 'sections'>
+ * & {type: 'generic'}
+ * & Partial<Pick<ReferenceDoc, 'title' | 'description' | 'sections'>>} LoadedReferenceDoc
+ */
+/**
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').MutuallyAssignable<
+ * import('../_shared/contract.js').NamedFields<z.infer<typeof GenericDocKindSchema>>,
+ * import('../_shared/contract.js').NamedFields<LoadedReferenceDoc>
+ * >
+ * >} _ReferenceDocDriftLock
+ */
+
/** Recursive field descriptor for a SchemaDoc. */
const SchemaFieldSchema =
- /** @type {import('zod').ZodType<import('./schema/type').SchemaFieldDoc>} */ (
+ /** @type {import('zod').ZodType<import('./schema/type.js').SchemaFieldDoc>} */ (
z.lazy(() =>
z
.object({
@@ -351,6 +455,15 @@ export const SchemaDocKindSchema = z
})
.passthrough();
+/**
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').MutuallyAssignable<
+ * import('../_shared/contract.js').NamedFields<z.infer<typeof SchemaDocKindSchema>>,
+ * import('../_shared/contract.js').NamedFields<SchemaDoc & {type: 'schema'}>
+ * >
+ * >} _SchemaDocDriftLock
+ */
+
/** New stamped command doc (`type: 'command'`). */
export const CommandDocKindSchema = z
.object({
@@ -411,6 +524,15 @@ export const CommandDocKindSchema = z
})
.passthrough();
+/**
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').MutuallyAssignable<
+ * import('../_shared/contract.js').NamedFields<z.infer<typeof CommandDocKindSchema>>,
+ * import('../_shared/contract.js').NamedFields<CommandDoc & {type: 'command'}>
+ * >
+ * >} _CommandDocDriftLock
+ */
+
/** New stamped enum doc (`type: 'enum'`). */
export const EnumDocKindSchema = z
.object({
@@ -432,6 +554,15 @@ export const EnumDocKindSchema = z
})
.passthrough();
+/**
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').MutuallyAssignable<
+ * import('../_shared/contract.js').NamedFields<z.infer<typeof EnumDocKindSchema>>,
+ * import('../_shared/contract.js').NamedFields<EnumDoc & {type: 'enum'}>
+ * >
+ * >} _EnumDocDriftLock
+ */
+
const NamespaceSlotSchema = z
.object({
title: nonEmptyString,
@@ -514,8 +645,8 @@ export const NamespaceDocKindSchema = z
});
/**
- * @typedef {import('../_shared/contract').Expect<
- * import('../_shared/contract').Equal<
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').Equal<
* z.infer<typeof NamespaceDocKindSchema>,
* NamespaceDoc
* >
diff --git a/packages/cli/authoring/doctypes/base/graph-fields.doc.mjs b/packages/cli/authoring/doctypes/base/graph-fields.doc.mjs
index 741a790d4b..3cdb701199 100644
--- a/packages/cli/authoring/doctypes/base/graph-fields.doc.mjs
+++ b/packages/cli/authoring/doctypes/base/graph-fields.doc.mjs
@@ -12,14 +12,14 @@ export const doc = {
displayName: 'Authored doc graph fields',
namespace: 'authoring',
description:
- 'Optional placement, compatibility aliases, and audience fields shared by every authored documentation kind.',
+ 'Placement, compatibility aliases, and audience: fields every authored doc kind declares for the docs graph. The docs graph is not built yet, so nothing reads them: a reference topic that sets one fails to load, and other doc kinds accept them and ignore them.',
appliesTo: 'Every supported .doc.mjs object',
fields: [
{
name: 'placement',
type: 'DocPlacement',
description:
- 'Requests one canonical parent. The compiler fails invalid explicit placement instead of silently using Unorganized.',
+ 'Requests one canonical parent in the docs graph. Not read yet: a topic that sets it fails to load.',
fields: [
{
name: 'placement.parent',
@@ -43,13 +43,20 @@ export const doc = {
name: 'aliases',
type: 'string[]',
description:
- 'Prior names or routes retained for compatibility. Aliases do not create another identity.',
+ 'Prior names or routes the docs graph will keep resolving to this doc, without creating another identity. Not read yet: a topic that sets it fails to load.',
},
{
name: 'audience',
type: "'public' | 'internal'",
- description: 'Bundle audience. Omit for public documentation.',
+ description:
+ "Which docs bundle includes this doc ('public' when omitted). Not read yet: a topic that sets it fails to load.",
default: "'public'",
},
],
+ notes: [
+ {
+ type: 'prose',
+ text: 'Unknown fields: `component`, `function`, `generic`, `schema`, `command` and `enum` docs accept a field they do not know, and nothing reads it, so a doc written for a newer CLI still loads here. `page`, `block` and `namespace` docs refuse one. Sections and content blocks refuse one in every doc.',
+ },
+ ],
};
diff --git a/packages/cli/authoring/doctypes/base/type.ts b/packages/cli/authoring/doctypes/base/type.ts
index b88c5e7804..fc2442d3a5 100644
--- a/packages/cli/authoring/doctypes/base/type.ts
+++ b/packages/cli/authoring/doctypes/base/type.ts
@@ -30,13 +30,17 @@ export interface DocPlacement {
order?: number;
}
-/** Graph metadata shared by every authored doc kind. */
+/**
+ * Graph metadata shared by every authored doc kind. Reserved for the docs
+ * graph, which is not built yet: nothing reads these fields, and a reference
+ * topic that sets one fails to load.
+ */
export interface AuthoredDocGraphFields {
- /** Requested canonical parent. Omit to use source adoption or Unorganized. */
+ /** Requested canonical parent in the docs graph. Not read yet. */
placement?: DocPlacement;
- /** Prior routes or names that must continue to resolve to this stable doc. */
+ /** Prior routes or names the docs graph will keep resolving. Not read yet. */
aliases?: string[];
- /** Bundle audience. Omit for public docs. */
+ /** Docs bundle audience; omit for public docs. Not read yet. */
audience?: DocAudience;
}
diff --git a/packages/cli/authoring/doctypes/command/command.doc.mjs b/packages/cli/authoring/doctypes/command/command.doc.mjs
index c1e7aeb9ed..247a5982a6 100644
--- a/packages/cli/authoring/doctypes/command/command.doc.mjs
+++ b/packages/cli/authoring/doctypes/command/command.doc.mjs
@@ -135,8 +135,9 @@ export const doc = {
},
{
name: 'options[].default',
- type: 'string',
- description: 'Default value as a string.',
+ type: 'string | boolean | string[]',
+ description:
+ 'Default value: a string, a boolean, or a list of strings.',
},
{
name: 'options[].cliOnly',
diff --git a/packages/cli/authoring/doctypes/command/parse.mjs b/packages/cli/authoring/doctypes/command/parse.mjs
index 98b3af9801..a1fb68ec30 100644
--- a/packages/cli/authoring/doctypes/command/parse.mjs
+++ b/packages/cli/authoring/doctypes/command/parse.mjs
@@ -8,7 +8,7 @@
import {CommandDocKindSchema} from '../_schema.mjs';
import {formatZodError} from '../../_shared/errors.mjs';
-/** @typedef {import('../types').CommandDoc} CommandDoc */
+/** @typedef {import('../types.js').CommandDoc} CommandDoc */
/**
* Validate an unknown value as a stamped command doc, or throw.
diff --git a/packages/cli/authoring/doctypes/command/type.ts b/packages/cli/authoring/doctypes/command/type.ts
index 7ee66e4582..507dd625b3 100644
--- a/packages/cli/authoring/doctypes/command/type.ts
+++ b/packages/cli/authoring/doctypes/command/type.ts
@@ -9,8 +9,8 @@
* `--help`. Colocated at `clients/cli/commands/<name>.doc.mjs`.
*/
-import type {AuthoredDocGraphFields} from '../base/type';
-import type {ReferenceContentBlock} from '../reference/type';
+import type {AuthoredDocGraphFields} from '../base/type.js';
+import type {ReferenceContentBlock} from '../reference/type.js';
/** A positional argument. `param` links it to a FunctionDoc param for its description. */
export interface CommandArgDoc {
diff --git a/packages/cli/authoring/doctypes/component/component.doc.mjs b/packages/cli/authoring/doctypes/component/component.doc.mjs
index 5fba8da8d9..ea09fb74c0 100644
--- a/packages/cli/authoring/doctypes/component/component.doc.mjs
+++ b/packages/cli/authoring/doctypes/component/component.doc.mjs
@@ -124,8 +124,7 @@ export const doc = {
name: 'usage',
type: 'UsageDoc',
description:
- 'Component usage documentation: concise summary, best practices, component-specific accessibility requirements, and optional visual anatomy. (Optional on SubComponentDoc, where the sub-component description is used instead.)',
- required: true,
+ 'Component usage documentation: concise summary, best practices, component-specific accessibility requirements, and optional visual anatomy. Required on a component doc; optional on a sub-component doc (`subComponentOf`), which uses its description instead.',
fields: [
{
name: 'usage.description',
@@ -242,6 +241,10 @@ export const docs = {
},
],
notes: [
+ {
+ type: 'prose',
+ text: "When it loads, a stamped component doc is checked as loosely as an unstamped one, so adding `type: 'component'` to an existing doc never breaks it: `displayName` may be missing, `category` may be any string, and `usage`, `theming`, `playground` and `examples` are not checked. Each entry in a group doc's `components` must have a `name`. Write to the type anyway; it is the contract.",
+ },
{
type: 'prose',
text: 'ComponentDoc is a discriminated union of three shapes that all extend ComponentBaseDoc. Pick the variant by which key you set: `props` (single), `components` (multi), or `subComponentOf` (sub).',
diff --git a/packages/cli/authoring/doctypes/component/parse.mjs b/packages/cli/authoring/doctypes/component/parse.mjs
index e53ec53f8a..94a376fad8 100644
--- a/packages/cli/authoring/doctypes/component/parse.mjs
+++ b/packages/cli/authoring/doctypes/component/parse.mjs
@@ -8,7 +8,7 @@
import {ComponentDocKindSchema} from '../_schema.mjs';
import {formatZodError} from '../../_shared/errors.mjs';
-/** @typedef {import('../types').ComponentDoc} ComponentDoc */
+/** @typedef {import('../types.js').ComponentDoc} ComponentDoc */
/**
* Validate an unknown value as a stamped component doc, or throw.
diff --git a/packages/cli/authoring/doctypes/component/type.ts b/packages/cli/authoring/doctypes/component/type.ts
index 2895ba39d3..1578351ba2 100644
--- a/packages/cli/authoring/doctypes/component/type.ts
+++ b/packages/cli/authoring/doctypes/component/type.ts
@@ -19,7 +19,7 @@ import type {
HookReturnDoc,
RegistryDocIdentity,
UsageDoc,
-} from '../base/type';
+} from '../base/type.js';
/**
* Shared fields between single-component and multi-component docs.
diff --git a/packages/cli/authoring/doctypes/enum/parse.mjs b/packages/cli/authoring/doctypes/enum/parse.mjs
index 83a6d6f20d..2ac916e1ce 100644
--- a/packages/cli/authoring/doctypes/enum/parse.mjs
+++ b/packages/cli/authoring/doctypes/enum/parse.mjs
@@ -8,7 +8,7 @@
import {EnumDocKindSchema} from '../_schema.mjs';
import {formatZodError} from '../../_shared/errors.mjs';
-/** @typedef {import('../types').EnumDoc} EnumDoc */
+/** @typedef {import('../types.js').EnumDoc} EnumDoc */
/**
* Validate an unknown value as a stamped enum doc, or throw.
diff --git a/packages/cli/authoring/doctypes/enum/type.ts b/packages/cli/authoring/doctypes/enum/type.ts
index f32c106c7d..931cbed1e0 100644
--- a/packages/cli/authoring/doctypes/enum/type.ts
+++ b/packages/cli/authoring/doctypes/enum/type.ts
@@ -5,7 +5,7 @@
* discriminants). Colocated next to the source of truth it documents.
*/
-import type {AuthoredDocGraphFields} from '../base/type';
+import type {AuthoredDocGraphFields} from '../base/type.js';
/** One member of an enumerated vocabulary. */
export interface EnumMemberDoc {
diff --git a/packages/cli/authoring/doctypes/function/function.doc.mjs b/packages/cli/authoring/doctypes/function/function.doc.mjs
index 173aec5a36..81ab9dd60b 100644
--- a/packages/cli/authoring/doctypes/function/function.doc.mjs
+++ b/packages/cli/authoring/doctypes/function/function.doc.mjs
@@ -250,6 +250,10 @@ export const doc = {
},
],
notes: [
+ {
+ type: 'prose',
+ text: 'When it loads, a stamped function doc may leave out `displayName`, and its `usage` is not checked. Write to the type anyway; it is the contract.',
+ },
{
type: 'prose',
text: "The `type` discriminant is 'function' for both flavors. Set `kind: 'hook'` or `kind: 'api'` to drive docsite sectioning; it is inferred from `importPath` when omitted.",
diff --git a/packages/cli/authoring/doctypes/function/parse.mjs b/packages/cli/authoring/doctypes/function/parse.mjs
index 81e404ac7c..b50931aa7f 100644
--- a/packages/cli/authoring/doctypes/function/parse.mjs
+++ b/packages/cli/authoring/doctypes/function/parse.mjs
@@ -14,7 +14,7 @@
import {parseHook} from '../hook/parse.mjs';
-/** @typedef {import('../types').FunctionDoc} FunctionDoc */
+/** @typedef {import('../types.js').FunctionDoc} FunctionDoc */
/**
* Validate an unknown value as a stamped function doc, or throw.
diff --git a/packages/cli/authoring/doctypes/function/type.ts b/packages/cli/authoring/doctypes/function/type.ts
index 5844181c83..d33b4e7e29 100644
--- a/packages/cli/authoring/doctypes/function/type.ts
+++ b/packages/cli/authoring/doctypes/function/type.ts
@@ -14,7 +14,7 @@ import type {
AuthoredDocGraphFields,
HookParamDoc,
UsageDoc,
-} from '../base/type';
+} from '../base/type.js';
/**
* A documented return. Hooks list named return fields (`name` set); CLI/API
diff --git a/packages/cli/authoring/doctypes/hook/hook.doc.mjs b/packages/cli/authoring/doctypes/hook/hook.doc.mjs
index f4ec021705..61e98ada6c 100644
--- a/packages/cli/authoring/doctypes/hook/hook.doc.mjs
+++ b/packages/cli/authoring/doctypes/hook/hook.doc.mjs
@@ -200,6 +200,10 @@ export const docs = {
},
],
notes: [
+ {
+ type: 'prose',
+ text: 'When it loads, a hook doc may leave out `displayName`, and its `usage` is not checked. Write to the type anyway; it is the contract.',
+ },
{
type: 'prose',
text: "A hook's discriminant is `type: 'function'`: HookDoc and FunctionDoc share the generalized function kind. HookDoc is the hook-flavored view: named `returns` fields and a required `usage` block.",
diff --git a/packages/cli/authoring/doctypes/hook/parse.mjs b/packages/cli/authoring/doctypes/hook/parse.mjs
index b3f6c2d083..3f0ebaaee4 100644
--- a/packages/cli/authoring/doctypes/hook/parse.mjs
+++ b/packages/cli/authoring/doctypes/hook/parse.mjs
@@ -8,7 +8,7 @@
import {FunctionDocKindSchema} from '../_schema.mjs';
import {formatZodError} from '../../_shared/errors.mjs';
-/** @typedef {import('../types').HookDoc} HookDoc */
+/** @typedef {import('../types.js').HookDoc} HookDoc */
/**
* Validate an unknown value as a stamped function/hook doc, or throw.
diff --git a/packages/cli/authoring/doctypes/hook/type.ts b/packages/cli/authoring/doctypes/hook/type.ts
index beab74a9f9..50b4b453e0 100644
--- a/packages/cli/authoring/doctypes/hook/type.ts
+++ b/packages/cli/authoring/doctypes/hook/type.ts
@@ -12,7 +12,7 @@ import type {
HookReturnDoc,
RegistryDocIdentity,
UsageDoc,
-} from '../base/type';
+} from '../base/type.js';
/**
* Documentation for a standalone hook's .doc.mjs file.
diff --git a/packages/cli/authoring/doctypes/legacy.mjs b/packages/cli/authoring/doctypes/legacy.mjs
index d261b6e4a2..ee8064b77a 100644
--- a/packages/cli/authoring/doctypes/legacy.mjs
+++ b/packages/cli/authoring/doctypes/legacy.mjs
@@ -10,9 +10,9 @@
import {LegacyDocSchema} from './_schema.mjs';
import {formatZodError} from '../_shared/errors.mjs';
-/** @typedef {import('./types').ComponentDoc} ComponentDoc */
-/** @typedef {import('./types').HookDoc} HookDoc */
-/** @typedef {import('./types').ReferenceDoc} ReferenceDoc */
+/** @typedef {import('./types.js').ComponentDoc} ComponentDoc */
+/** @typedef {import('./types.js').HookDoc} HookDoc */
+/** @typedef {import('./types.js').ReferenceDoc} ReferenceDoc */
/**
* Validate an unknown value as a legacy (unstamped) doc, or throw.
diff --git a/packages/cli/authoring/doctypes/load-contract.test.mjs b/packages/cli/authoring/doctypes/load-contract.test.mjs
new file mode 100644
index 0000000000..c806c689fe
--- /dev/null
+++ b/packages/cli/authoring/doctypes/load-contract.test.mjs
@@ -0,0 +1,207 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Every authored doc kind has a compile-time lock between its load check
+ * and its published type: the `_*DriftLock` typedefs in `_schema.mjs` and
+ * `template/parse.mjs`, which the strict typecheck evaluates. A lock names each
+ * place the loader is deliberately looser than the type. These tests pin that
+ * looser behavior and the published unknown-field policy, so tightening a load
+ * check is a reviewed change rather than a silent one.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath, pathToFileURL} from 'node:url';
+import {describe, expect, it} from 'vitest';
+import {parseDoc} from './parse.mjs';
+import {AuthoredDocKindSchema} from './_schema.mjs';
+import {doc as graphFieldsDoc} from './base/graph-fields.doc.mjs';
+import {problemsInTopic} from '../../foundation/discovery/docs-discovery.mjs';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const KINDS = AuthoredDocKindSchema.options;
+
+/** The lock that pins each kind's load check to its published type. */
+const LOCKS = {
+ component: '_ComponentDocDriftLock',
+ function: '_FunctionDocDriftLock',
+ generic: '_ReferenceDocDriftLock',
+ page: '_PageTemplateDocDriftLock',
+ block: '_BlockTemplateDocDriftLock',
+ schema: '_SchemaDocDriftLock',
+ command: '_CommandDocDriftLock',
+ enum: '_EnumDocDriftLock',
+ namespace: '_NamespaceDocDriftLock',
+};
+
+/** One valid example doc per kind, from the typed examples. */
+const EXAMPLES = Object.fromEntries(
+ await Promise.all(
+ KINDS.map(async kind => {
+ const file = {generic: 'reference', function: 'function'}[kind] ?? kind;
+ const url = pathToFileURL(
+ path.join(HERE, '../../test/authoring-types', `${file}.doc.mjs`),
+ );
+ return [kind, (await import(url.href)).docs];
+ }),
+ ),
+);
+
+describe('load check vs published type', () => {
+ it('locks every doc kind', () => {
+ const source = ['_schema.mjs', 'template/parse.mjs']
+ .map(file => fs.readFileSync(path.join(HERE, file), 'utf8'))
+ .join('\n');
+ expect(Object.keys(LOCKS).sort()).toEqual([...KINDS].sort());
+ const locks = [
+ ...Object.values(LOCKS),
+ '_AuthoredDocKindDriftLock',
+ '_HookDocIsFunctionDocLock',
+ ];
+ for (const lock of locks) {
+ expect(source, `${lock} is missing`).toMatch(
+ new RegExp(`\\}\\s*${lock}\\b`),
+ );
+ }
+ });
+
+ it('dispatches every doc kind and refuses any other', () => {
+ for (const kind of KINDS) {
+ expect(() => parseDoc(EXAMPLES[kind], `${kind}.doc.mjs`)).not.toThrow();
+ }
+ expect(() => parseDoc({type: 'widget', name: 'x'}, 'x.doc.mjs')).toThrow(
+ /unsupported type "widget"/,
+ );
+ });
+});
+
+describe('where loading is deliberately looser than the type', () => {
+ it('a stamped component needs no displayName; usage, theming and examples are unchecked', () => {
+ expect(() =>
+ parseDoc(
+ {
+ type: 'component',
+ name: 'Badge',
+ category: 'badges',
+ props: [],
+ usage: 'free text',
+ theming: 5,
+ examples: [{title: 'Basic'}],
+ },
+ 'Badge.doc.mjs',
+ ),
+ ).not.toThrow();
+ });
+
+ it('each entry of a stamped group doc needs a name, and nothing more', () => {
+ const group = (/** @type {unknown[]} */ components) => ({
+ type: 'component',
+ name: 'Tabs',
+ components,
+ });
+ expect(() =>
+ parseDoc(
+ group([{name: 'Tab'}, {name: 'TabPanel', description: 'x'}]),
+ 'Tabs.doc.mjs',
+ ),
+ ).not.toThrow();
+ for (const bad of [null, 5, 'Tab', {}, {name: ''}, {displayName: 'Tab'}]) {
+ expect(() => parseDoc(group([bad]), 'Tabs.doc.mjs')).toThrow(
+ /components\.0/,
+ );
+ }
+ });
+
+ it('a stamped function needs no displayName; usage is unchecked', () => {
+ expect(() =>
+ parseDoc(
+ {type: 'function', name: 'useX', params: [], returns: [], usage: 5},
+ 'useX.doc.mjs',
+ ),
+ ).not.toThrow();
+ });
+
+ it('a stamped generic doc loads without title, description or sections, but is no topic', () => {
+ const doc = parseDoc({type: 'generic', name: 'notes'}, 'notes.doc.mjs');
+ expect(doc.title).toBe('notes');
+ expect(problemsInTopic(doc)).toEqual([
+ 'description: expected a non-empty string',
+ 'sections: expected at least one section',
+ ]);
+ });
+
+ it('a template needs no displayName or aspectRatio and may use its own category', () => {
+ expect(() =>
+ parseDoc(
+ {type: 'block', name: 'widget-demo', category: 'components/Widget'},
+ 'widget-demo.doc.mjs',
+ ),
+ ).not.toThrow();
+ expect(() =>
+ parseDoc(
+ {type: 'page', name: 'widget-page', category: 'Widgets'},
+ 'widget-page.doc.mjs',
+ ),
+ ).not.toThrow();
+ });
+
+ it('schema, command and enum docs load only as their type allows', () => {
+ const {fields, ...schemaDoc} = EXAMPLES.schema;
+ const {summary, ...commandDoc} = EXAMPLES.command;
+ const {members, ...enumDoc} = EXAMPLES.enum;
+ expect(() => parseDoc(schemaDoc, 's.doc.mjs')).toThrow(/fields/);
+ expect(() => parseDoc(commandDoc, 'c.doc.mjs')).toThrow(/summary/);
+ expect(() => parseDoc(enumDoc, 'e.doc.mjs')).toThrow(/members/);
+ });
+});
+
+describe('unknown fields', () => {
+ const keeps = KINDS.filter(kind => {
+ try {
+ parseDoc({...EXAMPLES[kind], notAField: true}, `${kind}.doc.mjs`);
+ return true;
+ } catch {
+ return false;
+ }
+ });
+
+ it('match the published policy', () => {
+ const policy = graphFieldsDoc.notes
+ .map(note => ('text' in note ? note.text : ''))
+ .find(text => text.startsWith('Unknown fields'));
+ expect(policy, 'graph-fields.doc.mjs states the policy').toBeDefined();
+ const [kept, refused] = /** @type {string} */ (policy).split(
+ ' docs accept',
+ );
+ const named = (/** @type {string} */ text) =>
+ [...text.matchAll(/`([a-z]+)`/g)].map(match => match[1]).sort();
+ expect(named(kept)).toEqual([...keeps].sort());
+ expect(named(refused).filter(kind => KINDS.includes(kind))).toEqual(
+ KINDS.filter(kind => !keeps.includes(kind)).sort(),
+ );
+ });
+
+ it('are refused inside sections and content blocks', () => {
+ const [section] = EXAMPLES.generic.sections;
+ expect(() =>
+ parseDoc(
+ {...EXAMPLES.generic, sections: [{...section, notAField: true}]},
+ 'r.doc.mjs',
+ ),
+ ).toThrow();
+ expect(() =>
+ parseDoc(
+ {
+ ...EXAMPLES.generic,
+ sections: [
+ {
+ ...section,
+ content: [{type: 'prose', text: 'x', notAField: true}],
+ },
+ ],
+ },
+ 'r.doc.mjs',
+ ),
+ ).toThrow();
+ });
+});
diff --git a/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs b/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs
index 6827e7d9ba..80be4eca49 100644
--- a/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs
+++ b/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs
@@ -12,7 +12,7 @@ export const doc = {
displayName: 'NamespaceDoc',
namespace: 'authoring',
description:
- 'Declares named navigation slots and renderer-neutral layout blocks for already-discovered docs. It never scans folders or copies child documents.',
+ "Declares named navigation slots and renderer-neutral layout blocks for already-discovered docs. It never scans folders or copies child documents. Not loaded yet: only the docs graph reads namespace docs, and it is not built, so keep them out of an integration's docs directory for now.",
appliesTo: '<namespace>.doc.mjs',
fields: [
{
@@ -44,13 +44,13 @@ export const doc = {
name: 'placement',
type: 'DocPlacement',
description:
- 'Optional canonical parent request: {parent, slot?, order?}. Invalid explicit placement fails compilation instead of falling back.',
+ 'Optional canonical parent request: {parent, slot?, order?}. Invalid explicit placement will fail compilation instead of falling back.',
},
{
name: 'aliases',
type: 'string[]',
description:
- 'Prior names or routes that must keep resolving to this doc.',
+ 'Prior names or routes the docs graph will keep resolving to this doc.',
},
{
name: 'audience',
@@ -111,6 +111,10 @@ export const docs = {
},
],
notes: [
+ {
+ type: 'prose',
+ text: "Namespace docs are not loaded yet. Only the docs graph reads them, and it is not built. A namespace doc in an integration's docs directory fails to load as a topic, and with it every topic that package contributes, until the file is removed.",
+ },
{
type: 'prose',
text: 'Child docs request one canonical home with placement. Collections store and render stable references to those docs; they never create a second identity or parent.',
diff --git a/packages/cli/authoring/doctypes/namespace/parse.mjs b/packages/cli/authoring/doctypes/namespace/parse.mjs
index 1289693c58..208a2280b1 100644
--- a/packages/cli/authoring/doctypes/namespace/parse.mjs
+++ b/packages/cli/authoring/doctypes/namespace/parse.mjs
@@ -8,7 +8,7 @@
import {NamespaceDocKindSchema} from '../_schema.mjs';
import {formatZodError} from '../../_shared/errors.mjs';
-/** @typedef {import('../types').NamespaceDoc} NamespaceDoc */
+/** @typedef {import('../types.js').NamespaceDoc} NamespaceDoc */
/**
* Validate an unknown value as a NamespaceDoc, or throw a readable error.
diff --git a/packages/cli/authoring/doctypes/namespace/type.ts b/packages/cli/authoring/doctypes/namespace/type.ts
index 2646f96b5f..3363d4586d 100644
--- a/packages/cli/authoring/doctypes/namespace/type.ts
+++ b/packages/cli/authoring/doctypes/namespace/type.ts
@@ -6,8 +6,8 @@
* or copies child documents.
*/
-import type {AuthoredDocGraphFields, AuthoredDocKind} from '../base/type';
-import type {ReferenceContentBlock} from '../reference/type';
+import type {AuthoredDocGraphFields, AuthoredDocKind} from '../base/type.js';
+import type {ReferenceContentBlock} from '../reference/type.js';
/** Which providers may contribute appearances to a namespace slot. */
export type NamespaceProviderScope = 'same' | 'configured';
diff --git a/packages/cli/authoring/doctypes/parse.mjs b/packages/cli/authoring/doctypes/parse.mjs
index 9df666db44..2238eff23c 100644
--- a/packages/cli/authoring/doctypes/parse.mjs
+++ b/packages/cli/authoring/doctypes/parse.mjs
@@ -18,15 +18,15 @@ import {parseEnum} from './enum/parse.mjs';
import {parseNamespace} from './namespace/parse.mjs';
import {parseLegacyDoc} from './legacy.mjs';
-/** @typedef {import('./types').ComponentDoc} ComponentDoc */
-/** @typedef {import('./types').HookDoc} HookDoc */
-/** @typedef {import('./types').FunctionDoc} FunctionDoc */
-/** @typedef {import('./types').ReferenceDoc} ReferenceDoc */
-/** @typedef {import('./types').TemplateDoc} TemplateDoc */
-/** @typedef {import('./types').SchemaDoc} SchemaDoc */
-/** @typedef {import('./types').CommandDoc} CommandDoc */
-/** @typedef {import('./types').EnumDoc} EnumDoc */
-/** @typedef {import('./types').NamespaceDoc} NamespaceDoc */
+/** @typedef {import('./types.js').ComponentDoc} ComponentDoc */
+/** @typedef {import('./types.js').HookDoc} HookDoc */
+/** @typedef {import('./types.js').FunctionDoc} FunctionDoc */
+/** @typedef {import('./types.js').ReferenceDoc} ReferenceDoc */
+/** @typedef {import('./types.js').TemplateDoc} TemplateDoc */
+/** @typedef {import('./types.js').SchemaDoc} SchemaDoc */
+/** @typedef {import('./types.js').CommandDoc} CommandDoc */
+/** @typedef {import('./types.js').EnumDoc} EnumDoc */
+/** @typedef {import('./types.js').NamespaceDoc} NamespaceDoc */
/**
* Validate an unknown loaded doc value into its typed shape, or throw.
diff --git a/packages/cli/authoring/doctypes/reference/parse.mjs b/packages/cli/authoring/doctypes/reference/parse.mjs
index 32f8d61e17..49c03536e7 100644
--- a/packages/cli/authoring/doctypes/reference/parse.mjs
+++ b/packages/cli/authoring/doctypes/reference/parse.mjs
@@ -9,7 +9,7 @@
import {GenericDocKindSchema} from '../_schema.mjs';
import {formatZodError} from '../../_shared/errors.mjs';
-/** @typedef {import('../types').ReferenceDoc} ReferenceDoc */
+/** @typedef {import('../types.js').ReferenceDoc} ReferenceDoc */
/**
* Validate an unknown value as a stamped reference/topic doc, or throw.
diff --git a/packages/cli/authoring/doctypes/reference/reference.doc.mjs b/packages/cli/authoring/doctypes/reference/reference.doc.mjs
index 9ae1022ddd..73beacec6e 100644
--- a/packages/cli/authoring/doctypes/reference/reference.doc.mjs
+++ b/packages/cli/authoring/doctypes/reference/reference.doc.mjs
@@ -95,7 +95,7 @@ export const doc = {
name: 'sections[].content',
type: 'ReferenceContentBlock[]',
description:
- 'Ordered content blocks. Existing prose, heading, code, table, list, and token-ref blocks remain; V1 adds workflow, collection, and reference.',
+ 'Ordered content blocks: prose, heading, code, table, list, and token-ref. workflow, collection, and reference are declared for the docs graph and parse, but a topic that uses one fails to load until the docs graph ships.',
required: true,
},
{
@@ -140,7 +140,11 @@ export const docs = {
notes: [
{
type: 'prose',
- text: 'Each `sections[].content` is an ordered array of ReferenceContentBlock, a discriminated union. V1 adds only workflow, collection, and reference; choice, callout, and checklist remain invalid. The same union is reused by the `notes` field on SchemaDoc and CommandDoc.',
+ text: 'A stamped generic doc without `title`, `description` or `sections` still loads, as older codemod output does; its title falls back to `displayName` or `name`. Without a description and sections it is not a usable topic, and `astryx doctor` reports it.',
+ },
+ {
+ type: 'prose',
+ text: 'Each `sections[].content` is an ordered array of ReferenceContentBlock, a discriminated union. workflow, collection, and reference are declared for the docs graph: they parse, but topic loading rejects them until the docs graph ships. choice, callout, and checklist remain invalid. The same union is reused by the `notes` field on SchemaDoc and CommandDoc.',
},
{
type: 'code',
diff --git a/packages/cli/authoring/doctypes/reference/type.ts b/packages/cli/authoring/doctypes/reference/type.ts
index f2454b18c7..14dc63eb99 100644
--- a/packages/cli/authoring/doctypes/reference/type.ts
+++ b/packages/cli/authoring/doctypes/reference/type.ts
@@ -4,7 +4,7 @@
* @file Reference/topic doc types.
*/
-import type {AuthoredDocGraphFields} from '../base/type';
+import type {AuthoredDocGraphFields} from '../base/type.js';
/** One step in a renderer-neutral workflow. */
export interface WorkflowStep {
diff --git a/packages/cli/authoring/doctypes/schema/parse.mjs b/packages/cli/authoring/doctypes/schema/parse.mjs
index 9aa0df1435..95080e11d3 100644
--- a/packages/cli/authoring/doctypes/schema/parse.mjs
+++ b/packages/cli/authoring/doctypes/schema/parse.mjs
@@ -8,7 +8,7 @@
import {SchemaDocKindSchema} from '../_schema.mjs';
import {formatZodError} from '../../_shared/errors.mjs';
-/** @typedef {import('../types').SchemaDoc} SchemaDoc */
+/** @typedef {import('../types.js').SchemaDoc} SchemaDoc */
/**
* Validate an unknown value as a stamped schema doc, or throw.
diff --git a/packages/cli/authoring/doctypes/schema/type.ts b/packages/cli/authoring/doctypes/schema/type.ts
index d89ec32ad1..a38bddc8cd 100644
--- a/packages/cli/authoring/doctypes/schema/type.ts
+++ b/packages/cli/authoring/doctypes/schema/type.ts
@@ -6,8 +6,8 @@
* response envelope). Colocated as a `.doc.mjs` next to the schema it describes.
*/
-import type {AuthoredDocGraphFields} from '../base/type';
-import type {ReferenceContentBlock} from '../reference/type';
+import type {AuthoredDocGraphFields} from '../base/type.js';
+import type {ReferenceContentBlock} from '../reference/type.js';
/**
* One documented field of a schema. Object fields nest via `fields`, so a whole
diff --git a/packages/cli/authoring/doctypes/template/parse.mjs b/packages/cli/authoring/doctypes/template/parse.mjs
index 029943e615..8e2ce4b45b 100644
--- a/packages/cli/authoring/doctypes/template/parse.mjs
+++ b/packages/cli/authoring/doctypes/template/parse.mjs
@@ -12,7 +12,9 @@ import {z} from 'zod';
import {AuthoredDocGraphFields} from '../_schema.mjs';
import {formatZodError} from '../../_shared/errors.mjs';
-/** @typedef {import('../types').TemplateDoc} TemplateDoc */
+/** @typedef {import('../types.js').TemplateDoc} TemplateDoc */
+/** @typedef {import('./type.js').PageTemplateDoc} PageTemplateDoc */
+/** @typedef {import('./type.js').BlockTemplateDoc} BlockTemplateDoc */
const previewSchema = z
.object({
@@ -67,6 +69,36 @@ const blockTemplateSchema = z
})
.strict();
+/**
+ * Templates as they load. Integration templates already published omit
+ * `displayName` and `aspectRatio` and group themselves under their own
+ * `category`, so the loader accepts those (template discovery falls back to an
+ * aspect ratio of 1). The published types keep asking authors for all three.
+ *
+ * @typedef {Omit<PageTemplateDoc, 'displayName' | 'category'>
+ * & {displayName?: string, category?: string}} LoadedPageTemplateDoc
+ * @typedef {Omit<BlockTemplateDoc, 'displayName' | 'aspectRatio' | 'category'>
+ * & {displayName?: string, aspectRatio?: number, category?: string}} LoadedBlockTemplateDoc
+ */
+
+/**
+ * @typedef {import('../../_shared/contract.js').Expect<
+ * import('../../_shared/contract.js').MutuallyAssignable<
+ * import('../../_shared/contract.js').NamedFields<z.infer<typeof pageTemplateSchema>>,
+ * import('../../_shared/contract.js').NamedFields<LoadedPageTemplateDoc>
+ * >
+ * >} _PageTemplateDocDriftLock
+ */
+
+/**
+ * @typedef {import('../../_shared/contract.js').Expect<
+ * import('../../_shared/contract.js').MutuallyAssignable<
+ * import('../../_shared/contract.js').NamedFields<z.infer<typeof blockTemplateSchema>>,
+ * import('../../_shared/contract.js').NamedFields<LoadedBlockTemplateDoc>
+ * >
+ * >} _BlockTemplateDocDriftLock
+ */
+
const templateEnvelopeSchema = z
.discriminatedUnion('type', [pageTemplateSchema, blockTemplateSchema])
.superRefine((template, context) => {
diff --git a/packages/cli/authoring/doctypes/template/template.doc.mjs b/packages/cli/authoring/doctypes/template/template.doc.mjs
index 05717243a9..b9f6c05a43 100644
--- a/packages/cli/authoring/doctypes/template/template.doc.mjs
+++ b/packages/cli/authoring/doctypes/template/template.doc.mjs
@@ -148,6 +148,10 @@ export const doc = {
},
],
notes: [
+ {
+ type: 'prose',
+ text: 'When it loads, a template may leave out `displayName` and `aspectRatio` and use its own `category`, as integration templates already published do; a block with no `aspectRatio` previews at 1. Write to the type anyway; it is the contract.',
+ },
{
type: 'prose',
text: "TemplateDoc is a discriminated union keyed by `type`. Set `type: 'page'` for a full page template. Set `type: 'block'` for an editable composition; add `exampleFor` only when one component owns the example.",
diff --git a/packages/cli/authoring/doctypes/template/type.ts b/packages/cli/authoring/doctypes/template/type.ts
index 350855d0c7..f7bcb31ac9 100644
--- a/packages/cli/authoring/doctypes/template/type.ts
+++ b/packages/cli/authoring/doctypes/template/type.ts
@@ -4,7 +4,10 @@
* @file Template doc types.
*/
-import type {AuthoredDocGraphFields, RegistryDocIdentity} from '../base/type';
+import type {
+ AuthoredDocGraphFields,
+ RegistryDocIdentity,
+} from '../base/type.js';
export interface BaseTemplateDoc extends AuthoredDocGraphFields {
/** Identifier name for the template. For block templates this matches
diff --git a/packages/cli/authoring/doctypes/types.ts b/packages/cli/authoring/doctypes/types.ts
index 915dd82d3d..c21f8a048d 100644
--- a/packages/cli/authoring/doctypes/types.ts
+++ b/packages/cli/authoring/doctypes/types.ts
@@ -7,13 +7,13 @@
* behind `@astryxdesign/cli/authoring`.
*/
-export type * from './base/type';
-export type * from './component/type';
-export type * from './hook/type';
-export type * from './function/type';
-export type * from './reference/type';
-export type * from './namespace/type';
-export type * from './template/type';
-export type * from './schema/type';
-export type * from './command/type';
-export type * from './enum/type';
+export type * from './base/type.js';
+export type * from './component/type.js';
+export type * from './hook/type.js';
+export type * from './function/type.js';
+export type * from './reference/type.js';
+export type * from './namespace/type.js';
+export type * from './template/type.js';
+export type * from './schema/type.js';
+export type * from './command/type.js';
+export type * from './enum/type.js';
diff --git a/packages/cli/authoring/gap-report/parse.mjs b/packages/cli/authoring/gap-report/parse.mjs
index a29863782c..2bbf8aaec6 100644
--- a/packages/cli/authoring/gap-report/parse.mjs
+++ b/packages/cli/authoring/gap-report/parse.mjs
@@ -13,8 +13,8 @@
import {z} from 'zod';
import {formatZodError} from '../_shared/errors.mjs';
-/** @typedef {import('./type').GapReportHandler} GapReportHandler */
-/** @typedef {import('./type').GapReportHandlerReceipt} GapReportHandlerReceipt */
+/** @typedef {import('./type.js').GapReportHandler} GapReportHandler */
+/** @typedef {import('./type.js').GapReportHandlerReceipt} GapReportHandlerReceipt */
// Typed z.custom so z.infer reproduces the real function type, matching the
// pattern used by the debug handler and post-codemod hook parsers.
@@ -36,8 +36,8 @@ const handlerSchema = z
* {@link GapReportHandler} type. If they drift, `MutuallyAssignable` becomes
* `false` and `Expect<false>` fails `tsconfig.authoring-contract.json`.
*
- * @typedef {import('../_shared/contract').Expect<
- * import('../_shared/contract').MutuallyAssignable<z.infer<typeof handlerSchema>, GapReportHandler>
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').MutuallyAssignable<z.infer<typeof handlerSchema>, GapReportHandler>
* >} _GapReportHandlerDriftLock
*/
@@ -50,8 +50,8 @@ const receiptSchema = z
.strict();
/**
- * @typedef {import('../_shared/contract').Expect<
- * import('../_shared/contract').MutuallyAssignable<z.infer<typeof receiptSchema>, GapReportHandlerReceipt>
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').MutuallyAssignable<z.infer<typeof receiptSchema>, GapReportHandlerReceipt>
* >} _GapReportReceiptDriftLock
*/
diff --git a/packages/cli/authoring/gap-report/type.ts b/packages/cli/authoring/gap-report/type.ts
index cfd23c538f..d767d9adb0 100644
--- a/packages/cli/authoring/gap-report/type.ts
+++ b/packages/cli/authoring/gap-report/type.ts
@@ -14,7 +14,7 @@
* gap-report handlers.
*/
-import type {DebugInvocationSource} from '../debug/type';
+import type {DebugInvocationSource} from '../debug/type.js';
/** Supported gap-report categories. */
export type GapReportCategory =
diff --git a/packages/cli/authoring/identity/identity.doc.mjs b/packages/cli/authoring/identity/identity.doc.mjs
index 91867f859d..ca01da6dbc 100644
--- a/packages/cli/authoring/identity/identity.doc.mjs
+++ b/packages/cli/authoring/identity/identity.doc.mjs
@@ -12,8 +12,9 @@ export const doc = {
displayName: 'Provider and artifact identity',
namespace: 'authoring',
description:
- 'Separates stable provider/artifact identity from package instances and runtime lifecycle state.',
- appliesTo: 'Compiler inputs, manifests, search, Build, and Doctor',
+ 'Separates stable provider/artifact identity from package instances and runtime lifecycle state. providerId is in use today: an integration manifest may declare it, and Doctor and every command report two packages that claim one. The artifact, doc, instance, and compiler-input identities are defined for the docs graph, which is not built yet, and no command reads them.',
+ appliesTo:
+ 'Integration manifests and provider conflicts today; the docs graph once it ships',
fields: [
{
name: 'ProviderId',
diff --git a/packages/cli/authoring/identity/type.ts b/packages/cli/authoring/identity/type.ts
index 05331af0dc..8fa73bfce4 100644
--- a/packages/cli/authoring/identity/type.ts
+++ b/packages/cli/authoring/identity/type.ts
@@ -8,16 +8,16 @@
* artifact ID stays stable across those instances.
*/
-import type {AuthoredDocKind} from '../doctypes/base/type';
-import type {CommandDoc} from '../doctypes/command/type';
-import type {ComponentDoc} from '../doctypes/component/type';
-import type {EnumDoc} from '../doctypes/enum/type';
-import type {FunctionDoc} from '../doctypes/function/type';
-import type {HookDoc} from '../doctypes/hook/type';
-import type {NamespaceDoc} from '../doctypes/namespace/type';
-import type {ReferenceDoc} from '../doctypes/reference/type';
-import type {SchemaDoc} from '../doctypes/schema/type';
-import type {TemplateDoc} from '../doctypes/template/type';
+import type {AuthoredDocKind} from '../doctypes/base/type.js';
+import type {CommandDoc} from '../doctypes/command/type.js';
+import type {ComponentDoc} from '../doctypes/component/type.js';
+import type {EnumDoc} from '../doctypes/enum/type.js';
+import type {FunctionDoc} from '../doctypes/function/type.js';
+import type {HookDoc} from '../doctypes/hook/type.js';
+import type {NamespaceDoc} from '../doctypes/namespace/type.js';
+import type {ReferenceDoc} from '../doctypes/reference/type.js';
+import type {SchemaDoc} from '../doctypes/schema/type.js';
+import type {TemplateDoc} from '../doctypes/template/type.js';
declare const providerIdBrand: unique symbol;
declare const artifactIdBrand: unique symbol;
diff --git a/packages/cli/authoring/index.d.ts b/packages/cli/authoring/index.d.ts
index 92d4b34d87..81f6142043 100644
--- a/packages/cli/authoring/index.d.ts
+++ b/packages/cli/authoring/index.d.ts
@@ -23,18 +23,18 @@
// ═══════════════════════════════════════════════════════════════════════
// AUTHOR THESE — each is the default export of one authored file.
// ═══════════════════════════════════════════════════════════════════════
-export type {ComponentDoc} from './doctypes/types'; // Button.doc.{ts,mjs}
-export type {HookDoc} from './doctypes/types'; // useToast.doc.{ts,mjs}
-export type {FunctionDoc} from './doctypes/types'; // search.doc.mjs (hook | api)
-export type {ReferenceDoc} from './doctypes/types'; // theming.doc.{ts,mjs}
-export type {TemplateDoc} from './doctypes/types'; // Foo.template.{ts,mjs}
-export type {SchemaDoc} from './doctypes/types'; // config.doc.mjs (object shape)
-export type {CommandDoc} from './doctypes/types'; // search.doc.mjs (CLI command)
-export type {EnumDoc} from './doctypes/types'; // error-codes.doc.mjs (vocabulary)
-export type {NamespaceDoc} from './doctypes/types'; // cli.doc.mjs (hierarchy)
-export type {AstryxConfig} from './config/type'; // astryx.config.{ts,mjs}
-export type {DebugEvent} from './debug/type'; // one recorded CLI run
-export type {AstryxIntegration} from './integration/type'; // astryx.integration.{ts,mjs}
+export type {ComponentDoc} from './doctypes/types.js'; // Button.doc.{ts,mjs}
+export type {HookDoc} from './doctypes/types.js'; // useToast.doc.{ts,mjs}
+export type {FunctionDoc} from './doctypes/types.js'; // search.doc.mjs (hook | api)
+export type {ReferenceDoc} from './doctypes/types.js'; // theming.doc.{ts,mjs}
+export type {TemplateDoc} from './doctypes/types.js'; // Foo.template.{ts,mjs}
+export type {SchemaDoc} from './doctypes/types.js'; // config.doc.mjs (object shape)
+export type {CommandDoc} from './doctypes/types.js'; // search.doc.mjs (CLI command)
+export type {EnumDoc} from './doctypes/types.js'; // error-codes.doc.mjs (vocabulary)
+export type {NamespaceDoc} from './doctypes/types.js'; // cli.doc.mjs (hierarchy)
+export type {AstryxConfig} from './config/type.js'; // astryx.config.{ts,mjs}
+export type {DebugEvent} from './debug/type.js'; // one recorded CLI run
+export type {AstryxIntegration} from './integration/type.js'; // astryx.integration.{ts,mjs}
export type {
GapReportHandler,
GapReportHandlerContext,
@@ -42,8 +42,8 @@ export type {
GapReportCategory,
GapReportTarget,
GapReportHandlerReceipt,
-} from './gap-report/type'; // gap-report handler contract
-export type {AstryxCodemod, AstryxConfigCodemod} from './codemod/type'; // codemods/*
+} from './gap-report/type.js'; // gap-report handler contract
+export type {AstryxCodemod, AstryxConfigCodemod} from './codemod/type.js'; // codemods/*
// ═══════════════════════════════════════════════════════════════════════
// PARSERS — the CLI's load boundary (types come from each parser's JSDoc).
@@ -87,7 +87,7 @@ export type {
AuthoredDocSnapshot,
AuthoredDocSource,
AuthoredDocEntry,
-} from './identity/type';
+} from './identity/type.js';
export type {
// shared graph
AuthoredDocKind,
@@ -151,8 +151,8 @@ export type {
CommandExampleDoc,
// enum
EnumMemberDoc,
-} from './doctypes/types';
-export type {PostCodemodHook, DebugConfig} from './config/type';
+} from './doctypes/types.js';
+export type {PostCodemodHook, DebugConfig} from './config/type.js';
export type {
// debug
DebugSchemaVersion,
@@ -165,11 +165,11 @@ export type {
DebugEventEnv,
DebugEventProject,
DebugEventHandler,
-} from './debug/type';
+} from './debug/type.js';
export type {
AstryxCodemodDef,
AstryxConfigCodemodDef,
AstryxCodemodFile,
AstryxCodemodApi,
AstryxCodemodTransform,
-} from './codemod/type';
+} from './codemod/type.js';
diff --git a/packages/cli/authoring/integration/parse.mjs b/packages/cli/authoring/integration/parse.mjs
index 498df67f1f..625f082a1a 100644
--- a/packages/cli/authoring/integration/parse.mjs
+++ b/packages/cli/authoring/integration/parse.mjs
@@ -14,7 +14,7 @@
import {formatZodError} from '../_shared/errors.mjs';
import {integrationSchema} from './schema.mjs';
-/** @typedef {import('./type').AstryxIntegration} AstryxIntegration */
+/** @typedef {import('./type.js').AstryxIntegration} AstryxIntegration */
/**
* Validate an unknown value as an Astryx integration manifest, or throw.
diff --git a/packages/cli/authoring/integration/schema.mjs b/packages/cli/authoring/integration/schema.mjs
index f00728a2df..eaa367456d 100644
--- a/packages/cli/authoring/integration/schema.mjs
+++ b/packages/cli/authoring/integration/schema.mjs
@@ -16,7 +16,7 @@
import {z} from 'zod';
import {formatZodError} from '../_shared/errors.mjs';
-/** @typedef {import('./type').AstryxIntegration} AstryxIntegration */
+/** @typedef {import('./type.js').AstryxIntegration} AstryxIntegration */
const MAX_AGENT_DOC_LINES = 8;
const MAX_AGENT_DOC_LINE_CODE_POINTS = 240;
@@ -121,8 +121,8 @@ export function parseAgentDocsField(input, label) {
/**
* Compile-time drift-lock: sealed schema must infer exactly {@link AstryxIntegration}.
*
- * @typedef {import('../_shared/contract').Expect<
- * import('../_shared/contract').Equal<z.infer<typeof integrationSchema>, AstryxIntegration>
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').Equal<z.infer<typeof integrationSchema>, AstryxIntegration>
* >} _IntegrationDriftLock
*/
diff --git a/packages/cli/authoring/integration/type.ts b/packages/cli/authoring/integration/type.ts
index 573a589add..1e96a7e5be 100644
--- a/packages/cli/authoring/integration/type.ts
+++ b/packages/cli/authoring/integration/type.ts
@@ -66,4 +66,4 @@ export type {
GapReportCategory,
GapReportTarget,
GapReportHandlerReceipt,
-} from '../gap-report/type';
+} from '../gap-report/type.js';
diff --git a/packages/cli/foundation/discovery/authoring-self-docs.test.mjs b/packages/cli/foundation/discovery/authoring-self-docs.test.mjs
index 58233f23cd..a7643c45a0 100644
--- a/packages/cli/foundation/discovery/authoring-self-docs.test.mjs
+++ b/packages/cli/foundation/discovery/authoring-self-docs.test.mjs
@@ -9,7 +9,14 @@ import {
buildAuthoringTopic,
discoverAuthoringSelfDocSources,
} from './authoring-self-docs.mjs';
-import {problemsInTopic} from './docs-discovery.mjs';
+import {
+ GRAPH_BLOCK_TYPES,
+ GRAPH_ONLY_FIELDS,
+ problemsInTopic,
+} from './docs-discovery.mjs';
+import {doc as graphFieldsDoc} from '../../authoring/doctypes/base/graph-fields.doc.mjs';
+import {doc as namespaceDoc} from '../../authoring/doctypes/namespace/namespace.doc.mjs';
+import {doc as referenceDoc} from '../../authoring/doctypes/reference/reference.doc.mjs';
import {docs} from '../../api/docs/docs.mjs';
const SLOW = 60_000;
@@ -37,14 +44,58 @@ describe('authoring self-docs', () => {
expect(topic.sections).toHaveLength(AUTHORING_SELF_DOCS.length);
});
- it('is readable progressively through the docs API', async () => {
- const index = await docs('authoring', undefined, {index: true});
- expect(index.type).toBe('docs.index');
- expect(index.data.sections.map(s => s.id)).toContain('integration');
- const section = await docs('authoring', 'integration');
- expect(section.data.title).toBe('Astryx Integration');
- expect(section.data.content.some(block => block.type === 'table')).toBe(true);
- }, SLOW);
+ it(
+ 'is readable progressively through the docs API',
+ async () => {
+ const index = await docs('authoring', undefined, {index: true});
+ expect(index.type).toBe('docs.index');
+ expect(index.data.sections.map(s => s.id)).toContain('integration');
+ const section = await docs('authoring', 'integration');
+ expect(section.data.title).toBe('Astryx Integration');
+ expect(section.data.content.some(block => block.type === 'table')).toBe(
+ true,
+ );
+ },
+ SLOW,
+ );
+});
+
+describe('what the authoring docs say about the unbuilt docs graph', () => {
+ it('marks exactly the fields topic loading rejects as not read yet', () => {
+ const notReadYet = graphFieldsDoc.fields
+ .filter(field => /Not read yet/.test(field.description))
+ .map(field => field.name);
+ expect(notReadYet.sort()).toEqual([...GRAPH_ONLY_FIELDS].sort());
+ for (const field of graphFieldsDoc.fields) {
+ if (notReadYet.includes(field.name)) {
+ expect(field.description).toMatch(/fails to load/);
+ }
+ }
+ expect(graphFieldsDoc.description).toMatch(/not built yet/);
+ });
+
+ it('says a topic using a graph block fails to load', () => {
+ const content = referenceDoc.fields
+ .flatMap(field => [field, ...(field.fields ?? [])])
+ .find(field => field.name === 'sections[].content');
+ for (const type of GRAPH_BLOCK_TYPES) {
+ expect(content.description).toContain(type);
+ }
+ expect(content.description).toMatch(/fails to load/);
+ });
+
+ it('says namespace docs are not loaded yet', () => {
+ expect(namespaceDoc.description).toMatch(/Not loaded yet/);
+ expect(
+ problemsInTopic({
+ ...namespaceDoc.examples?.[0],
+ type: 'namespace',
+ name: 'x',
+ }),
+ ).toEqual([
+ '"x" is a namespace doc. Only the docs graph reads namespace docs, and it is not built yet; remove this file from the docs directory.',
+ ]);
+ });
});
describe('auditAuthoringSelfDocs', () => {
@@ -68,17 +119,25 @@ describe('auditAuthoringSelfDocs', () => {
path.join(root, 'kept', 'forgotten.doc.mjs'),
"export const doc = {name: 'forgotten', description: 'Not listed.'};\n",
);
- const audit = await auditAuthoringSelfDocs({root, sources: ['kept/kept.doc.mjs']});
+ const audit = await auditAuthoringSelfDocs({
+ root,
+ sources: ['kept/kept.doc.mjs'],
+ });
expect(audit.unreachable).toEqual(['kept/forgotten.doc.mjs']);
});
it('reports a self-doc that fails to load instead of throwing', async () => {
- fs.writeFileSync(path.join(root, 'kept', 'broken.doc.mjs'), 'export const doc = {;\n');
+ fs.writeFileSync(
+ path.join(root, 'kept', 'broken.doc.mjs'),
+ 'export const doc = {;\n',
+ );
const audit = await auditAuthoringSelfDocs({
root,
sources: ['kept/kept.doc.mjs', 'kept/broken.doc.mjs'],
});
- expect(audit.failed.map(entry => entry.source)).toEqual(['kept/broken.doc.mjs']);
+ expect(audit.failed.map(entry => entry.source)).toEqual([
+ 'kept/broken.doc.mjs',
+ ]);
expect(audit.sections).toBe(1);
});
diff --git a/packages/cli/foundation/discovery/docs-discovery.mjs b/packages/cli/foundation/discovery/docs-discovery.mjs
index 59af1b7d71..ba6f3bf068 100644
--- a/packages/cli/foundation/discovery/docs-discovery.mjs
+++ b/packages/cli/foundation/discovery/docs-discovery.mjs
@@ -138,7 +138,14 @@ const BLOCK_FIELDS = {
};
/** Blocks that are valid authoring but require the compiled graph renderer. */
-const GRAPH_BLOCK_TYPES = new Set(['workflow', 'collection', 'reference']);
+export const GRAPH_BLOCK_TYPES = new Set([
+ 'workflow',
+ 'collection',
+ 'reference',
+]);
+
+/** Doc fields only the docs graph reads; a topic that sets one fails to load. */
+export const GRAPH_ONLY_FIELDS = ['placement', 'aliases', 'audience'];
/**
* Fields a block kind may carry but does not need. Kept per kind rather than
@@ -176,6 +183,13 @@ const SECTION_FIELDS = ['id', 'title', 'category', 'content', 'previewType'];
* @returns {string[]} problems, each already pointed at a place in the doc
*/
export function problemsInTopic(doc) {
+ // A namespace doc is valid authoring that only the docs graph reads. Said
+ // plainly, instead of as the topic fields it does not have.
+ if (doc?.type === 'namespace') {
+ return [
+ `"${doc.name}" is a namespace doc. Only the docs graph reads namespace docs, and it is not built yet; remove this file from the docs directory.`,
+ ];
+ }
/** @type {string[]} */
const problems = [];
for (const field of ['name', 'title', 'description']) {
@@ -188,7 +202,7 @@ export function problemsInTopic(doc) {
`name: "${doc.name}" is not URL-safe. A topic name is its CLI argument and its docsite path, so it may hold only letters, digits, "_" and "-".`,
);
}
- for (const field of ['placement', 'aliases', 'audience']) {
+ for (const field of GRAPH_ONLY_FIELDS) {
if (doc?.[field] != null) {
problems.push(
`${field}: requires the compiled graph reader and is not supported by legacy topic readers`,
diff --git a/packages/cli/foundation/discovery/docs-discovery.test.mjs b/packages/cli/foundation/discovery/docs-discovery.test.mjs
index afdc71814e..d8e4b9e5c3 100644
--- a/packages/cli/foundation/discovery/docs-discovery.test.mjs
+++ b/packages/cli/foundation/discovery/docs-discovery.test.mjs
@@ -182,6 +182,26 @@ describe('discoverIntegrationDocs', () => {
expect(records).toEqual([]);
expect(errors[0].message).toContain('requires the compiled graph renderer');
});
+
+ it('names a namespace doc instead of listing topic fields it lacks', async () => {
+ const {records, errors} = await discoverIntegrationDocs(
+ integration('@acme/namespace', {
+ 'guides.doc.mjs': {
+ type: 'namespace',
+ name: 'guides',
+ title: 'Guides',
+ summary: 'Every guide.',
+ slots: {guides: {title: 'Guides', accepts: {kinds: ['generic']}}},
+ },
+ }),
+ );
+ expect(records).toEqual([]);
+ expect(errors).toHaveLength(1);
+ expect(errors[0].message).toContain(
+ '"guides" is a namespace doc. Only the docs graph reads namespace docs',
+ );
+ expect(errors[0].message).not.toContain('sections:');
+ });
});
describe('problemsInTopic', () => {
@@ -500,7 +520,10 @@ describe('problemsInTopic section keys', () => {
name: 'keys',
title: 'Keys',
description: 'Section keys.',
- sections: sections.map(s => ({content: [{type: 'prose', text: 'x'}], ...s})),
+ sections: sections.map(s => ({
+ content: [{type: 'prose', text: 'x'}],
+ ...s,
+ })),
});
it('rejects two sections that derive the same key', () => {
@@ -512,18 +535,18 @@ describe('problemsInTopic section keys', () => {
});
it('rejects an unsafe id', () => {
- expect(problemsInTopic(doc([{id: 'Quick Start', title: 'Quick Start'}]))).toEqual(
- [expect.stringContaining('is not a stable key')],
- );
+ expect(
+ problemsInTopic(doc([{id: 'Quick Start', title: 'Quick Start'}])),
+ ).toEqual([expect.stringContaining('is not a stable key')]);
});
it('rejects a title no key derives from, unless it has an id', () => {
expect(problemsInTopic(doc([{title: '亮/暗模式'}]))).toEqual([
expect.stringContaining('Give the section an id'),
]);
- expect(problemsInTopic(doc([{id: 'light-dark', title: '亮/暗模式'}]))).toEqual(
- [],
- );
+ expect(
+ problemsInTopic(doc([{id: 'light-dark', title: '亮/暗模式'}])),
+ ).toEqual([]);
});
});
@@ -535,12 +558,17 @@ describe('mergeTopic by section key', () => {
{title: 'Light/Dark Mode', content: [{type: 'prose', text: 'base'}]},
],
};
- const titles = doc => doc.sections.map(s => [s.id ?? null, s.title, s.content[0].text]);
+ const titles = doc =>
+ doc.sections.map(s => [s.id ?? null, s.title, s.content[0].text]);
it('replaces the section whose derived key an extension id names', () => {
const merged = mergeTopic(base, {
sections: [
- {id: 'quick-start', title: 'Quick Start with Acme', content: [{type: 'prose', text: 'acme'}]},
+ {
+ id: 'quick-start',
+ title: 'Quick Start with Acme',
+ content: [{type: 'prose', text: 'acme'}],
+ },
],
});
expect(titles(merged)).toEqual([
@@ -551,7 +579,9 @@ describe('mergeTopic by section key', () => {
it('replaces the section a title variant derives the same key as', () => {
const merged = mergeTopic(base, {
- sections: [{title: 'Light-Dark Mode', content: [{type: 'prose', text: 'acme'}]}],
+ sections: [
+ {title: 'Light-Dark Mode', content: [{type: 'prose', text: 'acme'}]},
+ ],
});
expect(titles(merged)).toEqual([
[null, 'Quick Start', 'base'],
@@ -561,7 +591,13 @@ describe('mergeTopic by section key', () => {
it('prefers the key over a legacy title for an extension with an id', () => {
const merged = mergeTopic(base, {
- sections: [{id: 'light-dark-mode', title: 'Quick Start', content: [{type: 'prose', text: 'acme'}]}],
+ sections: [
+ {
+ id: 'light-dark-mode',
+ title: 'Quick Start',
+ content: [{type: 'prose', text: 'acme'}],
+ },
+ ],
});
expect(titles(merged)).toEqual([
[null, 'Quick Start', 'base'],
diff --git a/packages/cli/test/authoring-self-docs-match-types.test.mjs b/packages/cli/test/authoring-self-docs-match-types.test.mjs
new file mode 100644
index 0000000000..f801d1c22e
--- /dev/null
+++ b/packages/cli/test/authoring-self-docs-match-types.test.mjs
@@ -0,0 +1,257 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx docs authoring` must describe the published authoring types
+ * exactly. For each self-doc this checks, against the TypeScript types
+ * themselves: every field of the type is documented, every documented field
+ * exists, each documented `type` string is the same type as the real field,
+ * and each `required` flag matches whether the field is required in every
+ * variant of the type. Graph fields may be left to the graph-fields self-doc.
+ */
+
+import * as path from 'node:path';
+import {fileURLToPath, pathToFileURL} from 'node:url';
+import ts from 'typescript';
+import {describe, expect, it} from 'vitest';
+
+const CLI = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const SUBPATHS = [
+ 'authoring',
+ 'doc',
+ 'config',
+ 'integration',
+ 'codemod',
+ 'debug',
+];
+const GRAPH_FIELDS = ['placement', 'aliases', 'audience'];
+
+/** Each self-doc and the published type (or union) it describes. */
+const SELF_DOCS = {
+ 'doctypes/base/graph-fields.doc.mjs': 'AuthoredDocGraphFields',
+ 'doctypes/component/component.doc.mjs': 'ComponentDoc',
+ 'doctypes/hook/hook.doc.mjs': 'HookDoc',
+ 'doctypes/function/function.doc.mjs': 'FunctionDoc',
+ 'doctypes/reference/reference.doc.mjs': 'ReferenceDoc',
+ 'doctypes/template/template.doc.mjs': 'TemplateDoc',
+ 'doctypes/schema/schema.doc.mjs': 'SchemaDoc',
+ 'doctypes/command/command.doc.mjs': 'CommandDoc',
+ 'doctypes/enum/enum.doc.mjs': 'EnumDoc',
+ 'doctypes/namespace/namespace.doc.mjs': 'NamespaceDoc',
+ 'config/config.doc.mjs': 'AstryxConfig',
+ 'integration/integration.doc.mjs': 'AstryxIntegration',
+ // The codemod types describe a loaded codemod, whose `isOptional` has its
+ // default; the self-doc describes what an author writes.
+ 'codemod/codemod.doc.mjs':
+ "(Omit<AstryxCodemod, 'isOptional'> & {isOptional?: boolean}) | (Omit<AstryxConfigCodemod, 'isOptional'> & {isOptional?: boolean})",
+};
+
+const config = ts.getParsedCommandLineOfConfigFile(
+ path.join(CLI, 'tsconfig.strict.json'),
+ {},
+ {...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {}},
+);
+const options = {...config.options, noEmit: true, skipLibCheck: true};
+const VIRTUAL = path.join(CLI, 'test', '__self_docs_match_types__.ts');
+
+/** Type-check `source` as a file inside the package; returns its diagnostics. */
+function check(source) {
+ const host = ts.createCompilerHost(options);
+ const getSourceFile = host.getSourceFile.bind(host);
+ host.getSourceFile = (file, version) =>
+ file === VIRTUAL
+ ? ts.createSourceFile(file, source, version)
+ : getSourceFile(file, version);
+ const fileExists = host.fileExists.bind(host);
+ host.fileExists = file => file === VIRTUAL || fileExists(file);
+ const program = ts.createProgram([VIRTUAL], options, host);
+ return {
+ program,
+ diagnostics: ts.getPreEmitDiagnostics(
+ program,
+ program.getSourceFile(VIRTUAL),
+ ),
+ };
+}
+
+/** Every type name the authoring subpaths export, for unqualified doc strings. */
+function exportedTypeNames() {
+ const probe = SUBPATHS.map(
+ (s, i) => `import type * as S${i} from '@astryxdesign/cli/${s}';`,
+ ).join('\n');
+ const {program} = check(`${probe}\nexport {};`);
+ const checker = program.getTypeChecker();
+ const names = new Map();
+ for (const [i, subpath] of SUBPATHS.entries()) {
+ const file = program.getSourceFile(VIRTUAL);
+ const decl = file.statements[i];
+ const sym = checker.getSymbolAtLocation(decl.moduleSpecifier);
+ if (!sym) continue;
+ for (const e of checker.getExportsOfModule(sym)) {
+ const target =
+ e.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(e) : e;
+ if (
+ target.flags &
+ (ts.SymbolFlags.Type |
+ ts.SymbolFlags.Interface |
+ ts.SymbolFlags.TypeAlias) &&
+ !names.has(e.name)
+ ) {
+ names.set(e.name, subpath);
+ }
+ }
+ }
+ return names;
+}
+
+const NAMES = exportedTypeNames();
+const PRELUDE = [
+ ...[...NAMES].map(
+ ([name, subpath]) =>
+ `import type {${name}} from '@astryxdesign/cli/${subpath}';`,
+ ),
+ 'type Expect<T extends true> = T;',
+ 'type Same<X, Y> = [X] extends [Y] ? ([Y] extends [X] ? true : false) : false;',
+ 'type Field<T, K extends PropertyKey> = T extends unknown ? (K extends keyof T ? T[K] : never) : never;',
+ 'type Req<T, K extends PropertyKey> = T extends unknown ? (K extends keyof T ? ({} extends Pick<T, K> ? false : true) : false) : never;',
+ 'type AlwaysRequired<T, K extends PropertyKey> = [Req<T, K>] extends [true] ? true : false;',
+ 'type Keys<T> = T extends unknown ? keyof T : never;',
+ 'type Defined<T> = unknown extends T ? T : NonNullable<T>;',
+].join('\n');
+
+/**
+ * Each documented field with the steps from the root type to it. A field's
+ * `fields` are its properties when named `<field>.x` or `<field>[].x`, and its
+ * parameters, in order, when it is a function and they are named on their own
+ * (as `transform` documents `file` and `api`).
+ *
+ * @returns {{field: any, steps: Array<{prop: string} | {elem: true} | {param: number}>}[]}
+ */
+function flatten(fields, prefix = '', base = [], out = []) {
+ let param = 0;
+ for (const field of fields) {
+ /** @type {Array<{prop: string} | {elem: true} | {param: number}>} */
+ let steps;
+ let name = field.name;
+ if (
+ prefix &&
+ !name.startsWith(`${prefix}.`) &&
+ !name.startsWith(`${prefix}[].`)
+ ) {
+ steps = [...base, {param: param++}];
+ } else {
+ if (prefix)
+ name = name.slice(
+ name.startsWith(`${prefix}[].`)
+ ? prefix.length + 3
+ : prefix.length + 1,
+ );
+ steps = [...base];
+ if (prefix && field.name.startsWith(`${prefix}[].`))
+ steps.push({elem: true});
+ for (const [i, segment] of name.split('.').entries()) {
+ steps.push({prop: segment.replace(/\[\]$/, '')});
+ if (segment.endsWith('[]') && i < name.split('.').length - 1)
+ steps.push({elem: true});
+ }
+ }
+ out.push({field, steps});
+ if (field.fields) flatten(field.fields, field.name, steps, out);
+ }
+ return out;
+}
+
+/** The type expression for the steps before the last one. */
+function parentOf(root, steps) {
+ let expr = `(${root})`;
+ for (const step of steps.slice(0, -1)) {
+ if ('prop' in step) expr = `NonNullable<Field<${expr}, '${step.prop}'>>`;
+ else if ('elem' in step) expr = `${expr}[number]`;
+ else expr = `Parameters<NonNullable<${expr}>>[${step.param}]`;
+ }
+ return expr;
+}
+
+describe('astryx docs authoring matches the published types', () => {
+ it.each(Object.entries(SELF_DOCS))(
+ '%s',
+ async (file, root) => {
+ const {doc} = await import(
+ pathToFileURL(path.join(CLI, 'authoring', file)).href
+ );
+ const fields = flatten(doc.fields);
+ /** @type {string[]} */
+ const lines = [PRELUDE];
+ /** @type {Map<number, string>} */
+ const meaning = new Map();
+ const line = (text, what) => {
+ lines.push(text);
+ meaning.set(lines.join('\n').split('\n').length - 1, what);
+ };
+ for (const [i, {field, steps}] of fields.entries()) {
+ const parent = parentOf(root, steps);
+ const last = steps.at(-1);
+ if ('param' in last) {
+ line(
+ `type Type${i} = Expect<Same<(${field.type}), Parameters<NonNullable<${parent}>>[${last.param}]>>;`,
+ `\`${field.name}\` is documented as \`${field.type}\`, which is not its type`,
+ );
+ continue;
+ }
+ line(
+ `type Has${i} = Expect<'${last.prop}' extends Keys<${parent}> ? true : false>;`,
+ `\`${field.name}\` is documented but is not a field of ${root}`,
+ );
+ line(
+ `type Type${i} = Expect<Same<(${field.type}), Defined<Field<${parent}, '${last.prop}'>>>>;`,
+ `\`${field.name}\` is documented as \`${field.type}\`, which is not its type`,
+ );
+ line(
+ `type Req${i} = Expect<Same<AlwaysRequired<${parent}, '${last.prop}'>, ${field.required ? 'true' : 'false'}>>;`,
+ `\`${field.name}\` is documented as ${field.required ? 'required' : 'optional'}, which does not match the type`,
+ );
+ }
+ const documented = new Set(
+ fields
+ .filter(({steps}) => steps.length === 1)
+ .map(({field}) => field.name),
+ );
+ const allowedMissing = file.endsWith('graph-fields.doc.mjs')
+ ? []
+ : GRAPH_FIELDS;
+ const topKeys = `Exclude<Keys<(${root})>, ${[...documented, ...allowedMissing].map(n => `'${n}'`).join(' | ') || 'never'}>`;
+ line(
+ `type Undocumented = Expect<Same<${topKeys}, never>>;`,
+ `${root} has fields the self-doc does not list`,
+ );
+ const source = lines.join('\n') + '\nexport {};\n';
+ const {diagnostics, program} = check(source);
+ const problems = diagnostics.map(d => {
+ const {line: at} = ts.getLineAndCharacterOfPosition(
+ d.file,
+ d.start ?? 0,
+ );
+ const what =
+ meaning.get(at) ??
+ ts.flattenDiagnosticMessageText(d.messageText, ' ');
+ if (what.endsWith('does not list')) {
+ const checker = program.getTypeChecker();
+ const alias = program
+ .getSourceFile(VIRTUAL)
+ .statements.find(
+ s =>
+ ts.isTypeAliasDeclaration(s) && s.name.text === 'Undocumented',
+ );
+ const missing = checker.typeToString(
+ checker.getTypeAtLocation(
+ alias.type.typeArguments[0].typeArguments[0],
+ ),
+ );
+ return `${what}: ${missing}`;
+ }
+ return what;
+ });
+ expect(problems, `${file}`).toEqual([]);
+ },
+ 60_000,
+ );
+});
diff --git a/packages/cli/test/authoring-types.test.mjs b/packages/cli/test/authoring-types.test.mjs
new file mode 100644
index 0000000000..632565f468
--- /dev/null
+++ b/packages/cli/test/authoring-types.test.mjs
@@ -0,0 +1,69 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The typed example docs in test/authoring-types load. The authoring
+ * contract typecheck proves each one matches its published type; this proves
+ * the CLI loads what the type allows, for every doc kind in both styles.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath, pathToFileURL} from 'node:url';
+import {describe, expect, it} from 'vitest';
+import {parseDoc} from '../authoring/doctypes/parse.mjs';
+import {AuthoredDocKindSchema} from '../authoring/doctypes/_schema.mjs';
+import {problemsInTopic} from '../foundation/discovery/docs-discovery.mjs';
+import * as satisfiesDocs from './authoring-types/all-kinds.doc.ts';
+
+const DIR = path.join(
+ path.dirname(fileURLToPath(import.meta.url)),
+ 'authoring-types',
+);
+const KINDS = AuthoredDocKindSchema.options;
+
+const jsdocDocs = await Promise.all(
+ fs
+ .readdirSync(DIR)
+ .filter(file => file.endsWith('.doc.mjs'))
+ .sort()
+ .map(async file => ({
+ file,
+ doc: (await import(pathToFileURL(path.join(DIR, file)).href)).docs,
+ })),
+);
+
+/** @param {any} doc */
+function load(doc) {
+ const parsed = parseDoc(doc, 'fixture');
+ // A reference doc must also load as a topic, not only parse.
+ if (doc.type === 'generic') expect(problemsInTopic(parsed)).toEqual([]);
+ return parsed;
+}
+
+describe('typed example docs', () => {
+ it.each(jsdocDocs.map(({file, doc}) => [file, doc]))(
+ 'loads the JSDoc example %s',
+ (_, doc) => {
+ expect(() => load(doc)).not.toThrow();
+ },
+ );
+
+ it.each(
+ Object.entries(satisfiesDocs).filter(([name]) => name !== 'missingUsage'),
+ )('loads the satisfies example %s', (_, doc) => {
+ expect(() => load(doc)).not.toThrow();
+ });
+
+ it('covers every doc kind in both styles', () => {
+ const kindsOf = (/** @type {any[]} */ docs) =>
+ new Set(docs.map(doc => doc.type).filter(Boolean));
+ const jsdoc = kindsOf(jsdocDocs.map(({doc}) => doc));
+ const typed = kindsOf(Object.values(satisfiesDocs));
+ for (const kind of KINDS) {
+ expect(jsdoc, `no JSDoc example for ${kind}`).toContain(kind);
+ if (kind !== 'namespace') {
+ expect(typed, `no satisfies example for ${kind}`).toContain(kind);
+ }
+ }
+ });
+});
diff --git a/packages/cli/test/authoring-types/all-kinds.doc.ts b/packages/cli/test/authoring-types/all-kinds.doc.ts
new file mode 100644
index 0000000000..3c0405d7aa
--- /dev/null
+++ b/packages/cli/test/authoring-types/all-kinds.doc.ts
@@ -0,0 +1,108 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Every authored doc kind written as TypeScript with `satisfies`: no builder
+ * call, only the published type. The JSDoc twins are the `*.doc.mjs` files
+ * beside this one.
+ */
+
+import type {
+ CommandDoc,
+ ComponentDoc,
+ EnumDoc,
+ FunctionDoc,
+ HookDoc,
+ ReferenceDoc,
+ SchemaDoc,
+ TemplateDoc,
+} from '@astryxdesign/cli/authoring';
+import type {BlockTemplateDoc, PageTemplateDoc} from '@astryxdesign/cli/doc';
+
+export const component = {
+ type: 'component',
+ name: 'Badge',
+ displayName: 'Badge',
+ props: [{name: 'label', type: 'string', description: 'Text inside.'}],
+ usage: {description: 'Show a short status.'},
+} satisfies ComponentDoc;
+
+export const componentGroup = {
+ type: 'component',
+ name: 'Tabs',
+ displayName: 'Tabs',
+ usage: {description: 'Switch between views.'},
+ components: [{name: 'Tab'}],
+} satisfies ComponentDoc;
+
+export const hook = {
+ type: 'function',
+ name: 'useToast',
+ displayName: 'useToast',
+ params: [],
+ returns: [{name: 'show', type: '() => void', description: 'Shows one.'}],
+ usage: {description: 'Show a message that dismisses itself.'},
+} satisfies HookDoc;
+
+export const fn = {
+ type: 'function',
+ name: 'search',
+ displayName: 'search()',
+ kind: 'api',
+ params: [{name: 'query', type: 'string', description: 'What to find.'}],
+ returns: [{type: 'Promise<SearchResponse>', description: 'Matches.'}],
+} satisfies FunctionDoc;
+
+export const reference = {
+ type: 'generic',
+ name: 'deploying',
+ title: 'Deploying',
+ description: 'Ship an app that uses Astryx.',
+ sections: [
+ {title: 'Build', content: [{type: 'prose', text: 'Build the theme.'}]},
+ ],
+} satisfies ReferenceDoc;
+
+export const page = {
+ type: 'page',
+ name: 'settings-page',
+ displayName: 'Settings page',
+} satisfies PageTemplateDoc satisfies TemplateDoc;
+
+export const block = {
+ type: 'block',
+ name: 'badge-counts',
+ displayName: 'Badge counts',
+ aspectRatio: 1.5,
+} satisfies BlockTemplateDoc satisfies TemplateDoc;
+
+export const schema = {
+ type: 'schema',
+ name: 'widget-config',
+ displayName: 'Widget config',
+ description: 'Options a widget integration reads.',
+ fields: [{name: 'size', type: "'sm' | 'md'", description: 'Widget size.'}],
+} satisfies SchemaDoc;
+
+export const command = {
+ type: 'command',
+ name: 'widget sync',
+ displayName: 'astryx widget sync',
+ summary: 'Copy widget assets into the app.',
+} satisfies CommandDoc;
+
+export const enumDoc = {
+ type: 'enum',
+ name: 'widget-status',
+ displayName: 'Widget status',
+ description: 'Every state a widget reports.',
+ members: [{value: 'ready', description: 'Loaded and usable.'}],
+} satisfies EnumDoc;
+
+// A required field left out is a type error, not a runtime surprise.
+export const missingUsage = {
+ type: 'component',
+ name: 'Badge',
+ displayName: 'Badge',
+ props: [],
+ // @ts-expect-error usage is required on a component doc
+} satisfies ComponentDoc;
diff --git a/packages/cli/test/authoring-types/block.doc.mjs b/packages/cli/test/authoring-types/block.doc.mjs
new file mode 100644
index 0000000000..c527e9aab7
--- /dev/null
+++ b/packages/cli/test/authoring-types/block.doc.mjs
@@ -0,0 +1,12 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const docs = {
+ type: 'block',
+ name: 'badge-counts',
+ displayName: 'Badge counts',
+ description: 'Badges that show unread counts.',
+ exampleFor: 'Badge',
+ aspectRatio: 1.5,
+ componentsUsed: ['Badge'],
+};
diff --git a/packages/cli/test/authoring-types/command.doc.mjs b/packages/cli/test/authoring-types/command.doc.mjs
new file mode 100644
index 0000000000..7dd0b1d949
--- /dev/null
+++ b/packages/cli/test/authoring-types/command.doc.mjs
@@ -0,0 +1,15 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */
+export const docs = {
+ type: 'command',
+ name: 'widget sync',
+ displayName: 'astryx widget sync',
+ summary: 'Copy widget assets into the app.',
+ args: [{name: 'dir', description: 'Where to copy them.', required: true}],
+ options: [
+ {flag: '--dry-run', description: 'Show what would change.', default: false},
+ ],
+ examples: [{label: 'Preview', cli: 'astryx widget sync public --dry-run'}],
+ exitCodes: [{code: 1, when: 'A widget asset is missing.'}],
+};
diff --git a/packages/cli/test/authoring-types/component-group.doc.mjs b/packages/cli/test/authoring-types/component-group.doc.mjs
new file mode 100644
index 0000000000..7857836228
--- /dev/null
+++ b/packages/cli/test/authoring-types/component-group.doc.mjs
@@ -0,0 +1,25 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+export const docs = {
+ type: 'component',
+ name: 'Tabs',
+ displayName: 'Tabs',
+ category: 'Navigation',
+ usage: {description: 'Switch between views that share one place.'},
+ components: [
+ {
+ name: 'Tabs',
+ displayName: 'Tabs',
+ description: 'The tab list and its panels.',
+ props: [
+ {
+ name: 'value',
+ type: 'string',
+ description: 'The selected tab.',
+ },
+ ],
+ },
+ {name: 'Tab'},
+ ],
+};
diff --git a/packages/cli/test/authoring-types/component-unstamped.doc.mjs b/packages/cli/test/authoring-types/component-unstamped.doc.mjs
new file mode 100644
index 0000000000..b2df7e4ef2
--- /dev/null
+++ b/packages/cli/test/authoring-types/component-unstamped.doc.mjs
@@ -0,0 +1,18 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+// Every component shipped today is written this way: no `type` field.
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+export const docs = {
+ name: 'Divider',
+ displayName: 'Divider',
+ category: 'Layout',
+ props: [
+ {
+ name: 'orientation',
+ type: "'horizontal' | 'vertical'",
+ description: 'Direction of the rule.',
+ default: "'horizontal'",
+ },
+ ],
+ usage: {description: 'Separate groups of content.'},
+};
diff --git a/packages/cli/test/authoring-types/component.doc.mjs b/packages/cli/test/authoring-types/component.doc.mjs
new file mode 100644
index 0000000000..ef5ffd9033
--- /dev/null
+++ b/packages/cli/test/authoring-types/component.doc.mjs
@@ -0,0 +1,35 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+export const docs = {
+ type: 'component',
+ name: 'Badge',
+ displayName: 'Badge',
+ category: 'Feedback & Status',
+ keywords: ['badge', 'count', 'status'],
+ props: [
+ {
+ name: 'label',
+ type: 'string',
+ description: 'Text inside the badge.',
+ required: true,
+ },
+ {
+ name: 'variant',
+ type: "'neutral' | 'accent'",
+ description: 'Color treatment.',
+ default: "'neutral'",
+ },
+ ],
+ theming: {targets: [{className: 'astryx-badge', states: ['hover']}]},
+ usage: {
+ description: 'Show a short status or count next to other content.',
+ bestPractices: [
+ {guidance: true, description: 'Keep the label to one or two words.'},
+ ],
+ anatomy: [
+ {name: 'Container', required: true, description: 'The pill shape.'},
+ ],
+ },
+ examples: [{label: 'Basic', code: '<Badge label="New" />'}],
+};
diff --git a/packages/cli/test/authoring-types/enum.doc.mjs b/packages/cli/test/authoring-types/enum.doc.mjs
new file mode 100644
index 0000000000..2270cef658
--- /dev/null
+++ b/packages/cli/test/authoring-types/enum.doc.mjs
@@ -0,0 +1,17 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').EnumDoc} */
+export const docs = {
+ type: 'enum',
+ name: 'widget-status',
+ displayName: 'Widget status',
+ description: 'Every state a widget reports.',
+ members: [
+ {value: 'ready', description: 'Loaded and usable.'},
+ {
+ value: 'stale',
+ description: 'Needs a sync.',
+ deprecated: 'Use needs-sync.',
+ },
+ ],
+};
diff --git a/packages/cli/test/authoring-types/function.doc.mjs b/packages/cli/test/authoring-types/function.doc.mjs
new file mode 100644
index 0000000000..67dd8d7b50
--- /dev/null
+++ b/packages/cli/test/authoring-types/function.doc.mjs
@@ -0,0 +1,23 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const docs = {
+ type: 'function',
+ name: 'search',
+ displayName: 'search()',
+ kind: 'api',
+ summary: 'Search components, hooks, templates, and docs.',
+ importPath: '@astryxdesign/cli/api',
+ signature: 'search(query: string): Promise<SearchResponse>',
+ params: [
+ {
+ name: 'query',
+ type: 'string',
+ description: 'What to look for.',
+ required: true,
+ },
+ ],
+ returns: [{type: 'Promise<SearchResponse>', description: 'Ranked matches.'}],
+ throws: [{code: 'ERR_INVALID_ARGUMENT', when: 'The query is empty.'}],
+ examples: [{label: 'Find a component', code: "await search('button');"}],
+};
diff --git a/packages/cli/test/authoring-types/hook.doc.mjs b/packages/cli/test/authoring-types/hook.doc.mjs
new file mode 100644
index 0000000000..e99dfb80de
--- /dev/null
+++ b/packages/cli/test/authoring-types/hook.doc.mjs
@@ -0,0 +1,25 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ type: 'function',
+ name: 'useToast',
+ displayName: 'useToast',
+ group: 'Toast',
+ params: [
+ {
+ name: 'options',
+ type: 'ToastOptions',
+ description: 'Default placement and duration.',
+ required: false,
+ },
+ ],
+ returns: [
+ {
+ name: 'show',
+ type: '(message: string) => void',
+ description: 'Shows a toast.',
+ },
+ ],
+ usage: {description: 'Show a short message that dismisses itself.'},
+};
diff --git a/packages/cli/test/authoring-types/page.doc.mjs b/packages/cli/test/authoring-types/page.doc.mjs
new file mode 100644
index 0000000000..2790ec20d9
--- /dev/null
+++ b/packages/cli/test/authoring-types/page.doc.mjs
@@ -0,0 +1,10 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const docs = {
+ type: 'page',
+ name: 'settings-page',
+ displayName: 'Settings page',
+ description: 'A page of grouped settings with a save bar.',
+ isReady: true,
+};
diff --git a/packages/cli/test/authoring-types/reference.doc.mjs b/packages/cli/test/authoring-types/reference.doc.mjs
new file mode 100644
index 0000000000..75c20ff5a4
--- /dev/null
+++ b/packages/cli/test/authoring-types/reference.doc.mjs
@@ -0,0 +1,26 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */
+export const docs = {
+ type: 'generic',
+ name: 'deploying',
+ title: 'Deploying',
+ description: 'Ship an app that uses Astryx.',
+ category: 'guide',
+ sections: [
+ {
+ id: 'build',
+ title: 'Build',
+ content: [
+ {type: 'prose', text: 'Build the app, then build the theme.'},
+ {type: 'code', lang: 'bash', code: 'npx astryx theme build'},
+ ],
+ },
+ {
+ title: 'Checklist',
+ content: [
+ {type: 'list', style: 'ordered', items: ['Build', 'Test', 'Ship']},
+ ],
+ },
+ ],
+};
diff --git a/packages/cli/test/authoring-types/schema.doc.mjs b/packages/cli/test/authoring-types/schema.doc.mjs
new file mode 100644
index 0000000000..8af6033727
--- /dev/null
+++ b/packages/cli/test/authoring-types/schema.doc.mjs
@@ -0,0 +1,27 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const docs = {
+ type: 'schema',
+ name: 'widget-config',
+ displayName: 'Widget config',
+ description: 'Options a widget integration reads.',
+ appliesTo: 'widget.config.mjs',
+ fields: [
+ {
+ name: 'size',
+ type: "'sm' | 'md'",
+ description: 'Default widget size.',
+ default: "'md'",
+ },
+ {
+ name: 'colors',
+ type: 'object',
+ description: 'Color overrides.',
+ fields: [
+ {name: 'colors.accent', type: 'string', description: 'Accent color.'},
+ ],
+ },
+ ],
+ examples: [{label: 'Small widgets', code: "export default {size: 'sm'};"}],
+};
diff --git a/packages/cli/test/drift/docs-drift.mjs b/packages/cli/test/drift/docs-drift.mjs
index a52115903f..f68d75cd3c 100644
--- a/packages/cli/test/drift/docs-drift.mjs
+++ b/packages/cli/test/drift/docs-drift.mjs
@@ -88,8 +88,13 @@ export async function runDrift() {
}
}
+ // The typed examples under test/authoring-types must parse, but they
+ // document nothing real, so they take no part in the cross-reference checks.
+ const production = docs.filter(
+ d => !d.file.startsWith('packages/cli/test/authoring-types/'),
+ );
const of = (/** @type {string} */ t) =>
- docs.filter(d => d.doc && d.doc.type === t);
+ production.filter(d => d.doc && d.doc.type === t);
const fnByName = new Map(of('function').map(d => [d.doc.name, d.doc]));
// Command drift: fn resolves, params resolve, name is real.
diff --git a/packages/cli/tsconfig.strict.json b/packages/cli/tsconfig.strict.json
index bc166822c6..ba65022f80 100644
--- a/packages/cli/tsconfig.strict.json
+++ b/packages/cli/tsconfig.strict.json
@@ -25,7 +25,9 @@
"scripts/**/*.mjs",
"assets/**/*.mjs",
"assets/**/*.ts",
- "assets/**/*.tsx"
+ "assets/**/*.tsx",
+ "test/authoring-types/**/*.mjs",
+ "test/authoring-types/**/*.ts"
],
"exclude": ["**/*.test.mjs"]
}