Skip to content

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

TypeScript

feat(cli): resolve {@link} in component docs and topic descriptions (#7756)

Joey8e723b06c26e
diff --git a/.changeset/component-doc-links.md b/.changeset/component-doc-links.md
new file mode 100644
index 0000000000..55cd6d1495
--- /dev/null
+++ b/.changeset/component-doc-links.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] A `{@link <target>}` in a component doc's text now reads as the command that opens its doc, in `astryx component <Name>`, its `--props` view, and component lists, in text and JSON: the description, usage, best practices, anatomy and accessibility notes, and each prop's and example's description. A topic's description reads the same way in `astryx docs`, its list, and the docs tree. Code fields and code ticks show the link as written. A Core component's links resolve against the CLI's docs; an integration's against its own. `astryx doctor integration components` warns on a link in an integration's component docs that names no doc, and `doctor integration docs` does the same for a topic's description. The written-pointer warning also reads component docs and topic descriptions, and each finding now names its `kind` and `field`.
+
+@josephfarina
diff --git a/docs/architecture/cli-surface.md b/docs/architecture/cli-surface.md
index 1f2aa2a7a9..ad78770916 100644
--- a/docs/architecture/cli-surface.md
+++ b/docs/architecture/cli-surface.md
@@ -213,7 +213,8 @@ validate` MUST warn on a PascalCase `.tsx` at the top of the components root
run of mostly function words, or one that three or more topics share, is not
a copy); fluff, a listed padding phrase or a topic whose share of content
words is under the published floor; and a stray pointer, a code span that is
- exactly `astryx docs <name>` for a doc that exists, where a `{@link}` to that
+ exactly `astryx docs <name>` for a doc that exists, in a topic's prose,
+ description or summary or a component doc's text, where a `{@link}` to that
doc would be checked. It also fails on doc structure a reader silently
drops: a prop documented twice, an overlay key that names no prop, two
sections with one key, an overlay beside no topic, and an empty section.
@@ -757,8 +758,9 @@ key that names no prop, two sections with one key, and an overlay beside no
topic. The phrase
list and the floor are published in the check's docs, and every finding
names the phrase, or the measured density and the floor, so its fix is
-mechanical. A stray pointer (a code span in prose that is exactly
-`astryx docs <name>` for a doc that exists) is exact as well: the `{@link}`
+mechanical. A stray pointer (a code span that is exactly
+`astryx docs <name>` for a doc that exists, in a topic's prose, description
+or summary or a component doc's text) is exact as well: the `{@link}`
that replaces it prints the command that opens the doc, and doctor's link
check then fails it when the doc goes away. A command with more words, or one
in a code block, is a walkthrough, not a pointer. Each is a warning, so `integration check --strict` fails on it and
diff --git a/docs/specs/AST-047-navigable-output/spec.md b/docs/specs/AST-047-navigable-output/spec.md
index 0b26cf216a..040b79e5a4 100644
--- a/docs/specs/AST-047-navigable-output/spec.md
+++ b/docs/specs/AST-047-navigable-output/spec.md
@@ -97,7 +97,12 @@ This record owns the moves a read offers and how they appear in text and JSON.
doc's `blocks`, which a later phase renders. A target without a
provider names a doc of the provider that wrote the link: in a topic that
merges sections from several providers, each section resolves against its
- own. The CLI MUST resolve
+ own. A component doc's text fields (`description`, `summary`, `label`, at any
+ depth, an example's label included; never code or defaults) and a topic's description and
+ summary hold links too, and a component doc's bare target names a doc of
+ the component's provider, where a Core component's provider is the CLI's
+ docs, which hold Core's guides. A search hit's description reads the same.
+ The CLI MUST resolve
every link when it reads a doc, and Doctor MUST warn on a link that is
unresolved or ambiguous. A link names a doc identity, not a provider instance,
so it survives version changes.
diff --git a/packages/cli/README.md b/packages/cli/README.md
index ad63f6075f..63d1454eea 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -419,68 +419,68 @@ Every response has a `type` discriminant. The full set is below (generated from
<!-- BEGIN GENERATED: response-types -->
-| Type | What `data` carries |
-| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. |
-| `init.remove` | The removal receipt — returned when --remove-agents is set: `data.removed` is true when a managed agent-docs block was found and removed, and false when there was none to remove. |
-| `component.list` | The component catalog grouped by component group (each component's group field): `detail` (the level: names \| compact \| full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries ({name, package, description, import}), or a full ComponentDoc per entry with its package. |
-| `component.batch` | The component specialization of the shared `BatchResponse` and `BatchRow` types. An explicit programmatic selector array, or two or more CLI selectors, returns one ordered receipt: `count` plus `results`, one row per selector including duplicates. Every row carries `selector` and `status` (found \| not_found \| ambiguous \| error). A found row carries `result`, the same {type, data} response as one selector. An ambiguous row carries `code`, `error`, and `candidates` ({package, component, kind, installed}). Other failed rows carry `code`, `error`, and optional `suggestions` ({name, reason}). |
-| `component.detail` | One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc). The envelope's package names the same owner. |
-| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). The envelope's package names the npm package that owns the component. |
-| `component.detail.source` | One component's source file, as {component, source}. The envelope's package names the npm package that owns the component. |
-| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. The envelope's package names the npm package that owns the component. |
-| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry ({name, package, displayName, description, isShowcase, category}); each block names the package that owns it, and the envelope's package names the component's owner. |
-| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description, package, replaces?}), in read order; meta.namespaces lists the docs tree's top-level namespaces, and meta.notLoaded each package whose docs did not load. |
-| `docs.detail` | One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined and each section naming the package that wrote it, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
-| `docs.index` | One topic's section index, the text read of a topic with more than one section (and --index): the topic's name, title, and description, plus sections, each {id, title, package, summary} (pass the id as the section argument; package is the npm package that wrote the section; summary is the section's one-line summary), and links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
-| `docs.detail.section` | One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open its topic index and the sections before and after it). The envelope's package names the npm package that wrote the section. |
-| `docs.node` | One node of the docs tree, read by its route: its id, kind, package, title, summary, and breadcrumb, plus a namespace's slots with their children (one level down, each naming its package) or a typed doc's content, and links ({up, previous, next, related}: the commands that open its parent, its neighbors, and the docs it names). |
-| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |
-| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |
-| `discover.list` | What the project has, the integrations it loads and the official packages it declares, official packages first (name, category, components, version, a list per other kind they add, and latest when a source knows it); meta.available lists what the project could add, the official packages first, each with the command that adds it, and meta.sources reports each source, the official list last; when it lists no integration it carries meta.configured to tell "nothing configured" from "nothing discovered". |
-| `discover.detail` | One package, for an @scope/name or @scope/name@version query: what the shown version adds, whether the project has it, and, when a source knows the package, its versions, latest release, and the command that adds it. |
-| `discover.detail.doc` | The validated ComponentDoc for one installed component, for an @scope/name/Component query. |
-| `discover.item` | One item that is not an installed component, for an @scope/name/<item> query: its kind, name, package, version, and whether the project has the package. |
-| `discover.search` | The echoed query plus every matching item and package across all packages, each with its kind and whether the project has it, even when only one matches; total is set when --limit cut the list. |
-| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, package, score, reason, description, command} (package is the npm package that owns the result), plus import (components, hooks), title, parent (the command that opens the level above), and, for a hit on one section, section (docs), or displayName and kind (templates). |
-| `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. |
-| `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, package, command, basis, reason, alternatives, ...} (the start and each alternative name the package that owns the template), pages (search's closest templates), blocks and domain as SearchResultEntry[] (each naming its package), frame and foundation (Core component names), and hint {reason, commands} when thin. |
-| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. The envelope's package is @astryxdesign/core. |
-| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. The envelope's package names the same owning package. |
-| `gap-report.categories` | The fixed gap category values and human-readable labels; when a loaded integration names its own issues URL, meta.destinations lists every destination ({to, default, issuesUrl}) and meta.ask tells an agent to ask the person. |
-| `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals; without --to, when a loaded integration names its own issues URL, destinations and ask as on gap-report.categories. |
-| `template.list` | The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list. |
-| `template.show` | The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). |
-| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. The envelope's package names the npm package that owns the template. |
-| `template.copy` | A scaffold receipt: template id, output directory, written file name, file count, demoMediaReplaced (how many Astryx demo media references were replaced with placeholders), notes (setup notes naming what the template needs that the project lacks — missing packages, missing StyleX compiler; empty when satisfied), missingPackages (external package names the template imports that are not in the project), and installCommand (a ready-to-run install command with the detected package manager and workspace version ranges; null when nothing is missing, or when several lockfiles leave the package manager undetermined). The envelope's package names the npm package that owns the template. |
-| `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
-| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. The envelope's package is @astryxdesign/core, the only package that ships hooks. |
-| `hook.detail` | One hook's full authored HookDoc. The envelope's package is @astryxdesign/core. |
-| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). The envelope's package is @astryxdesign/core. |
-| `theme.build` | A theme build receipt: name, tokenCount and componentCount (override counts), sizeKB, the written outputs {css, cssDts, js, dts, and variantsDts when applicable}, warnings (defects to fix), and notices (advisories about a correct theme, such as a named font it does not load). |
-| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |
-| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |
-| `theme.list` | Every bundled, installed package, and local theme as a ThemeListEntry[]. Each entry has slug, displayName, description, maintained, owner package or local root, source, added, and default fields. Optional meta.unmigratedCopies names earlier descriptor-less copies, their missing descriptor, and the upgrade command; those copies are not data entries. |
-| `theme.app` | The app theme record after add, remove, or use. It includes every added theme and its built imports, the default slug, generated module path, and the command change. After add, the envelope package names the npm package that owns the added theme; a local theme has none. |
-| `theme.eject` | A local source-fork receipt with the resolved slug, displayName, source theme maintained flag, source-selector package, outputDir, source entry, exportName, and every file written, including the descriptor. The written local descriptor always uses maintained: false. |
-| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
-| `theme.targets` | The whole themeable surface: the echoed filter, componentCount, and targets, one per theming target — {key, className, component, props, states}, where props and states are its legal override keys. |
-| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |
-| `upgrade.list` | Every available codemod, oldest→newest, as {name, package, title, version, optional}; returned for --list without running anything. |
-| `upgrade.registry` | The copied-composition receipt for --registry: applied, ok, the counts (found, current, wouldUpdate, updated, wouldMerge, merged, wouldRefreshReceipt, receiptsRefreshed, conflicts, missing, invalid, failed), and items. |
-| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. no_codemods and config_fixable carry cliBehindCore ({cliVersion, command}) when the installed Core is newer than the CLI, which then has no codemods for the releases after its own version. |
-| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, sourcePathFound (false when the resolved source directory does not exist, so no source file was read), and (apply mode) filesChanged, transformsApplied, and per-codemod errors. When the installed Core is newer than the CLI, it also carries cliBehindCore ({cliVersion, command}): codemods for the releases after cliVersion did not run. |
-| `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], subcommands?), jsonSupported, and the flat responseTypes index. |
-| `help` | Help, in one of two shapes. A bare `astryx --json` returns the root manifest: name, version, commands (the command names), jsonSupported, and manifest (the full payload `astryx manifest --json` returns). `--help --json` on any command, or `astryx help [command] --json`, returns that command's help: command, description, usage, options (each flags, description, and defaultValue and choices when set), and subcommands (each name and description). data.manifest marks the first shape; data.usage marks the second. |
-| `version` | The CLI version, for `astryx --version --json`: {version}. |
-| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and an optional fix, always present on warn and fail) plus a `summary` of counts per status. |
-| `integration.add` | A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun. |
-| `integration.pack-check` | The packed-package check: name, version, packable, tarball {filename, fileCount, size, unpackedSize} or null, inventory {manifest, roots [{kind, path, expectedFiles, missingFiles, complete}], expectedFiles, packedFiles}, contributions {local, packed}, each null or {themes [{slug, exportName}], components, templates [{id, type, name}], codemods [{version, id}], docs, agentDocsAppend}, and issues [{code, severity, message, fix?, file?, line?}] (the issues validation finds in the source and, prefixed packed_, in the packed tree, with the fix and the place when the check knows them). |
-| `integration.validate` | The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message, fix?, file?, line?} (fix: the change that resolves it; file and line: where, relative to the package). When the manifest loads, docTypes checks each doc against its published authoring type: status (checked \| skipped), reason, typescript, docs, findings (all warnings, each naming the field and a fix), unchecked, and fixtures (test fixture docs not checked). |
-| `integration.template-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. |
-| `integration.component-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. When the manifest loads and declares a components root, propDrift compares documented props with the TypeScript props: status (checked \| skipped), reason, typescript, components, typesCompared, typesSkipped, findings (all warnings; a default_mismatch carries docDefault, codeDefault, and a fix), unchecked, typesNotCompared, and propsNotChecked. |
-| `integration.doc-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). copiedPassages lists each pair of topics that repeat 10 or more words of prose word for word: topic, section, otherTopic, otherOwner (package \| core), words, passages, owner (the topic that should keep the text), text (the passage as the topic writes it), line (where the copy starts in the topic to change, or null), and message (the exact replacement); each is also a copied_passage warning in issues. fluff lists padding phrases and low-density topics: topic, kind (phrase \| density), phrase, section, file (relative to the package root), line, density, and message (what to cut or write instead); each is also a doc_fluff warning in issues. strayPointers lists each code span in prose that is exactly `astryx docs <name>` for a doc that exists: topic, section, file (relative to the package root), line, pointer (the written command), link (the {@link} that replaces it), and message; each is also a stray_doc_pointer warning in issues. |
-| `integration.check` | Every source check of an integration package in one result: validated (false when no integration manifest was found, so nothing was checked), the package name and version, strict, and checks, one entry per check (validate, components, templates, docs), each with check, errors, warnings, skipped, failed, and response, the envelope that check returns on its own. The totals are errors, warnings, and skipped; unchecked counts what the checks could not compare. With --strict, failures lists each warning and each piece of skipped work again as an error, in the issue format the checks use; it is empty without --strict. failed decides the exit code. |
+| Type | What `data` carries |
+| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. |
+| `init.remove` | The removal receipt — returned when --remove-agents is set: `data.removed` is true when a managed agent-docs block was found and removed, and false when there was none to remove. |
+| `component.list` | The component catalog grouped by component group (each component's group field): `detail` (the level: names \| compact \| full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries ({name, package, description, import}), or a full ComponentDoc per entry with its package. |
+| `component.batch` | The component specialization of the shared `BatchResponse` and `BatchRow` types. An explicit programmatic selector array, or two or more CLI selectors, returns one ordered receipt: `count` plus `results`, one row per selector including duplicates. Every row carries `selector` and `status` (found \| not_found \| ambiguous \| error). A found row carries `result`, the same {type, data} response as one selector. An ambiguous row carries `code`, `error`, and `candidates` ({package, component, kind, installed}). Other failed rows carry `code`, `error`, and optional `suggestions` ({name, reason}). |
+| `component.detail` | One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc). The envelope's package names the same owner. |
+| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). The envelope's package names the npm package that owns the component. |
+| `component.detail.source` | One component's source file, as {component, source}. The envelope's package names the npm package that owns the component. |
+| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. The envelope's package names the npm package that owns the component. |
+| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry ({name, package, displayName, description, isShowcase, category}); each block names the package that owns it, and the envelope's package names the component's owner. |
+| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description, package, replaces?}), in read order; meta.namespaces lists the docs tree's top-level namespaces, and meta.notLoaded each package whose docs did not load. |
+| `docs.detail` | One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined and each section naming the package that wrote it, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
+| `docs.index` | One topic's section index, the text read of a topic with more than one section (and --index): the topic's name, title, and description, plus sections, each {id, title, package, summary} (pass the id as the section argument; package is the npm package that wrote the section; summary is the section's one-line summary), and links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
+| `docs.detail.section` | One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open its topic index and the sections before and after it). The envelope's package names the npm package that wrote the section. |
+| `docs.node` | One node of the docs tree, read by its route: its id, kind, package, title, summary, and breadcrumb, plus a namespace's slots with their children (one level down, each naming its package) or a typed doc's content, and links ({up, previous, next, related}: the commands that open its parent, its neighbors, and the docs it names). |
+| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |
+| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |
+| `discover.list` | What the project has, the integrations it loads and the official packages it declares, official packages first (name, category, components, version, a list per other kind they add, and latest when a source knows it); meta.available lists what the project could add, the official packages first, each with the command that adds it, and meta.sources reports each source, the official list last; when it lists no integration it carries meta.configured to tell "nothing configured" from "nothing discovered". |
+| `discover.detail` | One package, for an @scope/name or @scope/name@version query: what the shown version adds, whether the project has it, and, when a source knows the package, its versions, latest release, and the command that adds it. |
+| `discover.detail.doc` | The validated ComponentDoc for one installed component, for an @scope/name/Component query. |
+| `discover.item` | One item that is not an installed component, for an @scope/name/<item> query: its kind, name, package, version, and whether the project has the package. |
+| `discover.search` | The echoed query plus every matching item and package across all packages, each with its kind and whether the project has it, even when only one matches; total is set when --limit cut the list. |
+| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, package, score, reason, description, command} (package is the npm package that owns the result), plus import (components, hooks), title, parent (the command that opens the level above), and, for a hit on one section, section (docs), or displayName and kind (templates). |
+| `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. |
+| `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, package, command, basis, reason, alternatives, ...} (the start and each alternative name the package that owns the template), pages (search's closest templates), blocks and domain as SearchResultEntry[] (each naming its package), frame and foundation (Core component names), and hint {reason, commands} when thin. |
+| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. The envelope's package is @astryxdesign/core. |
+| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. The envelope's package names the same owning package. |
+| `gap-report.categories` | The fixed gap category values and human-readable labels; when a loaded integration names its own issues URL, meta.destinations lists every destination ({to, default, issuesUrl}) and meta.ask tells an agent to ask the person. |
+| `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals; without --to, when a loaded integration names its own issues URL, destinations and ask as on gap-report.categories. |
+| `template.list` | The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list. |
+| `template.show` | The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). |
+| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. The envelope's package names the npm package that owns the template. |
+| `template.copy` | A scaffold receipt: template id, output directory, written file name, file count, demoMediaReplaced (how many Astryx demo media references were replaced with placeholders), notes (setup notes naming what the template needs that the project lacks — missing packages, missing StyleX compiler; empty when satisfied), missingPackages (external package names the template imports that are not in the project), and installCommand (a ready-to-run install command with the detected package manager and workspace version ranges; null when nothing is missing, or when several lockfiles leave the package manager undetermined). The envelope's package names the npm package that owns the template. |
+| `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
+| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. The envelope's package is @astryxdesign/core, the only package that ships hooks. |
+| `hook.detail` | One hook's full authored HookDoc. The envelope's package is @astryxdesign/core. |
+| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). The envelope's package is @astryxdesign/core. |
+| `theme.build` | A theme build receipt: name, tokenCount and componentCount (override counts), sizeKB, the written outputs {css, cssDts, js, dts, and variantsDts when applicable}, warnings (defects to fix), and notices (advisories about a correct theme, such as a named font it does not load). |
+| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |
+| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |
+| `theme.list` | Every bundled, installed package, and local theme as a ThemeListEntry[]. Each entry has slug, displayName, description, maintained, owner package or local root, source, added, and default fields. Optional meta.unmigratedCopies names earlier descriptor-less copies, their missing descriptor, and the upgrade command; those copies are not data entries. |
+| `theme.app` | The app theme record after add, remove, or use. It includes every added theme and its built imports, the default slug, generated module path, and the command change. After add, the envelope package names the npm package that owns the added theme; a local theme has none. |
+| `theme.eject` | A local source-fork receipt with the resolved slug, displayName, source theme maintained flag, source-selector package, outputDir, source entry, exportName, and every file written, including the descriptor. The written local descriptor always uses maintained: false. |
+| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
+| `theme.targets` | The whole themeable surface: the echoed filter, componentCount, and targets, one per theming target — {key, className, component, props, states}, where props and states are its legal override keys. |
+| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |
+| `upgrade.list` | Every available codemod, oldest→newest, as {name, package, title, version, optional}; returned for --list without running anything. |
+| `upgrade.registry` | The copied-composition receipt for --registry: applied, ok, the counts (found, current, wouldUpdate, updated, wouldMerge, merged, wouldRefreshReceipt, receiptsRefreshed, conflicts, missing, invalid, failed), and items. |
+| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. no_codemods and config_fixable carry cliBehindCore ({cliVersion, command}) when the installed Core is newer than the CLI, which then has no codemods for the releases after its own version. |
+| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, sourcePathFound (false when the resolved source directory does not exist, so no source file was read), and (apply mode) filesChanged, transformsApplied, and per-codemod errors. When the installed Core is newer than the CLI, it also carries cliBehindCore ({cliVersion, command}): codemods for the releases after cliVersion did not run. |
+| `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], subcommands?), jsonSupported, and the flat responseTypes index. |
+| `help` | Help, in one of two shapes. A bare `astryx --json` returns the root manifest: name, version, commands (the command names), jsonSupported, and manifest (the full payload `astryx manifest --json` returns). `--help --json` on any command, or `astryx help [command] --json`, returns that command's help: command, description, usage, options (each flags, description, and defaultValue and choices when set), and subcommands (each name and description). data.manifest marks the first shape; data.usage marks the second. |
+| `version` | The CLI version, for `astryx --version --json`: {version}. |
+| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and an optional fix, always present on warn and fail) plus a `summary` of counts per status. |
+| `integration.add` | A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun. |
+| `integration.pack-check` | The packed-package check: name, version, packable, tarball {filename, fileCount, size, unpackedSize} or null, inventory {manifest, roots [{kind, path, expectedFiles, missingFiles, complete}], expectedFiles, packedFiles}, contributions {local, packed}, each null or {themes [{slug, exportName}], components, templates [{id, type, name}], codemods [{version, id}], docs, agentDocsAppend}, and issues [{code, severity, message, fix?, file?, line?}] (the issues validation finds in the source and, prefixed packed_, in the packed tree, with the fix and the place when the check knows them). |
+| `integration.validate` | The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message, fix?, file?, line?} (fix: the change that resolves it; file and line: where, relative to the package). When the manifest loads, docTypes checks each doc against its published authoring type: status (checked \| skipped), reason, typescript, docs, findings (all warnings, each naming the field and a fix), unchecked, and fixtures (test fixture docs not checked). |
+| `integration.template-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. |
+| `integration.component-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. When the manifest loads and declares a components root, propDrift compares documented props with the TypeScript props: status (checked \| skipped), reason, typescript, components, typesCompared, typesSkipped, findings (all warnings; a default_mismatch carries docDefault, codeDefault, and a fix), unchecked, typesNotCompared, and propsNotChecked. |
+| `integration.doc-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). copiedPassages lists each pair of topics that repeat 10 or more words of prose word for word: topic, section, otherTopic, otherOwner (package \| core), words, passages, owner (the topic that should keep the text), text (the passage as the topic writes it), line (where the copy starts in the topic to change, or null), and message (the exact replacement); each is also a copied_passage warning in issues. fluff lists padding phrases and low-density topics: topic, kind (phrase \| density), phrase, section, file (relative to the package root), line, density, and message (what to cut or write instead); each is also a doc_fluff warning in issues. strayPointers lists each code span that is exactly `astryx docs <name>` for a doc that exists, in the prose, description or summary of a topic or the text fields of a component doc: topic (the topic or component doc), kind (topic \| component), section, field (the field outside any section, such as description or usage.bestPractices[0].description, else null), file (relative to the package root), line, pointer (the written command), link (the {@link} that replaces it), and message; each is also a stray_doc_pointer warning in issues. |
+| `integration.check` | Every source check of an integration package in one result: validated (false when no integration manifest was found, so nothing was checked), the package name and version, strict, and checks, one entry per check (validate, components, templates, docs), each with check, errors, warnings, skipped, failed, and response, the envelope that check returns on its own. The totals are errors, warnings, and skipped; unchecked counts what the checks could not compare. With --strict, failures lists each warning and each piece of skipped work again as an error, in the issue format the checks use; it is empty without --strict. failed decides the exit code. |
<!-- END GENERATED: response-types -->
<!-- Generated by scripts/generate-cli-readme.mjs from the response-types EnumDoc. Run `pnpm -F @astryxdesign/cli readme`. -->
diff --git a/packages/cli/api/component/_adapter.mjs b/packages/cli/api/component/_adapter.mjs
index 98d8914f90..e1fe489177 100644
--- a/packages/cli/api/component/_adapter.mjs
+++ b/packages/cli/api/component/_adapter.mjs
@@ -45,6 +45,11 @@ import {loadComponentDoc as loadValidatedComponentDoc} from '../../foundation/di
import {resolveComponentReplacements} from '../../foundation/discovery/component-replacement.mjs';
import {searchComponents} from '../../foundation/text/string-utils.mjs';
import {AstryxError} from '../error.mjs';
+import {
+ componentLinkProvider,
+ linkComponentDoc,
+ loadDocsCatalog,
+} from '../docs/_adapter.mjs';
export {CORE_PACKAGE, unscopedComponentOwners};
@@ -669,3 +674,114 @@ export function scopeIntegrationMember(docs, owner, dirName) {
if (docs.import) scoped.import = docs.import;
return scoped;
}
+
+/**
+ * A search response with every inline `{@link <target>}` in a component
+ * result's description resolved to the command that opens the doc it names,
+ * as `astryx component` prints it (spec:AST-047 FR9). The response object is
+ * kept, with its results replaced.
+ * @template {{data: {results: any[]}}} R
+ * @param {R} response
+ * @param {string} cwd
+ * @returns {Promise<R>}
+ */
+export async function linkSearchResponse(response, cwd) {
+ const results = response.data.results;
+ if (
+ !results.some(
+ result =>
+ result?.domain === 'component' &&
+ typeof result.description === 'string' &&
+ result.description.includes('{@link'),
+ )
+ ) {
+ return response;
+ }
+ const linked = [];
+ for (const result of results) {
+ if (
+ result?.domain !== 'component' ||
+ typeof result.description !== 'string' ||
+ !result.description.includes('{@link')
+ ) {
+ linked.push(result);
+ continue;
+ }
+ const read = await linkComponentResponse(
+ {
+ type: 'component.detail',
+ package: result.package,
+ data: {description: result.description},
+ },
+ cwd,
+ );
+ linked.push({...result, description: read.data.description});
+ }
+ response.data = {...response.data, results: linked};
+ return response;
+}
+
+/**
+ * A component read with every inline `{@link <target>}` in its doc text
+ * resolved to the command that opens the doc it names (spec:AST-047 FR9), in
+ * the detail, its props projection, and each list entry. A Core component's
+ * links resolve against the CLI's own docs; an integration's against that
+ * integration's. A link that names no doc prints as written.
+ * @template {{type: string, package?: string, data?: any}} R
+ * @param {R} response
+ * @param {string} cwd
+ * @returns {Promise<R>}
+ */
+export async function linkComponentResponse(response, cwd) {
+ const {type} = response;
+ if (
+ type !== 'component.detail' &&
+ type !== 'component.detail.props' &&
+ type !== 'component.list'
+ ) {
+ return response;
+ }
+ if (!JSON.stringify(response.data ?? null).includes('{@link')) {
+ return response;
+ }
+ const catalog = await loadDocsCatalog(cwd);
+ /** @type {Map<string, string>} */
+ const declared = new Map();
+ for (const integration of await loadIntegrationsSafely(cwd)) {
+ const id = /** @type {any} */ (integration).providerId;
+ if (typeof id === 'string') declared.set(integration.name, id);
+ }
+ /**
+ * @param {any} doc
+ * @param {string | undefined} owner
+ */
+ const link = async (doc, owner) => {
+ if (typeof owner !== 'string') return doc;
+ try {
+ return (
+ await linkComponentDoc(
+ catalog,
+ componentLinkProvider(owner, declared.get(owner)),
+ doc,
+ )
+ ).doc;
+ } catch {
+ // An owner that is not a provider id links nothing; its text reads as
+ // written.
+ return doc;
+ }
+ };
+ if (type !== 'component.list') {
+ return {...response, data: await link(response.data, response.package)};
+ }
+ /** @type {Record<string, any[]>} */
+ const components = {};
+ for (const [group, entries] of Object.entries(
+ response.data.components ?? {},
+ )) {
+ const linked = [];
+ for (const entry of entries) linked.push(await link(entry, entry?.package));
+ components[group] = linked;
+ }
+ return {...response, data: {...response.data, components}};
+}
diff --git a/packages/cli/api/component/component.mjs b/packages/cli/api/component/component.mjs
index 81aaeb2321..a3495f4fa0 100644
--- a/packages/cli/api/component/component.mjs
+++ b/packages/cli/api/component/component.mjs
@@ -32,6 +32,7 @@ import {
installedComponentPackageVersion,
resolveComponentReplacement,
unscopedComponentOwners,
+ linkComponentResponse,
} from './_adapter.mjs';
import {componentList} from './list/list.mjs';
import {componentDetail} from './detail/detail.mjs';
@@ -257,6 +258,23 @@ async function componentBatch(selectors, options, coreDir) {
* )>}
*/
export async function component(name, options = {}) {
+ // Every read resolves the links in the doc text it returns (spec:AST-047
+ // FR9); a batch's results are each a read of their own.
+ return /** @type {any} */ (
+ await linkComponentResponse(
+ await componentRead(name, options),
+ options.cwd ?? process.cwd(),
+ )
+ );
+}
+
+/**
+ * {@link component}, with each `{@link}` in its doc text as written.
+ * @param {string|string[]} [name]
+ * @param {Parameters<typeof component>[1]} [options]
+ * @returns {ReturnType<typeof component>}
+ */
+async function componentRead(name, options = {}) {
const {
cwd = process.cwd(),
list = false,
@@ -357,7 +375,7 @@ export async function component(name, options = {}) {
requireInstalledSelectorVersion(target, coreDir, loadedIntegrations);
}
if (target.name !== name || target.package !== packageScope) {
- return component(target.name, {...options, package: target.package});
+ return componentRead(target.name, {...options, package: target.package});
}
name = target.name;
}
@@ -396,7 +414,10 @@ export async function component(name, options = {}) {
dirName,
);
if (replacement?.package === packageScope) {
- return component(replacement.name, {...options, package: packageScope});
+ return componentRead(replacement.name, {
+ ...options,
+ package: packageScope,
+ });
}
}
const scoped = classifyScope(packageScope, {
@@ -424,8 +445,17 @@ export async function component(name, options = {}) {
// a showcase, so skip discovery entirely.
if (showcase) {
return scoped.kind === 'core'
- ? componentDetailShowcase(dirName, {cwd, name, ownerPackage: owner.package})
- : componentDetailShowcase(dirName, {cwd, name, resolve: false, ownerPackage: owner.package});
+ ? componentDetailShowcase(dirName, {
+ cwd,
+ name,
+ ownerPackage: owner.package,
+ })
+ : componentDetailShowcase(dirName, {
+ cwd,
+ name,
+ resolve: false,
+ ownerPackage: owner.package,
+ });
}
if (blocks) {
return componentDetailBlocks(dirName, cwd, owner.package);
@@ -443,7 +473,12 @@ export async function component(name, options = {}) {
// Legacy `pkg.astryx.docs` external package.
if (showcase) {
- return componentDetailShowcase(dirName, {cwd, name, packageScope, ownerPackage: packageScope});
+ return componentDetailShowcase(dirName, {
+ cwd,
+ name,
+ packageScope,
+ ownerPackage: packageScope,
+ });
}
const extDocPath = resolveLegacyExternalDoc(scoped.ext, dirName);
if (extDocPath) {
@@ -484,7 +519,7 @@ export async function component(name, options = {}) {
dirName,
);
if (replacement) {
- return component(replacement.name, {
+ return componentRead(replacement.name, {
...options,
package: replacement.package,
});
@@ -526,11 +561,19 @@ export async function component(name, options = {}) {
) {
const owner = effectiveOwners[0];
if (source) {
- return componentDetailSource(dirName, owner.sourcePath, {name, ownerPackage: owner.package});
+ return componentDetailSource(dirName, owner.sourcePath, {
+ name,
+ ownerPackage: owner.package,
+ });
}
if (showcase) {
// Integration components don't carry showcases — fail without scanning.
- return componentDetailShowcase(dirName, {cwd, name, resolve: false, ownerPackage: owner.package});
+ return componentDetailShowcase(dirName, {
+ cwd,
+ name,
+ resolve: false,
+ ownerPackage: owner.package,
+ });
}
const loaded = await loadComponentDoc(owner.docPath, docOpts);
const docs = scopeIntegrationMember(loaded, owner, dirName);
@@ -548,7 +591,11 @@ export async function component(name, options = {}) {
);
}
if (showcase) {
- return componentDetailShowcase(dirName, {cwd, name, ownerPackage: CORE_PACKAGE});
+ return componentDetailShowcase(dirName, {
+ cwd,
+ name,
+ ownerPackage: CORE_PACKAGE,
+ });
}
const resolved = await resolveUnscopedDoc(dirName, {coreDir, cwd, name});
@@ -565,7 +612,10 @@ export async function component(name, options = {}) {
const sub = scopeSubComponent(docs, dirName, coreDir);
if (sub) {
if (props)
- return componentDetailProps({props: sub.matchingComponent.props}, resolved.resolvedOwnerPackage);
+ return componentDetailProps(
+ {props: sub.matchingComponent.props},
+ resolved.resolvedOwnerPackage,
+ );
return componentDetail(
sub.scoped,
{
diff --git a/packages/cli/api/component/doc-links.test.mjs b/packages/cli/api/component/doc-links.test.mjs
new file mode 100644
index 0000000000..20947ac2fd
--- /dev/null
+++ b/packages/cli/api/component/doc-links.test.mjs
@@ -0,0 +1,386 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Links in a component doc's text and a topic's description
+ * (spec:AST-047 FR9): a read resolves each `{@link <target>}` to the command
+ * that opens its doc, in text and JSON, the way a topic section's links read.
+ * Code fields and code ticks show the syntax as written.
+ *
+ * Fixtures live under a repo-local temp dir, not /tmp, because Vite refuses to
+ * dynamically import a module from outside the project root.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {component} from './component.mjs';
+import {CORE_PACKAGE, linkComponentResponse} from './_adapter.mjs';
+import {docs} from '../docs/docs.mjs';
+import {search} from '../search/search.mjs';
+import {runCli} from '../../test-utils/run-cli.mjs';
+
+const SLOW = 60_000;
+
+let tmpDir;
+
+const ACME_BUTTON = {
+ type: 'component',
+ name: 'AcmeButton',
+ displayName: 'Acme Button',
+ usage: {
+ description:
+ 'A button. Set it up as {@link generic:acme-setup} says; theme it with {@link @astryxdesign/cli:generic:theme}.',
+ bestPractices: [
+ {
+ guidance: true,
+ description: 'Pair it with {@link component:AcmeButton}.',
+ },
+ ],
+ },
+ props: [
+ {
+ name: 'tone',
+ type: 'string',
+ description:
+ 'Read {@link generic:acme-setup}; write `{@link generic:acme-setup}` to link.',
+ default: "'{@link generic:acme-setup}'",
+ },
+ ],
+ examples: [
+ {
+ label: 'As {@link generic:acme-setup} shows',
+ code: '// {@link generic:acme-setup}',
+ },
+ ],
+};
+
+const ACME_SETUP = {
+ type: 'generic',
+ name: 'acme-setup',
+ title: 'Acme setup',
+ description:
+ 'Set up Acme, then theme it as {@link @astryxdesign/cli:generic:theme} says.',
+ sections: [
+ {title: 'Overview', content: [{type: 'prose', text: 'Install it.'}]},
+ ],
+};
+
+function scaffold() {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ "export default {integrations: ['@acme/widgets']};\n",
+ );
+ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');
+ fs.mkdirSync(path.join(pkgDir, 'components'), {recursive: true});
+ fs.mkdirSync(path.join(pkgDir, 'docs'), {recursive: true});
+ fs.writeFileSync(
+ path.join(pkgDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '1.0.0'}),
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'astryx.integration.mjs'),
+ "export default {components: './components', docs: './docs'};\n",
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'components', 'AcmeButton.doc.mjs'),
+ `export default ${JSON.stringify(ACME_BUTTON, null, 2)};\n`,
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'components', 'AcmeButton.tsx'),
+ 'export function AcmeButton() { return null; }\n',
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'docs', 'acme-setup.doc.mjs'),
+ `export default ${JSON.stringify(ACME_SETUP, null, 2)};\n`,
+ );
+}
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-component-links-'));
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe("a link in a component doc's text", () => {
+ it(
+ "reads as the command that opens its doc, against the integration's own docs",
+ async () => {
+ scaffold();
+ const read = /** @type {any} */ (
+ await component('AcmeButton', {cwd: tmpDir})
+ );
+ expect(read.type).toBe('component.detail');
+ expect(read.data.usage.description).toBe(
+ 'A button. Set it up as `astryx docs acme-setup` says; theme it with `astryx docs theme`.',
+ );
+ expect(read.data.usage.bestPractices[0].description).toBe(
+ 'Pair it with `astryx component AcmeButton --package @acme/widgets`.',
+ );
+ // Code ticks and code fields show the syntax as written.
+ expect(read.data.props[0].description).toBe(
+ 'Read `astryx docs acme-setup`; write `{@link generic:acme-setup}` to link.',
+ );
+ expect(read.data.props[0].default).toBe("'{@link generic:acme-setup}'");
+ expect(read.data.examples[0]).toEqual({
+ label: 'As `astryx docs acme-setup` shows',
+ code: '// {@link generic:acme-setup}',
+ });
+ },
+ SLOW,
+ );
+
+ it(
+ 'reads the same in `astryx discover <package>/<Component>`',
+ async () => {
+ scaffold();
+ const json = await runCli(
+ ['--json', 'discover', '@acme/widgets/AcmeButton'],
+ tmpDir,
+ );
+ expect(json.status).toBe(0);
+ expect(JSON.parse(json.stdout).data.usage.description).toBe(
+ 'A button. Set it up as `astryx docs acme-setup` says; theme it with `astryx docs theme`.',
+ );
+ },
+ SLOW,
+ );
+
+ it(
+ "reads the same in a search hit's description",
+ async () => {
+ scaffold();
+ const found = /** @type {any} */ (
+ await search('AcmeButton', {cwd: tmpDir, type: 'component'})
+ );
+ const hit = found.data.results.find(
+ (/** @type {any} */ result) => result.name === 'AcmeButton',
+ );
+ expect(hit.description).toBe(
+ 'A button. Set it up as `astryx docs acme-setup` says; theme it with `astryx docs theme`.',
+ );
+ },
+ SLOW,
+ );
+
+ it(
+ 'reads the same in the props projection, in JSON, and in text',
+ async () => {
+ scaffold();
+ const props = /** @type {any} */ (
+ await component('AcmeButton', {cwd: tmpDir, props: true})
+ );
+ expect(props.data[0].description).toBe(
+ 'Read `astryx docs acme-setup`; write `{@link generic:acme-setup}` to link.',
+ );
+
+ const json = await runCli(['--json', 'component', 'AcmeButton'], tmpDir);
+ expect(json.status).toBe(0);
+ expect(JSON.parse(json.stdout).data.usage.description).toContain(
+ '`astryx docs acme-setup`',
+ );
+
+ const text = await runCli(['component', 'AcmeButton'], tmpDir);
+ expect(text.status).toBe(0);
+ expect(text.stdout).toContain('`astryx docs acme-setup`');
+ expect(text.stdout).not.toContain('{@link generic:acme-setup} says');
+ },
+ SLOW,
+ );
+
+ it("resolves a Core component's links against the CLI's own docs", async () => {
+ const read = await linkComponentResponse(
+ {
+ type: 'component.detail',
+ package: CORE_PACKAGE,
+ data: {
+ usage: {description: 'Theme it with {@link generic:theme}.'},
+ props: [
+ {
+ name: 'x',
+ type: 'string',
+ description: 'See {@link generic:nope}.',
+ },
+ ],
+ },
+ },
+ tmpDir,
+ );
+ expect(read.data.usage.description).toBe(
+ 'Theme it with `astryx docs theme`.',
+ );
+ // A link that names no doc prints as written.
+ expect(read.data.props[0].description).toBe('See {@link generic:nope}.');
+ });
+});
+
+describe("a link in a topic's description", () => {
+ it(
+ 'reads as the command that opens its doc, in the detail and the list',
+ async () => {
+ scaffold();
+ const detail = /** @type {any} */ (
+ await docs('acme-setup', undefined, {cwd: tmpDir, full: true})
+ );
+ expect(detail.data.description).toBe(
+ 'Set up Acme, then theme it as `astryx docs theme` says.',
+ );
+ const listed = /** @type {any} */ (
+ await docs(undefined, undefined, {cwd: tmpDir})
+ );
+ expect(
+ listed.data.find((/** @type {any} */ t) => t.topic === 'acme-setup')
+ .description,
+ ).toBe('Set up Acme, then theme it as `astryx docs theme` says.');
+ },
+ SLOW,
+ );
+});
+
+describe("a link in a guide's description, as the docs tree shows it", () => {
+ it(
+ 'reads as the command that opens its doc in the guide and its namespace',
+ async () => {
+ const expected =
+ 'Document a theme by extending the core theme topic, so an app reads it in `astryx docs theme`.';
+ const guide = /** @type {any} */ (
+ await docs(
+ 'cli/integrations/building-blocks/themes/document-the-theme',
+ undefined,
+ {cwd: tmpDir, full: true},
+ )
+ );
+ expect(guide.data.description).toBe(expected);
+ const namespace = /** @type {any} */ (
+ await docs('cli/integrations/building-blocks/themes', undefined, {
+ cwd: tmpDir,
+ })
+ );
+ const child = namespace.data.slots
+ .flatMap((/** @type {any} */ slot) => slot.children)
+ .find((/** @type {any} */ each) => each.name === 'document-the-theme');
+ expect(child.summary).toBe(expected);
+ },
+ SLOW,
+ );
+});
+
+describe("a reference block's summary of another package's component", () => {
+ it(
+ "resolves the summary's links against the component's own package",
+ async () => {
+ const write = (
+ /** @type {string} */ file,
+ /** @type {string} */ text,
+ ) => {
+ fs.mkdirSync(path.dirname(path.join(tmpDir, file)), {recursive: true});
+ fs.writeFileSync(path.join(tmpDir, file), text);
+ };
+ const doc = (/** @type {object} */ value) =>
+ `export default ${JSON.stringify(value)};\n`;
+ write('package.json', JSON.stringify({name: 'consumer'}));
+ write(
+ 'astryx.config.mjs',
+ "export default {integrations: ['@acme/widgets', '@acme/other']};\n",
+ );
+ const widgets = 'node_modules/@acme/widgets';
+ write(
+ `${widgets}/package.json`,
+ JSON.stringify({name: '@acme/widgets', version: '1.0.0'}),
+ );
+ write(
+ `${widgets}/astryx.integration.mjs`,
+ "export default {docs: './docs'};\n",
+ );
+ write(
+ `${widgets}/docs/acme-ref.doc.mjs`,
+ doc({
+ type: 'generic',
+ name: 'acme-ref',
+ title: 'Acme ref',
+ description: 'Where the card is documented.',
+ sections: [
+ {
+ title: 'Overview',
+ content: [
+ {
+ type: 'reference',
+ target: '@acme/other:component:OtherCardBody',
+ },
+ ],
+ },
+ ],
+ }),
+ );
+ const other = 'node_modules/@acme/other';
+ write(
+ `${other}/package.json`,
+ JSON.stringify({name: '@acme/other', version: '1.0.0'}),
+ );
+ write(
+ `${other}/astryx.integration.mjs`,
+ "export default {components: './components', docs: './docs'};\n",
+ );
+ write(
+ `${other}/docs/other-setup.doc.mjs`,
+ doc({
+ type: 'generic',
+ name: 'other-setup',
+ title: 'Other setup',
+ description: 'Set up Other.',
+ sections: [
+ {
+ title: 'Overview',
+ content: [{type: 'prose', text: 'Install it.'}],
+ },
+ ],
+ }),
+ );
+ write(
+ `${other}/components/OtherCard.doc.mjs`,
+ doc({
+ type: 'component',
+ name: 'OtherCard',
+ displayName: 'Other Card',
+ usage: {description: 'A card.'},
+ props: [],
+ }),
+ );
+ write(
+ `${other}/components/OtherCard.tsx`,
+ 'export function OtherCard() { return null; }\n',
+ );
+ write(
+ `${other}/components/OtherCardBody.doc.mjs`,
+ doc({
+ type: 'component',
+ name: 'OtherCardBody',
+ displayName: 'Other Card Body',
+ subComponentOf: 'OtherCard',
+ description: 'Its body, set up as {@link generic:other-setup} says.',
+ props: [],
+ }),
+ );
+ write(
+ `${other}/components/OtherCardBody.tsx`,
+ 'export function OtherCardBody() { return null; }\n',
+ );
+
+ const read = /** @type {any} */ (
+ await docs('acme-ref', undefined, {cwd: tmpDir, full: true})
+ );
+
+ // `other-setup` is @acme/other's topic: from @acme/widgets, the
+ // linking package, the same link names no doc.
+ expect(read.data.sections[0].content[0].text).toContain(
+ 'Its body, set up as `astryx docs other-setup` says.',
+ );
+ },
+ SLOW,
+ );
+});
diff --git a/packages/cli/api/discover/detail/doc/doc.mjs b/packages/cli/api/discover/detail/doc/doc.mjs
index 331471458f..22832c18ec 100644
--- a/packages/cli/api/discover/detail/doc/doc.mjs
+++ b/packages/cli/api/discover/detail/doc/doc.mjs
@@ -14,6 +14,7 @@
*/
import {findComponent, loadValidatedDoc} from '../../_adapter.mjs';
+import {linkComponentResponse} from '../../../component/_adapter.mjs';
import {levenshteinDistance} from '../../../../foundation/text/string-utils.mjs';
import {AstryxError} from '../../../error.mjs';
import {ERROR_CODES} from '../../../../foundation/response/error-codes.mjs';
@@ -27,7 +28,14 @@ import {ERROR_CODES} from '../../../../foundation/response/error-codes.mjs';
* @returns {Promise<import('../../discover.type.mjs').DiscoverDetailDocResponse>}
*/
export async function docFromResult(result, opts) {
- return {type: 'discover.detail.doc', data: await loadValidatedDoc(result, opts)};
+ const data = await loadValidatedDoc(result, opts);
+ // Its `{@link}`s read as the commands that open their docs, as
+ // `astryx component` prints them (spec:AST-047 FR9).
+ const linked = await linkComponentResponse(
+ {type: 'component.detail', package: result.pkg.name, data},
+ process.cwd(),
+ );
+ return {type: 'discover.detail.doc', data: linked.data};
}
/**
diff --git a/packages/cli/api/docs/_adapter.mjs b/packages/cli/api/docs/_adapter.mjs
index d784cf3832..4d76219dd8 100644
--- a/packages/cli/api/docs/_adapter.mjs
+++ b/packages/cli/api/docs/_adapter.mjs
@@ -40,6 +40,7 @@ import {
import {sortDiagnostics} from '../../foundation/doc-compiler/diagnostics.mjs';
import {
linkBlocks,
+ linkFields,
parseLinkTarget,
} from '../../foundation/doc-compiler/links.mjs';
import {
@@ -264,8 +265,16 @@ function linkTopic(catalog, entry, lang) {
problems.push(...linked.problems);
sections.push({...section, content: linked.content});
}
+ // The topic's own text outside its sections, its description and
+ // summary, resolves against the topic's own provider.
+ const {resolve} = await linkerFor(providerOf(entry));
+ const fields = await linkFields(topicTextFields(raw.doc), resolve);
+ problems.push(...fields.problems);
return {
- node: deepFreeze({...raw, doc: {...raw.doc, sections}}),
+ node: deepFreeze({
+ ...raw,
+ doc: {...raw.doc, ...fields.doc, sections},
+ }),
problems,
};
})();
@@ -274,6 +283,82 @@ function linkTopic(catalog, entry, lang) {
return linked;
}
+/**
+ * The text fields of a topic outside its sections: its description and
+ * summary, those it has.
+ * @param {any} doc
+ * @returns {{description?: string, summary?: string}}
+ */
+function topicTextFields(doc) {
+ /** @type {{description?: string, summary?: string}} */
+ const fields = {};
+ if (typeof doc?.description === 'string')
+ fields.description = doc.description;
+ if (typeof doc?.summary === 'string') fields.summary = doc.summary;
+ return fields;
+}
+
+/**
+ * One line of a doc's text, such as a topic's or a tree node's summary, with
+ * every inline link resolved against the provider that wrote it (spec:AST-047
+ * FR9). A link that names no doc prints as written; doctor names it.
+ * @param {DocsCatalog} catalog
+ * @param {string} providerId the provider id of the doc the text sits in
+ * @param {string} text
+ * @returns {Promise<string>}
+ */
+export async function linkDocText(catalog, providerId, text) {
+ if (typeof text !== 'string' || !text.includes('{@link')) return text;
+ let provider;
+ try {
+ provider = normalizeProviderId(providerId);
+ } catch {
+ return text;
+ }
+ const linked = await linkFields(
+ {description: text},
+ await linkResolver(catalog, provider),
+ );
+ return linked.doc.description ?? text;
+}
+
+/**
+ * A component doc with every inline link in its text fields resolved
+ * (spec:AST-047 FR9): its description, usage, best practices, and each prop's
+ * and example's description. Code fields are shown as written. A Core
+ * component's links resolve against the CLI's own docs provider; an
+ * integration's against that integration's.
+ * @template T
+ * @param {DocsCatalog} catalog
+ * @param {string} providerId the provider id the component's links resolve
+ * against
+ * @param {T} doc
+ * @returns {Promise<{doc: T, problems: LinkProblem[]}>}
+ */
+export async function linkComponentDoc(catalog, providerId, doc) {
+ if (!JSON.stringify(doc ?? null).includes('{@link')) {
+ return {doc, problems: []};
+ }
+ return linkFields(
+ doc,
+ await linkResolver(catalog, normalizeProviderId(providerId)),
+ );
+}
+
+/**
+ * The provider id a component's doc links resolve against: the CLI's own for
+ * a Core component, else its owner package's (or the provider id its manifest
+ * declares).
+ * @param {string} ownerPackage
+ * @param {string} [providerId]
+ * @returns {string}
+ */
+export function componentLinkProvider(ownerPackage, providerId) {
+ return ownerPackage === CORE_PACKAGE
+ ? CLI_PROVIDER_ID
+ : normalizeProviderId(providerId ?? ownerPackage);
+}
+
/** @type {WeakMap<DocsCatalog, Promise<DocsTree>>} */
const treesByCatalog = new WeakMap();
@@ -347,12 +432,50 @@ async function buildProjectTree(catalog, fresh) {
docs: [...cli.docs, ...added.flatMap(each => each.guides)],
topics: await flatTopicInputs(catalog),
});
+ // A summary is a doc's text too: each link in it reads as the command that
+ // opens its doc, wherever the tree's summaries print (spec:AST-047 FR9).
+ for (const node of result.nodes.values()) {
+ if (typeof node.summary === 'string' && node.summary.includes('{@link')) {
+ node.summary = await linkSummary(
+ catalog,
+ result,
+ node.providerId,
+ node.summary,
+ );
+ }
+ }
return {
...result,
diagnostics: sortDiagnostics([...cli.diagnostics, ...result.diagnostics]),
};
}
+/**
+ * One summary with each inline link resolved to the command that opens its
+ * doc, against the provider that wrote it. A link that names no doc prints as
+ * written; doctor names it where it checks the doc's own fields.
+ * @param {DocsCatalog} catalog
+ * @param {DocsTree} tree
+ * @param {string} providerId
+ * @param {string} summary
+ * @returns {Promise<string>}
+ */
+async function linkSummary(catalog, tree, providerId, summary) {
+ if (!summary.includes('{@link')) return summary;
+ let provider;
+ try {
+ provider = normalizeProviderId(providerId);
+ } catch {
+ return summary;
+ }
+ const find = docFinderOver(catalog, tree, provider, false);
+ const linked = await linkFields({summary}, async target => {
+ const found = await find(target);
+ return 'problem' in found ? found : found.link;
+ });
+ return linked.doc.summary;
+}
+
/** @type {WeakMap<DocsTree, Map<string, TreeNode>>} */
const identitiesByTree = new WeakMap();
@@ -430,7 +553,22 @@ async function authoringDoc(catalog, kind, name) {
* @returns {Promise<(target: string) => Promise<FoundDoc | {problem: string}>>}
*/
async function docFinder(catalog, fromProvider) {
- const identities = identitiesOf(await projectTree(catalog));
+ return docFinderOver(catalog, await projectTree(catalog), fromProvider);
+}
+
+/**
+ * {@link docFinder} over a tree already built, so building the tree can
+ * resolve the links in its own summaries.
+ * @param {DocsCatalog} catalog
+ * @param {DocsTree} tree
+ * @param {string} fromProvider
+ * @param {boolean} [summaries] resolve the links in a found flat topic's
+ * summary; off while a summary is itself being resolved, so two summaries
+ * that link each other cannot loop
+ * @returns {(target: string) => Promise<FoundDoc | {problem: string}>}
+ */
+function docFinderOver(catalog, tree, fromProvider, summaries = true) {
+ const identities = identitiesOf(tree);
return async target => {
const parsed = parseLinkTarget(target);
if ('error' in parsed)
@@ -502,6 +640,14 @@ async function docFinder(catalog, fromProvider) {
const raw = await lowerRawTopic(catalog, entry);
title = raw.doc.title ?? title;
summary = raw.doc.description ?? summary;
+ if (summaries) {
+ summary = await linkSummary(
+ catalog,
+ tree,
+ providerOf(entry),
+ summary,
+ );
+ }
} catch {
// The topic budget check reports a topic that does not load; the
// link still opens it.
@@ -527,8 +673,20 @@ async function docFinder(catalog, fromProvider) {
parsed.kind,
parsed.name,
);
- if (link)
+ if (link) {
+ // The summary is the target doc's own text, so its links resolve
+ // against the target's provider, never the linking doc's: a Core
+ // component's against the CLI's docs, like its other fields.
+ if (summaries && link.summary.includes('{@link')) {
+ link.summary = await linkSummary(
+ catalog,
+ tree,
+ provider === CORE_COMPONENT_PROVIDER ? CLI_PROVIDER_ID : provider,
+ link.summary,
+ );
+ }
return {link: {target, ...link}, kind: parsed.kind, typed: null};
+ }
}
const searchType =
parsed.kind === 'component'
@@ -581,6 +739,15 @@ function bareLinkHint(error, target, catalog, identities, fromProvider) {
return `${error}, and no topic is named "${name}". Link a doc that exists, as \`{@link generic:<topic>}\` (\`astryx docs\` lists the topics), or remove the link.`;
}
+/** The provider Core's components and templates belong to. */
+const CORE_COMPONENT_PROVIDER = (() => {
+ try {
+ return normalizeProviderId(CORE_PACKAGE);
+ } catch {
+ return CORE_PACKAGE;
+ }
+})();
+
/** The doc kinds no docs tree holds: components and templates. */
const CONTRIBUTED_KINDS = new Set(['component', 'page', 'block']);
@@ -911,7 +1078,7 @@ export async function docsLinkProblems(
for (const problem of found) {
if ((problem.include === true) !== references) continue;
problems.push(
- `${where}${problem.section ? ` \u00a7 ${problem.section}` : ''}: ${problem.message}`,
+ `${where}${problem.section ? ` \u00a7 ${problem.section}` : ''}${problem.field ? ` (${problem.field})` : ''}: ${problem.message}`,
);
}
};
@@ -946,6 +1113,83 @@ export async function docsLinkProblems(
return problems;
}
+/**
+ * The catalog one integration package's docs and links read, as doctor checks
+ * it before any app configures it: the CLI's topics, Core's and the package's
+ * components and templates, and the package's own docs.
+ * @param {any} integration
+ * @param {{records: import('../../foundation/discovery/docs-discovery.mjs').DocsTopicRecord[], namespaces: import('../../foundation/doc-compiler/tree.mjs').TreeNamespaceInput[], guides: import('../../foundation/doc-compiler/tree.mjs').TreeDocInput[]} | null} discovered
+ * @returns {DocsCatalog}
+ */
+function packageCatalog(integration, discovered) {
+ const catalog = DocsCatalog.fromBuiltins();
+ catalog.setContributions(() => packageContributions(integration));
+ if (discovered) {
+ for (const record of discovered.records) catalog.add(record);
+ catalog.addTreeInputs({
+ namespaces: discovered.namespaces.map(input => ({...input, rank: 1})),
+ guides: discovered.guides.map(input => ({...input, rank: 1})),
+ });
+ }
+ return catalog;
+}
+
+/**
+ * What \`astryx doctor integration components\` checks of the links in one
+ * integration's own component docs (spec:AST-047 FR9): each link in a
+ * description, usage, best practice, or prop's or example's description that
+ * names no doc. It prints as written, so each is a warning.
+ * @param {any} integration a loaded integration
+ * @param {Parameters<typeof packageCatalog>[1]} discovered the package's own
+ * docs, which its components' links may name; null when it ships none
+ * @returns {Promise<Array<{severity: 'warning', message: string}>>}
+ */
+export async function packageComponentLinkProblems(integration, discovered) {
+ const catalog = packageCatalog(integration, discovered);
+ return (await componentLinkProblems(catalog, integration.name)).map(
+ message => ({severity: /** @type {const} */ ('warning'), message}),
+ );
+}
+
+/**
+ * Each link in a package's own component docs that names no doc. A family doc
+ * that documents several components is read once.
+ * @param {DocsCatalog} catalog
+ * @param {string} owner the package whose component docs are read
+ * @returns {Promise<string[]>}
+ */
+async function componentLinkProblems(catalog, owner) {
+ const contributions = await catalog.contributions();
+ /** @type {string[]} */
+ const problems = [];
+ const seen = new Set();
+ for (const record of contributions?.components ?? []) {
+ if (record.package !== owner || !record.docPath) continue;
+ if (seen.has(record.docPath)) continue;
+ seen.add(record.docPath);
+ /** @type {any} */
+ let doc;
+ try {
+ doc = await loadComponentDoc(record.docPath);
+ } catch {
+ // The components check reports a doc that does not load.
+ continue;
+ }
+ const linked = await linkComponentDoc(
+ catalog,
+ componentLinkProvider(record.package, record.providerId),
+ doc,
+ );
+ const name = typeof doc?.name === 'string' ? doc.name : record.name;
+ for (const problem of linked.problems) {
+ problems.push(
+ `component ${name}${problem.field ? ` (${problem.field})` : ''}: ${problem.message}`,
+ );
+ }
+ }
+ return problems;
+}
+
/**
* What \`astryx doctor integration docs\` checks in one integration's docs: the
* docs tree they build beside the CLI's (namespaces, placements, routes) and
@@ -957,13 +1201,7 @@ export async function docsLinkProblems(
* @returns {Promise<Array<{severity: 'error' | 'warning', message: string}>>}
*/
export async function packageDocsProblems(integration, discovered) {
- const catalog = DocsCatalog.fromBuiltins();
- catalog.setContributions(() => packageContributions(integration));
- for (const record of discovered.records) catalog.add(record);
- catalog.addTreeInputs({
- namespaces: discovered.namespaces.map(input => ({...input, rank: 1})),
- guides: discovered.guides.map(input => ({...input, rank: 1})),
- });
+ const catalog = packageCatalog(integration, discovered);
const tree = await projectTree(catalog);
/** @type {Array<{severity: 'error' | 'warning', message: string}>} */
const problems = tree.diagnostics
diff --git a/packages/cli/api/docs/list/list.mjs b/packages/cli/api/docs/list/list.mjs
index b689de9ce4..39d5c6fa23 100644
--- a/packages/cli/api/docs/list/list.mjs
+++ b/packages/cli/api/docs/list/list.mjs
@@ -15,7 +15,12 @@
*/
import {loadTopicFile} from '../../../foundation/doc-compiler/read.mjs';
-import {holdsOwnName, loadDocsCatalog, projectTree} from '../_adapter.mjs';
+import {
+ holdsOwnName,
+ linkDocText,
+ loadDocsCatalog,
+ projectTree,
+} from '../_adapter.mjs';
/**
* @param {object} [options]
@@ -39,7 +44,12 @@ export async function list({cwd} = {}) {
/** @type {import('../docs.type.mjs').DocsListEntry} */
const listed = {
topic: entry.name,
- description,
+ // A link in the description reads as the command that opens its doc.
+ description: await linkDocText(
+ catalog,
+ entry.providerId ?? entry.package,
+ description,
+ ),
package: entry.package,
};
if (entry.replaces != null) listed.replaces = entry.replaces;
diff --git a/packages/cli/api/integration/_adapter.mjs b/packages/cli/api/integration/_adapter.mjs
index 63dbe6e47d..1b6753c600 100644
--- a/packages/cli/api/integration/_adapter.mjs
+++ b/packages/cli/api/integration/_adapter.mjs
@@ -83,12 +83,30 @@ export function integrationFluff(discovered) {
/**
* Code spans in a package's prose that write `astryx docs <name>` for a doc
* that exists, where `{@link generic:<name>}` would be checked
- * (architecture:cli-surface DEC-8). Reads the package's topics and the names
- * of Core's docs.
+ * (architecture:cli-surface DEC-8). Reads the package's topics, its own
+ * component docs, and the names of Core's docs.
*
* @param {Parameters<typeof findStrayPointers>[0]} discovered the package's
* docs, as discoverIntegrationDocs returns them
+ * @param {any} [integration] the loaded integration, whose component docs are
+ * read too
*/
-export function integrationStrayPointers(discovered) {
- return findStrayPointers(discovered);
+export async function integrationStrayPointers(discovered, integration) {
+ /** @type {{name: string, file: string}[]} */
+ const components = [];
+ if (integration?.components) {
+ const seen = new Set();
+ try {
+ const {components: records} =
+ await discoverValidIntegrationComponents(integration);
+ for (const record of records) {
+ if (!record.docPath || seen.has(record.docPath)) continue;
+ seen.add(record.docPath);
+ components.push({name: record.name, file: record.docPath});
+ }
+ } catch {
+ // `validate` reports component docs that do not load.
+ }
+ }
+ return findStrayPointers({...discovered, components});
}
diff --git a/packages/cli/api/integration/authoring-checks.mjs b/packages/cli/api/integration/authoring-checks.mjs
index 29b88f84c5..2a36dcd11e 100644
--- a/packages/cli/api/integration/authoring-checks.mjs
+++ b/packages/cli/api/integration/authoring-checks.mjs
@@ -21,6 +21,7 @@
import path from 'node:path';
import {getCliInvocation} from '../../foundation/env/package-manager.mjs';
import {
+ packageComponentLinkProblems,
packageDocsProblems,
packageReferenceProblems,
} from '../docs/_adapter.mjs';
@@ -257,6 +258,19 @@ export async function integrationComponentConflicts(pkg, options = {}) {
// the project's own compiler; without one the report says it was skipped.
const propDrift = await integrationPropDrift(resolved.integration, cwd);
+ // A link in a component doc's text reads as the command that opens its doc,
+ // as one in a topic does; one that names no doc prints as written, so it is
+ // a warning (spec:AST-047 FR9). The package's own topics are linkable.
+ const ownDocs = resolved.integration.docs
+ ? await discoverIntegrationDocs(resolved.integration)
+ : null;
+ for (const {severity, message} of await packageComponentLinkProblems(
+ resolved.integration,
+ ownDocs,
+ )) {
+ issues.push({code: 'invalid_doc_graph', severity, message});
+ }
+
const coreDir = findCoreDir(cwd);
if (!coreDir) {
issues.push({
@@ -335,7 +349,29 @@ export async function integrationDocConflicts(pkg, options = {}) {
const fluff = [];
/** @type {import('./authoring-checks.type.mjs').StrayPointer[]} */
const strayPointers = [];
+ // Like the other findings' `doc`, a fluff or stray-pointer `file` is
+ // relative to the package root.
+ const packageDir = /** @type {any} */ (resolved.integration)?.__packageDir;
+ const fromPackage = (/** @type {string} */ file) =>
+ typeof packageDir === 'string'
+ ? path.relative(packageDir, file).split(path.sep).join('/')
+ : file;
if (!resolved.integration?.docs || name == null) {
+ // A package that ships components and no topics still has component docs
+ // a written pointer can sit in.
+ if (name != null && resolved.integration?.components) {
+ strayPointers.push(
+ ...(
+ await integrationStrayPointers(
+ {records: [], guides: []},
+ resolved.integration,
+ )
+ ).map(each => ({...each, file: fromPackage(each.file)})),
+ );
+ for (const {message} of strayPointers) {
+ issues.push({code: 'stray_doc_pointer', severity: 'warning', message});
+ }
+ }
return {
type: 'integration.doc-conflicts',
data: {
@@ -448,13 +484,6 @@ export async function integrationDocConflicts(pkg, options = {}) {
}
// Docs should be dense: padding phrases and mostly-glue topics, listed
// and warned about the same way (DEC-8).
- // Like the other findings' `doc`, a fluff or stray-pointer `file` is
- // relative to the package root.
- const packageDir = /** @type {any} */ (resolved.integration).__packageDir;
- const fromPackage = (/** @type {string} */ file) =>
- typeof packageDir === 'string'
- ? path.relative(packageDir, file).split(path.sep).join('/')
- : file;
fluff.push(
...(await integrationFluff(discovered)).map(each => ({
...each,
@@ -466,10 +495,9 @@ export async function integrationDocConflicts(pkg, options = {}) {
}
// A pointer to a doc is a link, so doctor checks it (DEC-8).
strayPointers.push(
- ...(await integrationStrayPointers(discovered)).map(each => ({
- ...each,
- file: fromPackage(each.file),
- })),
+ ...(await integrationStrayPointers(discovered, resolved.integration)).map(
+ each => ({...each, file: fromPackage(each.file)}),
+ ),
);
for (const {message} of strayPointers) {
issues.push({code: 'stray_doc_pointer', severity: 'warning', message});
diff --git a/packages/cli/api/integration/authoring-checks.test.mjs b/packages/cli/api/integration/authoring-checks.test.mjs
index c565d511a7..e875c4c785 100644
--- a/packages/cli/api/integration/authoring-checks.test.mjs
+++ b/packages/cli/api/integration/authoring-checks.test.mjs
@@ -1103,7 +1103,8 @@ describe('integrationDocConflicts stray doc pointers', () => {
await integrationDocConflicts(undefined, {cwd: tmpDir}),
).filter((/** @type {any} */ each) => each.topic === 'acme-setup');
- expect(found.map((/** @type {any} */ each) => each.line)).toEqual([9]);
+ // The summary's own pointer is listed too, at its line.
+ expect(found.map((/** @type {any} */ each) => each.line)).toEqual([5, 9]);
});
it('lists a written pointer to a doc with the link that replaces it, and warns', async () => {
@@ -1149,7 +1150,7 @@ describe('integrationDocConflicts stray doc pointers', () => {
expect(hit.link).toBe('{@link @astryxdesign/cli:namespace:layout}');
});
- it('finds the line in the string that holds the pointer, not in the summary or code', async () => {
+ it('finds each line in the string that holds the pointer, not in code', async () => {
writeTopics([]);
fs.writeFileSync(
path.join(tmpDir, 'docs', 'acme-lines.doc.mjs'),
@@ -1172,7 +1173,8 @@ describe('integrationDocConflicts stray doc pointers', () => {
await integrationDocConflicts(undefined, {cwd: tmpDir}),
);
- expect(found.map((/** @type {any} */ each) => each.line)).toEqual([8]);
+ // The description resolves links too, so its pointer is its own finding.
+ expect(found.map((/** @type {any} */ each) => each.line)).toEqual([5, 8]);
});
it('leaves a command for a doc that does not exist, and a walkthrough', async () => {
@@ -1188,3 +1190,144 @@ describe('integrationDocConflicts stray doc pointers', () => {
).toEqual([]);
});
});
+
+/**
+ * A package with one component doc and, optionally, one topic.
+ * @param {{usage: string, topicDescription?: string}} fixture
+ */
+function writeLinkedComponent({usage, topicDescription}) {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.integration.mjs'),
+ topicDescription == null
+ ? `export default {components: './components'};\n`
+ : `export default {components: './components', docs: './docs'};\n`,
+ );
+ fs.mkdirSync(path.join(tmpDir, 'components'), {recursive: true});
+ const doc = {
+ type: 'component',
+ name: 'AcmeButton',
+ displayName: 'Acme Button',
+ usage: {description: usage},
+ props: [],
+ };
+ fs.writeFileSync(
+ path.join(tmpDir, 'components', 'AcmeButton.doc.mjs'),
+ `export default ${JSON.stringify(doc, null, 2)};\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'components', 'AcmeButton.tsx'),
+ 'export function AcmeButton() { return null; }\n',
+ );
+ if (topicDescription == null) return;
+ fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});
+ const topic = {
+ type: 'generic',
+ name: 'acme-setup',
+ title: 'Fixture',
+ description: topicDescription,
+ sections: [
+ {title: 'Overview', content: [{type: 'prose', text: 'Install it.'}]},
+ ],
+ };
+ fs.writeFileSync(
+ path.join(tmpDir, 'docs', 'acme-setup.doc.mjs'),
+ `export default ${JSON.stringify(topic, null, 2)};\n`,
+ );
+}
+
+describe('links in component docs and topic descriptions', () => {
+ it("warns on a component doc's link that names no doc, and passes one to its own topic", async () => {
+ writeLinkedComponent({
+ usage:
+ 'Set it up as {@link generic:acme-setup} says, theme it with {@link @astryxdesign/cli:generic:theme}, then {@link generic:acme-nothing}.',
+ topicDescription: 'Install Acme.',
+ });
+
+ const {data} = await integrationComponentConflicts(undefined, {
+ cwd: tmpDir,
+ });
+ const links = data.issues.filter(
+ (/** @type {any} */ issue) => issue.code === 'invalid_doc_graph',
+ );
+ expect(links).toEqual([
+ {
+ code: 'invalid_doc_graph',
+ severity: 'warning',
+ message: expect.stringMatching(
+ /^component AcmeButton \(usage\.description\): "generic:acme-nothing" names no doc\./,
+ ),
+ },
+ ]);
+ });
+
+ it("warns on a topic description's link that names no doc", async () => {
+ writeLinkedComponent({
+ usage: 'A button.',
+ topicDescription: 'Install Acme; see {@link generic:acme-nothing}.',
+ });
+
+ const {data} = await integrationDocConflicts(undefined, {cwd: tmpDir});
+ const links = data.issues.filter(
+ (/** @type {any} */ issue) => issue.code === 'invalid_doc_graph',
+ );
+ expect(links).toEqual([
+ {
+ code: 'invalid_doc_graph',
+ severity: 'warning',
+ message: expect.stringMatching(
+ /^acme-setup \(description\): "generic:acme-nothing" names no doc\./,
+ ),
+ },
+ ]);
+ });
+
+ it('lists a written pointer in a component doc, with the link that replaces it', async () => {
+ writeLinkedComponent({usage: 'Theme it as `astryx docs theme` says.'});
+
+ const {data} = await integrationDocConflicts(undefined, {cwd: tmpDir});
+ const [pointer, ...rest] = data.strayPointers;
+
+ expect(rest).toEqual([]);
+ expect(pointer).toMatchObject({
+ topic: 'AcmeButton',
+ kind: 'component',
+ section: null,
+ field: 'usage.description',
+ file: 'components/AcmeButton.doc.mjs',
+ pointer: 'astryx docs theme',
+ link: '{@link @astryxdesign/cli:generic:theme}',
+ });
+ expect(pointer.line).toEqual(expect.any(Number));
+ expect(pointer.message).toBe(
+ `component "AcmeButton" (field usage.description, line ${pointer.line}) points at a doc with the written command \`astryx docs theme\`. ` +
+ 'Replace `astryx docs theme`, code ticks included, with {@link @astryxdesign/cli:generic:theme}: the CLI prints the command that opens the doc, and doctor checks the link.',
+ );
+ expect(data.issues).toContainEqual({
+ code: 'stray_doc_pointer',
+ severity: 'warning',
+ message: pointer.message,
+ });
+ });
+
+ it("lists a written pointer in a topic's description", async () => {
+ writeLinkedComponent({
+ usage: 'A button.',
+ topicDescription: 'Install Acme; theme it as `astryx docs theme` says.',
+ });
+
+ const {data} = await integrationDocConflicts(undefined, {cwd: tmpDir});
+
+ expect(data.strayPointers).toEqual([
+ expect.objectContaining({
+ topic: 'acme-setup',
+ kind: 'topic',
+ field: 'description',
+ link: '{@link @astryxdesign/cli:generic:theme}',
+ }),
+ ]);
+ });
+});
diff --git a/packages/cli/api/integration/authoring-checks.type.mjs b/packages/cli/api/integration/authoring-checks.type.mjs
index e594711272..124fbd337a 100644
--- a/packages/cli/api/integration/authoring-checks.type.mjs
+++ b/packages/cli/api/integration/authoring-checks.type.mjs
@@ -93,8 +93,13 @@
* it (architecture:cli-surface DEC-8).
*
* @typedef {object} StrayPointer
- * @property {string} topic the package topic that has it
+ * @property {string} topic the package topic, or component doc, that has it
+ * @property {'topic' | 'component'} kind whether it sits in a topic or a
+ * component doc
* @property {string | null} section the title of the section it is in
+ * @property {string | null} field the field it is in outside any section: a
+ * topic's `description` or `summary`, or a component doc's field path, such
+ * as `usage.bestPractices[0].description`
* @property {string} file the doc file, relative to the package root
* @property {number | null} line the file line that holds it, when found
* @property {string} pointer the written command, `astryx docs <name>`
diff --git a/packages/cli/api/integration/integrationComponentConflicts.doc.mjs b/packages/cli/api/integration/integrationComponentConflicts.doc.mjs
index fd70d3b5b4..04a2f22b30 100644
--- a/packages/cli/api/integration/integrationComponentConflicts.doc.mjs
+++ b/packages/cli/api/integration/integrationComponentConflicts.doc.mjs
@@ -17,6 +17,8 @@ export const doc = {
"component command required to keep an intentional overlap. Each component's " +
'replaces is checked too: its findings are issues, errors for a package that ' +
'declares the CLI range that turns replacement on and warnings otherwise. ' +
+ "A `{@link}` in a component doc's text that names no doc is an `invalid_doc_graph` " +
+ 'warning, since it prints as written. ' +
"Each component doc's props are compared with the component's TypeScript props, " +
"read with the project's own `typescript` (or, where `typescript` is missing or has no " +
'JavaScript compiler API, as TypeScript 7 does, the `@typescript/typescript6` it ' +
diff --git a/packages/cli/api/integration/integrationDocConflicts.doc.mjs b/packages/cli/api/integration/integrationDocConflicts.doc.mjs
index 5028f19884..9b1daec7a9 100644
--- a/packages/cli/api/integration/integrationDocConflicts.doc.mjs
+++ b/packages/cli/api/integration/integrationDocConflicts.doc.mjs
@@ -19,8 +19,9 @@ export const doc = {
"package's topics, or one of them and a Core topic other than the one it replaces. " +
'Code and examples are not compared. `fluff` lists each padding phrase, with its file ' +
'line, and each topic of 80 or more prose words in which fewer than half carry content. ' +
- '`strayPointers` lists each code span in prose that is exactly `astryx docs <name>` for a ' +
- 'doc that exists, with the `{@link}` that replaces it. ' +
+ '`strayPointers` lists each code span that is exactly `astryx docs <name>` for a doc that ' +
+ "exists, in a topic's prose, description or summary or a component doc's text fields, " +
+ 'with the `{@link}` that replaces it. ' +
'Each entry of these lists is also a warning (`copied_passage`, `doc_fluff`, `stray_doc_pointer`), so ' +
'`integration check --strict` fails on it; the check itself still fails only on errors.',
importPath: '@astryxdesign/cli/api',
diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjs
index 820f1f8e77..b77ccc362f 100644
--- a/packages/cli/api/search/search.mjs
+++ b/packages/cli/api/search/search.mjs
@@ -129,6 +129,7 @@ import {
import {AstryxError} from '../error.mjs';
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
import {setResultCoverage} from './coverage.mjs';
+import {linkSearchResponse} from '../component/_adapter.mjs';
/**
* A search candidate gathered from one content domain. Extra underscore-
@@ -2485,5 +2486,5 @@ async function searchOnce(query, options) {
components.map(c => ({name: c.name, keywords: c.keywords ?? []})),
);
}
- return response;
+ return linkSearchResponse(response, cwd);
}
diff --git a/packages/cli/assets/docs/tree/checks.doc.mjs b/packages/cli/assets/docs/tree/checks.doc.mjs
index b129afef1e..eb1509c23f 100644
--- a/packages/cli/assets/docs/tree/checks.doc.mjs
+++ b/packages/cli/assets/docs/tree/checks.doc.mjs
@@ -38,7 +38,7 @@ export const docs = {
'`npx astryx doctor integration components`',
"No component name clashes with a Core component, each `replaces` names one Core component, and each component doc's props match the component's TypeScript props",
'Core is not installed (`core_not_found`). In a package that declares the CLI range that turns replacement on, a `replaces` target is missing (`missing_component_replacement_target`) or invalid (`invalid_component_replacement`), or two components replace one Core component (`ambiguous_component_replacement`)',
- 'A name clashes with Core, a component sets `replaces` in a package without that range (`inactive_component_replacement`, plus any missing, invalid, or duplicate `replaces` reported as a warning), or a documented prop differs from the code: it is missing there (`not_in_code`), the doc omits a prop the package declares (`not_in_doc`), or its `required` (`required_mismatch`), type (`type_mismatch`), or literal `default` (`default_mismatch`) disagrees. It reads props with your installed `typescript`; without it, it prints `[skip] Props not compared`',
+ 'A name clashes with Core, a component sets `replaces` in a package without that range (`inactive_component_replacement`, plus any missing, invalid, or duplicate `replaces` reported as a warning), or a documented prop differs from the code: it is missing there (`not_in_code`), the doc omits a prop the package declares (`not_in_doc`), or its `required` (`required_mismatch`), type (`type_mismatch`), or literal `default` (`default_mismatch`) disagrees, or a `{@link}` in a component doc names no doc (`invalid_doc_graph`). It reads props with your installed `typescript`; without it, it prints `[skip] Props not compared`',
],
[
'`npx astryx doctor integration templates`',
@@ -50,7 +50,7 @@ export const docs = {
'`npx astryx doctor integration docs`',
'Your docs tree, every link, topic names against Core, passages two topics repeat word for word, padding phrases and low-density topics, and written pointers to docs',
'A topic takes a Core topic name without `replaces` or `extends`, a doc is invalid (`invalid_doc`), or a namespace or placement fails, which hides the doc (`invalid_doc_graph`)',
- 'A link names no doc (`invalid_doc_graph`), two topics repeat a passage word for word (`copied_passage`), prose pads with a listed phrase or falls under the density floor (`doc_fluff`), or prose writes `astryx docs <name>` where a link would be checked (`stray_doc_pointer`)',
+ 'A link names no doc (`invalid_doc_graph`), two topics repeat a passage word for word (`copied_passage`), prose pads with a listed phrase or falls under the density floor (`doc_fluff`), or prose, a description or summary, or the text of a component doc writes `astryx docs <name>` where a link would be checked (`stray_doc_pointer`)',
],
[
'`npx astryx integration check`',
diff --git a/packages/cli/assets/docs/tree/document-the-theme.doc.mjs b/packages/cli/assets/docs/tree/document-the-theme.doc.mjs
index d14900ac00..577e3ab449 100644
--- a/packages/cli/assets/docs/tree/document-the-theme.doc.mjs
+++ b/packages/cli/assets/docs/tree/document-the-theme.doc.mjs
@@ -13,7 +13,7 @@ export const docs = {
title: 'Document the theme',
category: 'guide',
description:
- 'Document a theme by extending the core theme topic, so an app reads it in `astryx docs theme`.',
+ 'Document a theme by extending the core theme topic, so an app reads it in {@link generic:theme}.',
sections: [
{
id: 'extend-the-theme-topic',
diff --git a/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs
index e984a5b9c4..2014c94c7b 100644
--- a/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs
+++ b/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs
@@ -27,7 +27,8 @@ export const doc = {
'`required`, and a type that does not match where both sides read exactly ' +
'(it lists every other documented type as not compared, with the reason). ' +
'Without TypeScript it prints one ' +
- 'line saying the comparison was skipped.',
+ 'line saying the comparison was skipped. It also warns on each `{@link}` in ' +
+ "a component doc's text that names no doc.",
fn: 'integrationComponentConflicts',
args: [
{
@@ -51,7 +52,7 @@ export const doc = {
exitCodes: [
{
code: 0,
- when: 'the check completed; component name conflicts, replaces findings for a package without the CLI range, and props that differ from the code are warnings',
+ when: 'the check completed; component name conflicts, replaces findings for a package without the CLI range, props that differ from the code, and links that name no doc are warnings',
},
{
code: 1,
diff --git a/packages/cli/foundation/discovery/stray-pointers.mjs b/packages/cli/foundation/discovery/stray-pointers.mjs
index 1cfe033250..669d6e8c42 100644
--- a/packages/cli/foundation/discovery/stray-pointers.mjs
+++ b/packages/cli/foundation/discovery/stray-pointers.mjs
@@ -13,6 +13,7 @@
import fs from 'node:fs';
+import {textFields} from '../doc-compiler/links.mjs';
import {builtinGuideFiles} from './docs-discovery.mjs';
import {
fileWords,
@@ -52,17 +53,32 @@ function loadCoreKinds() {
}
/**
- * The strings of a doc the compiler resolves links in: the text of prose and
- * heading blocks, list items, and table cells, in each section's content, with
- * the section's title. A summary or other field prints a link as written, so
- * it is not read.
+ * The strings of a doc the CLI resolves links in (spec:AST-047 FR9). In a
+ * topic: its description and summary, then the text of prose and heading
+ * blocks, list items, and table cells in each section's content, with the
+ * section's title. In a component doc (any doc with no sections): every text
+ * field, such as its description, usage, best practices, and each prop's and
+ * example's description, with the field's path. Code is never read.
*
* @param {unknown} doc an authored doc object
- * @returns {{text: string, section: string | null}[]}
+ * @returns {{text: string, section: string | null, field: string | null}[]}
*/
export function linkableStrings(doc) {
- /** @type {{text: string, section: string | null}[]} */
+ /** @type {{text: string, section: string | null, field: string | null}[]} */
const strings = [];
+ if (doc == null || typeof doc !== 'object') return strings;
+ const top = /** @type {Record<string, any>} */ (doc);
+ if (!Array.isArray(top.sections)) {
+ for (const {field, text} of textFields(doc)) {
+ strings.push({text, section: null, field});
+ }
+ return strings;
+ }
+ for (const field of ['description', 'summary']) {
+ if (typeof top[field] === 'string') {
+ strings.push({text: top[field], section: null, field});
+ }
+ }
/**
* @param {unknown} value
* @param {string | null} section
@@ -79,7 +95,9 @@ export function linkableStrings(doc) {
if (!Array.isArray(record.content)) return;
for (const block of record.content) {
const add = (/** @type {unknown} */ text) => {
- if (typeof text === 'string') strings.push({text, section: title});
+ if (typeof text === 'string') {
+ strings.push({text, section: title, field: null});
+ }
};
switch (block?.type) {
case 'prose':
@@ -143,20 +161,23 @@ function locateString(lines, file, text, words, from) {
}
/**
- * Each stray pointer in a package's topics.
+ * Each stray pointer in a package's topics and component docs.
*
- * @param {{records: {name: string, path: string}[], guides?: {name: string, ref?: {topicFile?: string}}[], namespaces?: {doc?: {name?: string}}[]}} discovered
+ * @param {{records: {name: string, path: string}[], guides?: {name: string, ref?: {topicFile?: string}}[], namespaces?: {doc?: {name?: string}}[], components?: {name: string, file: string}[]}} discovered
* @returns {Promise<import('../../api/integration/authoring-checks.type.mjs').StrayPointer[]>}
*/
export async function findStrayPointers(discovered) {
+ /** @type {{name: string, file: string | undefined, kind: 'topic' | 'component'}[]} */
const topics = [
...discovered.records.map(record => ({
name: record.name,
file: record.path,
+ kind: /** @type {const} */ ('topic'),
})),
...(discovered.guides ?? []).map(guide => ({
name: guide.name,
file: guide.ref?.topicFile,
+ kind: /** @type {const} */ ('topic'),
})),
];
/** @type {Map<string, string>} */
@@ -165,6 +186,13 @@ export async function findStrayPointers(discovered) {
const name = namespace?.doc?.name;
if (typeof name === 'string' && !own.has(name)) own.set(name, 'namespace');
}
+ for (const component of discovered.components ?? []) {
+ topics.push({
+ name: component.name,
+ file: component.file,
+ kind: 'component',
+ });
+ }
const core = await loadCoreKinds();
// A topic that extends another has no route of its own: a link to it names
// the page it shows on, the topic it extends.
@@ -210,10 +238,17 @@ export async function findStrayPointers(discovered) {
} catch {
// No line numbers; the finding still names the section.
}
+ // A component doc is named by its own name: a family doc by the family.
+ const name =
+ topic.kind === 'component' && typeof doc.name === 'string'
+ ? doc.name
+ : topic.name;
+ const label =
+ topic.kind === 'component' ? `component "${name}"` : `"${name}"`;
// Each string is found by its whole run of words, from where the last
// one was found, so two strings that open alike keep their own lines.
let cursor = 0;
- for (const {text, section} of linkableStrings(doc)) {
+ for (const {text, section, field} of linkableStrings(doc)) {
const words = textWords(text);
const index = locateString(lines, source, text, words, cursor);
if (index >= 0) cursor = index + words.length;
@@ -233,19 +268,22 @@ export async function findStrayPointers(discovered) {
);
const where = [
section ? `section "${section}"` : null,
+ field ? `field ${field}` : null,
line == null ? null : `line ${line}`,
]
.filter(Boolean)
.join(', ');
found.push({
- topic: topic.name,
+ topic: name,
+ kind: topic.kind,
section,
+ field,
file: topic.file,
line,
pointer: command,
link,
message:
- `"${topic.name}"${where ? ` (${where})` : ''} points at a doc with the written command \`${command}\`. ` +
+ `${label}${where ? ` (${where})` : ''} points at a doc with the written command \`${command}\`. ` +
`Replace \`${command}\`, code ticks included, with ${link}: the CLI prints the command that opens the doc, and doctor checks the link.`,
});
}
diff --git a/packages/cli/foundation/discovery/stray-pointers.test.mjs b/packages/cli/foundation/discovery/stray-pointers.test.mjs
index 0fec23fb37..e0bcce372d 100644
--- a/packages/cli/foundation/discovery/stray-pointers.test.mjs
+++ b/packages/cli/foundation/discovery/stray-pointers.test.mjs
@@ -29,10 +29,11 @@ describe('pointersIn', () => {
});
describe('linkableStrings', () => {
- it('reads prose, headings, list items and table cells, not the summary or code', () => {
+ it("reads a topic's description and summary, then prose, headings, list items and table cells, not code", () => {
const strings = linkableStrings({
name: 'acme',
description: 'Read `astryx docs theme`.',
+ summary: 'In short.',
sections: [
{
title: 'Use it',
@@ -47,11 +48,39 @@ describe('linkableStrings', () => {
],
});
expect(strings).toEqual([
- {text: 'prose', section: 'Use it'},
- {text: 'heading', section: 'Use it'},
- {text: 'item', section: 'Use it'},
- {text: 'head', section: 'Use it'},
- {text: 'cell', section: 'Use it'},
+ {text: 'Read `astryx docs theme`.', section: null, field: 'description'},
+ {text: 'In short.', section: null, field: 'summary'},
+ {text: 'prose', section: 'Use it', field: null},
+ {text: 'heading', section: 'Use it', field: null},
+ {text: 'item', section: 'Use it', field: null},
+ {text: 'head', section: 'Use it', field: null},
+ {text: 'cell', section: 'Use it', field: null},
+ ]);
+ });
+
+ it("reads a component doc's text fields, not its names, types, defaults, or code", () => {
+ const strings = linkableStrings({
+ type: 'component',
+ name: 'AcmeButton',
+ displayName: 'Acme Button',
+ usage: {
+ description: 'usage',
+ bestPractices: [{guidance: true, description: 'practice'}],
+ },
+ props: [
+ {name: 'tone', type: 'string', default: "'a'", description: 'prop'},
+ ],
+ examples: [{label: 'example', code: 'astryx docs theme'}],
+ });
+ expect(strings).toEqual([
+ {text: 'usage', section: null, field: 'usage.description'},
+ {
+ text: 'practice',
+ section: null,
+ field: 'usage.bestPractices[0].description',
+ },
+ {text: 'prop', section: null, field: 'props[0].description'},
+ {text: 'example', section: null, field: 'examples[0].label'},
]);
});
});
diff --git a/packages/cli/foundation/doc-compiler/links.mjs b/packages/cli/foundation/doc-compiler/links.mjs
index ead57fc8f8..5fb08431cb 100644
--- a/packages/cli/foundation/doc-compiler/links.mjs
+++ b/packages/cli/foundation/doc-compiler/links.mjs
@@ -65,6 +65,8 @@ const CODE_SPAN = /(`[^`]*`)/;
* @property {string} target the target as written
* @property {string} message
* @property {string} [section] the key of the section the link sits in
+ * @property {string} [field] the field the link sits in, outside any section:
+ * `description`, or a path such as `props[2].description`
* @property {true} [include] the problem is in a `reference` block, which
* includes content rather than linking to it: a reader loses that content,
* so the authoring check fails on it
@@ -91,7 +93,11 @@ export function parseLinkTarget(target) {
};
}
const parts = target.trim().split(':');
- if (parts.length < 2 || parts.length > 3 || parts.some(p => p.trim() === '')) {
+ if (
+ parts.length < 2 ||
+ parts.length > 3 ||
+ parts.some(p => p.trim() === '')
+ ) {
return {error: `"${target}" is not \`[<provider>:]<kind>:<name>\``};
}
const provider = parts.length === 3 ? parts[0].trim() : null;
@@ -127,6 +133,159 @@ export function unlinkText(text) {
.join('');
}
+/**
+ * Text with each inline link replaced by the command that opens its doc. A
+ * link written inside code ticks is shown as written: it documents the syntax,
+ * it does not link. A link that names no doc prints as written: text that was
+ * never meant as a link reads the way it did, and doctor names the problem.
+ * @param {unknown} text
+ * @param {(target: string) => Promise<DocLink | null>} find
+ * @returns {Promise<any>}
+ */
+async function resolveInline(text, find) {
+ if (typeof text !== 'string' || !text.includes('{@link')) return text;
+ let out = '';
+ for (const part of text.split(CODE_SPAN)) {
+ if (part.startsWith('`')) {
+ out += part;
+ continue;
+ }
+ let last = 0;
+ for (const match of part.matchAll(INLINE_LINK)) {
+ const link = await find(match[1]);
+ const at = /** @type {number} */ (match.index);
+ out += part.slice(last, at);
+ out += link ? `\`${link.command}\`` : match[0];
+ last = at + match[0].length;
+ }
+ out += part.slice(last);
+ }
+ return out;
+}
+
+/**
+ * The fields of a doc that hold text a reader reads, where a link resolves:
+ * a description or summary, an example's label, and each value of a
+ * `propDescriptions` overlay. Every other string is a name, a type, a
+ * default, or code, and is shown as written.
+ */
+const TEXT_FIELDS = new Set(['description', 'summary', 'label']);
+
+/** Fields that hold code or data, never text: nothing below them links. */
+const CODE_FIELDS = new Set([
+ 'code',
+ 'playground',
+ 'slotElements',
+ 'registry',
+ 'keywords',
+]);
+
+/**
+ * Every text field of a doc object, in authored order, by the same rules
+ * {@link linkFields} resolves links by: the strings a reader reads, never a
+ * name, type, default, or code.
+ * @param {unknown} doc
+ * @returns {{field: string, text: string}[]}
+ */
+export function textFields(doc) {
+ /** @type {{field: string, text: string}[]} */
+ const out = [];
+ /**
+ * @param {unknown} value
+ * @param {string} at
+ * @param {boolean} text
+ */
+ const walk = (value, at, text) => {
+ if (typeof value === 'string') {
+ if (text) out.push({field: at, text: value});
+ return;
+ }
+ if (Array.isArray(value)) {
+ value.forEach((item, i) => walk(item, `${at}[${i}]`, false));
+ return;
+ }
+ if (value == null || typeof value !== 'object') return;
+ for (const [key, field] of Object.entries(value)) {
+ const path = at === '' ? key : `${at}.${key}`;
+ if (CODE_FIELDS.has(key)) continue;
+ if (key === 'propDescriptions' && field && typeof field === 'object') {
+ for (const [prop, description] of Object.entries(field)) {
+ walk(description, `${path}.${prop}`, true);
+ }
+ } else {
+ walk(field, path, TEXT_FIELDS.has(key));
+ }
+ }
+ };
+ walk(doc, '', false);
+ return out;
+}
+
+/**
+ * Resolve every inline link in the text fields of a doc object, such as a
+ * component doc or a topic's summary fields (spec:AST-047 FR9): its
+ * description, its usage and best practices, each prop's and example's
+ * description, at any depth. Code and code ticks show link syntax as written.
+ * @template T
+ * @param {T} doc
+ * @param {LinkResolver} resolve
+ * @returns {Promise<{doc: T, problems: LinkProblem[]}>}
+ */
+export async function linkFields(doc, resolve) {
+ /** @type {LinkProblem[]} */
+ const problems = [];
+ /**
+ * @param {unknown} value
+ * @param {string} at the field path, e.g. `usage.bestPractices[0].description`
+ * @param {boolean} text whether a string here is text
+ * @returns {Promise<any>}
+ */
+ const walk = async (value, at, text) => {
+ if (typeof value === 'string') {
+ if (!text) return value;
+ return resolveInline(value, async target => {
+ const found = await resolve(target);
+ if ('problem' in found) {
+ problems.push({target, message: found.problem, field: at});
+ return null;
+ }
+ return found;
+ });
+ }
+ if (Array.isArray(value)) {
+ const out = [];
+ for (let i = 0; i < value.length; i++) {
+ out.push(await walk(value[i], `${at}[${i}]`, false));
+ }
+ return out;
+ }
+ if (value == null || typeof value !== 'object') return value;
+ /** @type {Record<string, unknown>} */
+ const out = {};
+ for (const [key, field] of Object.entries(value)) {
+ const path = at === '' ? key : `${at}.${key}`;
+ if (CODE_FIELDS.has(key)) {
+ out[key] = field;
+ } else if (
+ key === 'propDescriptions' &&
+ field &&
+ typeof field === 'object'
+ ) {
+ /** @type {Record<string, unknown>} */
+ const described = {};
+ for (const [prop, description] of Object.entries(field)) {
+ described[prop] = await walk(description, `${path}.${prop}`, true);
+ }
+ out[key] = described;
+ } else {
+ out[key] = await walk(field, path, TEXT_FIELDS.has(key));
+ }
+ }
+ return out;
+ };
+ return {doc: await walk(doc, '', false), problems};
+}
+
/**
* Resolve every link in a list of content blocks, in order.
* @param {any[]} blocks
@@ -156,30 +315,7 @@ export async function linkBlocks(blocks, resolve, at = {}, include) {
* @param {unknown} text
* @returns {Promise<any>}
*/
- const linkText = async text => {
- if (typeof text !== 'string' || !text.includes('{@link')) return text;
- let out = '';
- // A link written inside code ticks is shown as written: it documents the
- // syntax, it does not link.
- for (const part of text.split(CODE_SPAN)) {
- if (part.startsWith('`')) {
- out += part;
- continue;
- }
- let last = 0;
- for (const match of part.matchAll(INLINE_LINK)) {
- const link = await find(match[1]);
- const at = /** @type {number} */ (match.index);
- out += part.slice(last, at);
- // A link that names no doc prints as written: text that was never
- // meant as a link reads the way it did, and doctor names the problem.
- out += link ? `\`${link.command}\`` : match[0];
- last = at + match[0].length;
- }
- out += part.slice(last);
- }
- return out;
- };
+ const linkText = text => resolveInline(text, find);
/**
* @param {unknown[]} values
* @returns {Promise<any[]>}
@@ -251,7 +387,8 @@ export async function linkBlocks(blocks, resolve, at = {}, include) {
}
if (Array.isArray(step.references)) {
const links = [];
- for (const target of step.references) links.push(await find(target));
+ for (const target of step.references)
+ links.push(await find(target));
linked.links = links;
}
steps.push(linked);
diff --git a/packages/cli/foundation/doc-compiler/links.test.mjs b/packages/cli/foundation/doc-compiler/links.test.mjs
index cd796d9646..0419c04c2d 100644
--- a/packages/cli/foundation/doc-compiler/links.test.mjs
+++ b/packages/cli/foundation/doc-compiler/links.test.mjs
@@ -8,8 +8,10 @@
import {describe, expect, it} from 'vitest';
import {
linkBlocks,
+ linkFields,
linkSections,
parseLinkTarget,
+ textFields,
unlinkText,
} from './links.mjs';
@@ -58,14 +60,20 @@ describe('linkBlocks', () => {
const {content, problems} = await linkBlocks(
[
{type: 'prose', text: 'Check it with {@link command:doctor}.'},
- {type: 'list', style: 'unordered', items: ['See {@link @acme/kit:generic:setup}']},
+ {
+ type: 'list',
+ style: 'unordered',
+ items: ['See {@link @acme/kit:generic:setup}'],
+ },
{type: 'table', headers: ['Doc'], rows: [['{@link command:doctor}']]},
{type: 'code', lang: 'js', code: '{@link command:doctor}'},
],
resolve,
);
expect(problems).toEqual([]);
- expect(content[0].text).toBe('Check it with `astryx docs cli/commands/doctor`.');
+ expect(content[0].text).toBe(
+ 'Check it with `astryx docs cli/commands/doctor`.',
+ );
expect(content[1].items).toEqual(['See `astryx docs acme/setup`']);
expect(content[2].rows).toEqual([['`astryx docs cli/commands/doctor`']]);
// Code is an example: it is shown as written.
@@ -74,7 +82,12 @@ describe('linkBlocks', () => {
it('shows a link written in code ticks as written', async () => {
const {content, problems} = await linkBlocks(
- [{type: 'prose', text: 'Write `{@link <target>}` to link; {@link command:doctor} checks it.'}],
+ [
+ {
+ type: 'prose',
+ text: 'Write `{@link <target>}` to link; {@link command:doctor} checks it.',
+ },
+ ],
resolve,
);
expect(problems).toEqual([]);
@@ -172,7 +185,10 @@ describe('linkBlocks', () => {
},
],
resolve,
- ).then(({sections, problems}) => ({content: sections[0].content, problems}));
+ ).then(({sections, problems}) => ({
+ content: sections[0].content,
+ problems,
+ }));
expect(content[0].text).toBe('See {@link command:nope}.');
expect(content[1].link).toBeNull();
expect(problems.map(p => [p.section, p.target])).toEqual([
@@ -190,3 +206,80 @@ describe('unlinkText', () => {
);
});
});
+
+describe('linkFields', () => {
+ /** A component doc with a link in every kind of text field, and in code. */
+ const DOC = {
+ name: 'AcmeButton',
+ description: 'Run {@link command:doctor} first.',
+ usage: {
+ description: 'Set it up: {@link @acme/kit:generic:setup}.',
+ bestPractices: [
+ {guidance: true, description: 'Check with {@link command:doctor}.'},
+ ],
+ },
+ props: [
+ {
+ name: 'tone',
+ type: '{@link command:doctor}',
+ default: "'{@link command:doctor}'",
+ description: 'Like `{@link command:doctor}`, or {@link generic:nope}.',
+ },
+ ],
+ propDescriptions: {tone: 'See {@link command:doctor}.'},
+ examples: [
+ {label: 'From {@link command:doctor}', code: '{@link command:doctor}'},
+ ],
+ playground: {defaults: {label: '{@link command:doctor}'}},
+ };
+
+ it('resolves each text field and leaves names, types, defaults, and code as written', async () => {
+ const {doc, problems} = await linkFields(DOC, resolve);
+ expect(doc).toEqual({
+ ...DOC,
+ description: 'Run `astryx docs cli/commands/doctor` first.',
+ usage: {
+ description: 'Set it up: `astryx docs acme/setup`.',
+ bestPractices: [
+ {
+ guidance: true,
+ description: 'Check with `astryx docs cli/commands/doctor`.',
+ },
+ ],
+ },
+ props: [
+ {
+ ...DOC.props[0],
+ description:
+ 'Like `{@link command:doctor}`, or {@link generic:nope}.',
+ },
+ ],
+ propDescriptions: {tone: 'See `astryx docs cli/commands/doctor`.'},
+ examples: [
+ {
+ label: 'From `astryx docs cli/commands/doctor`',
+ code: '{@link command:doctor}',
+ },
+ ],
+ });
+ expect(problems).toEqual([
+ {
+ target: 'generic:nope',
+ message: expect.any(String),
+ field: 'props[0].description',
+ },
+ ]);
+ });
+
+ it('names the same text fields textFields reads', async () => {
+ const {problems} = await linkFields(DOC, async target => ({
+ problem: `no ${target}`,
+ }));
+ const fields = textFields(DOC)
+ .filter(({text}) => text.replace(/`[^`]*`/g, '').includes('{@link'))
+ .map(({field}) => field);
+ expect([...new Set(problems.map(problem => problem.field))]).toEqual(
+ fields,
+ );
+ });
+});
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index c6aa5329ab..75e8a6bd2e 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -348,7 +348,7 @@ export const doc = {
{
value: 'integration.doc-conflicts',
description:
- 'validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` | `error`) and `relationship` (`replaces` | `extends` | `accidental`). copiedPassages lists each pair of topics that repeat 10 or more words of prose word for word: topic, section, otherTopic, otherOwner (package | core), words, passages, owner (the topic that should keep the text), text (the passage as the topic writes it), line (where the copy starts in the topic to change, or null), and message (the exact replacement); each is also a copied_passage warning in issues. fluff lists padding phrases and low-density topics: topic, kind (phrase | density), phrase, section, file (relative to the package root), line, density, and message (what to cut or write instead); each is also a doc_fluff warning in issues. strayPointers lists each code span in prose that is exactly `astryx docs <name>` for a doc that exists: topic, section, file (relative to the package root), line, pointer (the written command), link (the {@link} that replaces it), and message; each is also a stray_doc_pointer warning in issues.',
+ 'validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` | `error`) and `relationship` (`replaces` | `extends` | `accidental`). copiedPassages lists each pair of topics that repeat 10 or more words of prose word for word: topic, section, otherTopic, otherOwner (package | core), words, passages, owner (the topic that should keep the text), text (the passage as the topic writes it), line (where the copy starts in the topic to change, or null), and message (the exact replacement); each is also a copied_passage warning in issues. fluff lists padding phrases and low-density topics: topic, kind (phrase | density), phrase, section, file (relative to the package root), line, density, and message (what to cut or write instead); each is also a doc_fluff warning in issues. strayPointers lists each code span that is exactly `astryx docs <name>` for a doc that exists, in the prose, description or summary of a topic or the text fields of a component doc: topic (the topic or component doc), kind (topic | component), section, field (the field outside any section, such as description or usage.bestPractices[0].description, else null), file (relative to the package root), line, pointer (the written command), link (the {@link} that replaces it), and message; each is also a stray_doc_pointer warning in issues.',
},
{
value: 'integration.check',