Skip to content

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

TypeScript

Docs graph for the CLI and integrations, template replacement, and themeTemplate export (AST-046, AST-047, AST-035) (#6626)

Joey533ecc73b08e
diff --git a/.changeset/cli-docs-graph-links.md b/.changeset/cli-docs-graph-links.md
new file mode 100644
index 0000000000..4465c5a896
--- /dev/null
+++ b/.changeset/cli-docs-graph-links.md
@@ -0,0 +1,34 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Link docs by identity, and let integrations add to the docs tree. (#6626)
+
+A doc links another doc inside its text with `{@link [<provider>:]<kind>:<name>}`,
+such as `{@link command:doctor}`. The CLI prints each link as the `astryx docs`
+command that opens the doc; a link that names no doc prints as written, and
+`astryx doctor` warns on it. An older CLI prints the link as plain text.
+`reference`, `workflow`, and `collection` blocks stay in namespace docs.
+
+An integration can ship namespace docs and place its guides in them. They show
+up in `astryx docs` beside `cli`, with the same moves, links, and search, and
+`astryx doctor integration docs` checks them before the package ships. A
+namespace doc in an integration's docs directory no longer fails to load, and
+`astryx integration add doc <name> --parent <namespace>` writes a placed guide.
+A CLI release that does not read the docs tree can hide every doc topic of a
+package that ships a namespace doc or a placed guide, with nothing saying why,
+so `--parent` declares the CLI that reads them as an optional
+`@astryxdesign/cli` peer, and `astryx integration pack --check` fails a package
+that ships either one without it.
+
+The CLI keeps its own routes: an integration's flat topic or namespace named
+`cli`, `unorganized`, or after one of the CLI's topics (compared without case)
+is withdrawn from the tree, its name opens the CLI's doc, and doctor warns.
+
+Every flat topic now sits in `astryx docs unorganized`, under its own name,
+so every doc has a place in the tree with a way up and across. Search hits
+for a topic name the level and the package that wrote it.
+
+New guide: `astryx docs cli/writing-docs`.
+
+@josephfarina
diff --git a/.changeset/cli-docs-one-level.md b/.changeset/cli-docs-one-level.md
new file mode 100644
index 0000000000..8ff15984b6
--- /dev/null
+++ b/.changeset/cli-docs-one-level.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] In text, `astryx docs <topic>` lists the topic's sections when it has more than one. (#6626)
+
+Read one with `astryx docs <topic> <section>`, or print the whole topic with `--full`. `--dense` still prints the whole dense doc, so the agent bootstrap in AGENTS.md reads the same as before. The JSON contract is unchanged: `astryx docs <topic> --json` and `docs(topic)` in `@astryxdesign/cli/api` still return the whole topic (`docs.detail`), and `--index` returns its section list.
+
+@josephfarina
diff --git a/.changeset/cli-docs-topic.md b/.changeset/cli-docs-topic.md
index 667bc3be51..495d5d7a67 100644
--- a/.changeset/cli-docs-topic.md
+++ b/.changeset/cli-docs-topic.md
@@ -2,8 +2,8 @@
'@astryxdesign/cli': patch
---
-[feat] Read every command and API function with `astryx docs cli`. (#6498)
+[feat] Read the CLI's docs as a tree, one level at a time. (#6498, #6626)
-`astryx docs cli` has one section for each command (`commands-<name>`) and for each API function, plus the JSON output envelope, error codes, and response types (`api-<name>`). Every command, API function, schema, and enum doc the CLI ships now declares the `namespace` that reads it, and `astryx doctor` fails when one has none or names one no topic reads.
+`astryx docs cli` lists the CLI's guides and reference. `astryx docs cli/commands` lists every command, `astryx docs cli/api` lists the API's functions, schemas, and enums, and a route such as `astryx docs cli/api/functions/search` prints one doc. `--json` returns `docs.node` for a namespace or typed doc, identified by its doc identity (a generated level has `id: null`). The text of `astryx docs` lists the docs tree's namespaces first; its `--json` keeps `data` as the topic list and adds them in `meta.namespaces`. Every command, API function, schema, and enum doc the CLI ships declares the `namespace` that reads it: `astryx doctor` fails when one has none or names one nothing reads, and warns when one has no route in the tree.
@josephfarina
diff --git a/.changeset/cli-export-theme-template.md b/.changeset/cli-export-theme-template.md
new file mode 100644
index 0000000000..474cc6406f
--- /dev/null
+++ b/.changeset/cli-export-theme-template.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Export `themeTemplate()` from `@astryxdesign/cli/api`, matching the documented API behind `astryx theme template`. (#6626)
+
+@josephfarina
diff --git a/.changeset/cli-integrations-route.md b/.changeset/cli-integrations-route.md
new file mode 100644
index 0000000000..98161c01d7
--- /dev/null
+++ b/.changeset/cli-integrations-route.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/cli': minor
+---
+
+[breaking] The integration guide moved from `astryx docs cli-integrations` to `astryx docs cli/integrations`. (#6626)
+
+The guide now lives in the CLI's docs tree, under `cli`. The old name is gone: `astryx docs cli-integrations` and `docs('cli-integrations')` fail with an unknown topic. Use `astryx docs cli/integrations`, including section reads such as `astryx docs cli/integrations components`. The docsite page stays at `/docs/cli-integrations`.
+
+@josephfarina
diff --git a/.changeset/cli-search-docs-sections.md b/.changeset/cli-search-docs-sections.md
new file mode 100644
index 0000000000..63fca95c55
--- /dev/null
+++ b/.changeset/cli-search-docs-sections.md
@@ -0,0 +1,11 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] `astryx search` finds the smallest doc part that answers. (#6626)
+
+A doc hit is now one section (`astryx docs cli/integrations codemods`), one docs-tree route (`astryx docs cli/api/functions/assert-response`), or a topic's index, never a whole-topic read. Typed docs match by their own name and by the identifiers they define, such as error codes. `astryx search --type doc` works without `@astryxdesign/core`. `astryx docs` lists the docs tree first, and a namespace shows each child's own name when its route name differs.
+
+Every docs read now ends with its moves: `Up`, plus `Previous` and `Next` for a section or a docs-tree page, and `Related` for a typed doc (its command or API function, and its related docs). `--json` carries them as `links` (`up`, `previous`, `next`, `related`). Each search hit carries `parent`, the command that opens the level above it, and a docs-tree hit carries `package`.
+
+@josephfarina
diff --git a/.changeset/integration-template-replacements.md b/.changeset/integration-template-replacements.md
new file mode 100644
index 0000000000..3edb6189ab
--- /dev/null
+++ b/.changeset/integration-template-replacements.md
@@ -0,0 +1,36 @@
+---
+'@astryxdesign/cli': minor
+---
+
+[breaking] Let integration templates replace Core templates by id. (#6265, #6626)
+
+An integration template can set `replaces` in its own metadata to a Core
+template id. Unqualified template lookup and discovery surfaces use a valid
+replacement, while `--package @astryxdesign/core` still selects the original.
+Missing targets, type mismatches, a declaration on a template that cannot be
+used, and duplicate declarations fail closed and are reported by `astryx doctor
+integration templates`. When separate configured packages replace one target,
+the package configured later wins with a warning. Explicitly configured packages
+always precede autolinked ones. When only autolinked packages conflict, the
+dependency listed later in package.json wins with a warning and the CLI
+recommends explicit configuration.
+
+Invalid contribution kinds remain reportable without hiding other valid kinds.
+Invalid template or component files do not hide valid siblings.
+`astryx doctor` warns about integration contribution problems, so a project
+that passed before keeps passing; `astryx doctor integration templates` fails on
+them. `astryx integration pack --check` fails a package that sets `replaces`
+unless its `@astryxdesign/cli` peer range starts at 0.7.0 or later.
+
+Migration for integration authors: require `@astryxdesign/cli >=0.7.0` in a
+package that sets `replaces`. Earlier CLIs reject the field and withhold the
+package's templates and doc topics.
+
+Migration for JSON consumers: `template.list` entries can now include optional
+`replaces`, and a winning replacement removes its Core target from the default
+list. Select `@astryxdesign/core` explicitly when you need the original. Every
+`IntegrationTemplateConflict` now has required `relationship` and can have
+`severity: 'info'`; update exhaustive shape or severity handling before
+upgrading.
+
+@josephfarina
diff --git a/.github/scripts/cli-api-types-verify.mjs b/.github/scripts/cli-api-types-verify.mjs
index e617dcaa21..48262f00d6 100644
--- a/.github/scripts/cli-api-types-verify.mjs
+++ b/.github/scripts/cli-api-types-verify.mjs
@@ -105,7 +105,7 @@ const scenario = `
import {
component, docs, blog, discover, template, hook, search, build, swizzle,
gapReport, upgrade, init, doctor, layoutExpand, layoutCheck, layoutGrammar,
- themeBuild, themeAdd, themeList, listThemes,
+ themeBuild, themeAdd, themeTemplate, themeList, listThemes,
integrationAdd, integrationAddComponent, integrationAddDoc,
integrationAddTemplate, integrationAddCodemod, integrationAddAgentDoc,
integrationAddTheme, integrationPackCheck,
@@ -131,8 +131,8 @@ async function main() {
void ({} as ComponentDetailResponse); void ({} as SearchResponse); void ({} as UpgradeRunResponse);
void ({} as GapReportReceiptResponse); void ({} as GapReportCategoriesResponse);
void [docs, blog, discover, template, hook, search, build, swizzle, gapReport, upgrade, init,
- doctor, layoutExpand, layoutCheck, layoutGrammar, themeBuild, themeAdd, themeList,
- listThemes, validateIntegration, summarizeIssues, AstryxError, s];
+ doctor, layoutExpand, layoutCheck, layoutGrammar, themeBuild, themeAdd, themeTemplate,
+ themeList, listThemes, validateIntegration, summarizeIssues, AstryxError, s];
}
void main;
diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjs
index 4a99ef2b81..d334af5dc8 100644
--- a/apps/docsite/scripts/generate-data.mjs
+++ b/apps/docsite/scripts/generate-data.mjs
@@ -25,7 +25,10 @@ import {execFileSync} from 'node:child_process';
import {createRequire} from 'node:module';
import {fileURLToPath, pathToFileURL} from 'node:url';
import {resolveContentRoot} from './resolve-content-root.mjs';
-import {template as queryTemplates} from '@astryxdesign/cli/api';
+import {
+ docs as readDocs,
+ template as queryTemplates,
+} from '@astryxdesign/cli/api';
import docsiteConfig from '../astryx.config.mjs';
import {expandWorkspaceDirs} from '../../../scripts/lib/workspace-globs.mjs';
import {
@@ -1674,6 +1677,41 @@ export const templateMetadataCount = ${templateMetadata.length};
// ── 5. Docs Registry ──────────────────────────────────────────────────
+/**
+ * Every guide in the CLI's docs tree, read through the CLI's public docs API:
+ * walk down from each top-level namespace and read each guide by its route.
+ * @returns {Promise<Array<{topic: string, title: string, description: string, category: string | null, sections: unknown[]}>>}
+ */
+async function docsTreeGuides() {
+ const guides = [];
+ const list = await readDocs();
+ const pending = (list.meta?.namespaces ?? []).map(entry => entry.topic);
+ while (pending.length > 0) {
+ const route = pending.shift();
+ const read = await readDocs(route);
+ if (read.type !== 'docs.node') continue;
+ for (const slot of read.data.slots) {
+ for (const child of slot.children) {
+ if (child.kind === 'namespace') {
+ pending.push(child.route);
+ } else if (child.kind === 'generic' && child.route.includes('/')) {
+ // A flat topic in the Unorganized level keeps its own name, and the
+ // flat registry above already has its page.
+ const doc = (await readDocs(child.route)).data;
+ guides.push({
+ topic: child.route.replaceAll('/', '-'),
+ title: doc.title || child.title,
+ description: doc.description || '',
+ category: doc.category || null,
+ sections: doc.sections || [],
+ });
+ }
+ }
+ }
+ }
+ return guides;
+}
+
async function generateDocsRegistry() {
console.log('Generating docs registry...');
@@ -1698,10 +1736,6 @@ async function generateDocsRegistry() {
if (DOCSITE_TARGET !== 'canary' && topic === 'shadcn-compatibility') {
continue;
}
- // /docs/cli is the @astryxdesign/cli package page. The CLI reference topic
- // (`astryx docs cli`) joins the site when its namespace page takes that
- // URL; packages/cli/test/doc-routes.test.mjs records the same skip.
- if (topic === 'cli') continue;
const docPath = path.join(DOCS_DIR, file);
let title = '';
@@ -1718,6 +1752,22 @@ async function generateDocsRegistry() {
const meta = readDocMeta(docPath);
description = meta.description;
}
+ if (sections.length > 0) {
+ // Read the sections through the CLI's docs API, so each link between
+ // docs (`{@link <target>}`) reads as the command that opens its doc, as
+ // it does in `astryx docs`. Only the CLI's own topics are read here, so
+ // the read runs from the CLI package. The docsite renders token tables
+ // itself, so a resolved token reference is not copied into the registry.
+ const read = await readDocs(topic, undefined, {cwd: CLI_ROOT});
+ sections = read.data.sections.map(section => ({
+ ...section,
+ content: section.content.map(block => {
+ if (block?.type !== 'token-ref') return block;
+ const {resolved: _resolved, ...authored} = block;
+ return authored;
+ }),
+ }));
+ }
docTopics.push({
topic,
@@ -1728,6 +1778,14 @@ async function generateDocsRegistry() {
});
}
+ // Guides the CLI's docs tree places (spec:AST-046) are not topic files: the
+ // CLI reads them only by route. Until the site renders the tree itself, each
+ // keeps a flat page whose slug is its route with "/" as "-", so
+ // `cli/integrations` stays at /docs/cli-integrations.
+ for (const guide of await docsTreeGuides()) {
+ docTopics.push(guide);
+ }
+
docTopics.sort((a, b) => a.topic.localeCompare(b.topic));
const content = `// Auto-generated by scripts/generate-data.mjs — do not edit
diff --git a/apps/docsite/src/components/codeLinkifiers.ts b/apps/docsite/src/components/codeLinkifiers.ts
index 0340cfe9c9..70932ea9c7 100644
--- a/apps/docsite/src/components/codeLinkifiers.ts
+++ b/apps/docsite/src/components/codeLinkifiers.ts
@@ -35,9 +35,10 @@ const KNOWN_TOPICS = new Set(docTopics.map(d => d.topic));
* topics return null so a renamed doc degrades to plain code, not a 404.
*/
const docTopic: CodeLinkifier = code => {
- const match = /^(?:npx )?astryx docs(?:\s+([a-z][\w-]*))?(?:\s.*)?$/.exec(
- code,
- );
+ const match =
+ /^(?:npx )?astryx docs(?:\s+([a-z][\w-]*(?:\/[a-z][\w-]*)*))?(?:\s.*)?$/.exec(
+ code,
+ );
if (!match) {
return null;
}
@@ -45,7 +46,10 @@ const docTopic: CodeLinkifier = code => {
if (topic == null) {
return '/docs';
}
- return KNOWN_TOPICS.has(topic) ? `/docs/${topic}` : null;
+ // A docs-tree guide (`cli/integrations`) has a flat page named after its
+ // route, with "/" as "-", until the site renders the tree itself.
+ const slug = topic.replaceAll('/', '-');
+ return KNOWN_TOPICS.has(slug) ? `/docs/${slug}` : null;
};
/** Every documented component and hook name; each has a /components page. */
diff --git a/docs/architecture/cli-surface.md b/docs/architecture/cli-surface.md
index 8b643f75f4..3316925956 100644
--- a/docs/architecture/cli-surface.md
+++ b/docs/architecture/cli-surface.md
@@ -80,11 +80,15 @@ goes through the `Project` seam in `foundation/config`, which resolves the
integrations named in `astryx.config` and then autolinks any DECLARED dependency
that ships a root `astryx.integration.*` manifest — a config entry is how a
project pins an integration, not how the CLI finds one. Each integration is
-loaded independently, so one broken package degrades that package's
-contribution and never fails the run.
+loaded independently. A manifest load failure withdraws that package. An error
+in one contribution kind does not hide other valid kinds, and invalid template
+or component files do not hide valid siblings.
AST-017 DEC-4 owns stable response-entry fields and requires their complete type,
-test, applicable text, and consumer-documentation projections.
+test, applicable text, and consumer-documentation projections. A `template.list`
+entry can carry optional `replaces`, naming the Core id that a winning
+integration template supersedes; the Core entry is omitted from the default list
+and remains available through explicit Core package selection.
## Boundaries and invariants
@@ -162,11 +166,13 @@ test, applicable text, and consumer-documentation projections.
resolver, and fails when the packed artifact has no usable public export. This
contract does not require project-local TypeScript or promise validation under
TypeScript's Node16 or bundler resolution modes.
-- **INV18 — Integration diagnostics are read-only and package-specific.** Doctor
- validation reports malformed or unreachable roots and contribution conflicts
- without rewriting the package. Everyday discovery skips a broken integration
- and records its issue; a package-scoped theme lookup surfaces that package's
- blocking catalog error instead of misreporting the theme as unknown.
+- **INV18 — Integration diagnostics are read-only and contribution-specific.**
+ Doctor reports malformed or unreachable roots and contribution conflicts
+ without rewriting the package. A manifest load failure withdraws the package.
+ A contribution-kind error remains visible without hiding other valid kinds.
+ Invalid template and component files do not hide valid siblings. A
+ package-scoped theme lookup still surfaces that package's blocking catalog
+ error instead of misreporting the theme as unknown.
- **INV19 — Integration themes are packaged editable source.** The manifest's
`themes` root contains one directory per slug. Every theme source has a mandatory
same-stem, strongly typed `ThemeDoc`; there is no root item catalog. Discovery
@@ -224,13 +230,31 @@ test, applicable text, and consumer-documentation projections.
there is no catalog file under a root and no per-item map or list in the
manifest (`spec:AST-039/FR11`). A released alternate reader is an isolated
compatibility path, not a second authoring convention.
-- **INV25 — Every CLI doc names the topic that reads it.** Each command, API
- function, schema, and enum doc the CLI ships declares a `namespace`.
- `cli/commands` and `cli/api` docs are sections of `astryx docs cli`, keyed
- `commands-<name>` and `api-<name>`; `authoring` docs are sections of
+- **INV25 — Every CLI doc names the group that reads it.** Each command, API
+ function, schema, and enum doc the CLI ships declares a `namespace`. The docs
+ tree adopts `cli/commands` and `cli/api` docs, one route each under
+ `cli/commands` and `cli/api/<kind>s`; `authoring` docs are sections of
`astryx docs authoring` and appear in its list. `astryx doctor` fails when a
- CLI doc has no namespace, names one no topic reads, or disagrees with the
+ CLI doc has no namespace, names one nothing reads, or disagrees with the
authoring list, so every doc the CLI ships stays readable from the CLI.
+- **INV26 — The docs tree gives each doc one home (`spec:AST-046`).** The tree
+ is compiled in `foundation/doc-compiler/tree.mjs` from namespace docs, the
+ guides they place, and the typed docs they adopt; the CLI's own tree files
+ live in `assets/docs/tree/`. A namespace never lists or scans its children.
+ `astryx docs <route>` reads it one level at a time, and `astryx doctor` warns
+ on any tree error diagnostic or unplaced CLI doc.
+ An integration's namespace docs and placed guides join the same tree, named
+ by its provider id; the CLI's own docs keep a contested route.
+ Every flat topic sits in the generated Unorganized level under its own name,
+ so every doc has a home in the tree.
+- **INV27 — Every read says where to go next (`spec:AST-047`).** A read names
+ its place and ends with its moves (up, down, across, and out) as runnable
+ commands, and its JSON carries the same moves as `links`; a search hit
+ carries `parent`. Nothing a read shows can go stale: moves are derived, and a
+ test proves every command a doc shows is real. `astryx docs` and
+ `astryx search` meet it first.
+ A link between docs names its target by doc identity and is resolved on
+ every read; Doctor warns on one that names no doc.
Some modules predate INV20–INV23 and do not meet them yet; `spec:AST-042` lists
the known gaps.
@@ -251,6 +275,10 @@ updated in the same pull request when it moves an invariant:
module access to the environment (INV20–INV21);
- adding a command, API function, schema, or enum doc, or a namespace a CLI
doc may declare (INV25);
+- adding a docs-tree namespace or guide, or changing how a doc gets its home or
+ its route (INV26);
+- adding a read that offers no moves, or changing how a move is spelled in text
+ or JSON (INV27);
- changing an integration writer's receipt, no-clobber/rollback behavior,
package.json mutation policy, or public subpath spelling;
- changing what `integration pack --check` executes, resolves, or proves about
diff --git a/docs/specs/AST-017/spec.md b/docs/specs/AST-017/spec.md
index 3edd9a31aa..6f2421ce51 100644
--- a/docs/specs/AST-017/spec.md
+++ b/docs/specs/AST-017/spec.md
@@ -363,7 +363,7 @@ and every integration handler run, the app first; a throwing handler is skipped
without affecting the others or the command; `inheritDebug: false` in the
package's `astryx` field refuses inherited handlers; and a repeated project load
delivers each event once. Its configuration schema entry states that rule, and
-the `cli-integrations` authoring topic documents the `debug` named export. Draft
+the `cli/integrations` guide documents the `debug` named export. Draft
AST-031 details the same model for runtime handler features. No command yet
reports an effective contributed value with its sources, so existing contributed
settings do not meet FR20's inspection requirement; this record does not choose
diff --git a/docs/specs/AST-031/spec.md b/docs/specs/AST-031/spec.md
index cd1baa9742..0a6ac5072a 100644
--- a/docs/specs/AST-031/spec.md
+++ b/docs/specs/AST-031/spec.md
@@ -13,7 +13,7 @@ owners: [josephfarina, cixzhang]
affects_architecture: [architecture:cli-surface]
affects_families: []
affects_contributing: []
-affects_consumer_docs: [cli-integrations]
+affects_consumer_docs: [cli/integrations]
---
# Runtime integration feature composition system spec
diff --git a/docs/specs/AST-035/spec.md b/docs/specs/AST-035/spec.md
new file mode 100644
index 0000000000..5bcaf37733
--- /dev/null
+++ b/docs/specs/AST-035/spec.md
@@ -0,0 +1,174 @@
+---
+schema_version: 4
+template_version: 1
+kind: system-spec
+id: spec:AST-035
+authority: current
+archive_reason: null
+superseded_by: null
+approved_by: josephfarina
+approved_at: 2026-09-24
+phase: accepted
+owners: [josephfarina, cixzhang]
+affects_architecture: [architecture:cli-surface]
+affects_families: []
+affects_contributing: [contributing:templates, contributing:api-conventions]
+affects_consumer_docs: [cli/integrations]
+---
+
+# Integration template replacement system spec
+
+## Intent
+
+Let an installed integration provide the project-specific implementation of a Core
+template without making the common lookup ambiguous or removing access to the Core
+original.
+
+## Non-goals
+
+- Replacing integration components or reference-doc topics. Those surfaces own their
+ own contracts.
+- Rewriting template source that a consumer already copied into an app.
+- Making an integration template available when its source or metadata is invalid.
+- Selecting an integration that the project neither configures nor autolinks.
+
+## Requirements
+
+- **FR1 — A template declares its own replacement.** An integration template MAY
+ set `replaces` in its own metadata to an existing Core template id. No
+ package-level map declares replacements (`spec:AST-039/FR11`). The field is part
+ of the strict template metadata object, so CLIs before 0.7.0 reject it; an
+ integration that uses it MUST declare `@astryxdesign/cli >=0.7.0`.
+- **FR2 — A valid replacement owns default discovery.** When one valid declaration
+ applies, unqualified template lookup and default template projections MUST use the
+ integration template for the Core id. The integration template MUST remain
+ addressable by its own id. List, search, build suggestions, Project discovery, and
+ block-layout lookup MUST project the same winner.
+- **FR3 — Explicit package selection preserves alternatives.** Selecting
+ `@astryxdesign/core` MUST address the original Core template. Selecting an
+ integration package MUST retain access to its shadowed or rejected template by its
+ own id.
+- **FR4 — Invalid declarations fail closed.** A missing Core target, template-kind
+ mismatch, a declaration on a template that cannot be used, or more than one
+ declaration for one target inside a package MUST be an error. An invalid set MUST NOT replace Core. Valid integration
+ templates remain available by their own ids when replacement metadata alone is
+ invalid.
+- **FR5 — Precedence is deterministic.** When multiple explicitly configured
+ integrations validly replace one target, the integration configured later wins and
+ the CLI reports a warning. An explicitly configured replacement MUST win over an
+ autolinked replacement. When only autolinked integrations validly replace one
+ target, the dependency listed later in package.json wins with a warning; naming
+ the intended package in `astryx.config` makes precedence explicit. Invalid
+ autolinked declarations remain reportable but MUST NOT disable a valid explicit
+ replacement.
+- **FR6 — Omission preserves selection behavior for valid integrations.** Without
+ `replaces`, valid template selection and package-aware ambiguity remain
+ unchanged. FR9 intentionally changes failure isolation with or without the field.
+- **FR7 — Diagnostics are complete and stable.** `astryx doctor integration templates`
+ MUST report intentional replacements, missing targets, declarations on templates
+ that cannot be used, kind mismatches, and same-package ambiguity. Error findings MUST produce exit code
+ 1 and MUST NOT be followed by a false success message.
+- **FR8 — Public schema projection is complete.** Effective `template.list` entries
+ MAY include optional `replaces`. The response type, generated inventory, terminal
+ projection, consumer documentation, and tests MUST describe that field and the
+ expanded integration-template diagnostic behavior together.
+- **FR9 — Failure isolation preserves valid contributions.** An error in one
+ contribution kind MUST remain reportable without removing the integration's other
+ valid contribution kinds. Within template and component discovery, one unusable file
+ MUST NOT remove valid siblings. Other kinds keep their existing per-kind atomicity. A
+ manifest load failure still withdraws the integration because no contribution roots
+ are trustworthy. This rule applies whether or not any template declares `replaces`.
+
+### Platform support
+
+- Minimum CLI for an integration that declares `replaces`: `@astryxdesign/cli
+ > =0.7.0`. Earlier CLIs parse template metadata strictly: they reject the field,
+ > print one warning, and withhold the package's templates and doc topics, while
+ > its components still load.
+- Replacement selection itself starts in `@astryxdesign/cli 0.7.0`, the release
+ produced by this breaking minor changeset.
+- Browser evidence: not applicable to catalog selection. A generated consumer app
+ MUST still build or run when its selected template renders integration-owned
+ navigation.
+
+## Current-state impact
+
+The template metadata type and parser gain one optional field, `replaces`. Shared template
+resolution becomes the owner for replacement validation, precedence, aliases, and the
+default discovery view. Template commands, search/build, Project, layout, Doctor,
+response documentation, and the integration-authoring guide project that result.
+Project reports invalid contributions while retaining other valid contribution kinds
+and valid template or component siblings.
+
+The field is optional, and valid templates keep their selection behavior when it is
+absent. The overall release is breaking: a winning replacement removes its
+Core target from the default `template.list` response, every
+`IntegrationTemplateConflict` gains required `relationship`, and its `severity` can
+now be `info`. The changeset uses a minor bump under 0.x and includes migration
+instructions as required by `spec:AST-017/FR8`. Optional `replaces` is projected
+across every public response surface under `spec:AST-017/FR13`.
+
+## Verification
+
+| Contract | Verification | Representative states | Mutation or failure expectation |
+| -------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- |
+| FR1, FR6 | Template parser and discovery tests plus a released-CLI consumer run | field present, field absent, 0.6.3 CLI | a replacement is honored from anywhere but the template's own metadata |
+| FR2, FR3 | Template API/CLI and real consumer-app tests | target id, own id, Core package, integration package | lookup becomes ambiguous or the Core original is unreachable |
+| FR4, FR7 | Doctor and discovery tests | missing local/source, missing target, wrong kind, duplicate, same-id rejection | invalid metadata activates a replacement or Doctor reports success |
+| FR5 | Multi-integration and autolink tests | configured order, explicit versus autolinked, invalid loser | file/display order chooses the winner or invalid autolinking disables explicit intent |
+| FR2, FR8 | List, search/build, Project, layout, response, and generated-doc checks | alias plus undeclared exact-id collision, page and block | two projections disagree or a public field is undocumented |
+| FR9 | Project discovery and issue-order tests | invalid component/template siblings, valid contribution kinds and siblings | one bad contribution removes unrelated valid output |
+
+## Decision log
+
+### DEC-1 — Replacement declarations live on the integration manifest
+
+**Reference:** `spec:AST-035/DEC-1`
+**Proposed by:** `josephfarina`, `2026-09-11`
+**Superseded by:** `spec:AST-035/DEC-3` and `spec:AST-039/DEC-4`, `2026-09-24`
+
+Use `templateReplacements: Record<integrationTemplateId, coreTemplateId>` on the
+integration manifest. This makes intent explicit. CLIs from 0.5.3 onward ignore the
+field when it is unknown without rejecting understood contributions; integrations
+that use it must not claim compatibility with 0.5.2 or earlier. Replacement selection
+starts in 0.7.0.
+
+Rejected: adding `replaces` directly to `TemplateDoc`. A CLI released before that
+field would reject the strict metadata object and make the integration template
+unavailable instead of degrading cleanly.
+
+### DEC-2 — Explicit project configuration owns replacement precedence
+
+**Reference:** `spec:AST-035/DEC-2`
+**Proposed by:** `josephfarina`, `2026-09-11`
+
+Use configuration order when more than one explicitly configured package replaces a
+target, and prefer any explicit replacement over autolinking. This keeps the
+consumer-authored config authoritative while making valid conflicts deterministic and
+visible.
+
+Rejected: making every cross-package replacement ambiguous. That would prevent a
+consumer from intentionally composing integrations in a declared order. Also
+rejected: letting autolinking override explicit config merely because it is appended
+to discovery later.
+
+### DEC-3 — A template declares its own replacement
+
+**Reference:** `spec:AST-035/DEC-3`
+**Proposed by:** `josephfarina`, `2026-09-24`
+
+Put `replaces` in the integration template's own metadata. Every integration item
+keeps its per-item metadata in its own descriptor (`spec:AST-039/FR11`), and doc
+topics already declare replacement with the same field. The cost: a CLI older than
+0.7.0 rejects the unknown field and withholds the package's templates and doc
+topics, where the manifest map let it fall back to own-id access. Integration
+themes in 0.7.0 already need a 0.7.0 CLI, so this adds no new kind of break;
+integrations that use `replaces` declare `@astryxdesign/cli >=0.7.0`.
+
+Rejected: `templateReplacements` in the manifest (DEC-1). It is a central catalog of
+per-item data, which `spec:AST-039/FR11` forbids for every kind.
+
+## Open questions
+
+None. The CLI owner accepted the contract on 2026-09-23 and moved FR1 to
+per-template `replaces` on 2026-09-24 (DEC-3).
diff --git a/docs/specs/AST-039/spec.md b/docs/specs/AST-039/spec.md
index 671e565f62..a38717061b 100644
--- a/docs/specs/AST-039/spec.md
+++ b/docs/specs/AST-039/spec.md
@@ -13,7 +13,7 @@ owners: [josephfarina]
affects_architecture: [architecture:cli-surface]
affects_families: []
affects_contributing: [contributing:cli-conventions]
-affects_consumer_docs: [cli-integrations]
+affects_consumer_docs: [cli/integrations]
---
# Integration contribution descriptor system spec
diff --git a/docs/specs/AST-040-consumer-file-modification/spec.md b/docs/specs/AST-040-consumer-file-modification/spec.md
index 6a390df661..d437298fb7 100644
--- a/docs/specs/AST-040-consumer-file-modification/spec.md
+++ b/docs/specs/AST-040-consumer-file-modification/spec.md
@@ -13,7 +13,7 @@ owners: [josephfarina]
affects_architecture: [architecture:cli-surface]
affects_families: []
affects_contributing: [contributing:cli-conventions]
-affects_consumer_docs: [cli-integrations]
+affects_consumer_docs: [cli/integrations]
---
# Evidence-based consumer file modification system spec
@@ -129,7 +129,7 @@ permission to edit matching literals anywhere in that file. Both behaviors are
non-conforming with FR1–FR3; this record does not choose their implementation.
Post-codemod hooks already exist and serve as the declared regeneration for FR5.
-The `cli-integrations` authoring topic and the codemod authoring guidance must
+The `cli/integrations` guide and the codemod authoring guidance must
explain protection, how to mark generated files, and how transforms prove scope.
This specification-only change alters no runtime behavior or published package
diff --git a/docs/specs/AST-042-cli-command-admission/spec.md b/docs/specs/AST-042-cli-command-admission/spec.md
index 34d03f90ef..a56329efb0 100644
--- a/docs/specs/AST-042-cli-command-admission/spec.md
+++ b/docs/specs/AST-042-cli-command-admission/spec.md
@@ -132,8 +132,6 @@ The CLI has 17 top-level commands. The command docs of 28 commands and
subcommands name the function they call. Known gaps, for which this record does
not assign migrations:
-- `theme template` calls a function that `@astryxdesign/cli/api` does not
- export (FR1);
- the component, discover, layout, search, template, and theme handlers read
project state or files themselves (FR1);
- the theme handler draws its target table from characters, and the docs
diff --git a/docs/specs/AST-046-docs-tree/spec.md b/docs/specs/AST-046-docs-tree/spec.md
new file mode 100644
index 0000000000..4795d373ff
--- /dev/null
+++ b/docs/specs/AST-046-docs-tree/spec.md
@@ -0,0 +1,266 @@
+---
+schema_version: 4
+template_version: 1
+kind: system-spec
+id: spec:AST-046
+authority: draft
+archive_reason: null
+superseded_by: null
+approved_by: null
+approved_at: null
+phase: implementing
+owners: [josephfarina]
+affects_architecture: [architecture:cli-surface]
+affects_families: []
+affects_contributing: []
+affects_consumer_docs: [cli/integrations, authoring]
+---
+
+# Documentation tree system spec
+
+## Intent
+
+A reader who opens the Astryx docs should find every doc in one tree and move
+through it one level at a time: `astryx docs cli` lists the CLI's guides and
+reference, `astryx docs cli/api` lists the API's functions, schemas, and enums,
+and `astryx docs cli/api/functions/search` prints one function. Each doc keeps
+its own file and becomes one node with one route. The compiler builds the tree
+from the typed docs that already exist; no one keeps a list of children by hand.
+Search leads into the same tree: a hit names the smallest part that answers, so
+a reader never reads a whole guide to find one fact.
+
+The tree is the backbone of one docs graph. Every provider's docs are its nodes,
+each with one home in the tree; the links between docs (a command and its API
+function, a token reference, a replacement) are its other edges, named by doc
+identity. Phase 1 builds the backbone for the CLI's own docs and each
+integration's, and `spec:AST-047` turns the edges into moves a reader can
+follow.
+
+This record owns how a doc gets its one home in the tree, how a route is formed,
+how `astryx docs` reads the tree, and what `astryx doctor` checks. It rolls out
+in phases: phase 1 places the CLI's own docs and the namespace docs and guides
+each integration ships, and gives every other doc a home in a generated
+Unorganized level; later phases move those docs into real sections and move
+the docsite onto the tree.
+
+## Non-goals
+
+- The docsite's page layout. In phase 1 the docsite keeps its flat pages; a
+ guide the tree places keeps a flat page named after its route. The docsite
+ moves onto the tree in a later phase, as its own change.
+- A top-level browse of every provider. It is a later phase.
+- Aliases and audiences. `aliases` and `audience` stay reserved fields that a
+ doc may not set.
+- Rendering `collection` blocks. A topic that uses one fails to load.
+
+## Requirements
+
+- **FR1 — Identity is separate from the route.** A node with an authored doc
+ MUST be identified by that doc's identity: its DocId, as the provider-identity
+ contract defines it, built from its provider's ProviderId (which can differ from its
+ package name), its kind, and its name. The identity MUST NOT change when the node
+ moves. A generated level has no authored doc and no identity: its `id` is
+ `null`. A node's route is its parent's route, `/`, and its own segment; a
+ top-level namespace's route is its name, and a flat topic keeps its own name
+ (FR12). A segment is the node's name as
+ lowercase letters and digits joined by single hyphens. The route is the
+ readable name; `docs.node` carries both.
+- **FR2 — Each doc has one home, decided in a fixed order.** A doc's home MUST
+ be decided once, in this order: its explicit `placement`; otherwise the one
+ adoption rule in its own package that matches its discovery group and kind;
+ otherwise, for a reference topic, the generated Unorganized level (FR12). A placement MUST name a namespace of the doc's own package
+ (`namespace:<name>`), a slot that namespace declares, and a slot that accepts
+ the doc's kind. A placement that fails MUST withdraw the doc with a
+ diagnostic; it MUST NOT fall back to adoption. A doc that two rules adopt MUST
+ be withdrawn with a diagnostic that names both namespaces.
+- **FR3 — Namespaces never list or scan their children.** A namespace doc
+ declares its slots and its adoption rules. It MUST NOT enumerate its
+ children, and the compiler MUST NOT infer a parent from a folder. A child
+ names its parent with `placement`, or a namespace adopts a discovery group: a
+ CLI typed doc's group is the `namespace` it declares (`cli/commands`,
+ `cli/api`). An adoption rule with `groupBy: 'kind'` MUST add one generated
+ namespace per kind (`functions`, `schemas`, `enums`), in the order the rule
+ lists the kinds.
+- **FR4 — Routes are unique.** Two nodes MUST NOT share a route. When they
+ would, the compiler MUST keep one by a deterministic order and withdraw the
+ other with a diagnostic that names both. The same inputs MUST build the same
+ tree, whatever order they arrive in. Children sort by `placement.order`, then
+ title, then identity.
+- **FR5 — `astryx docs` reads the tree one level at a time.** `astryx docs
+<route>` MUST resolve a flat topic first, then a tree route, except that a
+ topic whose route the tree gives to another doc (FR11) opens that doc. A namespace MUST
+ print its title, its summary, and each slot's children one level down, each
+ with its summary and the command to open it; it MUST NOT inline its
+ grandchildren. When a child's title is not its route name
+ (`assertResponse()`, `search()`), the text view MUST show the title before
+ the summary. A typed doc MUST print its content. Both MUST end with the way
+ back up. A guide the tree places MUST read like a topic, by
+ its route (`spec:AST-047` FR3). `--json` MUST return `docs.node` for a
+ namespace or typed doc: its identity, route, kind, package, title, summary,
+ breadcrumb, and either its slots with their children or its content.
+- **FR6 — A route has no sections.** A section argument on a namespace or typed
+ doc MUST fail with `ERR_UNKNOWN_SECTION` and name its children. An unknown
+ route MUST fail with `ERR_UNKNOWN_TOPIC` and suggest the children of the
+ deepest namespace the route reaches.
+- **FR7 — The topic list names the tree.** `astryx docs --json` MUST list each
+ top-level namespace in `meta.namespaces`, so `data` stays the topic list, and
+ every entry in it reads as a topic. The text view MUST show the namespaces first,
+ under their own heading, because that is where the CLI's own docs start. A
+ package whose docs did not load MUST be named, in `meta.notLoaded` and under
+ its own heading in text, so its author knows why its docs are missing.
+- **FR8 — Doctor proves the tree.** `astryx doctor` MUST warn when the tree has
+ an error diagnostic, when a CLI typed doc whose group the tree reads has no
+ route, and when a link between docs names no doc (`spec:AST-047` FR9). These
+ checks are new, so they warn: a project that passed before keeps passing. The progressive-disclosure check MUST hold each guide the tree
+ places to the same size budget as every topic.
+- **FR9 — Phase 1 places the CLI's own docs.** The CLI MUST ship the `cli`
+ namespace with the `integrations` guide and the `commands` and `api`
+ namespaces under it. Every command doc MUST have a route under
+ `cli/commands`, and every function, schema, and enum doc in the `cli/api`
+ group a route under `cli/api/<kind>s`. The integration guide's route MUST be
+ `cli/integrations`; its old flat name `cli-integrations` is gone. A CLI route
+ or name MAY change like this when every reference changes with it: links name
+ docs by identity (`spec:AST-047` FR9), and the graph walk fails on a reference
+ left behind (`spec:AST-047` FR11, FR12).
+- **FR10 — Search finds the smallest part that answers.** `astryx search` MUST
+ index each section of each topic and placed guide, and each namespace and
+ typed doc of the tree. A section result MUST carry `section`, and its command
+ MUST read only that section. A tree result's command MUST read its route. A
+ topic result's command MUST list the topic's sections when it has more than
+ one. A typed doc MUST also match by its own name, and a doc part by each
+ identifier it defines or names in code (`assertResponse`,
+ `ERR_UNKNOWN_SECTION`). A docs-only search (`--type doc`) MUST NOT need
+ `@astryxdesign/core`, because `astryx docs` does not.
+- **FR11 — Integrations join the tree.** A configured integration MAY ship
+ namespace docs, and guides with `placement`, in its docs directory. The tree
+ MUST read them beside the CLI's own, identify each node by the integration's
+ provider id (FR1) and name its `package` by the integration's npm name, and
+ hold them to FR2–FR8. A placed guide MUST NOT also `replaces` or `extends` a
+ topic. When two providers claim one route, the CLI's own docs MUST keep it,
+ including its flat topics' names and the Unorganized level, then integrations
+ in configured order; between integrations a namespace keeps its route over a
+ topic, and a name a topic answers to through `replaces` is that topic's route.
+ The claim that loses MUST be a `duplicate_route` diagnostic filed against the
+ provider that lost it, and the topic list, reads, and search MUST agree with
+ the tree. `astryx doctor integration docs` MUST run the
+ same tree and link checks on one integration's docs, so an author finds a
+ broken placement or link before the package ships, and
+ `astryx integration add doc <name> --parent <namespace>` MUST write a guide
+ placed in that namespace, found by its name, and the namespace doc when the
+ package has none. A CLI release that does not read the docs tree can hide every doc topic of a
+ package that ships a namespace doc or a placed guide, with nothing saying why
+ (published 0.6.3 does so for a namespace doc, and earlier builds of main for a
+ placed guide too), so such a package MUST declare a `@astryxdesign/cli` peer
+ range that admits only CLIs that read it: `integration add doc --parent` MUST declare it,
+ and `astryx integration pack --check` MUST fail without it. The same check
+ covers a template that sets `replaces` (`spec:AST-035`).
+- **FR12 — Every doc has a home.** Every flat topic, the CLI's and each
+ integration's, MUST sit in the generated Unorganized level (`unorganized`), in
+ the order the topic list reads. The level has no authored doc, so its `id` is
+ `null`, and it lists its topics one level down with the command that opens
+ each. A topic keeps its own name as its route, so no name changes; a read of
+ it offers Up to the level and Previous and Next among its topics, as any tree
+ node does. Placing a topic in a real section takes it out of the level.
+
+### Platform support
+
+- Supported feature/engine floor: every supported CLI runtime.
+- Unsupported behavior: none.
+- Browser evidence: not applicable; the docsite is unchanged in phase 1.
+
+## Current-state impact
+
+Before this record, `astryx docs` read only flat topics. The CLI's typed docs
+were sections of one generated `cli` topic, and the NamespaceDoc type and the
+`placement` field existed but nothing read them.
+
+Phase 1 changes:
+
+- the CLI ships its namespace docs and the guides they place in
+ `assets/docs/tree/`, each named after its doc; the flat topic list does not
+ read that directory;
+- the compiler builds the tree from those files and the CLI's typed docs, and
+ `collectDocInputs` lists the tree files as a `tree` root;
+- the four tree diagnostics (`invalid_namespace`, `invalid_placement`,
+ `overlapping_adoption`, `duplicate_route`) join the compiler's codes;
+- `astryx docs`, `docs()`, and `astryx doctor` read the tree as FR5–FR8 state;
+- `astryx search` finds sections and tree nodes, as FR10 states;
+- an integration's namespace docs and placed guides join the tree, and
+ `astryx doctor integration docs` checks them, as FR11 states;
+- `cli-integrations` moves to `cli/integrations`, and every reference moves
+ with it;
+- every flat topic sits in the generated Unorganized level, as FR12 states;
+- the docsite reads the placed guide through `docs()` and keeps
+ `/docs/cli-integrations`.
+
+`architecture:cli-surface` INV25 and INV26 carry this record into the code.
+
+## Verification
+
+| Contract | Verification | Representative states | Mutation or failure expectation |
+| ------------- | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
+| FR1, FR3, FR4 | Tree builder fixture tests | three authored levels; adoption with and without `groupBy`; reversed input order; order and title sort | A route that ignores the parent, a folder that implies a parent, or a tree that depends on input order |
+| FR2 | Tree builder failure fixtures | no slot; unknown slot; a slot that refuses the kind; another package's parent; not a reference; two adopters; a cycle | A failed placement that falls back to adoption, or a failure without a diagnostic |
+| FR5, FR6, FR7 | `docs()` dispatcher tests and CLI runs | `cli`, `cli/api`, one function, the placed guide and its sections, the old name, a typo route | A namespace that inlines grandchildren, a lost section read, or a wrong error code |
+| FR8 | Doctor tests | this repo; a fixture tree with a broken placement | A broken tree or an unplaced CLI doc that passes |
+| FR9 | Real-tree tests and the route inventory | every command, function, schema, and enum doc; every exported API function | A CLI typed doc without its route, or a route inventory row the tree contradicts |
+| FR10 | Search tests and CLI runs | a guide section; a typed doc by its own name; an error code; a topic hit; no core installed | A section hit whose command reads the whole topic, or a docs-only search that needs core |
+| FR11 | Integration tree tests | a namespace and two placed guides from a package whose provider id differs from its name; a broken link; a claim on the `cli` route | A node named by the package name, a broken link that passes either doctor, or an integration that takes a CLI route |
+| FR12 | `docs()` tests, the graph walk, and search tests | the level and its children in list order; a topic's Up, Previous, and Next; a flat topic hit's parent; an integration's flat topic | A flat topic without a home, a topic whose name changes, or a level that lists a placed guide |
+
+## Decision log
+
+### DEC-1 — Roll out the tree in phases, CLI first
+
+**Reference:** `spec:AST-046/DEC-1`
+**Decider:** `josephfarina`, `2026-09-22`
+
+The compiler, the CLI reader, and Doctor come first; the docsite moves onto the
+tree late, and current docsite pages stay up until then. Starting with the CLI's
+own docs tests the contract on docs one team owns.
+
+Rejected: one change that moves every doc and the docsite at once. It is too
+large to review, and every route changes before the contract is proven.
+
+### DEC-2 — A CLI typed doc's `namespace` is its adoption group
+
+**Reference:** `spec:AST-046/DEC-2`
+**Decider:** `josephfarina`, `2026-09-24`
+
+Every CLI typed doc already declares the `namespace` that reads it, and Doctor
+already enforces it. The tree adopts by that group, so a new command or
+function appears in the tree with no other edit.
+
+Rejected: a second field for the tree, and a list of children in each namespace.
+Both repeat what the doc already says and drift from it.
+
+### DEC-3 — Rename, and move every reference with it
+
+**Reference:** `spec:AST-046/DEC-3`
+**Decider:** `josephfarina`, `2026-09-28`
+
+`cli-integrations` becomes `cli/integrations`, with no alias. A CLI name or
+route may change when every reference changes with it: links name docs by
+identity, so they follow the doc, and the graph walk fails on any reference
+left behind. An alias would keep a second name for one doc.
+
+Rejected: keeping `cli-integrations` as an alias, and removing it before typed
+links and the graph walk could prove no reference was left.
+
+### DEC-4 — Integrations join the tree in the first phase
+
+**Reference:** `spec:AST-046/DEC-4`
+**Decider:** `josephfarina`, `2026-09-28`
+
+The tree, its moves, and its checks work the same for every provider. Holding
+integrations back would leave their docs on a weaker path and delay the checks
+their authors need, so an integration's namespace docs and placed guides join
+the tree in the same change as the CLI's.
+
+Rejected: a later phase for integration namespaces.
+
+## Open questions
+
+- The layout of the docsite's tree pages: children listed on the namespace page,
+ or inlined on it. The data is the same either way; the docsite phase decides.
+- Where the `authoring` group's docs live in the tree.
diff --git a/docs/specs/AST-047-navigable-output/spec.md b/docs/specs/AST-047-navigable-output/spec.md
new file mode 100644
index 0000000000..0aafa017a4
--- /dev/null
+++ b/docs/specs/AST-047-navigable-output/spec.md
@@ -0,0 +1,194 @@
+---
+schema_version: 4
+template_version: 1
+kind: system-spec
+id: spec:AST-047
+authority: draft
+archive_reason: null
+superseded_by: null
+approved_by: null
+approved_at: null
+phase: implementing
+owners: [josephfarina]
+affects_architecture: [architecture:cli-surface]
+affects_families: []
+affects_contributing: []
+affects_consumer_docs: [cli]
+---
+
+# Navigable CLI output system spec
+
+## Intent
+
+Every read the CLI prints is a node in a graph. A reader who lands anywhere,
+from a search hit, a link, or a guess, must see where they are and every move
+they can make next, as commands they can run: up to the level the node sits
+in, down to its children, across to its neighbors, and out to the nodes it
+names. Nobody has to know a route in advance or read a long page to find one
+fact: they search, land on the smallest node that answers, and move from there.
+
+This record owns the moves a read offers and how they appear in text and JSON.
+`spec:AST-046` owns the docs tree those moves walk first.
+
+## Non-goals
+
+- What the nodes of each command are. The docs tree is `spec:AST-046`'s; each
+ command that adopts this record decides its own nodes.
+- Interactive navigation. There are no prompts, pagers, or state kept between
+ runs; each move is its own command.
+- Links out of the CLI, such as docsite URLs.
+
+## Requirements
+
+- **FR1 — A read names where it is.** A read below the top MUST name its
+ place: a docs-tree node its breadcrumb, a section its topic, and a search hit
+ the path of titles above it (`Astryx CLI › API › Functions › search()`).
+- **FR2 — Up.** Every read except the top MUST offer the command that opens the
+ level it sits in: for a section, its topic's section list; for a node or a
+ topic, the level it sits in (a guide's namespace, or the Unorganized level for
+ a flat topic, `spec:AST-046` FR12); for a top-level namespace, the topic list.
+- **FR3 — Down.** A read that has children MUST list them, each with its
+ summary, and give the command that opens one: a namespace its children, a
+ topic's index its sections, and the topic list its topics and namespaces. In text,
+ a topic with more than one section is read one level at a time: a bare read
+ lists its sections, and `--full` prints the whole doc; the dense variant is
+ written to be read whole, so `--dense` prints it whole. The JSON contract is
+ unchanged: `docs(topic)` and `--json` return the whole doc, and `--index` its
+ sections.
+- **FR4 — Across.** A read with a place in an ordered level MUST offer the
+ commands that open the item before it and the item after it, when they exist:
+ a section's neighbors in its topic, and a docs-tree node's neighbors in its
+ parent's slot.
+- **FR5 — Out.** A read that names another node MUST give the command that
+ opens it: a command doc its API function, a function doc its command, and a
+ typed doc each doc it lists as related.
+- **FR6 — Search lands on nodes.** Each search hit MUST be one node, the
+ smallest that answers (`spec:AST-046` FR10), with the command that reads it
+ and the command that opens the level above it.
+- **FR7 — Moves are commands, and JSON carries them.** In text, each move MUST
+ be a whole command with the project's run prefix. In JSON, a read MUST carry
+ its moves as data: `links`, with `up`, `previous` and `next` where FR4 applies, and
+ `related` where FR5 applies to a typed doc, each an `astryx ...` command; a search hit carries `command` and
+ `parent`. `links` MUST be present on every read but the topic list, as a field
+ added to each existing response, and the published types MUST type each move
+ as an `astryx docs` command. The text view
+ MUST stay a projection of the JSON.
+- **FR8 — A wrong move says where to go.** A route, topic, or section that does
+ not exist MUST fail with a stable error code and suggest the nodes a reader
+ can reach from the nearest level that does exist (`spec:AST-046` FR6).
+- **FR9 — Moves are derived, not written.** The CLI MUST derive Up, Down, and
+ Across from the docs tree and a topic's sections, and Out from a typed doc's
+ own fields, so no doc lists its own moves and every provider's docs, from
+ Core, the CLI, or an integration, get the same moves. A link from one doc to
+ another MUST name its target by doc identity, never by route or title. A bare
+ name in a typed field (`fn`, `command`, `related`) names a doc of its own
+ provider, so it is a doc identity: it resolves among the kinds its field
+ allows, and a name that matches docs of more than one allowed kind is an
+ error, never a silent pick. Inside a doc's text, a link MUST be written
+ `{@link <target>}` and read as the command that opens its doc; a link that
+ names no doc MUST print as written. A topic's sections hold only the stable
+ content blocks, so `reference` and `workflow` blocks (GraphContentBlock)
+ belong to a namespace 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
+ 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.
+- **FR10 — Phase 1 covers docs and search.** `astryx docs` and `astryx search`
+ MUST meet FR1–FR9, FR11, and FR12. A command a doc shows as an example, in a code
+ block or in prose, is not a link: FR11 keeps it true. Other commands adopt
+ this record in later phases, each as its own change.
+- **FR11 — Nothing a read shows can go stale.** A move or a cross-link MUST be
+ derived when the read is made, never stored in a doc. Every other `astryx`
+ command that a doc, a hint line, or the repository's agent prompt shows MUST
+ name a real command and only options that command takes, and every
+ `astryx docs` command it shows MUST open; a test MUST fail the build
+ otherwise. A command a doc shows wrong on purpose, as an error-code example,
+ MUST be listed as such, and the list MUST fail when an entry is no longer
+ shown.
+- **FR12 — Every doc is one walk away.** Every doc a provider ships MUST be
+ reachable from `astryx docs` by following the moves reads offer: Down from the
+ topic list and each namespace, then Across and Out. Neighbors MUST agree: the
+ read an item's Next opens names that item as its Previous. A test MUST walk
+ the whole graph from the top and fail on a doc file it cannot reach, a move
+ that does not open, or a link that names no doc.
+
+### Platform support
+
+The moves are plain commands with the prefix of the project's package manager,
+so they run in any shell the CLI runs in. JSON carries them without the prefix.
+
+## Current-state impact
+
+Before this record, only docs-tree namespaces and typed docs offered a way up,
+and only in text; a section, a topic, and a topic's index were dead ends.
+
+Phase 1 changes:
+
+- in text, a bare topic read lists the topic's sections when it has more than
+ one; `--full` and `--dense` print it whole; `docs(topic)` and `--json` still
+ return the whole doc;
+- `docs.node`, `docs.index`, `docs.detail`, and `docs.detail.section` carry
+ `links`: `up` on every read, and `previous` and `next` on sections and
+ docs-tree nodes;
+- a section read, a whole-topic read, and a topic's index end with their moves;
+- a docs search hit carries `parent` and the path of titles above it;
+- links between docs are typed (`{@link <target>}` in text, and the typed
+ fields), resolved on every read, and checked by Doctor, which warns; the
+ hand-written `astryx docs` links in the CLI's own docs become typed links;
+- a test proves every command a doc or hint shows is a real command with real
+ options, and every docs command opens;
+- a test walks the whole graph from the top and reaches every doc file the CLI
+ ships, as FR12 states.
+
+`architecture:cli-surface` INV27 carries this record into the code.
+
+## Verification
+
+| Contract | Verification | Representative states | Mutation or failure expectation |
+| ------------ | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| FR1–FR5, FR7 | `docs()` dispatcher tests, CLI runs, and the graph walk (`packages/cli/test/docs-graph.test.mjs`) | a top-level namespace; a typed doc in the middle of its slot; the first and the last section of a guide; a flat topic, whole | A read with no way up, a move that does not run, or a text move with no `links` |
+| FR6 | Search tests | a section hit; a docs-tree hit; a topic hit | A hit without `parent`, or a `parent` that does not open the level above |
+| FR8 | `spec:AST-046` FR6 tests | an unknown route, topic, and section | A dead end without suggestions |
+| FR9 | Link tests, the doctor docs-tree check, and the graph walk | an inline link, a link in a list and a table, and a typed field; a link to another provider; a link in code ticks | A link that names no doc and still passes, a link resolved by guess, or a stored route |
+| FR11 | The graph walk's shown-commands check | commands in doc prose and code blocks, CLI hint lines, and the agent prompt; the wrong-on-purpose list | A command or option the CLI does not have, a docs command that does not open, or a stale list entry |
+| FR12 | The graph walk (`packages/cli/test/docs-graph.test.mjs`) | every tree node; every doc file the CLI ships; Next and Previous on sections, topics, guides, and tree nodes | A doc file no walk reaches, a move that does not open, or a Next whose read names another Previous |
+
+## Decision log
+
+### DEC-1 — A move is a command, not a route
+
+**Reference:** `spec:AST-047/DEC-1`
+**Decider:** `josephfarina`, `2026-09-28`
+
+Each move is a whole `astryx ...` command that a reader can run as is.
+
+Rejected: bare routes. They make the reader rebuild the command and know which
+argument a section key goes in.
+
+### DEC-2 — Across names the neighbors, not the whole level
+
+**Reference:** `spec:AST-047/DEC-2`
+**Decider:** `josephfarina`, `2026-09-28`
+
+FR4 names the item before and the item after; the whole level is one move up.
+
+Rejected: listing every sibling on every read, which makes each leaf as long as
+its parent.
+
+### DEC-3 — Adopt per command, docs and search first
+
+**Reference:** `spec:AST-047/DEC-3`
+**Decider:** `josephfarina`, `2026-09-28`
+
+Readers get lost in the docs first, and search is how they arrive. Other
+commands adopt the moves as their own changes.
+
+Rejected: one change for every command, which is too large to review and
+decides every command's nodes at once.
+
+## Open questions
+
+- Which command adopts this record next, and what its nodes are.
+- Whether top-level namespaces offer `previous` and `next` among each other.
diff --git a/packages/cli/README.md b/packages/cli/README.md
index d9f2f9439e..aa4722a6b6 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -21,16 +21,16 @@ The CLI documents itself, so these commands print what the installed version doe
- `astryx <command> --help`: one command's arguments and options.
- `astryx manifest --json`: every command, option, and response type, as JSON.
-- `astryx docs cli --index`: one section for each command (`commands-<name>`)
- and each API function, plus the JSON output envelope, error codes, and
- response types (`api-<name>`). Read one with `astryx docs cli <key>`, for
- example `astryx docs cli api-search`.
+- `astryx docs cli`: the CLI's docs tree, one level at a time.
+ `astryx docs cli/commands` lists every command, `astryx docs cli/api` lists
+ the API's functions, schemas, and enums, and a route such as
+ `astryx docs cli/api/functions/search` prints one.
- `astryx docs authoring --index`: the authoring reference, with one section for
each file an author writes: the `astryx.config.*` file, the
`astryx.integration.*` manifest, codemods, and every doc type (`ComponentDoc`,
`TemplateDoc`, `ThemeDoc`, and the rest). Read one section with
`astryx docs authoring <section>`, for example `astryx docs authoring config`.
-- `astryx docs cli-integrations`: the guide to building an integration package.
+- `astryx docs cli/integrations`: the guide to building an integration package.
- `astryx docs`: every docs topic, including the design-system guides (for
example `tokens`, `theme`, and `layout`).
@@ -428,24 +428,25 @@ Every response has a `type` discriminant. The full set is below (generated from
| `component.detail.source` | One component's source file, as {component, source}. |
| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. |
| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry. |
-| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description}), in discovery order. |
-| `docs.detail` | One topic's full ReferenceDoc, with token-ref blocks inlined. |
-| `docs.index` | One topic's section index (--index): the topic's name, title, and description, plus sections, each {id, title, summary} (pass the id as the section argument; summary is the section's one-line summary). |
-| `docs.detail.section` | One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined. |
+| `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, 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, summary} (pass the id as the section argument; 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). |
+| `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) 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` | The configured external packages (name, category, components, version, description); when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |
| `discover.detail` | A single external package entry, for an @scope/name query. |
| `discover.detail.doc` | The validated ComponentDoc for one external component: an @scope/name/Component query, or a free-text term resolving to exactly one component. |
| `discover.search` | The echoed query plus the matching {package, component} pairs, when a free-text term matches several components. |
-| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, score, reason, description, command}, plus import (components, hooks), title (docs), or displayName and kind (templates). |
+| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, score, reason, description, command}, plus import (components, hooks), title, parent (the command that opens the level above), package (for a docs-tree hit), 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 composition kit: echoed query, hasResults, matchCount (total matched, never a cap), directMatch, pages (closest templates), blocks (drop-in patterns) and domain (idea components/hooks) as SearchResultEntry[], frame and foundation name arrays, and hint {reason, commands} when thin. |
| `swizzle.list` | The names of swizzlable components discoverable from cwd's @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 an optional maintainer note. |
| `gap-report.categories` | The fixed gap category values and human-readable labels. |
| `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. |
-| `template.list` | Every discovered template (page + block); each entry carries id, name, description, kind, owning package, optional category and componentsUsed, and readiness flags. |
+| `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 raw source plus its description, kind, and the component names it composes. |
| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. |
| `template.copy` | A scaffold receipt: template id, output directory, written file name, and file count. |
@@ -469,9 +470,9 @@ Every response has a `type` discriminant. The full set is below (generated from
| `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}]. |
| `integration.validate` | The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |
-| `integration.template-conflicts` | The integration identity, structural issues, and non-blocking conflicts where an integration template id is also owned by Core; each conflict includes the exact package-qualified command. |
+| `integration.template-conflicts` | The integration identity, issues, and conflicts as {severity: info \| warning, relationship: replaces \| accidental, replaces?, command}. |
| `integration.component-conflicts` | 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. |
-| `integration.doc-conflicts` | The integration identity, structural issues, and Core doc overlaps classified as intentional replacements, intentional extensions, or accidental same-name conflicts. |
+| `integration.doc-conflicts` | The integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). |
| `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, and written (the output path, or null when nothing was written). |
| `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). |
| `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. |
@@ -667,9 +668,10 @@ wrong type fails there; a field this CLI does not know is ignored with a
warning naming it, so a manifest written against a newer CLI still contributes
everything this one understands.
-Discovery is resilient: a broken or misconfigured integration is skipped with a
-one-line warning on stderr instead of crashing the CLI, and it never corrupts a
-`--json` envelope. To inspect problems, run
+Discovery is resilient. A manifest load failure skips that package with a warning.
+An invalid contribution kind remains reportable without hiding other valid kinds,
+and invalid template or component metadata is omitted without hiding valid siblings.
+Warnings go to stderr and never corrupt a `--json` envelope. To inspect problems, run
`astryx doctor integration validate <package>` for structure, then use `templates`,
`components`, or `docs` under the same `astryx doctor integration` group to check
Core identity overlaps before publishing. Bare `astryx doctor` checks overall
@@ -679,5 +681,5 @@ For the full authoring walkthrough (component doc format, template packaging
and `exports` requirements, and codemod authoring), see the guide:
```bash
-astryx docs cli-integrations
+astryx docs cli/integrations
```
diff --git a/packages/cli/api/component/_adapter.mjs b/packages/cli/api/component/_adapter.mjs
index 9df8446976..456cb038f8 100644
--- a/packages/cli/api/component/_adapter.mjs
+++ b/packages/cli/api/component/_adapter.mjs
@@ -35,16 +35,15 @@ import {
resolveIntegrationImportPath as resolveIntegrationImport,
} from '../../foundation/discovery/component-discovery.mjs';
import {Project} from '../../foundation/config/project.mjs';
-import {loadDocs} from '../../foundation/discovery/component-loader.mjs';
+import {loadComponentDoc as loadValidatedComponentDoc} from '../../foundation/discovery/component-loader.mjs';
import {searchComponents} from '../../foundation/text/string-utils.mjs';
import {AstryxError} from '../error.mjs';
export {CORE_PACKAGE};
/**
- * A loaded component doc. `loadDocs` returns the authored `.doc.mjs` shape,
- * which is either a single-component or multi-component doc; this loose view
- * captures the fields the API reads across both forms.
+ * A loaded component doc. The shared validated loader accepts stamped and legacy
+ * component docs; this loose view captures the fields the API reads across both.
* @typedef {object} LoadedComponentDoc
* @property {string} [name]
* @property {string} [description]
@@ -56,9 +55,7 @@ export {CORE_PACKAGE};
*/
/**
- * Options object for `loadDocs`, matching its declared parameter shape (used
- * as a cast target so `lang` (which the API may hold as `string|null`) type
- * checks against `loadDocs`'s `lang?: string`).
+ * Options object for the shared component-doc loader.
* @typedef {{zh?: boolean, dense?: boolean, lang?: string}} LoadDocsOpts
*/
@@ -381,9 +378,22 @@ export async function resolveUnscopedDoc(dirName, {coreDir, cwd, name}) {
*/
export async function loadComponentDoc(docPath, opts = {}) {
const {zh = false, dense = false, lang = null} = opts;
- return /** @type {LoadedComponentDoc} */ (
- await loadDocs(docPath, /** @type {LoadDocsOpts} */ ({zh, dense, lang}))
- );
+ try {
+ return /** @type {LoadedComponentDoc} */ (
+ await loadValidatedComponentDoc(
+ docPath,
+ /** @type {LoadDocsOpts} */ ({zh, dense, lang}),
+ )
+ );
+ } catch (err) {
+ throw new AstryxError(
+ `Cannot load component metadata: ${
+ err instanceof Error ? err.message : String(err)
+ }`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_DOC,
+ );
+ }
}
/**
diff --git a/packages/cli/api/component/component.mjs b/packages/cli/api/component/component.mjs
index 24d9a4f80d..b72b58a1d1 100644
--- a/packages/cli/api/component/component.mjs
+++ b/packages/cli/api/component/component.mjs
@@ -143,14 +143,20 @@ export async function component(name, options = {}) {
// Searches that package first — critical for names that exist in both core
// and an external package (AppShell, Button, SideNav).
if (packageScope) {
- const scoped = classifyScope(packageScope, {owners, loadedIntegrations, cwd, name});
+ const scoped = classifyScope(packageScope, {
+ owners,
+ loadedIntegrations,
+ cwd,
+ name,
+ });
if (scoped.kind === 'core' || scoped.kind === 'integration') {
const owner = scoped.owner;
if (source) {
return componentDetailSource(dirName, owner.sourcePath, {
name,
- notFoundInPackage: scoped.kind === 'integration' ? packageScope : null,
+ notFoundInPackage:
+ scoped.kind === 'integration' ? packageScope : null,
});
}
// showcase/blocks were previously dropped on the scoped path — a
@@ -187,17 +193,48 @@ export async function component(name, options = {}) {
}
const docs = await loadComponentDoc(extDocPath, docOpts);
if (props) return componentDetailProps(docs);
- return componentDetail(docs, {package: scoped.ext.name, sourcePath: null}, dirName, coreDir);
+ return componentDetail(
+ docs,
+ {package: scoped.ext.name, sourcePath: null},
+ dirName,
+ coreDir,
+ );
+ }
+ throw new AstryxError(
+ `No component "${name}" in package "${packageScope}"`,
+ undefined,
+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,
+ );
+ }
+
+ // Invalid integration metadata does not create ambiguity against a valid
+ // owner. Keep raw owners only when no doc owner is valid, so an integration-
+ // only component still exposes its source and returns ERR_INVALID_DOC for
+ // detail instead of degrading to an unrelated unknown-component error.
+ const validOwners = [];
+ for (const owner of owners) {
+ if (owner.package === CORE_PACKAGE) {
+ validOwners.push(owner);
+ continue;
+ }
+ try {
+ await loadComponentDoc(owner.docPath);
+ validOwners.push(owner);
+ } catch {
+ // Project/Doctor report invalid metadata; it is not an effective owner.
}
- throw new AstryxError(`No component "${name}" in package "${packageScope}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);
}
+ const effectiveOwners = validOwners.length > 0 ? validOwners : owners;
- // ── Ambiguity: owned by MORE THAN ONE package, no --package ─────
- assertUnambiguousOwners(owners, dirName);
+ // ── Ambiguity: owned by MORE THAN ONE valid package, no --package ──
+ assertUnambiguousOwners(effectiveOwners, dirName);
// ── Single non-core owner (an integration provides it, core does not) ──
- if (owners.length === 1 && owners[0].package !== CORE_PACKAGE) {
- const owner = owners[0];
+ if (
+ effectiveOwners.length === 1 &&
+ effectiveOwners[0].package !== CORE_PACKAGE
+ ) {
+ const owner = effectiveOwners[0];
if (source) {
return componentDetailSource(dirName, owner.sourcePath, {name});
}
@@ -213,7 +250,11 @@ export async function component(name, options = {}) {
// ── No-scope core path ─────────────────────────────────────────
// `--source` reads core directly (no external/fuzzy fallback).
if (source) {
- return componentDetailSource(dirName, resolveCoreSourcePath(coreDir, dirName), {name});
+ return componentDetailSource(
+ dirName,
+ resolveCoreSourcePath(coreDir, dirName),
+ {name},
+ );
}
if (showcase) {
return componentDetailShowcase(dirName, {cwd, name});
@@ -232,10 +273,14 @@ export async function component(name, options = {}) {
// scope the response to just the matching sub-component.
const sub = scopeSubComponent(docs, dirName, coreDir);
if (sub) {
- if (props) return componentDetailProps({props: sub.matchingComponent.props});
+ if (props)
+ return componentDetailProps({props: sub.matchingComponent.props});
return componentDetail(
sub.scoped,
- {package: resolved.resolvedOwnerPackage, sourcePath: resolved.resolvedSourcePath},
+ {
+ package: resolved.resolvedOwnerPackage,
+ sourcePath: resolved.resolvedSourcePath,
+ },
dirName,
coreDir,
);
@@ -244,7 +289,10 @@ export async function component(name, options = {}) {
if (props) return componentDetailProps(docs);
return componentDetail(
docs,
- {package: resolved.resolvedOwnerPackage, sourcePath: resolved.resolvedSourcePath},
+ {
+ package: resolved.resolvedOwnerPackage,
+ sourcePath: resolved.resolvedSourcePath,
+ },
resolved.resolvedName,
coreDir,
);
diff --git a/packages/cli/api/component/list/list.mjs b/packages/cli/api/component/list/list.mjs
index 659dbadb0d..217ad77894 100644
--- a/packages/cli/api/component/list/list.mjs
+++ b/packages/cli/api/component/list/list.mjs
@@ -15,7 +15,7 @@ import {
CORE_PACKAGE,
discoverComponents,
discoverExternalComponentsGrouped,
- discoverIntegrationComponents,
+ discoverValidIntegrationComponents,
findComponentReadme,
findExternalComponentDoc,
resolveImportPath,
@@ -228,7 +228,8 @@ export async function componentList(
const seenIntegration = new Set();
for (const integration of loadedIntegrations) {
seenIntegration.add(integration.name);
- const owned = discoverIntegrationComponents(integration);
+ const {components: owned} =
+ await discoverValidIntegrationComponents(integration);
// Group integration components by their doc `group`, falling back to the
// package name. Keys are package-qualified so they never collide with
// core groups or each other.
diff --git a/packages/cli/api/docs/_adapter.mjs b/packages/cli/api/docs/_adapter.mjs
index 3e2c696610..03968e817c 100644
--- a/packages/cli/api/docs/_adapter.mjs
+++ b/packages/cli/api/docs/_adapter.mjs
@@ -25,10 +25,28 @@ import {
} from '../../foundation/doc-compiler/compile.mjs';
import {
deepFreeze,
+ loadTopicFile,
loadTopicInput,
OVERLAY_LANGUAGES,
overlayLanguages,
} from '../../foundation/doc-compiler/read.mjs';
+import {
+ buildDocsTree,
+ loadTreeInputs,
+} from '../../foundation/doc-compiler/tree.mjs';
+import {sortDiagnostics} from '../../foundation/doc-compiler/diagnostics.mjs';
+import {
+ linkBlocks,
+ parseLinkTarget,
+} from '../../foundation/doc-compiler/links.mjs';
+import {
+ createDocId,
+ normalizeProviderId,
+} from '../../foundation/identity/provider-identity.mjs';
+import {
+ cliDocIndex,
+ cliDocSection,
+} from '../../foundation/discovery/cli-self-docs.mjs';
import {AstryxError} from '../error.mjs';
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
@@ -69,16 +87,16 @@ function overlayLanguage(lang) {
const loweredByCatalog = new WeakMap();
/**
- * One topic, lowered for `lang`: overlaid, extensions merged, keys stamped.
- * Memoized per catalog, so a read that references a topic twice loads it once.
- * Every read of the catalog shares the memoized node, so it is frozen; the
- * lenses hand readers copies.
+ * One topic, lowered for `lang` with its links as written: overlaid,
+ * extensions merged, keys stamped. Memoized per catalog, so a read that
+ * references a topic twice loads it once. Every read of the catalog shares the
+ * memoized node, so it is frozen; the lenses hand readers copies.
* @param {DocsCatalog} catalog
* @param {import('../../foundation/discovery/docs-discovery.mjs').DocsTopicEntry} entry
* @param {string | null} [lang]
* @returns {Promise<import('../../foundation/doc-compiler/compile.mjs').CompiledReferenceNode>}
*/
-export function lowerTopic(catalog, entry, lang = null) {
+function lowerRawTopic(catalog, entry, lang = null) {
const overlay = overlayLanguage(lang);
let cache = loweredByCatalog.get(catalog);
if (!cache) {
@@ -96,6 +114,365 @@ export function lowerTopic(catalog, entry, lang = null) {
return lowered;
}
+/**
+ * @typedef {import('../../foundation/doc-compiler/tree.mjs').DocsTree} DocsTree
+ * @typedef {import('../../foundation/doc-compiler/tree.mjs').TreeNode} TreeNode
+ * @typedef {import('../../foundation/doc-compiler/links.mjs').LinkProblem} LinkProblem
+ * @typedef {import('../../foundation/doc-compiler/links.mjs').LinkResolver} LinkResolver
+ * @typedef {import('../../foundation/discovery/docs-discovery.mjs').DocsTopicEntry} DocsTopicEntry
+ */
+
+/** @type {WeakMap<DocsCatalog, Map<string, Promise<{node: import('../../foundation/doc-compiler/compile.mjs').CompiledReferenceNode, problems: LinkProblem[]}>>>} */
+const linkedByCatalog = new WeakMap();
+
+/**
+ * The CLI's own topics alone, for a check that runs without a project.
+ * @returns {DocsCatalog}
+ */
+export function builtinCatalog() {
+ return DocsCatalog.fromBuiltins();
+}
+
+/**
+ * The provider id a topic's (or an extension's) links resolve against: its
+ * owner's.
+ * @param {{providerId?: string, package: string}} entry
+ * @returns {string}
+ */
+function providerOf(entry) {
+ return normalizeProviderId(entry.providerId ?? entry.package);
+}
+
+/**
+ * One topic, lowered for `lang` with every link between docs resolved
+ * (spec:AST-047 FR9): an inline `{@link <target>}` reads as the command that
+ * opens its doc, and a `reference` or `workflow` block carries the doc it
+ * names. Memoized per catalog and frozen, like the lowered node.
+ * @param {DocsCatalog} catalog
+ * @param {DocsTopicEntry} entry
+ * @param {string | null} [lang]
+ * @returns {Promise<import('../../foundation/doc-compiler/compile.mjs').CompiledReferenceNode>}
+ */
+export async function lowerTopic(catalog, entry, lang = null) {
+ return (await linkTopic(catalog, entry, lang)).node;
+}
+
+/**
+ * Each link in a topic that names no doc.
+ * @param {DocsCatalog} catalog
+ * @param {DocsTopicEntry} entry
+ * @returns {Promise<LinkProblem[]>}
+ */
+export async function topicLinkProblems(catalog, entry) {
+ return (await linkTopic(catalog, entry, null)).problems;
+}
+
+/**
+ * @param {DocsCatalog} catalog
+ * @param {DocsTopicEntry} entry
+ * @param {string | null} lang
+ */
+function linkTopic(catalog, entry, lang) {
+ let cache = linkedByCatalog.get(catalog);
+ if (!cache) {
+ cache = new Map();
+ linkedByCatalog.set(catalog, cache);
+ }
+ const key = `${entry.name.toLowerCase()}\u0000${overlayLanguage(lang) ?? ''}`;
+ let linked = cache.get(key);
+ if (!linked) {
+ linked = (async () => {
+ const raw = await lowerRawTopic(catalog, entry, lang);
+ /** @type {Map<string, LinkResolver>} */
+ const resolvers = new Map();
+ /** @param {string} provider */
+ const resolverFor = async provider => {
+ let resolve = resolvers.get(provider);
+ if (!resolve) {
+ resolve = await linkResolver(catalog, provider);
+ resolvers.set(provider, resolve);
+ }
+ return resolve;
+ };
+ /** @type {LinkProblem[]} */
+ const problems = [];
+ const sections = [];
+ // Each section resolves its links against the provider that wrote it:
+ // an extension's sections against the extension's provider, never the
+ // base topic's.
+ for (const section of raw.doc.sections) {
+ const provider = raw.sectionProviders?.[section.id];
+ const linked = await linkBlocks(
+ section.content,
+ await resolverFor(
+ provider == null ? providerOf(entry) : normalizeProviderId(provider),
+ ),
+ {section: section.id ?? section.title},
+ );
+ problems.push(...linked.problems);
+ sections.push({...section, content: linked.content});
+ }
+ return {
+ node: deepFreeze({...raw, doc: {...raw.doc, sections}}),
+ problems,
+ };
+ })();
+ cache.set(key, linked);
+ }
+ return linked;
+}
+
+/** @type {WeakMap<DocsCatalog, Promise<DocsTree>>} */
+const treesByCatalog = new WeakMap();
+
+/**
+ * The project's docs tree: the CLI's own docs plus the namespace docs and
+ * placed guides the configured integrations ship (spec:AST-046), built once
+ * per catalog. Without integration docs it is the CLI's tree, built once per
+ * process.
+ * @param {DocsCatalog} catalog
+ * @param {{fresh?: boolean}} [options] `fresh`: reread the CLI's tree files
+ * @returns {Promise<DocsTree>}
+ */
+export function projectTree(catalog, {fresh = false} = {}) {
+ let tree = treesByCatalog.get(catalog);
+ if (!tree || fresh) {
+ tree = buildProjectTree(catalog, fresh);
+ treesByCatalog.set(catalog, tree);
+ }
+ return tree;
+}
+
+/** @type {ReturnType<typeof loadTreeInputs> | undefined} */
+let cliTreeInputs;
+
+/**
+ * Every flat topic in the catalog, as the tree's Unorganized level reads it.
+ * @param {DocsCatalog} catalog
+ * @returns {Promise<import('../../foundation/doc-compiler/tree.mjs').TreeTopicInput[]>}
+ */
+async function flatTopicInputs(catalog) {
+ /** @type {import('../../foundation/doc-compiler/tree.mjs').TreeTopicInput[]} */
+ const topics = [];
+ for (const entry of catalog.entries()) {
+ const aliases = catalog.aliasesOf(entry);
+ let {title, description} = entry;
+ if (title == null || description == null) {
+ try {
+ const file = await loadTopicFile(entry.path, null);
+ title ??= file.doc?.title;
+ description ??= file.doc?.description;
+ } catch {
+ // A topic that does not load is reported where it is read.
+ }
+ }
+ topics.push({
+ provider: entry.package,
+ providerId: entry.providerId ?? entry.package,
+ name: entry.name,
+ title: title ?? entry.name,
+ summary: description ?? '',
+ source: `${entry.package}:${entry.name}`,
+ ...(aliases.length > 0 ? {aliases} : {}),
+ });
+ }
+ return topics;
+}
+
+/**
+ * The CLI's tree, each configured integration's namespaces and guides, and
+ * every flat topic in the generated Unorganized level.
+ * @param {DocsCatalog} catalog
+ * @param {boolean} fresh
+ * @returns {Promise<DocsTree>}
+ */
+async function buildProjectTree(catalog, fresh) {
+ const added = catalog.treeInputs;
+ if (fresh || !cliTreeInputs) cliTreeInputs = loadTreeInputs();
+ const cli = await cliTreeInputs;
+ const result = buildDocsTree({
+ namespaces: [...cli.namespaces, ...added.flatMap(each => each.namespaces)],
+ docs: [...cli.docs, ...added.flatMap(each => each.guides)],
+ topics: await flatTopicInputs(catalog),
+ });
+ return {
+ ...result,
+ diagnostics: sortDiagnostics([...cli.diagnostics, ...result.diagnostics]),
+ };
+}
+
+/** @type {WeakMap<DocsTree, Map<string, TreeNode>>} */
+const identitiesByTree = new WeakMap();
+
+/** @param {string} provider @param {string} kind @param {string} name */
+function identityKey(provider, kind, name) {
+ return `${provider}\u0000${kind}\u0000${kind === 'generic' ? name.toLowerCase() : name}`;
+}
+
+/**
+ * Every tree node with an identity, by provider id, kind, and name.
+ * @param {DocsTree} tree
+ */
+function identitiesOf(tree) {
+ let index = identitiesByTree.get(tree);
+ if (!index) {
+ index = new Map();
+ for (const node of tree.nodes.values()) {
+ if (node.id == null) continue;
+ let provider = node.providerId;
+ try {
+ provider = normalizeProviderId(node.providerId);
+ } catch {
+ // Kept as given; a link names it the same way.
+ }
+ index.set(identityKey(provider, node.kind, node.name), node);
+ }
+ identitiesByTree.set(tree, index);
+ }
+ return index;
+}
+
+/**
+ * How a doc's links find their targets (spec:AST-047 FR9): a doc in the
+ * project's docs tree by its identity, or a flat topic by its provider and
+ * name. A target that matches neither is a problem, never a guess.
+ * @param {DocsCatalog} catalog
+ * @param {string} fromProvider the provider id of the doc the links sit in
+ * @returns {Promise<LinkResolver>}
+ */
+export async function linkResolver(catalog, fromProvider) {
+ const identities = identitiesOf(await projectTree(catalog));
+ return async target => {
+ const parsed = parseLinkTarget(target);
+ if ('error' in parsed) return {problem: parsed.error};
+ let provider;
+ try {
+ provider = normalizeProviderId(parsed.provider ?? fromProvider);
+ } catch {
+ return {
+ problem: `"${target}" names "${parsed.provider}", which is not a provider id: an npm package name, or the \`providerId\` its manifest declares`,
+ };
+ }
+ const node = identities.get(identityKey(provider, parsed.kind, parsed.name));
+ if (node) {
+ return {
+ target,
+ id: /** @type {string} */ (node.id),
+ route: node.route,
+ title: node.title,
+ summary: node.summary,
+ command: `astryx docs ${node.route}`,
+ };
+ }
+ if (parsed.kind === 'generic') {
+ const entry = catalog.resolve(parsed.name);
+ if (
+ entry &&
+ !entry.tree &&
+ (providerOf(entry) === provider ||
+ catalog.aliasesOf(entry).includes(parsed.name.toLowerCase()))
+ ) {
+ let title = entry.title ?? entry.name;
+ let summary = entry.description ?? '';
+ try {
+ const raw = await lowerRawTopic(catalog, entry);
+ title = raw.doc.title ?? title;
+ summary = raw.doc.description ?? summary;
+ } catch {
+ // The topic budget check reports a topic that does not load; the
+ // link still opens it.
+ }
+ return {
+ target,
+ id: createDocId(provider, 'generic', parsed.name),
+ route: entry.name,
+ title,
+ summary,
+ command: `astryx docs ${entry.name}`,
+ };
+ }
+ }
+ return {
+ problem: `"${target}" names no doc. Find it with \`astryx search ${parsed.name} --type doc\`, then name it as \`[<provider>:]<kind>:<name>\`.`,
+ };
+ };
+}
+
+/**
+ * Every link in the project's docs that names no doc: in each topic, each
+ * guide the tree places, and each typed doc.
+ * @param {DocsCatalog} catalog
+ * @param {DocsTree} tree
+ * @param {{owner?: string}} [options] `owner`: only the docs this package owns
+ * @returns {Promise<string[]>}
+ */
+export async function docsLinkProblems(catalog, tree, {owner} = {}) {
+ /** @type {string[]} */
+ const problems = [];
+ /** @param {string} where @param {LinkProblem[]} found */
+ const note = (where, found) => {
+ for (const problem of found) {
+ problems.push(
+ `${where}${problem.section ? ` \u00a7 ${problem.section}` : ''}: ${problem.message}`,
+ );
+ }
+ };
+ for (const entry of catalog.entries()) {
+ // A package owns a topic it wrote, and the sections it adds to another
+ // package's topic.
+ if (
+ owner != null &&
+ entry.package !== owner &&
+ !entry.extensions.some(extension => extension.package === owner)
+ ) {
+ continue;
+ }
+ try {
+ note(entry.name, await topicLinkProblems(catalog, entry));
+ } catch {
+ // The topic budget check reports a topic that does not load.
+ }
+ }
+ for (const node of tree.nodes.values()) {
+ if (owner != null && node.provider !== owner) continue;
+ if (node.kind === 'generic' && node.ref?.topicFile) {
+ try {
+ note(node.route, await topicLinkProblems(catalog, guideEntry(node)));
+ } catch {
+ // As above.
+ }
+ } else if (node.ref?.selfDoc) {
+ note(node.route, (await nodeContent(catalog, tree, node)).problems);
+ }
+ }
+ 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
+ * every link in them (spec:AST-046, spec:AST-047).
+ * @param {{name: string}} 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[]}} discovered
+ * @returns {Promise<string[]>}
+ */
+export async function packageDocsProblems(integration, discovered) {
+ const catalog = DocsCatalog.fromBuiltins();
+ 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 tree = await projectTree(catalog);
+ const problems = tree.diagnostics
+ .filter(d => d.severity === 'error' && d.provider === integration.name)
+ .map(d => `${d.source ?? integration.name}: ${d.message}`);
+ problems.push(
+ ...(await docsLinkProblems(catalog, tree, {owner: integration.name})),
+ );
+ return problems;
+}
+
/**
* How a token reference finds its target: the topic it names in `catalog`,
* lowered for the same language.
@@ -125,40 +502,295 @@ export async function compileTopic(catalog, entry, lang = null) {
}
/**
- * Resolve `topic` against the project's catalog (throwing `ERR_UNKNOWN_TOPIC`
- * when unmatched) and lower it with any --dense/--zh overlay and any
- * integration extension applied. Shared by the leaves so topic normalization
- * and unknown-topic handling live in exactly one place.
- *
- * @param {string} topic
- * @param {object} [options]
- * @param {string} [options.lang]
- * @param {boolean} [options.zh]
- * @param {boolean} [options.dense]
- * @param {string} [options.cwd]
- * @returns {Promise<{
- * catalog: DocsCatalog,
- * node: import('../../foundation/doc-compiler/compile.mjs').CompiledReferenceNode,
- * lang: string | null,
- * }>}
+ * A guide the docs tree places, as a topic entry the topic readers open by its
+ * route. It is never a flat topic: `astryx docs <route>` is its only name.
+ * @param {import('../../foundation/doc-compiler/tree.mjs').TreeNode} node
+ * @returns {import('../../foundation/discovery/docs-discovery.mjs').DocsTopicEntry}
*/
-export async function resolveTopicDocs(topic, options = {}) {
- const {lang = null, zh = false, dense = false, cwd} = options;
- const effectiveLang = lang || (dense ? 'dense' : zh ? 'zh' : null);
- const catalog = await loadDocsCatalog(cwd);
+export function guideEntry(node) {
+ return {
+ name: node.route,
+ route: node.route,
+ package: node.provider,
+ providerId: node.providerId,
+ path: node.ref.topicFile,
+ extensions: [],
+ tree: true,
+ parent: node.parent ?? undefined,
+ };
+}
+
+/** @type {WeakMap<DocsTree, ReturnType<typeof cliDocIndex>>} */
+const typedDocIndexes = new WeakMap();
- // A public API caller could pass a non-string topic; `resolve` answers
- // undefined for one, which lands on the same stable code as an unknown name
- // rather than a raw TypeError (which downgrades to ERR_UNKNOWN).
- const entry = catalog.resolve(topic);
- if (!entry) {
- throw new AstryxError(
- `Unknown topic "${String(topic)}"`,
- catalog.names().map(t => ({name: t, reason: 'available topic'})),
- ERROR_CODES.ERR_UNKNOWN_TOPIC,
+/**
+ * What a typed doc in the docs tree prints: its content, with every link to
+ * another doc resolved (spec:AST-047 FR9). A namespace has no content. The
+ * CLI's doc modules are discovery, so this lives in the adapter
+ * (architecture:cli-surface INV21).
+ * @param {DocsCatalog} catalog
+ * @param {DocsTree} tree
+ * @param {TreeNode} node
+ * @returns {Promise<{content: any[], problems: LinkProblem[]}>}
+ */
+export async function nodeContent(catalog, tree, node) {
+ if (!node.ref?.selfDoc) return {content: [], problems: []};
+ let index = typedDocIndexes.get(tree);
+ if (!index) {
+ index = cliDocIndex(
+ [...tree.nodes.values()].flatMap(each =>
+ each.ref?.selfDoc ? [each.ref.selfDoc] : [],
+ ),
);
+ typedDocIndexes.set(tree, index);
}
+ const resolve = await linkResolver(catalog, node.providerId);
+ return linkBlocks(cliDocSection(node.ref.selfDoc, index).content, resolve);
+}
+
+/**
+ * The command that opens the level a topic sits in when the tree cannot say:
+ * a guide's parent namespace, or the topic list.
+ * @param {import('../../foundation/discovery/docs-discovery.mjs').DocsTopicEntry} entry
+ * @returns {import('./docs.type.mjs').DocsCommand}
+ */
+export function topicUp(entry) {
+ return entry.tree && entry.parent
+ ? `astryx docs ${entry.parent}`
+ : 'astryx docs';
+}
+/**
+ * The moves from a node's place in the tree (spec:AST-047 FR2, FR4): up to its
+ * parent (the topic list, at the top), and across to the nodes before and
+ * after it in its parent's slot.
+ * @param {DocsTree} tree
+ * @param {TreeNode} node
+ * @returns {import('./docs.type.mjs').DocsLinks}
+ */
+export function placeLinks(tree, node) {
+ /** @type {import('./docs.type.mjs').DocsLinks} */
+ const links = {
+ up: node.parent == null ? 'astryx docs' : `astryx docs ${node.parent}`,
+ };
+ const parent = node.parent == null ? undefined : tree.get(node.parent);
+ const siblings =
+ parent?.slots.find(slot => slot.children.includes(node.route))?.children ??
+ [];
+ const at = siblings.indexOf(node.route);
+ if (at > 0) links.previous = `astryx docs ${siblings[at - 1]}`;
+ if (at !== -1 && at < siblings.length - 1) {
+ links.next = `astryx docs ${siblings[at + 1]}`;
+ }
+ return links;
+}
+
+/**
+ * The moves a topic read offers: from its place in the tree, where a guide
+ * sits in its namespace and a flat topic in the Unorganized level.
+ * @param {DocsCatalog} catalog
+ * @param {import('../../foundation/discovery/docs-discovery.mjs').DocsTopicEntry} entry
+ * @returns {Promise<import('./docs.type.mjs').DocsLinks>}
+ */
+export async function topicLinks(catalog, entry) {
+ const tree = await projectTree(catalog);
+ const node = tree.get(entry.tree ? (entry.route ?? entry.name) : entry.name);
+ const placed =
+ node && (entry.tree ? node.kind === 'generic' : node.ref?.flatTopic === entry.name);
+ return placed ? placeLinks(tree, node) : {up: topicUp(entry)};
+}
+
+/**
+ * What a docs argument names: a topic (a flat one, or a guide the docs tree
+ * places), a namespace or typed doc in the tree, or nothing, as nameOwner
+ * decides.
+ * @param {unknown} topic
+ * @param {{cwd?: string}} [options]
+ * @returns {Promise<
+ * | {kind: 'topic', catalog: DocsCatalog, entry: import('../../foundation/discovery/docs-discovery.mjs').DocsTopicEntry}
+ * | {kind: 'node', catalog: DocsCatalog, tree: import('../../foundation/doc-compiler/tree.mjs').DocsTree, node: import('../../foundation/doc-compiler/tree.mjs').TreeNode}
+ * | {kind: 'unknown', catalog: DocsCatalog}
+ * >}
+ */
+export async function resolveDocsArgument(topic, {cwd} = {}) {
+ const catalog = await loadDocsCatalog(cwd);
+ if (typeof topic !== 'string' || topic === '')
+ return {kind: 'unknown', catalog};
+ const tree = await projectTree(catalog);
+ const owner = nameOwner(tree, catalog, topic);
+ if (owner == null) return {kind: 'unknown', catalog};
+ if (owner.kind === 'topic') return {kind: 'topic', catalog, entry: owner.entry};
+ return treeArgument(catalog, tree, owner.node);
+}
+
+/**
+ * Who answers to a name a reader types (spec:AST-046 FR5, FR11). The tree
+ * decides first: the node at that route, compared without case, holds it. A
+ * name with no node of its own is a topic's other name (its `replaces`
+ * alias), and that topic answers, unless the tree gave the topic's own route
+ * to another doc. Reads, the topic list, and search all ask this, so they
+ * agree on every name.
+ * @param {DocsTree} tree
+ * @param {DocsCatalog} catalog
+ * @param {string} name
+ * @returns {{kind: 'topic', entry: import('../../foundation/discovery/docs-discovery.mjs').DocsTopicEntry} | {kind: 'node', node: TreeNode} | null}
+ */
+export function nameOwner(tree, catalog, name) {
+ const node = tree.get(name) ?? tree.getFolded?.(name);
+ if (node != null) {
+ if (node.ref?.flatTopic == null) return {kind: 'node', node};
+ const entry = catalog.resolve(node.ref.flatTopic);
+ return entry == null ? null : {kind: 'topic', entry};
+ }
+ const entry = catalog.resolve(name);
+ if (entry == null) return null;
+ const owner = routeOwner(tree, entry);
+ return owner == null ? {kind: 'topic', entry} : {kind: 'node', node: owner};
+}
+
+/**
+ * Whether a topic answers to its own name: what the topic list and search
+ * offer must open that topic.
+ * @param {DocsTree} tree
+ * @param {DocsCatalog} catalog
+ * @param {import('../../foundation/discovery/docs-discovery.mjs').DocsTopicEntry} entry
+ * @returns {boolean}
+ */
+export function holdsOwnName(tree, catalog, entry) {
+ const owner = nameOwner(tree, catalog, entry.name);
+ return (
+ owner?.kind === 'topic' &&
+ owner.entry.name === entry.name &&
+ owner.entry.package === entry.package
+ );
+}
+
+/**
+ * What a tree node opens as: a guide the tree places reads like a topic; a
+ * namespace or a typed doc is a node.
+ * @param {DocsCatalog} catalog
+ * @param {DocsTree} tree
+ * @param {TreeNode} node
+ * @returns {{kind: 'topic', catalog: DocsCatalog, entry: import('../../foundation/discovery/docs-discovery.mjs').DocsTopicEntry} | {kind: 'node', catalog: DocsCatalog, tree: DocsTree, node: TreeNode}}
+ */
+function treeArgument(catalog, tree, node) {
+ if (node.kind === 'generic') {
+ return {kind: 'topic', catalog, entry: guideEntry(node)};
+ }
+ return {kind: 'node', catalog, tree, node};
+}
+
+/**
+ * The doc that took a flat topic's route in the docs tree, when it is not
+ * that topic (spec:AST-046 FR11): the CLI keeps its routes, such as `cli`
+ * and `unorganized`, and a namespace keeps its route over a topic of the same
+ * name. Null when the topic owns its route, or the tree has no node there.
+ * @param {DocsTree} tree
+ * @param {import('../../foundation/discovery/docs-discovery.mjs').DocsTopicEntry} entry
+ * @returns {TreeNode | null}
+ */
+export function routeOwner(tree, entry) {
+ const node = tree.get(entry.name) ?? tree.getFolded?.(entry.name);
+ if (node == null) return null;
+ return node.ref?.flatTopic === entry.name && node.provider === entry.package
+ ? null
+ : node;
+}
+
+/**
+ * The error for a docs argument that names nothing. For a route, it suggests
+ * the children of the deepest namespace the route reaches; otherwise, every
+ * topic and every top-level namespace.
+ * @param {unknown} topic
+ * @param {DocsCatalog} catalog
+ * @returns {Promise<AstryxError>}
+ */
+export async function unknownTopicError(topic, catalog) {
+ const tree = await projectTree(catalog);
+ /** @type {Array<{name: string, reason: string}>} */
+ let suggestions = [];
+ if (typeof topic === 'string' && topic.includes('/')) {
+ const parts = topic.split('/');
+ for (
+ let depth = parts.length - 1;
+ depth > 0 && suggestions.length === 0;
+ depth--
+ ) {
+ const near = tree.get(parts.slice(0, depth).join('/'));
+ if (near) {
+ suggestions = near.slots.flatMap(slot =>
+ slot.children.map(route => ({
+ name: route,
+ reason: tree.get(route)?.summary ?? '',
+ })),
+ );
+ }
+ }
+ }
+ if (suggestions.length === 0 && typeof topic === 'string') {
+ // The docs whose own name it is (`doctor` is cli/commands/doctor), or whose
+ // route it spells with hyphens (`cli-integrations`, the guide's name before
+ // it moved to cli/integrations).
+ const wanted = topic.toLowerCase();
+ suggestions = [...tree.nodes.values()]
+ .filter(
+ node =>
+ !node.ref?.flatTopic &&
+ (node.name.toLowerCase() === wanted ||
+ node.route.replaceAll('/', '-').toLowerCase() === wanted),
+ )
+ .map(node => ({name: node.route, reason: node.summary}));
+ }
+ if (suggestions.length === 0) {
+ suggestions = [
+ ...tree
+ .roots()
+ .map(root => ({name: root.route, reason: 'docs namespace'})),
+ ...catalog.names().map(name => ({name, reason: 'available topic'})),
+ ];
+ }
+ return new AstryxError(
+ `Unknown topic "${String(topic)}"${notLoaded(catalog)}`,
+ suggestions,
+ ERROR_CODES.ERR_UNKNOWN_TOPIC,
+ );
+}
+
+/**
+ * A sentence naming the packages whose docs did not load, or nothing: a doc
+ * that fails to load withdraws its package's docs, so a reader who cannot
+ * find one learns where to look.
+ * @param {DocsCatalog} catalog
+ * @returns {string}
+ */
+export function notLoaded(catalog) {
+ const packages = [...new Set(catalog.issues.map(issue => issue.package))];
+ if (packages.length === 0) return '';
+ return `. The docs of ${packages.join(', ')} did not load; run \`astryx doctor integration docs\` in that package to see why.`;
+}
+
+/**
+ * Resolve a topic (a flat one, or a guide the docs tree places by its route)
+ * and lower it for the topic readers.
+ * @param {unknown} topic
+ * @param {{lang?: string | null, zh?: boolean, dense?: boolean, cwd?: string}} [options]
+ */
+export async function resolveTopicDocs(topic, options = {}) {
+ const {lang = null, zh = false, dense = false, cwd} = options;
+ const effectiveLang = lang || (dense ? 'dense' : zh ? 'zh' : null);
+ // A public API caller could pass a non-string topic; it lands on the same
+ // stable code as an unknown name rather than a raw TypeError.
+ const found = await resolveDocsArgument(topic, {cwd});
+ if (found.kind !== 'topic') {
+ throw found.kind === 'node'
+ ? new AstryxError(
+ `"${found.node.route}" is a ${found.node.kind === 'namespace' ? 'namespace' : `${found.node.kind} doc`} in the docs tree, not a topic. Read it with \`astryx docs ${found.node.route}\`.`,
+ undefined,
+ ERROR_CODES.ERR_UNKNOWN_TOPIC,
+ )
+ : await unknownTopicError(topic, found.catalog);
+ }
+ const {catalog, entry} = found;
const node = await lowerTopic(catalog, entry, effectiveLang);
- return {catalog, node, lang: effectiveLang};
+ return {catalog, node, lang: effectiveLang, entry};
}
diff --git a/packages/cli/api/docs/detail/detail.mjs b/packages/cli/api/docs/detail/detail.mjs
index e8c160a12b..d665550b39 100644
--- a/packages/cli/api/docs/detail/detail.mjs
+++ b/packages/cli/api/docs/detail/detail.mjs
@@ -13,7 +13,7 @@
import {linkReferenceTopic} from '../../../foundation/doc-compiler/compile.mjs';
import {detailView} from '../../../foundation/doc-compiler/lenses.mjs';
-import {referenceTargets, resolveTopicDocs} from '../_adapter.mjs';
+import {referenceTargets, resolveTopicDocs, topicLinks} from '../_adapter.mjs';
/**
* @param {string} topic
@@ -25,10 +25,18 @@ import {referenceTargets, resolveTopicDocs} from '../_adapter.mjs';
* @returns {Promise<import('../docs.type.mjs').DocsDetailResponse>}
*/
export async function detail(topic, options = {}) {
- const {catalog, node, lang} = await resolveTopicDocs(topic, options);
+ const {catalog, node, lang, entry} = await resolveTopicDocs(topic, options);
const linked = await linkReferenceTopic(
node,
referenceTargets(catalog, lang),
);
- return {type: 'docs.detail', data: detailView(linked)};
+ return {
+ type: 'docs.detail',
+ data: {
+ ...detailView(linked),
+ // A guide the docs tree places is read by its route, not its doc name.
+ ...(entry.tree ? {name: entry.name} : {}),
+ links: await topicLinks(catalog, entry),
+ },
+ };
}
diff --git a/packages/cli/api/docs/detail/section/section.mjs b/packages/cli/api/docs/detail/section/section.mjs
index 9a37b6c46c..4a640726fd 100644
--- a/packages/cli/api/docs/detail/section/section.mjs
+++ b/packages/cli/api/docs/detail/section/section.mjs
@@ -17,7 +17,10 @@
import {AstryxError} from '../../../error.mjs';
import {ERROR_CODES} from '../../../../foundation/response/error-codes.mjs';
-import {findDocSection} from '../../../../foundation/discovery/docs-section-key.mjs';
+import {
+ findDocSection,
+ sectionKey,
+} from '../../../../foundation/discovery/docs-section-key.mjs';
import {linkReferenceSection} from '../../../../foundation/doc-compiler/compile.mjs';
import {
readerSections,
@@ -47,7 +50,7 @@ export async function section(topic, sectionName, options = {}) {
);
}
- const {catalog, node, lang} = await resolveTopicDocs(topic, options);
+ const {catalog, node, lang, entry} = await resolveTopicDocs(topic, options);
const sections = readerSections(node);
const {section: match} = findDocSection(sections, sectionName);
if (!match) {
@@ -68,5 +71,19 @@ export async function section(topic, sectionName, options = {}) {
match,
referenceTargets(catalog, lang),
);
- return {type: 'docs.detail.section', data: sectionView(node, linked)};
+ // The moves from one section (spec:AST-047): up to its topic's index, and
+ // across to the sections before and after it.
+ const at = sections.indexOf(match);
+ /** @type {import('../../docs.type.mjs').DocsLinks} */
+ const links = {up: `astryx docs ${entry.name} --index`};
+ if (at > 0) {
+ links.previous = `astryx docs ${entry.name} ${sectionKey(sections[at - 1])}`;
+ }
+ if (at !== -1 && at < sections.length - 1) {
+ links.next = `astryx docs ${entry.name} ${sectionKey(sections[at + 1])}`;
+ }
+ return {
+ type: 'docs.detail.section',
+ data: {...sectionView(node, linked), links},
+ };
}
diff --git a/packages/cli/api/docs/docs.doc.mjs b/packages/cli/api/docs/docs.doc.mjs
index c0922d5f0c..c098207b79 100644
--- a/packages/cli/api/docs/docs.doc.mjs
+++ b/packages/cli/api/docs/docs.doc.mjs
@@ -16,18 +16,26 @@ export const doc = {
summary:
'Read the reference docs: list every topic, one topic\'s sections, one section, or a whole topic.',
description:
- 'No topic lists every reference-doc topic; a topic returns that full ' +
- 'ReferenceDoc; `index: true` returns the topic\'s section index instead ' +
- '(each section\'s key, title, and summary); a topic plus a section returns ' +
- 'that one section, found by its key, then its exact title, then a unique ' +
- 'part of its title (an ambiguous query is refused). Token-ref blocks are ' +
+ 'No topic lists every reference-doc topic; a topic returns its whole ' +
+ 'ReferenceDoc, and `index: true` returns its section index (each ' +
+ 'section\'s key, title, and summary); a topic plus a section returns ' +
+ 'that one section. Token-ref blocks are ' +
'inlined in every read. The topic set is the CLI\'s own docs plus the ' +
'ones the project\'s configured integrations contribute, including any ' +
'topic an integration replaces or extends, so it depends on the cwd. ' +
+ 'A route opens a node of the docs tree instead: a namespace such as ' +
+ "`cli/api` returns its children one level down, a typed doc such as " +
+ "`cli/api/functions/search` returns its content, and a guide the tree " +
+ 'places (`cli/integrations`) reads like any topic. ' +
+ 'Every read but the list carries `links`, the commands that move from it: ' +
+ '`up` to the level it sits in, `previous` and `next` to its neighbors, and, ' +
+ 'for a typed doc, `related` to the docs it names (its command or function, ' +
+ 'and its related docs); `previous` and `next` ' +
+ 'to the section or node before and after it. ' +
'Overlay options select localized or dense variants.',
importPath: '@astryxdesign/cli/api',
signature:
- 'docs(topic?: string, section?: string, options?: DocsOptions): Promise<DocsListResponse | DocsIndexResponse | DocsDetailResponse | DocsDetailSectionResponse>',
+ 'docs(topic?: string, section?: string, options?: DocsOptions): Promise<DocsListResponse | DocsIndexResponse | DocsDetailResponse | DocsDetailSectionResponse | DocsNodeResponse>',
keywords: [
'docs',
'documentation',
@@ -43,7 +51,7 @@ export const doc = {
name: 'topic',
type: 'string',
description:
- "Doc topic to load (e.g. 'principles'). Omit to list all topics.",
+ "Doc topic to load (e.g. 'principles'), or a docs-tree route (e.g. 'cli/api/functions/search'). Omit to list all topics.",
},
{
name: 'section',
@@ -64,13 +72,14 @@ export const doc = {
{
name: 'options.dense',
type: 'boolean',
- description: 'Return the token-efficient dense doc variant.',
+ description:
+ 'Return the token-efficient dense doc variant. It is written to be read whole, so it returns the whole doc.',
},
{
name: 'options.index',
type: 'boolean',
description:
- "Return the topic's section index (each section's key, title, and summary) instead of the whole doc.",
+ "Return the topic's section index (each section's key, title, and summary), even for a topic with one section.",
},
{
name: 'options.cwd',
@@ -83,41 +92,52 @@ export const doc = {
{
type: 'docs.list',
description:
- 'All available reference-doc topics as DocsListEntry[] ({topic, description, package, replaces?}), in read order.',
+ "Every reference-doc topic in read order, as DocsListEntry[] ({topic, description, package, replaces?}), each readable with docs(topic). meta.namespaces lists the docs tree's top-level namespaces ({topic, description, package}), and meta.notLoaded each package whose docs did not load ({package, message}).",
},
{
type: 'docs.detail',
description:
- "One topic's full ReferenceDoc, with token-ref blocks inlined.",
+ "One topic's full ReferenceDoc, with token-ref blocks inlined, plus links.",
},
{
type: 'docs.index',
description:
- "One topic's section index (index: true): {name, title, description, sections: [{id, title, summary}]}.",
+ "One topic's section index (index: true): {name, title, description, sections: [{id, title, summary}], links}.",
},
{
type: 'docs.detail.section',
description:
'One ReferenceSection of the topic, found by key or title, with token-ref blocks inlined.',
},
+ {
+ type: 'docs.node',
+ description:
+ "A namespace or typed doc in the docs tree, read by its route: {id, route, kind, package, title, summary, breadcrumb, slots, content}. A namespace lists each slot's children one level down; a typed doc carries its content.",
+ },
],
throws: [
{
code: 'ERR_UNKNOWN_TOPIC',
- when: 'the topic is not a string or matches no known doc topic',
+ when: 'the topic is not a string, or matches no topic and no docs-tree route',
},
{
code: 'ERR_UNKNOWN_SECTION',
- when: 'a section is requested but is empty, matches no section, or matches more than one',
+ when: 'a section is requested but is empty, matches no section, matches more than one, or is asked of a docs-tree namespace or typed doc, which have no sections',
},
],
examples: [
{label: 'List topics', code: 'const r = await docs();'},
- {label: 'Load a topic', code: "await docs('principles');"},
+ {label: 'A whole topic', code: "await docs('principles');"},
{
label: "A topic's sections",
code: "await docs('principles', undefined, {index: true});",
},
+ {label: 'A docs-tree namespace', code: "await docs('cli/api');"},
+ {label: 'One API function', code: "await docs('cli/api/functions/search');"},
+ {
+ label: 'A whole guide from the docs tree',
+ code: "await docs('cli/integrations');",
+ },
{label: 'One section by key', code: "await docs('tokens', 'spacing');"},
],
command: 'docs',
diff --git a/packages/cli/api/docs/docs.mjs b/packages/cli/api/docs/docs.mjs
index 59a57ee5b9..f3e3352f2c 100644
--- a/packages/cli/api/docs/docs.mjs
+++ b/packages/cli/api/docs/docs.mjs
@@ -3,27 +3,35 @@
/**
* @file Programmatic API for the docs command.
*
- * Dispatcher + barrel. `docs()` routes by argument shape into one of four
+ * Dispatcher + barrel. `docs()` routes by argument shape into one of five
* leaves, each projecting into a single { type, data } envelope:
*
* docs() -> list -> docs.list
* docs(topic) -> detail -> docs.detail
* docs(topic, undefined, {index: true}) -> index -> docs.index
* docs(topic, section) -> section -> docs.detail.section
+ * docs(route) -> node -> docs.node
*
- * A topic read returns the whole doc, as it always has. The index is how a
- * reader works progressively instead: list the topic's sections, then read one
- * by its key. The leaves live in list/, index/, detail/, and detail/section/;
- * the discovery, overlay loading, and topic resolution they share sit in
- * _adapter.mjs.
+ * A topic read returns the whole doc, as it always has; `index` returns its
+ * sections, so a reader can open one by its key (spec:AST-047). The CLI's text
+ * view lists the sections by default. A route names a node
+ * of the docs tree (spec:AST-046): a namespace lists its children, a guide the
+ * tree places reads like any topic, and a typed doc prints its content. The
+ * leaves
+ * live in list/, index/, detail/, detail/section/, and node/; the discovery,
+ * overlay loading, and resolution they share sit in _adapter.mjs.
*/
import {list} from './list/list.mjs';
import {index} from './index/index.mjs';
import {detail} from './detail/detail.mjs';
import {section as sectionLeaf} from './detail/section/section.mjs';
+import {node as nodeLeaf, nodeView} from './node/node.mjs';
+import {resolveDocsArgument} from './_adapter.mjs';
+import {AstryxError} from '../error.mjs';
+import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
-export {list, index, detail, sectionLeaf as section};
+export {list, index, detail, sectionLeaf as section, nodeLeaf as node};
/**
* @param {string} [topic]
@@ -39,11 +47,39 @@ export {list, index, detail, sectionLeaf as section};
* import('./docs.type.mjs').DocsListResponse |
* import('./docs.type.mjs').DocsIndexResponse |
* import('./docs.type.mjs').DocsDetailResponse |
- * import('./docs.type.mjs').DocsDetailSectionResponse
+ * import('./docs.type.mjs').DocsDetailSectionResponse |
+ * import('./docs.type.mjs').DocsNodeResponse
* >}
*/
export async function docs(topic, section, options = {}) {
if (!topic) return list(options);
+ const found = await resolveDocsArgument(topic, options);
+ if (found.kind === 'node') {
+ // A namespace or a typed doc has no sections: it is one read. `--index`
+ // asks for what the node read already is.
+ if (section) {
+ throw new AstryxError(
+ `"${found.node.route}" has no sections. ${
+ found.node.kind === 'namespace'
+ ? 'Open one of its children instead.'
+ : `Read it whole: astryx docs ${found.node.route}.`
+ }`,
+ found.node.kind === 'namespace'
+ ? found.node.slots.flatMap(slot =>
+ slot.children.map(route => ({
+ name: route,
+ reason: found.tree.get(route)?.summary ?? '',
+ })),
+ )
+ : [{name: found.node.route, reason: found.node.summary}],
+ ERROR_CODES.ERR_UNKNOWN_SECTION,
+ );
+ }
+ return {
+ type: 'docs.node',
+ data: await nodeView(found.catalog, found.tree, found.node),
+ };
+ }
if (section) return sectionLeaf(topic, section, options);
if (options.index) return index(topic, options);
return detail(topic, options);
diff --git a/packages/cli/api/docs/docs.test.mjs b/packages/cli/api/docs/docs.test.mjs
index 59fa375b63..7e815fb0f3 100644
--- a/packages/cli/api/docs/docs.test.mjs
+++ b/packages/cli/api/docs/docs.test.mjs
@@ -26,11 +26,9 @@ describe('docs() dispatcher routing', () => {
expect((await docs('')).type).toBe('docs.list');
}, SLOW);
- it('topic only -> docs.detail', async () => {
+ it('topic only -> docs.detail, the whole doc', async () => {
const {data} = await docs();
- const topic = data[0].topic;
- const r = await docs(topic);
- expect(r.type).toBe('docs.detail');
+ expect((await docs(data[0].topic)).type).toBe('docs.detail');
}, SLOW);
it('topic + index -> docs.index', async () => {
@@ -69,6 +67,162 @@ describe('docs() dispatcher routing', () => {
});
}, SLOW);
+ it("lists the docs tree's namespaces in meta, so every data entry reads as a topic", async () => {
+ const res = await docs();
+ expect(res.meta.namespaces.map(entry => entry.topic)).toEqual(['cli', 'unorganized']);
+ for (const entry of res.data) {
+ expect((await docs(entry.topic)).type).toBe('docs.detail');
+ }
+ }, SLOW);
+
+ it('opens a route typed in another case', async () => {
+ const r = await docs('CLI/API');
+ expect(r.type).toBe('docs.node');
+ expect(r.data).toMatchObject({route: 'cli/api', links: {up: 'astryx docs cli'}});
+ }, SLOW);
+
+ it('a section of a typed doc -> ERR_UNKNOWN_SECTION, suggesting the doc itself', async () => {
+ const err = await docs('cli/api/functions/search', 'x').catch(e => e);
+ expect(err.code).toBe('ERR_UNKNOWN_SECTION');
+ expect(err.message).toContain('astryx docs cli/api/functions/search');
+ expect(err.suggestions.map(s => s.name)).toEqual(['cli/api/functions/search']);
+ }, SLOW);
+
+ it('a namespace route -> docs.node, one level of children', async () => {
+ const r = await docs('cli/api');
+ expect(r.type).toBe('docs.node');
+ expect(r.data).toMatchObject({
+ id: 'astryx:artifact:v1/%40astryxdesign%2Fcli/namespace/api',
+ route: 'cli/api',
+ kind: 'namespace',
+ package: '@astryxdesign/cli',
+ breadcrumb: [{route: 'cli', title: 'Astryx CLI'}],
+ content: [],
+ });
+ expect(r.data.slots.flatMap(slot => slot.children.map(c => c.route))).toEqual([
+ 'cli/api/functions',
+ 'cli/api/schemas',
+ 'cli/api/enums',
+ ]);
+ }, SLOW);
+
+ it('a typed doc route -> docs.node with its content', async () => {
+ const r = await docs('cli/api/functions/search');
+ expect(r.type).toBe('docs.node');
+ expect(r.data).toMatchObject({
+ id: 'astryx:artifact:v1/%40astryxdesign%2Fcli/function/search',
+ kind: 'function',
+ title: 'search()',
+ slots: [],
+ });
+ expect(r.data.breadcrumb.map(link => link.route)).toEqual([
+ 'cli',
+ 'cli/api',
+ 'cli/api/functions',
+ ]);
+ expect(JSON.stringify(r.data.content)).toContain(
+ '`astryx search` runs it. Read it with `astryx docs cli/commands/search`.',
+ );
+ }, SLOW);
+
+ it('a guide the tree places reads like a topic: the whole doc, its index, a section', async () => {
+ expect((await docs('cli/integrations')).type).toBe('docs.detail');
+ const index = await docs('cli/integrations', undefined, {index: true});
+ expect(index).toMatchObject({type: 'docs.index', data: {name: 'cli/integrations'}});
+ expect(index.data.sections.length).toBeGreaterThan(1);
+ expect((await docs('cli/integrations', 'components')).type).toBe(
+ 'docs.detail.section',
+ );
+ }, SLOW);
+
+ it('every read carries its moves (spec:AST-047)', async () => {
+ const root = (await docs('cli')).data;
+ expect(root.links).toEqual({up: 'astryx docs'});
+ const leaf = (await docs('cli/api/functions/search')).data;
+ expect(leaf.links.up).toBe('astryx docs cli/api/functions');
+ expect(leaf.links.previous).toMatch(/^astryx docs cli\/api\/functions\/[a-z-]+$/);
+ expect(leaf.links.next).toMatch(/^astryx docs cli\/api\/functions\/[a-z-]+$/);
+ const index = await docs('cli/integrations', undefined, {index: true});
+ // A guide moves across its namespace's slot, as any tree node does.
+ expect(index.data.links).toEqual({
+ up: 'astryx docs cli',
+ next: 'astryx docs cli/writing-docs',
+ });
+ const first = (await docs('cli/integrations', index.data.sections[0].id)).data;
+ expect(first.links).toEqual({
+ up: 'astryx docs cli/integrations --index',
+ next: `astryx docs cli/integrations ${index.data.sections[1].id}`,
+ });
+ const last = index.data.sections.at(-1).id;
+ const end = (await docs('cli/integrations', last)).data;
+ expect(end.links.next).toBeUndefined();
+ expect(end.links.previous).toBe(
+ `astryx docs cli/integrations ${index.data.sections.at(-2).id}`,
+ );
+ // A flat topic's home is the Unorganized level, and it moves across it.
+ const flat = (await docs('principles')).data.links;
+ expect(flat.up).toBe('astryx docs unorganized');
+ expect(flat.previous).toMatch(/^astryx docs [a-z-]+$/);
+ expect(flat.next).toMatch(/^astryx docs [a-z-]+$/);
+ const home = (await docs('unorganized')).data;
+ expect(home).toMatchObject({id: null, kind: 'namespace', links: {up: 'astryx docs'}});
+ expect(home.slots[0].children.map(child => child.route)).toEqual(
+ (await docs()).data.map(entry => entry.topic),
+ );
+ }, SLOW);
+
+ it('names a node by its doc identity; a generated level has id null', async () => {
+ const level = (await docs('cli/api/functions')).data;
+ expect(level).toHaveProperty('id', null);
+ expect(level.route).toBe('cli/api/functions');
+ }, SLOW);
+
+ it("offers a typed doc's related docs as moves", async () => {
+ const fn = (await docs('cli/api/functions/search')).data;
+ expect(fn.links.related).toContain('astryx docs cli/commands/search');
+ const cmd = (await docs('cli/commands/search')).data;
+ expect(cmd.links.related).toContain('astryx docs cli/api/functions/search');
+ }, SLOW);
+
+ it('a topic read returns the whole doc; index returns its sections', async () => {
+ expect((await docs('principles')).type).toBe('docs.detail');
+ const index = await docs('principles', undefined, {index: true});
+ expect(index.type).toBe('docs.index');
+ expect(index.data.sections.length).toBeGreaterThan(1);
+ expect((await docs('principles', undefined, {dense: true})).type).toBe(
+ 'docs.detail',
+ );
+ }, SLOW);
+
+ it("the guide's old flat name is gone, and its error names the new route", async () => {
+ await expect(docs('cli-integrations')).rejects.toMatchObject({
+ code: 'ERR_UNKNOWN_TOPIC',
+ suggestions: [expect.objectContaining({name: 'cli/integrations'})],
+ });
+ expect((await docs()).data.map(entry => entry.topic)).not.toContain(
+ 'cli-integrations',
+ );
+ }, SLOW);
+
+ it('a section of a namespace -> ERR_UNKNOWN_SECTION, naming its children', async () => {
+ const err = await docs('cli', 'commands').catch(e => e);
+ expect(err).toBeInstanceOf(AstryxError);
+ expect(err.code).toBe('ERR_UNKNOWN_SECTION');
+ expect(err.suggestions.map(s => s.name)).toEqual([
+ 'cli/integrations',
+ 'cli/writing-docs',
+ 'cli/commands',
+ 'cli/api',
+ ]);
+ }, SLOW);
+
+ it('an unknown route suggests the children of the deepest namespace it reaches', async () => {
+ const err = await docs('cli/api/functions/serch').catch(e => e);
+ expect(err.code).toBe('ERR_UNKNOWN_TOPIC');
+ expect(err.suggestions.map(s => s.name)).toContain('cli/api/functions/search');
+ expect(err.suggestions.every(s => s.name.startsWith('cli/api/functions/'))).toBe(true);
+ }, SLOW);
+
it('non-string topic -> ERR_UNKNOWN_TOPIC (not a raw TypeError)', async () => {
for (const bad of [123, {}, ['tokens'], true]) {
const err = await docs(/** @type {any} */ (bad)).catch(e => e);
diff --git a/packages/cli/api/docs/docs.type.mjs b/packages/cli/api/docs/docs.type.mjs
index 767326c28d..bb202e9d4a 100644
--- a/packages/cli/api/docs/docs.type.mjs
+++ b/packages/cli/api/docs/docs.type.mjs
@@ -10,6 +10,8 @@
* astryx --json docs <topic> -> docs.detail
* astryx --json docs <topic> --index -> docs.index
* astryx --json docs <topic> <section> -> docs.detail.section
+ * astryx --json docs <route> -> docs.node (a namespace or a
+ * typed doc in the docs tree)
* (unknown topic/section) -> CLIError
*/
@@ -17,7 +19,11 @@
* astryx --json docs
* @typedef {object} DocsListResponse
* @property {'docs.list'} type
- * @property {DocsListEntry[]} data
+ * @property {DocsListEntry[]} data every topic, each readable as a topic
+ * @property {{namespaces?: DocsListNamespace[], notLoaded?: Array<{package: string, message: string}>}} [meta]
+ * `namespaces`: the docs tree's top-level namespaces, each opened by its
+ * `topic` as a docs.node; `notLoaded`: each package whose doc files did not
+ * load, and why (its docs are withdrawn)
*/
/**
@@ -30,6 +36,15 @@
* was contributed as a replacement
*/
+/**
+ * A top-level namespace of the docs tree, as `astryx docs --json` lists it in
+ * `meta.namespaces`.
+ * @typedef {object} DocsListNamespace
+ * @property {string} topic its route, the argument that opens it
+ * @property {string} description
+ * @property {string} package the package that owns it
+ */
+
/**
* astryx --json docs <topic> --index
* @typedef {object} DocsIndexResponse
@@ -41,7 +56,35 @@
* astryx --json docs <topic>
* @typedef {object} DocsDetailResponse
* @property {'docs.detail'} type
- * @property {import('@astryxdesign/cli/authoring').ReferenceDoc} data
+ * @property {import('@astryxdesign/cli/authoring').ReferenceDoc & {links: DocsLinks}} data
+ * the whole doc, and the moves from it
+ */
+
+/**
+ * The doc a link opens (spec:AST-047 FR9). A docs read resolves every link:
+ * an inline `{@link <target>}` reads as `link.command`, a `reference` block
+ * carries `link` (null when the target names no doc), and each `workflow` step
+ * carries `links`, one per reference.
+ * @typedef {import('../../foundation/doc-compiler/links.mjs').DocLink} DocLink
+ */
+
+/**
+ * One move: a whole `astryx docs` command a reader can run as is.
+ * @typedef {'astryx docs' | `astryx docs ${string}`} DocsCommand
+ */
+
+/**
+ * The moves a docs read offers (spec:AST-047). Every read but the topic list
+ * carries them.
+ * @typedef {object} DocsLinks
+ * @property {DocsCommand} up opens the level the read sits in: a section's
+ * topic index, a node's parent namespace, or the topic list
+ * @property {DocsCommand} [previous] opens the item before it at its level: the
+ * previous section of its topic, or the previous node in its parent's slot
+ * @property {DocsCommand} [next] opens the item after it at its level
+ * @property {DocsCommand[]} [related] opens each doc a typed doc names: a
+ * function's command, a command's function, and the docs it lists as
+ * related
*/
/**
@@ -52,6 +95,7 @@
* @property {string} title
* @property {string} description
* @property {DocsIndexSection[]} sections
+ * @property {DocsLinks} links the moves from the index
*/
/**
@@ -66,7 +110,61 @@
* astryx --json docs <topic> <section>
* @typedef {object} DocsDetailSectionResponse
* @property {'docs.detail.section'} type
- * @property {import('@astryxdesign/cli/authoring').ReferenceSection} data
+ * @property {import('@astryxdesign/cli/authoring').ReferenceSection & {links: DocsLinks}} data
+ * the section, and the moves from it: up to its topic's index, and across to
+ * the sections before and after it
+ */
+
+/**
+ * astryx --json docs <route>, for a namespace or a typed doc in the docs tree
+ * @typedef {object} DocsNodeResponse
+ * @property {'docs.node'} type
+ * @property {DocsNode} data
+ */
+
+/**
+ * One node of the docs tree.
+ * @typedef {object} DocsNode
+ * @property {string | null} id the doc's DocId, built from its provider's
+ * ProviderId, kind, and name (see the provider-identity authoring doc);
+ * unchanged when the node moves. Always present; null on a generated level,
+ * such as `cli/api/functions`, which has no authored doc
+ * @property {string} route pass it to `astryx docs`
+ * @property {string} kind `namespace`, or the typed doc's kind: `command`,
+ * `function`, `schema`, or `enum`
+ * @property {string} package the package that owns the node
+ * @property {string} title
+ * @property {string} summary
+ * @property {DocsNodeLink[]} breadcrumb the namespaces above it, top first
+ * @property {DocsNodeSlot[]} slots a namespace's slots that hold children, in
+ * order; empty for a typed doc
+ * @property {import('@astryxdesign/cli/authoring').ReferenceContentBlock[]} content
+ * a typed doc's content; empty for a namespace
+ * @property {DocsLinks} links the moves from the node: up to its parent (the
+ * topic list, for a top-level namespace), and across to its neighbors in its
+ * parent's slot
+ */
+
+/**
+ * @typedef {object} DocsNodeLink
+ * @property {string} route
+ * @property {string} title
+ */
+
+/**
+ * @typedef {object} DocsNodeSlot
+ * @property {string} name the slot's key in its namespace
+ * @property {string} title
+ * @property {DocsNodeChild[]} children in reading order
+ */
+
+/**
+ * @typedef {object} DocsNodeChild
+ * @property {string} route pass it to `astryx docs` to go one level down
+ * @property {string} name the last segment of its route
+ * @property {string} kind
+ * @property {string} title
+ * @property {string} summary
*/
/**
diff --git a/packages/cli/api/docs/index/index.mjs b/packages/cli/api/docs/index/index.mjs
index c56b5181a3..26b6a407f8 100644
--- a/packages/cli/api/docs/index/index.mjs
+++ b/packages/cli/api/docs/index/index.mjs
@@ -15,7 +15,7 @@
*/
import {indexView} from '../../../foundation/doc-compiler/lenses.mjs';
-import {resolveTopicDocs} from '../_adapter.mjs';
+import {resolveTopicDocs, topicLinks} from '../_adapter.mjs';
/**
* @param {string} topic
@@ -27,6 +27,14 @@ import {resolveTopicDocs} from '../_adapter.mjs';
* @returns {Promise<import('../docs.type.mjs').DocsIndexResponse>}
*/
export async function index(topic, options = {}) {
- const {node} = await resolveTopicDocs(topic, options);
- return {type: 'docs.index', data: indexView(node)};
+ const {node, entry, catalog} = await resolveTopicDocs(topic, options);
+ const view = indexView(node);
+ /** @type {import('../docs.type.mjs').DocsIndex} */
+ const data = {
+ ...view,
+ // A guide the docs tree places is read by its route, not its doc name.
+ name: entry.tree ? entry.name : view.name,
+ links: await topicLinks(catalog, entry),
+ };
+ return {type: 'docs.index', data};
}
diff --git a/packages/cli/api/docs/index/index.test.mjs b/packages/cli/api/docs/index/index.test.mjs
index a721a3087d..dcc17be134 100644
--- a/packages/cli/api/docs/index/index.test.mjs
+++ b/packages/cli/api/docs/index/index.test.mjs
@@ -49,7 +49,7 @@ describe('docs.index leaf', () => {
});
describe('docs() topic reads', () => {
- it('returns the whole topic by default, as before', async () => {
+ it('returns the whole topic by default', async () => {
const res = await docs('theme');
expect(res.type).toBe('docs.detail');
expect(res.data.sections[0].content.length).toBeGreaterThan(0);
diff --git a/packages/cli/api/docs/integration-tree.test.mjs b/packages/cli/api/docs/integration-tree.test.mjs
new file mode 100644
index 0000000000..620e172cd3
--- /dev/null
+++ b/packages/cli/api/docs/integration-tree.test.mjs
@@ -0,0 +1,547 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Integration docs in the docs tree (spec:AST-046, spec:AST-047): an
+ * integration's namespace docs and placed guides join the CLI's tree with the
+ * same moves, links, search, and doctor checks, named by its provider id.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {docs} from './docs.mjs';
+import {loadDocsCatalog} from './_adapter.mjs';
+import {search} from '../search/search.mjs';
+import {checkDocsTree} from '../doctor/doctor.mjs';
+import {integrationDocConflicts} from '../integration/authoring-checks.mjs';
+
+const SLOW = 60_000;
+
+/** @type {string} */
+let tmpDir;
+
+const NAMESPACE = {
+ type: 'namespace',
+ name: 'acme',
+ title: 'Acme',
+ summary: 'Everything about the Acme kit.',
+ slots: {guides: {title: 'Guides', accepts: {kinds: ['generic']}}},
+};
+
+/**
+ * A guide placed in the acme namespace.
+ * @param {string} name
+ * @param {object} [fields]
+ */
+function guide(name, fields = {}) {
+ return {
+ type: 'generic',
+ name,
+ title: `Acme ${name}`,
+ description: `How to ${name} the Acme kit.`,
+ placement: {parent: 'namespace:acme', slot: 'guides'},
+ sections: [
+ {title: 'Overview', content: [{type: 'prose', text: `Do ${name}.`}]},
+ ],
+ ...fields,
+ };
+}
+
+/** The docs of a small integration: a namespace, two guides, and a topic. */
+function kit() {
+ return {
+ 'acme.doc.mjs': NAMESPACE,
+ 'setup.doc.mjs': guide('setup', {
+ placement: {parent: 'namespace:acme', slot: 'guides', order: 1},
+ sections: [
+ {
+ title: 'Install',
+ content: [
+ {
+ type: 'prose',
+ text: 'Frobnicate the kit, then check it with {@link @astryxdesign/cli:command:doctor}.',
+ },
+ {type: 'prose', text: 'Next: {@link generic:deploy}.'},
+ ],
+ },
+ {
+ title: 'Configure',
+ content: [{type: 'prose', text: 'Add it to astryx.config.'}],
+ },
+ ],
+ }),
+ 'deploy.doc.mjs': guide('deploy', {
+ placement: {parent: 'namespace:acme', slot: 'guides', order: 2},
+ }),
+ 'notes.doc.mjs': {
+ type: 'generic',
+ name: 'acme-notes',
+ title: 'Acme notes',
+ description: 'Notes about the kit.',
+ sections: [
+ {
+ title: 'Start',
+ content: [{type: 'prose', text: 'Start at {@link generic:setup}.'}],
+ },
+ ],
+ },
+ };
+}
+
+/** A guide whose only link names no doc. */
+const broken = () =>
+ guide('broken', {
+ sections: [
+ {
+ title: 'Overview',
+ content: [{type: 'prose', text: 'See {@link generic:nope}.'}],
+ },
+ ],
+ });
+
+/**
+ * A consumer project that configures `@acme/kit`, whose manifest names a
+ * provider id that differs from its package name.
+ * @param {Record<string, object>} files
+ */
+function scaffold(files) {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ "export default {integrations: ['@acme/kit']};\n",
+ );
+ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'kit');
+ fs.mkdirSync(path.join(pkgDir, 'docs'), {recursive: true});
+ fs.writeFileSync(
+ path.join(pkgDir, 'package.json'),
+ JSON.stringify({name: '@acme/kit', version: '1.0.0'}),
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'astryx.integration.mjs'),
+ "export default {docs: './docs', providerId: '@acme/tree-provider'};\n",
+ );
+ for (const [file, doc] of Object.entries(files)) {
+ fs.writeFileSync(
+ path.join(pkgDir, 'docs', file),
+ `export const docs = ${JSON.stringify(doc, null, 2)};\n`,
+ );
+ }
+}
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(
+ path.join(process.cwd(), '.astryx-integration-tree-test-'),
+ );
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('integration docs in the docs tree', () => {
+ it('names a package whose docs did not load, instead of dropping them silently', async () => {
+ scaffold({
+ ...kit(),
+ 'broken.doc.mjs': {
+ type: 'generic',
+ name: 'broken',
+ title: 'Broken',
+ description: 'A topic whose block no topic may hold.',
+ sections: [
+ {title: 'Only', content: [{type: 'reference', target: 'generic:setup'}]},
+ ],
+ },
+ });
+ const listed = await docs(undefined, undefined, {cwd: tmpDir});
+ expect(listed.meta?.notLoaded).toEqual([
+ expect.objectContaining({package: '@acme/kit', message: expect.any(String)}),
+ ]);
+ }, 60_000);
+
+ it('lists an integration namespace beside the CLI, named by its provider id', async () => {
+ scaffold(kit());
+ const listed = await docs(undefined, undefined, {cwd: tmpDir});
+ expect(listed.meta.namespaces).toContainEqual({
+ topic: 'acme',
+ description: 'Everything about the Acme kit.',
+ package: '@acme/kit',
+ });
+ const top = await docs('acme', undefined, {cwd: tmpDir});
+ expect(top.type).toBe('docs.node');
+ expect(top.data).toMatchObject({
+ id: 'astryx:artifact:v1/%40acme%2Ftree-provider/namespace/acme',
+ package: '@acme/kit',
+ links: {up: 'astryx docs'},
+ });
+ expect(
+ top.data.slots[0].children.map((/** @type {any} */ c) => c.route),
+ ).toEqual(['acme/setup', 'acme/deploy']);
+ }, SLOW);
+
+ it('reads a placed guide one level at a time, with its links resolved', async () => {
+ scaffold(kit());
+ const index = await docs('acme/setup', undefined, {cwd: tmpDir, index: true});
+ expect(index.type).toBe('docs.index');
+ expect(index.data.links.up).toBe('astryx docs acme');
+ const install = await docs('acme/setup', 'install', {cwd: tmpDir});
+ const [prose, next] = install.data.content;
+ expect(prose.text).toBe(
+ 'Frobnicate the kit, then check it with `astryx docs cli/commands/doctor`.',
+ );
+ expect(next.text).toBe('Next: `astryx docs acme/deploy`.');
+ const notes = await docs('acme-notes', undefined, {cwd: tmpDir});
+ expect(notes.data.sections[0].content[0].text).toBe(
+ 'Start at `astryx docs acme/setup`.',
+ );
+ }, SLOW);
+
+ it('finds a section of the guide by search, with its package and parent', async () => {
+ scaffold(kit());
+ const {data} = await search('frobnicate', {cwd: tmpDir, type: 'doc'});
+ expect(data.results[0]).toMatchObject({
+ name: 'acme/setup',
+ section: 'install',
+ command: 'astryx docs acme/setup install',
+ parent: 'astryx docs acme/setup --index',
+ package: '@acme/kit',
+ });
+ }, SLOW);
+
+ it('passes doctor, and warns on a link that names no doc', async () => {
+ scaffold(kit());
+ const ok = await checkDocsTree({
+ docsCatalog: await loadDocsCatalog(tmpDir),
+ });
+ expect(ok).toMatchObject({id: 'docs-tree', status: 'pass'});
+ scaffold({...kit(), 'broken.doc.mjs': broken()});
+ const bad = await checkDocsTree({
+ docsCatalog: await loadDocsCatalog(tmpDir),
+ });
+ expect(bad.status).toBe('warn');
+ expect(bad.message).toContain('acme/broken');
+ expect(bad.message).toContain('"generic:nope" names no doc');
+ }, SLOW);
+
+ it("keeps the CLI's routes: an integration namespace or topic that claims one is withdrawn, and both doctors say so", async () => {
+ const flat = (/** @type {string} */ name) => ({
+ type: 'generic',
+ name,
+ title: `Acme ${name}`,
+ description: `Acme's ${name} notes.`,
+ sections: [
+ {title: 'One', content: [{type: 'prose', text: 'One.'}]},
+ {title: 'Two', content: [{type: 'prose', text: 'Two.'}]},
+ ],
+ });
+ scaffold({
+ ...kit(),
+ 'unorganized.doc.mjs': {...NAMESPACE, name: 'unorganized', title: 'Mine', summary: 'Mine.'},
+ 'tokens.doc.mjs': {...NAMESPACE, name: 'tokens', title: 'Acme tokens', summary: 'Acme tokens.'},
+ 'cli.doc.mjs': flat('cli'),
+ });
+ const listed = await docs(undefined, undefined, {cwd: tmpDir});
+ expect(listed.meta.namespaces).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({topic: 'cli', package: '@astryxdesign/cli'}),
+ expect.objectContaining({topic: 'unorganized', package: '@astryxdesign/cli'}),
+ ]),
+ );
+ expect(listed.meta.namespaces.filter(n => ['tokens', 'unorganized'].includes(n.topic) && n.package === '@acme/kit')).toEqual([]);
+ expect(listed.data.map(entry => entry.topic)).not.toContain('cli');
+ // Each name opens the CLI's doc, and a CLI topic keeps its home.
+ expect((await docs('cli', undefined, {cwd: tmpDir})).data).toMatchObject({route: 'cli', package: '@astryxdesign/cli'});
+ expect((await docs('unorganized', undefined, {cwd: tmpDir})).data).toMatchObject({route: 'unorganized', package: '@astryxdesign/cli'});
+ const tokens = await docs('tokens', undefined, {cwd: tmpDir});
+ expect(tokens.type).toBe('docs.detail');
+ expect(tokens.data.links.up).toBe('astryx docs unorganized');
+ // The project doctor and the package doctor both name the claims.
+ const check = await checkDocsTree({docsCatalog: await loadDocsCatalog(tmpDir)});
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('takes the route "unorganized", which the CLI\'s own docs keep');
+ expect(check.message).toContain('takes the route "tokens"');
+ expect(check.message).toContain('both have the route "cli"');
+ const result = await integrationDocConflicts('@acme/kit', {cwd: tmpDir});
+ const graph = result.data.issues.filter(issue => issue.code === 'invalid_doc_graph').map(issue => issue.message).join('\n');
+ expect(graph).toContain('takes the route "unorganized"');
+ expect(graph).toContain('takes the route "tokens"');
+ expect(graph).toContain('route "cli"');
+ }, SLOW);
+
+ it("keeps the CLI's routes from a claim that differs only in case", async () => {
+ const flat = (/** @type {string} */ name) => ({
+ type: 'generic',
+ name,
+ title: `Acme ${name}`,
+ description: `Acme's ${name} notes.`,
+ sections: [
+ {title: 'One', content: [{type: 'prose', text: 'One.'}]},
+ {title: 'Two', content: [{type: 'prose', text: 'Two.'}]},
+ ],
+ });
+ scaffold({...kit(), 'caps-cli.doc.mjs': flat('CLI')});
+ // Another spelling, in a nested folder of the package's docs.
+ const nested = path.join(tmpDir, 'node_modules', '@acme', 'kit', 'docs', 'nested');
+ fs.mkdirSync(nested, {recursive: true});
+ fs.writeFileSync(
+ path.join(nested, 'caps-unorganized.doc.mjs'),
+ `export const docs = ${JSON.stringify(flat('Unorganized'), null, 2)};\n`,
+ );
+ fs.writeFileSync(
+ path.join(nested, 'caps-tokens.doc.mjs'),
+ `export const docs = ${JSON.stringify(flat('TOKENS'), null, 2)};\n`,
+ );
+ expect((await docs('cli', undefined, {cwd: tmpDir})).data).toMatchObject({route: 'cli', package: '@astryxdesign/cli'});
+ expect((await docs('unorganized', undefined, {cwd: tmpDir})).data).toMatchObject({route: 'unorganized', package: '@astryxdesign/cli'});
+ expect((await docs('theme', undefined, {cwd: tmpDir, index: true})).data.links.up).toBe('astryx docs unorganized');
+ const listed = await docs(undefined, undefined, {cwd: tmpDir});
+ expect(listed.data.map(entry => entry.topic.toLowerCase())).not.toContain('cli');
+ // Search does not offer a topic whose route another doc owns.
+ const found = await search("Acme's CLI notes", {cwd: tmpDir, type: 'doc', limit: 20});
+ expect(
+ found.data.results.filter(hit => hit.package === '@acme/kit' && /^cli$/i.test(hit.name)),
+ ).toEqual([]);
+ const check = await checkDocsTree({docsCatalog: await loadDocsCatalog(tmpDir)});
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('route "CLI"');
+ expect(check.message).toContain('takes the route "Unorganized"');
+ // `TOKENS` is the CLI's topic `tokens` in another spelling: the CLI's wins.
+ const tokens = await docs('TOKENS', undefined, {cwd: tmpDir, index: true});
+ expect(tokens.data).toMatchObject({name: 'tokens', links: {up: 'astryx docs unorganized'}});
+ expect(tokens.data.title).not.toBe('Acme TOKENS');
+ const result = await integrationDocConflicts('@acme/kit', {cwd: tmpDir});
+ const graph = result.data.issues
+ .filter(issue => issue.code === 'invalid_doc_graph')
+ .map(issue => issue.message)
+ .join('\n');
+ expect(graph).toContain('route "CLI"');
+ expect(graph).toContain('takes the route "Unorganized"');
+ }, SLOW);
+
+ it("keeps a replaced name for the topic that replaces it, over another integration's namespace", async () => {
+ scaffold({...kit(), 'tokens-ns.doc.mjs': {...NAMESPACE, name: 'tokens', title: 'Kit tokens', summary: 'Kit tokens.'}});
+ const two = path.join(tmpDir, 'node_modules', '@acme', 'two');
+ fs.mkdirSync(path.join(two, 'docs'), {recursive: true});
+ fs.writeFileSync(path.join(two, 'package.json'), JSON.stringify({name: '@acme/two', version: '1.0.0'}));
+ fs.writeFileSync(path.join(two, 'astryx.integration.mjs'), "export default {docs: './docs'};\n");
+ fs.writeFileSync(
+ path.join(two, 'docs', 'acme-tokens.doc.mjs'),
+ `export const docs = ${JSON.stringify({
+ type: 'generic',
+ name: 'acme-tokens',
+ title: 'Acme tokens',
+ description: 'Acme tokens.',
+ replaces: 'tokens',
+ sections: [{title: 'One', content: [{type: 'prose', text: 'One.'}]}],
+ }, null, 2)};\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ "export default {integrations: ['@acme/kit', '@acme/two']};\n",
+ );
+ const listed = await docs(undefined, undefined, {cwd: tmpDir});
+ expect(listed.meta.namespaces.map(entry => entry.topic)).not.toContain('tokens');
+ const read = await docs('tokens', undefined, {cwd: tmpDir, index: true});
+ expect(read.data.name).toBe('acme-tokens');
+ const check = await checkDocsTree({docsCatalog: await loadDocsCatalog(tmpDir)});
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('which the topic "acme-tokens" also answers to');
+ }, SLOW);
+
+ it('keeps every name a topic replaced twice answers to, and the CLI\'s links to it still open', async () => {
+ scaffold({...kit(), 'tokens-ns.doc.mjs': {...NAMESPACE, name: 'tokens', title: 'Kit tokens', summary: 'Kit tokens.'}});
+ /** @param {string} pkg @param {string} name @param {string} replaces */
+ const replacement = (pkg, name, replaces) => {
+ const dir = path.join(tmpDir, 'node_modules', '@acme', pkg);
+ fs.mkdirSync(path.join(dir, 'docs'), {recursive: true});
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({name: `@acme/${pkg}`, version: '1.0.0'}));
+ fs.writeFileSync(path.join(dir, 'astryx.integration.mjs'), "export default {docs: './docs'};\n");
+ fs.writeFileSync(
+ path.join(dir, 'docs', `${name}.doc.mjs`),
+ `export const docs = ${JSON.stringify({
+ type: 'generic',
+ name,
+ title: `Tokens by ${pkg}`,
+ description: `Tokens by ${pkg}.`,
+ replaces,
+ sections: [{title: 'One', content: [{type: 'prose', text: 'One.'}]}],
+ }, null, 2)};\n`,
+ );
+ };
+ replacement('two', 'acme-tokens', 'tokens');
+ replacement('three', 'b-tokens', 'tokens');
+ replacement('four', 'super-tokens', 'b-tokens');
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ "export default {integrations: ['@acme/kit', '@acme/two', '@acme/three', '@acme/four']};\n",
+ );
+ const listed = await docs(undefined, undefined, {cwd: tmpDir});
+ expect(listed.meta.namespaces.map(entry => entry.topic)).not.toContain('tokens');
+ for (const name of ['tokens', 'acme-tokens', 'b-tokens', 'super-tokens']) {
+ expect((await docs(name, undefined, {cwd: tmpDir, index: true})).data.name).toBe('super-tokens');
+ }
+ // A walk over every topic: the CLI's own links to `tokens` still open it.
+ /** @type {string[]} */
+ const raw = [];
+ for (const entry of listed.data) {
+ const read = await docs(entry.topic, undefined, {cwd: tmpDir});
+ if (/\{@link [^}]*tokens\}/.test(JSON.stringify(read.data))) raw.push(entry.topic);
+ }
+ expect(raw).toEqual([]);
+ const principles = await docs('principles', undefined, {cwd: tmpDir});
+ expect(JSON.stringify(principles.data)).toContain('astryx docs super-tokens');
+ const check = await checkDocsTree({docsCatalog: await loadDocsCatalog(tmpDir)});
+ expect(check.message).toContain('takes the route "tokens", which the topic "super-tokens" also answers to');
+ expect(check.message).not.toContain('names no doc');
+ }, SLOW);
+
+ it("keeps the CLI's routes from a replacement that answers to one, in one package or across a chain", async () => {
+ const flat = (/** @type {string} */ name, /** @type {object} */ extra = {}) => ({
+ type: 'generic',
+ name,
+ title: `Acme ${name}`,
+ description: `Acme's ${name} notes.`,
+ sections: [
+ {title: 'One', content: [{type: 'prose', text: 'One.'}]},
+ {title: 'Two', content: [{type: 'prose', text: 'Two.'}]},
+ ],
+ ...extra,
+ });
+ scaffold({
+ ...kit(),
+ 'a-cli.doc.mjs': flat('cli'),
+ 'a-unorganized.doc.mjs': flat('Unorganized'),
+ 'z-b2.doc.mjs': flat('b2', {replaces: 'cli'}),
+ 'z-u2.doc.mjs': flat('u2', {replaces: 'Unorganized'}),
+ });
+ // Another package carries the chain on: c3 replaces b2, which replaced cli.
+ const three = path.join(tmpDir, 'node_modules', '@acme', 'three');
+ fs.mkdirSync(path.join(three, 'docs'), {recursive: true});
+ fs.writeFileSync(path.join(three, 'package.json'), JSON.stringify({name: '@acme/three', version: '1.0.0'}));
+ fs.writeFileSync(path.join(three, 'astryx.integration.mjs'), "export default {docs: './docs'};\n");
+ fs.writeFileSync(
+ path.join(three, 'docs', 'c3.doc.mjs'),
+ `export const docs = ${JSON.stringify(flat('c3', {replaces: 'b2'}), null, 2)};\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ "export default {integrations: ['@acme/kit', '@acme/three']};\n",
+ );
+ for (const name of ['cli', 'CLI']) {
+ expect((await docs(name, undefined, {cwd: tmpDir})).data).toMatchObject({route: 'cli', package: '@astryxdesign/cli'});
+ }
+ for (const name of ['unorganized', 'UNORGANIZED']) {
+ expect((await docs(name, undefined, {cwd: tmpDir})).data).toMatchObject({route: 'unorganized', package: '@astryxdesign/cli'});
+ }
+ // The replacement still answers to its own names.
+ for (const name of ['b2', 'c3']) {
+ expect((await docs(name, undefined, {cwd: tmpDir, index: true})).data.name).toBe('c3');
+ }
+ const listed = await docs(undefined, undefined, {cwd: tmpDir});
+ for (const entry of listed.data) {
+ const read = await docs(entry.topic, undefined, {cwd: tmpDir});
+ expect(read.type).toBe('docs.detail');
+ expect(read.data.name).toBe(entry.topic);
+ }
+ const check = await checkDocsTree({docsCatalog: await loadDocsCatalog(tmpDir)});
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('The topic "c3" answers to "cli" through replaces');
+ expect(check.message).toContain('The topic "u2" answers to "unorganized" through replaces');
+ const inPackage = await integrationDocConflicts('@acme/kit', {cwd: tmpDir});
+ const graph = inPackage.data.issues
+ .filter(issue => issue.code === 'invalid_doc_graph')
+ .map(issue => issue.message)
+ .join('\n');
+ expect(graph).toContain('answers to "cli" through replaces');
+ }, SLOW);
+
+ it('runs the same checks inside the package: doctor integration docs', async () => {
+ scaffold({...kit(), 'broken.doc.mjs': broken()});
+ const result = await integrationDocConflicts('@acme/kit', {cwd: tmpDir});
+ expect(result.data.issues).toContainEqual(
+ expect.objectContaining({
+ code: 'invalid_doc_graph',
+ severity: 'warning',
+ message: expect.stringContaining('"generic:nope" names no doc'),
+ }),
+ );
+ }, SLOW);
+
+ it("resolves an extension's links against the extension's provider, not the base topic's", async () => {
+ scaffold({
+ ...kit(),
+ 'integrations.doc.mjs': guide('integrations'),
+ 'theme-acme.doc.mjs': {
+ type: 'generic',
+ name: 'theme-acme',
+ title: 'Acme theming',
+ description: 'Acme notes on theming.',
+ extends: 'theme',
+ sections: [
+ {
+ title: 'Acme theming notes',
+ content: [
+ {
+ type: 'prose',
+ text: 'See {@link generic:integrations}, and {@link @astryxdesign/cli:generic:tokens} for the tokens.',
+ },
+ ],
+ },
+ ],
+ },
+ });
+ const {data} = await docs('theme', 'acme-theming-notes', {cwd: tmpDir});
+ // `generic:integrations` is the extension's own guide, never the CLI's
+ // `cli/integrations`; a provider-qualified link reaches the CLI's topic.
+ expect(data.content[0].text).toBe(
+ 'See `astryx docs acme/integrations`, and `astryx docs tokens` for the tokens.',
+ );
+ // The CLI's own sections of the topic still resolve against the CLI.
+ const full = await docs('theme', undefined, {cwd: tmpDir});
+ expect(JSON.stringify(full.data)).not.toContain('{@link');
+ }, SLOW);
+
+ it("warns, in the project and in the package, on an extension link that names no doc of its provider", async () => {
+ scaffold({
+ ...kit(),
+ 'theme-acme.doc.mjs': {
+ type: 'generic',
+ name: 'theme-acme',
+ title: 'Acme theming',
+ description: 'Acme notes on theming.',
+ extends: 'theme',
+ sections: [
+ {
+ title: 'Acme theming notes',
+ content: [{type: 'prose', text: 'See {@link generic:tokens}.'}],
+ },
+ ],
+ },
+ });
+ const check = await checkDocsTree({
+ docsCatalog: await loadDocsCatalog(tmpDir),
+ });
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('"generic:tokens" names no doc');
+ const result = await integrationDocConflicts('@acme/kit', {cwd: tmpDir});
+ expect(result.data.issues).toContainEqual(
+ expect.objectContaining({
+ code: 'invalid_doc_graph',
+ message: expect.stringContaining('"generic:tokens" names no doc'),
+ }),
+ );
+ }, SLOW);
+
+ it('keeps the CLI route when an integration claims it, and names the claim', async () => {
+ scaffold({'cli.doc.mjs': {...NAMESPACE, name: 'cli', title: 'Not the CLI'}});
+ const top = await docs('cli', undefined, {cwd: tmpDir});
+ expect(top.data.package).toBe('@astryxdesign/cli');
+ const check = await checkDocsTree({
+ docsCatalog: await loadDocsCatalog(tmpDir),
+ });
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('both have the route "cli"');
+ }, SLOW);
+});
diff --git a/packages/cli/api/docs/integrationDocs.test.mjs b/packages/cli/api/docs/integrationDocs.test.mjs
index 4d9fc759f3..d8a633f450 100644
--- a/packages/cli/api/docs/integrationDocs.test.mjs
+++ b/packages/cli/api/docs/integrationDocs.test.mjs
@@ -102,7 +102,7 @@ describe('integration-contributed topics', () => {
// The built-in topics keep their own owner.
expect(listed.data.find(t => t.topic === 'tokens').package).toBe('@astryxdesign/cli');
- const detail = await docs('deploying', undefined, {cwd: tmpDir});
+ const detail = await docs('deploying', undefined, {cwd: tmpDir, full: true});
expect(detail.type).toBe('docs.detail');
expect(detail.data.sections[0].content[0].text).toBe('Push the button.');
@@ -129,7 +129,7 @@ describe('integration-contributed topics', () => {
}),
});
- const detail = await docs('getting-started', undefined, {cwd: tmpDir});
+ const detail = await docs('getting-started', undefined, {cwd: tmpDir, full: true});
expect(detail.data.sections.map(s => s.title)).toEqual(['Install']);
expect(detail.data.sections[0].content[0].text).toBe('yarn add @acme/widgets');
@@ -146,14 +146,14 @@ describe('integration-contributed topics', () => {
scaffold({
'setup.doc.mjs': topic({name: 'setup', replaces: 'getting-started'}),
});
- const byOldName = await docs('getting-started', undefined, {cwd: tmpDir});
- const byNewName = await docs('setup', undefined, {cwd: tmpDir});
+ const byOldName = await docs('getting-started', undefined, {cwd: tmpDir, full: true});
+ const byNewName = await docs('setup', undefined, {cwd: tmpDir, full: true});
expect(byOldName.data.name).toBe('setup');
expect(byNewName.data.name).toBe('setup');
}, SLOW);
it('merges an extension into the topic it extends', async () => {
- const builtin = await docs('theme');
+ const builtin = await docs('theme', undefined, {full: true});
const baseSectionTitle = builtin.data.sections[0].title;
scaffold({
'theme-internal.doc.mjs': topic({
@@ -166,7 +166,7 @@ describe('integration-contributed topics', () => {
}),
});
- const extended = await docs('theme', undefined, {cwd: tmpDir});
+ const extended = await docs('theme', undefined, {cwd: tmpDir, full: true});
// The extension is not a topic of its own.
expect((await docs(undefined, undefined, {cwd: tmpDir})).data.some(
t => t.topic === 'theme-internal',
@@ -178,7 +178,7 @@ describe('integration-contributed topics', () => {
}, SLOW);
it('migrates a real built-in section to a stable ID without duplicating it', async () => {
- const builtin = await docs('theme');
+ const builtin = await docs('theme', undefined, {full: true});
// Readers see a key on every section; the migration case is one whose
// source authors no id.
const {docs: authored} = await import('../../assets/docs/theme.doc.mjs');
@@ -198,7 +198,7 @@ describe('integration-contributed topics', () => {
}),
});
- const extended = await docs('theme', undefined, {cwd: tmpDir});
+ const extended = await docs('theme', undefined, {cwd: tmpDir, full: true});
expect(extended.data.sections).toHaveLength(builtin.data.sections.length);
const matches = extended.data.sections.filter(
section => section.title === target.title,
@@ -228,7 +228,7 @@ describe('integration-contributed topics', () => {
}),
});
- const extended = await docs('theme', undefined, {cwd: tmpDir});
+ const extended = await docs('theme', undefined, {cwd: tmpDir, full: true});
expect(extended.data.sections).toHaveLength(index.data.sections.length);
expect(extended.data.sections.filter(s => s.id === target.id)).toEqual([
expect.objectContaining({content: [{type: 'prose', text: 'Acme first.'}]}),
@@ -240,7 +240,7 @@ describe('integration-contributed topics', () => {
it.each(['zh', 'dense'])(
'replaces translated real sections by their authored titles under --%s',
async lang => {
- const english = await docs('theme');
+ const english = await docs('theme', undefined, {full: true});
const englishTitles = english.data.sections.map(section => section.title);
expect(englishTitles).toEqual(
expect.arrayContaining(['Quick Start', 'Theme Props']),
@@ -263,11 +263,11 @@ describe('integration-contributed topics', () => {
}),
});
- const base = await docs('theme', undefined, {lang});
+ const base = await docs('theme', undefined, {lang, full: true});
expect(base.data.sections.map(section => section.title)).not.toEqual(
englishTitles,
);
- const extended = await docs('theme', undefined, {cwd: tmpDir, lang});
+ const extended = await docs('theme', undefined, {cwd: tmpDir, lang, full: true});
expect(extended.data.sections).toHaveLength(base.data.sections.length);
expect(
extended.data.sections.filter(
@@ -285,11 +285,11 @@ describe('integration-contributed topics', () => {
it('offers the contributed topics as suggestions on an unknown one', async () => {
scaffold({'deploying.doc.mjs': topic()});
- await expect(docs('nope-not-a-topic', undefined, {cwd: tmpDir})).rejects.toBeInstanceOf(
+ await expect(docs('nope-not-a-topic', undefined, {cwd: tmpDir, full: true})).rejects.toBeInstanceOf(
AstryxError,
);
try {
- await docs('nope-not-a-topic', undefined, {cwd: tmpDir});
+ await docs('nope-not-a-topic', undefined, {cwd: tmpDir, full: true});
} catch (err) {
expect(err.suggestions.map(s => s.name)).toContain('deploying');
}
diff --git a/packages/cli/api/docs/list/list.mjs b/packages/cli/api/docs/list/list.mjs
index 9a1fb62867..b689de9ce4 100644
--- a/packages/cli/api/docs/list/list.mjs
+++ b/packages/cli/api/docs/list/list.mjs
@@ -8,14 +8,14 @@
* English `description` is read from its file; a contributed topic already
* carries the one discovery read. The listing never applies --dense/--zh
* overlays.
- * @output { type: 'docs.list', data: DocsListEntry[] } — one entry per topic in
- * read order, each naming the package that owns it, matching
- * `astryx --json docs`.
+ * @output { type: 'docs.list', data: DocsListEntry[] } — one entry per topic
+ * in read order, then one per top-level docs-tree namespace, each naming the
+ * package that owns it, matching `astryx --json docs`.
* @position Leaf under api/docs. Sibling of detail; both share _adapter.mjs.
*/
import {loadTopicFile} from '../../../foundation/doc-compiler/read.mjs';
-import {loadDocsCatalog} from '../_adapter.mjs';
+import {holdsOwnName, loadDocsCatalog, projectTree} from '../_adapter.mjs';
/**
* @param {object} [options]
@@ -24,9 +24,13 @@ import {loadDocsCatalog} from '../_adapter.mjs';
*/
export async function list({cwd} = {}) {
const catalog = await loadDocsCatalog(cwd);
+ const tree = await projectTree(catalog);
/** @type {Array<import('../docs.type.mjs').DocsListEntry>} */
const entries = [];
for (const entry of catalog.entries()) {
+ // A topic whose name opens another doc is not listed (spec:AST-046
+ // FR11); `astryx doctor` names the clash.
+ if (!holdsOwnName(tree, catalog, entry)) continue;
let description = entry.description ?? '';
if (entry.description == null) {
const file = await loadTopicFile(entry.path, null);
@@ -41,5 +45,21 @@ export async function list({cwd} = {}) {
if (entry.replaces != null) listed.replaces = entry.replaces;
entries.push(listed);
}
- return {type: 'docs.list', data: entries};
+ // The docs tree's top-level namespaces, the CLI's and each integration's,
+ // each the way into a whole branch (spec:AST-046 FR7). They go in `meta`,
+ // so `data` stays the topic list 0.6 returned: every entry reads as a topic.
+ const namespaces = tree.roots().map(root => ({
+ topic: root.route,
+ description: root.summary,
+ package: root.provider,
+ }));
+ /** @type {NonNullable<import('../docs.type.mjs').DocsListResponse['meta']>} */
+ const meta = {};
+ if (namespaces.length > 0) meta.namespaces = namespaces;
+ // A package whose docs did not load is named, so its author knows why its
+ // topics are missing.
+ if (catalog.issues.length > 0) meta.notLoaded = [...catalog.issues];
+ return Object.keys(meta).length === 0
+ ? {type: 'docs.list', data: entries}
+ : {type: 'docs.list', data: entries, meta};
}
diff --git a/packages/cli/api/docs/node/node.mjs b/packages/cli/api/docs/node/node.mjs
new file mode 100644
index 0000000000..0a6ec9041a
--- /dev/null
+++ b/packages/cli/api/docs/node/node.mjs
@@ -0,0 +1,192 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file docs.node leaf — one namespace or typed doc in the docs tree.
+ *
+ * @input A route the docs tree resolves: a namespace such as `cli/api`, or a
+ * typed doc such as `cli/api/functions/search`, plus {cwd}.
+ * @output { type: 'docs.node', data: DocsNode } — the node's identity, title
+ * and summary, the namespaces above it, and either its slots with their
+ * children (a namespace) or its content (a typed doc). A namespace never
+ * lists its grandchildren, so a reader goes down one level at a time.
+ * Matches `astryx --json docs <route>`.
+ * @position Leaf under api/docs, beside the topic leaves. A guide the tree
+ * places is a topic: the detail leaf reads it by its route.
+ */
+
+import {
+ nodeContent,
+ placeLinks,
+ resolveDocsArgument,
+ unknownTopicError,
+} from '../_adapter.mjs';
+
+/**
+ * @typedef {import('../../../foundation/doc-compiler/tree.mjs').DocsTree} DocsTree
+ * @typedef {import('../../../foundation/doc-compiler/tree.mjs').TreeNode} TreeNode
+ */
+
+/**
+ * The docs.node view of one tree node.
+ * @param {import('../../../foundation/discovery/docs-discovery.mjs').DocsCatalog} catalog
+ * @param {DocsTree} tree
+ * @param {TreeNode} node
+ * @returns {Promise<import('../docs.type.mjs').DocsNode>}
+ */
+export async function nodeView(catalog, tree, node) {
+ const {content} = await nodeContent(catalog, tree, node);
+ return {
+ id: node.id,
+ route: node.route,
+ kind: node.kind,
+ package: node.provider,
+ title: node.title,
+ summary: node.summary,
+ breadcrumb: tree
+ .ancestors(node)
+ .map(ancestor => ({route: ancestor.route, title: ancestor.title})),
+ slots: node.slots
+ .filter(slot => slot.children.length > 0)
+ .map(slot => ({
+ name: slot.name,
+ title: slot.title,
+ children: slot.children.map(route => {
+ const child = /** @type {TreeNode} */ (tree.get(route));
+ return {
+ route: child.route,
+ name: child.route.slice(child.route.lastIndexOf('/') + 1),
+ kind: child.kind,
+ title: child.title,
+ summary: child.summary,
+ };
+ }),
+ })),
+ content,
+ links: nodeLinks(tree, node),
+ };
+}
+
+/**
+ * The moves a node offers (spec:AST-047): up to the level it sits in (the
+ * topic list, for a top-level namespace), and across to the nodes before and
+ * after it in its parent's slot.
+ * @param {DocsTree} tree
+ * @param {TreeNode} node
+ * @returns {import('../docs.type.mjs').DocsLinks}
+ */
+function nodeLinks(tree, node) {
+ const links = placeLinks(tree, node);
+ const related = typedEdges(tree, node).routes;
+ if (related.length > 0) {
+ links.related = related.map(
+ route =>
+ /** @type {import('../docs.type.mjs').DocsCommand} */ (
+ `astryx docs ${route}`
+ ),
+ );
+ }
+ return links;
+}
+
+/** @type {WeakMap<DocsTree, Map<string, string>>} */
+const routeIndexes = new WeakMap();
+
+/**
+ * The route of each node, by its kind and name.
+ * @param {DocsTree} tree
+ * @returns {Map<string, string>}
+ */
+function routeIndex(tree) {
+ let routes = routeIndexes.get(tree);
+ if (!routes) {
+ routes = new Map();
+ for (const each of tree.nodes.values()) {
+ routes.set(`${each.kind}\u0000${each.name}`, each.route);
+ }
+ routeIndexes.set(tree, routes);
+ }
+ return routes;
+}
+
+/**
+ * The kinds of doc each typed field may name. A bare name in one of these
+ * fields names a doc of the same provider and one of these kinds, so it is a
+ * doc identity (spec:AST-047 FR9).
+ */
+const EDGE_KINDS = {
+ function: {command: ['command'], related: ['function']},
+ command: {fn: ['function'], related: ['command']},
+};
+
+/**
+ * The typed edges a doc declares (spec:AST-047 FR5), resolved to routes: a
+ * function doc's `command` and `related`, and a command doc's `fn` and
+ * `related`. A bare name resolves among the kinds its field allows; a name
+ * that matches docs of more than one allowed kind is an error, never a silent
+ * pick. A `command` resolves to the command doc its leading words name, so
+ * `integration add theme` (the `integration add` command with its kind
+ * argument) opens `integration add`. Every name that resolves to no doc, or to
+ * more than one, is returned in `unresolved`; the graph walk test fails on it,
+ * so no edge a doc declares can go stale.
+ * @param {DocsTree} tree
+ * @param {TreeNode} node
+ * @returns {{routes: string[], unresolved: string[]}}
+ */
+export function typedEdges(tree, node) {
+ const doc = /** @type {any} */ (node.ref)?.selfDoc;
+ /** @type {string[]} */
+ const routes = [];
+ /** @type {string[]} */
+ const unresolved = [];
+ const fields = /** @type {Record<string, string[]> | undefined} */ (
+ /** @type {any} */ (EDGE_KINDS)[node.kind]
+ );
+ if (!doc || !fields) return {routes, unresolved};
+ const index = routeIndex(tree);
+ /** @param {string[]} kinds @param {string} name */
+ const among = (kinds, name) =>
+ kinds
+ .map(kind => index.get(`${kind}\u0000${name}`))
+ .filter(route => typeof route === 'string');
+ for (const [field, kinds] of Object.entries(fields)) {
+ const value = doc[field];
+ const names = Array.isArray(value) ? value : value == null ? [] : [value];
+ for (const name of names) {
+ if (typeof name !== 'string' || name.trim() === '') continue;
+ let found = among(kinds, name);
+ if (found.length === 0 && field === 'command') {
+ const words = name.trim().split(/\s+/);
+ for (let n = words.length - 1; n > 0 && found.length === 0; n--) {
+ found = among(kinds, words.slice(0, n).join(' '));
+ }
+ }
+ if (found.length === 1) routes.push(/** @type {string} */ (found[0]));
+ else if (found.length === 0) {
+ unresolved.push(`${field} "${name}" names no ${kinds.join(' or ')} doc`);
+ } else {
+ unresolved.push(
+ `${field} "${name}" names more than one doc (${found.join(', ')})`,
+ );
+ }
+ }
+ }
+ return {
+ routes: [...new Set(routes)].filter(route => route !== node.route),
+ unresolved,
+ };
+}
+
+/**
+ * @param {string} route
+ * @param {{cwd?: string}} [options]
+ * @returns {Promise<import('../docs.type.mjs').DocsNodeResponse>}
+ */
+export async function node(route, options = {}) {
+ const found = await resolveDocsArgument(route, options);
+ if (found.kind !== 'node')
+ throw await unknownTopicError(route, found.catalog);
+ return {
+ type: 'docs.node',
+ data: await nodeView(found.catalog, found.tree, found.node),
+ };
+}
diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjs
index 9559183d31..d1beabff56 100644
--- a/packages/cli/api/doctor/doctor.mjs
+++ b/packages/cli/api/doctor/doctor.mjs
@@ -34,7 +34,16 @@ import {
docsIndexBytes,
oversizedDocSections,
} from '../../foundation/discovery/docs-output-budget.mjs';
-import {compileTopic, lowerTopic, overlayLanguages} from '../docs/_adapter.mjs';
+import {
+ builtinCatalog,
+ compileTopic,
+ docsLinkProblems,
+ guideEntry,
+ lowerTopic,
+ overlayLanguages,
+ projectTree,
+} from '../docs/_adapter.mjs';
+import {typedEdges} from '../docs/node/node.mjs';
import {detailView, indexView} from '../../foundation/doc-compiler/lenses.mjs';
import {semverCompare, isValidSemver, satisfiesRange} from '../../foundation/env/semver.mjs';
@@ -66,6 +75,8 @@ import {semverCompare, isValidSemver, satisfiesRange} from '../../foundation/env
* `invalid_doc` issues from the project's contributed docs.
* @property {string|null} [docsCatalogError] - Why the project's docs catalog
* could not be built, when it could not.
+ * @property {Array<{package: string, code: string, severity: 'warning'|'error', message: string}>|null} [integrationIssues]
+ * Combined project-level integration issues, including cross-package template replacement warnings.
* @property {Error|null} [configError] - Error thrown while resolving the config
* path (e.g. multiple config files present), surfaced by checkConfig as a FAIL.
*/
@@ -585,7 +596,45 @@ export function checkPeerDeps(ctx) {
}
/**
- * Check 9 — report the detected package manager, and say so when the project's
+ * Summarize the combined integration graph, including cross-package warnings.
+ * @param {DoctorContext} ctx
+ * @returns {DoctorCheck}
+ */
+export function checkIntegrationIssues(ctx) {
+ const issues = ctx.integrationIssues;
+ if (issues == null) {
+ return {
+ id: 'integration-issues',
+ label: 'Integration contributions',
+ status: 'info',
+ message: 'Skipped — the project integration graph could not be loaded.',
+ };
+ }
+ if (issues.length === 0) {
+ return {
+ id: 'integration-issues',
+ label: 'Integration contributions',
+ status: 'pass',
+ message: 'Integration contributions and cross-package relationships are valid.',
+ };
+ }
+ const errors = issues.filter(issue => issue.severity === 'error').length;
+ const details = issues
+ .map(issue => `${issue.package}: ${issue.message}`)
+ .join(' | ');
+ // This check is new, so it warns: a project that passed before keeps
+ // passing (spec:AST-046 FR8). `astryx doctor integration` fails on errors.
+ return {
+ id: 'integration-issues',
+ label: 'Integration contributions',
+ status: 'warn',
+ message: `${issues.length} integration issue(s)${errors > 0 ? `, ${errors} of them errors` : ''}: ${details}`,
+ fix: 'Run `astryx doctor integration` for package-specific diagnostics and resolve cross-package precedence in astryx.config.',
+ };
+}
+
+/**
+ * Check 10 — report the detected package manager, and say so when the project's
* own declaration disagrees with what is on disk.
*
* Two states are worth surfacing rather than guessing past, because in both the
@@ -882,9 +931,13 @@ export async function checkAuthoringDocs(_ctx, options = {}) {
const CLI_DOCS_FIX =
"Set `namespace` on each CLI doc to the one that reads it: cli/commands for a command, cli/api for an API function or the output schema, error codes, and response types, and authoring for a file an author writes (and list it in AUTHORING_SELF_DOCS).";
+/** How the docs-tree check's problems are fixed. */
+const DOCS_TREE_FIX =
+ 'Fix each placement, adoption rule, or link the message names: a placement names a namespace of its own package, one of its slots, and a slot that accepts its kind; exactly one namespace adopts each doc; every route belongs to one doc; every link names a doc that exists, as `[<provider>:]<kind>:<name>`.';
+
/**
* Every command, API function, schema, and enum doc the CLI ships declares a
- * namespace, and the topic that namespace names reads it: `astryx docs cli`
+ * namespace, and something reads it: the docs tree under `astryx docs cli`
* for `cli/commands` and `cli/api`, `astryx docs authoring` for `authoring`.
* @param {DoctorContext | Partial<DoctorContext>} _ctx
* @param {{root?: string, sources?: string[], authoringSources?: string[]}} [options]
@@ -911,10 +964,9 @@ export async function checkCliDocs(_ctx, options = {}) {
...audit.failed.map(
({source, error}) => `${source} failed to load: ${error}`,
),
- ...audit.keyProblems.map(problem => `\`astryx docs cli\`: ${problem}`),
...audit.oversized.map(
({key, bytes}) =>
- `cli section "${key}" is ${kilobytes(bytes)}, over the ${kilobytes(DOC_OUTPUT_BUDGET_BYTES)} one read may return`,
+ `CLI doc "${key}" is ${kilobytes(bytes)}, over the ${kilobytes(DOC_OUTPUT_BUDGET_BYTES)} one read may return`,
),
];
if (problems.length > 0) {
@@ -930,7 +982,7 @@ export async function checkCliDocs(_ctx, options = {}) {
id,
label,
status: 'pass',
- message: `All ${audit.docs} CLI docs are readable: ${audit.sections} in \`astryx docs cli\` and ${audit.authoring} in \`astryx docs authoring\`.`,
+ message: `All ${audit.docs} CLI docs are readable: ${audit.tree} in the \`astryx docs cli\` tree and ${audit.authoring} in \`astryx docs authoring\`.`,
};
} catch (err) {
return {
@@ -943,6 +995,81 @@ export async function checkCliDocs(_ctx, options = {}) {
}
}
+/**
+ * The docs tree builds with no error, and every CLI typed doc in a `cli/...`
+ * group has a route in it (spec:AST-046): each placement names a namespace of
+ * its own package and a slot that accepts it, exactly one namespace adopts
+ * each doc, and each route belongs to one doc.
+ * @param {DoctorContext | Partial<DoctorContext>} _ctx
+ * @param {{tree?: import('../../foundation/doc-compiler/tree.mjs').DocsTree}} [options]
+ * test seam: a tree to check instead of the CLI's own
+ * @returns {Promise<DoctorCheck>}
+ */
+export async function checkDocsTree(_ctx, options = {}) {
+ const id = 'docs-tree';
+ const label = 'Docs tree';
+ try {
+ const catalog =
+ /** @type {any} */ (_ctx)?.docsCatalog ?? builtinCatalog();
+ const tree = options.tree ?? (await projectTree(catalog, {fresh: true}));
+ const problems = tree.diagnostics
+ .filter(d => d.severity === 'error')
+ .map(d => `${d.source ?? d.provider ?? 'docs tree'}: ${d.message}`);
+ if (options.tree === undefined) {
+ const {loadCliSelfDocs, CLI_DOC_NAMESPACES} =
+ await import('../../foundation/discovery/cli-self-docs.mjs');
+ const placed = new Set(
+ [...tree.nodes.values()].map(
+ node => `${node.provider}\u0000${node.kind}\u0000${node.name}`,
+ ),
+ );
+ for (const {source, doc} of (await loadCliSelfDocs()).loaded) {
+ if (CLI_DOC_NAMESPACES[doc.namespace]?.reader !== 'tree') continue;
+ if (!placed.has(`@astryxdesign/cli\u0000${doc.type}\u0000${doc.name}`)) {
+ problems.push(
+ `${source} has namespace "${doc.namespace}", but no docs-tree namespace adopts it`,
+ );
+ }
+ }
+ // Every link between docs names a doc that exists (spec:AST-047 FR9):
+ // typed fields, reference and workflow blocks, and inline links.
+ for (const node of tree.nodes.values()) {
+ for (const edge of typedEdges(tree, node).unresolved) {
+ problems.push(`${node.route}: ${edge}`);
+ }
+ }
+ problems.push(...(await docsLinkProblems(catalog, tree)));
+ }
+ // New findings warn: a project that passed before keeps passing
+ // (0.6 compatibility), and the warning names what to fix.
+ if (problems.length > 0) {
+ return {
+ id,
+ label,
+ status: 'warn',
+ message: joinProblems(problems),
+ fix: DOCS_TREE_FIX,
+ };
+ }
+ const nodes = [...tree.nodes.values()];
+ const namespaces = nodes.filter(node => node.kind === 'namespace').length;
+ return {
+ id,
+ label,
+ status: 'pass',
+ message: `The docs tree has ${nodes.length - namespaces} docs in ${namespaces} sections (${tree.roots().length} at the top), each at one route.`,
+ };
+ } catch (err) {
+ return {
+ id,
+ label,
+ status: 'warn',
+ message: `The docs tree could not be built: ${err instanceof Error ? err.message : String(err)}`,
+ fix: 'Reinstall @astryxdesign/cli.',
+ };
+ }
+}
+
/**
* Every topic reads progressively, in every language it ships: it loads, its
* section index and each of its sections fit in one read, and no contributed
@@ -965,7 +1092,13 @@ export async function checkDocsProgressiveDisclosure(ctx) {
let topics = 0;
const catalog = ctx.docsCatalog;
if (catalog) {
- for (const entry of catalog.entries()) {
+ // A guide the docs tree places is a topic read by its route; it is held
+ // to the same budget as every flat topic.
+ const guides = [...(await projectTree(catalog)).nodes.values()]
+ // A flat topic in the Unorganized level is checked above, as a topic.
+ .filter(node => node.kind === 'generic' && !node.ref?.flatTopic)
+ .map(guideEntry);
+ for (const entry of [...catalog.entries(), ...guides]) {
for (const lang of [null, ...overlayLanguages(entry)]) {
const where = lang ? `${entry.name} [${lang}]` : entry.name;
try {
@@ -1019,6 +1152,7 @@ export const SYNC_CHECKS = [
checkThemes,
checkImplicitIntegrations,
checkProviderIdentity,
+ checkIntegrationIssues,
checkAgentDocs,
checkPeerDeps,
checkPackageManager,
@@ -1058,6 +1192,8 @@ export async function runChecks(options = {}) {
let docsCatalogIssues = [];
/** @type {string|null} */
let docsCatalogError = null;
+ /** @type {Array<{package: string, code: string, severity: 'warning'|'error', message: string}>|null} */
+ let integrationIssues = null;
try {
const project = await Project.load(cwd);
configTheme =
@@ -1072,6 +1208,7 @@ export async function runChecks(options = {}) {
docsCatalog = null;
docsCatalogError = err instanceof Error ? err.message : String(err);
}
+ integrationIssues = await project.issues();
} catch {
// Best-effort: a missing/invalid config leaves configTheme null.
}
@@ -1087,6 +1224,7 @@ export async function runChecks(options = {}) {
docsCatalog,
docsCatalogIssues,
docsCatalogError,
+ integrationIssues,
configError,
};
@@ -1101,6 +1239,7 @@ export async function runChecks(options = {}) {
}
checks.push(await checkAuthoringDocs(ctx));
checks.push(await checkCliDocs(ctx));
+ checks.push(await checkDocsTree(ctx));
checks.push(await checkDocsProgressiveDisclosure(ctx));
const summary = {pass: 0, warn: 0, fail: 0, info: 0};
diff --git a/packages/cli/api/doctor/doctor.test.mjs b/packages/cli/api/doctor/doctor.test.mjs
index 29a029777b..29a51a11e9 100644
--- a/packages/cli/api/doctor/doctor.test.mjs
+++ b/packages/cli/api/doctor/doctor.test.mjs
@@ -23,9 +23,11 @@ import {
doctor,
checkAuthoringDocs,
checkCliDocs,
+ checkDocsTree,
checkDocsProgressiveDisclosure,
checkImplicitIntegrations,
checkProviderIdentity,
+ checkIntegrationIssues,
checkVersionAlignment,
checkPackageManager,
} from './doctor.mjs';
@@ -84,6 +86,27 @@ describe('doctor leaf', () => {
}, SLOW);
});
+describe('integration issue check', () => {
+ it('surfaces cross-package replacement warnings', () => {
+ const check = checkIntegrationIssues({
+ integrationIssues: [
+ {
+ package: '@acme/later',
+ code: 'ambiguous_template_replacement',
+ severity: 'warning',
+ message: 'Later configured replacement wins.',
+ },
+ ],
+ });
+
+ expect(check).toMatchObject({
+ id: 'integration-issues',
+ status: 'warn',
+ message: expect.stringContaining('Later configured replacement wins.'),
+ });
+ });
+});
+
describe('doctor leaf — degradation & error paths', () => {
it('does not crash on multiple config files; reports a config FAIL', async () => {
const dir = mkProject({
@@ -476,7 +499,7 @@ describe('checkCliDocs', () => {
id: 'cli-docs',
label: 'CLI docs',
status: 'pass',
- message: `All ${audit.docs} CLI docs are readable: ${audit.sections} in \`astryx docs cli\` and ${audit.authoring} in \`astryx docs authoring\`.`,
+ message: `All ${audit.docs} CLI docs are readable: ${audit.tree} in the \`astryx docs cli\` tree and ${audit.authoring} in \`astryx docs authoring\`.`,
});
},
SLOW,
@@ -518,6 +541,71 @@ describe('checkCliDocs', () => {
);
});
+describe('checkDocsTree', () => {
+ it(
+ 'passes on this repo: every CLI doc in a cli group has one route',
+ async () => {
+ const {loadDocsTree} = await import(
+ '../../foundation/doc-compiler/tree.mjs'
+ );
+ const tree = await loadDocsTree({fresh: true});
+ const nodes = [...tree.nodes.values()];
+ const namespaces = nodes.filter(node => node.kind === 'namespace').length;
+ expect(await checkDocsTree()).toEqual({
+ id: 'docs-tree',
+ label: 'Docs tree',
+ status: 'pass',
+ message: expect.stringMatching(
+ /^The docs tree has \d+ docs in \d+ sections \(\d+ at the top\), each at one route\.$/,
+ ),
+ });
+ },
+ SLOW,
+ );
+
+ it('fails on a tree with a broken placement, and names the fix', async () => {
+ const {buildDocsTree} = await import(
+ '../../foundation/doc-compiler/tree.mjs'
+ );
+ const tree = buildDocsTree({
+ namespaces: [
+ {
+ provider: '@acme/kit',
+ providerId: '@acme/kit',
+ source: '@acme/kit/tree/guides.doc.mjs',
+ doc: {
+ type: 'namespace',
+ name: 'guides',
+ title: 'Guides',
+ summary: 'Every guide.',
+ slots: {all: {title: 'All', accepts: {kinds: ['generic']}}},
+ },
+ },
+ ],
+ docs: [
+ {
+ provider: '@acme/kit',
+ providerId: '@acme/kit',
+ source: '@acme/kit/tree/setup.doc.mjs',
+ kind: 'generic',
+ name: 'setup',
+ title: 'Setup',
+ summary: 'Set it up.',
+ group: null,
+ placement: {parent: 'namespace:guidez'},
+ },
+ ],
+ });
+ const c = await checkDocsTree(undefined, {tree});
+ // New findings warn (0.6 compatibility): a broken tree is named, not fatal.
+ expect(c).toMatchObject({id: 'docs-tree', status: 'warn'});
+ expect(c.message).toContain(
+ '@acme/kit/tree/setup.doc.mjs: placement.parent "namespace:guidez" names no namespace; @acme/kit declares "guides".',
+ );
+ expect(c.fix).toMatch(/a placement names a namespace of its own package/);
+ });
+});
+
describe('checkAuthoringDocs against the public authoring surface', () => {
const NAMESPACE = 'doctypes/namespace/namespace.doc.mjs';
const NAMESPACE_TYPES =
diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjs
index 5034f1f7f6..460c0e5abb 100644
--- a/packages/cli/api/index.mjs
+++ b/packages/cli/api/index.mjs
@@ -28,6 +28,7 @@ export {template} from './template/template.mjs';
export {
themeBuild,
themeAdd,
+ themeTemplate,
themeList,
themeListAvailable,
themeTargets,
diff --git a/packages/cli/api/init/init.doc.mjs b/packages/cli/api/init/init.doc.mjs
index 90ff52b47e..ef536e5792 100644
--- a/packages/cli/api/init/init.doc.mjs
+++ b/packages/cli/api/init/init.doc.mjs
@@ -102,5 +102,5 @@ export const doc = {
{label: 'Remove agent docs', code: 'await init({removeAgents: true});'},
],
command: 'init',
- related: ['doctor', 'upgrade', 'build', 'theme'],
+ related: ['doctor', 'upgrade', 'build', 'themeTemplate'],
};
diff --git a/packages/cli/api/integration/add-contribution.mjs b/packages/cli/api/integration/add-contribution.mjs
index 4a062c7e66..d355d8ca17 100644
--- a/packages/cli/api/integration/add-contribution.mjs
+++ b/packages/cli/api/integration/add-contribution.mjs
@@ -34,6 +34,11 @@ import {
} from '../../foundation/integrations/integrations.mjs';
import {isValidSemver} from '../../foundation/env/semver.mjs';
import {assertContributionVisible} from '../../foundation/integrations/contribution-inventory.mjs';
+import {
+ docsTreeCliProblem,
+ withDocsTreeCli,
+} from '../../foundation/integrations/cli-requirement.mjs';
+import {discoverIntegrationDocs} from '../../foundation/discovery/docs-discovery.mjs';
import {findIntegrationComponentDoc} from '../../foundation/discovery/component-discovery.mjs';
import {parseAgentDocsField} from '../../authoring/integration/schema.mjs';
import {integrationAddTheme} from './add-theme.mjs';
@@ -83,6 +88,17 @@ function resolvePackage(cwd) {
}
const owner = typeof pkg.name === 'string' ? pkg.name : '(local integration)';
const existingManifest = findLocalIntegrationManifestOrNull(packageDir);
+ // The nearest package.json above the cwd may belong to another package (an
+ // app that contains the folder). Only a package that is already an
+ // integration is found from a subfolder; the first add runs in the package.
+ const here = path.resolve(cwd ?? process.cwd());
+ if (existingManifest == null && path.resolve(packageDir) !== here) {
+ throw new AstryxError(
+ `${here} has no package.json. The nearest is ${packageFile} (${owner}), which is not an Astryx integration yet. Run this in your integration package's own directory, next to its package.json.`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
const manifestFile =
existingManifest ?? path.join(packageDir, 'astryx.integration.mjs');
return {
@@ -353,7 +369,7 @@ async function addComponent(name, options) {
/**
* @param {string} name topic name (must match [\w-]+)
- * @param {{cwd?: string, dryRun?: boolean, replaces?: string, extends?: string}} options
+ * @param {{cwd?: string, dryRun?: boolean, replaces?: string, extends?: string, parent?: string}} options
* @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
*/
async function addDoc(name, options) {
@@ -372,6 +388,20 @@ async function addDoc(name, options) {
ERROR_CODES.ERR_INVALID_ARGUMENT,
);
}
+ if (options.parent != null && (options.replaces != null || options.extends != null)) {
+ throw new AstryxError(
+ 'A guide placed in a namespace has its own route: it cannot also replace or extend a topic.',
+ undefined,
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ if (options.parent != null && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(options.parent)) {
+ throw new AstryxError(
+ '--parent must name a namespace in lowercase letters and digits joined by single hyphens, such as "acme".',
+ undefined,
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
for (const [option, value] of [
['--replaces', options.replaces],
['--extends', options.extends],
@@ -432,20 +462,92 @@ async function addDoc(name, options) {
}
const title = kebabToTitle(name);
+ // --parent names a namespace of this package by its name, wherever its file
+ // is. An existing one is used as it is: its `guides` slot, or else its only
+ // slot that takes a guide. Otherwise the namespace doc is written, unless a
+ // file of that name is already something else (spec:AST-046 FR11).
+ const namespaceFile =
+ options.parent == null
+ ? null
+ : assertWithin(`${options.parent}.doc.mjs`, root, {
+ label: 'namespace doc file',
+ });
+ let parentSlot = 'guides';
+ let writeNamespace = false;
+ if (options.parent != null && namespaceFile != null) {
+ const {namespaces} = await discoverIntegrationDocs({
+ name: owner,
+ docs: root,
+ });
+ const existing = namespaces.find(ns => ns.doc.name === options.parent);
+ if (existing != null) {
+ const takesGuides = Object.entries(existing.doc.slots ?? {})
+ .filter(([, slot]) => slot?.accepts?.kinds?.includes('generic'))
+ .map(([slotName]) => slotName);
+ const slot = takesGuides.includes('guides')
+ ? 'guides'
+ : takesGuides.length === 1
+ ? takesGuides[0]
+ : null;
+ if (slot == null) {
+ throw new AstryxError(
+ takesGuides.length === 0
+ ? `Namespace "${options.parent}" (${existing.source}) has no slot that takes a guide. Add one, such as guides: {title: 'Guides', accepts: {kinds: ['generic']}}.`
+ : `Namespace "${options.parent}" (${existing.source}) has more than one slot that takes a guide (${takesGuides.join(', ')}). Write the guide yourself, and name its slot in its placement.`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ parentSlot = slot;
+ } else if (fs.existsSync(namespaceFile)) {
+ throw new AstryxError(
+ `${projectPath(path.relative(packageDir, namespaceFile))} exists but does not load as the namespace "${options.parent}". Fix or rename that file, or pass another --parent.`,
+ undefined,
+ ERROR_CODES.ERR_FILE_EXISTS,
+ );
+ } else {
+ writeNamespace = true;
+ }
+ }
const relationship = options.replaces
? `\n replaces: '${options.replaces}',`
: options.extends
? `\n extends: '${options.extends}',`
- : '';
+ : options.parent
+ ? `\n placement: {parent: 'namespace:${options.parent}', slot: '${parentSlot}'},`
+ : '';
+ const namespaceTitle =
+ options.parent == null ? '' : kebabToTitle(options.parent);
+ const namespaceContents = `/** @type {import('@astryxdesign/cli/authoring').NamespaceDoc} */\nexport default {\n type: 'namespace',\n name: '${options.parent}',\n title: '${namespaceTitle}',\n summary: 'Guides for ${namespaceTitle}.',\n slots: {\n guides: {title: 'Guides', accepts: {kinds: ['generic']}},\n },\n};\n`;
const docContents = `/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */\nexport default {\n type: 'generic',\n name: '${name}',\n title: '${title}',\n description: '${title} documentation.',${relationship}\n sections: [\n {\n title: 'Overview',\n content: [\n { type: 'prose', text: '${title} documentation.' },\n ],\n },\n ],\n};\n`;
/** @type {import('./add-helpers.mjs').WritePlan[]} */
const plans = [{path: docFile, contents: docContents, createOnly: true}];
- const pkgUpdate = packageJsonUpdate(
+ if (namespaceFile != null && writeNamespace) {
+ plans.push({path: namespaceFile, contents: namespaceContents, createOnly: true});
+ }
+ let pkgUpdate = packageJsonUpdate(
packageFile,
rootPath,
path.basename(manifestFile),
);
+ // A namespace doc needs a CLI that reads it: an older one hides every doc
+ // topic the package ships. Declare that CLI as a peer, so an older one fails
+ // at install instead (spec:AST-046 FR11).
+ if (options.parent != null) {
+ const expectedOriginal =
+ pkgUpdate?.expectedOriginal ?? fs.readFileSync(packageFile);
+ const text = pkgUpdate?.contents ?? expectedOriginal.toString('utf-8');
+ const current = JSON.parse(text);
+ if (docsTreeCliProblem(current) != null) {
+ pkgUpdate = {
+ contents:
+ JSON.stringify(withDocsTreeCli(current), null, 2) +
+ (text.endsWith('\n') ? '\n' : ''),
+ expectedOriginal,
+ };
+ }
+ }
if (pkgUpdate != null) {
plans.push({
path: packageFile,
@@ -1105,7 +1207,7 @@ export function integrationAddAgentDoc(line, options = {}) {
const KIND_OPTIONS = {
component: new Set(['cwd', 'dryRun']),
- doc: new Set(['cwd', 'dryRun', 'replaces', 'extends']),
+ doc: new Set(['cwd', 'dryRun', 'replaces', 'extends', 'parent']),
template: new Set(['cwd', 'dryRun', 'templateType']),
codemod: new Set(['cwd', 'dryRun', 'to']),
'agent-doc': new Set(['cwd', 'dryRun']),
@@ -1136,7 +1238,7 @@ function validateKindOptions(kind, options) {
*
* @param {'component'|'doc'|'template'|'codemod'|'agent-doc'|'theme'} kind
* @param {string} name
- * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string}} [options]
+ * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string, parent?: string}} [options]
* @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
*/
export async function integrationAdd(kind, name, options = {}) {
diff --git a/packages/cli/api/integration/add-contribution.test.mjs b/packages/cli/api/integration/add-contribution.test.mjs
index 123eb3860c..c8e3003d16 100644
--- a/packages/cli/api/integration/add-contribution.test.mjs
+++ b/packages/cli/api/integration/add-contribution.test.mjs
@@ -12,6 +12,7 @@ import {
integrationAddTemplate,
} from './add-contribution.mjs';
import {validateLocalIntegration} from './validate-integration.mjs';
+import {DOCS_TREE_CLI} from '../../foundation/integrations/cli-requirement.mjs';
let tmpDir;
@@ -314,6 +315,142 @@ describe('integrationAdd doc', () => {
expect(docErrors).toEqual([]);
});
+ it('refuses to write from a folder with no package.json into the package above it', async () => {
+ setupBare();
+ const inside = path.join(tmpDir, 'kit');
+ fs.mkdirSync(inside);
+ await expect(
+ integrationAdd('doc', 'my-guide', {cwd: inside, parent: 'acme'}),
+ ).rejects.toMatchObject({
+ code: 'ERR_INVALID_ARGUMENT',
+ message: expect.stringContaining('has no package.json'),
+ });
+ expect(fs.existsSync(path.join(tmpDir, 'docs'))).toBe(false);
+ expect(fs.existsSync(path.join(tmpDir, 'astryx.integration.mjs'))).toBe(false);
+ });
+
+ it('finds an integration from a folder inside it', async () => {
+ setup();
+ const inside = path.join(tmpDir, 'src');
+ fs.mkdirSync(inside);
+ const result = await integrationAdd('doc', 'my-guide', {cwd: inside});
+ expect(result.data.files).toContain('docs/my-guide.doc.mjs');
+ expect(fs.existsSync(path.join(tmpDir, 'docs/my-guide.doc.mjs'))).toBe(true);
+ });
+
+ it('places a guide in a namespace of the package, writing the namespace once', async () => {
+ setup();
+ const first = await integrationAdd('doc', 'deploying', {
+ cwd: tmpDir,
+ parent: 'acme',
+ });
+ expect(first.data.files).toEqual(
+ expect.arrayContaining(['docs/deploying.doc.mjs', 'docs/acme.doc.mjs']),
+ );
+ const guide = fs.readFileSync(path.join(tmpDir, 'docs/deploying.doc.mjs'), 'utf-8');
+ expect(guide).toContain("placement: {parent: 'namespace:acme', slot: 'guides'}");
+ const namespace = fs.readFileSync(path.join(tmpDir, 'docs/acme.doc.mjs'), 'utf-8');
+ expect(namespace).toContain("type: 'namespace'");
+ expect(namespace).toContain("guides: {title: 'Guides', accepts: {kinds: ['generic']}}");
+
+ // The namespace doc needs a CLI that reads it, declared as an optional peer.
+ const pkg = JSON.parse(fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'));
+ expect(pkg.peerDependencies).toEqual({'@astryxdesign/cli': `>=${DOCS_TREE_CLI}`});
+ expect(pkg.peerDependenciesMeta).toEqual({'@astryxdesign/cli': {optional: true}});
+
+ const second = await integrationAdd('doc', 'upgrading', {
+ cwd: tmpDir,
+ parent: 'acme',
+ });
+ expect(second.data.files).not.toContain('docs/acme.doc.mjs');
+
+ const validation = await validateLocalIntegration(tmpDir);
+ expect(validation.issues.filter(i => i.code === 'invalid_doc')).toEqual([]);
+ });
+
+ it('finds the --parent namespace by its name, wherever its file is, and uses its slot', async () => {
+ setup({manifest: "export default {docs: './docs'};\n"});
+ fs.mkdirSync(path.join(tmpDir, 'docs', 'ns'), {recursive: true});
+ fs.writeFileSync(
+ path.join(tmpDir, 'docs', 'ns', 'acme.doc.mjs'),
+ "export default {type: 'namespace', name: 'acme', title: 'Acme', summary: 'Acme.', slots: {items: {title: 'Items', accepts: {kinds: ['generic']}}}};\n",
+ );
+ const result = await integrationAdd('doc', 'deploying', {cwd: tmpDir, parent: 'acme'});
+ expect(result.data.files).not.toContain('docs/acme.doc.mjs');
+ expect(fs.existsSync(path.join(tmpDir, 'docs', 'acme.doc.mjs'))).toBe(false);
+ expect(fs.readFileSync(path.join(tmpDir, 'docs', 'deploying.doc.mjs'), 'utf-8')).toContain(
+ "placement: {parent: 'namespace:acme', slot: 'items'}",
+ );
+ });
+
+ it('refuses --parent when its file is not that namespace, or the namespace has no slot for a guide', async () => {
+ setup({manifest: "export default {docs: './docs'};\n"});
+ fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});
+ const nsFile = path.join(tmpDir, 'docs', 'acme.doc.mjs');
+ fs.writeFileSync(
+ nsFile,
+ "export default {type: 'generic', name: 'acme', title: 'Acme', description: 'A topic.', sections: [{title: 'Only', content: [{type: 'prose', text: 'x'}]}]};\n",
+ );
+ await expect(
+ integrationAdd('doc', 'deploying', {cwd: tmpDir, parent: 'acme'}),
+ ).rejects.toMatchObject({code: 'ERR_FILE_EXISTS'});
+ // A fresh file: the module loader keeps the first import of a path.
+ fs.writeFileSync(
+ path.join(tmpDir, 'docs', 'beta.doc.mjs'),
+ "export default {type: 'namespace', name: 'beta', title: 'Beta', summary: 'Beta.', slots: {items: {title: 'Items', accepts: {kinds: ['function']}}}};\n",
+ );
+ await expect(
+ integrationAdd('doc', 'deploying', {cwd: tmpDir, parent: 'beta'}),
+ ).rejects.toMatchObject({
+ code: 'ERR_INVALID_ARGUMENT',
+ message: expect.stringContaining('no slot that takes a guide'),
+ });
+ fs.writeFileSync(
+ path.join(tmpDir, 'docs', 'gamma.doc.mjs'),
+ "export default {type: 'namespace', name: 'gamma', title: 'Gamma', summary: 'Gamma.', slots: {guides: {title: 'Guides', accepts: {kinds: ['function']}}, more: {title: 'More', accepts: {kinds: ['generic']}}, extra: {title: 'Extra', accepts: {kinds: ['generic']}}}};\n",
+ );
+ await expect(
+ integrationAdd('doc', 'deploying', {cwd: tmpDir, parent: 'gamma'}),
+ ).rejects.toMatchObject({
+ code: 'ERR_INVALID_ARGUMENT',
+ message: expect.stringContaining('more than one slot that takes a guide (more, extra)'),
+ });
+ expect(fs.existsSync(path.join(tmpDir, 'docs', 'deploying.doc.mjs'))).toBe(false);
+ });
+
+ it('raises a CLI peer that admits a CLI too old for namespace docs, and keeps one that does not', async () => {
+ setup();
+ const file = path.join(tmpDir, 'package.json');
+ const write = (/** @type {string} */ range) => {
+ const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
+ pkg.peerDependencies = {'@astryxdesign/cli': range};
+ fs.writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\n`);
+ };
+ write('^0.6.0');
+ await integrationAdd('doc', 'deploying', {cwd: tmpDir, parent: 'acme'});
+ expect(JSON.parse(fs.readFileSync(file, 'utf-8')).peerDependencies).toEqual({
+ '@astryxdesign/cli': `>=${DOCS_TREE_CLI}`,
+ });
+ write('^9.1.0');
+ await integrationAdd('doc', 'upgrading', {cwd: tmpDir, parent: 'acme'});
+ expect(JSON.parse(fs.readFileSync(file, 'utf-8')).peerDependencies).toEqual({
+ '@astryxdesign/cli': '^9.1.0',
+ });
+ });
+
+ it('refuses --parent with a relationship, or a namespace name that is not a route segment', async () => {
+ setup();
+ await expect(
+ integrationAdd('doc', 'x', {cwd: tmpDir, parent: 'acme', replaces: 'getting-started'}),
+ ).rejects.toMatchObject({code: 'ERR_INVALID_ARGUMENT'});
+ await expect(
+ integrationAdd('doc', 'x', {cwd: tmpDir, parent: 'Acme Kit'}),
+ ).rejects.toMatchObject({code: 'ERR_INVALID_ARGUMENT'});
+ await expect(
+ integrationAdd('template', 'x', {cwd: tmpDir, parent: 'acme'}),
+ ).rejects.toMatchObject({code: 'ERR_INVALID_ARGUMENT'});
+ });
+
it('includes replaces in the generated doc', async () => {
setup();
const result = await integrationAdd('doc', 'my-tokens', {
diff --git a/packages/cli/api/integration/authoring-checks.mjs b/packages/cli/api/integration/authoring-checks.mjs
index 7307e24ff6..24d0eb9ec3 100644
--- a/packages/cli/api/integration/authoring-checks.mjs
+++ b/packages/cli/api/integration/authoring-checks.mjs
@@ -3,13 +3,13 @@
/**
* @file Integration authoring diagnostics against the built-in Core catalog.
*
- * Components and templates may intentionally share a Core identity, but
- * unqualified lookup then fails closed and callers must select the package.
- * Docs have explicit `replaces` / `extends` relationships, so the check can
- * distinguish intentional ownership from an accidental same-name shadow.
+ * Templates may intentionally replace Core identities; undeclared same-id
+ * overlaps stay fail-closed and require package selection. Docs have explicit
+ * `replaces` / `extends` relationships with parallel validation semantics.
*/
import {getCliInvocation} from '../../foundation/env/package-manager.mjs';
+import {packageDocsProblems} from '../docs/_adapter.mjs';
import {findCoreDir} from '../../foundation/fs/paths.mjs';
import {
discoverIntegrationComponents,
@@ -20,6 +20,7 @@ import {
discoverIntegrationDocs,
} from '../../foundation/discovery/docs-discovery.mjs';
import {
+ applyTemplateReplacements,
discoverCoreTemplates,
discoverIntegrationTemplatesForOne,
} from '../../foundation/discovery/template-adapter.mjs';
@@ -48,16 +49,27 @@ async function resolveIntegration(pkg, cwd) {
/**
* Add discovery errors once to an issue list.
* @param {Array<{code: string, severity: 'warning' | 'error', message: string}>} issues
- * @param {Array<{message: string} | Error>} errors
+ * @param {Array<{message: string, code?: string, severity?: 'warning' | 'error'} | Error>} errors
* @param {string} code
*/
function addErrors(issues, errors, code) {
for (const error of errors) {
const message = error.message;
- if (issues.some(issue => issue.code === code && issue.message === message)) {
+ const issueCode =
+ 'code' in error && typeof error.code === 'string' ? error.code : code;
+ const severity =
+ 'severity' in error &&
+ (error.severity === 'warning' || error.severity === 'error')
+ ? error.severity
+ : 'error';
+ if (
+ issues.some(
+ issue => issue.code === issueCode && issue.message === message,
+ )
+ ) {
continue;
}
- issues.push({code, severity: 'error', message});
+ issues.push({code: issueCode, severity, message});
}
}
@@ -74,7 +86,7 @@ export async function integrationTemplateConflicts(pkg, options = {}) {
const version = resolved.found ? (resolved.version ?? null) : null;
const issues = [...resolved.issues];
- if (!resolved.integration?.templates || name == null) {
+ if (!resolved.integration || name == null) {
return {
type: 'integration.template-conflicts',
data: {name, version, conflicts: [], issues},
@@ -87,6 +99,31 @@ export async function integrationTemplateConflicts(pkg, options = {}) {
]);
addErrors(issues, errors, 'invalid_template');
+ const replacementResolution = applyTemplateReplacements(
+ [...coreTemplates, ...templates],
+ errors.filter(error => error.replacementTarget != null),
+ );
+ for (const error of replacementResolution.errors) {
+ if (
+ !issues.some(
+ issue => issue.code === error.code && issue.message === error.message,
+ )
+ ) {
+ issues.push({
+ code: error.code,
+ severity: error.severity,
+ message: error.message,
+ });
+ }
+ }
+ const activeReplacementIds = new Set(
+ replacementResolution.templates
+ .filter(
+ template => template.package === name && template.replaces != null,
+ )
+ .map(template => template.dirName),
+ );
+
/** @type {Map<string, Array<{type: 'page' | 'block', name: string}>>} */
const coreById = new Map();
for (const template of coreTemplates) {
@@ -101,30 +138,57 @@ export async function integrationTemplateConflicts(pkg, options = {}) {
}
const run = getCliInvocation(cwd);
- const conflicts = templates
- .flatMap(template => {
- const coreMatches = coreById.get(template.dirName);
- if (!coreMatches) return [];
- const command = `${run} template ${shellArg(template.dirName)} --package ${shellArg(name)}`;
- const coreKinds = coreMatches
+ /** @type {import('./authoring-checks.type.mjs').IntegrationTemplateConflict[]} */
+ const conflicts = [];
+ for (const template of templates) {
+ const sameIdCore = coreById.get(template.dirName);
+ const replacementIsActive = activeReplacementIds.has(template.dirName);
+
+ if (replacementIsActive && template.replaces != null) {
+ conflicts.push({
+ id: template.dirName,
+ severity: 'info',
+ relationship: 'replaces',
+ replaces: template.replaces,
+ integrationPackage: name,
+ integrationType: template.type,
+ integrationName: template.name,
+ coreMatches: coreById.get(template.replaces) ?? [],
+ message:
+ `Intentional replacement: "${template.dirName}" replaces the Core template ` +
+ `"${template.replaces}" for unqualified lookup.`,
+ command: `${run} template ${shellArg(template.replaces)} --package ${shellArg('@astryxdesign/core')}`,
+ });
+ }
+
+ if (
+ sameIdCore &&
+ !(replacementIsActive && template.replaces === template.dirName)
+ ) {
+ const coreKinds = sameIdCore
.map(match => `${match.type} "${match.name}"`)
.join(', ');
- return [
- {
- id: template.dirName,
- severity: /** @type {const} */ ('warning'),
- integrationPackage: name,
- integrationType: template.type,
- integrationName: template.name,
- coreMatches,
- message:
- `Template id "${template.dirName}" conflicts with Core (${coreKinds}). ` +
- 'Consider renaming the integration template. If you keep it, always select it with --package.',
- command,
- },
- ];
- })
- .sort((a, b) => a.id.localeCompare(b.id));
+ const compatibleKind = sameIdCore.some(
+ match => match.type === template.type,
+ );
+ conflicts.push({
+ id: template.dirName,
+ severity: 'warning',
+ relationship: 'accidental',
+ integrationPackage: name,
+ integrationType: template.type,
+ integrationName: template.name,
+ coreMatches: sameIdCore,
+ message: compatibleKind
+ ? `Template id "${template.dirName}" conflicts with Core (${coreKinds}). Consider renaming it, or set replaces: ${JSON.stringify(template.dirName)} in its metadata to replace the Core template.`
+ : `Template id "${template.dirName}" conflicts with Core (${coreKinds}), but a ${template.type} template cannot replace a different template kind. Rename the integration template.`,
+ command: `${run} template ${shellArg(template.dirName)} --package ${shellArg(name)}`,
+ });
+ }
+ }
+ conflicts.sort((a, b) =>
+ `${a.id}:${a.relationship}`.localeCompare(`${b.id}:${b.relationship}`),
+ );
return {
type: 'integration.template-conflicts',
@@ -211,10 +275,11 @@ export async function integrationDocConflicts(pkg, options = {}) {
};
}
- const [{records, errors}, builtinTopics] = await Promise.all([
+ const [discovered, builtinTopics] = await Promise.all([
discoverIntegrationDocs(resolved.integration),
Promise.resolve(discoverBuiltinTopics()),
]);
+ const {records, errors} = discovered;
addErrors(issues, errors, 'invalid_doc');
const coreTopicsByKey = new Map(
Object.keys(builtinTopics).map(topic => [topic.toLowerCase(), topic]),
@@ -276,6 +341,18 @@ export async function integrationDocConflicts(pkg, options = {}) {
),
);
+ // The same graph checks `astryx doctor` runs in a project: the namespaces
+ // and placed guides this package adds to the docs tree, and every link in
+ // its docs (spec:AST-046, spec:AST-047).
+ if (errors.length === 0) {
+ for (const message of await packageDocsProblems(
+ /** @type {{name: string}} */ (resolved.integration),
+ discovered,
+ )) {
+ issues.push({code: 'invalid_doc_graph', severity: 'warning', message});
+ }
+ }
+
return {
type: 'integration.doc-conflicts',
data: {name, version, findings, issues},
diff --git a/packages/cli/api/integration/authoring-checks.test.mjs b/packages/cli/api/integration/authoring-checks.test.mjs
index e639da5d61..f9f2d3b19d 100644
--- a/packages/cli/api/integration/authoring-checks.test.mjs
+++ b/packages/cli/api/integration/authoring-checks.test.mjs
@@ -20,7 +20,14 @@ import {
let tmpDir;
-function writeIntegration({id, name, type = 'block', root = tmpDir}) {
+function writeIntegration({
+ id,
+ name,
+ type = 'block',
+ root = tmpDir,
+ replacements,
+ withSource = true,
+}) {
fs.mkdirSync(root, {recursive: true});
fs.writeFileSync(
path.join(root, 'package.json'),
@@ -34,8 +41,9 @@ function writeIntegration({id, name, type = 'block', root = tmpDir}) {
fs.mkdirSync(path.dirname(stem), {recursive: true});
fs.writeFileSync(
`${stem}.doc.mjs`,
- `export default {type: '${type}', name: ${JSON.stringify(name)}, description: 'fixture'};\n`,
+ `export default {type: '${type}', name: ${JSON.stringify(name)}, description: 'fixture'${replacements?.[id] == null ? '' : `, replaces: ${JSON.stringify(replacements[id])}`}};\n`,
);
+ if (!withSource) return;
fs.writeFileSync(
`${stem}.tsx`,
'export default function Fixture() { return null; }\n',
@@ -158,6 +166,159 @@ describe('integrationTemplateConflicts', () => {
);
});
+ it('classifies a valid replacement and points to the Core original', async () => {
+ const core = (await discoverCoreTemplates()).find(
+ template => template.type === 'page',
+ );
+ expect(core).toBeDefined();
+ writeIntegration({
+ id: 'acme-app-shell',
+ name: 'Acme app shell',
+ type: core.type,
+ replacements: {'acme-app-shell': core.dirName},
+ });
+
+ const result = await integrationTemplateConflicts(undefined, {cwd: tmpDir});
+
+ expect(result.data.issues).toEqual([]);
+ expect(result.data.conflicts).toEqual([
+ expect.objectContaining({
+ id: 'acme-app-shell',
+ severity: 'info',
+ relationship: 'replaces',
+ replaces: core.dirName,
+ }),
+ ]);
+ expect(result.data.conflicts[0].command).toContain(
+ `template ${core.dirName} --package @astryxdesign/core`,
+ );
+ });
+
+ it('reports a replacement target that Core does not provide', async () => {
+ writeIntegration({
+ id: 'acme-app-shell',
+ name: 'Acme app shell',
+ type: 'page',
+ replacements: {'acme-app-shell': 'missing-core-shell'},
+ });
+
+ const result = await integrationTemplateConflicts(undefined, {cwd: tmpDir});
+
+ expect(result.data.issues).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'missing_template_replacement_target',
+ severity: 'error',
+ }),
+ ]),
+ );
+ });
+
+ it('reports a replacement declared by a template that cannot be used', async () => {
+ const [core] = await discoverCoreTemplates();
+ expect(core).toBeDefined();
+ writeIntegration({
+ id: 'broken-template',
+ name: 'Broken template',
+ type: core.type,
+ replacements: {'broken-template': core.dirName},
+ withSource: false,
+ });
+
+ const result = await integrationTemplateConflicts(undefined, {cwd: tmpDir});
+
+ expect(result.data.issues).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'invalid_template_replacement',
+ severity: 'error',
+ message: expect.stringContaining('cannot be used'),
+ }),
+ ]),
+ );
+ });
+
+ it('reports two templates that replace the same Core target as ambiguous', async () => {
+ const [core] = await discoverCoreTemplates();
+ expect(core).toBeDefined();
+ const replacements = {
+ 'acme-app-shell-a': core.dirName,
+ 'acme-app-shell-b': core.dirName,
+ };
+ writeIntegration({
+ id: 'acme-app-shell-a',
+ name: 'Acme app shell A',
+ type: core.type,
+ replacements,
+ });
+ writeIntegration({
+ id: 'acme-app-shell-b',
+ name: 'Acme app shell B',
+ type: core.type,
+ replacements,
+ });
+
+ const result = await integrationTemplateConflicts(undefined, {cwd: tmpDir});
+
+ expect(result.data.issues).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'ambiguous_template_replacement',
+ severity: 'error',
+ }),
+ ]),
+ );
+ });
+
+ it('reports a replacement whose template kind differs from Core', async () => {
+ const corePage = (await discoverCoreTemplates()).find(
+ template => template.type === 'page',
+ );
+ expect(corePage).toBeDefined();
+ writeIntegration({
+ id: 'acme-app-shell',
+ name: 'Acme app shell',
+ type: 'block',
+ replacements: {'acme-app-shell': corePage.dirName},
+ });
+
+ const result = await integrationTemplateConflicts(undefined, {cwd: tmpDir});
+
+ expect(result.data.issues).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'invalid_template_replacement',
+ severity: 'error',
+ message: expect.stringContaining('same type'),
+ }),
+ ]),
+ );
+ });
+
+ it('does not recommend an impossible replacement for a different Core kind', async () => {
+ const corePage = (await discoverCoreTemplates()).find(
+ template => template.type === 'page',
+ );
+ expect(corePage).toBeDefined();
+ writeIntegration({
+ id: corePage.dirName,
+ name: 'Acme block with a page id',
+ type: 'block',
+ });
+
+ const result = await integrationTemplateConflicts(undefined, {cwd: tmpDir});
+ const conflict = result.data.conflicts.find(
+ item => item.id === corePage.dirName,
+ );
+
+ expect(conflict?.relationship).toBe('accidental');
+ expect(conflict?.message).toContain(
+ 'cannot replace a different template kind',
+ );
+ expect(conflict?.message).toContain('Rename');
+ expect(conflict?.message).not.toContain('set replaces');
+ });
+
it('shell-quotes unusual ids instead of allowing command substitution', () => {
expect(shellArg('safe/id')).toBe('safe/id');
expect(shellArg('my$thing')).toBe("'my$thing'");
diff --git a/packages/cli/api/integration/authoring-checks.type.mjs b/packages/cli/api/integration/authoring-checks.type.mjs
index 5afc6713b4..f70a6c83f4 100644
--- a/packages/cli/api/integration/authoring-checks.type.mjs
+++ b/packages/cli/api/integration/authoring-checks.type.mjs
@@ -16,7 +16,9 @@
/**
* @typedef {object} IntegrationTemplateConflict
* @property {string} id
- * @property {'warning'} severity
+ * @property {'info' | 'warning'} severity
+ * @property {'replaces' | 'accidental'} relationship
+ * @property {string} [replaces]
* @property {string} integrationPackage
* @property {'page' | 'block'} integrationType
* @property {string} integrationName
diff --git a/packages/cli/api/integration/integration-authoring.type.mjs b/packages/cli/api/integration/integration-authoring.type.mjs
index bd130bc006..9f9740c308 100644
--- a/packages/cli/api/integration/integration-authoring.type.mjs
+++ b/packages/cli/api/integration/integration-authoring.type.mjs
@@ -20,6 +20,7 @@
* @typedef {IntegrationAddBaseOptions & {
* replaces?: string,
* extends?: string,
+ * parent?: string,
* }} IntegrationAddDocOptions
*/
@@ -48,6 +49,7 @@
* @property {'page'|'block'} [templateType]
* @property {string} [replaces]
* @property {string} [extends]
+ * @property {string} [parent]
* @property {string} [to]
*/
diff --git a/packages/cli/api/integration/integrationAdd.doc.mjs b/packages/cli/api/integration/integrationAdd.doc.mjs
index 8776628dba..f3a67c1496 100644
--- a/packages/cli/api/integration/integrationAdd.doc.mjs
+++ b/packages/cli/api/integration/integrationAdd.doc.mjs
@@ -67,6 +67,12 @@ export const doc = {
description:
'Existing topic to extend. Only valid for doc, and not with options.replaces.',
},
+ {
+ name: 'options.parent',
+ type: 'string',
+ description:
+ "Namespace of this package to place the doc in, as a guide in its `guides` slot; the namespace doc is written when missing. Only valid for doc, and not with options.replaces or options.extends.",
+ },
{
name: 'options.to',
type: 'string',
diff --git a/packages/cli/api/integration/integrationAddDoc.doc.mjs b/packages/cli/api/integration/integrationAddDoc.doc.mjs
index f97e1aed47..d2f337e3e9 100644
--- a/packages/cli/api/integration/integrationAddDoc.doc.mjs
+++ b/packages/cli/api/integration/integrationAddDoc.doc.mjs
@@ -9,7 +9,7 @@ export const doc = {
displayName: 'integrationAddDoc()',
summary: 'Add a complete reference-doc contribution.',
description:
- 'Creates a valid generic topic, declares the docs root on first use, and supports an intentional replaces or extends relationship.',
+ 'Creates a valid generic topic, declares the docs root on first use, and supports an intentional replaces or extends relationship, or places the doc as a guide in a namespace of the package.',
importPath: '@astryxdesign/cli/api',
signature:
'integrationAddDoc(name: string, options?: IntegrationAddDocOptions): Promise<IntegrationAddResponse>',
@@ -42,6 +42,12 @@ export const doc = {
type: 'string',
description: 'Existing topic this topic extends.',
},
+ {
+ name: 'options.parent',
+ type: 'string',
+ description:
+ "Namespace of this package to place the doc in, as a guide in its `guides` slot; the namespace doc is written when missing, and package.json declares the CLI that reads it as an optional `@astryxdesign/cli` peer. Only valid for doc, and not with options.replaces or options.extends.",
+ },
],
returns: [
{
diff --git a/packages/cli/api/integration/integrationDocConflicts.doc.mjs b/packages/cli/api/integration/integrationDocConflicts.doc.mjs
index 4cebc89c04..e14b42573b 100644
--- a/packages/cli/api/integration/integrationDocConflicts.doc.mjs
+++ b/packages/cli/api/integration/integrationDocConflicts.doc.mjs
@@ -9,7 +9,7 @@ export const doc = {
name: 'integrationDocConflicts',
namespace: 'cli/api',
displayName: 'integrationDocConflicts()',
- summary: 'Classify integration doc overlaps with Core topics.',
+ summary: 'Check an integration\'s docs: the docs tree they add, every link, and overlaps with Core topics.',
description:
'Loads one local or installed integration and classifies Core doc overlaps as ' +
'intentional replacements, intentional extensions, or accidental same-name ' +
diff --git a/packages/cli/api/integration/integrationPackCheck.doc.mjs b/packages/cli/api/integration/integrationPackCheck.doc.mjs
index 7acf10ca3d..2901479e02 100644
--- a/packages/cli/api/integration/integrationPackCheck.doc.mjs
+++ b/packages/cli/api/integration/integrationPackCheck.doc.mjs
@@ -9,7 +9,7 @@ export const doc = {
displayName: 'integrationPackCheck()',
summary: 'Prove an integration package survives npm packing.',
description:
- "Validates the local integration, runs the package lifecycle, packs with npm, checks required files against npm's authoritative tarball list, extracts the real tarball into a scratch consumer, compares local and packed contribution inventories, and resolves every packed component through its documented public import to verify that module exports the component.",
+ "Validates the local integration, runs the package lifecycle, packs with npm, checks required files against npm's authoritative tarball list, extracts the real tarball into a scratch consumer, compares local and packed contribution inventories, and resolves every packed component through its documented public import to verify that module exports the component. A package that ships a namespace doc or a placed guide, or has a template that sets `replaces`, fails unless its `@astryxdesign/cli` peer range admits only CLIs that read them.",
importPath: '@astryxdesign/cli/api',
signature:
'integrationPackCheck(options?: IntegrationPackCheckOptions): Promise<IntegrationPackCheckResponse>',
diff --git a/packages/cli/api/integration/integrationTemplateConflicts.doc.mjs b/packages/cli/api/integration/integrationTemplateConflicts.doc.mjs
index a7972da549..e27193d733 100644
--- a/packages/cli/api/integration/integrationTemplateConflicts.doc.mjs
+++ b/packages/cli/api/integration/integrationTemplateConflicts.doc.mjs
@@ -11,11 +11,12 @@ export const doc = {
name: 'integrationTemplateConflicts',
namespace: 'cli/api',
displayName: 'integrationTemplateConflicts()',
- summary: 'Find integration template ids that also exist in Core.',
+ summary: 'Validate integration template replacements and Core id overlaps.',
description:
- 'Loads one local or installed integration, compares its template ids with the ' +
- 'built-in Core page and block templates, and returns non-blocking conflicts with ' +
- 'the exact package-qualified CLI command required to keep an intentional overlap.',
+ 'Loads one local or installed integration, validates its template replacement ' +
+ 'declarations against the built-in Core page and block templates, and reports ' +
+ 'intentional replacements, missing targets, ambiguous declarations, type ' +
+ 'mismatches, and undeclared same-id conflicts.',
importPath: '@astryxdesign/cli/api',
signature:
'integrationTemplateConflicts(pkg?: string, options?: IntegrationAuthoringOptions): Promise<IntegrationTemplateConflictResponse>',
@@ -38,7 +39,7 @@ export const doc = {
{
type: 'integration.template-conflicts',
description:
- 'The integration identity, structural issues, and every Core template-id conflict with a package-qualified command.',
+ 'The integration identity, structural and replacement-declaration issues, intentional Core replacements, and undeclared same-id conflicts.',
},
],
examples: [
diff --git a/packages/cli/api/integration/pack-check.mjs b/packages/cli/api/integration/pack-check.mjs
index b7af96fb8e..f8f8ddc8ae 100644
--- a/packages/cli/api/integration/pack-check.mjs
+++ b/packages/cli/api/integration/pack-check.mjs
@@ -27,6 +27,11 @@ import {spawnSync} from 'node:child_process';
import jscodeshift from 'jscodeshift';
import {assertWithin} from '../../foundation/fs/path-safety.mjs';
import {resolvePackageDir} from '../../foundation/integrations/integrations.mjs';
+import {
+ docsTreeCliProblem,
+ replacesCliProblem,
+} from '../../foundation/integrations/cli-requirement.mjs';
+import {discoverIntegrationDocs} from '../../foundation/discovery/docs-discovery.mjs';
import {
discoverIntegrationComponents,
resolveIntegrationImportPath,
@@ -591,6 +596,35 @@ export async function integrationPackCheck(options = {}) {
);
}
}
+ // A namespace doc or a placed guide needs a CLI that reads the docs tree
+ // (spec:AST-046 FR11): an older CLI can hide every doc topic the package
+ // ships, so the declared CLI range must admit only CLIs that read it.
+ if (loaded.docs) {
+ const {namespaces, guides} = await discoverIntegrationDocs(loaded).catch(
+ () => ({namespaces: [], guides: []}),
+ );
+ const problem =
+ namespaces.length > 0 || guides.length > 0
+ ? docsTreeCliProblem(pkg)
+ : null;
+ if (problem != null) {
+ issues.push(error('docs_tree_needs_cli', problem));
+ }
+ }
+ // A template that sets `replaces` needs a CLI that reads the field
+ // (spec:AST-035): an older CLI withholds the package's templates and docs.
+ if (loaded.templates) {
+ const found = await discoverIntegrationTemplatesForOne(loaded).catch(
+ () => ({templates: [], errors: []}),
+ );
+ const setsReplaces =
+ found.templates.some(template => template.replaces != null) ||
+ found.errors.some(
+ (/** @type {any} */ issue) => issue.replacementTarget != null,
+ );
+ const problem = setsReplaces ? replacesCliProblem(pkg) : null;
+ if (problem != null) issues.push(error('replaces_needs_cli', problem));
+ }
// Temp resources — always cleaned up
const tgzTmpDir = fs.mkdtempSync(
diff --git a/packages/cli/api/integration/pack-check.test.mjs b/packages/cli/api/integration/pack-check.test.mjs
index 56e29d0311..e8917a8325 100644
--- a/packages/cli/api/integration/pack-check.test.mjs
+++ b/packages/cli/api/integration/pack-check.test.mjs
@@ -280,6 +280,93 @@ describe('integrationPackCheck', () => {
expect(fileErrors.length).toBeGreaterThan(0);
});
+ it('fails a package that ships a namespace doc on a CLI range that cannot read it', async () => {
+ writePackage({manifest: "export default {docs: './docs'};\n", themes: false});
+ fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});
+ fs.writeFileSync(
+ path.join(tmpDir, 'docs', 'acme.doc.mjs'),
+ "export default {type: 'namespace', name: 'acme', title: 'Acme', summary: 'Acme guides.', slots: {guides: {title: 'Guides', accepts: {kinds: ['generic']}}}};\n",
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'docs', 'deploying.doc.mjs'),
+ "export default {type: 'generic', name: 'deploying', title: 'Deploying', description: 'Ship it.', placement: {parent: 'namespace:acme', slot: 'guides'}, sections: [{title: 'Overview', content: [{type: 'prose', text: 'Ship it.'}]}]};\n",
+ );
+ const file = path.join(tmpDir, 'package.json');
+ const peer = (/** @type {string | undefined} */ range) => {
+ const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
+ if (range == null) delete pkg.peerDependencies;
+ else pkg.peerDependencies = {'@astryxdesign/cli': range};
+ fs.writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\n`);
+ };
+ const codes = async () =>
+ (await integrationPackCheck({cwd: tmpDir})).data.issues.map(
+ (/** @type {{code: string}} */ issue) => issue.code,
+ );
+
+ peer(undefined);
+ expect(await codes()).toContain('docs_tree_needs_cli');
+ peer('^0.6.0 || >=0.7.0');
+ expect(await codes()).toContain('docs_tree_needs_cli');
+ peer('>=0.7.0');
+ expect(await codes()).not.toContain('docs_tree_needs_cli');
+ }, 120_000);
+
+ it('fails a package with only a placed guide on a CLI range that cannot read the docs tree, and passes flat topics', async () => {
+ writePackage({manifest: "export default {docs: './docs'};\n", themes: false});
+ fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});
+ fs.writeFileSync(
+ path.join(tmpDir, 'docs', 'notes.doc.mjs'),
+ "export default {type: 'generic', name: 'notes', title: 'Notes', description: 'Notes.', sections: [{title: 'Overview', content: [{type: 'prose', text: 'Notes.'}]}]};\n",
+ );
+ const codes = async () =>
+ (await integrationPackCheck({cwd: tmpDir})).data.issues.map(
+ (/** @type {{code: string}} */ issue) => issue.code,
+ );
+ // Flat topics alone need no CLI peer.
+ expect(await codes()).not.toContain('docs_tree_needs_cli');
+ fs.writeFileSync(
+ path.join(tmpDir, 'docs', 'setup.doc.mjs'),
+ "export default {type: 'generic', name: 'setup', title: 'Setup', description: 'Set up.', placement: {parent: 'namespace:acme', slot: 'guides'}, sections: [{title: 'Overview', content: [{type: 'prose', text: 'Set up.'}]}]};\n",
+ );
+ expect(await codes()).toContain('docs_tree_needs_cli');
+ const file = path.join(tmpDir, 'package.json');
+ const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
+ pkg.peerDependencies = {'@astryxdesign/cli': '>=0.7.0'};
+ fs.writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\n`);
+ expect(await codes()).not.toContain('docs_tree_needs_cli');
+ }, 120_000);
+
+ it('fails a package with a template that sets replaces on a CLI range that rejects the field', async () => {
+ writePackage({manifest: "export default {templates: './templates'};\n", themes: false});
+ fs.mkdirSync(path.join(tmpDir, 'templates'), {recursive: true});
+ fs.writeFileSync(
+ path.join(tmpDir, 'templates', 'acme-shell.doc.mjs'),
+ "export default {type: 'page', name: 'acme-shell', description: 'Acme shell.', replaces: 'shell-side-nav'};\n",
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'templates', 'acme-shell.tsx'),
+ 'export default function AcmeShell() { return null; }\n',
+ );
+ const file = path.join(tmpDir, 'package.json');
+ const peer = (/** @type {string | undefined} */ range) => {
+ const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
+ if (range == null) delete pkg.peerDependencies;
+ else pkg.peerDependencies = {'@astryxdesign/cli': range};
+ fs.writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\n`);
+ };
+ const codes = async () =>
+ (await integrationPackCheck({cwd: tmpDir})).data.issues.map(
+ (/** @type {{code: string}} */ issue) => issue.code,
+ );
+
+ peer(undefined);
+ expect(await codes()).toContain('replaces_needs_cli');
+ peer('^0.6.0');
+ expect(await codes()).toContain('replaces_needs_cli');
+ peer('>=0.7.0');
+ expect(await codes()).not.toContain('replaces_needs_cli');
+ }, 120_000);
+
it('passes when package.json has no files field', async () => {
writePackage({files: undefined});
const result = await integrationPackCheck({cwd: tmpDir});
@@ -288,6 +375,40 @@ describe('integrationPackCheck', () => {
expect(result.data.packable).toBe(true);
});
+ it('detects a lifecycle script that changes packed template replacements', async () => {
+ const script = [
+ "const fs=require('fs')",
+ "const p='templates/acme-shell.template.mjs'",
+ "const s=fs.readFileSync(p,'utf8')",
+ "fs.writeFileSync(p,s.replace('shell-side-nav','shell-top-nav'))",
+ ].join(';');
+ writePackage({
+ manifest: "export default {templates: './templates'};\n",
+ files: ['astryx.integration.mjs', 'templates'],
+ themes: false,
+ scripts: {prepack: `node -e "${script}"`},
+ });
+ fs.mkdirSync(path.join(tmpDir, 'templates'));
+ fs.writeFileSync(
+ path.join(tmpDir, 'templates', 'acme-shell.template.mjs'),
+ "export default {type: 'page', name: 'Acme shell', description: 'Fixture.', replaces: 'shell-side-nav'};\n",
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'templates', 'acme-shell.tsx'),
+ 'export default function AcmeShell() { return null; }\n',
+ );
+
+ const result = await integrationPackCheck({cwd: tmpDir});
+
+ expect(result.data.packable).toBe(false);
+ expect(result.data.issues).toContainEqual(
+ expect.objectContaining({
+ code: 'identity_mismatch',
+ message: expect.stringContaining('acme-shell'),
+ }),
+ );
+ });
+
it('detects a lifecycle script that changes the packed identity', async () => {
const script = [
"const fs=require('fs')",
diff --git a/packages/cli/api/integration/pack-check.type.mjs b/packages/cli/api/integration/pack-check.type.mjs
index 473f3ede4b..72987e6b74 100644
--- a/packages/cli/api/integration/pack-check.type.mjs
+++ b/packages/cli/api/integration/pack-check.type.mjs
@@ -17,6 +17,19 @@
/** @typedef {IntegrationPackCheckResponse} PackCheckResponse */
+/**
+ * Public contribution inventory returned by pack-check. Kept here rather than
+ * importing the runtime inventory module so the type-only `/json` surface does
+ * not pull implementation dependencies into downstream type checking.
+ * @typedef {object} PackCheckContributionIdentities
+ * @property {{slug: string, exportName: string}[]} themes
+ * @property {string[]} components
+ * @property {{id: string, type: string, name: string, replaces?: string}[]} templates
+ * @property {{version: string, id: string}[]} codemods
+ * @property {string[]} docs
+ * @property {string[]} agentDocsAppend
+ */
+
/**
* @typedef {object} PackCheckData
* @property {string|null} name
@@ -24,7 +37,7 @@
* @property {boolean} packable — true when zero error-severity issues
* @property {PackCheckTarball|null} tarball
* @property {PackCheckInventory} inventory
- * @property {{local: import('../../foundation/integrations/contribution-inventory.mjs').ContributionIdentities|null, packed: import('../../foundation/integrations/contribution-inventory.mjs').ContributionIdentities|null}} contributions
+ * @property {{local: PackCheckContributionIdentities|null, packed: PackCheckContributionIdentities|null}} contributions
* @property {import('../../foundation/integrations/issue').AstryxIntegrationIssue[]} issues
*/
diff --git a/packages/cli/api/integration/validate-integration.test.mjs b/packages/cli/api/integration/validate-integration.test.mjs
index 075a357c39..81df01fd16 100644
--- a/packages/cli/api/integration/validate-integration.test.mjs
+++ b/packages/cli/api/integration/validate-integration.test.mjs
@@ -160,7 +160,7 @@ describe('validate-integration API', () => {
fs.mkdirSync(componentsDir);
fs.writeFileSync(
path.join(componentsDir, 'Widget.doc.mjs'),
- `export default {name: 'Widget'};\n`,
+ `export default {name: 'Widget', props: []};\n`,
);
fs.writeFileSync(
path.join(componentsDir, 'Widget.tsx'),
@@ -485,7 +485,7 @@ export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description:
fs.mkdirSync(cDir, {recursive: true});
fs.writeFileSync(
path.join(cDir, 'Widget.doc.mjs'),
- `export default { name: 'Widget' };\n`,
+ `export default { type: 'component', name: 'Widget', props: [] };\n`,
);
fs.writeFileSync(
path.join(cDir, 'Widget.tsx'),
@@ -507,7 +507,7 @@ export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description:
// Doc with no sibling Widget.tsx.
fs.writeFileSync(
path.join(cDir, 'Widget.doc.mjs'),
- `export default { name: 'Widget' };\n`,
+ `export default { type: 'component', name: 'Widget', props: [] };\n`,
);
const result = await validateLocalIntegration(pkgDir);
diff --git a/packages/cli/api/integration/validateIntegration.doc.mjs b/packages/cli/api/integration/validateIntegration.doc.mjs
index b5230e0123..74b160cf6f 100644
--- a/packages/cli/api/integration/validateIntegration.doc.mjs
+++ b/packages/cli/api/integration/validateIntegration.doc.mjs
@@ -60,5 +60,5 @@ export const doc = {
},
],
command: 'doctor integration validate',
- related: ['summarizeIssues', 'doctor integration templates', 'upgrade'],
+ related: ['summarizeIssues', 'integrationTemplateConflicts', 'upgrade'],
};
diff --git a/packages/cli/api/json/index.ts b/packages/cli/api/json/index.ts
index f3d8534383..2d36ad7302 100644
--- a/packages/cli/api/json/index.ts
+++ b/packages/cli/api/json/index.ts
@@ -28,6 +28,8 @@ export type * from '../init/init.type.mjs';
export type * from '../doctor/doctor.type.mjs';
export type * from '../layout/layout.type.mjs';
export type * from '../integration/validate-integration.type.mjs';
+export type * from '../integration/authoring-checks.type.mjs';
+export type * from '../integration/pack-check.type.mjs';
export type * from '../../foundation/response/base';
export type * from '../../foundation/response/error-codes';
export type * from '../../clients/cli/lib/manifest';
diff --git a/packages/cli/api/layout/_adapter.mjs b/packages/cli/api/layout/_adapter.mjs
index 17e333d449..42434cd9af 100644
--- a/packages/cli/api/layout/_adapter.mjs
+++ b/packages/cli/api/layout/_adapter.mjs
@@ -50,7 +50,18 @@ async function loadBlocks(cwd) {
const blocks = [];
try {
const all = await discoverTemplates(cwd);
- for (const t of all) if (t.type === 'block') blocks.push({...t, kind: 'template'});
+ const templates = all.filter(template => template.type === 'block');
+ /** @type {Map<string, import('../../foundation/discovery/template-adapter.mjs').DiscoveredTemplate>} */
+ const byId = new Map();
+ // Exact ids are the fallback. Active replacement aliases override them in a
+ // second pass, matching template() regardless of discovery/display order.
+ for (const template of templates) byId.set(template.dirName, template);
+ for (const template of templates) {
+ if (template.replaces != null) byId.set(template.replaces, template);
+ }
+ for (const [id, template] of byId) {
+ blocks.push({...template, dirName: id, kind: 'template'});
+ }
} catch {
// discovery is best-effort
}
@@ -91,7 +102,10 @@ export function formatIssue(issue) {
* @param {string} expression
* @param {{form?: 'compact'|'outline'|'auto', loose?: boolean, cwd?: string}} [options]
*/
-export async function analyze(expression, {form = 'auto', loose = false, cwd = process.cwd()} = {}) {
+export async function analyze(
+ expression,
+ {form = 'auto', loose = false, cwd = process.cwd()} = {},
+) {
// Validate inputs in the API (not just the CLI): an empty expression or an
// unknown --form must error, not silently parse as an empty/compact layout.
if (typeof expression !== 'string' || expression.trim() === '') {
@@ -108,9 +122,10 @@ export async function analyze(expression, {form = 'auto', loose = false, cwd = p
ERROR_CODES.ERR_INVALID_OPTION,
);
}
- const registry = /** @type {import('../../foundation/xle/xle-ast').Registry} */ (
- /** @type {unknown} */ (await buildRegistry({cwd}))
- );
+ const registry =
+ /** @type {import('../../foundation/xle/xle-ast').Registry} */ (
+ /** @type {unknown} */ (await buildRegistry({cwd}))
+ );
const blocks = await loadBlocks(cwd);
/** @type {import('../../foundation/xle/xle-ast').XLEDoc} */
diff --git a/packages/cli/api/search/search.doc.mjs b/packages/cli/api/search/search.doc.mjs
index 5fe6fef367..56e9fbe4fd 100644
--- a/packages/cli/api/search/search.doc.mjs
+++ b/packages/cli/api/search/search.doc.mjs
@@ -47,14 +47,15 @@ export const doc = {
{
name: 'options.cwd',
type: 'string',
- description: 'Directory to resolve @astryxdesign/core from.',
+ description:
+ "Directory to resolve @astryxdesign/core from. A docs-only search (`type: 'doc'`) does not need it.",
},
],
returns: [
{
type: 'search',
description:
- 'The query echoed back, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit`: each has domain, name, score, reason, description, and follow-up command, plus `import` for components and hooks, `title` for docs, and `displayName` and `kind` for templates.',
+ 'The query echoed back, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit`: each has domain, name, score, reason, description, and follow-up command, plus `import` for components and hooks, `title` for docs, and `displayName` and `kind` for templates. A doc result is the smallest part that answers: one section (with `section`, and a command that reads only it), one docs-tree route, or a topic, whose command lists its sections. `parent` is the command that opens the level above it: the section list of its topic, the namespace a tree node sits in, the Unorganized level for a flat topic, or the topic list for a top-level namespace. Every doc result also carries `package`, the npm package that authored it (for a section, the package its file came from).',
},
],
throws: [
@@ -64,7 +65,7 @@ export const doc = {
},
{
code: 'ERR_CORE_NOT_FOUND',
- when: '@astryxdesign/core cannot be found from the cwd',
+ when: '@astryxdesign/core cannot be found from the cwd, and the search reads it: every `type` but `doc`',
},
],
examples: [
diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjs
index 06ae9d9142..e8f845bcc1 100644
--- a/packages/cli/api/search/search.mjs
+++ b/packages/cli/api/search/search.mjs
@@ -54,7 +54,7 @@ import {readDocView} from '../../foundation/doc-compiler/read.mjs';
import {findCoreDir} from '../../foundation/fs/paths.mjs';
import {
discoverComponents,
- discoverIntegrationComponents,
+ discoverValidIntegrationComponents,
findComponentReadme,
resolveImportPath,
resolveIntegrationImportPath,
@@ -66,7 +66,20 @@ import {
import {loadIntegrationsSafely} from '../component/_adapter.mjs';
import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';
import {discoverTemplates, extractComponents} from '../template/template.mjs';
-import {loadDocsCatalog, lowerTopic} from '../docs/_adapter.mjs';
+import {templateLookupIds} from '../../foundation/discovery/template-adapter.mjs';
+import {
+ guideEntry,
+ loadDocsCatalog,
+ lowerTopic,
+ projectTree,
+ holdsOwnName,
+} from '../docs/_adapter.mjs';
+import {unlinkText} from '../../foundation/doc-compiler/links.mjs';
+import {nodeView} from '../docs/node/node.mjs';
+import {
+ sectionKey,
+ sectionSummary,
+} from '../../foundation/discovery/docs-section-key.mjs';
import {AstryxError} from '../error.mjs';
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
import {setResultCoverage} from './coverage.mjs';
@@ -84,8 +97,18 @@ import {setResultCoverage} from './coverage.mjs';
* @property {string[]} [guidance]
* @property {string} [_import]
* @property {string} [_title]
+ * @property {string} [_topic] - A doc result's topic or docs-tree route.
+ * @property {string} [_section] - A doc result's section key, when it is one section.
+ * @property {string} [_command] - The command that reads exactly this doc part.
+ * @property {string} [_parent] - The command that opens the level above a doc
+ * part: its topic's section list, or the docs-tree namespace it sits in.
+ * @property {string} [_package] - The npm package that authored a docs-tree
+ * doc part. Flat topics carry none: an extension's sections can come from
+ * another package.
* @property {string} [_displayName]
* @property {'page'|'block'} [_kind]
+ * @property {string} [_resultName]
+ * @property {string} [_commandName]
*/
/**
@@ -647,7 +670,8 @@ async function gatherIntegrationComponents(cwd) {
/** @type {Candidate[]} */
const candidates = [];
for (const integration of loadedIntegrations) {
- for (const rec of discoverIntegrationComponents(integration)) {
+ const {components} = await discoverValidIntegrationComponents(integration);
+ for (const rec of components) {
const doc = await loadModuleDoc(rec.docPath);
candidates.push({
domain: 'component',
@@ -730,7 +754,11 @@ async function gatherHooks(coreDir) {
}
/**
- * Build doc-topic candidates: topic name + description + section prose.
+ * Build doc candidates at the grain a reader reads them: each section of a
+ * topic, whose command reads just that section; each topic as a whole, whose
+ * command lists its sections; and each docs-tree node by its route. The tree's
+ * guides split into sections like topics, and its typed docs also match by
+ * their own name, so `assertResponse` finds `cli/api/functions/assert-response`.
*
* Reads the project's catalog rather than the CLI's own docs directory, so a
* topic an integration contributed (or replaced) is searchable exactly like a
@@ -748,38 +776,268 @@ async function gatherDocs(cwd) {
} catch {
return candidates;
}
+ let tree = null;
+ try {
+ tree = await projectTree(catalog);
+ } catch {
+ // `astryx doctor` reports a tree that fails to build; search still
+ // indexes the topics.
+ }
for (const entry of catalog.entries()) {
- let doc = null;
+ // A topic whose name opens another doc (spec:AST-046 FR11) is not
+ // offered: every hit's command must open the hit.
+ if (tree && !holdsOwnName(tree, catalog, entry)) continue;
+ let lowered = null;
try {
- doc = (await lowerTopic(catalog, entry)).doc;
+ lowered = await lowerTopic(catalog, entry);
} catch {
// A topic that cannot be loaded is reported by the commands that own
// integration issues; search just cannot index it.
}
- let description = '';
- /** @type {string[]} */
- const prose = [];
- if (doc) {
- description = doc.description || '';
- for (const section of doc.sections || []) {
- if (section.title) prose.push(section.title);
- for (const block of section.content || []) {
- if (block.type === 'prose' && block.text) prose.push(block.text);
- }
+ const doc = lowered?.doc ?? null;
+ // A flat topic lives in the Unorganized level; its hits say so, and name
+ // the package each section came from.
+ const home = tree?.get(entry.name);
+ const placed = home?.ref?.flatTopic === entry.name ? home : null;
+ /** @type {Map<string, string>} */
+ const packages = new Map([
+ [entry.providerId ?? entry.package, entry.package],
+ ...entry.extensions.map(
+ ext => /** @type {[string, string]} */ ([ext.providerId ?? ext.package, ext.package]),
+ ),
+ ]);
+ candidates.push(
+ ...topicCandidates(
+ entry.name,
+ doc,
+ entry.title,
+ '',
+ placed && tree
+ ? [
+ ...tree.ancestors(placed).map(a => a.title),
+ doc?.title || entry.title || entry.name,
+ ].join(' › ')
+ : undefined,
+ placed ? `astryx docs ${placed.parent}` : undefined,
+ entry.package,
+ key =>
+ packages.get(lowered?.sectionProviders?.[key] ?? '') ?? entry.package,
+ ),
+ );
+ }
+ if (tree == null) return candidates;
+ for (const node of tree.nodes.values()) {
+ // A flat topic is indexed above, as a topic.
+ if (node.ref?.flatTopic) continue;
+ // A tree hit names where it lives: its ancestors' titles, then its own.
+ const path = [...tree.ancestors(node).map(a => a.title), node.title];
+ if (node.kind === 'generic') {
+ let doc = null;
+ try {
+ doc = (await lowerTopic(catalog, guideEntry(node))).doc;
+ } catch {
+ // As above: the owning commands report it.
}
+ candidates.push(
+ ...topicCandidates(
+ node.route,
+ doc,
+ node.title,
+ node.summary,
+ path.join(' › '),
+ node.parent == null ? undefined : `astryx docs ${node.parent}`,
+ node.provider,
+ ),
+ );
+ continue;
+ }
+ const selfDoc = /** @type {any} */ (node.ref)?.selfDoc;
+ // A typed doc's content is what `astryx docs <route>` prints. The first
+ // column of its tables names what the doc defines (an error code, an
+ // option, a parameter), so each is a keyword the doc answers to.
+ /** @type {any[]} */
+ const content = (await nodeView(catalog, tree, node)).content ?? [];
+ /** @type {string[]} */
+ const defined = [];
+ for (const block of content) {
+ if (block.type !== 'table' || !Array.isArray(block.rows)) continue;
+ for (const row of block.rows)
+ if (row[0] != null) defined.push(plain(row[0]));
}
candidates.push({
domain: 'doc',
- name: entry.name,
- keywords: [],
- description,
- prose,
- _title: doc?.title || entry.title || entry.name,
+ name: node.name,
+ keywords: [
+ node.route.slice(node.route.lastIndexOf('/') + 1),
+ ...(Array.isArray(selfDoc?.keywords) ? selfDoc.keywords : []),
+ ...defined,
+ ...codeTerms({content}),
+ ],
+ description: node.summary || '',
+ prose: sectionProse({title: node.title, content}),
+ _topic: node.route,
+ _title: path.join(' › '),
+ _command: `astryx docs ${node.route}`,
+ _parent: node.parent == null ? 'astryx docs' : `astryx docs ${node.parent}`,
+ _package: node.provider,
});
}
return candidates;
}
+/**
+ * The words one section says: its prose, headings, and list items.
+ * @param {any} section
+ * @returns {string[]}
+ */
+function sectionProse(section) {
+ /** @type {string[]} */
+ const prose = [];
+ if (section?.title) prose.push(section.title);
+ for (const block of section?.content || []) {
+ if ((block.type === 'prose' || block.type === 'heading') && block.text) {
+ prose.push(block.text);
+ } else if (block.type === 'list' && Array.isArray(block.items)) {
+ for (const item of block.items) {
+ const text = typeof item === 'string' ? item : item?.text;
+ if (typeof text === 'string') prose.push(text);
+ }
+ } else if (block.type === 'table' && Array.isArray(block.rows)) {
+ for (const row of block.rows) prose.push(row.map(plain).join(' '));
+ } else if (block.type === 'code' && typeof block.code === 'string') {
+ prose.push([block.label, block.code].filter(Boolean).join(' '));
+ }
+ }
+ return prose;
+}
+
+/**
+ * The identifiers a doc part names in code ticks (`token-ref`,
+ * `ERR_UNKNOWN_SECTION`). Each is a keyword: a reader who types one exactly
+ * wants the part that defines or explains it.
+ * @param {any} part - a section, or `{content}` of a typed doc
+ * @returns {string[]}
+ */
+function codeTerms(part) {
+ /** @type {Set<string>} */
+ const terms = new Set();
+ /** @param {unknown} text */
+ const scan = text => {
+ for (const m of String(text ?? '').matchAll(/`([^`\s]{2,40})`/g)) {
+ terms.add(m[1]);
+ }
+ };
+ for (const block of part?.content || []) {
+ if (block.type === 'prose') scan(block.text);
+ else if (block.type === 'list' && Array.isArray(block.items)) {
+ for (const item of block.items) {
+ scan(typeof item === 'string' ? item : item?.text);
+ }
+ } else if (block.type === 'table' && Array.isArray(block.rows)) {
+ for (const row of block.rows) for (const cell of row) scan(cell);
+ }
+ }
+ return [...terms];
+}
+
+/**
+ * The headings inside a section. Each names a subsection, so a query that
+ * names one should find the section as surely as one that names its title.
+ * @param {any} section
+ * @returns {string[]}
+ */
+function headings(section) {
+ return (section?.content || [])
+ .filter(
+ (/** @type {any} */ block) => block.type === 'heading' && block.text,
+ )
+ .map((/** @type {any} */ block) => String(block.text));
+}
+
+/**
+ * A table cell as plain words, without its code ticks.
+ * @param {unknown} cell
+ * @returns {string}
+ */
+function plain(cell) {
+ return unlinkText(String(cell ?? '')).replaceAll('`', '');
+}
+
+/**
+ * The candidates one topic yields: the topic itself, and one per section when
+ * it has more than one. A topic's command lists its sections, and a section's
+ * command reads only that section, so a hit never costs a whole-topic read.
+ * @param {string} name - the topic name, or a placed guide's route
+ * @param {any} doc - the lowered topic, or null when it did not load
+ * @param {string} [title]
+ * @param {string} [summary]
+ * @param {string} [path] - where the topic lives in the docs tree, as titles
+ * joined by ` › `; a flat topic is its own title
+ * @param {string} [parent] - the command that opens the level above the
+ * topic: its namespace, or the Unorganized level for a flat topic
+ * @param {string} [pkg] - the npm package that authored the topic
+ * @param {(key: string) => string} [sectionPackage] - the npm package a
+ * section came from: an extension's section names the extension's package
+ * @returns {Candidate[]}
+ */
+function topicCandidates(
+ name,
+ doc,
+ title,
+ summary = '',
+ path,
+ parent,
+ pkg,
+ sectionPackage,
+) {
+ /** @type {any[]} */
+ const sections = doc?.sections ?? [];
+ const docTitle = path || doc?.title || title || name;
+ const split = sections.length > 1;
+ /** @type {Candidate[]} */
+ const out = [
+ {
+ domain: 'doc',
+ name,
+ keywords: [
+ ...(doc?.title || title ? [doc?.title || title] : []),
+ ...(Array.isArray(doc?.keywords) ? doc.keywords : []),
+ ],
+ description: doc?.description || summary,
+ prose: split
+ ? sections.map(section => section.title).filter(Boolean)
+ : sections.flatMap(sectionProse),
+ _topic: name,
+ _title: docTitle,
+ _command: split ? `astryx docs ${name} --index` : `astryx docs ${name}`,
+ ...(parent ? {_parent: parent} : {}),
+ ...(pkg ? {_package: pkg} : {}),
+ },
+ ];
+ if (!split) return out;
+ for (const section of sections) {
+ const key = sectionKey(section);
+ out.push({
+ domain: 'doc',
+ name: key,
+ keywords: [
+ ...(section.title ? [section.title] : []),
+ ...headings(section),
+ ...codeTerms(section),
+ ],
+ description: sectionSummary(section),
+ prose: sectionProse(section),
+ _topic: name,
+ _section: key,
+ _title: `${docTitle} › ${section.title}`,
+ _command: `astryx docs ${name} ${key}`,
+ _parent: `astryx docs ${name} --index`,
+ ...((sectionPackage?.(key) ?? pkg) ? {_package: sectionPackage?.(key) ?? pkg} : {}),
+ });
+ }
+ return out;
+}
+
/**
* Build template candidates (page + block) from the template discovery API.
* @param {string} cwd
@@ -793,6 +1051,13 @@ async function gatherTemplates(cwd) {
return [];
}
return templates.map(t => {
+ // A replacement's target is its canonical unqualified lookup id. Keep the
+ // integration-owned id as a keyword and response label, but score and print
+ // commands against the id that `template()` resolves back to this entry.
+ // This matters for replacement chains: one replacement's own id can be the
+ // target of another, so using that shadowed id as the command would select
+ // the other template.
+ const commandName = t.replaces ?? t.dirName;
// Blocks ship an authored componentsUsed; page templates don't, so derive
// them from the source. Category words (e.g. "Dashboard - Analytics") are
// strong intent signal for pages, which otherwise only index on name +
@@ -805,6 +1070,7 @@ async function gatherTemplates(cwd) {
const keywords = Array.isArray(t.componentsUsed)
? [...t.componentsUsed]
: [];
+ keywords.push(...templateLookupIds(t).filter(id => id !== commandName));
/** @type {string[]} */
let weakKeywords = [];
if (t.type === 'page') {
@@ -820,12 +1086,14 @@ async function gatherTemplates(cwd) {
}
return {
domain: 'template',
- name: t.dirName,
+ name: commandName,
keywords,
weakKeywords,
description: t.description || '',
_displayName: t.name,
_kind: t.type, // 'page' | 'block'
+ _resultName: t.dirName,
+ _commandName: commandName,
};
});
}
@@ -844,7 +1112,7 @@ async function gatherTemplates(cwd) {
function toResult(c, score, reason, matchedTerms, queryTerms) {
const base = {
domain: c.domain,
- name: c.name,
+ name: c._resultName ?? c.name,
score,
reason,
description: c.description || '',
@@ -866,10 +1134,16 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {
};
break;
case 'doc':
+ // A doc result names its topic or route, plus the section when the
+ // hit is one section; its command reads exactly that part.
result = {
...base,
+ name: c._topic ?? c.name,
+ ...(c._section ? {section: c._section} : {}),
title: c._title,
- command: `astryx docs ${c.name}`,
+ command: c._command ?? `astryx docs ${c.name}`,
+ ...(c._parent ? {parent: c._parent} : {}),
+ ...(c._package ? {package: c._package} : {}),
};
break;
case 'template':
@@ -877,7 +1151,7 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {
...base,
displayName: c._displayName,
kind: c._kind,
- command: `astryx template ${c.name}`,
+ command: `astryx template ${c._commandName ?? c.name} --type ${c._kind}`,
};
break;
default:
@@ -929,8 +1203,11 @@ export async function search(query, options = {}) {
const term = String(query).trim().toLowerCase();
const tokens = tokenizeQuery(term);
- const coreDir = findCoreDir(cwd);
- if (!coreDir) {
+ // `astryx docs` reads docs without @astryxdesign/core, so a docs-only
+ // search must too. Every other domain reads core.
+ const docsOnly = type === 'doc';
+ const coreDir = docsOnly ? null : findCoreDir(cwd);
+ if (!docsOnly && !coreDir) {
throw new AstryxError(
'Could not find @astryxdesign/core package',
undefined,
@@ -942,8 +1219,10 @@ export async function search(query, options = {}) {
/** @param {string} d */
const wants = d => !type || type === d;
const [components, hooks, docTopics, templates] = await Promise.all([
- wants('component') ? gatherComponents(coreDir, cwd) : [],
- wants('hook') ? gatherHooks(coreDir) : [],
+ wants('component')
+ ? gatherComponents(/** @type {string} */ (coreDir), cwd)
+ : [],
+ wants('hook') ? gatherHooks(/** @type {string} */ (coreDir)) : [],
wants('doc') ? gatherDocs(cwd) : [],
wants('template') ? gatherTemplates(cwd) : [],
]);
diff --git a/packages/cli/api/search/search.test.mjs b/packages/cli/api/search/search.test.mjs
index c6a937f12f..aa041c642c 100644
--- a/packages/cli/api/search/search.test.mjs
+++ b/packages/cli/api/search/search.test.mjs
@@ -84,7 +84,8 @@ describe('search leaf — per-domain result fields', () => {
expect(res.import).toMatch(/\S/);
} else if (res.domain === 'doc') {
expect(res.title).toMatch(/\S/);
- expect(res.command).toBe(`astryx docs ${res.name}`);
+ const read = `astryx docs ${res.name}`;
+ expect([read, `${read} --index`, `${read} ${res.section}`]).toContain(res.command);
} else {
expect(res.displayName).toMatch(/\S/);
expect(['page', 'block']).toContain(res.kind);
@@ -93,6 +94,88 @@ describe('search leaf — per-domain result fields', () => {
}, SLOW);
});
+describe('search leaf — docs at the grain a reader reads them', () => {
+ it(
+ 'finds one section of a guide, and a docs-tree leaf by its own name',
+ async () => {
+ const guide = await search('codemod protected files', {cwd, type: 'doc'});
+ expect(guide.data.results.slice(0, 3)).toContainEqual(
+ expect.objectContaining({
+ domain: 'doc',
+ name: 'cli/integrations',
+ section: 'codemods',
+ title: 'Astryx CLI › CLI Integrations › Codemods',
+ parent: 'astryx docs cli/integrations --index',
+ command: 'astryx docs cli/integrations codemods',
+ }),
+ );
+ const block = await search('token-ref', {cwd});
+ expect(block.data.results[0]).toMatchObject({
+ name: 'authoring',
+ section: 'reference-doc',
+ command: 'astryx docs authoring reference-doc',
+ });
+ const fn = await search('assertResponse', {cwd, type: 'doc'});
+ expect(fn.data.results[0]).toMatchObject({
+ name: 'cli/api/functions/assert-response',
+ title: 'Astryx CLI › API › Functions › assertResponse()',
+ parent: 'astryx docs cli/api/functions',
+ command: 'astryx docs cli/api/functions/assert-response',
+ });
+ expect(fn.data.results[0]).not.toHaveProperty('section');
+ },
+ SLOW,
+ );
+
+ it(
+ 'gives a top-level namespace hit the topic list as its parent',
+ async () => {
+ for (const [query, route] of [['unorganized', 'unorganized'], ['Astryx CLI', 'cli']]) {
+ const r = await search(query, {cwd, type: 'doc'});
+ expect(r.data.results).toContainEqual(
+ expect.objectContaining({
+ name: route,
+ command: `astryx docs ${route}`,
+ parent: 'astryx docs',
+ }),
+ );
+ }
+ },
+ SLOW,
+ );
+
+ it(
+ 'points a topic hit at its index, never a whole-topic read',
+ async () => {
+ const r = await search('cli/integrations', {cwd, type: 'doc'});
+ expect(r.data.results[0]).toMatchObject({
+ name: 'cli/integrations',
+ command: 'astryx docs cli/integrations --index',
+ });
+ expect(r.data.results[0]).not.toHaveProperty('section');
+ },
+ SLOW,
+ );
+
+ it(
+ 'searches docs where @astryxdesign/core is not installed',
+ async () => {
+ const bare = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-search-bare-'),
+ );
+ try {
+ const r = await search('assertResponse', {cwd: bare, type: 'doc'});
+ expect(r.data.results[0].name).toBe(
+ 'cli/api/functions/assert-response',
+ );
+ } finally {
+ fs.rmSync(bare, {recursive: true, force: true});
+ }
+ },
+ SLOW,
+ );
+});
+
describe('search leaf — matchCount is the total, not the cap', () => {
it('reports every match while `results` stays bounded by the limit', async () => {
// The regression: `matchCount` used to be `results.length`, so a query
@@ -247,12 +330,18 @@ describe('search leaf — integration components', () => {
);
fs.writeFileSync(
path.join(widgetsDir, 'components', 'FancyGizmo.doc.mjs'),
- `export const docs = {
+ `export default {
+ type: 'component',
name: 'FancyGizmo',
keywords: ['gizmo', 'widget'],
usage: {description: 'A fancy gizmo widget.'},
+ props: [],
};\n`,
);
+ fs.writeFileSync(
+ path.join(widgetsDir, 'components', 'FancyGizmo.tsx'),
+ `export function FancyGizmo() { return null; }\n`,
+ );
return dir;
}
diff --git a/packages/cli/api/search/search.type.mjs b/packages/cli/api/search/search.type.mjs
index 12b1880141..23b868b12f 100644
--- a/packages/cli/api/search/search.type.mjs
+++ b/packages/cli/api/search/search.type.mjs
@@ -16,13 +16,16 @@
* A single ranked search result, tagged with its domain.
* @typedef {object} SearchResultEntry
* @property {SearchDomain} domain - Which content domain this result came from.
- * @property {string} name - Primary identifier (component/hook name, doc topic, template dir).
+ * @property {string} name - Primary identifier (component/hook name, doc topic or docs-tree route, template dir).
* @property {number} score - Relevance score (higher is better).
* @property {string} reason - Human-readable reason the candidate matched (e.g. `keyword "button"`).
* @property {string} description - One-line description, when available.
* @property {string} command - Follow-up command to act on this result (e.g. `astryx component Button`).
* @property {string} [import] - Import path — present for component and hook results.
* @property {string} [title] - Doc title — present for doc results.
+ * @property {string} [section] - Section key — present when a doc result is one section of a topic; `command` reads only that section.
+ * @property {string} [package] - The npm package that authored a doc result; for a section, the package whose file the section came from.
+ * @property {string} [parent] - Command that opens the level above a doc result — its topic's section list for a section, the docs-tree namespace it sits in for a tree node — so a reader can see the siblings and open another.
* @property {string} [displayName] - Friendly display name — present for template results.
* @property {'page' | 'block'} [kind] - Template kind (`page` | `block`) — present for template results.
*/
diff --git a/packages/cli/api/template/list/list.mjs b/packages/cli/api/template/list/list.mjs
index 5462e7335f..47dd96dacd 100644
--- a/packages/cli/api/template/list/list.mjs
+++ b/packages/cli/api/template/list/list.mjs
@@ -32,6 +32,7 @@ export function templateList(templates, options = {}) {
description: t.description,
type: t.type,
package: pkgOf(t),
+ replaces: t.replaces,
category: t.category || undefined,
componentsUsed: t.componentsUsed ?? undefined,
aspectRatio: t.aspectRatio,
diff --git a/packages/cli/api/template/template-integration.test.mjs b/packages/cli/api/template/template-integration.test.mjs
index 8181d00a31..3aee706c93 100644
--- a/packages/cli/api/template/template-integration.test.mjs
+++ b/packages/cli/api/template/template-integration.test.mjs
@@ -12,7 +12,15 @@
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
-import {template} from './template.mjs';
+import {
+ discoverAllWithErrors,
+ discoverCoreTemplates,
+ template,
+} from './template.mjs';
+import {search} from '../search/search.mjs';
+import {build} from '../build/build.mjs';
+import {layoutExpand} from '../layout/layout.mjs';
+import {runCli} from '../../test-utils/run-cli.mjs';
let tmpDir;
let originalCwd;
@@ -50,7 +58,7 @@ function installWidgets(consumerDir) {
}
/** Write a template doc + same-stem source under the templates root. */
-function writeTemplate(pkgDir, id, {kind, body, withSource = true}) {
+function writeTemplate(pkgDir, id, {kind, body, source, withSource = true}) {
const docPath = path.join(pkgDir, 'templates', `${id}.doc.mjs`);
fs.mkdirSync(path.dirname(docPath), {recursive: true});
fs.writeFileSync(
@@ -61,7 +69,32 @@ function writeTemplate(pkgDir, id, {kind, body, withSource = true}) {
if (withSource) {
fs.writeFileSync(
path.join(pkgDir, 'templates', `${id}.tsx`),
- `export default function ${id.replace(/[^a-zA-Z0-9]/g, '')}() { return null; }\n`,
+ source ??
+ `export default function ${id.replace(/[^a-zA-Z0-9]/g, '')}() { return null; }\n`,
+ );
+ }
+}
+
+/**
+ * Set `replaces` on each named template's own doc, declaring the templates
+ * root first when the package has no manifest yet.
+ */
+function declareReplaces(pkgDir, replacements) {
+ const manifest = path.join(pkgDir, 'astryx.integration.mjs');
+ if (!fs.existsSync(manifest)) {
+ fs.writeFileSync(manifest, `export default {templates: './templates'};\n`);
+ }
+ for (const [id, target] of Object.entries(replacements)) {
+ const docPath = path.join(pkgDir, 'templates', `${id}.doc.mjs`);
+ const doc = fs.readFileSync(docPath, 'utf-8');
+ if (!doc.includes('export default {'))
+ throw new Error(`${id}: no doc object`);
+ fs.writeFileSync(
+ docPath,
+ doc.replace(
+ 'export default {',
+ `export default {replaces: ${JSON.stringify(target)}, `,
+ ),
);
}
}
@@ -178,6 +211,26 @@ describe('integration template discovery', () => {
expect(result.data.find(t => t.id === 'untyped')).toBeUndefined();
});
+ it('does not read Object prototype keys as replacements', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ for (const id of ['constructor', 'toString', '__proto__']) {
+ writeTemplate(pkgDir, id, {kind: 'page'});
+ }
+
+ const discovered = await discoverAllWithErrors(tmpDir);
+ expect(
+ discovered.errors.filter(error => error.replacementTarget != null),
+ ).toEqual([]);
+ for (const id of ['constructor', 'toString', '__proto__']) {
+ const entry = discovered.templates.find(
+ template =>
+ template.dirName === id && template.package === '@acme/widgets',
+ );
+ expect(entry).toBeDefined();
+ expect(entry?.replaces).toBeUndefined();
+ }
+ });
+
it('errors with candidates when an id is ambiguous across type/package', async () => {
const pkgDir = installWidgets(tmpDir);
// Same id "hero" as both a page and a block within the integration.
@@ -239,6 +292,972 @@ describe('integration template discovery', () => {
expect(fs.existsSync(path.join(tmpDir, 'dest', 'page.tsx'))).toBe(true);
});
+ it('uses a declared integration replacement by default and keeps the Core original addressable', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'acme-app-shell', {
+ kind: 'page',
+ source:
+ 'export default function AcmeAppShell() { return <nav>AcmeSideNav + AcmeTopNav</nav>; }\n',
+ });
+ declareReplaces(pkgDir, {
+ 'acme-app-shell': 'shell-side-nav',
+ });
+
+ const listed = await template(undefined, {list: true, cwd: tmpDir});
+ expect(
+ listed.data.find(entry => entry.id === 'acme-app-shell'),
+ ).toMatchObject({
+ package: '@acme/widgets',
+ replaces: 'shell-side-nav',
+ });
+ expect(
+ listed.data.find(
+ entry =>
+ entry.id === 'shell-side-nav' &&
+ entry.package === '@astryxdesign/core',
+ ),
+ ).toBeUndefined();
+
+ const selected = await template('shell-side-nav', {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(selected.data.template).toBe('acme-app-shell');
+ expect(selected.data.source).toContain('AcmeSideNav + AcmeTopNav');
+
+ const searched = await search('shell-side-nav', {
+ type: 'template',
+ cwd: tmpDir,
+ });
+ expect(searched.data.results).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({name: 'acme-app-shell'}),
+ ]),
+ );
+
+ const original = await template('shell-side-nav', {
+ package: '@astryxdesign/core',
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(original.data.template).toBe('shell-side-nav');
+ expect(original.data.source).toContain('@astryxdesign/core/SideNav');
+ expect(original.data.source).not.toContain('AcmeSideNav + AcmeTopNav');
+ });
+
+ it('uses canonical replacement resolution for copy collisions', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'acme-app-shell', {kind: 'page'});
+ declareReplaces(pkgDir, {
+ 'acme-app-shell': 'shell-side-nav',
+ });
+ const target = path.join(tmpDir, 'existing');
+ fs.mkdirSync(target);
+ fs.writeFileSync(path.join(target, 'page.tsx'), '// keep me\n');
+
+ const result = await runCli(
+ ['template', 'shell-side-nav', 'existing'],
+ tmpDir,
+ );
+
+ expect(result.status).toBe(1);
+ expect(`${result.stdout}\n${result.stderr}`).toContain(
+ 'Refusing to overwrite existing file',
+ );
+ expect(fs.readFileSync(path.join(target, 'page.tsx'), 'utf-8')).toBe(
+ '// keep me\n',
+ );
+ });
+
+ it('keeps package-scoped lookup exact when one package also owns the Core id', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'acme-app-shell', {
+ kind: 'page',
+ source:
+ "export default function AcmeAppShell() { return 'active replacement'; }\n",
+ });
+ writeTemplate(pkgDir, 'shell-side-nav', {
+ kind: 'page',
+ source:
+ "export default function PackageShellSideNav() { return 'package exact id'; }\n",
+ });
+ declareReplaces(pkgDir, {
+ 'acme-app-shell': 'shell-side-nav',
+ });
+
+ const unqualified = await template('shell-side-nav', {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(unqualified.data.template).toBe('acme-app-shell');
+ expect(unqualified.data.source).toContain('active replacement');
+
+ const packageExact = await template('shell-side-nav', {
+ package: '@acme/widgets',
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(packageExact.data.template).toBe('shell-side-nav');
+ expect(packageExact.data.source).toContain('package exact id');
+
+ const packageOwnId = await template('acme-app-shell', {
+ package: '@acme/widgets',
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(packageOwnId.data.template).toBe('acme-app-shell');
+ expect(packageOwnId.data.source).toContain('active replacement');
+ });
+
+ it('preserves an active replacement whose own id is another active target', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'shell-top-nav', {
+ kind: 'page',
+ source:
+ "export default function FirstReplacement() { return 'first replacement'; }\n",
+ });
+ writeTemplate(pkgDir, 'acme-second-shell', {
+ kind: 'page',
+ source:
+ "export default function SecondReplacement() { return 'second replacement'; }\n",
+ });
+ declareReplaces(pkgDir, {
+ 'shell-top-nav': 'shell-side-nav',
+ 'acme-second-shell': 'shell-top-nav',
+ });
+
+ const first = await template('shell-side-nav', {show: true, cwd: tmpDir});
+ expect(first.data.template).toBe('shell-top-nav');
+ expect(first.data.source).toContain('first replacement');
+
+ const second = await template('shell-top-nav', {show: true, cwd: tmpDir});
+ expect(second.data.template).toBe('acme-second-shell');
+ expect(second.data.source).toContain('second replacement');
+
+ const firstSearch = await search('shell-side-nav', {
+ type: 'template',
+ cwd: tmpDir,
+ });
+ expect(firstSearch.data.results[0]).toMatchObject({
+ name: 'shell-top-nav',
+ command: 'astryx template shell-side-nav --type page',
+ });
+
+ const secondSearch = await search('shell-top-nav', {
+ type: 'template',
+ cwd: tmpDir,
+ });
+ expect(secondSearch.data.results[0]).toMatchObject({
+ name: 'acme-second-shell',
+ command: 'astryx template shell-top-nav --type page',
+ });
+
+ const renderedBuild = await runCli(['build', 'shell-side-nav'], tmpDir);
+ expect(renderedBuild.status).toBe(0);
+ expect(renderedBuild.stdout).toContain(
+ 'template shell-side-nav --type page <path>',
+ );
+ expect(renderedBuild.stdout).not.toContain('template shell-top-nav <path>');
+
+ const listed = await template(undefined, {list: true, cwd: tmpDir});
+ expect(listed.data).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: 'shell-top-nav',
+ replaces: 'shell-side-nav',
+ package: '@acme/widgets',
+ }),
+ expect.objectContaining({
+ id: 'acme-second-shell',
+ replaces: 'shell-top-nav',
+ package: '@acme/widgets',
+ }),
+ ]),
+ );
+ });
+
+ it('keeps an active replacement ahead of an undeclared exact-id template in search', async () => {
+ const active = installWidgets(tmpDir);
+ writeTemplate(active, 'active-shell', {
+ kind: 'page',
+ body: `export default {type: 'page', name: 'ZZZ active shell', description: 'replacement'};\n`,
+ });
+ declareReplaces(active, {'active-shell': 'shell-side-nav'});
+
+ const accidental = path.join(tmpDir, 'node_modules', '@acme', 'extra');
+ fs.mkdirSync(path.join(accidental, 'templates'), {recursive: true});
+ fs.writeFileSync(
+ path.join(accidental, 'package.json'),
+ JSON.stringify({name: '@acme/extra', version: '1.0.0'}),
+ );
+ fs.writeFileSync(
+ path.join(accidental, 'astryx.integration.mjs'),
+ `export default {templates: './templates'};\n`,
+ );
+ writeTemplate(accidental, 'shell-side-nav', {
+ kind: 'page',
+ body: `export default {type: 'page', name: 'AAA accidental shell', description: 'collision'};\n`,
+ });
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default { integrations: ['@acme/widgets', '@acme/extra'] };\n`,
+ );
+
+ const selected = await template('shell-side-nav', {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(selected.data.template).toBe('active-shell');
+ const searched = await search('shell-side-nav', {
+ type: 'template',
+ cwd: tmpDir,
+ });
+ expect(searched.data.results[0]).toMatchObject({
+ name: 'active-shell',
+ command: 'astryx template shell-side-nav --type page',
+ });
+ });
+
+ it('resolves a replacement block through the layout alias', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'acme-card-callout', {
+ kind: 'block',
+ source:
+ 'export default function AcmeCardCallout() { return <span>Acme replacement block</span>; }\n',
+ });
+ declareReplaces(pkgDir, {
+ 'acme-card-callout': 'CardCallout',
+ });
+
+ const accidental = path.join(tmpDir, 'node_modules', '@acme', 'extra');
+ fs.mkdirSync(path.join(accidental, 'templates'), {recursive: true});
+ fs.writeFileSync(
+ path.join(accidental, 'package.json'),
+ JSON.stringify({name: '@acme/extra', version: '1.0.0'}),
+ );
+ fs.writeFileSync(
+ path.join(accidental, 'astryx.integration.mjs'),
+ `export default {templates: './templates'};\n`,
+ );
+ writeTemplate(accidental, 'CardCallout', {
+ kind: 'block',
+ body: `export default {type: 'block', name: 'ZZZ accidental block', description: 'collision'};\n`,
+ source:
+ 'export default function Accidental() { return <span>Accidental block</span>; }\n',
+ });
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default { integrations: ['@acme/widgets', '@acme/extra'] };\n`,
+ );
+
+ const result = await layoutExpand('C{card-callout}', {
+ name: 'ReplacementLayout',
+ cwd: tmpDir,
+ });
+
+ expect(result.data.code).toContain('Acme replacement block');
+ expect(result.data.code).not.toContain('Accidental block');
+ expect(result.data.blocksReferenced).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({name: 'CardCallout', mode: 'splice'}),
+ ]),
+ );
+ }, 30_000);
+
+ it('resolves chained block aliases consistently in template and layout', async () => {
+ const [firstTarget, secondTarget] = (await discoverCoreTemplates()).filter(
+ candidate => candidate.type === 'block',
+ );
+ expect(firstTarget).toBeDefined();
+ expect(secondTarget).toBeDefined();
+
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, secondTarget.dirName, {
+ kind: 'block',
+ source:
+ 'export default function FirstReplacement() { return <span>First chain replacement</span>; }\n',
+ });
+ writeTemplate(pkgDir, 'acme-final-block', {
+ kind: 'block',
+ source:
+ 'export default function FinalReplacement() { return <span>Final chain replacement</span>; }\n',
+ });
+ declareReplaces(pkgDir, {
+ [secondTarget.dirName]: firstTarget.dirName,
+ 'acme-final-block': secondTarget.dirName,
+ });
+
+ const firstTemplate = await template(firstTarget.dirName, {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(firstTemplate.data.source).toContain('First chain replacement');
+ const layoutId = id =>
+ id.replace(/([a-z0-9])([A-Z])/gu, '$1-$2').toLowerCase();
+ const firstLayout = await layoutExpand(
+ `C{${layoutId(firstTarget.dirName)}}`,
+ {
+ cwd: tmpDir,
+ },
+ );
+ expect(firstLayout.data.code).toContain('First chain replacement');
+ expect(firstLayout.data.code).not.toContain('Final chain replacement');
+
+ const secondTemplate = await template(secondTarget.dirName, {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(secondTemplate.data.source).toContain('Final chain replacement');
+ const secondLayout = await layoutExpand(
+ `C{${layoutId(secondTarget.dirName)}}`,
+ {
+ cwd: tmpDir,
+ },
+ );
+ expect(secondLayout.data.code).toContain('Final chain replacement');
+ }, 30_000);
+
+ it('keeps the old discovery behavior when no replacement is declared', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'acme-app-shell', {kind: 'page'});
+
+ const core = await template('shell-side-nav', {show: true, cwd: tmpDir});
+ expect(core.data.template).toBe('shell-side-nav');
+ const integration = await template('acme-app-shell', {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(integration.data.template).toBe('acme-app-shell');
+ });
+
+ it('fails an ambiguous replacement closed and reports every declaration', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'acme-app-shell-a', {kind: 'page'});
+ writeTemplate(pkgDir, 'acme-app-shell-b', {kind: 'page'});
+ declareReplaces(pkgDir, {
+ 'acme-app-shell-a': 'shell-side-nav',
+ 'acme-app-shell-b': 'shell-side-nav',
+ });
+
+ const discovered = await discoverAllWithErrors(tmpDir);
+ expect(
+ discovered.errors.filter(
+ error => error.code === 'ambiguous_template_replacement',
+ ),
+ ).toHaveLength(2);
+ const selected = await template('shell-side-nav', {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(selected.data.template).toBe('shell-side-nav');
+ expect(
+ discovered.templates.filter(template =>
+ template.dirName.startsWith('acme-app-shell-'),
+ ),
+ ).toHaveLength(2);
+ });
+
+ it('does not activate a replacement when the same package also declares a missing template', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'acme-app-shell', {kind: 'page'});
+ writeTemplate(pkgDir, 'missing-app-shell', {
+ kind: 'page',
+ withSource: false,
+ });
+ declareReplaces(pkgDir, {
+ 'acme-app-shell': 'shell-side-nav',
+ 'missing-app-shell': 'shell-side-nav',
+ });
+
+ const discovered = await discoverAllWithErrors(tmpDir);
+ expect(discovered.errors).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'invalid_template_replacement',
+ template: 'missing-app-shell',
+ }),
+ ]),
+ );
+ const selected = await template('shell-side-nav', {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(selected.data.template).toBe('shell-side-nav');
+ const own = await template('acme-app-shell', {show: true, cwd: tmpDir});
+ expect(own.data.template).toBe('acme-app-shell');
+ });
+
+ it('keeps Core when a template whose metadata does not load declares the same replacement', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'acme-app-shell', {kind: 'page'});
+ writeTemplate(pkgDir, 'broken-app-shell', {
+ kind: 'page',
+ body: "export default {type: 'page', name: 'broken', description: 'b', bogusField: 1};\n",
+ });
+ writeTemplate(pkgDir, 'unparsable-app-shell', {
+ kind: 'page',
+ body: "export default {replaces: 'shell-side-nav', type: 'page' name: 'x'};\n",
+ });
+ declareReplaces(pkgDir, {
+ 'acme-app-shell': 'shell-side-nav',
+ 'broken-app-shell': 'shell-side-nav',
+ });
+
+ const discovered = await discoverAllWithErrors(tmpDir);
+ for (const id of ['broken-app-shell', 'unparsable-app-shell']) {
+ expect(discovered.errors).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'invalid_template_replacement',
+ template: id,
+ replacementTarget: 'shell-side-nav',
+ }),
+ ]),
+ );
+ }
+ const selected = await template('shell-side-nav', {show: true, cwd: tmpDir});
+ expect(selected.data.template).toBe('shell-side-nav');
+ });
+
+ it('keeps Core when an installed .doc.ts template with invalid metadata computes its replacement', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'acme-app-shell', {kind: 'page'});
+ declareReplaces(pkgDir, {'acme-app-shell': 'shell-side-nav'});
+ fs.writeFileSync(
+ path.join(pkgDir, 'templates', 'ts-app-shell.doc.ts'),
+ "const target: string = 'shell-side-nav';\nexport default {replaces: target, type: 'page', name: 'ts', description: 'd', bogusField: 1};\n",
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'templates', 'ts-app-shell.tsx'),
+ 'export default function TsAppShell() { return null; }\n',
+ );
+ const discovered = await discoverAllWithErrors(tmpDir);
+ expect(discovered.errors).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'invalid_template_replacement',
+ template: 'ts-app-shell',
+ replacementTarget: 'shell-side-nav',
+ }),
+ ]),
+ );
+ const selected = await template('shell-side-nav', {show: true, cwd: tmpDir});
+ expect(selected.data.template).toBe('shell-side-nav');
+ });
+
+ it('keeps --json stdout clean when an unusable template doc writes as it loads', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.integration.mjs'),
+ "export default {templates: './local-templates'};\n",
+ );
+ fs.mkdirSync(path.join(tmpDir, 'local-templates'), {recursive: true});
+ fs.writeFileSync(
+ path.join(tmpDir, 'local-templates', 'acme-shell.doc.ts'),
+ "process.stdout.write('HELLO-FROM-DOC\\n');\nexport default {name: 'acme-shell', description: 'Acme shell.', replaces: 'dashboard'};\n",
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'local-templates', 'acme-shell.tsx'),
+ 'export default function AcmeShell() { return null; }\n',
+ );
+ const result = await runCli(['--json', 'template', '--list'], tmpDir);
+ expect(result.stdout).not.toContain('HELLO-FROM-DOC');
+ // One clean JSON envelope, and the doc was read: its replacement shows.
+ const envelope = JSON.parse(result.stdout);
+ expect(envelope.type).toBe('template.list');
+ const discovered = await discoverAllWithErrors(tmpDir);
+ expect(discovered.errors).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({template: 'acme-shell', replacementTarget: 'dashboard'}),
+ ]),
+ );
+ });
+
+ it('lets the later configured package win a shared replacement target with a warning', async () => {
+ const first = installWidgets(tmpDir);
+ writeTemplate(first, 'acme-app-shell-a', {
+ kind: 'page',
+ source:
+ "export default function AcmeAppShellA() { return 'first replacement'; }\n",
+ });
+ declareReplaces(first, {
+ 'acme-app-shell-a': 'shell-side-nav',
+ });
+
+ const second = path.join(tmpDir, 'node_modules', '@acme', 'extra');
+ fs.mkdirSync(path.join(second, 'templates'), {recursive: true});
+ fs.writeFileSync(
+ path.join(second, 'package.json'),
+ JSON.stringify({name: '@acme/extra', version: '1.0.0'}),
+ );
+ writeTemplate(second, 'acme-app-shell-b', {
+ kind: 'page',
+ source:
+ "export default function AcmeAppShellB() { return 'later replacement'; }\n",
+ });
+ declareReplaces(second, {
+ 'acme-app-shell-b': 'shell-side-nav',
+ });
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default { integrations: ['@acme/widgets', '@acme/extra'] };\n`,
+ );
+
+ const discovered = await discoverAllWithErrors(tmpDir);
+ expect(discovered.errors).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'ambiguous_template_replacement',
+ severity: 'warning',
+ package: '@acme/extra',
+ }),
+ ]),
+ );
+ const selected = await template('shell-side-nav', {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(selected.data.template).toBe('acme-app-shell-b');
+ expect(selected.data.source).toContain('later replacement');
+
+ const command = await runCli(['template', 'shell-side-nav'], tmpDir);
+ expect(command.status).toBe(0);
+ expect(command.stderr).toContain('@acme/extra has 1 integration issue');
+ expect(command.stderr).toContain('astryx doctor');
+
+ const doctor = await runCli(['doctor'], tmpDir);
+ expect(doctor.status).toBe(0);
+ expect(doctor.stdout).toContain('configured later');
+ });
+
+ it('keeps an explicitly configured replacement ahead of an autolinked one', async () => {
+ const explicit = installWidgets(tmpDir);
+ writeTemplate(explicit, 'explicit-shell', {
+ kind: 'page',
+ source:
+ "export default function ExplicitShell() { return 'explicit replacement'; }\n",
+ });
+ declareReplaces(explicit, {
+ 'explicit-shell': 'shell-side-nav',
+ });
+
+ const implicit = path.join(tmpDir, 'node_modules', '@acme', 'implicit');
+ fs.mkdirSync(path.join(implicit, 'templates'), {recursive: true});
+ fs.writeFileSync(
+ path.join(implicit, 'package.json'),
+ JSON.stringify({name: '@acme/implicit', version: '1.0.0'}),
+ );
+ writeTemplate(implicit, 'implicit-shell', {
+ kind: 'page',
+ source:
+ "export default function ImplicitShell() { return 'implicit replacement'; }\n",
+ });
+ declareReplaces(implicit, {
+ 'implicit-shell': 'shell-side-nav',
+ });
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({
+ name: 'consumer',
+ dependencies: {
+ '@acme/widgets': '1.0.0',
+ '@acme/implicit': '1.0.0',
+ },
+ }),
+ );
+
+ const discovered = await discoverAllWithErrors(tmpDir);
+ expect(discovered.errors).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'ambiguous_template_replacement',
+ severity: 'warning',
+ package: '@acme/widgets',
+ message: expect.stringContaining('explicitly configured'),
+ }),
+ ]),
+ );
+ const selected = await template('shell-side-nav', {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(selected.data.template).toBe('explicit-shell');
+ expect(selected.data.source).toContain('explicit replacement');
+ });
+
+ it('describes precedence truthfully when only autolinked packages conflict', async () => {
+ const first = installWidgets(tmpDir);
+ writeTemplate(first, 'first-shell', {kind: 'page'});
+ declareReplaces(first, {
+ 'first-shell': 'shell-side-nav',
+ });
+
+ const second = path.join(tmpDir, 'node_modules', '@acme', 'implicit');
+ fs.mkdirSync(path.join(second, 'templates'), {recursive: true});
+ fs.writeFileSync(
+ path.join(second, 'package.json'),
+ JSON.stringify({name: '@acme/implicit', version: '1.0.0'}),
+ );
+ writeTemplate(second, 'second-shell', {kind: 'page'});
+ declareReplaces(second, {
+ 'second-shell': 'shell-side-nav',
+ });
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ 'export default {};\n',
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({
+ name: 'consumer',
+ dependencies: {
+ '@acme/widgets': '1.0.0',
+ '@acme/implicit': '1.0.0',
+ },
+ }),
+ );
+
+ const discovered = await discoverAllWithErrors(tmpDir);
+ const warning = discovered.errors.find(
+ error => error.code === 'ambiguous_template_replacement',
+ );
+
+ expect(warning?.package).toBe('@acme/implicit');
+ expect(warning?.message).toContain(
+ 'listed later in package.json dependencies',
+ );
+ expect(warning?.message).toContain('astryx.config');
+ expect(warning?.message).not.toContain('configured later');
+ });
+
+ it('does not let an invalid autolinked declaration disable an explicit replacement', async () => {
+ const explicit = installWidgets(tmpDir);
+ writeTemplate(explicit, 'explicit-shell', {
+ kind: 'page',
+ source:
+ "export default function ExplicitShell() { return 'explicit replacement'; }\n",
+ });
+ declareReplaces(explicit, {
+ 'explicit-shell': 'shell-side-nav',
+ });
+
+ const implicit = path.join(tmpDir, 'node_modules', '@acme', 'implicit');
+ fs.mkdirSync(path.join(implicit, 'templates'), {recursive: true});
+ fs.writeFileSync(
+ path.join(implicit, 'package.json'),
+ JSON.stringify({name: '@acme/implicit', version: '1.0.0'}),
+ );
+ writeTemplate(implicit, 'wrong-kind-shell', {kind: 'block'});
+ declareReplaces(implicit, {
+ 'wrong-kind-shell': 'shell-side-nav',
+ });
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({
+ name: 'consumer',
+ dependencies: {
+ '@acme/widgets': '1.0.0',
+ '@acme/implicit': '1.0.0',
+ },
+ }),
+ );
+
+ const discovered = await discoverAllWithErrors(tmpDir);
+ expect(discovered.errors).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'invalid_template_replacement',
+ package: '@acme/implicit',
+ }),
+ ]),
+ );
+ const selected = await template('shell-side-nav', {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(selected.data.template).toBe('explicit-shell');
+ });
+
+ it('fails closed when an earlier package has an invalid replacement for the winning target', async () => {
+ const first = installWidgets(tmpDir);
+ writeTemplate(first, 'wrong-kind-shell', {kind: 'block'});
+ declareReplaces(first, {
+ 'wrong-kind-shell': 'shell-side-nav',
+ });
+
+ const second = path.join(tmpDir, 'node_modules', '@acme', 'extra');
+ fs.mkdirSync(path.join(second, 'templates'), {recursive: true});
+ fs.writeFileSync(
+ path.join(second, 'package.json'),
+ JSON.stringify({name: '@acme/extra', version: '1.0.0'}),
+ );
+ writeTemplate(second, 'valid-shell', {kind: 'page'});
+ declareReplaces(second, {
+ 'valid-shell': 'shell-side-nav',
+ });
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default { integrations: ['@acme/widgets', '@acme/extra'] };\n`,
+ );
+
+ const discovered = await discoverAllWithErrors(tmpDir);
+ expect(discovered.errors).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'invalid_template_replacement',
+ package: '@acme/widgets',
+ }),
+ ]),
+ );
+ const selected = await template('shell-side-nav', {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(selected.data.template).toBe('shell-side-nav');
+ });
+
+ it('reports a missing Core target and leaves the integration template available by its own id', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'acme-app-shell', {kind: 'page'});
+ declareReplaces(pkgDir, {
+ 'acme-app-shell': 'missing-core-shell',
+ });
+
+ const discovered = await discoverAllWithErrors(tmpDir);
+ expect(discovered.errors).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'missing_template_replacement_target',
+ template: 'acme-app-shell',
+ }),
+ ]),
+ );
+ const integration = await template('acme-app-shell', {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(integration.data.template).toBe('acme-app-shell');
+ const listed = await template(undefined, {
+ list: true,
+ package: '@acme/widgets',
+ cwd: tmpDir,
+ });
+ expect(
+ listed.data.find(entry => entry.id === 'acme-app-shell')?.replaces,
+ ).toBeUndefined();
+ });
+
+ it('reports a missing self-id target without hiding the integration template', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'ghost-shell', {kind: 'page'});
+ declareReplaces(pkgDir, {
+ 'ghost-shell': 'ghost-shell',
+ });
+
+ const discovered = await discoverAllWithErrors(tmpDir);
+ expect(discovered.errors).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'missing_template_replacement_target',
+ template: 'ghost-shell',
+ replacementTarget: 'ghost-shell',
+ }),
+ ]),
+ );
+ expect(
+ discovered.templates.find(
+ candidate =>
+ candidate.dirName === 'ghost-shell' &&
+ candidate.package === '@acme/widgets',
+ ),
+ ).toBeDefined();
+
+ const selected = await template('ghost-shell', {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(selected.data.template).toBe('ghost-shell');
+ expect(selected.data.source).toContain('ghostshell');
+ });
+
+ it('reports a replacement whose kind does not match Core', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'acme-app-shell', {kind: 'block'});
+ declareReplaces(pkgDir, {
+ 'acme-app-shell': 'shell-side-nav',
+ });
+
+ const discovered = await discoverAllWithErrors(tmpDir);
+ expect(discovered.errors).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'invalid_template_replacement',
+ template: 'acme-app-shell',
+ }),
+ ]),
+ );
+ const selected = await template('shell-side-nav', {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(selected.data.template).toBe('shell-side-nav');
+ });
+
+ it('falls back to Core for a rejected same-id replacement while package lookup keeps the integration template', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'shell-side-nav', {kind: 'block'});
+ declareReplaces(pkgDir, {
+ 'shell-side-nav': 'shell-side-nav',
+ });
+
+ const selected = await template('shell-side-nav', {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(selected.data.template).toBe('shell-side-nav');
+ expect(selected.data.type).toBe('page');
+
+ const integration = await template('shell-side-nav', {
+ package: '@acme/widgets',
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(integration.data.template).toBe('shell-side-nav');
+ expect(integration.data.type).toBe('block');
+
+ const block = await template('shell-side-nav', {
+ type: 'block',
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(block.data.template).toBe('shell-side-nav');
+ expect(block.data.type).toBe('block');
+
+ const listedBlocks = await template(undefined, {
+ list: true,
+ type: 'block',
+ cwd: tmpDir,
+ });
+ expect(listedBlocks.data).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: 'shell-side-nav',
+ type: 'block',
+ package: '@acme/widgets',
+ }),
+ ]),
+ );
+
+ const searched = await search('shell-side-nav', {
+ type: 'template',
+ limit: 100,
+ cwd: tmpDir,
+ });
+ const sameId = searched.data.results.filter(
+ result => result.name === 'shell-side-nav',
+ );
+ expect(sameId).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ kind: 'page',
+ command: 'astryx template shell-side-nav --type page',
+ }),
+ expect.objectContaining({
+ kind: 'block',
+ command: 'astryx template shell-side-nav --type block',
+ }),
+ ]),
+ );
+
+ const kit = await build('shell-side-nav', {
+ type: 'template',
+ limit: 100,
+ cwd: tmpDir,
+ });
+ expect(kit.type).toBe('build.kit');
+ if (kit.type !== 'build.kit') throw new Error('expected build.kit');
+ expect(kit.data.blocks).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: 'shell-side-nav',
+ command: 'astryx template shell-side-nav --type block',
+ }),
+ ]),
+ );
+ });
+
+ it('round-trips both kinds when a block replacement shadows a page with the same id', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'acme-callout', {
+ kind: 'block',
+ source:
+ "export default function AcmeCallout() { return 'replacement block'; }\n",
+ });
+ writeTemplate(pkgDir, 'CardCallout', {
+ kind: 'page',
+ source:
+ "export default function CardCalloutPage() { return 'ordinary page'; }\n",
+ });
+ declareReplaces(pkgDir, {
+ 'acme-callout': 'CardCallout',
+ });
+
+ const bare = await template('CardCallout', {show: true, cwd: tmpDir});
+ expect(bare.data.template).toBe('acme-callout');
+ expect(bare.data.type).toBe('block');
+
+ const page = await template('CardCallout', {
+ type: 'page',
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(page.data.template).toBe('CardCallout');
+ expect(page.data.type).toBe('page');
+
+ const searched = await search('CardCallout', {
+ type: 'template',
+ limit: 100,
+ cwd: tmpDir,
+ });
+ expect(searched.data.results).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: 'CardCallout',
+ kind: 'page',
+ command: 'astryx template CardCallout --type page',
+ }),
+ expect.objectContaining({
+ name: 'acme-callout',
+ kind: 'block',
+ command: 'astryx template CardCallout --type block',
+ }),
+ ]),
+ );
+
+ const kit = await build('CardCallout', {
+ type: 'template',
+ limit: 100,
+ cwd: tmpDir,
+ });
+ expect(kit.type).toBe('build.kit');
+ if (kit.type !== 'build.kit') throw new Error('expected build.kit');
+ expect(kit.data.pages).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: 'CardCallout',
+ command: 'astryx template CardCallout --type page',
+ }),
+ ]),
+ );
+ expect(kit.data.blocks).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: 'acme-callout',
+ command: 'astryx template CardCallout --type block',
+ }),
+ ]),
+ );
+ });
+
it('copies a block template into a directory as <id-basename>.tsx', async () => {
const pkgDir = installWidgets(tmpDir);
writeTemplate(pkgDir, 'marketing/hero', {kind: 'block'});
diff --git a/packages/cli/api/template/template.doc.mjs b/packages/cli/api/template/template.doc.mjs
index 76d6d8112f..d14ded4b05 100644
--- a/packages/cli/api/template/template.doc.mjs
+++ b/packages/cli/api/template/template.doc.mjs
@@ -17,15 +17,27 @@ export const doc = {
description:
'One entry point for the template family: with no name it lists the discovered ' +
"templates; with a name it returns that template's source, a layout skeleton, or " +
- 'scaffolds it into the project. Templates are discovered across core, external ' +
- 'packages, and integrations, so the same id can appear in more than one place; ' +
- 'narrow an ambiguous name with type and/or package. The cdn option writes the ' +
- 'annotated no-build-step CDN starter page, which ships as an asset rather than as ' +
+ 'scaffolds it into the project. A configured integration may replace a Core ' +
+ 'template id for unqualified discovery and lookup; package selection still ' +
+ 'addresses the Core original. Other duplicate ids remain ambiguous and can be ' +
+ 'narrowed by type and/or package. The cdn option writes the annotated ' +
+ 'no-build-step CDN starter page, which ships as an asset rather than as ' +
'a discovered template.',
importPath: '@astryxdesign/cli/api',
signature:
'template(name?: string, options?: TemplateOptions): Promise<TemplateListResponse | TemplateShowResponse | TemplateSkeletonResponse | TemplateCopyResponse | TemplateCdnResponse>',
- keywords: ['template', 'scaffold', 'page', 'block', 'skeleton', 'starter', 'cdn', 'esm', 'importmap', 'no-build'],
+ keywords: [
+ 'template',
+ 'scaffold',
+ 'page',
+ 'block',
+ 'skeleton',
+ 'starter',
+ 'cdn',
+ 'esm',
+ 'importmap',
+ 'no-build',
+ ],
params: [
{
name: 'name',
@@ -70,7 +82,7 @@ export const doc = {
name: 'options.package',
type: 'string',
description:
- 'Narrow lookups to templates from a specific owning package (core templates report @astryxdesign/core).',
+ 'Narrow lookups to templates from a specific owning package. Without it, a valid integration replacement is selected for the Core id; use @astryxdesign/core to select the original.',
},
{
name: 'options.targetPath',
@@ -96,7 +108,7 @@ export const doc = {
{
type: 'template.list',
description:
- 'Every discovered template (page + block); each entry carries id, name, description, kind, owning package, optional category and componentsUsed, and readiness flags. Filtered by type/package when provided.',
+ 'The effective templates (page + block); a valid integration replacement takes the place of its Core target and carries `replaces`. Pass `package` to list one package, including replaced Core originals.',
},
{
type: 'template.show',
@@ -143,7 +155,15 @@ export const doc = {
],
examples: [
{label: 'List templates', code: 'const {data} = await template();'},
+ {
+ label: 'List exact Core ids',
+ code: "await template(undefined, {list: true, package: '@astryxdesign/core'});",
+ },
{label: 'Show source', code: "await template('dashboard');"},
+ {
+ label: 'Select a replaced Core original',
+ code: "await template('shell-side-nav', {package: '@astryxdesign/core'});",
+ },
{
label: 'Layout skeleton',
code: "await template('dashboard', {skeleton: true});",
diff --git a/packages/cli/api/template/template.mjs b/packages/cli/api/template/template.mjs
index 36459bc727..77afdef1c1 100644
--- a/packages/cli/api/template/template.mjs
+++ b/packages/cli/api/template/template.mjs
@@ -15,7 +15,13 @@
* ./list, ./show, ./skeleton, ./copy, ./cdn and shared discovery in foundation/discovery.
*/
-import {discoverAll, pkgOf} from '../../foundation/discovery/template-adapter.mjs';
+import {
+ discoverAll,
+ discoverAllResolved,
+ discoverAllUnresolved,
+ pkgOf,
+ templateLookupIds,
+} from '../../foundation/discovery/template-adapter.mjs';
import {AstryxError} from '../error.mjs';
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
import {templateList} from './list/list.mjs';
@@ -88,18 +94,49 @@ export async function template(name, options = {}) {
});
}
- const templates = await discoverAll(cwd);
+ const templates =
+ packageFilter === '@astryxdesign/core'
+ ? await discoverAllUnresolved(cwd)
+ : packageFilter
+ ? await discoverAllResolved(cwd)
+ : await discoverAll(cwd);
if (list || (!name && !skeleton)) {
return templateList(templates, {type, package: packageFilter});
}
- // Resolve `name` to a single template. The same id can appear across types
- // and/or packages (e.g. a core "hero" page and an integration "hero"
- // block); narrow with --type / --package.
- let candidates = templates.filter(t => t.dirName === name);
- if (type) candidates = candidates.filter(t => t.type === type);
- if (packageFilter) candidates = candidates.filter(t => pkgOf(t) === packageFilter);
+ // Resolve `name` to a single template. Without an explicit package, an active
+ // integration replacement owns the Core id it names. Package-qualified lookup
+ // stays exact, which keeps the original addressable as
+ // `--package @astryxdesign/core`.
+ let pool = templates;
+ if (type) pool = pool.filter(t => t.type === type);
+ if (packageFilter) pool = pool.filter(t => pkgOf(t) === packageFilter);
+ // With no name there is nothing to replace; `--skeleton` alone must still
+ // fail as an unknown template.
+ const replacements =
+ packageFilter || name == null ? [] : pool.filter(t => t.replaces === name);
+ let candidates = packageFilter
+ ? pool.filter(t => t.dirName === (name ?? ''))
+ : replacements.length > 0
+ ? replacements
+ : pool.filter(t => templateLookupIds(t).includes(name ?? ''));
+
+ // A rejected same-id declaration must not displace Core for the bare command,
+ // but a different-kind integration template remains reachable with --type.
+ if (!packageFilter && !type && candidates.length > 1) {
+ const core = candidates.filter(t => pkgOf(t) === '@astryxdesign/core');
+ const rejected = candidates.filter(t => pkgOf(t) !== '@astryxdesign/core');
+ if (
+ core.length === 1 &&
+ rejected.length === candidates.length - 1 &&
+ rejected.every(
+ t => t.replacementRejected && t.replacementTarget === (name ?? ''),
+ )
+ ) {
+ candidates = core;
+ }
+ }
if (name && candidates.length === 0) {
throw new AstryxError(
diff --git a/packages/cli/api/template/template.type.mjs b/packages/cli/api/template/template.type.mjs
index 7f82f7c834..b4418f39aa 100644
--- a/packages/cli/api/template/template.type.mjs
+++ b/packages/cli/api/template/template.type.mjs
@@ -31,6 +31,7 @@
* @property {string} description
* @property {'page' | 'block'} type
* @property {string} package - Owning package; core (built-in) templates report '@astryxdesign/core'.
+ * @property {string} [replaces] - Core template id this integration template replaces by default.
* @property {string} [category] - Optional grouping/category label.
* @property {string[]} [componentsUsed] - Component display names the template composes.
* @property {number} [aspectRatio] - Block preview width/height ratio.
@@ -93,8 +94,8 @@
* @property {boolean} [skeleton]
* @property {boolean} [show]
* @property {boolean | string} [cdn] Write the no-build-step CDN starter page instead of resolving a template. A string is used as the destination path.
- * @property {'page' | 'block'} [type] Filter templates by kind: 'page' or 'block'. Only applies to list views.
- * @property {string} [package] Narrow to templates from a specific package (id-only lookups across packages are ambiguous).
+ * @property {'page' | 'block'} [type] Filter templates by kind: 'page' or 'block'. Narrows both list and direct lookup.
+ * @property {string} [package] Narrow to templates from a specific package. Without it, a valid integration replacement is selected for the Core id; @astryxdesign/core explicitly selects the original.
* @property {string} [targetPath]
* @property {boolean} [overwrite] Overwrite an existing target file instead of erroring (ERR_FILE_EXISTS).
* @property {string} [cwd]
diff --git a/packages/cli/api/theme/template/template.test.mjs b/packages/cli/api/theme/template/template.test.mjs
index 267c30e3d7..c08692055d 100644
--- a/packages/cli/api/theme/template/template.test.mjs
+++ b/packages/cli/api/theme/template/template.test.mjs
@@ -13,6 +13,7 @@ import {describe, it, expect, beforeEach, afterEach} from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
+import {themeTemplate as publicThemeTemplate} from '../../index.mjs';
import {themeTemplate, THEME_TEMPLATE_DEFAULT_PATH} from './template.mjs';
import {isErrorCode} from '../../../foundation/response/error-codes.mjs';
@@ -25,6 +26,10 @@ afterEach(() => {
});
describe('themeTemplate()', () => {
+ it('is available through the public API entry point', () => {
+ expect(publicThemeTemplate).toBe(themeTemplate);
+ });
+
it('writes the template and returns a theme.template receipt', () => {
const res = themeTemplate({cwd: tmpDir});
diff --git a/packages/cli/api/theme/themeTemplate.doc.mjs b/packages/cli/api/theme/themeTemplate.doc.mjs
index 292b3b8f16..984cb5d329 100644
--- a/packages/cli/api/theme/themeTemplate.doc.mjs
+++ b/packages/cli/api/theme/themeTemplate.doc.mjs
@@ -24,7 +24,7 @@ export const doc = {
'`overwrite`, so it is safe to re-run.',
importPath: '@astryxdesign/cli/api',
signature:
- 'themeTemplate(options?: {targetPath?: string, overwrite?: boolean, cwd?: string}): ThemeNewResponse',
+ 'themeTemplate(options?: {targetPath?: string, overwrite?: boolean, cwd?: string}): ThemeTemplateResponse',
keywords: ['theme', 'template', 'starter', 'defineTheme', 'scaffold', 'reference', 'tokens'],
params: [
{
diff --git a/packages/cli/assets/docs/cli.doc.mjs b/packages/cli/assets/docs/cli.doc.mjs
deleted file mode 100644
index afa9ec2b40..0000000000
--- a/packages/cli/assets/docs/cli.doc.mjs
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file `astryx docs cli`: every command, API function, output schema, and
- * enum the CLI documents, one section each.
- *
- * Built from the docs whose `namespace` is `cli/commands` or `cli/api`, so it
- * cannot drift from the commands and functions it describes. `astryx doctor`
- * names a CLI doc with no namespace, or one no topic reads.
- */
-
-import {buildCliTopic} from '../../foundation/discovery/cli-self-docs.mjs';
-
-/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */
-export const docs = await buildCliTopic();
diff --git a/packages/cli/assets/docs/getting-started.doc.mjs b/packages/cli/assets/docs/getting-started.doc.mjs
index a5fd1abac1..65de63e884 100644
--- a/packages/cli/assets/docs/getting-started.doc.mjs
+++ b/packages/cli/assets/docs/getting-started.doc.mjs
@@ -98,11 +98,11 @@ export const docs = {
},
{
type: 'prose',
- text: 'These stylesheets are cascade-layered: the reset loads in @layer reset and component styles in @layer astryx-base. If your project has existing global CSS, a legacy reset, or Tailwind, declare the layer order explicitly and assign every stylesheet to a layer deliberately: unlayered styles and later layers both override astryx-base regardless of specificity. See the Cascade Layer Safety section in `astryx docs migration` before building screens.',
+ text: 'These stylesheets are cascade-layered: the reset loads in @layer reset and component styles in @layer astryx-base. If your project has existing global CSS, a legacy reset, or Tailwind, declare the layer order explicitly and assign every stylesheet to a layer deliberately: unlayered styles and later layers both override astryx-base regardless of specificity. See the Cascade Layer Safety section in {@link generic:migration} before building screens.',
},
{
type: 'prose',
- text: 'Run `astryx docs theme` for the full theming guide.',
+ text: 'Run {@link generic:theme} for the full theming guide.',
},
],
},
diff --git a/packages/cli/assets/docs/principles.doc.mjs b/packages/cli/assets/docs/principles.doc.mjs
index c568db41c3..9f42985fa6 100644
--- a/packages/cli/assets/docs/principles.doc.mjs
+++ b/packages/cli/assets/docs/principles.doc.mjs
@@ -39,10 +39,10 @@ export const docs = {
style: 'ordered',
items: [
'Use components for everything they cover',
- 'Page layout is frame-first: pick the shell and budget regions before writing content (see \`astryx docs layout\`)',
+ 'Page layout is frame-first: pick the shell and budget regions before writing content (see {@link generic:layout})',
'Dense data renders as rows (Table, List/Item), edge-to-edge with dividers; Card is for widgets, galleries, and settings groups',
- 'StyleX or Tailwind for custom styling; both are first-class (see \`astryx docs styling\`)',
- 'Semantic tokens, not hardcoded values (see \`astryx docs tokens\`)',
+ 'StyleX or Tailwind for custom styling; both are first-class (see {@link generic:styling})',
+ 'Semantic tokens, not hardcoded values (see {@link generic:tokens})',
'CSS custom properties for colors, not hex values',
'Form inputs are controlled (value + onChange)',
'Use useLinkComponent() for navigation so consumers can plug in their framework router via LinkProvider',
@@ -60,7 +60,7 @@ export const docs = {
},
{
type: 'prose',
- text: 'See \`astryx docs styling\` for the complete guide with examples.',
+ text: 'See {@link generic:styling} for the complete guide with examples.',
},
],
},
@@ -76,7 +76,7 @@ export const docs = {
'Hardcoded colors (#fff). Use var(--color-*) or Tailwind semantic classes (text-primary, bg-surface)',
'Hardcoded spacing (16px). Use spacing tokens or Tailwind spacing utilities',
'Hardcoded <a> elements. Use useLinkComponent() so consumers can swap in their framework router via LinkProvider',
- 'Wrapping every list item or page section in a Card. Decide the frame first; dense data renders as rows (see \`astryx docs layout\`)',
+ 'Wrapping every list item or page section in a Card. Decide the frame first; dense data renders as rows (see {@link generic:layout})',
'Badge as decoration. Reserve Badge for counts and enumerated states; use StatusDot or Token for status',
'Inventing props. Read component docs first',
],
@@ -89,7 +89,7 @@ export const docs = {
content: [
{
type: 'prose',
- text: 'The design system provides semantic design tokens for spacing, color, radius, shadow, typography, and size. Tokens adapt to the active theme and color mode. Run \`astryx docs tokens\` for the full reference with all values.',
+ text: 'The design system provides semantic design tokens for spacing, color, radius, shadow, typography, and size. Tokens adapt to the active theme and color mode. Run {@link generic:tokens} for the full reference with all values.',
},
],
},
diff --git a/packages/cli/assets/docs/styling-libraries.doc.mjs b/packages/cli/assets/docs/styling-libraries.doc.mjs
index 5027c6cb93..d494f7e582 100644
--- a/packages/cli/assets/docs/styling-libraries.doc.mjs
+++ b/packages/cli/assets/docs/styling-libraries.doc.mjs
@@ -24,7 +24,7 @@ export const docs = {
},
{
type: 'prose',
- text: 'For available token names and values, run `astryx docs tokens`. Focused references are also available with `astryx docs color`, `astryx docs spacing`, `astryx docs shape`, `astryx docs typography`, `astryx docs elevation`, and `astryx docs motion`.',
+ text: 'For available token names and values, run {@link generic:tokens}. Focused references are also available with {@link generic:color}, {@link generic:spacing}, {@link generic:shape}, {@link generic:typography}, {@link generic:elevation}, and {@link generic:motion}.',
},
],
},
@@ -455,7 +455,7 @@ function RevenueChart({data}: {data: Array<{x: string; y: number}>}) {
'Import the reset/base CSS and a theme CSS file early enough for first paint. For production SSR, prefer built themes from `astryx theme build` or published `/built` theme imports plus `theme.css`.',
'Choose one owner for color mode. Theme uses `data-theme="light|dark"` and `color-scheme` to resolve `light-dark()` tokens.',
'Map the external library\'s semantic layer to system variables by intent, not by exact naming. For example, MUI `background.paper` maps to `--color-background-surface`.',
- 'Use `astryx docs tokens` and focused token docs when building mappings. Keep mappings small at first: text, surface/body/card/popover, border, accent, status, spacing, radius, typography, shadow.',
+ 'Use {@link generic:tokens} and focused token docs when building mappings. Keep mappings small at first: text, surface/body/card/popover, border, accent, status, spacing, radius, typography, shadow.',
'Use token resolver APIs only for non-CSS APIs that need resolved values.',
],
},
diff --git a/packages/cli/assets/docs/styling.doc.mjs b/packages/cli/assets/docs/styling.doc.mjs
index 34e8b77c5b..357216da45 100644
--- a/packages/cli/assets/docs/styling.doc.mjs
+++ b/packages/cli/assets/docs/styling.doc.mjs
@@ -30,7 +30,7 @@ export const docs = {
},
{
type: 'prose',
- text: 'All approaches resolve to the same design tokens, so theming and dark mode work regardless of which you choose. For external styling libraries, run `astryx docs styling-libraries`; it covers Tailwind, StyleX, Panda, Chakra, MUI, CSS-in-JS, CSS Modules, Sass, and `useTheme()` for non-CSS processing.',
+ text: 'All approaches resolve to the same design tokens, so theming and dark mode work regardless of which you choose. For external styling libraries, run {@link generic:styling-libraries}; it covers Tailwind, StyleX, Panda, Chakra, MUI, CSS-in-JS, CSS Modules, Sass, and `useTheme()` for non-CSS processing.',
},
],
},
@@ -118,7 +118,7 @@ const overrides = stylex.create({
},
{
type: 'prose',
- text: 'The bridge is pure CSS with zero JS. Theme changes (dark mode, custom themes) apply automatically because the utilities reference the same CSS custom properties that components use. This is the paved Tailwind path; for other styling libraries that follow the same aliasing pattern, run `astryx docs styling-libraries`.',
+ text: 'The bridge is pure CSS with zero JS. Theme changes (dark mode, custom themes) apply automatically because the utilities reference the same CSS custom properties that components use. This is the paved Tailwind path; for other styling libraries that follow the same aliasing pattern, run {@link generic:styling-libraries}.',
},
],
},
@@ -263,7 +263,7 @@ const overrides = stylex.create({
},
{
type: 'prose',
- text: 'For systematic theming, use defineTheme component overrides instead of raw CSS selectors. defineTheme keeps the higher-level `prop:value` API (`variant:primary`, `size:sm`) and handles selector generation for you. Run `astryx docs theme` for the full theming guide.',
+ text: 'For systematic theming, use defineTheme component overrides instead of raw CSS selectors. defineTheme keeps the higher-level `prop:value` API (`variant:primary`, `size:sm`) and handles selector generation for you. Run {@link generic:theme} for the full theming guide.',
},
],
},
@@ -338,7 +338,7 @@ const styles = stylex.create({
},
{
type: 'prose',
- text: 'See `astryx docs tokens` for the full token reference (all spacing, color, radius, shadow, and typography tokens with values). See `astryx docs theme` for how to override tokens via defineTheme.',
+ text: 'See {@link generic:tokens} for the full token reference (all spacing, color, radius, shadow, and typography tokens with values). See {@link generic:theme} for how to override tokens via defineTheme.',
},
],
},
diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjs
index 553a907e4d..070771d6bb 100644
--- a/packages/cli/assets/docs/theme.doc.mjs
+++ b/packages/cli/assets/docs/theme.doc.mjs
@@ -391,7 +391,7 @@ const brandTheme = defineTheme({
content: [
{
type: 'prose',
- text: 'The `components` field in defineTheme uses semantic component keys and style keys, not raw CSS selectors. Use `base` for all instances, `variant:value` or `stateName` for specific props/states, and let the theme pipeline choose the underlying selector. For raw external CSS escape hatches, prefer the data-attribute selector surface documented in `astryx docs styling`.',
+ text: 'The `components` field in defineTheme uses semantic component keys and style keys, not raw CSS selectors. Use `base` for all instances, `variant:value` or `stateName` for specific props/states, and let the theme pipeline choose the underlying selector. For raw external CSS escape hatches, prefer the data-attribute selector surface documented in {@link generic:styling}.',
},
{
type: 'code',
@@ -572,7 +572,7 @@ import './themes/ocean.css';
},
{
type: 'prose',
- text: "The build also warns when the theme names font families it does not load (webfonts like Fraunces) and prints the `<link>`/`@font-face` to add. The built CSS only sets font-family, so loading the font files stays the app's job. See `astryx docs typography` for the full recipe.",
+ text: "The build also warns when the theme names font families it does not load (webfonts like Fraunces) and prints the `<link>`/`@font-face` to add. The built CSS only sets font-family, so loading the font files stays the app's job. See {@link generic:typography} for the full recipe.",
},
],
},
@@ -811,7 +811,7 @@ function ChartConfig() {
},
{
type: 'prose',
- text: 'See `astryx docs styling-libraries` for styling-library interop and `astryx docs tokens` for the full token reference.',
+ text: 'See {@link generic:styling-libraries} for styling-library interop and {@link generic:tokens} for the full token reference.',
},
],
},
diff --git a/packages/cli/assets/docs/tokens.doc.mjs b/packages/cli/assets/docs/tokens.doc.mjs
index 8991ae4734..0572576c50 100644
--- a/packages/cli/assets/docs/tokens.doc.mjs
+++ b/packages/cli/assets/docs/tokens.doc.mjs
@@ -1102,7 +1102,7 @@ export const docs = {
},
{
"type": "prose",
- "text": "See `astryx docs styling` for how to apply tokens via xstyle, className, and compound component patterns. See `astryx docs theme` for overriding tokens with defineTheme."
+ "text": "See {@link generic:styling} for how to apply tokens via xstyle, className, and compound component patterns. See {@link generic:theme} for overriding tokens with defineTheme."
}
]
}
diff --git a/packages/cli/assets/docs/tree/api.doc.mjs b/packages/cli/assets/docs/tree/api.doc.mjs
new file mode 100644
index 0000000000..2fc3f39e72
--- /dev/null
+++ b/packages/cli/assets/docs/tree/api.doc.mjs
@@ -0,0 +1,30 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx docs cli/api`: the programmatic API of `@astryxdesign/cli/api`.
+ *
+ * Adopts each function, schema, and enum doc whose `namespace` is `cli/api`,
+ * one generated level per kind: `cli/api/functions`, `cli/api/schemas`, and
+ * `cli/api/enums`.
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').NamespaceDoc} */
+export const docs = {
+ type: 'namespace',
+ name: 'api',
+ title: 'API',
+ summary:
+ 'The programmatic API: functions, the JSON output envelope, error codes, and response types.',
+ keywords: ['api', 'functions', 'schemas', 'enums', 'json'],
+ placement: {parent: 'namespace:cli', slot: 'reference', order: 20},
+ slots: {
+ kinds: {title: 'Reference', accepts: {kinds: ['namespace']}},
+ },
+ adopts: [
+ {
+ source: {group: 'cli/api', kinds: ['function', 'schema', 'enum']},
+ into: 'kinds',
+ groupBy: 'kind',
+ },
+ ],
+};
diff --git a/packages/cli/assets/docs/tree/cli.doc.mjs b/packages/cli/assets/docs/tree/cli.doc.mjs
new file mode 100644
index 0000000000..1c1903bb91
--- /dev/null
+++ b/packages/cli/assets/docs/tree/cli.doc.mjs
@@ -0,0 +1,23 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx docs cli`: the top of the CLI's docs tree (spec:AST-046).
+ *
+ * A namespace declares a level and its slots. It never lists its children:
+ * a guide places itself here with `placement`, and the `commands` and `api`
+ * namespaces adopt the CLI's typed docs by the `namespace` group each declares.
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').NamespaceDoc} */
+export const docs = {
+ type: 'namespace',
+ name: 'cli',
+ title: 'Astryx CLI',
+ summary:
+ 'Commands, programmatic APIs, integration authoring, and output contracts.',
+ keywords: ['cli', 'commands', 'api', 'reference'],
+ slots: {
+ guides: {title: 'Guides', accepts: {kinds: ['generic', 'namespace']}},
+ reference: {title: 'Reference', accepts: {kinds: ['namespace']}},
+ },
+};
diff --git a/packages/cli/assets/docs/tree/commands.doc.mjs b/packages/cli/assets/docs/tree/commands.doc.mjs
new file mode 100644
index 0000000000..bff46a102d
--- /dev/null
+++ b/packages/cli/assets/docs/tree/commands.doc.mjs
@@ -0,0 +1,25 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx docs cli/commands`: every command the CLI ships.
+ *
+ * Adopts each command doc whose `namespace` is `cli/commands`, so a new
+ * command appears here with no edit to this file.
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').NamespaceDoc} */
+export const docs = {
+ type: 'namespace',
+ name: 'commands',
+ title: 'Commands',
+ summary:
+ 'Every command and subcommand: usage, options, examples, and exit codes.',
+ keywords: ['commands', 'usage', 'options', 'flags'],
+ placement: {parent: 'namespace:cli', slot: 'reference', order: 10},
+ slots: {
+ commands: {title: 'Commands', accepts: {kinds: ['command']}},
+ },
+ adopts: [
+ {source: {group: 'cli/commands', kinds: ['command']}, into: 'commands'},
+ ],
+};
diff --git a/packages/cli/assets/docs/cli-integrations.doc.mjs b/packages/cli/assets/docs/tree/integrations.doc.mjs
similarity index 86%
rename from packages/cli/assets/docs/cli-integrations.doc.mjs
rename to packages/cli/assets/docs/tree/integrations.doc.mjs
index 76d1c52e17..cda2fc1b84 100644
--- a/packages/cli/assets/docs/cli-integrations.doc.mjs
+++ b/packages/cli/assets/docs/tree/integrations.doc.mjs
@@ -1,13 +1,20 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */
+/**
+ * @file `astryx docs cli/integrations`: the guide to building an integration
+ * package. It lives in the docs tree under the `cli` namespace (spec:AST-046),
+ * so its only route is `cli/integrations`.
+ */
+/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */
export const docs = {
- name: 'cli-integrations',
+ type: 'generic',
+ name: 'integrations',
+ placement: {parent: 'namespace:cli', slot: 'guides', order: 10},
title: 'CLI Integrations',
category: 'guide',
description:
- 'Author an npm package that contributes components, templates, themes, docs, and upgrade codemods to Astryx.',
+ 'Build an Astryx integration: an npm package that contributes components, templates, themes, docs, and upgrade codemods.',
sections: [
{
@@ -20,11 +27,11 @@ export const docs = {
},
{
type: 'prose',
- text: 'The authoring CLI owns the integration file. The first `astryx integration add` creates `astryx.integration.mjs`; each later add declares its root only after writing a valid contribution behind it. Identity (name and version) still comes from package.json. For the consumer side, run `astryx docs getting-started`.',
+ text: 'The authoring CLI owns the integration file. The first `astryx integration add` creates `astryx.integration.mjs`; each later add declares its root only after writing a valid contribution behind it. Identity (name and version) still comes from package.json. For the consumer side, run {@link generic:getting-started}.',
},
{
type: 'prose',
- text: 'Every file an integration author writes is documented field by field in `npx astryx docs authoring`: the manifest, astryx.config, codemods, identity, and each doc type. `npx astryx docs authoring --index` lists them, and `npx astryx docs authoring <key>` reads one.',
+ text: 'Every file an integration author writes is documented field by field in {@link generic:authoring}: the manifest, astryx.config, codemods, identity, and each doc type. `npx astryx docs authoring --index` lists them, and `npx astryx docs authoring <key>` reads one.',
},
{
type: 'prose',
@@ -175,16 +182,37 @@ export const docs = {
},
{
type: 'prose',
- text: 'A template id is its source-relative path with the metadata suffix removed; the display `name` is not its identity and may repeat. If an integration id matches a Core id, unqualified lookup fails closed instead of choosing one. Run `astryx doctor integration templates <package>` before publishing: it recommends renaming, but an intentional overlap is allowed when callers always pass `--package <package>`.',
+ text: "A template id is its exact source-relative path with the metadata suffix removed; the display `name` is not its identity and may repeat. Run `astryx --json template --list --package @astryxdesign/core` and copy the Core entry's `id` exactly. To replace one, generate the source/metadata pair with `integration add template`, then set `replaces` in that template's own metadata to the exact Core id. The declaration lives on the template, as `replaces` does on a doc topic; the manifest only points at the templates root.",
+ },
+ {
+ type: 'code',
+ lang: 'bash',
+ label: 'Create the integration template',
+ code: 'astryx integration add template acme-app-shell --type page',
+ },
+ {
+ type: 'code',
+ lang: 'typescript',
+ label: 'Declare the replacement',
+ code: "// templates/acme-app-shell.doc.mjs\n/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */\nexport default {\n type: 'page',\n name: 'acme-app-shell',\n displayName: 'Acme App Shell',\n description: 'An app shell with Acme navigation.',\n replaces: 'shell-side-nav',\n};",
},
{
type: 'code',
lang: 'typescript',
- code: "// AcmeLandingPage.doc.mjs\n/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */\nexport default {\n type: 'page',\n name: 'acme-landing-page',\n displayName: 'Acme Landing Page',\n description: 'A complete product landing page.',\n};",
+ label: 'Use product navigation in the replacement source',
+ code: "// templates/acme-app-shell.tsx\nimport {AppShell} from '@astryxdesign/core/AppShell';\nimport {Card} from '@astryxdesign/core/Card';\nimport {AcmeSideNav, AcmeTopNav} from '@acme/navigation';\n\nexport default function AcmeAppShell() {\n return (\n <AppShell\n sideNav={<AcmeSideNav />}\n topNav={<AcmeTopNav />}>\n <Card>Product content</Card>\n </AppShell>\n );\n}",
+ },
+ {
+ type: 'prose',
+ text: 'With that declaration, `astryx template shell-side-nav` selects `acme-app-shell`; template listing, search, build suggestions, and block-layout lookup use the same effective identity. `astryx template shell-side-nav --package @astryxdesign/core` still selects the original, and `astryx template acme-app-shell --package @acme/navigation` explicitly selects the integration template. In the `template.list` JSON response, a winning replacement entry carries `replaces` naming the Core id it supersedes, and the Core entry is omitted from the default listing. A page can replace only a Core page, and a block can replace only a Core block. Missing Core targets, type mismatches, a declaration on a template that cannot be used, and more than one replacement from one package fail closed: Core stays the default and `astryx doctor integration templates <package>` reports the error. If multiple explicitly configured packages each replace the target, the package configured later wins with a warning. An explicitly configured replacement always wins over an autolinked one. If only autolinked packages conflict, the package listed later in package.json dependencies wins with a warning; add the intended package to `astryx.config` to make the choice explicit. Without `replaces`, valid template selection keeps the existing package-aware ambiguity behavior; contribution failure isolation still follows the rules below.',
+ },
+ {
+ type: 'prose',
+ text: "`replaces` is part of the strict template metadata object, so a CLI older than 0.7.0 rejects it: on those CLIs the package's templates and doc topics are withheld with one warning, while its components still load. Declare `@astryxdesign/cli >=0.7.0` when a package uses `replaces`.",
},
{
type: 'prose',
- text: 'The CLI needs both files at consume time. `integration add` includes the templates root when package.json already has a files allowlist. It never creates an exports map, because doing that can make previously-open deep imports private; when a map already exists, it adds the generated source subpath without replacing author-owned entries. Use consumer-safe extensionless subpaths in the exports map (e.g. `"./templates/AcmeDashboard"` instead of `"./templates/AcmeDashboard.tsx"`), so consumers import without knowing the file extension. `integration pack --check` proves the source and metadata survive the tarball and verifies every component through the public import its metadata advertises.',
+ text: 'The CLI needs both files at consume time. `integration add` includes the templates root when package.json already has a files allowlist. It never creates an exports map, because doing that can make previously-open deep imports private; when a map already exists, it adds the generated source subpath without replacing author-owned entries. Use consumer-safe extensionless subpaths in the exports map (e.g. `"./templates/AcmeDashboard"` instead of `"./templates/AcmeDashboard.tsx"`), so consumers import without knowing the file extension. `integration pack --check` proves the source and metadata, including `replaces`, survive the tarball and verifies every component through the public import its metadata advertises.',
},
],
},
@@ -426,7 +454,7 @@ export const docs = {
},
{
type: 'prose',
- text: 'Discovery is resilient. A broken or misconfigured integration is skipped with a single non-blocking warning on stderr instead of crashing the CLI, and it never corrupts a `--json` stdout envelope. Everyday commands keep working with the remaining valid contributions.',
+ text: "Discovery is resilient. A manifest that fails to load is skipped because none of its roots are trustworthy. An error in one contribution kind is reported without hiding the integration's other valid kinds. Invalid template and component files are omitted without hiding valid siblings; other kinds keep their existing all-or-nothing behavior. Everyday commands keep working with the remaining valid contributions, warnings go to stderr, and `--json` stdout stays clean.",
},
{
type: 'prose',
diff --git a/packages/cli/assets/docs/tree/integrations.test.mjs b/packages/cli/assets/docs/tree/integrations.test.mjs
new file mode 100644
index 0000000000..1f331626a4
--- /dev/null
+++ b/packages/cli/assets/docs/tree/integrations.test.mjs
@@ -0,0 +1,62 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {docs as integrationGuide} from './integrations.doc.mjs';
+import {doc as integrationSchema} from '../../../authoring/integration/integration.doc.mjs';
+import {doc as templateSchema} from '../../../authoring/doctypes/template/template.doc.mjs';
+
+function guideText() {
+ return integrationGuide.sections
+ .flatMap(section => section.content)
+ .flatMap(block => {
+ if (block.type === 'prose') return [block.text];
+ if (block.type === 'code') return [block.label ?? '', block.code];
+ if (block.type === 'list') return block.items;
+ return [];
+ })
+ .join('\n');
+}
+
+describe('integration template replacement docs', () => {
+ it('documents the complete author and consumer contract', () => {
+ const text = guideText();
+
+ for (const required of [
+ "replaces: 'shell-side-nav'",
+ 'acme-app-shell',
+ 'astryx --json template --list --package @astryxdesign/core',
+ 'astryx template shell-side-nav --package @astryxdesign/core',
+ 'astryx template acme-app-shell --package @acme/navigation',
+ 'templates/acme-app-shell.doc.mjs',
+ 'AcmeSideNav',
+ 'AcmeTopNav',
+ '<Card>Product content</Card>',
+ 'fail closed',
+ 'configured later wins',
+ 'wins over an autolinked one',
+ 'listed later in package.json dependencies',
+ 'valid siblings',
+ 'Without `replaces`',
+ '@astryxdesign/cli >=0.7.0',
+ 'templates and doc topics are withheld',
+ '`template.list` JSON response',
+ ]) {
+ expect(text, required).toContain(required);
+ }
+ });
+
+ it('declares a replacement on the template, never in the manifest', () => {
+ expect(guideText()).not.toContain('templateReplacements');
+ expect(
+ integrationSchema.fields.some(field => /replac/i.test(field.name)),
+ ).toBe(false);
+
+ const field = templateSchema.fields.find(
+ candidate => candidate.name === 'replaces',
+ );
+ expect(field).toMatchObject({type: 'string'});
+ expect(field.description).toContain('Integration templates only');
+ expect(field.description).toContain('--package @astryxdesign/core');
+ expect(field.description).toContain('0.7.0');
+ });
+});
diff --git a/packages/cli/assets/docs/tree/writing-docs.doc.mjs b/packages/cli/assets/docs/tree/writing-docs.doc.mjs
new file mode 100644
index 0000000000..e5c23a9d3a
--- /dev/null
+++ b/packages/cli/assets/docs/tree/writing-docs.doc.mjs
@@ -0,0 +1,286 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx docs cli/writing-docs`: the guide to writing docs that readers,
+ * people and agents alike, find by search or by moving one level at a time.
+ * It lives in the docs tree under the `cli` namespace, so its only route is
+ * `cli/writing-docs`.
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */
+export const docs = {
+ type: 'generic',
+ name: 'writing-docs',
+ placement: {parent: 'namespace:cli', slot: 'guides', order: 20},
+ title: 'Writing docs',
+ category: 'guide',
+ description:
+ 'Write docs that people and agents find by search or by reading one level at a time.',
+
+ sections: [
+ {
+ title: 'How the docs work',
+ category: 'guide',
+ content: [
+ {
+ type: 'prose',
+ text: 'Every doc is one node in one docs graph, with a stable identity and one home in a tree.',
+ },
+ {
+ type: 'list',
+ style: 'unordered',
+ items: [
+ "Identity: the doc's provider, its kind, and its name. Moving a doc never changes it.",
+ 'Route: the names of the doc and its parents, such as `cli/api/functions/search`; `astryx docs <route>` reads it.',
+ 'Moves: every read ends with Up, Previous, Next, and Related, each as a command you can run.',
+ 'Search: a hit is the smallest part that answers, one section or one tree page. It gives the command that reads it and the command that opens the level above.',
+ ],
+ },
+ {
+ type: 'prose',
+ text: "You never write moves or lists of children. The CLI derives them from each doc's home and its typed links.",
+ },
+ ],
+ },
+ {
+ title: 'Add a doc',
+ category: 'guide',
+ content: [
+ {
+ type: 'prose',
+ text: 'To add a doc, write one `.doc.mjs` file named after the doc, and stamp the type that matches what it describes.',
+ },
+ {
+ type: 'table',
+ headers: ['You document', 'Doc type', '`type`'],
+ rows: [
+ ['A topic or a guide', 'ReferenceDoc', "'generic'"],
+ ['A CLI command', 'CommandDoc', "'command'"],
+ ['A CLI API function', 'FunctionDoc', "'function'"],
+ ['An object shape', 'SchemaDoc', "'schema'"],
+ ['A fixed list of values', 'EnumDoc', "'enum'"],
+ ['A component', 'ComponentDoc', "'component'"],
+ ['A level of the tree', 'NamespaceDoc', "'namespace'"],
+ ],
+ },
+ {
+ type: 'prose',
+ text: 'A topic or guide holds `sections`. Each section has a `title` and `content` blocks, and covers one idea. The `description` is one sentence that says what the doc covers.',
+ },
+ {
+ type: 'code',
+ lang: 'javascript',
+ label: 'docs/deploying.doc.mjs',
+ code: "export default {\n type: 'generic',\n name: 'deploying',\n title: 'Deploying',\n description: 'Ship an app built with Acme widgets.',\n sections: [\n {\n title: 'Build before you ship',\n content: [\n {type: 'prose', text: 'Build the app, then check it with {@link @astryxdesign/cli:command:doctor}.'},\n {type: 'code', lang: 'bash', code: 'npm run build'},\n {type: 'list', style: 'unordered', items: ['Check the output folder.']},\n {type: 'table', headers: ['Env', 'Value'], rows: [['NODE_ENV', 'production']]},\n ],\n },\n ],\n};",
+ },
+ {
+ type: 'list',
+ style: 'unordered',
+ items: [
+ 'A name is a command argument, so use only letters, digits, `_`, and `-`. Use lowercase kebab-case, such as `writing-docs`, so the name and its route segment match.',
+ 'Keep the name stable. Links name a doc by its identity, and the name is part of it.',
+ 'A name that collides with an existing topic is an error unless the doc declares `replaces` or `extends`.',
+ 'Name the cases a doc does not cover, and link to where they are covered. A reader cannot tell a case you left out from a case that does not exist.',
+ ],
+ },
+ {
+ type: 'prose',
+ text: 'Every field of every doc type is in {@link generic:authoring}.',
+ },
+ ],
+ },
+ {
+ title: 'Place a doc',
+ category: 'guide',
+ content: [
+ {
+ type: 'prose',
+ text: 'Each doc gets one home in one of three ways: a namespace adopts it, it places itself, or it stays a flat topic. Folders never decide a home.',
+ },
+ {
+ type: 'prose',
+ text: "Adopted: a CLI typed doc declares `namespace`, either `'cli/commands'` or `'cli/api'`. That namespace adopts it by kind, so its route is `cli/commands/<name>` or `cli/api/functions/<name>`.",
+ },
+ {
+ type: 'code',
+ lang: 'javascript',
+ code: "{type: 'function', name: 'search', namespace: 'cli/api' /* ... */} // cli/api/functions/search",
+ },
+ {
+ type: 'prose',
+ text: "Placed: a guide declares `placement`. The `parent` names a namespace of your own package, the `slot` is one that namespace declares for the doc's kind, and `order` sorts the siblings in the slot. A placement that fails withdraws the doc with an error.",
+ },
+ {
+ type: 'code',
+ lang: 'javascript',
+ code: "placement: {parent: 'namespace:cli', slot: 'guides', order: 20}, // cli/writing-docs",
+ },
+ {
+ type: 'prose',
+ text: 'Flat: a doc with neither is a flat topic, read with `astryx docs <name>`.',
+ },
+ {
+ type: 'code',
+ lang: 'javascript',
+ code: "{type: 'generic', name: 'tokens', title: 'All Tokens' /* ... */} // astryx docs tokens",
+ },
+ ],
+ },
+ {
+ title: 'Link docs',
+ category: 'guide',
+ content: [
+ {
+ type: 'prose',
+ text: 'Link a doc with `{@link <target>}` or a typed field, never by writing its `astryx docs` route in prose: a route you write goes stale when the doc moves. Other commands, such as `astryx doctor`, you write as they are.',
+ },
+ {
+ type: 'prose',
+ text: "Typed fields: a FunctionDoc's `command` names the CLI command that runs it, and its `related` names functions. A CommandDoc's `fn` names the function it runs, and its `related` names commands.",
+ },
+ {
+ type: 'code',
+ lang: 'javascript',
+ code: "{type: 'function', name: 'search', command: 'search', related: ['docs']}\n{type: 'command', name: 'search', fn: 'search', related: ['docs']}",
+ },
+ {
+ type: 'prose',
+ text: "Inside a section's text, write `{@link <target>}`, where the target is `[<provider>:]<kind>:<name>`; leave out the provider for a doc of your own provider. The CLI prints the command that opens the doc. It works in prose, list items, and table cells; link syntax inside code ticks is shown as written, and an older CLI prints the link as plain text. A namespace doc can also carry `reference` and `workflow` blocks in its `blocks`, though the CLI does not print them yet; a topic's sections cannot hold them.",
+ },
+ {
+ type: 'code',
+ lang: 'javascript',
+ code: "{type: 'prose', text: 'Check it with {@link command:doctor}.'}\n{type: 'list', style: 'unordered', items: ['Search with {@link @astryxdesign/cli:function:search}.']}\n\n// In a namespace doc's blocks only:\n{type: 'workflow', steps: [\n {title: 'Write the doc', references: ['generic:authoring']},\n {title: 'Check it', references: ['command:doctor']},\n]}",
+ },
+ {
+ type: 'prose',
+ text: "The route in the printed command is derived when the doc is read, so a link follows its doc when the doc moves. A target that names no doc prints as written, and so does a typed-field name that matches more than one doc; `astryx doctor` warns on both.",
+ },
+ ],
+ },
+ {
+ title: 'Keep reads short',
+ category: 'guide',
+ content: [
+ {
+ type: 'prose',
+ text: 'Keep every read short so a reader gets one answer per command: one idea per section, a summary first, and a hard size limit.',
+ },
+ {
+ type: 'list',
+ style: 'unordered',
+ items: [
+ 'Give each section one idea. If it needs a second topic, split it into two sections.',
+ "A section's summary, shown in the section list and in search, is its first prose block or first list item, cut at 240 characters. Lead with what the section answers.",
+ 'In text, a topic with more than one section reads as its section list. The reader opens one section, or prints everything with `--full`. With `--json`, a topic returns the whole doc and `--index` its section list.',
+ 'Every read should fit in 32 KB; `astryx doctor` warns on one that does not. Aim for sections under about 30 lines.',
+ ],
+ },
+ {
+ type: 'code',
+ lang: 'bash',
+ code: 'astryx docs cli/writing-docs\nastryx docs cli/writing-docs keep-reads-short\nastryx docs cli/writing-docs --full',
+ },
+ ],
+ },
+ {
+ title: 'Make docs findable',
+ category: 'guide',
+ content: [
+ {
+ type: 'prose',
+ text: 'Search finds a doc only by the words it indexes, so put the words a reader types where search looks.',
+ },
+ {
+ type: 'prose',
+ text: "Search matches titles, section titles, headings, each section's summary, and identifiers written in code ticks, such as `ERR_UNKNOWN_SECTION` or `token-ref`. It also matches a doc's own name and the `keywords` of a namespace or typed doc.",
+ },
+ {
+ type: 'list',
+ style: 'do',
+ items: [
+ 'Title a section with the task or question, such as "Place a doc".',
+ 'Start each section with a sentence that names its subject and answers it.',
+ 'Write exact identifiers in code ticks: field names, block types, and error codes.',
+ 'Add `keywords` only for words that are not already in the title or summary.',
+ ],
+ },
+ {
+ type: 'list',
+ style: 'dont',
+ items: [
+ 'Open a section with background. Its first block is its summary.',
+ 'Use vague titles such as "Overview" or "Details" when a specific one fits.',
+ ],
+ },
+ {
+ type: 'prose',
+ text: 'Test it the way a new reader arrives: search for the question, not the title, and check that the first hit answers it.',
+ },
+ {
+ type: 'code',
+ lang: 'bash',
+ code: 'astryx search placement --type doc',
+ },
+ ],
+ },
+ {
+ title: 'Docs from an integration',
+ category: 'guide',
+ content: [
+ {
+ type: 'prose',
+ text: 'An integration joins the same graph with a namespace doc in its docs directory and guides placed in it. The namespace shows in `astryx docs` beside `cli`, with the same moves, search, and links. You can place a doc only in a namespace of your own package.',
+ },
+ {
+ type: 'prose',
+ text: 'Let the CLI write the files: inside the package, `astryx integration add doc deploying --parent acme` writes the guide with its placement, declares the docs root, and writes the `acme` namespace doc the first time. Run `astryx docs` in the package to see it.',
+ },
+ {
+ type: 'prose',
+ text: "A CLI release that does not read the docs tree can hide every doc topic your package ships when the package contains a namespace doc or a placed guide: none appear in `astryx docs`, in text or JSON, and `astryx doctor` may not say why. So `--parent` also declares the CLI release your docs need as an optional `@astryxdesign/cli` peer in package.json, which makes npm warn when an older CLI is installed, and `astryx integration pack --check` fails a package that ships either one without it.",
+ },
+ {
+ type: 'code',
+ lang: 'javascript',
+ code: "// docs/acme.doc.mjs\n/** @type {import('@astryxdesign/cli/authoring').NamespaceDoc} */\nexport default {\n type: 'namespace', name: 'acme', title: 'Acme widgets',\n summary: 'Guides for building apps with Acme widgets.',\n slots: {guides: {title: 'Guides', accepts: {kinds: ['generic']}}},\n};\n\n// docs/deploying.doc.mjs (route: acme/deploying)\n/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */\nexport default {\n type: 'generic', name: 'deploying', title: 'Deploying',\n description: 'Ship an app built with Acme widgets.',\n placement: {parent: 'namespace:acme', slot: 'guides', order: 10},\n sections: [{title: 'Check before you ship', content: [\n {type: 'prose', text: 'Run {@link @astryxdesign/cli:command:doctor} before every deploy.'},\n ]}],\n};",
+ },
+ {
+ type: 'prose',
+ text: "The link names the `@astryxdesign/cli` provider because its target lives in another package. A link without a provider resolves against yours: your manifest's `providerId`, or else your package name. That holds in a topic that `extends` another package's topic too: your sections link your docs, and a link to the other package's docs names its provider.",
+ },
+ {
+ type: 'prose',
+ text: 'Everything else an integration ships is in {@link generic:integrations}.',
+ },
+ ],
+ },
+ {
+ title: 'Check your docs',
+ category: 'guide',
+ content: [
+ {
+ type: 'prose',
+ text: 'Run the doctor commands to check every home, link, and read in your docs.',
+ },
+ {
+ type: 'list',
+ style: 'unordered',
+ items: [
+ '`astryx doctor`, in a project, checks the whole graph: the tree, the links, and the size of each read.',
+ '`astryx doctor integration docs`, inside an integration package, runs the same checks on that package\'s docs before it ships.',
+ '`astryx integration pack --check` fails a package that ships a namespace doc or a placed guide without a CLI peer that reads them.',
+ ],
+ },
+ {
+ type: 'prose',
+ text: 'No check can tell whether a doc is still true. Describe what the CLI does now, and change the doc in the same change that changes the behavior.',
+ },
+ {
+ type: 'prose',
+ text: 'A problem in the tree or a link is a warning: it names what to fix, but the exit code stays 0, so read the report (or its `--json`) before you ship.',
+ },
+ ],
+ },
+ ],
+};
diff --git a/packages/cli/authoring/doctypes/base/graph-fields.doc.mjs b/packages/cli/authoring/doctypes/base/graph-fields.doc.mjs
index f6b7b1dbce..f7cbf74017 100644
--- a/packages/cli/authoring/doctypes/base/graph-fields.doc.mjs
+++ b/packages/cli/authoring/doctypes/base/graph-fields.doc.mjs
@@ -12,25 +12,27 @@ export const doc = {
displayName: 'Authored doc graph fields',
namespace: 'authoring',
description:
- 'Placement, compatibility aliases, and audience: fields every authored doc kind declares for the docs graph. The docs graph is not built yet, so nothing reads them: a reference topic that sets one fails to load, and other doc kinds accept them and ignore them.',
+ "Placement, compatibility aliases, and audience: fields every authored doc kind declares for the docs tree. The docs tree reads `placement` for every guide, the CLI's and each integration's; aliases and audience are not built yet. A reference topic outside the docs tree that sets one fails to load, and other doc kinds accept them and ignore them.",
appliesTo: 'Every supported .doc.mjs object',
fields: [
{
name: 'placement',
type: 'DocPlacement',
description:
- 'Requests one canonical parent in the docs graph. Not read yet: a topic that sets it fails to load.',
+ "Names the doc's one parent in the docs tree: a namespace of the same package, one of its slots, and an order. Read for every guide, the CLI's and each integration's: a guide with `placement` gets a route in the tree instead of a flat topic name, and cannot also `replaces` or `extends` a topic. In the CLI's own topic directory a topic that sets it fails to load: the CLI keeps its guides in its docs tree directory. Commands, API functions, schemas, and enums do not set it: the tree adopts each by its `namespace`.",
fields: [
{
name: 'placement.parent',
type: 'string',
- description: 'Stable reference to the requested parent namespace.',
+ description:
+ 'The parent namespace: `namespace:<name>` in the same package.',
required: true,
},
{
name: 'placement.slot',
type: 'string',
- description: 'Named slot owned by the parent namespace.',
+ description:
+ "A slot the parent namespace declares; it must accept this doc's kind. Optional when the parent has one slot.",
},
{
name: 'placement.order',
@@ -43,7 +45,7 @@ export const doc = {
name: 'aliases',
type: 'string[]',
description:
- 'Prior names or routes the docs graph will keep resolving to this doc, without creating another identity. Not read yet: a topic that sets it fails to load.',
+ 'Prior names or routes the docs tree will keep resolving to this doc, without creating another identity. Not read yet: a topic that sets it fails to load.',
},
{
name: 'audience',
diff --git a/packages/cli/authoring/doctypes/base/type.ts b/packages/cli/authoring/doctypes/base/type.ts
index fc2442d3a5..eadd266529 100644
--- a/packages/cli/authoring/doctypes/base/type.ts
+++ b/packages/cli/authoring/doctypes/base/type.ts
@@ -31,14 +31,15 @@ export interface DocPlacement {
}
/**
- * Graph metadata shared by every authored doc kind. Reserved for the docs
- * graph, which is not built yet: nothing reads these fields, and a reference
- * topic that sets one fails to load.
+ * Tree metadata shared by every authored doc kind. The docs tree reads
+ * `placement` for every guide, the CLI's and each integration's
+ * (spec:AST-046); nothing reads `aliases` or `audience` yet. A reference topic
+ * outside the docs tree that sets one fails to load.
*/
export interface AuthoredDocGraphFields {
- /** Requested canonical parent in the docs graph. Not read yet. */
+ /** The doc's one parent in the docs tree: a namespace of its own package. */
placement?: DocPlacement;
- /** Prior routes or names the docs graph will keep resolving. Not read yet. */
+ /** Prior routes or names the docs tree will keep resolving. Not read yet. */
aliases?: string[];
/** Docs bundle audience; omit for public docs. Not read yet. */
audience?: DocAudience;
diff --git a/packages/cli/authoring/doctypes/command/command.doc.mjs b/packages/cli/authoring/doctypes/command/command.doc.mjs
index 79f6b78006..ae3949c295 100644
--- a/packages/cli/authoring/doctypes/command/command.doc.mjs
+++ b/packages/cli/authoring/doctypes/command/command.doc.mjs
@@ -54,7 +54,7 @@ export const doc = {
name: 'namespace',
type: 'string',
description:
- "The `astryx docs` topic that reads this doc. The CLI's commands use 'cli/commands' (the section `commands-<name>` of the `cli` topic). Every command doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads.",
+ "Optional in the type, but every doc the CLI ships declares it. The group that reads this doc. The CLI's commands use 'cli/commands', which the docs tree adopts: each is the leaf `cli/commands/<name>`. Every command doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that nothing reads.",
},
{
name: 'aliases',
diff --git a/packages/cli/authoring/doctypes/command/type.ts b/packages/cli/authoring/doctypes/command/type.ts
index 738e2f758e..919e239518 100644
--- a/packages/cli/authoring/doctypes/command/type.ts
+++ b/packages/cli/authoring/doctypes/command/type.ts
@@ -65,7 +65,7 @@ export interface CommandDoc extends AuthoredDocGraphFields {
summary: string;
/** Longer help body / when-to-use. */
description?: string;
- /** The `astryx docs` topic that reads this doc. The CLI's commands use 'cli/commands' (the section `commands-<name>` of the `cli` topic). Every command doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads. */
+ /** The group that reads this doc. The CLI's commands use 'cli/commands', which the docs tree adopts: each is the leaf `cli/commands/<name>`. Every command doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that nothing reads. */
namespace?: string;
/** Alternate slugs that also resolve to this doc. */
aliases?: string[];
@@ -81,7 +81,7 @@ export interface CommandDoc extends AuthoredDocGraphFields {
examples?: CommandExampleDoc[];
/** Documented exit codes. */
exitCodes?: {code: number; when: string}[];
- /** Related command names. */
+ /** Related command names; the CLI links each to its doc. */
related?: string[];
/** Freeform prose/notes. */
notes?: ReferenceContentBlock[];
diff --git a/packages/cli/authoring/doctypes/enum/enum.doc.mjs b/packages/cli/authoring/doctypes/enum/enum.doc.mjs
index 257198617e..2ba3d0eda3 100644
--- a/packages/cli/authoring/doctypes/enum/enum.doc.mjs
+++ b/packages/cli/authoring/doctypes/enum/enum.doc.mjs
@@ -49,7 +49,7 @@ export const doc = {
name: 'namespace',
type: 'string',
description:
- "The `astryx docs` topic that reads this doc. The CLI's enums use 'cli/api' (the section `api-<name>` of the `cli` topic). Every enum doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads.",
+ "Optional in the type, but every doc the CLI ships declares it. The group that reads this doc. The CLI's enums use 'cli/api', which the docs tree adopts by kind: each is the leaf `cli/api/enums/<name>`. Every enum doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that nothing reads.",
},
{
name: 'aliases',
diff --git a/packages/cli/authoring/doctypes/enum/type.ts b/packages/cli/authoring/doctypes/enum/type.ts
index 4d5005ee59..67d5bccd11 100644
--- a/packages/cli/authoring/doctypes/enum/type.ts
+++ b/packages/cli/authoring/doctypes/enum/type.ts
@@ -32,7 +32,7 @@ export interface EnumDoc extends AuthoredDocGraphFields {
displayName: string;
/** One-line summary shown in listings. */
description: string;
- /** The `astryx docs` topic that reads this doc. The CLI's enums use 'cli/api' (the section `api-<name>` of the `cli` topic). Every enum doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads. */
+ /** The group that reads this doc. The CLI's enums use 'cli/api', which the docs tree adopts by kind: each is the leaf `cli/api/enums/<name>`. Every enum doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that nothing reads. */
namespace?: string;
/** Alternate slugs that also resolve to this doc. */
aliases?: string[];
diff --git a/packages/cli/authoring/doctypes/function/function.doc.mjs b/packages/cli/authoring/doctypes/function/function.doc.mjs
index ad0a853cd6..b2875622b5 100644
--- a/packages/cli/authoring/doctypes/function/function.doc.mjs
+++ b/packages/cli/authoring/doctypes/function/function.doc.mjs
@@ -57,7 +57,7 @@ export const doc = {
name: 'namespace',
type: 'string',
description:
- "The `astryx docs` topic that reads this doc. The CLI's API functions use 'cli/api' (the section `api-<name>` of the `cli` topic). Every function doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads.",
+ "Optional in the type, but every doc the CLI ships declares it. The group that reads this doc. The CLI's API functions use 'cli/api', which the docs tree adopts by kind: each is the leaf `cli/api/functions/<name>`. Every function doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that nothing reads.",
},
{
name: 'aliases',
@@ -201,7 +201,8 @@ export const doc = {
{
name: 'related',
type: 'string[]',
- description: 'Related function/command names.',
+ description:
+ 'Related function names; the CLI links each to its doc. Name the CLI command with `command`, not here.',
},
{
name: 'relatedComponents',
diff --git a/packages/cli/authoring/doctypes/function/type.ts b/packages/cli/authoring/doctypes/function/type.ts
index 09860b787e..e301b3e29e 100644
--- a/packages/cli/authoring/doctypes/function/type.ts
+++ b/packages/cli/authoring/doctypes/function/type.ts
@@ -62,7 +62,7 @@ export interface FunctionDoc extends AuthoredDocGraphFields {
summary?: string;
/** Longer description. */
description?: string;
- /** The `astryx docs` topic that reads this doc. The CLI's API functions use 'cli/api' (the section `api-<name>` of the `cli` topic). Every function doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads. */
+ /** The group that reads this doc. The CLI's API functions use 'cli/api', which the docs tree adopts by kind: each is the leaf `cli/api/functions/<name>`. Every function doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that nothing reads. */
namespace?: string;
/** Alternate slugs that also resolve to this doc. */
aliases?: string[];
@@ -84,7 +84,8 @@ export interface FunctionDoc extends AuthoredDocGraphFields {
usage?: UsageDoc;
/** The CLI command that wraps this function, e.g. 'search'. */
command?: string;
- /** Related function/command names. */
+ /** Related function names; the CLI links each to its doc. Name the CLI
+ * command with `command`, not here. */
related?: string[];
/** Component names this is commonly used with (hooks). */
relatedComponents?: string[];
diff --git a/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs b/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs
index 4d1d31b3ac..799873edba 100644
--- a/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs
+++ b/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs
@@ -12,7 +12,7 @@ export const doc = {
displayName: 'NamespaceDoc',
namespace: 'authoring',
description:
- "Declares named navigation slots and renderer-neutral layout blocks for already-discovered docs. It never scans folders or copies child documents. Not loaded yet: only the docs graph reads namespace docs, and it is not built, so keep them out of an integration's docs directory for now.",
+ "Declares one level of the docs tree: named slots, and adoption rules for already-discovered docs. It never scans folders, lists its children, or copies child documents: a child names its parent with `placement`, or a namespace adopts a discovery group. `astryx docs <route>` lists each slot's children one level down. The CLI keeps its namespace docs in its docs tree directory; an integration ships its own in its docs directory, and they appear in `astryx docs` beside the CLI's.",
appliesTo: '<namespace>.doc.mjs',
fields: [
{
@@ -44,13 +44,13 @@ export const doc = {
name: 'placement',
type: 'DocPlacement',
description:
- 'Optional canonical parent request: {parent, slot?, order?}. Invalid explicit placement will fail compilation instead of falling back.',
+ 'Optional canonical parent: {parent, slot?, order?}. `parent` names a namespace of the same package as `namespace:<name>`. An invalid placement withdraws the namespace with a diagnostic; it never falls back.',
},
{
name: 'aliases',
type: 'string[]',
description:
- 'Prior names or routes the docs graph will keep resolving to this doc.',
+ 'Prior names or routes the docs tree will keep resolving to this doc. Not read yet.',
},
{
name: 'audience',
@@ -80,7 +80,7 @@ export const doc = {
name: 'blocks',
type: '(ReferenceContentBlock | GraphContentBlock)[]',
description:
- 'Ordered layout content. Graph-only workflow, collection, and reference blocks are available here without widening the stable ReferenceContentBlock union used by existing topic renderers.',
+ 'Ordered layout content for the namespace page. Graph-only workflow, collection, and reference blocks are available here without widening the stable ReferenceContentBlock union used by existing topic renderers. Not rendered yet: `astryx docs <route>` lists every slot and its children in order.',
},
],
examples: [
@@ -103,17 +103,13 @@ export const docs = {
source: {group: 'cli-commands', kinds: ['command']},
into: 'reference',
}],
- blocks: [
- {type: 'collection', source: {slot: 'guides'}, presentation: 'cards'},
- {type: 'collection', source: {slot: 'reference'}, presentation: 'compact'},
- ],
};`,
},
],
notes: [
{
type: 'prose',
- text: "Namespace docs are not loaded yet. Only the docs graph reads them, and it is not built. A namespace doc in an integration's docs directory fails to load as a topic, and with it every topic that package contributes, until the file is removed.",
+ text: "The docs tree reads namespace docs from the CLI and from every configured integration. An integration's namespace doc is a top-level level of the tree, and its guides name it with `placement`; a doc can be placed only in a namespace of its own package. When two packages claim one route, the CLI's own docs win, then integrations in configured order, and `astryx doctor` names the loser.",
},
{
type: 'prose',
diff --git a/packages/cli/authoring/doctypes/reference/reference.doc.mjs b/packages/cli/authoring/doctypes/reference/reference.doc.mjs
index 7c15fd860d..52758377ca 100644
--- a/packages/cli/authoring/doctypes/reference/reference.doc.mjs
+++ b/packages/cli/authoring/doctypes/reference/reference.doc.mjs
@@ -95,7 +95,7 @@ export const doc = {
name: 'sections[].content',
type: 'ReferenceContentBlock[]',
description:
- 'Ordered content blocks: prose, heading, code, table, list, and token-ref. Graph-only workflow, collection, and reference blocks are available through GraphContentBlock on NamespaceDoc, without widening this stable union.',
+ 'Ordered content blocks: prose, heading, code, table, list, and token-ref. Graph-only workflow, collection, and reference blocks are available through GraphContentBlock on NamespaceDoc, without widening this stable union. Inside text, `{@link <target>}` links another doc by identity (`[<provider>:]<kind>:<name>`): the CLI prints the command that opens it, and `astryx doctor` warns on one that names no doc.',
required: true,
},
{
@@ -144,7 +144,7 @@ export const docs = {
},
{
type: 'prose',
- text: 'Each `sections[].content` is an ordered array of ReferenceContentBlock, the stable discriminated union of prose, heading, code, table, list, and token-ref. Docs-graph-only workflow, collection, and reference blocks are exported separately as GraphContentBlock and accepted by NamespaceDoc. choice, callout, and checklist remain invalid. ReferenceContentBlock is also reused by the `notes` field on SchemaDoc and CommandDoc.',
+ text: 'Each `sections[].content` is an ordered array of ReferenceContentBlock, the stable discriminated union of prose, heading, code, table, list, and token-ref. Docs-graph-only workflow, collection, and reference blocks are exported separately as GraphContentBlock and accepted by NamespaceDoc. choice, callout, and checklist remain invalid. ReferenceContentBlock is also reused by the `notes` field on SchemaDoc and CommandDoc. Inside text, `{@link <target>}` links another doc by identity (`[<provider>:]<kind>:<name>`): the CLI prints the command that opens it, and `astryx doctor` warns on one that names no doc.',
},
{
type: 'code',
@@ -161,7 +161,7 @@ export const docs = {
type GraphContentBlock =
| { type: 'workflow'; title?: string; steps: WorkflowStep[] }
| { type: 'collection'; source: {slot: string}; presentation?: 'list' | 'cards' | 'compact'; whenEmpty?: 'show' | 'omit' }
- | { type: 'reference'; target: string; projection?: {fields?: string[]; sections?: string[]} };`,
+ | { type: 'reference'; target: string; presentation?: 'summary' | 'compact' };`,
},
{
type: 'prose',
diff --git a/packages/cli/authoring/doctypes/reference/type.ts b/packages/cli/authoring/doctypes/reference/type.ts
index 172aa941ff..569fab74c2 100644
--- a/packages/cli/authoring/doctypes/reference/type.ts
+++ b/packages/cli/authoring/doctypes/reference/type.ts
@@ -60,9 +60,12 @@ export type GraphContentBlock =
* { type: 'table', headers: ['Token', 'Value'], rows: [['--spacing-4', '16px']] }
* { type: 'list', style: 'do', items: ['Use semantic tokens'] }
* { type: 'token-ref', topic: 'tokens', section: 'Color Tokens' }
+ * { type: 'prose', text: 'Check it with {@link command:doctor}.' }
* ```
*/
export type ReferenceContentBlock =
+ /** Text. `{@link [<provider>:]<kind>:<name>}` inside it links another doc
+ * by identity; `astryx docs` prints the command that opens that doc. */
| {type: 'prose'; text: string}
| {type: 'heading'; level: 3 | 4 | 5 | 6; text: string}
| {type: 'code'; lang: string; code: string; label?: string}
diff --git a/packages/cli/authoring/doctypes/schema/schema.doc.mjs b/packages/cli/authoring/doctypes/schema/schema.doc.mjs
index 9f56ec63be..e6d643597f 100644
--- a/packages/cli/authoring/doctypes/schema/schema.doc.mjs
+++ b/packages/cli/authoring/doctypes/schema/schema.doc.mjs
@@ -49,7 +49,7 @@ export const doc = {
name: 'namespace',
type: 'string',
description:
- "The `astryx docs` topic that reads this doc: 'authoring' for a file an author writes (a section of `astryx docs authoring`), or 'cli/api' for a shape the CLI returns (the section `api-<name>` of the `cli` topic). Every schema doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads.",
+ "The group that reads this doc: 'authoring' for a file an author writes (a section of `astryx docs authoring`), or 'cli/api' for a shape the CLI returns (the docs tree adopts it by kind, as the leaf `cli/api/schemas/<name>`). Every schema doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that nothing reads.",
},
{
name: 'aliases',
diff --git a/packages/cli/authoring/doctypes/schema/type.ts b/packages/cli/authoring/doctypes/schema/type.ts
index 269bf86354..3d6c2f1f90 100644
--- a/packages/cli/authoring/doctypes/schema/type.ts
+++ b/packages/cli/authoring/doctypes/schema/type.ts
@@ -47,7 +47,7 @@ export interface SchemaDoc extends AuthoredDocGraphFields {
displayName: string;
/** One-line summary shown in listings. */
description: string;
- /** The `astryx docs` topic that reads this doc: 'authoring' for a file an author writes (a section of `astryx docs authoring`), or 'cli/api' for a shape the CLI returns (the section `api-<name>` of the `cli` topic). Every schema doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads. */
+ /** The group that reads this doc: 'authoring' for a file an author writes (a section of `astryx docs authoring`), or 'cli/api' for a shape the CLI returns (the docs tree adopts it by kind, as the leaf `cli/api/schemas/<name>`). Every schema doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that nothing reads. */
namespace?: string;
/** Alternate slugs that also resolve to this doc (back-compat). */
aliases?: string[];
diff --git a/packages/cli/authoring/doctypes/template/parse.mjs b/packages/cli/authoring/doctypes/template/parse.mjs
index 8e2ce4b45b..fe8aa6ca90 100644
--- a/packages/cli/authoring/doctypes/template/parse.mjs
+++ b/packages/cli/authoring/doctypes/template/parse.mjs
@@ -51,6 +51,10 @@ const baseTemplateFields = {
scaffold: z.boolean().optional(),
isHiddenFromOverview: z.boolean().optional(),
registry: registryIdentitySchema.optional(),
+ replaces: z
+ .string()
+ .min(1, 'replaces must name a Core template id')
+ .optional(),
};
const pageTemplateSchema = z
diff --git a/packages/cli/authoring/doctypes/template/parse.test.mjs b/packages/cli/authoring/doctypes/template/parse.test.mjs
index 9ed67ca710..80ea25acc6 100644
--- a/packages/cli/authoring/doctypes/template/parse.test.mjs
+++ b/packages/cli/authoring/doctypes/template/parse.test.mjs
@@ -22,6 +22,24 @@ function reason(value, label = 'template') {
}
describe('parseTemplate (load boundary)', () => {
+ it('accepts replaces on page and block templates', () => {
+ for (const type of ['page', 'block']) {
+ const parsed = parseTemplate({
+ type,
+ name: 'Acme shell',
+ description: 'Replaces a Core template.',
+ replaces: 'shell-side-nav',
+ });
+ expect(parsed.replaces).toBe('shell-side-nav');
+ }
+ });
+
+ it('rejects an empty replaces', () => {
+ expect(reason({type: 'page', name: 'Acme shell', replaces: ''})).toMatch(
+ /replaces must name a Core template id/,
+ );
+ });
+
it('accepts a stamped page template', () => {
const parsed = parseTemplate({
type: 'page',
diff --git a/packages/cli/authoring/doctypes/template/template.doc.mjs b/packages/cli/authoring/doctypes/template/template.doc.mjs
index d5f08bad8d..8c44f1b9b7 100644
--- a/packages/cli/authoring/doctypes/template/template.doc.mjs
+++ b/packages/cli/authoring/doctypes/template/template.doc.mjs
@@ -52,6 +52,12 @@ export const doc = {
type: 'string',
description: 'One-sentence description of what the template provides.',
},
+ {
+ name: 'replaces',
+ type: 'string',
+ description:
+ "Integration templates only: the exact id of the Core template this one replaces for unqualified lookup. Find it with `astryx --json template --list --package @astryxdesign/core`; the Core original stays selectable with `--package @astryxdesign/core`. A page replaces only a Core page and a block only a Core block. Needs @astryxdesign/cli 0.7.0 or later: earlier CLIs reject the field and withhold the package's templates and doc topics.",
+ },
{
name: 'isReady',
type: 'boolean',
diff --git a/packages/cli/authoring/doctypes/template/type.ts b/packages/cli/authoring/doctypes/template/type.ts
index f7bcb31ac9..c3b0936d67 100644
--- a/packages/cli/authoring/doctypes/template/type.ts
+++ b/packages/cli/authoring/doctypes/template/type.ts
@@ -28,6 +28,14 @@ export interface BaseTemplateDoc extends AuthoredDocGraphFields {
/** Optional stable slug override and prior aliases for registry output. */
registry?: RegistryDocIdentity;
+
+ /** Integration templates only: the exact id of the Core template this one
+ * replaces for unqualified lookup (find it with
+ * `astryx --json template --list --package @astryxdesign/core`). The Core
+ * original stays selectable with `--package @astryxdesign/core`. Needs
+ * `@astryxdesign/cli` 0.7.0 or later: earlier CLIs reject the field and
+ * withhold the package's templates and doc topics. */
+ replaces?: string;
/** Whether this template is ready for use. Templates with
* isReady: false show as "(WIP)" in the gallery and CLI. */
isReady?: boolean;
diff --git a/packages/cli/authoring/identity/identity.doc.mjs b/packages/cli/authoring/identity/identity.doc.mjs
index ca01da6dbc..69d95ecb64 100644
--- a/packages/cli/authoring/identity/identity.doc.mjs
+++ b/packages/cli/authoring/identity/identity.doc.mjs
@@ -12,9 +12,9 @@ export const doc = {
displayName: 'Provider and artifact identity',
namespace: 'authoring',
description:
- 'Separates stable provider/artifact identity from package instances and runtime lifecycle state. providerId is in use today: an integration manifest may declare it, and Doctor and every command report two packages that claim one. The artifact, doc, instance, and compiler-input identities are defined for the docs graph, which is not built yet, and no command reads them.',
+ 'Separates stable provider/artifact identity from package instances and runtime lifecycle state. Provider identity names integration manifests and settles provider conflicts. Docs-tree nodes are identified by doc identity; the tree covers the CLI\'s own docs. Artifact, instance, and compiler-input identities are defined for every provider-owned artifact; no command reads them.',
appliesTo:
- 'Integration manifests and provider conflicts today; the docs graph once it ships',
+ 'Integration manifests, provider conflicts, and docs-tree node ids.',
fields: [
{
name: 'ProviderId',
diff --git a/packages/cli/authoring/integration/type.ts b/packages/cli/authoring/integration/type.ts
index aaf813d5c3..cac9ae40fc 100644
--- a/packages/cli/authoring/integration/type.ts
+++ b/packages/cli/authoring/integration/type.ts
@@ -11,7 +11,7 @@
* The manifest module may also carry `debug` and `gapReport` NAMED exports.
* They are not fields here on purpose: a CLI released before a given manifest
* field existed could reject it and lose every contribution, while an unknown
- * named export is simply not read. See the `cli-integrations` doc topic.
+ * named export is simply not read. See `astryx docs cli/integrations`.
*/
export interface AstryxIntegration {
/** Stable logical provider ID. Omit to use package.json#name. Set this only
diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjs
index cb90ea65f4..56e50cf59a 100644
--- a/packages/cli/clients/cli/commands/build-theme.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.mjs
@@ -196,7 +196,7 @@ async function warnOnThemeIntegrationIssues(json) {
try {
const project = await Project.load(process.cwd());
await project.themes();
- await warnOnIntegrationIssues(project.loadedIntegrations, {json});
+ await warnOnIntegrationIssues(project, {json});
} catch {
// Never let the nudge break the command.
}
diff --git a/packages/cli/clients/cli/commands/build.mjs b/packages/cli/clients/cli/commands/build.mjs
index cd04d363c0..218089f1de 100644
--- a/packages/cli/clients/cli/commands/build.mjs
+++ b/packages/cli/clients/cli/commands/build.mjs
@@ -177,10 +177,13 @@ export function registerBuild(program) {
// `template <name> <path>` scaffolds into your project; <path> is the file
// (or folder) to write it to — a placeholder, since we can't know your
// layout. `--skeleton` and `component <Name>` just print, so no path.
+ const pageCommand = pages.length
+ ? formatCliCommand(pages[0].command)
+ : null;
const startCmd = directMatch
- ? `${run} template ${pages[0].name} <path>`
+ ? `${pageCommand} <path>`
: pages.length
- ? `${run} template ${pages[0].name} --skeleton`
+ ? pageCommand
: `${run} component AppShell`;
const startNote = directMatch
? `This \`${pages[0].name}\` page template appears to be the closest to what you want, so we recommend scaffolding it into your project — replace \`<path>\` with the file (or folder) to write it to — then adapting. Otherwise, browse PAGE TEMPLATES first, then BLOCKS and DOMAIN COMPONENTS below.`
diff --git a/packages/cli/clients/cli/commands/component-ownership.test.mjs b/packages/cli/clients/cli/commands/component-ownership.test.mjs
index a9887902ea..c66a2a12b2 100644
--- a/packages/cli/clients/cli/commands/component-ownership.test.mjs
+++ b/packages/cli/clients/cli/commands/component-ownership.test.mjs
@@ -71,7 +71,7 @@ function createFixture({
);
fs.writeFileSync(
path.join(compDir, 'MetaAppShell.doc.mjs'),
- `export const docs = {\n name: 'MetaAppShell',\n usage: { description: 'Meta-flavored app shell.' },\n props: [{ name: 'title', type: 'string', description: 'Header title' }],\n};\n`,
+ `export default {\n type: 'component',\n name: 'MetaAppShell',\n usage: { description: 'Meta-flavored app shell.' },\n props: [{ name: 'title', type: 'string', description: 'Header title' }],\n};\n`,
);
if (withSource) {
fs.writeFileSync(
@@ -82,7 +82,7 @@ function createFixture({
if (extraComponent) {
fs.writeFileSync(
path.join(compDir, `${extraComponent}.doc.mjs`),
- `export const docs = {\n name: '${extraComponent}',\n usage: { description: '${extraComponent} from meta.' },\n};\n`,
+ `export default {\n type: 'component',\n name: '${extraComponent}',\n usage: { description: '${extraComponent} from meta.' },\n props: [],\n};\n`,
);
fs.writeFileSync(
path.join(compDir, `${extraComponent}.tsx`),
@@ -100,7 +100,7 @@ function createFixture({
: '';
fs.writeFileSync(
path.join(entryDir, `${entryPoint.component}.doc.mjs`),
- `export const docs = {\n name: '${entryPoint.component}',${ownSpecifier}\n usage: { description: '${entryPoint.component} from an entry point.' },\n};\n`,
+ `export default {\n type: 'component',\n name: '${entryPoint.component}',${ownSpecifier}\n usage: { description: '${entryPoint.component} from an entry point.' },\n props: [],\n};\n`,
);
}
diff --git a/packages/cli/clients/cli/commands/component/index.mjs b/packages/cli/clients/cli/commands/component/index.mjs
index 92a6072ef5..5d38329a42 100644
--- a/packages/cli/clients/cli/commands/component/index.mjs
+++ b/packages/cli/clients/cli/commands/component/index.mjs
@@ -111,7 +111,7 @@ export function registerComponent(program) {
// doctor integration validate. Best-effort; suppressed in --json mode.
try {
const project = await Project.load(process.cwd());
- await warnOnIntegrationIssues(project.loadedIntegrations, {json});
+ await warnOnIntegrationIssues(project, {json});
} catch {
// Never let the nudge break the command.
}
diff --git a/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs b/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs
index 7af13d118f..cb19040e43 100644
--- a/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs
+++ b/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs
@@ -69,11 +69,12 @@ describe('astryx discover with a manifest that fails to load', () => {
expect(status).toBe(0);
expect(stderr).toContain(
- 'Warning: @test/broken has 1 integration issue(s). ' +
- 'Run: astryx doctor integration validate @test/broken',
+ 'Warning: @test/broken has 1 integration issue(s). Run: astryx doctor',
);
expect(stdout).not.toContain('No integrations configured.');
- expect(stdout).toContain('No external components found in configured integrations.');
+ expect(stdout).toContain(
+ 'No external components found in configured integrations.',
+ );
});
it('reports meta.configured=true in --json, with the nudge suppressed', async () => {
@@ -101,7 +102,7 @@ describe('astryx discover with a configured package that is not installed', () =
);
fs.writeFileSync(
path.join(healthy, 'components', 'Widget.doc.mjs'),
- `export const docs = {name: 'Widget', usage: {description: 'A widget.'}};\n`,
+ `export const docs = {name: 'Widget', usage: {description: 'A widget.'}, props: []};\n`,
);
fs.writeFileSync(
path.join(healthy, 'components', 'Widget.tsx'),
@@ -129,8 +130,7 @@ describe('astryx discover with a configured package that is not installed', () =
expect(status).toBe(0);
expect(stderr).toContain(
- 'Warning: @test/missing has 1 integration issue(s). ' +
- 'Run: astryx doctor integration validate @test/missing',
+ 'Warning: @test/missing has 1 integration issue(s). Run: astryx doctor\n',
);
});
});
@@ -149,8 +149,7 @@ describe('astryx search with a manifest that fails to load', () => {
expect(status).toBe(0);
expect(stderr).toContain(
- 'Warning: @test/broken has 1 integration issue(s). ' +
- 'Run: astryx doctor integration validate @test/broken',
+ 'Warning: @test/broken has 1 integration issue(s). Run: astryx doctor',
);
const asJson = await runCli(['search', 'button', '--json'], {cwd: project});
diff --git a/packages/cli/clients/cli/commands/discover.mjs b/packages/cli/clients/cli/commands/discover.mjs
index 6c10fa57eb..17e41cd9e8 100644
--- a/packages/cli/clients/cli/commands/discover.mjs
+++ b/packages/cli/clients/cli/commands/discover.mjs
@@ -83,7 +83,7 @@ export function registerDiscover(program) {
// doctor integration validate. Best-effort; suppressed in --json mode.
try {
const project = await Project.load(process.cwd());
- await warnOnIntegrationIssues(project.loadedIntegrations, {json});
+ await warnOnIntegrationIssues(project, {json});
} catch {
// Never let the nudge break the command.
}
diff --git a/packages/cli/clients/cli/commands/docs.doc.mjs b/packages/cli/clients/cli/commands/docs.doc.mjs
index c5a592aeb9..c1a592f693 100644
--- a/packages/cli/clients/cli/commands/docs.doc.mjs
+++ b/packages/cli/clients/cli/commands/docs.doc.mjs
@@ -15,10 +15,14 @@ export const doc = {
namespace: 'cli/commands',
summary: 'Print reference docs',
description:
- 'Reads the reference docs: with no topic it lists every topic; a topic prints that ' +
- 'full doc; `--index` lists its sections instead, each with the key to read it by; a ' +
- 'topic plus a section prints that section (by key, exact title, or a unique part of ' +
- 'a title).',
+ 'Reads the reference docs one level at a time: with no topic it lists every topic; a ' +
+ 'topic lists its sections, each with the key to read it by (a topic with one section ' +
+ 'prints whole); a topic plus a section prints that section; `--full` prints the whole ' +
+ 'topic, as does `--dense`. With `--json`, a topic returns its whole doc, as docs() ' +
+ 'does, and `--index` its section index. A route ' +
+ 'opens a node of the docs tree: `cli` lists its guides and reference, ' +
+ '`cli/api/functions` lists every API function, and `cli/api/functions/search` prints ' +
+ 'one.',
fn: 'docs',
args: [
{name: 'topic', param: 'topic', required: false},
@@ -28,20 +32,28 @@ export const doc = {
{
flag: '--index',
param: 'options.index',
- description: "List the topic's sections and their keys instead of printing the whole topic",
+ description: "List the topic's sections and their keys, even for a topic with one section",
+ },
+ {
+ flag: '--full',
+ description:
+ 'Print the whole topic instead of its sections (text; `--json` returns the whole topic unless --index). Cannot be set with --index',
},
],
examples: [
{label: 'List topics', cli: 'astryx docs'},
- {label: 'One topic as JSON', cli: 'astryx docs spacing --json'},
- {label: "A topic's sections", cli: 'astryx docs theme --index'},
+ {label: "A topic's sections", cli: 'astryx docs theme'},
+ {label: 'A whole topic as JSON', cli: 'astryx docs spacing --json'},
{label: 'One section', cli: 'astryx docs theme quick-start'},
+ {label: 'The CLI docs tree', cli: 'astryx docs cli'},
+ {label: 'One API function', cli: 'astryx docs cli/api/functions/search'},
+ {label: 'A whole guide', cli: 'astryx docs cli/integrations --full'},
],
exitCodes: [
{code: 0, when: 'success'},
{
code: 1,
- when: 'unknown topic, or a section that matches no section or more than one',
+ when: 'unknown topic or route, or a section that matches no section or more than one',
},
],
related: ['search', 'component', 'hook', 'template'],
diff --git a/packages/cli/clients/cli/commands/docs.mjs b/packages/cli/clients/cli/commands/docs.mjs
index 3a912ba23f..81d05bc0ed 100644
--- a/packages/cli/clients/cli/commands/docs.mjs
+++ b/packages/cli/clients/cli/commands/docs.mjs
@@ -3,18 +3,26 @@
/**
* @file docs command — Print Astryx reference docs
*
- * A topic prints its whole doc; `--index` lists its sections instead, so a
- * reader can open one section by its key.
+ * In text, every read is one level: a topic lists its sections, so a reader can
+ * open one section by its key, and `--full` prints the whole topic. `--json`
+ * keeps the docs() contract: a topic returns its whole doc, and `--index` its
+ * sections.
* Supports --detail (full|compact|brief) and --lang (en|zh|dense).
*
* Usage:
* astryx docs List available topics
- * astryx docs <topic> Print the whole topic
- * astryx docs <topic> --index List the topic's sections
+ * astryx docs <topic> List the topic's sections (a topic
+ * with one section prints whole)
* astryx docs <topic> <section> Print one section
+ * astryx docs <topic> --full Print the whole topic
+ * astryx docs <route> Open a node of the docs tree, such as
+ * cli, cli/api, or cli/api/functions/search
*/
-import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
+import {
+ formatCliCommand,
+ getCliInvocation,
+} from '../../../foundation/env/package-manager.mjs';
import {jsonOut} from '../../../foundation/response/json.mjs';
import {
emit,
@@ -25,6 +33,7 @@ import {
wrapText,
} from '../formatters/index.mjs';
import {cliError} from '../lib/cli-error.mjs';
+import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
import {defineCommand} from '../lib/define-command.mjs';
import {resultSet} from '../../../foundation/debug/index.mjs';
import {docs as docsApi} from '../../../api/docs/docs.mjs';
@@ -146,6 +155,24 @@ function formatReferenceFull(docs, detail) {
return `${header}\n\n${sections.join(sep)}`;
}
+/**
+ * The moves a read offers (spec:AST-047), one runnable command per line: up to
+ * the level it sits in, the item before and after it, and the docs it names.
+ * @param {import('../../../api/docs/docs.type.mjs').DocsLinks | undefined} links
+ * @returns {string[]}
+ */
+function linkLines(links) {
+ if (!links) return [];
+ return [
+ `Up: ${formatCliCommand(links.up)}`,
+ ...(links.previous ? [`Previous: ${formatCliCommand(links.previous)}`] : []),
+ ...(links.next ? [`Next: ${formatCliCommand(links.next)}`] : []),
+ ...(links.related ?? []).map(
+ (command, i) => `${i === 0 ? 'Related: ' : ' '}${formatCliCommand(command)}`,
+ ),
+ ];
+}
+
/**
* A topic's section index: what the topic is, one line per section with the
* key to read it by, and how to read further.
@@ -158,20 +185,80 @@ function emitIndex(index, run) {
index.title,
index.description ? wrapText(index.description) : undefined,
),
+ // Summaries wrap rather than being cut: the summary is how a reader picks
+ // the one section to open.
records(index.sections, {
fields: ['id', 'title', 'summary'],
layout: 'inline',
- overflow: 'truncate',
}),
text(
[
`Read one section: ${run} docs ${index.name} <section>`,
- `Read everything: ${run} docs ${index.name}`,
+ `Read everything: ${run} docs ${index.name} --full`,
+ ...linkLines(index.links),
].join('\n'),
),
);
}
+/**
+ * One child row of a namespace: its route name, then the doc's own title when
+ * it is not the route name (`assertResponse()`, `search()`), then its summary.
+ * @param {import('../../../api/docs/docs.type.mjs').DocsNodeChild} child
+ * @returns {{name: string, summary: string}}
+ */
+function childRow(child) {
+ return {
+ name: child.name,
+ summary:
+ child.title === child.name ? child.summary : `${child.title}: ${child.summary}`,
+ };
+}
+
+/**
+ * One node of the docs tree. A namespace lists each slot's children, one level
+ * down, with the command to open one; a typed doc prints its content. Both end
+ * with the way back up.
+ * @param {import('../../../api/docs/docs.type.mjs').DocsNode} node
+ * @param {'full' | 'compact' | 'brief'} detail
+ * @param {string} run
+ */
+function emitNode(node, detail, run) {
+ if (node.kind === 'namespace') {
+ emit(
+ section(node.title, wrapText(node.summary)),
+ ...node.slots.flatMap(slot => [
+ // A namespace with one slot titled like itself needs no second heading.
+ ...(node.slots.length === 1 && slot.title === node.title
+ ? []
+ : [section(slot.title)]),
+ records(slot.children.map(childRow), {
+ fields: ['name', 'summary'],
+ layout: 'inline',
+ overflow: 'truncate',
+ }),
+ ]),
+ text(
+ [
+ // A child's route is its parent's route and its name, except a flat
+ // topic in the Unorganized level, which keeps its own name.
+ node.slots.every(slot =>
+ slot.children.every(child => child.route.startsWith(`${node.route}/`)),
+ )
+ ? `Open one: ${run} docs ${node.route}/<name>`
+ : `Open one: ${run} docs <name>`,
+ ...linkLines(node.links),
+ ].join('\n'),
+ ),
+ );
+ return;
+ }
+ emit(
+ code(formatSection({title: node.title, content: node.content}, detail)),
+ text(linkLines(node.links).join('\n')),
+ );
+}
+
/**
* What the run answered with. A named topic (or one of its sections) resolves
* or throws, so it is always a direct match of one doc; the bare form lists
@@ -180,7 +267,8 @@ function emitIndex(index, run) {
* @param {import('../../../api/docs/docs.type.mjs').DocsListResponse
* | import('../../../api/docs/docs.type.mjs').DocsIndexResponse
* | import('../../../api/docs/docs.type.mjs').DocsDetailResponse
- * | import('../../../api/docs/docs.type.mjs').DocsDetailSectionResponse} result
+ * | import('../../../api/docs/docs.type.mjs').DocsDetailSectionResponse
+ * | import('../../../api/docs/docs.type.mjs').DocsNodeResponse} result
* @returns {import('../../../foundation/debug/command-result.mjs').CommandResult}
*/
function summarize(result) {
@@ -200,7 +288,7 @@ export function registerDocs(program) {
action: async (
/** @type {string | undefined} */ topic,
/** @type {string | undefined} */ sectionName,
- /** @type {{index?: boolean}} */ options = {},
+ /** @type {{index?: boolean, full?: boolean}} */ options = {},
) => {
const run = getCliInvocation();
const lang = program.opts().lang || null;
@@ -209,14 +297,37 @@ export function registerDocs(program) {
const detail = program.opts().detail || 'full';
const json = program.opts().json || false;
+ if (options.index && options.full) {
+ return cliError(
+ 'Ask for the section list or the whole topic, not both: --index and --full cannot both be set.',
+ {code: ERROR_CODES.ERR_INVALID_ARGUMENT},
+ );
+ }
+ // Text reads one level: a topic lists its sections (one with a single
+ // section prints whole). JSON keeps docs(): the whole topic unless
+ // --index. The dense variant is written to be read whole.
+ const listSections =
+ Boolean(options.index) ||
+ (!json &&
+ !options.full &&
+ !dense &&
+ lang !== 'dense' &&
+ sectionName == null);
let result;
try {
result = await docsApi(topic, sectionName, {
lang,
zh,
dense,
- index: Boolean(options.index),
+ index: listSections,
});
+ if (
+ !options.index &&
+ result.type === 'docs.index' &&
+ result.data.sections.length <= 1
+ ) {
+ result = await docsApi(topic, sectionName, {lang, zh, dense});
+ }
} catch (e) {
// docs API throws structured errors with {name, reason} suggestions —
// pass them through untouched so the CLI envelope matches the API.
@@ -236,17 +347,50 @@ export function registerDocs(program) {
switch (result.type) {
case 'docs.list': {
- // Keep the published 0.6 text projection: stacked topic and
- // description fields, followed by the two original usage lines.
+ // The text view mirrors the JSON list, with the docs tree's
+ // namespaces (`meta.namespaces`) first under their own heading: that
+ // is where the CLI's own docs start, and a namespace reads
+ // differently from a topic.
+ const namespaces = result.meta?.namespaces ?? [];
+ const topics = result.data;
emit(
- section('Available docs'),
- records(result.data, {fields: ['topic', 'description']}),
+ ...(namespaces.length > 0
+ ? [
+ section('Docs tree'),
+ records(namespaces, {
+ fields: ['topic', 'description', 'package'],
+ layout: 'inline',
+ }),
+ ]
+ : []),
+ section('Topics'),
+ records(topics, {
+ fields: ['topic', 'description', 'package'],
+ layout: 'inline',
+ }),
text(
[
- `Usage: ${run} docs <topic>`,
- ` ${run} docs <topic> <section>`,
+ `Usage: ${run} docs <topic> list a topic's sections`,
+ ` ${run} docs <topic> <section> read one section`,
+ ` ${run} docs <topic> --full read the whole topic`,
+ ` ${run} docs cli/api go down the docs tree one level at a time`,
+ `With --json, a topic returns its whole doc; add --index for its section list.`,
].join('\n'),
),
+ // A package whose doc files did not load has no topics here; say
+ // so, and where to look, instead of leaving them silently missing.
+ ...(result.meta?.notLoaded?.length
+ ? [
+ section('Not loaded'),
+ records(result.meta.notLoaded, {
+ fields: ['package', 'message'],
+ layout: 'inline',
+ }),
+ text(
+ `Run \`${run} doctor integration docs\` in that package to see every problem.`,
+ ),
+ ]
+ : []),
);
break;
}
@@ -257,12 +401,25 @@ export function registerDocs(program) {
}
case 'docs.detail': {
- emit(code(formatReferenceFull(result.data, detail)));
+ emit(
+ code(formatReferenceFull(result.data, detail)),
+ text(linkLines(result.data.links).join('\n')),
+ );
break;
}
case 'docs.detail.section': {
- emit(code(formatSection(result.data, detail)));
+ // One section ends with its moves: up to its topic's index, and to
+ // the sections before and after it.
+ emit(
+ code(formatSection(result.data, detail)),
+ text(linkLines(result.data.links).join('\n')),
+ );
+ break;
+ }
+
+ case 'docs.node': {
+ emitNode(result.data, detail, run);
break;
}
}
diff --git a/packages/cli/clients/cli/commands/docs.test.mjs b/packages/cli/clients/cli/commands/docs.test.mjs
index d2c0d8e220..05133acc43 100644
--- a/packages/cli/clients/cli/commands/docs.test.mjs
+++ b/packages/cli/clients/cli/commands/docs.test.mjs
@@ -75,7 +75,7 @@ describe('hyphenated doc filenames', () => {
it('returns docs.detail via API for hyphenated topic', async () => {
const {docs: docsApi} = await import('../../../api/docs/docs.mjs');
- const result = await docsApi('getting-started');
+ const result = await docsApi('getting-started', undefined, {full: true});
expect(result.type).toBe('docs.detail');
expect(result.data).toBeDefined();
expect(result.data.description).toBeDefined();
@@ -108,10 +108,11 @@ describe('progressive reads', () => {
/** @param {string} out */
const widest = out => Math.max(...out.split('\n').map(line => line.length));
- it('keeps the 0.6.x stacked topic list', async () => {
+ it('lists every topic on one line each', async () => {
const {status, stdout} = await runCli(['docs']);
expect(status).toBe(0);
- expect(stdout).toMatch(/^topic: +principles$/m);
+ expect(stdout).toMatch(/^principles +\S/m);
+ expect(widest(stdout)).toBeLessThanOrEqual(120);
expect(stdout).toContain('Usage: pnpm exec astryx docs <topic>');
}, SLOW);
@@ -120,7 +121,7 @@ describe('progressive reads', () => {
expect(status).toBe(0);
expect(stdout).toMatch(/^quick-start +Quick Start/m);
expect(stdout).toContain('docs theme <section>');
- expect(stdout).toMatch(/Read everything: +\S.* docs theme$/m);
+ expect(stdout).toMatch(/Read everything: +\S.* docs theme --full$/m);
expect(widest(stdout)).toBeLessThanOrEqual(120);
}, SLOW);
@@ -130,20 +131,23 @@ describe('progressive reads', () => {
expect(stdout).toMatch(/^## Quick Start/m);
}, SLOW);
- it('prints the whole topic by default, as before', async () => {
+ it("lists a topic's sections by default; --full prints the whole topic", async () => {
const index = await runCli(['docs', 'theme', '--index']);
- const full = await runCli(['docs', 'theme']);
+ expect((await runCli(['docs', 'theme'])).stdout).toBe(index.stdout);
+ const full = await runCli(['docs', 'theme', '--full']);
expect(full.status).toBe(0);
expect(full.stdout).toMatch(/^## Quick Start/m);
expect(full.stdout.length).toBeGreaterThan(index.stdout.length * 3);
- expect((await runCli(['--detail', 'full', 'docs', 'theme'])).stdout).toBe(
+ expect((await runCli(['--detail', 'full', 'docs', 'theme', '--full'])).stdout).toBe(
full.stdout,
);
}, SLOW);
it('returns the matching envelopes as JSON', async () => {
const envelope = async args => JSON.parse((await runCli([...args, '--json'])).stdout);
+ // JSON keeps docs(): a bare read is the whole topic.
expect((await envelope(['docs', 'theme'])).type).toBe('docs.detail');
+ expect((await envelope(['docs', 'theme', '--full'])).type).toBe('docs.detail');
expect((await envelope(['docs', 'theme', '--index'])).type).toBe(
'docs.index',
);
@@ -153,6 +157,109 @@ describe('progressive reads', () => {
}, SLOW);
});
+describe('the docs tree, one level at a time', () => {
+ const SLOW = 60_000;
+ /** @param {string} out */
+ const widest = out => Math.max(...out.split('\n').map(line => line.length));
+
+ it('lists the docs tree first, under its own heading, then the topics', async () => {
+ const {status, stdout} = await runCli(['docs']);
+ expect(status).toBe(0);
+ expect(stdout).toMatch(/^Docs tree$/m);
+ expect(stdout).toMatch(/^Topics$/m);
+ expect(stdout).toMatch(/^cli +Commands, programmatic APIs/m);
+ expect(stdout.indexOf('\ncli ')).toBeLessThan(stdout.indexOf('\nprinciples '));
+ expect(stdout).not.toMatch(/^cli-integrations /m);
+ }, SLOW);
+
+ it("shows a child's own name when its route name does not spell it", async () => {
+ const {status, stdout} = await runCli(['docs', 'cli/api/functions']);
+ expect(status).toBe(0);
+ expect(stdout).toMatch(/^assert-response +assertResponse\(\): \S/m);
+ expect(stdout).toMatch(/^search +search\(\): Unified ranked search/m);
+ }, SLOW);
+
+ it('prints a namespace: each slot, its children, and how to go down and up', async () => {
+ const {status, stdout} = await runCli(['docs', 'cli/api']);
+ expect(status).toBe(0);
+ expect(stdout).toMatch(/^API$/m);
+ expect(stdout).toMatch(/^Reference$/m);
+ expect(stdout).toMatch(/^functions +Functions: Every function/m);
+ expect(stdout).toMatch(/^schemas +/m);
+ expect(stdout).toMatch(/^enums +/m);
+ // One level only: no function is listed on the api page.
+ expect(stdout).not.toMatch(/^search +/m);
+ expect(stdout).toMatch(/Open one: .*docs cli\/api\/<name>$/m);
+ expect(stdout).toMatch(/Up: .*docs cli$/m);
+ expect(widest(stdout)).toBeLessThanOrEqual(120);
+ }, SLOW);
+
+ it('prints a typed doc and the way back up', async () => {
+ const {status, stdout} = await runCli(['docs', 'cli/api/functions/search']);
+ expect(status).toBe(0);
+ expect(stdout).toMatch(/^## search\(\)/m);
+ expect(stdout).toContain('Read it with `astryx docs cli/commands/search`.');
+ expect(stdout).toMatch(/Up: .*docs cli\/api\/functions$/m);
+ }, SLOW);
+
+ it('reads the dense variant whole, asked with --dense or with --lang dense', async () => {
+ for (const args of [['--dense', 'docs', 'theme'], ['--lang', 'dense', 'docs', 'theme']]) {
+ const {status, stdout} = await runCli(args);
+ expect(status).toBe(0);
+ expect(stdout).not.toContain('Read one section:');
+ }
+ }, SLOW);
+
+ it('refuses --index with --full', async () => {
+ const both = await runCli(['docs', 'theme', '--index', '--full', '--json']);
+ expect(both.status).toBe(1);
+ expect(JSON.parse(both.stdout).code).toBe('ERR_INVALID_ARGUMENT');
+ }, SLOW);
+
+ it('reads the integration guide by its route, and not by its old name', async () => {
+ const guide = await runCli(['docs', 'cli/integrations', '--index']);
+ expect(guide.status).toBe(0);
+ expect(guide.stdout).toMatch(/Read one section: .*docs cli\/integrations <section>/);
+ // A bare read is one level too: the sections, and how to read it all.
+ const bare = await runCli(['docs', 'cli/integrations']);
+ expect(bare.status).toBe(0);
+ expect(bare.stdout).toBe(guide.stdout);
+ expect(bare.stdout).toMatch(/Read everything: +.*docs cli\/integrations --full$/m);
+ const one = await runCli(['docs', 'cli/integrations', 'codemods']);
+ expect(one.status).toBe(0);
+ expect(one.stdout).toMatch(/^## Codemods$/m);
+ expect(one.stdout).toMatch(/^Up: .*docs cli\/integrations --index$/m);
+ expect(one.stdout).toMatch(/^Previous: .*docs cli\/integrations agent-docs$/m);
+ expect(one.stdout).toMatch(/^Next: .*docs cli\/integrations recording-runs$/m);
+ const full = await runCli(['docs', 'cli/integrations', '--full']);
+ expect(full.status).toBe(0);
+ expect(full.stdout).toMatch(/^## Overview$/m);
+ expect(full.stdout.length).toBeGreaterThan(bare.stdout.length * 4);
+ const old = await runCli(['docs', 'cli-integrations']);
+ expect(old.status).toBe(1);
+ expect(old.stderr).toContain('Unknown topic "cli-integrations"');
+ }, SLOW);
+
+ it('returns docs.node as JSON, and fails a section of a namespace', async () => {
+ const node = JSON.parse((await runCli(['docs', 'cli', '--json'])).stdout);
+ expect(node).toMatchObject({
+ type: 'docs.node',
+ data: {route: 'cli', kind: 'namespace', breadcrumb: []},
+ });
+ expect(node.data.slots.map(slot => slot.name)).toEqual(['guides', 'reference']);
+ const section = await runCli(['docs', 'cli', 'commands', '--json']);
+ expect(section.status).toBe(1);
+ const error = JSON.parse(section.stdout);
+ expect(error).toMatchObject({code: 'ERR_UNKNOWN_SECTION'});
+ expect(error.suggestions.map(s => s.name)).toEqual([
+ 'cli/integrations',
+ 'cli/writing-docs',
+ 'cli/commands',
+ 'cli/api',
+ ]);
+ }, SLOW);
+});
+
describe('text width in every language', () => {
const SLOW = 60_000;
/** Widest line outside code blocks, in terminal columns. */
diff --git a/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjs
index 1b12790bd4..0f7ab7565c 100644
--- a/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjs
+++ b/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjs
@@ -8,7 +8,7 @@ export const doc = {
name: 'doctor integration docs',
displayName: 'astryx doctor integration docs',
namespace: 'cli/commands',
- summary: 'Classify integration doc overlaps with Core topics',
+ summary: 'Check an integration\'s docs: the docs tree they add, every link, and overlaps with Core topics',
description:
'Reports intentional Core topic replacements and extensions as information. ' +
'A same-name topic without `replaces` or `extends` is an accidental conflict ' +
@@ -32,7 +32,7 @@ export const doc = {
],
exitCodes: [
{code: 0, when: 'all Core overlaps are explicitly declared or no overlap exists'},
- {code: 1, when: 'an overlap is accidental or the integration docs are invalid'},
+ {code: 1, when: 'an overlap is accidental, a doc is invalid, or a namespace or placement fails. A link that names no doc is a warning, and does not change the exit code'},
],
related: ['doctor integration validate', 'docs'],
};
diff --git a/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjs
index d44a5e4a8a..051a2c4d34 100644
--- a/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjs
+++ b/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjs
@@ -10,12 +10,13 @@ export const doc = {
name: 'doctor integration templates',
displayName: 'astryx doctor integration templates',
namespace: 'cli/commands',
- summary: 'Warn when integration template ids conflict with Core',
+ summary: 'Validate integration template replacements and Core id overlaps',
description:
- 'Compares one local or installed integration with the built-in Core page and ' +
- 'block template ids. A conflict is allowed and exits successfully, but the ' +
- 'report recommends renaming and gives the exact --package command required ' +
- 'to select the integration template when the overlap is intentional.',
+ 'Validates one local or installed integration against the built-in Core page ' +
+ 'and block template ids. Intentional replacements are informational and name ' +
+ 'the command for selecting the Core original. Missing targets, ambiguous ' +
+ 'replacements, and invalid declarations are errors; undeclared same-id overlaps ' +
+ 'remain warnings that require package selection.',
fn: 'integrationTemplateConflicts',
args: [
{
@@ -37,8 +38,14 @@ export const doc = {
},
],
exitCodes: [
- {code: 0, when: 'the check completed; template conflicts are warnings'},
- {code: 1, when: 'the integration or one of its templates is invalid'},
+ {
+ code: 0,
+ when: 'replacement declarations are valid; undeclared id conflicts are warnings',
+ },
+ {
+ code: 1,
+ when: 'the integration, a template, or a replacement declaration is invalid',
+ },
],
related: ['doctor integration validate', 'template'],
};
diff --git a/packages/cli/clients/cli/commands/doctor-integration.test.mjs b/packages/cli/clients/cli/commands/doctor-integration.test.mjs
index 10b021391b..2996a3241c 100644
--- a/packages/cli/clients/cli/commands/doctor-integration.test.mjs
+++ b/packages/cli/clients/cli/commands/doctor-integration.test.mjs
@@ -31,6 +31,8 @@ function writeIntegration({
id,
name = 'Integration template',
missingRoot = false,
+ replacements,
+ type = 'page',
}) {
fs.writeFileSync(
path.join(tmpDir, 'package.json'),
@@ -45,7 +47,7 @@ function writeIntegration({
fs.mkdirSync(path.dirname(stem), {recursive: true});
fs.writeFileSync(
`${stem}.doc.mjs`,
- `export default {type: 'page', name: ${JSON.stringify(name)}, description: 'fixture'};\n`,
+ `export default {type: '${type}', name: ${JSON.stringify(name)}, description: 'fixture'${replacements?.[id] == null ? '' : `, replaces: ${JSON.stringify(replacements[id])}`}};\n`,
);
fs.writeFileSync(
`${stem}.tsx`,
@@ -249,6 +251,71 @@ describe('doctor integration — command', () => {
expect(process.exitCode).toBeUndefined();
});
+ it('templates reports an intentional replacement and the Core-original command', async () => {
+ const core = (await discoverCoreTemplates()).find(
+ template => template.type === 'page',
+ );
+ expect(core).toBeDefined();
+ writeIntegration({
+ id: 'acme-app-shell',
+ type: core.type,
+ replacements: {'acme-app-shell': core.dirName},
+ });
+ process.chdir(tmpDir);
+
+ await createProgram().parseAsync([
+ 'node',
+ 'astryx',
+ '--json',
+ 'doctor',
+ 'integration',
+ 'templates',
+ ]);
+
+ const parsed = JSON.parse(logCalls.join('\n'));
+ expect(parsed.data.issues).toEqual([]);
+ expect(parsed.data.conflicts).toEqual([
+ expect.objectContaining({
+ id: 'acme-app-shell',
+ relationship: 'replaces',
+ replaces: core.dirName,
+ severity: 'info',
+ }),
+ ]);
+ expect(parsed.data.conflicts[0].command).toContain(
+ `--package @astryxdesign/core`,
+ );
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it('templates exits 1 for a missing replacement target', async () => {
+ writeIntegration({
+ id: 'acme-app-shell',
+ replacements: {'acme-app-shell': 'missing-core-shell'},
+ });
+ process.chdir(tmpDir);
+
+ await createProgram().parseAsync([
+ 'node',
+ 'astryx',
+ '--json',
+ 'doctor',
+ 'integration',
+ 'templates',
+ ]);
+
+ const parsed = JSON.parse(logCalls.join('\n'));
+ expect(parsed.data.issues).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'missing_template_replacement_target',
+ severity: 'error',
+ }),
+ ]),
+ );
+ expect(process.exitCode).toBe(1);
+ });
+
it('templates exits 1 when structural errors prevent a trustworthy check', async () => {
writeIntegration({missingRoot: true});
process.chdir(tmpDir);
diff --git a/packages/cli/clients/cli/commands/doctor.mjs b/packages/cli/clients/cli/commands/doctor.mjs
index cfcebfadfa..f00357d97d 100644
--- a/packages/cli/clients/cli/commands/doctor.mjs
+++ b/packages/cli/clients/cli/commands/doctor.mjs
@@ -125,14 +125,18 @@ function printTemplateConflicts(data) {
),
...issueBlocks(data.issues),
];
- if (data.conflicts.length === 0) {
- output.push(text('[ok] No template ids conflict with Core.'));
- } else {
+ if (data.conflicts.length === 0 && data.issues.length === 0) {
+ output.push(
+ text('[ok] No template replacements or id conflicts with Core.'),
+ );
+ } else if (data.conflicts.length > 0) {
output.push(
records(data.conflicts, {
fields: [
'severity',
+ 'relationship',
'id',
+ 'replaces',
'integrationPackage',
'integrationType',
'integrationName',
@@ -141,10 +145,7 @@ function printTemplateConflicts(data) {
],
format: {severity: statusToken},
}),
- text(
- `${data.conflicts.length} Core template conflict(s). ` +
- 'Renaming is recommended but optional; keep the package-qualified command if the overlap is intentional.',
- ),
+ text(`${data.conflicts.length} Core template relationship(s).`),
);
}
emit(...output);
@@ -165,7 +166,13 @@ function printComponentConflicts(data) {
} else {
output.push(
records(data.conflicts, {
- fields: ['severity', 'name', 'integrationPackage', 'message', 'command'],
+ fields: [
+ 'severity',
+ 'name',
+ 'integrationPackage',
+ 'message',
+ 'command',
+ ],
format: {severity: statusToken},
}),
text(
@@ -187,6 +194,13 @@ function printDocConflicts(data) {
),
...issueBlocks(data.issues),
];
+ if (
+ !data.issues.some(
+ issue => issue.severity === 'error' || issue.code === 'invalid_doc_graph',
+ )
+ ) {
+ output.push(text('[ok] The docs tree and every link in these docs check out.'));
+ }
if (data.findings.length === 0) {
output.push(text('[ok] No doc topics overlap with Core.'));
} else {
@@ -272,7 +286,8 @@ async function runAuthoringCheck(program, pkg, kind) {
const structuralErrors = summarizeIssues(result.data.issues).errors;
const docErrors =
result.type === 'integration.doc-conflicts'
- ? result.data.findings.filter(finding => finding.severity === 'error').length
+ ? result.data.findings.filter(finding => finding.severity === 'error')
+ .length
: 0;
if (structuralErrors > 0 || docErrors > 0) process.exitCode = 1;
return NO_RESULT_SET;
diff --git a/packages/cli/clients/cli/commands/integration-add.doc.mjs b/packages/cli/clients/cli/commands/integration-add.doc.mjs
index c326ff192b..4655b761b4 100644
--- a/packages/cli/clients/cli/commands/integration-add.doc.mjs
+++ b/packages/cli/clients/cli/commands/integration-add.doc.mjs
@@ -50,6 +50,12 @@ export const doc = {
description:
'Existing doc topic this one extends (letters, digits, _ and -); only valid for doc and not with --replaces',
},
+ {
+ flag: '--parent <namespace>',
+ param: 'options.parent',
+ description:
+ "Namespace of this package to place the doc in, as a guide in its `guides` slot; writes the namespace doc when it is missing, and declares the CLI that reads it as an optional `@astryxdesign/cli` peer. Only valid for doc, and not with --replaces or --extends",
+ },
{
flag: '--to <version>',
param: 'options.to',
@@ -79,6 +85,10 @@ export const doc = {
label: 'Extend a doc topic',
cli: 'astryx integration add doc acme-theming --extends theme',
},
+ {
+ label: 'Add a guide to the package\'s own docs section',
+ cli: 'astryx integration add doc deploying --parent acme',
+ },
{
label: 'Add a codemod',
cli: 'astryx integration add codemod rename-widget --to 1.2.0',
diff --git a/packages/cli/clients/cli/commands/integration.mjs b/packages/cli/clients/cli/commands/integration.mjs
index 4db8108b4d..6da9164e8f 100644
--- a/packages/cli/clients/cli/commands/integration.mjs
+++ b/packages/cli/clients/cli/commands/integration.mjs
@@ -58,6 +58,7 @@ export function registerIntegration(program) {
templateType: options.type,
replaces: options.replaces,
extends: options.extends,
+ parent: options.parent,
to: options.to,
});
} catch (error) {
diff --git a/packages/cli/clients/cli/commands/search.mjs b/packages/cli/clients/cli/commands/search.mjs
index e8b77d4d83..ba7130a254 100644
--- a/packages/cli/clients/cli/commands/search.mjs
+++ b/packages/cli/clients/cli/commands/search.mjs
@@ -49,7 +49,7 @@ export function registerSearch(program) {
try {
const project = await Project.load(process.cwd());
- await warnOnIntegrationIssues(project.loadedIntegrations, {json});
+ await warnOnIntegrationIssues(project, {json});
} catch {
// Never let the nudge break the command.
}
@@ -115,7 +115,9 @@ export function registerSearch(program) {
const fields = options.verbose
? [
'name',
+ 'section',
'domain',
+ 'package',
'title',
'displayName',
'kind',
@@ -124,16 +126,20 @@ export function registerSearch(program) {
'import',
'description',
'command',
+ 'parent',
]
: [
'name',
+ 'section',
'domain',
+ 'package',
'title',
'displayName',
'kind',
'import',
'description',
'command',
+ 'parent',
];
// The heading mirrors the JSON: `matchCount` is what matched, and the
@@ -145,7 +151,10 @@ export function registerSearch(program) {
? `Results for "${q}" (${results.length} of ${matchCount})`
: `Results for "${q}" (${results.length})`,
),
- records(results, {fields, format: {command: formatCliCommand}}),
+ records(results, {
+ fields,
+ format: {command: formatCliCommand, parent: formatCliCommand},
+ }),
);
return answered;
},
diff --git a/packages/cli/clients/cli/commands/setup-nudge.test.mjs b/packages/cli/clients/cli/commands/setup-nudge.test.mjs
index 6f31a8c320..29b9f86862 100644
--- a/packages/cli/clients/cli/commands/setup-nudge.test.mjs
+++ b/packages/cli/clients/cli/commands/setup-nudge.test.mjs
@@ -89,6 +89,12 @@ describe('enforcement layer 3 — per-command setup nudge', () => {
expect((await runCli(['docs', 'tokens'], tmp)).stderr).not.toMatch(NUDGE);
});
+ it('is quiet in an integration package, which is not an app', async () => {
+ asProject();
+ write('astryx.integration.mjs', 'export default {};\n');
+ expect((await runCli(['docs', 'tokens'], tmp)).stderr).not.toMatch(NUDGE);
+ });
+
it('does not nudge for the installer command itself', async () => {
asProject();
expect((await runCli(['init'], tmp)).stderr).not.toMatch(NUDGE);
diff --git a/packages/cli/clients/cli/commands/template.doc.mjs b/packages/cli/clients/cli/commands/template.doc.mjs
index b843f80797..b47b7000fb 100644
--- a/packages/cli/clients/cli/commands/template.doc.mjs
+++ b/packages/cli/clients/cli/commands/template.doc.mjs
@@ -18,9 +18,11 @@ export const doc = {
description:
'One entry point for the template family: with no name it lists the discovered ' +
'templates; with a name it shows the source or a layout skeleton, or scaffolds it ' +
- 'into the project at a target path. Narrow an ambiguous name with --type and/or --package. ' +
- '--cdn writes the no-build-step CDN starter page, which ships as an asset rather than as ' +
- 'a discovered template.',
+ 'into the project at a target path. A configured integration replacement is the ' +
+ 'default for its Core id; use --package @astryxdesign/core for the original. ' +
+ 'Narrow other ambiguous names with --type and/or --package. --cdn writes the ' +
+ 'no-build-step CDN starter page, which ships as an asset rather than as a ' +
+ 'discovered template.',
fn: 'template',
args: [
{
@@ -55,7 +57,8 @@ export const doc = {
{
flag: '--package <pkg>',
param: 'options.package',
- description: 'Narrow to templates from a specific package',
+ description:
+ 'Narrow to templates from a specific package. Use @astryxdesign/core to select an original hidden by an integration replacement.',
},
{
flag: '--skeleton',
@@ -81,15 +84,29 @@ export const doc = {
],
examples: [
{label: 'List templates', cli: 'astryx template --json'},
+ {
+ label: 'List exact Core ids',
+ cli: 'astryx --json template --list --package @astryxdesign/core',
+ },
{
label: 'Scaffold into the app',
cli: 'astryx template dashboard ./src/app',
},
+ {
+ label: 'Select a replaced Core original',
+ cli: 'astryx template shell-side-nav ./src/app --package @astryxdesign/core',
+ },
{label: 'CDN starter page', cli: 'astryx template --cdn'},
- {label: 'CDN starter page, elsewhere', cli: 'astryx template --cdn public/demo.html'},
+ {
+ label: 'CDN starter page, elsewhere',
+ cli: 'astryx template --cdn public/demo.html',
+ },
],
exitCodes: [
- {code: 0, when: 'success, including a CDN page left untouched because it already exists'},
+ {
+ code: 0,
+ when: 'success, including a CDN page left untouched because it already exists',
+ },
{
code: 1,
when: 'unknown or ambiguous template, no source, a path escape, or an existing target without --overwrite',
diff --git a/packages/cli/clients/cli/commands/template.mjs b/packages/cli/clients/cli/commands/template.mjs
index fd363b573c..4056c36f49 100644
--- a/packages/cli/clients/cli/commands/template.mjs
+++ b/packages/cli/clients/cli/commands/template.mjs
@@ -4,12 +4,9 @@
* @file template command — thin CLI wrapper around api/template.mjs
*/
-import * as path from 'node:path';
-import * as fs from 'node:fs';
import {jsonOut} from '../../../foundation/response/json.mjs';
import {emit, section, text, records, code} from '../formatters/index.mjs';
import {cliError} from '../lib/cli-error.mjs';
-import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
import {template as templateApi} from '../../../api/template/template.mjs';
import {Project} from '../../../foundation/config/project.mjs';
import {warnOnIntegrationIssues} from '../../../foundation/integrations/integration-warnings.mjs';
@@ -21,18 +18,6 @@ import {doc as templateFn} from '../../../api/template/template.doc.mjs';
export {discoverTemplates, listTemplates} from '../../../api/template/template.mjs';
-/**
- * A template entry as produced by the discover* helpers in api/template.mjs.
- * The api layer returns these as `object[]`; this local shape captures the
- * fields the command consumes. Remove once api/template.mjs exports a precise
- * type for its discovered templates.
- * @typedef {object} DiscoveredTemplate
- * @property {'page' | 'block'} type
- * @property {string} dirName
- * @property {string} name
- * @property {string} filePath
- */
-
/**
* The discriminated response returned by the template API. The api layer
* currently declares `{type: string, data: unknown}`; narrow it here to the
@@ -89,36 +74,11 @@ export function registerTemplate(program) {
// doctor integration validate. Best-effort; suppressed in --json mode.
try {
const project = await Project.load(process.cwd());
- await warnOnIntegrationIssues(
- /** @type {Array<import('../../../foundation/integrations/integrations.mjs').LoadedIntegration>} */ (
- project.loadedIntegrations
- ),
- {json},
- );
+ await warnOnIntegrationIssues(project, {json});
} catch {
// Never let the nudge break the command.
}
- // Pre-flight overwrite check (only when we'd actually copy a file).
- // The API resolves the destination; we need to mirror its logic
- // narrowly enough to detect collisions before invoking it.
- if (
- name &&
- targetPath &&
- !options.list &&
- !options.skeleton &&
- !options.cdn
- ) {
- const collision = await detectTemplateCollision(name, targetPath);
- if (collision && !options.overwrite) {
- const rel = path.relative(process.cwd(), collision) || collision;
- const msg =
- `Refusing to overwrite existing file ${rel}. ` +
- `Re-run with --overwrite (or -f) to replace it.`;
- return cliError(msg, {code: ERROR_CODES.ERR_FILE_EXISTS});
- }
- }
-
/** @type {TemplateResponse} */
let result;
try {
@@ -156,12 +116,14 @@ export function registerTemplate(program) {
// isn't the built-in core package.
/** @param {import('../../../api/template/template.type.mjs').TemplateListEntry} t */
const toRow = t => ({
+ id: t.id,
name: t.isReady ? t.name : `${t.name} (WIP)`,
description: t.description,
package:
t.package && t.package !== '@astryxdesign/core' ? t.package : '',
+ replaces: t.replaces ?? '',
});
- const fields = ['name', 'description', 'package'];
+ const fields = ['id', 'name', 'description', 'package', 'replaces'];
emit(
pages.length > 0 && section('Page Templates'),
pages.length > 0 && records(pages.map(toRow), {fields}),
@@ -229,52 +191,3 @@ export function registerTemplate(program) {
},
});
}
-
-/**
- * Mirror the destination-resolution logic in api/template.mjs so we can
- * detect a clobber before invoking the API.
- *
- * Returns the absolute destination file path if it already exists, or
- * `null` otherwise (template missing, no collision, or list/skeleton mode).
- *
- * Path-safety enforcement happens inside the API; here we only need
- * enough precision to check existence — a false negative just means the
- * API will catch the issue and abort.
- *
- * @param {string} name
- * @param {string} targetPath
- * @returns {Promise<string | null>}
- */
-async function detectTemplateCollision(name, targetPath) {
- const {discoverTemplates} = await import('../../../api/template/template.mjs');
- /** @type {DiscoveredTemplate[]} */
- let templates;
- try {
- templates = /** @type {DiscoveredTemplate[]} */ (
- await discoverTemplates(process.cwd())
- );
- } catch {
- return null;
- }
- const match = templates.find(t => t.dirName === name);
- if (!match) return null;
-
- // Resolve target as the API will. We can't call assertWithin here
- // because the API does it itself; we just need to know "is there a
- // file at the destination?".
- const resolved = path.resolve(process.cwd(), targetPath);
-
- // File-arg branch: targetPath looks like `./foo.tsx`.
- const {isFilePathArg} = await import('../../../foundation/fs/path-safety.mjs');
- let dest;
- if (isFilePathArg(targetPath)) {
- dest = resolved;
- } else {
- const fileName = match.type === 'block'
- ? path.basename(match.filePath)
- : 'page.tsx';
- dest = path.join(resolved, fileName);
- }
-
- return fs.existsSync(dest) ? dest : null;
-}
diff --git a/packages/cli/clients/cli/commands/text-json-parity.test.mjs b/packages/cli/clients/cli/commands/text-json-parity.test.mjs
index 44c8399b00..6f51834491 100644
--- a/packages/cli/clients/cli/commands/text-json-parity.test.mjs
+++ b/packages/cli/clients/cli/commands/text-json-parity.test.mjs
@@ -310,7 +310,8 @@ const CASES = [
name: 'docs',
args: ['docs'],
jsonFieldAllowlist: [
- 'package — omitted to preserve the published 0.6 docs list text contract',
+ 'topic — inline layout lead column, not a key: value record',
+ 'description — inline layout trailing column',
],
},
{
diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjs
index 0e15a38305..ec42e28705 100644
--- a/packages/cli/clients/cli/index.mjs
+++ b/packages/cli/clients/cli/index.mjs
@@ -276,6 +276,12 @@ const commands = [
];
const SETUP_NUDGE_EXEMPT = new Set(['init', 'agent-docs']);
+/** An integration package's manifest: the package is not an app to set up. */
+const INTEGRATION_MANIFEST_FILES = [
+ 'astryx.integration.ts',
+ 'astryx.integration.mjs',
+ 'astryx.integration.js',
+];
/**
* Build a fresh, fully-wired Astryx CLI program (root options, hooks, all
@@ -519,6 +525,8 @@ export async function createProgram() {
if (SETUP_NUDGE_EXEMPT.has(actionCommand.name())) return;
const cwd = process.cwd();
if (!fs.existsSync(path.join(cwd, 'package.json'))) return; // not a project
+ // An integration package is not an app: `init` is not its next step.
+ if (INTEGRATION_MANIFEST_FILES.some(file => fs.existsSync(path.join(cwd, file)))) return;
if (isAstryxInitialized(cwd)) return; // already set up — stay quiet
// Same wording as the core/cli postinstall nudges. #4151's getCliInvocation()
// renders the correct form for THIS project — scoped `npx @astryxdesign/cli`
diff --git a/packages/cli/clients/cli/lib/manifest.mjs b/packages/cli/clients/cli/lib/manifest.mjs
index 080b2363b8..13dd81b78d 100644
--- a/packages/cli/clients/cli/lib/manifest.mjs
+++ b/packages/cli/clients/cli/lib/manifest.mjs
@@ -57,7 +57,13 @@ export const RESPONSE_TYPES = {
'component.detail.showcase',
'component.detail.blocks',
],
- docs: ['docs.list', 'docs.index', 'docs.detail', 'docs.detail.section'],
+ docs: [
+ 'docs.list',
+ 'docs.index',
+ 'docs.detail',
+ 'docs.detail.section',
+ 'docs.node',
+ ],
blog: ['blog.list', 'blog.detail'],
discover: [
'discover.list',
@@ -110,8 +116,9 @@ const EXAMPLES = {
docs: [
'astryx docs',
'astryx docs spacing --json',
- 'astryx docs theme --index',
+ 'astryx docs theme',
'astryx docs theme quick-start',
+ 'astryx docs cli/integrations --full',
],
discover: ['astryx discover --json'],
search: [
diff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjs
index 4b81e9a2da..d4c4031083 100644
--- a/packages/cli/foundation/agent-docs/agent-docs.mjs
+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs
@@ -486,6 +486,7 @@ export function generateCompressedIndex(
if (resolvedTopics.length > 0) {
lines.push(` docs <topic> ${resolvedTopics.join(', ')}`);
}
+ lines.push(' docs cli commands, API reference, integration authoring (one level at a time)');
lines.push(' swizzle <Name> eject component source for deep customization');
lines.push(' upgrade --apply run after any Astryx or integration dependency bump');
const appendCount = agentDocs.reduce(
diff --git a/packages/cli/foundation/agent-docs/agent-docs.test.mjs b/packages/cli/foundation/agent-docs/agent-docs.test.mjs
index ed332e350d..84623d68b0 100644
--- a/packages/cli/foundation/agent-docs/agent-docs.test.mjs
+++ b/packages/cli/foundation/agent-docs/agent-docs.test.mjs
@@ -134,7 +134,6 @@ describe('generateCompressedIndex', () => {
const line = topicLine(generateCompressedIndex('1.0.0'));
for (const topic of [
'getting-started',
- 'cli-integrations',
'browser-support',
'styling-libraries',
'working-with-ai',
@@ -143,6 +142,16 @@ describe('generateCompressedIndex', () => {
}
});
+ it('points to the CLI docs tree on a line of its own', () => {
+ // The integration guide lives in the docs tree now (cli/integrations), so
+ // the topic line no longer names it; the tree's entry point does.
+ const block = generateCompressedIndex('1.0.0');
+ expect(block).toContain(
+ ' docs cli commands, API reference, integration authoring (one level at a time)',
+ );
+ expect(topicLine(block)).not.toContain('cli-integrations');
+ });
+
it('lists the topics it is given, so an integration’s reach the agent', () => {
const line = topicLine(
generateCompressedIndex('1.0.0', {topics: ['tokens', 'deploying']}),
diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjs
index 8da8794695..5669ff2fd0 100644
--- a/packages/cli/foundation/config/project.mjs
+++ b/packages/cli/foundation/config/project.mjs
@@ -21,10 +21,10 @@
* - Discovery methods (components/templates/codemods/docs/themes) are MEMOIZED per
* instance (via the pluggable cache) and orchestrate the EXISTING discovery
* functions — Project never reimplements discovery.
- * - SKIP + WARN policy: as a discovery method runs, per-integration work is
- * guarded so one broken integration never throws out of discovery. Any
- * AstryxIntegrationIssue encountered is collected into a private set and
- * that integration's contributions are skipped.
+ * - SKIP + WARN policy: discovery records each integration issue. Other valid
+ * contribution kinds remain available; invalid template and component files
+ * do not hide valid siblings. A manifest load failure still withdraws the
+ * package because its roots cannot be trusted.
* - `issues()` returns the deduped accumulated set, and (when called
* directly) fills in validation for any configured integration not yet
* visited by a discovery call, so it is always complete on demand.
@@ -52,11 +52,13 @@ import {
import {
CORE_PACKAGE,
discoverOwnedComponents,
- discoverIntegrationComponents,
+ discoverValidIntegrationComponents,
} from '../discovery/component-discovery.mjs';
import {findCoreDir} from '../fs/paths.mjs';
import {
- discoverAll as discoverTemplates,
+ applyTemplateReplacements,
+ effectiveTemplateDiscovery,
+ discoverAllUnresolved as discoverTemplates,
discoverIntegrationTemplatesForOne,
} from '../discovery/template-adapter.mjs';
import {
@@ -72,10 +74,7 @@ import {
discoverIntegrationCodemods,
selectIntegrationCodemods,
} from '../../assets/codemods/integration-discovery.mjs';
-import {
- INVALID_AGENT_DOCS,
- validateLoadedIntegration,
-} from '../integrations/validate-contributions.mjs';
+import {validateLoadedIntegration} from '../integrations/validate-contributions.mjs';
import {
InMemoryConfigCache,
cacheKey,
@@ -346,6 +345,8 @@ export class Project {
* @type {Set<object>}
*/
#visitedIssues = new Set();
+ /** @type {Promise<Array<object>> | null} */
+ #templatesPromise = null;
/**
* @param {object} init
@@ -597,22 +598,6 @@ export class Project {
return integration?.name ?? integration?.__spec ?? '(integration)';
}
- /**
- * Whether this package has an error that invalidates its regular manifest
- * contributions. Invalid `agentDocs` blocks agent-doc writes only; it must not
- * withdraw components, templates, docs, or codemods.
- * @param {string} pkg
- * @returns {boolean}
- */
- #hasBlockingContributionIssue(pkg) {
- return this.#issues.some(
- issue =>
- issue.package === pkg &&
- issue.severity === 'error' &&
- issue.code !== INVALID_AGENT_DOCS,
- );
- }
-
/**
* Validate one loaded integration and collect any issues. Marks the
* integration visited so issues() won't redo the work. Best-effort: a
@@ -649,9 +634,9 @@ export class Project {
/**
* Core + integration component ownership records. Wraps
* discoverOwnedComponents for core and discoverIntegrationComponents (via
- * discoverOwnedComponents) for integrations, but applies the skip+warn
- * policy per integration: a broken integration's components are skipped and
- * its issues collected, never thrown. Memoized per instance.
+ * discoverOwnedComponents) for integrations. Invalid component records are
+ * omitted and reported; valid component siblings and other contribution kinds
+ * remain available. Memoized per instance.
*
* @returns {Promise<Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>>}
*/
@@ -671,18 +656,17 @@ export class Project {
}
}
- // Each integration in isolation so one broken integration is skipped.
+ // Each integration is discovered independently. Invalid records are
+ // omitted below without hiding valid siblings or other contribution kinds.
for (const integration of this.#loadedIntegrations) {
await this.#collectIssues(integration);
const pkg = this.#pkgLabel(integration);
- if (this.#hasBlockingContributionIssue(pkg)) continue;
try {
- // discoverOwnedComponents owns the core+integration record shape;
- // here we add only this integration's records (core is handled
- // above) so a single broken integration can be skipped in isolation.
- for (const rec of discoverIntegrationComponents(integration)) {
- records.push(rec);
- }
+ // #collectIssues (above) already reported each withdrawn record,
+ // with its fix, through the same discovery.
+ const {components} =
+ await discoverValidIntegrationComponents(integration);
+ records.push(...components);
} catch (err) {
this.#pushIssue(pkg, {
code: 'invalid_component',
@@ -697,17 +681,21 @@ export class Project {
}
/**
- * Core + integration templates, type-tagged. Wraps discoverTemplates (core +
- * external blocks) and discoverIntegrationTemplatesForOne per integration so
- * a broken integration's templates are skipped and its issues collected.
- * Memoized per instance.
+ * Core + integration templates, type-tagged, with valid integration
+ * replacements projected over their Core targets. Wraps raw template discovery
+ * (Core + external blocks) and discoverIntegrationTemplatesForOne per integration
+ * so unusable template files are reported and omitted while valid siblings
+ * remain available. Memoized per instance.
*
* @returns {Promise<Array<object>>}
*/
async templates() {
- return this.#memo('templates', async () => {
+ if (this.#templatesPromise) return this.#templatesPromise;
+ this.#templatesPromise = (async () => {
/** @type {any[]} */
const templates = [];
+ /** @type {import('../discovery/template-adapter.mjs').TemplateDiscoveryError[]} */
+ const replacementErrors = [];
// Core + external-package templates (discoverTemplates internally also
// loads integration templates via loadConfig today; we intentionally
@@ -728,20 +716,24 @@ export class Project {
for (const integration of this.#loadedIntegrations) {
await this.#collectIssues(integration);
const pkg = this.#pkgLabel(integration);
- if (this.#hasBlockingContributionIssue(pkg)) continue;
+ // Template discovery already isolates invalid template files and returns
+ // every valid sibling. Do not withdraw templates because another
+ // contribution kind in this package is broken.
try {
const {templates: ts, errors} =
await discoverIntegrationTemplatesForOne(integration);
for (const e of errors) {
this.#pushIssue(pkg, {
- code: 'invalid_template',
- severity: 'error',
+ code: e.code ?? 'invalid_template',
+ severity: e.severity ?? 'error',
message: e.message,
});
+ if (e.replacementTarget != null) replacementErrors.push(e);
}
- // Only contribute templates when the integration had no per-template
- // errors (skip the whole integration's templates on any error).
- if (errors.length === 0) templates.push(...ts);
+ // Discovery already omits each unusable template from `ts`. Keep all
+ // valid siblings, while the collected errors remain visible through
+ // issues() and replacement errors disable only their own targets.
+ templates.push(...ts);
} catch (err) {
this.#pushIssue(pkg, {
code: 'invalid_template',
@@ -751,15 +743,24 @@ export class Project {
}
}
- return templates.sort((a, b) => a.name.localeCompare(b.name));
- });
+ const resolved = applyTemplateReplacements(templates, replacementErrors);
+ for (const error of resolved.errors) {
+ this.#pushIssue(error.package, {
+ code: error.code,
+ severity: error.severity,
+ message: error.message,
+ });
+ }
+ return effectiveTemplateDiscovery(resolved.templates);
+ })();
+ return this.#templatesPromise;
}
/**
* Bundled source themes plus themes contributed by installed integrations.
* Each record keeps its package owner and source directory so callers can
- * both list and copy it without reconstructing paths. A broken integration's
- * themes are skipped under the same issue policy as every other kind.
+ * both list and copy it without reconstructing paths. A broken theme
+ * contribution is reported without hiding the package's other valid kinds.
*
* @returns {Promise<import('../discovery/theme-discovery.mjs').DiscoveredTheme[]>}
*/
@@ -770,7 +771,6 @@ export class Project {
for (const integration of this.#loadedIntegrations) {
await this.#collectIssues(integration);
const pkg = this.#pkgLabel(integration);
- if (this.#hasBlockingContributionIssue(pkg)) continue;
if (!integration?.themes) continue;
try {
themes.push(...(await discoverIntegrationThemes(integration)));
@@ -804,14 +804,16 @@ export class Project {
async docs() {
return this.#memo('docs', async () => {
const catalog = DocsCatalog.fromBuiltins();
+ let rank = 0;
for (const integration of this.#loadedIntegrations) {
+ rank += 1;
await this.#collectIssues(integration);
const pkg = this.#pkgLabel(integration);
- if (this.#hasBlockingContributionIssue(pkg)) continue;
if (!integration?.docs) continue;
try {
- const {records, errors} = await discoverIntegrationDocs(integration);
+ const {records, errors, namespaces, guides} =
+ await discoverIntegrationDocs(integration);
for (const e of errors) {
this.#pushIssue(pkg, {
code: 'invalid_doc',
@@ -823,11 +825,20 @@ export class Project {
// how a bad template withdraws its package's templates: a partial
// docs contribution is the state where a `replaces` silently does
// nothing and a reader gets the topic it was meant to replace.
- if (errors.length > 0) continue;
+ if (errors.length > 0) {
+ for (const e of errors) {
+ catalog.addIssue({package: integration.name ?? pkg, message: e.message});
+ }
+ continue;
+ }
for (const record of records) {
const issue = catalog.add(record);
if (issue) this.#pushIssue(pkg, issue);
}
+ catalog.addTreeInputs({
+ namespaces: namespaces.map(input => ({...input, rank})),
+ guides: guides.map(input => ({...input, rank})),
+ });
} catch (err) {
this.#pushIssue(pkg, {
code: 'invalid_doc',
@@ -844,8 +855,8 @@ export class Project {
/**
* Core registry transforms + integration codemods for an upgrade range.
* Wraps getTransformsBetween (core) and discoverIntegrationCodemods /
- * selectIntegrationCodemods (integrations). A broken integration's codemods
- * are skipped (issue collected) rather than failing the whole resolution.
+ * selectIntegrationCodemods (integrations). An invalid codemod contribution
+ * is reported and omitted without hiding other valid contribution kinds.
* Memoized per (from, to) key.
*
* @param {string} fromVersion exclusive lower bound
@@ -863,7 +874,6 @@ export class Project {
for (const integration of this.#loadedIntegrations) {
await this.#collectIssues(integration);
const pkg = this.#pkgLabel(integration);
- if (this.#hasBlockingContributionIssue(pkg)) continue;
if (!integration?.codemods) continue;
try {
// Validate this integration's codemods discover cleanly in
@@ -918,6 +928,10 @@ export class Project {
* @returns {Promise<ProjectIntegrationIssue[]>}
*/
async issues() {
+ // Template replacement validity depends on the combined Core + integration
+ // catalog. Resolve it first so issue results never depend on which discovery
+ // method the caller happened to invoke earlier.
+ await this.templates();
for (const integration of this.#loadedIntegrations) {
await this.#collectIssues(integration);
}
diff --git a/packages/cli/foundation/config/project.test.mjs b/packages/cli/foundation/config/project.test.mjs
index fabe68d597..bda0cb8608 100644
--- a/packages/cli/foundation/config/project.test.mjs
+++ b/packages/cli/foundation/config/project.test.mjs
@@ -6,6 +6,7 @@ import * as path from 'node:path';
import {Project, DEFAULT_ISSUES_URL, findConfigPath} from './project.mjs';
import {InMemoryConfigCache} from './config-cache.mjs';
import * as componentDiscovery from '../discovery/component-discovery.mjs';
+import {discoverCoreTemplates} from '../discovery/template-adapter.mjs';
let tmpDir;
let originalCwd;
@@ -21,6 +22,9 @@ function scaffold({
issuesUrl,
withComponents = true,
withTemplates = true,
+ templateId = 'hero',
+ templateType = 'block',
+ templateReplaces = null,
withCodemods = true,
brokenComponent = false,
brokenCodemod = false,
@@ -65,7 +69,7 @@ function scaffold({
fs.mkdirSync(compDir, {recursive: true});
fs.writeFileSync(
path.join(compDir, 'Widget.doc.mjs'),
- `export const docs = { name: 'Widget', usage: {description: 'A widget'} };\n`,
+ `export const docs = { name: 'Widget', usage: {description: 'A widget'}, props: [] };\n`,
);
if (!brokenComponent) {
fs.writeFileSync(
@@ -80,12 +84,12 @@ function scaffold({
const tDir = path.join(pkgDir, 'templates');
fs.mkdirSync(tDir, {recursive: true});
fs.writeFileSync(
- path.join(tDir, 'hero.doc.mjs'),
- `export default { type: 'block', name: 'Hero', description: 'A hero' };\n`,
+ path.join(tDir, `${templateId}.doc.mjs`),
+ `export default { type: '${templateType}', name: 'Fixture template', description: 'A fixture template'${templateReplaces == null ? '' : `, replaces: ${JSON.stringify(templateReplaces)}`} };\n`,
);
fs.writeFileSync(
- path.join(tDir, 'hero.tsx'),
- `export default function Hero() { return null; }\n`,
+ path.join(tDir, `${templateId}.tsx`),
+ `export default function FixtureTemplate() { return null; }\n`,
);
}
@@ -324,6 +328,91 @@ describe('Project discovery', () => {
expect(hero.type).toBe('block');
});
+ it('templates() projects a valid integration replacement instead of its Core target', async () => {
+ const corePage = (await discoverCoreTemplates()).find(
+ template => template.type === 'page',
+ );
+ expect(corePage).toBeDefined();
+ scaffold({
+ templateId: 'acme-app-shell',
+ templateType: 'page',
+ templateReplaces: corePage.dirName,
+ });
+ const project = await Project.load(tmpDir);
+
+ const templates = await project.templates();
+
+ expect(
+ templates.find(template => template.dirName === 'acme-app-shell'),
+ ).toMatchObject({
+ package: '@acme/widgets',
+ replaces: corePage.dirName,
+ });
+ expect(
+ templates.find(
+ template =>
+ template.dirName === corePage.dirName &&
+ template.package !== '@acme/widgets',
+ ),
+ ).toBeUndefined();
+ expect(await project.issues()).toEqual([]);
+ });
+
+ it('reports replacement issues regardless of discovery call order without hiding other contributions', async () => {
+ scaffold({
+ templateReplaces: 'missing-core-template',
+ });
+
+ const componentsFirst = await Project.load(tmpDir);
+ expect(
+ (await componentsFirst.components()).some(
+ component => component.package === '@acme/widgets',
+ ),
+ ).toBe(true);
+ expect(await componentsFirst.issues()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'missing_template_replacement_target',
+ package: '@acme/widgets',
+ }),
+ ]),
+ );
+
+ const issuesFirst = await Project.load(tmpDir, {fresh: true});
+ expect(await issuesFirst.issues()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'missing_template_replacement_target',
+ package: '@acme/widgets',
+ }),
+ ]),
+ );
+ expect(
+ (await issuesFirst.components()).some(
+ component => component.package === '@acme/widgets',
+ ),
+ ).toBe(true);
+ const ownTemplate = (await issuesFirst.templates()).find(
+ template =>
+ template.package === '@acme/widgets' && template.dirName === 'hero',
+ );
+ expect(ownTemplate).toBeDefined();
+ expect(ownTemplate).not.toHaveProperty('replaces');
+
+ const sharedCache = new InMemoryConfigCache();
+ const warm = await Project.load(tmpDir, {cache: sharedCache});
+ await warm.templates();
+ const cached = await Project.load(tmpDir, {cache: sharedCache});
+ expect(await cached.issues()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: 'missing_template_replacement_target',
+ package: '@acme/widgets',
+ }),
+ ]),
+ );
+ });
+
it('codemods() returns core registry groups + integration groups', async () => {
scaffold();
const project = await Project.load(tmpDir);
@@ -468,6 +557,53 @@ describe('Project issues (skip + warn)', () => {
expect(issues.some(i => i.package === '@acme/widgets')).toBe(true);
});
+ it('keeps valid contribution kinds and siblings when others are broken', async () => {
+ const pkgDir = scaffold({brokenComponent: true});
+ fs.writeFileSync(
+ path.join(pkgDir, 'templates', 'broken.template.mjs'),
+ `export default {type: 'block', name: 'Broken', description: 'Missing source'};\n`,
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'components', 'ValidWidget.doc.mjs'),
+ `export default {type: 'component', name: 'ValidWidget', props: []};\n`,
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'components', 'ValidWidget.tsx'),
+ `export function ValidWidget() { return null; }\n`,
+ );
+ const project = await Project.load(tmpDir);
+
+ const templates = await project.templates();
+ const components = await project.components();
+ const issues = await project.issues();
+
+ expect(
+ templates.find(
+ template =>
+ template.dirName === 'hero' && template.package === '@acme/widgets',
+ ),
+ ).toBeDefined();
+ expect(
+ components.find(
+ component =>
+ component.name === 'ValidWidget' &&
+ component.package === '@acme/widgets',
+ ),
+ ).toBeDefined();
+ expect(
+ components.find(
+ component =>
+ component.name === 'Widget' && component.package === '@acme/widgets',
+ ),
+ ).toBeUndefined();
+ expect(issues).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({code: 'invalid_component'}),
+ expect.objectContaining({code: 'invalid_template'}),
+ ]),
+ );
+ });
+
it('does not throw when an integration codemod is broken', async () => {
scaffold({brokenCodemod: true});
const project = await Project.load(tmpDir);
diff --git a/packages/cli/foundation/discovery/authoring-self-docs.test.mjs b/packages/cli/foundation/discovery/authoring-self-docs.test.mjs
index eb31990339..5c007311b9 100644
--- a/packages/cli/foundation/discovery/authoring-self-docs.test.mjs
+++ b/packages/cli/foundation/discovery/authoring-self-docs.test.mjs
@@ -60,17 +60,25 @@ describe('authoring self-docs', () => {
);
});
-describe('what the authoring docs say about the unbuilt docs graph', () => {
- it('marks exactly the fields topic loading rejects as not read yet', () => {
+describe('what the authoring docs say about the docs tree', () => {
+ it('marks exactly the fields the docs tree does not read yet', () => {
const notReadYet = graphFieldsDoc.fields
.filter(field => /Not read yet/.test(field.description))
.map(field => field.name);
- expect(notReadYet.sort()).toEqual([...GRAPH_ONLY_FIELDS].sort());
+ // The tree reads `placement` for every guide (spec:AST-046); the other
+ // graph fields are still refused by every topic reader.
+ expect(notReadYet.sort()).toEqual(
+ GRAPH_ONLY_FIELDS.filter(field => field !== 'placement').sort(),
+ );
for (const field of graphFieldsDoc.fields) {
- if (notReadYet.includes(field.name)) {
+ if (GRAPH_ONLY_FIELDS.includes(field.name)) {
expect(field.description).toMatch(/fails to load/);
}
}
+ const placement = graphFieldsDoc.fields.find(f => f.name === 'placement');
+ expect(placement.description).toMatch(
+ /Read for every guide, the CLI's and each integration's/,
+ );
expect(graphFieldsDoc.description).toMatch(/not built yet/);
});
@@ -85,8 +93,10 @@ describe('what the authoring docs say about the unbuilt docs graph', () => {
}
});
- it('says namespace docs are not loaded yet', () => {
- expect(namespaceDoc.description).toMatch(/Not loaded yet/);
+ it('says where namespace docs live: the CLI tree, and each integration', () => {
+ expect(namespaceDoc.description).toMatch(
+ /an integration ships its own in its docs directory/,
+ );
expect(
problemsInTopic({
...namespaceDoc.examples?.[0],
@@ -94,7 +104,7 @@ describe('what the authoring docs say about the unbuilt docs graph', () => {
name: 'x',
}),
).toEqual([
- '"x" is a namespace doc. Only the docs graph reads namespace docs, and it is not built yet; remove this file from the docs directory.',
+ '"x" is a namespace doc, which the docs tree reads, not the topic list. The CLI keeps its own in assets/docs/tree; an integration ships its namespace docs in its docs directory.',
]);
});
});
diff --git a/packages/cli/foundation/discovery/cli-self-docs.mjs b/packages/cli/foundation/discovery/cli-self-docs.mjs
index ab4b3a6d9a..803b71a220 100644
--- a/packages/cli/foundation/discovery/cli-self-docs.mjs
+++ b/packages/cli/foundation/discovery/cli-self-docs.mjs
@@ -1,17 +1,18 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file The CLI's own docs, read by their `namespace`: every command, API
- * function, schema, and enum doc the CLI ships says which `astryx docs` topic
- * reads it, and the `cli` topic is built from the ones that name it.
+ * @file The CLI's own typed docs, read by their `namespace`: every command,
+ * API function, schema, and enum doc the CLI ships names the group that reads
+ * it. The docs tree adopts `cli/commands` and `cli/api` (spec:AST-046); the
+ * authoring topic reads `authoring` from its own list.
*
* @input The command, function, schema, and enum docs under
* clients/cli/commands, api, authoring, and foundation.
- * @output {@link buildCliTopic} for `astryx docs cli`, and
+ * @output {@link loadCliSelfDocs} for the docs tree, {@link cliDocSection} for
+ * what `astryx docs <route>` prints for one of them, and
* {@link auditCliSelfDocs}, which `astryx doctor` runs.
- * @position foundation/discovery — the reader for docs whose namespace starts
- * with `cli/`. The authoring topic reads the `authoring` namespace from its
- * own list (authoring-self-docs.mjs).
+ * @position foundation/discovery. The tree (doc-compiler/tree.mjs) gives each
+ * doc its route; this module only loads the docs and renders one.
*/
import * as fs from 'node:fs';
@@ -23,7 +24,7 @@ import {
DOC_OUTPUT_BUDGET_BYTES,
oversizedDocSections,
} from './docs-output-budget.mjs';
-import {sectionKeyProblems} from './docs-section-key.mjs';
+import {routeSegment} from './docs-section-key.mjs';
/** The directories, relative to the CLI root, that hold the CLI's own docs. */
export const CLI_SELF_DOC_DIRS = [
@@ -37,23 +38,20 @@ export const CLI_SELF_DOC_DIRS = [
const NAMESPACED_KINDS = new Set(['command', 'function', 'schema', 'enum']);
/**
- * Every namespace a CLI doc may declare, and the topic that reads it. A doc in
- * a `cli/` namespace is the section `<key prefix>-<name>` of `astryx docs cli`;
- * a doc in `authoring` is a section of `astryx docs authoring`.
- * @type {Record<string, {topic: string, keyPrefix?: string}>}
+ * Every namespace a CLI doc may declare, and what reads it. The docs tree
+ * adopts `cli/commands` (under `cli/commands`) and `cli/api` (under
+ * `cli/api/<kind>s`); `astryx docs authoring` reads `authoring` from its list.
+ * @type {Record<string, {reader: 'tree' | 'authoring'}>}
*/
export const CLI_DOC_NAMESPACES = {
- 'cli/commands': {topic: 'cli', keyPrefix: 'commands'},
- 'cli/api': {topic: 'cli', keyPrefix: 'api'},
- authoring: {topic: 'authoring'},
+ 'cli/commands': {reader: 'tree'},
+ 'cli/api': {reader: 'tree'},
+ authoring: {reader: 'authoring'},
};
/** Blocks a doc's notes may carry that a topic section can render. */
const TOPIC_BLOCKS = new Set(['prose', 'list', 'code', 'heading', 'table']);
-/** Section order within the `cli` topic: commands, then the API by kind. */
-const KIND_ORDER = ['command', 'function', 'schema', 'enum'];
-
/**
* Every `*.doc.mjs` under the CLI's doc directories, relative to `root` and
* sorted. Fixture, test, and dependency directories are skipped.
@@ -121,29 +119,27 @@ export async function loadCliSelfDocs(
}
/**
- * A name as a section-key segment: lowercase words joined by hyphens.
- * `integrationPackCheck` and `integration pack` both read naturally.
- * @param {string} name
- * @returns {string}
+ * What cross-links need: the loaded function docs by name, the command names,
+ * and the route the docs tree gave a doc, if it gave one.
+ * @typedef {object} CliDocIndex
+ * @property {Map<string, any>} functions
+ * @property {Set<string>} commands
+ * @property {(kind: string, name: string) => string | null} route
*/
-export function keySegment(name) {
- return name
- .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, '-')
- .replace(/^-+|-+$/g, '');
-}
/**
- * The section key a doc is read by in `astryx docs cli`, or null when its
- * namespace is not one of the topic's.
- * @param {any} doc
- * @returns {string | null}
+ * @param {any[]} docs every loaded CLI typed doc
+ * @param {(kind: string, name: string) => string | null} [route]
+ * @returns {CliDocIndex}
*/
-export function cliSectionKey(doc) {
- const prefix = CLI_DOC_NAMESPACES[doc?.namespace]?.keyPrefix;
- if (prefix == null) return null;
- return `${prefix}-${keySegment(String(doc.name))}`;
+export function cliDocIndex(docs, route = () => null) {
+ return {
+ functions: new Map(
+ docs.filter(d => d.type === 'function').map(d => [d.name, d]),
+ ),
+ commands: new Set(docs.filter(d => d.type === 'command').map(d => d.name)),
+ route,
+ };
}
/** @param {unknown} value */
@@ -197,9 +193,9 @@ function noteBlocks(notes) {
}
/**
- * One command doc as a section of `astryx docs cli`.
+ * What `astryx docs <route>` prints for one command doc.
* @param {any} cmd
- * @param {{functions: Map<string, any>, commands: Set<string>}} index
+ * @param {CliDocIndex} index
*/
function commandSection(cmd, index) {
const fn = cmd.fn == null ? undefined : index.functions.get(cmd.fn);
@@ -255,6 +251,8 @@ function commandSection(cmd, index) {
rows: exitCodes.map((/** @type {any} */ e) => [String(e.code), e.when]),
});
}
+ // Links name docs by identity; the route in each command is derived when
+ // the doc is read (spec:AST-047 FR9).
const subcommands = (cmd.subcommands ?? []).filter(
(/** @type {string} */ sub) => index.commands.has(`${cmd.name} ${sub}`),
);
@@ -264,28 +262,44 @@ function commandSection(cmd, index) {
style: 'unordered',
items: subcommands.map(
(/** @type {string} */ sub) =>
- `\`astryx ${cmd.name} ${sub}\`: \`astryx docs cli commands-${keySegment(`${cmd.name} ${sub}`)}\``,
+ `\`astryx ${cmd.name} ${sub}\`: {@link command:${cmd.name} ${sub}}`,
),
});
}
if (fn != null) {
content.push({
type: 'prose',
- text: `It runs \`${fn.name}()\` from \`${fn.importPath}\`. Read it with \`astryx docs cli ${cliSectionKey(fn)}\`.`,
+ text: `It runs \`${fn.name}()\` from \`${fn.importPath}\`. Read it with {@link function:${fn.name}}.`,
});
}
content.push(...noteBlocks(cmd.notes));
return {
- id: cliSectionKey(cmd),
+ id: routeSegment(cmd.name),
title: cmd.displayName ?? `astryx ${cmd.name}`,
content,
};
}
/**
- * One API function doc as a section of `astryx docs cli`.
+ * The command doc a command line belongs to: its longest leading words that
+ * name one (`integration add theme` is the `integration add` command).
+ * @param {string} line
+ * @param {Set<string>} commands
+ * @returns {string | null}
+ */
+function commandDocName(line, commands) {
+ const words = line.trim().split(/\s+/);
+ for (let n = words.length; n > 0; n--) {
+ const name = words.slice(0, n).join(' ');
+ if (commands.has(name)) return name;
+ }
+ return null;
+}
+
+/**
+ * What `astryx docs <route>` prints for one API function doc.
* @param {any} fn
- * @param {{functions: Map<string, any>, commands: Set<string>}} index
+ * @param {CliDocIndex} index
*/
function functionSection(fn, index) {
/** @type {any[]} */
@@ -341,26 +355,28 @@ function functionSection(fn, index) {
code: example.code,
});
}
- if (fn.command != null && index.commands.has(fn.command)) {
+ const commandDoc =
+ fn.command == null ? null : commandDocName(fn.command, index.commands);
+ if (commandDoc != null) {
content.push({
type: 'prose',
- text: `\`astryx ${fn.command}\` runs it. Read it with \`astryx docs cli commands-${keySegment(fn.command)}\`.`,
+ text: `\`astryx ${fn.command}\` runs it. Read it with {@link command:${commandDoc}}.`,
});
}
return {
- id: cliSectionKey(fn),
+ id: routeSegment(fn.name),
title: fn.displayName ?? `${fn.name}()`,
content,
};
}
/**
- * One enum doc as a section of `astryx docs cli`.
+ * What `astryx docs <route>` prints for one enum doc.
* @param {any} doc
*/
function enumSection(doc) {
return {
- id: cliSectionKey(doc),
+ id: routeSegment(doc.name),
title: doc.displayName ?? doc.name,
content: [
{type: 'prose', text: doc.description},
@@ -379,79 +395,33 @@ function enumSection(doc) {
}
/**
- * The docs a `cli/` namespace names, in reading order: commands by name (a
- * group before its subcommands), then API functions, schemas, and enums.
- * @param {any[]} docs
- * @returns {any[]}
- */
-function cliDocsInOrder(docs) {
- return docs
- .filter(doc => CLI_DOC_NAMESPACES[doc.namespace]?.topic === 'cli')
- .sort(
- (a, b) =>
- KIND_ORDER.indexOf(a.type) - KIND_ORDER.indexOf(b.type) ||
- (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
- );
-}
-
-/**
- * The `cli` topic: one section per doc whose namespace is `cli/…`.
- * @param {any[]} docs every loaded CLI doc; the ones in other namespaces are
- * left out
- * @returns {import('../../authoring/doctypes/reference/type').ReferenceDoc}
- */
-export function buildCliReferenceDoc(docs) {
- const ordered = cliDocsInOrder(docs);
- const index = {
- functions: new Map(
- ordered.filter(d => d.type === 'function').map(d => [d.name, d]),
- ),
- commands: new Set(
- ordered.filter(d => d.type === 'command').map(d => d.name),
- ),
- };
- return /** @type {any} */ ({
- name: 'cli',
- title: 'CLI Reference',
- category: 'guide',
- description:
- 'Every command and API function of the CLI, with the JSON output envelope, error codes, and response types, read from the docs the CLI ships.',
- sections: ordered.map(doc =>
- doc.type === 'command'
- ? commandSection(doc, index)
- : doc.type === 'function'
- ? functionSection(doc, index)
- : doc.type === 'enum'
- ? enumSection(doc)
- : {...selfDocSection(doc), id: cliSectionKey(doc)},
- ),
- });
-}
-
-/**
- * The `cli` topic from every CLI doc that loads. One that fails is left out
- * here and reported by {@link auditCliSelfDocs}.
- * @returns {Promise<import('../../authoring/doctypes/reference/type').ReferenceDoc>}
+ * What `astryx docs <route>` prints for one CLI typed doc: its title and the
+ * blocks of its content, with cross-links to the routes the tree gave.
+ * @param {any} doc
+ * @param {CliDocIndex} index
+ * @returns {{id: string, title: string, content: any[]}}
*/
-export async function buildCliTopic() {
- const {loaded} = await loadCliSelfDocs();
- return buildCliReferenceDoc(loaded.map(entry => entry.doc));
+export function cliDocSection(doc, index) {
+ if (doc.type === 'command') return commandSection(doc, index);
+ if (doc.type === 'function') return functionSection(doc, index);
+ if (doc.type === 'enum') return enumSection(doc);
+ return {...selfDocSection(doc), id: routeSegment(doc.name)};
}
/**
- * What stands between a CLI doc and a reader: a missing namespace, one no
- * topic reads, one that disagrees with the authoring topic's list, a doc that
- * fails to load, and a `cli` section that clashes or is too large.
+ * What stands between a CLI doc and a reader: a missing namespace, one nothing
+ * reads, one that disagrees with the authoring topic's list, a doc that fails
+ * to load, and a tree leaf too large for one read. Whether the tree gives
+ * every `cli/...` doc a route is the docs-tree check's job.
* @param {{root?: string, sources?: string[], budget?: number, authoringSources?: string[]}} [options]
* @returns {Promise<{
* docs: number,
- * sections: number,
+ * tree: number,
* authoring: number,
* missing: string[],
* unknown: {source: string, namespace: string}[],
* misfiled: {source: string, message: string}[],
* failed: {source: string, error: string}[],
- * keyProblems: string[],
* oversized: {key: string, title: string, bytes: number}[],
* }>}
*/
@@ -472,6 +442,8 @@ export async function auditCliSelfDocs({
const unknown = [];
/** @type {{source: string, message: string}[]} */
const misfiled = [];
+ /** @type {any[]} */
+ const treeDocs = [];
let authoring = 0;
for (const {source, doc} of loaded) {
const namespace = doc.namespace;
@@ -484,7 +456,7 @@ export async function auditCliSelfDocs({
continue;
}
const inAuthoring = listed.has(source);
- if (namespace === 'authoring') {
+ if (CLI_DOC_NAMESPACES[namespace].reader === 'authoring') {
if (inAuthoring) authoring++;
else {
misfiled.push({
@@ -497,18 +469,22 @@ export async function auditCliSelfDocs({
source,
message: `${source} is read in \`astryx docs authoring\`, but its namespace is "${namespace}"`,
});
+ } else {
+ treeDocs.push(doc);
}
}
- const topic = buildCliReferenceDoc(loaded.map(entry => entry.doc));
+ const index = cliDocIndex(loaded.map(entry => entry.doc));
return {
docs: loaded.length,
- sections: topic.sections.length,
+ tree: treeDocs.length,
authoring,
missing,
unknown,
misfiled,
failed,
- keyProblems: sectionKeyProblems(topic.sections),
- oversized: oversizedDocSections(topic.sections, budget),
+ oversized: oversizedDocSections(
+ treeDocs.map(doc => cliDocSection(doc, index)),
+ budget,
+ ),
};
}
diff --git a/packages/cli/foundation/discovery/cli-self-docs.test.mjs b/packages/cli/foundation/discovery/cli-self-docs.test.mjs
index 90994dcd15..b65c0138d4 100644
--- a/packages/cli/foundation/discovery/cli-self-docs.test.mjs
+++ b/packages/cli/foundation/discovery/cli-self-docs.test.mjs
@@ -1,15 +1,16 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Tests for the CLI docs reader. Every command, API function, schema, and
- * enum doc this package ships is readable in the topic its namespace names.
- * Each way one can fail to be is reported: no namespace, a namespace no topic
- * reads, a clash with the authoring topic's list, a doc that does not load, and
- * two `cli` sections with one key.
+ * @file Tests for the CLI's own typed docs. Every command, API function,
+ * schema, and enum doc this package ships declares the group that reads it,
+ * and each way one can fail to be read is reported: no namespace, a namespace
+ * nothing reads, a clash with the authoring topic's list, a doc that does not
+ * load, and a leaf too large for one read. What `astryx docs <route>` prints
+ * for one doc is pinned here; where the tree puts it is tree.test.mjs's job.
*
* @input This package's own docs, and fixture doc trees written under the
* working directory.
- * @output Assertions on the audit, the `cli` topic, and reads through `docs()`.
+ * @output Assertions on the audit and on each doc's rendered content.
* @position packages/cli/foundation/discovery — tests for cli-self-docs.mjs.
*/
@@ -19,14 +20,11 @@ import {afterAll, describe, expect, it} from 'vitest';
import {
CLI_DOC_NAMESPACES,
auditCliSelfDocs,
- buildCliReferenceDoc,
- buildCliTopic,
- cliSectionKey,
+ cliDocIndex,
+ cliDocSection,
discoverCliSelfDocSources,
- keySegment,
- loadCliSelfDocs,
} from './cli-self-docs.mjs';
-import * as api from '../../api/index.mjs';
+import {routeSegment} from './docs-section-key.mjs';
const SLOW = 60_000;
@@ -99,7 +97,7 @@ const audit = (/** @type {string} */ root, authoringSources = []) =>
describe('the CLI docs this package ships', () => {
it(
- 'each declare a namespace a topic reads, and none fails, clashes, or overflows',
+ 'each declare a namespace something reads, and none fails, clashes, or overflows',
async () => {
const result = await auditCliSelfDocs();
expect({
@@ -107,83 +105,23 @@ describe('the CLI docs this package ships', () => {
unknown: result.unknown,
misfiled: result.misfiled,
failed: result.failed,
- keyProblems: result.keyProblems,
oversized: result.oversized,
}).toEqual({
missing: [],
unknown: [],
misfiled: [],
failed: [],
- keyProblems: [],
oversized: [],
});
expect(result.docs).toBeGreaterThan(0);
- expect(result.sections + result.authoring).toBe(result.docs);
- },
- SLOW,
- );
-
- it(
- 'give every function @astryxdesign/cli/api exports a section of astryx docs cli',
- async () => {
- const topic = await buildCliTopic();
- const keys = new Set(topic.sections.map(section => section.id));
- const exported = Object.entries(api)
- .filter(
- ([, value]) =>
- typeof value === 'function' &&
- Object.getOwnPropertyDescriptor(value, 'prototype')?.writable !==
- false,
- )
- .map(([name]) => `api-${keySegment(name)}`);
- expect(exported.length).toBeGreaterThan(0);
- expect(exported.filter(key => !keys.has(key))).toEqual([]);
- },
- SLOW,
- );
-
- it(
- 'give every command doc a section, keyed commands-<name>',
- async () => {
- const {loaded} = await loadCliSelfDocs();
- const commands = loaded.filter(({doc}) => doc.type === 'command');
- expect(commands.length).toBeGreaterThan(0);
- const keys = new Set(
- (await buildCliTopic()).sections.map(section => section.id),
- );
- expect(
- commands
- .map(({doc}) => `commands-${keySegment(doc.name)}`)
- .filter(key => !keys.has(key)),
- ).toEqual([]);
- },
- SLOW,
- );
-
- it(
- 'are read one section at a time through docs()',
- async () => {
- const search = await api.docs('cli', 'api-search');
- expect(search).toMatchObject({type: 'docs.detail.section'});
- expect(JSON.stringify(search.data)).toContain('search()');
- const command = await api.docs('cli', 'commands-integration-add');
- expect(JSON.stringify(command.data)).toContain(
- 'astryx integration add <kind> <name>',
- );
- const codes = await api.docs('cli', 'api-error-codes');
- expect(JSON.stringify(codes.data)).toContain('ERR_UNKNOWN_SECTION');
- const index = await api.docs('cli', undefined, {index: true});
- expect(index.type).toBe('docs.index');
- expect(index.data.sections.length).toBe(
- (await buildCliTopic()).sections.length,
- );
+ expect(result.tree + result.authoring).toBe(result.docs);
},
SLOW,
);
});
describe('auditCliSelfDocs', () => {
- it('reports a doc with no namespace, and one no topic reads', async () => {
+ it('reports a doc with no namespace, and one nothing reads', async () => {
const root = writeTree({
'api/alpha/alpha.doc.mjs': docModule(fn('alpha', {namespace: undefined})),
'clients/cli/commands/beta.doc.mjs': docModule(
@@ -196,7 +134,7 @@ describe('auditCliSelfDocs', () => {
expect(result.unknown).toEqual([
{source: 'clients/cli/commands/beta.doc.mjs', namespace: 'cli'},
]);
- expect(result.sections).toBe(1);
+ expect(result.tree).toBe(1);
});
it('holds the authoring namespace to the authoring topic list', async () => {
@@ -211,6 +149,7 @@ describe('auditCliSelfDocs', () => {
'authoring/y/y.doc.mjs is read in `astryx docs authoring`, but its namespace is "cli/api"',
]);
expect(result.authoring).toBe(1);
+ expect(result.tree).toBe(0);
});
it('reports a doc that fails to load, and skips fixture directories', async () => {
@@ -231,40 +170,71 @@ describe('auditCliSelfDocs', () => {
error: expect.stringContaining('boom'),
}),
]);
- expect(result.sections).toBe(1);
+ expect(result.tree).toBe(1);
});
- it('reports two cli sections that share a key', async () => {
+ it('reports a tree doc too large for one read', async () => {
const root = writeTree({
- 'api/a/fooBar.doc.mjs': docModule(fn('fooBar')),
- 'api/b/foo_bar.doc.mjs': docModule(fn('foo_bar')),
+ 'api/big/big.doc.mjs': docModule(
+ fn('big', {description: 'x'.repeat(2_000)}),
+ ),
+ 'api/small/small.doc.mjs': docModule(fn('small')),
+ });
+ const result = await auditCliSelfDocs({root, authoringSources: [], budget: 1_000});
+ expect(result.oversized.map(entry => entry.key)).toEqual(['big']);
+ });
+
+ it('names every namespace a CLI doc may declare, and what reads it', () => {
+ expect(CLI_DOC_NAMESPACES).toEqual({
+ 'cli/commands': {reader: 'tree'},
+ 'cli/api': {reader: 'tree'},
+ authoring: {reader: 'authoring'},
});
- const result = await audit(root);
- expect(result.keyProblems).toHaveLength(1);
- expect(result.keyProblems[0]).toContain('api-foo-bar');
});
});
-describe('buildCliReferenceDoc', () => {
- it('keeps a command and the function it runs apart, and links them', () => {
- const topic = buildCliReferenceDoc([
- fn('docs', {command: 'docs'}),
- command('docs', {fn: 'docs'}),
- ]);
- expect(topic.sections.map(s => s.id)).toEqual([
- 'commands-docs',
- 'api-docs',
- ]);
- expect(JSON.stringify(topic.sections[0].content)).toContain(
- 'It runs `docs()` from `@astryxdesign/cli/api`. Read it with `astryx docs cli api-docs`.',
+/**
+ * An index whose routes are the ones the docs tree gives the CLI's own docs.
+ * @param {any[]} docs
+ */
+const indexOf = docs =>
+ cliDocIndex(docs, (kind, name) =>
+ kind === 'command'
+ ? `cli/commands/${routeSegment(name)}`
+ : kind === 'function'
+ ? `cli/api/functions/${routeSegment(name)}`
+ : null,
+ );
+
+describe('cliDocSection', () => {
+ it('links a command and the function it runs by identity, never by route', () => {
+ const docs = [fn('docs', {command: 'docs'}), command('docs', {fn: 'docs'})];
+ const index = indexOf(docs);
+ expect(JSON.stringify(cliDocSection(docs[1], index).content)).toContain(
+ 'It runs `docs()` from `@astryxdesign/cli/api`. Read it with {@link function:docs}.',
);
- expect(JSON.stringify(topic.sections[1].content)).toContain(
- '`astryx docs` runs it. Read it with `astryx docs cli commands-docs`.',
+ expect(JSON.stringify(cliDocSection(docs[0], index).content)).toContain(
+ '`astryx docs` runs it. Read it with {@link command:docs}.',
+ );
+ });
+
+ it("links a function to the command its command line starts with, or to none", () => {
+ const docs = [
+ fn('integrationAddTheme', {command: 'integration add theme'}),
+ command('integration add'),
+ fn('gone', {command: 'gone away'}),
+ ];
+ const index = cliDocIndex(docs);
+ expect(JSON.stringify(cliDocSection(docs[0], index).content)).toContain(
+ '`astryx integration add theme` runs it. Read it with {@link command:integration add}.',
+ );
+ expect(JSON.stringify(cliDocSection(docs[2], index).content)).not.toContain(
+ 'runs it',
);
});
it('renders a command: usage, arguments, options, examples, exit codes, subcommands', () => {
- const topic = buildCliReferenceDoc([
+ const docs = [
command('grp', {subcommands: ['sub', 'gone']}),
command('grp sub', {
description: 'The long form.',
@@ -292,14 +262,23 @@ describe('buildCliReferenceDoc', () => {
fn('grpSub', {
params: [{name: 'options.limit', type: 'number', description: 'Max.'}],
}),
- ]);
- const [group, sub] = topic.sections;
+ ];
+ // `grp gone` has no doc, so it gets no line.
+ const index = cliDocIndex(docs, (kind, name) =>
+ kind === 'command' && name === 'grp gone'
+ ? null
+ : kind === 'command'
+ ? `cli/commands/${routeSegment(name)}`
+ : `cli/api/functions/${routeSegment(name)}`,
+ );
+ const group = cliDocSection(docs[0], index);
+ const sub = cliDocSection(docs[1], index);
expect(group.content).toContainEqual({
type: 'list',
style: 'unordered',
- items: ['`astryx grp sub`: `astryx docs cli commands-grp-sub`'],
+ items: ['`astryx grp sub`: {@link command:grp sub}'],
});
- expect(sub).toMatchObject({id: 'commands-grp-sub', title: 'astryx grp sub'});
+ expect(sub).toMatchObject({id: 'grp-sub', title: 'astryx grp sub'});
expect(sub.content).toEqual([
{type: 'prose', text: 'Do grp sub'},
{type: 'prose', text: 'The long form.'},
@@ -331,28 +310,28 @@ describe('buildCliReferenceDoc', () => {
},
{
type: 'prose',
- text: 'It runs `grpSub()` from `@astryxdesign/cli/api`. Read it with `astryx docs cli api-grp-sub`.',
+ text: 'It runs `grpSub()` from `@astryxdesign/cli/api`. Read it with {@link function:grpSub}.',
},
]);
});
- it('renders an API function and an enum', () => {
- const topic = buildCliReferenceDoc([
- fn('alpha', {
- description: 'Longer.',
- signature: 'alpha(x: string): Promise<Alpha>',
- params: [{name: 'x', type: 'string', description: 'The x.'}],
- throws: [{code: 'ERR_X', when: 'x is bad'}],
- examples: [{label: 'Call it', code: "await alpha('x');"}],
- }),
- enumDoc('codes', {
- members: [
- {value: 'A', description: 'The a.'},
- {value: 'B', description: 'The b.', deprecated: 'Use A.'},
- ],
- }),
- ]);
- expect(topic.sections[0].content).toEqual([
+ it('renders an API function, an enum, and a schema', () => {
+ const alpha = fn('alpha', {
+ description: 'Longer.',
+ signature: 'alpha(x: string): Promise<Alpha>',
+ params: [{name: 'x', type: 'string', description: 'The x.'}],
+ throws: [{code: 'ERR_X', when: 'x is bad'}],
+ examples: [{label: 'Call it', code: "await alpha('x');"}],
+ });
+ const codes = enumDoc('codes', {
+ members: [
+ {value: 'A', description: 'The a.'},
+ {value: 'B', description: 'The b.', deprecated: 'Use A.'},
+ ],
+ });
+ const output = schema('output', {namespace: 'cli/api'});
+ const index = indexOf([alpha, codes, output]);
+ expect(cliDocSection(alpha, index).content).toEqual([
{type: 'prose', text: 'The alpha function.'},
{type: 'prose', text: 'Longer.'},
{type: 'code', lang: 'ts', code: 'alpha(x: string): Promise<Alpha>'},
@@ -374,8 +353,8 @@ describe('buildCliReferenceDoc', () => {
},
{type: 'code', lang: 'ts', label: 'Call it', code: "await alpha('x');"},
]);
- expect(topic.sections[1]).toEqual({
- id: 'api-codes',
+ expect(cliDocSection(codes, index)).toEqual({
+ id: 'codes',
title: 'codes',
content: [
{type: 'prose', text: 'The codes.'},
@@ -389,49 +368,8 @@ describe('buildCliReferenceDoc', () => {
},
],
});
- });
-
- it('orders commands, then functions, schemas, and enums, and leaves other namespaces out', () => {
- const topic = buildCliReferenceDoc([
- enumDoc('codes'),
- schema('output', {namespace: 'cli/api'}),
- fn('beta'),
- schema('config'),
- command('zed'),
- fn('alpha'),
- command('abc'),
- fn('gone', {namespace: 'somewhere'}),
- ]);
- expect(topic.sections.map(s => s.id)).toEqual([
- 'commands-abc',
- 'commands-zed',
- 'api-alpha',
- 'api-beta',
- 'api-output',
- 'api-codes',
- ]);
- });
-});
-
-describe('section keys', () => {
- it('join lowercase words with hyphens, whatever the name looks like', () => {
- expect(keySegment('integrationPackCheck')).toBe('integration-pack-check');
- expect(keySegment('doctor integration validate')).toBe(
- 'doctor-integration-validate',
- );
- expect(keySegment('error-codes')).toBe('error-codes');
- expect(keySegment('isError')).toBe('is-error');
- });
-
- it('come from the namespace a doc declares, and only a cli one', () => {
- expect(cliSectionKey(fn('search'))).toBe('api-search');
- expect(cliSectionKey(command('theme add'))).toBe('commands-theme-add');
- expect(cliSectionKey(schema('config'))).toBeNull();
- expect(cliSectionKey(fn('x', {namespace: 'cli'}))).toBeNull();
- expect(Object.keys(CLI_DOC_NAMESPACES)).toEqual([
- 'cli/commands',
- 'cli/api',
- 'authoring',
- ]);
+ const rendered = cliDocSection(output, index);
+ expect(rendered.id).toBe('output');
+ expect(JSON.stringify(rendered.content)).toContain('The output file.');
});
});
diff --git a/packages/cli/foundation/discovery/component-discovery.mjs b/packages/cli/foundation/discovery/component-discovery.mjs
index 85aa9c3655..0e9f9c511e 100644
--- a/packages/cli/foundation/discovery/component-discovery.mjs
+++ b/packages/cli/foundation/discovery/component-discovery.mjs
@@ -8,6 +8,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import {existsCaseExact} from '../fs/paths.mjs';
import {CORE_PROVIDER_ID} from '../identity/providers.mjs';
+import {loadComponentDoc} from './component-loader.mjs';
const SKIP_DIRS = new Set(['hooks', 'utils', '__tests__', 'node_modules']);
@@ -692,6 +693,53 @@ export function discoverIntegrationComponents(integration) {
return [...byName.values()];
}
+/**
+ * Load and validate every discovered integration component independently.
+ * Invalid metadata or a missing same-stem source removes only that component;
+ * callers can report the returned errors while retaining valid siblings.
+ *
+ * @param {{name: string, components?: string, issuesUrl?: string}} integration
+ * @returns {Promise<{
+ * components: Array<{name: string, package: string, docPath: string, sourcePath: string, issuesUrl: string|undefined, group: string|null}>,
+ * discovered: Array<{name: string, package: string, docPath: string, sourcePath: string|null, issuesUrl: string|undefined, group: string|null}>,
+ * errors: Array<{name: string, message: string}>,
+ * }>}
+ */
+export async function discoverValidIntegrationComponents(integration) {
+ const discovered = discoverIntegrationComponents(integration);
+ /** @type {Array<{name: string, package: string, docPath: string, sourcePath: string, issuesUrl: string|undefined, group: string|null}>} */
+ const components = [];
+ /** @type {Array<{name: string, message: string}>} */
+ const errors = [];
+
+ for (const record of discovered) {
+ if (record.sourcePath == null) {
+ errors.push({
+ name: record.name,
+ message: `Component "${record.name}" is missing its same-stem source file ${record.name}.tsx.`,
+ });
+ continue;
+ }
+ try {
+ await loadComponentDoc(record.docPath);
+ components.push(
+ /** @type {{name: string, package: string, docPath: string, sourcePath: string, issuesUrl: string|undefined, group: string|null}} */ (
+ record
+ ),
+ );
+ } catch (err) {
+ errors.push({
+ name: record.name,
+ message: `Component "${record.name}" has invalid metadata: ${
+ err instanceof Error ? err.message : String(err)
+ }`,
+ });
+ }
+ }
+
+ return {components, discovered, errors};
+}
+
/**
* Find an integration component's doc file by name within a loaded
* integration's resolved `components` dir. Honors the same-stem convention
diff --git a/packages/cli/foundation/discovery/docs-discovery.mjs b/packages/cli/foundation/discovery/docs-discovery.mjs
index 230234c932..a2fd8f96d7 100644
--- a/packages/cli/foundation/discovery/docs-discovery.mjs
+++ b/packages/cli/foundation/discovery/docs-discovery.mjs
@@ -71,6 +71,8 @@ const TOPIC_NAME_RE = /^[\w-]+$/;
* @typedef {object} DocsTopicRecord A doc file discovered under a docs root.
* @property {string} name
* @property {string} package owner package
+ * @property {string} [providerId] the owner's ProviderId, when it differs from
+ * the package name
* @property {string} path absolute path to the doc file
* @property {string} [title]
* @property {string} [description]
@@ -83,13 +85,21 @@ const TOPIC_NAME_RE = /^[\w-]+$/;
* @typedef {object} DocsTopicEntry A resolved topic in the catalog.
* @property {string} name
* @property {string} package owner package
+ * @property {string} [providerId] the owner's ProviderId; the package name when
+ * absent. Links in the topic resolve against it.
* @property {string} path absolute path to the doc file
* @property {string} [title]
* @property {string} [description]
* @property {string|null} [category]
* @property {string} [replaces] the topic this one took the place of
- * @property {Array<{package: string, path: string}>} extensions overlays to
- * merge onto the base doc, in the order their integrations were configured
+ * @property {Array<{package: string, path: string, providerId?: string}>} extensions
+ * overlays to merge onto the base doc, in the order their integrations were
+ * configured; each section an extension adds resolves its links against the
+ * extension's provider id (its package name when absent)
+ * @property {string} [parent] the route of the namespace a tree guide sits in
+ * @property {string} [route] a tree guide's route
+ * @property {boolean} [tree] a guide that only the docs tree reads, by its
+ * route; never a flat topic
*/
/**
@@ -144,7 +154,10 @@ export const GRAPH_BLOCK_TYPES = new Set([
'reference',
]);
-/** Doc fields only the docs graph reads; a topic that sets one fails to load. */
+/**
+ * Doc fields only the docs tree reads. A flat topic that sets one fails to
+ * load; a guide the tree places may set `placement` (spec:AST-046).
+ */
export const GRAPH_ONLY_FIELDS = ['placement', 'aliases', 'audience'];
/**
@@ -180,14 +193,16 @@ const SECTION_FIELDS = ['id', 'title', 'category', 'content', 'previewType'];
* where the file that needs fixing can be named.
*
* @param {any} doc a parsed doc
+ * @param {{placement?: boolean}} [options] `placement`: the doc is a guide the
+ * docs tree places, so its `placement` field is read, not rejected
* @returns {string[]} problems, each already pointed at a place in the doc
*/
-export function problemsInTopic(doc) {
- // A namespace doc is valid authoring that only the docs graph reads. Said
+export function problemsInTopic(doc, {placement = false} = {}) {
+ // A namespace doc is valid authoring that only the docs tree reads. Said
// plainly, instead of as the topic fields it does not have.
if (doc?.type === 'namespace') {
return [
- `"${doc.name}" is a namespace doc. Only the docs graph reads namespace docs, and it is not built yet; remove this file from the docs directory.`,
+ `"${doc.name}" is a namespace doc, which the docs tree reads, not the topic list. The CLI keeps its own in assets/docs/tree; an integration ships its namespace docs in its docs directory.`,
];
}
/** @type {string[]} */
@@ -203,6 +218,8 @@ export function problemsInTopic(doc) {
);
}
for (const field of GRAPH_ONLY_FIELDS) {
+ // A guide the docs tree places carries `placement`; the tree reads it.
+ if (field === 'placement' && placement) continue;
if (doc?.[field] != null) {
problems.push(
`${field}: requires the compiled graph reader and is not supported by legacy topic readers`,
@@ -319,6 +336,35 @@ export function problemsInTopic(doc) {
return problems;
}
+/**
+ * The fields the docs tree reads from a namespace doc an integration ships.
+ * @param {any} doc
+ * @returns {string[]}
+ */
+export function problemsInNamespace(doc) {
+ /** @type {string[]} */
+ const problems = [];
+ for (const field of ['name', 'title', 'summary']) {
+ if (typeof doc?.[field] !== 'string' || doc[field] === '') {
+ problems.push(`${field}: expected a non-empty string`);
+ }
+ }
+ const slots = doc?.slots;
+ if (slots == null || typeof slots !== 'object' || Object.keys(slots).length === 0) {
+ problems.push('slots: expected at least one slot');
+ return problems;
+ }
+ for (const [name, slot] of Object.entries(slots)) {
+ if (typeof slot?.title !== 'string' || slot.title === '') {
+ problems.push(`slots.${name}.title: expected a non-empty string`);
+ }
+ if (!Array.isArray(slot?.accepts?.kinds) || slot.accepts.kinds.length === 0) {
+ problems.push(`slots.${name}.accepts.kinds: expected at least one kind`);
+ }
+ }
+ return problems;
+}
+
/**
* Discover the topics contributed by a single loaded integration. Mirrors
* `discoverIntegrationComponents`: walk the resolved root, take every
@@ -326,11 +372,15 @@ export function problemsInTopic(doc) {
* discovery this loads each doc, because a topic's name and its relationship
* to an existing topic are fields inside the file.
*
+ * A namespace doc and a guide with `placement` go to the docs tree instead of
+ * the topic list (spec:AST-046): they come back in `namespaces` and `guides`,
+ * named by the integration's provider id.
+ *
* Errors are returned, not thrown: one unusable doc is reported as an issue
* against its package while the rest of the CLI keeps working.
*
- * @param {{name: string, docs?: string}} integration a loaded integration
- * @returns {Promise<{records: DocsTopicRecord[], errors: Error[]}>}
+ * @param {{name: string, docs?: string, providerId?: string}} integration a loaded integration
+ * @returns {Promise<{records: DocsTopicRecord[], errors: Error[], namespaces: import('../doc-compiler/tree.mjs').TreeNamespaceInput[], guides: import('../doc-compiler/tree.mjs').TreeDocInput[]}>}
*/
export async function discoverIntegrationDocs(integration) {
const docsDir = integration?.docs;
@@ -338,7 +388,14 @@ export async function discoverIntegrationDocs(integration) {
const records = [];
/** @type {Error[]} */
const errors = [];
- if (!docsDir || !fs.existsSync(docsDir)) return {records, errors};
+ /** @type {import('../doc-compiler/tree.mjs').TreeNamespaceInput[]} */
+ const namespaces = [];
+ /** @type {import('../doc-compiler/tree.mjs').TreeDocInput[]} */
+ const guides = [];
+ if (!docsDir || !fs.existsSync(docsDir)) {
+ return {records, errors, namespaces, guides};
+ }
+ const providerId = integration.providerId ?? integration.name;
/** @type {string[]} */
const files = [];
@@ -373,11 +430,34 @@ export async function discoverIntegrationDocs(integration) {
);
continue;
}
- const problems = problemsInTopic(doc);
+ const relative = path.relative(docsDir, file);
+ const source = `${integration.name}/${relative.split(path.sep).join('/')}`;
+ if (/** @type {any} */ (doc)?.type === 'namespace') {
+ const problems = problemsInNamespace(doc);
+ if (problems.length > 0) {
+ errors.push(
+ new Error(
+ `${relative} is not a usable namespace doc:\n${problems
+ .map(problem => ` ${problem}`)
+ .join('\n')}`,
+ ),
+ );
+ continue;
+ }
+ namespaces.push({
+ provider: integration.name,
+ providerId,
+ source,
+ doc: /** @type {any} */ (doc),
+ });
+ continue;
+ }
+ const placed = /** @type {any} */ (doc)?.placement != null;
+ const problems = problemsInTopic(doc, {placement: placed});
if (problems.length > 0) {
errors.push(
new Error(
- `${path.relative(docsDir, file)} is not a usable topic:\n${problems
+ `${relative} is not a usable topic:\n${problems
.map(problem => ` ${problem}`)
.join('\n')}`,
),
@@ -398,6 +478,29 @@ export async function discoverIntegrationDocs(integration) {
continue;
}
seen.set(topicKey, path.relative(docsDir, file));
+ if (placed) {
+ if (parsed.replaces != null || parsed.extends != null) {
+ errors.push(
+ new Error(
+ `${relative} is placed in the docs tree and also declares \`${parsed.replaces != null ? 'replaces' : 'extends'}\`. A placed guide has its own route; only a flat topic takes over or extends another.`,
+ ),
+ );
+ continue;
+ }
+ guides.push({
+ provider: integration.name,
+ providerId,
+ source,
+ kind: 'generic',
+ name: parsed.name,
+ title: parsed.title,
+ summary: parsed.description,
+ group: null,
+ placement: parsed.placement,
+ ref: {topicFile: file},
+ });
+ continue;
+ }
if (parsed.replaces != null && parsed.extends != null) {
errors.push(
new Error(
@@ -415,10 +518,11 @@ export async function discoverIntegrationDocs(integration) {
category: parsed.category ?? null,
replaces: parsed.replaces,
extendsTopic: parsed.extends,
+ ...(providerId === integration.name ? {} : {providerId}),
});
}
- return {records, errors};
+ return {records, errors, namespaces, guides};
}
/**
@@ -504,6 +608,46 @@ export class DocsCatalog {
#topics = new Map();
/** @type {Map<string, string>} old topic name → the name that replaced it */
#aliases = new Map();
+ /** @type {Array<{namespaces: import('../doc-compiler/tree.mjs').TreeNamespaceInput[], guides: import('../doc-compiler/tree.mjs').TreeDocInput[]}>} */
+ #treeInputs = [];
+ /** @type {Array<{package: string, message: string}>} */
+ #issues = [];
+
+ /**
+ * Record a doc file a package ships that did not load. Its package's docs
+ * are withdrawn; readers name the package so an author knows where to look.
+ * @param {{package: string, message: string}} issue
+ */
+ addIssue(issue) {
+ this.#issues.push(issue);
+ }
+
+ /**
+ * The doc files that did not load, by package.
+ * @returns {ReadonlyArray<{package: string, message: string}>}
+ */
+ get issues() {
+ return this.#issues;
+ }
+
+ /**
+ * Add the namespace docs and placed guides one integration ships to the
+ * docs tree (spec:AST-046).
+ * @param {{namespaces: import('../doc-compiler/tree.mjs').TreeNamespaceInput[], guides: import('../doc-compiler/tree.mjs').TreeDocInput[]}} inputs
+ */
+ addTreeInputs(inputs) {
+ if (inputs.namespaces.length > 0 || inputs.guides.length > 0) {
+ this.#treeInputs.push(inputs);
+ }
+ }
+
+ /**
+ * What the integrations add to the docs tree, in configured order.
+ * @returns {ReadonlyArray<{namespaces: import('../doc-compiler/tree.mjs').TreeNamespaceInput[], guides: import('../doc-compiler/tree.mjs').TreeDocInput[]}>}
+ */
+ get treeInputs() {
+ return this.#treeInputs;
+ }
/**
* Seed a catalog with the CLI's own topics.
@@ -541,7 +685,11 @@ export class DocsCatalog {
message: `"${record.name}" extends "${record.extendsTopic}", which is not a topic in this project.`,
};
}
- target.extensions.push({package: record.package, path: record.path});
+ target.extensions.push({
+ package: record.package,
+ path: record.path,
+ ...(record.providerId ? {providerId: record.providerId} : {}),
+ });
return null;
}
@@ -579,6 +727,7 @@ export class DocsCatalog {
description: record.description,
category: record.category,
replaces: replaced,
+ ...(record.providerId ? {providerId: record.providerId} : {}),
// Extensions were authored against the content that just went away.
extensions: [],
});
@@ -608,11 +757,26 @@ export class DocsCatalog {
title: record.title,
description: record.description,
category: record.category,
+ ...(record.providerId ? {providerId: record.providerId} : {}),
extensions: [],
});
return null;
}
+ /**
+ * Every other name a topic answers to, lowercased: the names of the topics
+ * it replaced, directly or through a chain of replacements. `resolve` finds
+ * the topic by each of them.
+ * @param {DocsTopicEntry} entry
+ * @returns {string[]}
+ */
+ aliasesOf(entry) {
+ const key = entry.name.toLowerCase();
+ return [...this.#aliases]
+ .filter(([, to]) => to === key)
+ .map(([from]) => from);
+ }
+
/**
* Look a topic up by name, case-insensitively, following the alias a renamed
* replacement left behind.
diff --git a/packages/cli/foundation/discovery/docs-discovery.test.mjs b/packages/cli/foundation/discovery/docs-discovery.test.mjs
index 046a3a44f4..b14337e09c 100644
--- a/packages/cli/foundation/discovery/docs-discovery.test.mjs
+++ b/packages/cli/foundation/discovery/docs-discovery.test.mjs
@@ -74,16 +74,16 @@ describe('discoverBuiltinTopics', () => {
describe('discoverIntegrationDocs', () => {
it('contributes nothing when no docs root is declared or the root is gone', async () => {
- expect(await discoverIntegrationDocs({name: '@acme/widgets'})).toEqual({
- records: [],
- errors: [],
- });
+ const nothing = {records: [], errors: [], namespaces: [], guides: []};
+ expect(await discoverIntegrationDocs({name: '@acme/widgets'})).toEqual(
+ nothing,
+ );
expect(
await discoverIntegrationDocs({
name: '@acme/widgets',
docs: path.join(tmpDir, 'nope'),
}),
- ).toEqual({records: [], errors: []});
+ ).toEqual(nothing);
});
it('reads every topic under the root, with what it declares', async () => {
@@ -169,10 +169,7 @@ describe('discoverIntegrationDocs', () => {
id: 'steps',
title: 'Steps',
content: [
- {
- type: 'workflow',
- steps: [{title: 'Install', description: 'Run install.'}],
- },
+ {type: 'collection', source: {slot: 'guides'}},
],
},
],
@@ -183,9 +180,9 @@ describe('discoverIntegrationDocs', () => {
expect(errors[0].message).toContain('Invalid discriminator value');
});
- it('names a namespace doc instead of listing topic fields it lacks', async () => {
- const {records, errors} = await discoverIntegrationDocs(
- integration('@acme/namespace', {
+ it('hands namespace docs and placed guides to the docs tree, by provider id', async () => {
+ const found = await discoverIntegrationDocs({
+ ...integration('@acme/namespace', {
'guides.doc.mjs': {
type: 'namespace',
name: 'guides',
@@ -193,14 +190,56 @@ describe('discoverIntegrationDocs', () => {
summary: 'Every guide.',
slots: {guides: {title: 'Guides', accepts: {kinds: ['generic']}}},
},
+ 'setup.doc.mjs': topic({
+ name: 'setup',
+ title: 'Set up',
+ placement: {parent: 'namespace:guides', slot: 'guides', order: 1},
+ }),
+ 'deploying.doc.mjs': topic(),
+ }),
+ providerId: '@acme/tree-provider',
+ });
+ expect(found.errors).toEqual([]);
+ expect(found.records.map(record => record.name)).toEqual(['deploying']);
+ expect(found.records[0].providerId).toBe('@acme/tree-provider');
+ expect(found.namespaces).toMatchObject([
+ {
+ provider: '@acme/namespace',
+ providerId: '@acme/tree-provider',
+ source: '@acme/namespace/guides.doc.mjs',
+ doc: {name: 'guides'},
+ },
+ ]);
+ expect(found.guides).toMatchObject([
+ {
+ provider: '@acme/namespace',
+ providerId: '@acme/tree-provider',
+ kind: 'generic',
+ name: 'setup',
+ placement: {parent: 'namespace:guides', slot: 'guides', order: 1},
+ },
+ ]);
+ });
+
+ it('names what a namespace doc lacks, and refuses a placed guide that replaces a topic', async () => {
+ const {errors, namespaces, guides} = await discoverIntegrationDocs(
+ integration('@acme/namespace', {
+ 'guides.doc.mjs': {type: 'namespace', name: 'guides', title: 'Guides'},
+ 'setup.doc.mjs': topic({
+ name: 'setup',
+ replaces: 'getting-started',
+ placement: {parent: 'namespace:guides', slot: 'guides'},
+ }),
}),
);
- expect(records).toEqual([]);
- expect(errors).toHaveLength(1);
- expect(errors[0].message).toContain(
- '"guides" is a namespace doc. Only the docs graph reads namespace docs',
+ expect(namespaces).toEqual([]);
+ expect(guides).toEqual([]);
+ expect(errors.map(error => error.message).join('\n')).toMatch(
+ /guides\.doc\.mjs.*slots/,
+ );
+ expect(errors.map(error => error.message).join('\n')).toContain(
+ 'is placed in the docs tree and also declares `replaces`',
);
- expect(errors[0].message).not.toContain('sections:');
});
});
diff --git a/packages/cli/foundation/discovery/docs-output-budget.mjs b/packages/cli/foundation/discovery/docs-output-budget.mjs
index dc9f2cfaa9..53f40f50fb 100644
--- a/packages/cli/foundation/discovery/docs-output-budget.mjs
+++ b/packages/cli/foundation/discovery/docs-output-budget.mjs
@@ -26,7 +26,7 @@ export function docPayloadBytes(payload) {
}
/**
- * @param {import('../../api/docs/docs.type.mjs').DocsIndex} index
+ * @param {Omit<import('../../api/docs/docs.type.mjs').DocsIndex, 'links'> | import('../../api/docs/docs.type.mjs').DocsIndex} index
* @returns {number}
*/
export function docsIndexBytes(index) {
diff --git a/packages/cli/foundation/discovery/docs-section-key.mjs b/packages/cli/foundation/discovery/docs-section-key.mjs
index e66b61d0d6..7deff958c8 100644
--- a/packages/cli/foundation/discovery/docs-section-key.mjs
+++ b/packages/cli/foundation/discovery/docs-section-key.mjs
@@ -93,6 +93,20 @@ function legacyTitleMatchIndex(sections, query) {
});
}
+/**
+ * A name as a docs-tree route segment: lowercase words joined by hyphens, so
+ * `integrationPackCheck` and `integration pack` both read naturally.
+ * @param {string} name
+ * @returns {string}
+ */
+export function routeSegment(name) {
+ return String(name)
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '');
+}
+
/**
* Fatal key problems: only an explicitly authored `id` can make a previously
* readable topic invalid. Derived-key collisions and titles with no Latin
@@ -292,7 +306,7 @@ export function sectionSummary(section, max = SECTION_SUMMARY_MAX) {
* The index a topic-only read returns: what the topic is, and one entry per
* section with the key to read it by.
* @param {{name: string, title: string, description: string, sections: any[]}} doc
- * @returns {import('../../api/docs/docs.type.mjs').DocsIndex}
+ * @returns {Omit<import('../../api/docs/docs.type.mjs').DocsIndex, 'links'>}
*/
export function buildDocsIndexData(doc) {
return {
diff --git a/packages/cli/foundation/discovery/template-adapter.mjs b/packages/cli/foundation/discovery/template-adapter.mjs
index a63750f27a..7762752c8a 100644
--- a/packages/cli/foundation/discovery/template-adapter.mjs
+++ b/packages/cli/foundation/discovery/template-adapter.mjs
@@ -25,6 +25,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import {createRequire} from 'node:module';
import {readDocView} from '../doc-compiler/read.mjs';
+import {importDocModule} from '../doc-compiler/import.mjs';
import {CLI_ROOT, discoverExternalPackages} from '../fs/paths.mjs';
import {CORE_PROVIDER_ID} from '../identity/providers.mjs';
import {Project} from '../config/project.mjs';
@@ -44,6 +45,53 @@ export function pkgOf(t) {
return t.package ?? CORE_PACKAGE;
}
+/**
+ * Every id that should resolve to a discovered template. Replacements keep
+ * their own integration id and also own the Core id they replace.
+ * @param {{dirName: string, replaces?: string}} template
+ * @returns {string[]}
+ */
+export function templateLookupIds(template) {
+ if (template.replaces && template.replaces !== template.dirName) {
+ return [template.dirName, template.replaces];
+ }
+ return [template.dirName];
+}
+
+/**
+ * Remove entries shadowed in the default discovery view while retaining them in
+ * package-scoped views. An active replacement owns its target id. A rejected
+ * same-id declaration falls back to Core when a Core template of the same kind
+ * owns that id; otherwise the integration template remains available by kind.
+ * @param {DiscoveredTemplate[]} templates
+ * @returns {DiscoveredTemplate[]}
+ */
+export function effectiveTemplateDiscovery(templates) {
+ const activeTargets = new Set(
+ templates
+ .filter(template => template.replaces != null)
+ .map(template => `${template.type}:${template.replaces}`),
+ );
+ const coreIds = new Set(
+ templates
+ .filter(template => pkgOf(template) === CORE_PACKAGE)
+ .map(template => `${template.type}:${template.dirName}`),
+ );
+ return templates.filter(template => {
+ if (
+ template.replacementRejected &&
+ template.replacementTarget === template.dirName &&
+ coreIds.has(`${template.type}:${template.dirName}`)
+ ) {
+ return false;
+ }
+ return (
+ !activeTargets.has(`${template.type}:${template.dirName}`) ||
+ template.replaces != null
+ );
+ });
+}
+
/**
* A discovered template (page or block), normalized across core, external, and
* integration sources. Not every source populates every field, so
@@ -66,6 +114,11 @@ export function pkgOf(t) {
* @property {string} filePath
* @property {string} docPath
* @property {string} [package]
+ * @property {boolean} [autolinked] whether the owning integration was discovered
+ * from package.json rather than named in astryx.config
+ * @property {string} [replaces] active Core template id this integration template replaces
+ * @property {boolean} [replacementRejected] whether an invalid declaration was disabled
+ * @property {string} [replacementTarget] disabled declaration target
*/
/**
@@ -74,6 +127,15 @@ export function pkgOf(t) {
* @property {string} package
* @property {string} [template]
* @property {string} message
+ * @property {string} [code]
+ * @property {'warning' | 'error'} [severity]
+ * @property {string} [replacementTarget] Core target whose replacement set is invalid
+ * @property {boolean} [autolinked] whether the declaration came from an autolinked integration
+ */
+
+/**
+ * A semantic error in an integration template replacement declaration.
+ * @typedef {TemplateDiscoveryError & {code: 'missing_template_replacement_target' | 'ambiguous_template_replacement' | 'invalid_template_replacement', severity: 'warning' | 'error'}} TemplateReplacementError
*/
/**
@@ -683,38 +745,291 @@ export async function discoverCoreTemplates() {
}
/**
+ * Apply valid integration replacements to a raw template set.
+ *
+ * One declaration owns its Core target. When different configured packages
+ * replace the same target, the later package wins and discovery returns a
+ * warning, matching integration-doc replacement order. Multiple declarations
+ * inside one package are invalid and fail closed. Missing targets and kind
+ * mismatches also fail closed: Core stays selected and every integration
+ * template remains addressable by its own id.
+ *
+ * @param {DiscoveredTemplate[]} templates
+ * @param {TemplateDiscoveryError[]} [declarationErrors]
+ * @returns {{templates: DiscoveredTemplate[], errors: TemplateReplacementError[]}}
+ */
+export function applyTemplateReplacements(templates, declarationErrors = []) {
+ /** @type {Map<string, DiscoveredTemplate[]>} */
+ const coreById = new Map();
+ /** @type {Map<string, DiscoveredTemplate[]>} */
+ const replacementsByTarget = new Map();
+
+ for (const template of templates) {
+ if (pkgOf(template) === CORE_PACKAGE) {
+ const matches = coreById.get(template.dirName) ?? [];
+ matches.push(template);
+ coreById.set(template.dirName, matches);
+ }
+ if (template.replaces != null) {
+ const replacements = replacementsByTarget.get(template.replaces) ?? [];
+ replacements.push(template);
+ replacementsByTarget.set(template.replaces, replacements);
+ }
+ }
+
+ const activeReplacements = new Set();
+ const replacedCore = new Set();
+ /** @type {TemplateReplacementError[]} */
+ const errors = declarationErrors.map(error => ({
+ ...error,
+ code: /** @type {TemplateReplacementError['code']} */ (
+ error.code ?? 'invalid_template_replacement'
+ ),
+ severity: error.severity ?? 'error',
+ }));
+ /** @param {TemplateReplacementError} error */
+ const pushError = error => {
+ if (
+ errors.some(
+ existing =>
+ existing.code === error.code &&
+ existing.package === error.package &&
+ existing.template === error.template &&
+ existing.message === error.message,
+ )
+ ) {
+ return;
+ }
+ errors.push(error);
+ };
+ for (const [target, replacements] of replacementsByTarget) {
+ const targetErrors = errors.filter(
+ error => error.replacementTarget === target,
+ );
+ const hasExplicitIntent =
+ replacements.some(replacement => !replacement.autolinked) ||
+ targetErrors.some(error => !error.autolinked);
+ const contenders = hasExplicitIntent
+ ? replacements.filter(replacement => !replacement.autolinked)
+ : replacements;
+ let targetInvalid = targetErrors.some(
+ error =>
+ error.severity === 'error' && (!hasExplicitIntent || !error.autolinked),
+ );
+
+ /** @type {Map<string, DiscoveredTemplate[]>} */
+ const byPackage = new Map();
+ for (const replacement of replacements) {
+ const pkg = pkgOf(replacement);
+ const fromPackage = byPackage.get(pkg) ?? [];
+ fromPackage.push(replacement);
+ byPackage.set(pkg, fromPackage);
+ }
+ for (const [pkg, declarations] of byPackage) {
+ if (declarations.length < 2) continue;
+ if (!hasExplicitIntent || !declarations[0].autolinked) {
+ targetInvalid = true;
+ }
+ const message =
+ `${pkg} declares ${declarations.length} templates as replacements for Core ` +
+ `template "${target}" (${declarations.map(template => template.dirName).join(', ')}). ` +
+ 'One package must declare at most one replacement for a Core target.';
+ for (const declaration of declarations) {
+ pushError({
+ code: 'ambiguous_template_replacement',
+ severity: 'error',
+ package: pkg,
+ template: declaration.dirName,
+ replacementTarget: target,
+ autolinked: declaration.autolinked,
+ message,
+ });
+ }
+ }
+
+ const coreMatches = coreById.get(target) ?? [];
+ /** @type {Map<DiscoveredTemplate, DiscoveredTemplate>} */
+ const coreMatchByReplacement = new Map();
+ for (const replacement of replacements) {
+ const invalidAffectsTarget =
+ !hasExplicitIntent || !replacement.autolinked;
+ if (coreMatches.length === 0) {
+ if (invalidAffectsTarget) targetInvalid = true;
+ pushError({
+ code: 'missing_template_replacement_target',
+ severity: 'error',
+ package: pkgOf(replacement),
+ template: replacement.dirName,
+ replacementTarget: target,
+ autolinked: replacement.autolinked,
+ message: `Template "${replacement.dirName}" replaces "${target}", which is not a Core template id.`,
+ });
+ continue;
+ }
+ const sameType = coreMatches.filter(
+ core => core.type === replacement.type,
+ );
+ if (sameType.length !== 1) {
+ if (invalidAffectsTarget) targetInvalid = true;
+ const kinds = coreMatches.map(core => core.type).join(', ');
+ pushError({
+ code: 'invalid_template_replacement',
+ severity: 'error',
+ package: pkgOf(replacement),
+ template: replacement.dirName,
+ replacementTarget: target,
+ autolinked: replacement.autolinked,
+ message:
+ `Template "${replacement.dirName}" is a ${replacement.type} template, but Core ` +
+ `template "${target}" is ${kinds || 'not available'}. A replacement must have the same type.`,
+ });
+ continue;
+ }
+ coreMatchByReplacement.set(replacement, sameType[0]);
+ }
+
+ const validContenders = contenders.filter(replacement =>
+ coreMatchByReplacement.has(replacement),
+ );
+ if (targetInvalid || validContenders.length === 0) continue;
+
+ const replacement = validContenders[validContenders.length - 1];
+ const validReplacements = replacements.filter(candidate =>
+ coreMatchByReplacement.has(candidate),
+ );
+ if (validReplacements.length > 1) {
+ const autolinkedLost =
+ hasExplicitIntent &&
+ validReplacements.some(candidate => candidate.autolinked);
+ const allAutolinked = validReplacements.every(
+ candidate => candidate.autolinked,
+ );
+ pushError({
+ code: 'ambiguous_template_replacement',
+ severity: 'warning',
+ package: pkgOf(replacement),
+ template: replacement.dirName,
+ replacementTarget: target,
+ autolinked: replacement.autolinked,
+ message: autolinkedLost
+ ? `Core template "${target}" is replaced by ${validReplacements.map(candidate => pkgOf(candidate)).join(', ')}. ${pkgOf(replacement)} is explicitly configured, so it wins over autolinked integrations.`
+ : allAutolinked
+ ? `Core template "${target}" is replaced by autolinked dependencies ${validReplacements.map(candidate => pkgOf(candidate)).join(', ')}. ${pkgOf(replacement)} is listed later in package.json dependencies, so it wins. Add the intended package to astryx.config integrations to make precedence explicit.`
+ : `Core template "${target}" is replaced by ${validReplacements.map(candidate => pkgOf(candidate)).join(', ')}. ${pkgOf(replacement)} is configured later, so it wins.`,
+ });
+ }
+
+ activeReplacements.add(replacement);
+ const coreMatch = coreMatchByReplacement.get(replacement);
+ if (coreMatch) replacedCore.add(coreMatch);
+ }
+
+ const effective = templates.flatMap(template => {
+ if (replacedCore.has(template)) return [];
+ if (template.replaces != null && !activeReplacements.has(template)) {
+ const fallback = {
+ ...template,
+ replacementRejected: true,
+ replacementTarget: template.replaces,
+ };
+ delete fallback.replaces;
+ return [fallback];
+ }
+ return [template];
+ });
+
+ return {
+ templates: effective.sort((a, b) => a.name.localeCompare(b.name)),
+ errors,
+ };
+}
+
+/**
+ * Discover the raw Core, external, and integration template set before
+ * replacement declarations are applied.
* @param {string} [cwd]
- * @returns {Promise<DiscoveredTemplate[]>}
+ * @returns {Promise<{templates: DiscoveredTemplate[], errors: TemplateDiscoveryError[]}>}
*/
-export async function discoverAll(cwd = process.cwd()) {
+async function discoverAllSources(cwd = process.cwd()) {
const [core, external, integration] = await Promise.all([
discoverCoreTemplates(),
discoverExternalBlocks(cwd),
discoverIntegrationTemplates(cwd),
]);
- return [...core, ...external, ...integration.templates].sort((a, b) =>
+ return {
+ templates: [...core, ...external, ...integration.templates],
+ errors: integration.errors,
+ };
+}
+
+/**
+ * Discover every template without hiding replaced Core originals. Internal
+ * package-qualified selection uses this view.
+ * @param {string} [cwd]
+ * @returns {Promise<DiscoveredTemplate[]>}
+ */
+export async function discoverAllUnresolved(cwd = process.cwd()) {
+ return (await discoverAllSources(cwd)).templates.sort((a, b) =>
a.name.localeCompare(b.name),
);
}
/**
- * Like {@link discoverAll} but also returns integration-template discovery
- * errors (missing same-stem source, missing `type`, load failure). Use this
- * when the caller wants to warn about malformed integration templates.
+ * Resolve replacement declarations while retaining package-addressable entries
+ * that are shadowed or rejected in the default discovery view.
+ * @param {string} [cwd]
+ * @returns {Promise<{templates: DiscoveredTemplate[], errors: Array<TemplateDiscoveryError | TemplateReplacementError>}>}
+ */
+async function resolveAllSources(cwd = process.cwd()) {
+ const discovered = await discoverAllSources(cwd);
+ const replacementErrors = discovered.errors.filter(
+ error => error.replacementTarget != null,
+ );
+ const resolved = applyTemplateReplacements(
+ discovered.templates,
+ replacementErrors,
+ );
+ return {
+ templates: resolved.templates,
+ errors: [
+ ...discovered.errors.filter(error => error.replacementTarget == null),
+ ...resolved.errors,
+ ],
+ };
+}
+
+/**
+ * Discover the resolved catalog before default-view shadowing. Internal
+ * package-qualified selection uses this view.
+ * @param {string} [cwd]
+ * @returns {Promise<DiscoveredTemplate[]>}
+ */
+export async function discoverAllResolved(cwd = process.cwd()) {
+ return (await resolveAllSources(cwd)).templates;
+}
+
+/**
+ * @param {string} [cwd]
+ * @returns {Promise<DiscoveredTemplate[]>}
+ */
+export async function discoverAll(cwd = process.cwd()) {
+ return effectiveTemplateDiscovery(await discoverAllResolved(cwd));
+}
+
+/**
+ * Like {@link discoverAll} but also returns integration-template discovery and
+ * replacement-declaration errors. Use this when the caller wants to warn about
+ * malformed integration templates or inactive replacement declarations.
*
* @param {string} [cwd]
- * @returns {Promise<{templates: DiscoveredTemplate[], errors: TemplateDiscoveryError[]}>}
+ * @returns {Promise<{templates: DiscoveredTemplate[], errors: Array<TemplateDiscoveryError | TemplateReplacementError>}>}
*/
export async function discoverAllWithErrors(cwd = process.cwd()) {
- const [pages, blocks, integration] = await Promise.all([
- discoverPages(),
- discoverAllBlocks(cwd),
- discoverIntegrationTemplates(cwd),
- ]);
- const templates = [...pages, ...blocks, ...integration.templates].sort(
- (a, b) => a.name.localeCompare(b.name),
- );
- return {templates, errors: integration.errors};
+ const resolved = await resolveAllSources(cwd);
+ return {
+ templates: effectiveTemplateDiscovery(resolved.templates),
+ errors: resolved.errors,
+ };
}
/**
@@ -807,13 +1122,51 @@ async function discoverIntegrationTemplates(cwd = process.cwd()) {
return {templates, errors};
}
+/**
+ * Report replacement declarations that cannot hold inside one package: two of
+ * its templates replacing the same Core target. Cross-package precedence and
+ * target checks happen in {@link applyTemplateReplacements}.
+ * @param {string} pkg
+ * @param {boolean | undefined} autolinked
+ * @param {DiscoveredTemplate[]} templates
+ * @param {TemplateDiscoveryError[]} errors
+ */
+function reportSamePackageReplacements(pkg, autolinked, templates, errors) {
+ /** @type {Map<string, string[]>} */
+ const idsByTarget = new Map();
+ for (const template of templates) {
+ if (template.replaces == null) continue;
+ const ids = idsByTarget.get(template.replaces) ?? [];
+ ids.push(template.dirName);
+ idsByTarget.set(template.replaces, ids);
+ }
+ for (const [target, ids] of idsByTarget) {
+ if (ids.length < 2) continue;
+ const message =
+ `${pkg} declares ${ids.length} templates as replacements for Core template ` +
+ `"${target}" (${ids.join(', ')}). One package must declare at most one ` +
+ 'replacement for a Core target.';
+ for (const template of ids) {
+ errors.push({
+ code: 'ambiguous_template_replacement',
+ severity: 'error',
+ package: pkg,
+ autolinked,
+ template,
+ replacementTarget: target,
+ message,
+ });
+ }
+ }
+}
+
/**
* Discover the templates contributed by a SINGLE integration. Same per-template
* rules as {@link discoverIntegrationTemplates} (same-stem source required,
* page|block type required); broken templates are recorded in `errors` rather
* than thrown. Exposed for `doctor integration validate` and template authoring checks.
*
- * @param {{name?: string, __spec?: string, templates?: string}} integration
+ * @param {{name?: string, __spec?: string, __autolinked?: boolean, templates?: string}} integration
* @returns {Promise<{templates: DiscoveredTemplate[], errors: TemplateDiscoveryError[]}>}
*/
export async function discoverIntegrationTemplatesForOne(integration) {
@@ -842,6 +1195,20 @@ export async function discoverIntegrationTemplatesForOne(integration) {
template: id,
message: `Template "${id}" is missing its same-stem source file ${path.basename(sourcePath)}.`,
});
+ // A replacement this unusable template declares still counts, so its
+ // target fails closed instead of going to a sibling.
+ const declared = await declaredReplacement(docPath, id);
+ if (declared != null) {
+ errors.push({
+ code: 'invalid_template_replacement',
+ severity: 'error',
+ package: pkgLabel,
+ autolinked: integration.__autolinked,
+ template: id,
+ replacementTarget: declared,
+ message: `Template "${id}" replaces "${declared}", but it cannot be used: it is missing its same-stem source file ${path.basename(sourcePath)}.`,
+ });
+ }
continue;
}
@@ -854,6 +1221,20 @@ export async function discoverIntegrationTemplatesForOne(integration) {
template: id,
message: `Template "${id}" failed to load: ${/** @type {any} */ (err).message}`,
});
+ // A replacement this unusable template declares still counts, so its
+ // target fails closed instead of going to a sibling (spec:AST-035 FR4).
+ const declared = await declaredReplacement(docPath, id);
+ if (declared != null) {
+ errors.push({
+ code: 'invalid_template_replacement',
+ severity: 'error',
+ package: pkgLabel,
+ autolinked: integration.__autolinked,
+ template: id,
+ replacementTarget: declared,
+ message: `Template "${id}" replaces "${declared}", but it cannot be used: its metadata does not load.`,
+ });
+ }
continue;
}
@@ -867,6 +1248,18 @@ export async function discoverIntegrationTemplatesForOne(integration) {
template: id,
message: `Template "${id}" is missing a "type" of "page" or "block". Stamp the default export with type: 'page' or type: 'block'.`,
});
+ const declared = doc?.replaces ?? (await declaredReplacement(docPath, id));
+ if (declared != null) {
+ errors.push({
+ code: 'invalid_template_replacement',
+ severity: 'error',
+ package: pkgLabel,
+ autolinked: integration.__autolinked,
+ template: id,
+ replacementTarget: declared,
+ message: `Template "${id}" replaces "${declared}", but it cannot be used: it has no "type".`,
+ });
+ }
continue;
}
@@ -894,12 +1287,55 @@ export async function discoverIntegrationTemplatesForOne(integration) {
filePath: sourcePath,
docPath,
package: pkgLabel,
+ autolinked: integration.__autolinked,
+ replaces: doc?.replaces,
});
}
+ reportSamePackageReplacements(
+ pkgLabel,
+ integration.__autolinked,
+ templates,
+ errors,
+ );
return {templates, errors};
}
+/**
+ * The replacement a template doc declares, even when the doc does not validate
+ * or load: an unusable template's declaration still counts, so its target
+ * fails closed (spec:AST-035 FR4). Null when it declares none.
+ * @param {string} docPath
+ * @param {string} id
+ * @returns {Promise<string | null>}
+ */
+async function declaredReplacement(docPath, id) {
+ try {
+ const doc = await loadIntegrationDoc(docPath, `Template "${id}"`);
+ return doc?.replaces ?? null;
+ } catch {
+ // The doc does not validate; read what it declares without validating.
+ }
+ try {
+ // The guarded importer: anything the doc writes to stdout as it loads
+ // goes to stderr, so `--json` output stays clean.
+ const raw = (await importDocModule(docPath))?.default;
+ if (raw != null && typeof raw === 'object') {
+ return typeof raw.replaces === 'string' ? raw.replaces : null;
+ }
+ } catch {
+ // The module does not load at all; its text may still name a target.
+ }
+ try {
+ const match = /\breplaces\s*:\s*['"]([^'"\n]+)['"]/u.exec(
+ fs.readFileSync(docPath, 'utf8'),
+ );
+ return match ? match[1] : null;
+ } catch {
+ return null;
+ }
+}
+
/**
* @param {string} componentName
* @param {string} [cwd]
diff --git a/packages/cli/foundation/discovery/template-adapter.test.mjs b/packages/cli/foundation/discovery/template-adapter.test.mjs
index 3ff8f69710..b96343e9d3 100644
--- a/packages/cli/foundation/discovery/template-adapter.test.mjs
+++ b/packages/cli/foundation/discovery/template-adapter.test.mjs
@@ -17,6 +17,7 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {
+ effectiveTemplateDiscovery,
extractComponents,
findPageDocFile,
stripTemplateAssetRefs,
@@ -179,3 +180,44 @@ describe('findPageDocFile', () => {
);
});
});
+
+describe('effectiveTemplateDiscovery', () => {
+ it('shadows only the matching template kind', () => {
+ const pageReplacement = {
+ type: 'page',
+ dirName: 'acme-dashboard',
+ name: 'Acme dashboard',
+ description: '',
+ filePath: '/acme-dashboard.tsx',
+ docPath: '/acme-dashboard.doc.mjs',
+ package: '@acme/widgets',
+ replaces: 'dashboard',
+ };
+ const corePage = {
+ type: 'page',
+ dirName: 'dashboard',
+ name: 'Dashboard page',
+ description: '',
+ filePath: '/dashboard-page.tsx',
+ docPath: '/dashboard-page.doc.mjs',
+ };
+ const coreBlock = {
+ type: 'block',
+ dirName: 'dashboard',
+ name: 'Dashboard block',
+ description: '',
+ filePath: '/dashboard-block.tsx',
+ docPath: '/dashboard-block.doc.mjs',
+ };
+
+ const effective = effectiveTemplateDiscovery([
+ corePage,
+ coreBlock,
+ pageReplacement,
+ ]);
+
+ expect(effective).toContain(pageReplacement);
+ expect(effective).toContain(coreBlock);
+ expect(effective).not.toContain(corePage);
+ });
+});
diff --git a/packages/cli/foundation/doc-compiler/bundle.mjs b/packages/cli/foundation/doc-compiler/bundle.mjs
index eccdfa464c..d1b31a5d35 100644
--- a/packages/cli/foundation/doc-compiler/bundle.mjs
+++ b/packages/cli/foundation/doc-compiler/bundle.mjs
@@ -25,7 +25,7 @@ import {
} from './compile.mjs';
import {diagnostic as rawDiagnostic, sortDiagnostics} from './diagnostics.mjs';
import {collectDocInputs} from './inputs.mjs';
-import {compileDocFile, loadTopicInput} from './read.mjs';
+import {compileDocFile, loadTopicInput, readDocView} from './read.mjs';
import {packageSource, scrubPaths} from './source.mjs';
/**
@@ -127,6 +127,50 @@ export async function compileDocs(project, {lang = null} = {}) {
/** @type {Array<CompiledDocNode | CompiledReferenceNode>} */
const nodes = [];
for (const input of inputs) {
+ // A guide the docs tree places is a reference topic, lowered and linked
+ // like one; a namespace doc lowers like any typed descriptor below.
+ if (
+ input.root === 'tree' &&
+ (await treeDocType(input.file)) === 'generic'
+ ) {
+ const entry = {
+ name: input.name,
+ package: input.owner,
+ path: input.file,
+ extensions: [],
+ tree: true,
+ };
+ const topic = await loadTopicInput(entry, lang);
+ if ('error' in topic.base || 'overlayError' in topic.base) {
+ const failure =
+ 'error' in topic.base ? topic.base.error : topic.base.overlayError;
+ diagnostics.push(
+ diagnostic('error' in topic.base ? 'load_failed' : 'overlay_failed', {
+ provider: input.owner,
+ source: input.source,
+ message: `${topic.base.file}: ${messageOf(failure)}`,
+ }),
+ );
+ continue;
+ }
+ try {
+ const linked = await linkReferenceTopic(
+ lowerReferenceTopic(topic),
+ lowerTarget,
+ );
+ diagnostics.push(...unresolvedReferences(linked, input));
+ nodes.push(linked);
+ } catch (error) {
+ diagnostics.push(
+ diagnostic('invalid_topic', {
+ provider: input.owner,
+ source: input.source,
+ message: messageOf(error),
+ }),
+ );
+ }
+ continue;
+ }
if (input.root === 'docs') {
if (input.role !== 'base') continue;
const lowered = topics.get(input.name.toLowerCase());
@@ -146,6 +190,7 @@ export async function compileDocs(project, {lang = null} = {}) {
input.root === 'components' || input.root === 'hooks' ? lang : null,
check: true,
...(input.root === 'templates' ? {loader: 'template'} : {}),
+ ...(input.root === 'tree' ? {loader: 'native'} : {}),
...(input.root === 'themes'
? {
label: themeDescriptorLabel(input.file, input.owner),
@@ -174,6 +219,21 @@ export async function compileDocs(project, {lang = null} = {}) {
};
}
+/**
+ * The stamped type of a docs-tree file, or null when it cannot be read; the
+ * compile that follows reports why.
+ * @param {string} file
+ * @returns {Promise<string | null>}
+ */
+async function treeDocType(file) {
+ try {
+ const doc = await readDocView(file, {root: 'tree', loader: 'native'});
+ return typeof doc?.type === 'string' ? doc.type : null;
+ } catch {
+ return null;
+ }
+}
+
/**
* A warning for each token reference in a linked topic that finds no topic or
* no section.
diff --git a/packages/cli/foundation/doc-compiler/bundle.test.mjs b/packages/cli/foundation/doc-compiler/bundle.test.mjs
index 075ab268da..489444d678 100644
--- a/packages/cli/foundation/doc-compiler/bundle.test.mjs
+++ b/packages/cli/foundation/doc-compiler/bundle.test.mjs
@@ -144,19 +144,26 @@ describe('compileDocs over a broken integration', () => {
expect(bundle.nodes.some(node => node.id === 'acme-guide')).toBe(true);
});
- it('reports a component doc that fails to load, and compiles the rest', async () => {
+ it('withdraws a component doc that fails to load, reports it, and compiles the rest', async () => {
write(
'components/AcmeCard.doc.mjs',
"throw new Error('boom');\nexport default {};\n",
);
const project = await Project.load(tmpDir);
const bundle = await compileDocs(project);
- const found = bundle.diagnostics.filter(d => d.provider === '@acme/kit');
- // Discovery lists the doc; compiling it fails at load, and only it.
- expect(found.map(d => [d.code, d.source])).toEqual([
- ['load_failed', '@acme/kit/components/AcmeCard.doc.mjs'],
- ]);
- expect(found[0].message).toMatch(/boom/);
+ // Discovery loads each integration component doc and withdraws one that
+ // fails, so the project reports it and the compiler never reads it.
+ const issues = (await project.issues()).filter(
+ issue => issue.package === '@acme/kit',
+ );
+ expect(issues.map(issue => issue.code)).toEqual(['invalid_component']);
+ expect(issues[0].message).toMatch(/boom/);
+ expect(
+ bundle.diagnostics.filter(d => d.provider === '@acme/kit'),
+ ).toEqual([]);
+ expect(
+ bundle.nodes.some(node => node.id === '@acme/kit:components:AcmeCard'),
+ ).toBe(false);
expect(bundle.nodes.some(node => node.kind === 'reference')).toBe(true);
});
@@ -165,9 +172,13 @@ describe('compileDocs over a broken integration', () => {
'components/AcmeCard.doc.mjs',
"export default {type: 'component', displayName: 'No name'};\n",
);
- const bundle = await compileDocs(await Project.load(tmpDir));
- const found = bundle.diagnostics.filter(d => d.provider === '@acme/kit');
- expect(found.map(d => d.code)).toEqual(['invalid_doc']);
+ const project = await Project.load(tmpDir);
+ const bundle = await compileDocs(project);
+ const issues = (await project.issues()).filter(
+ issue => issue.package === '@acme/kit',
+ );
+ expect(issues.map(issue => issue.code)).toEqual(['invalid_component']);
+ expect(issues[0].message).toMatch(/invalid metadata/);
expect(
bundle.nodes.some(node => node.id === '@acme/kit:components:AcmeCard'),
).toBe(false);
diff --git a/packages/cli/foundation/doc-compiler/compile.mjs b/packages/cli/foundation/doc-compiler/compile.mjs
index 91cf473a13..e74f4c6bbc 100644
--- a/packages/cli/foundation/doc-compiler/compile.mjs
+++ b/packages/cli/foundation/doc-compiler/compile.mjs
@@ -63,6 +63,7 @@ export const COMPILED_DOC_KINDS = /** @type {const} */ ([
'command',
'enum',
'theme',
+ 'namespace',
]);
/**
@@ -76,6 +77,7 @@ export const ROOT_KINDS = Object.freeze({
templates: ['page', 'block'],
themes: ['theme'],
'self-docs': ['command', 'function', 'schema', 'enum'],
+ tree: ['namespace', 'generic'],
});
/**
@@ -94,8 +96,14 @@ export const ROOT_KINDS = Object.freeze({
* @property {string} provider the package that owns the topic
* @property {string | null} replaces the topic it took the place of
* @property {string | null} lang the overlay language, or null for authored text
+ * @property {string} [providerId] the owner's provider id; the package name
+ * when absent. The base file's sections resolve their links against it.
* @property {AuthoredFile} base
- * @property {Array<AuthoredFile & {provider: string}>} extensions in merge order
+ * @property {Array<AuthoredFile & {provider: string, providerId?: string}>} extensions
+ * in merge order; each extension's sections resolve their links against its
+ * own provider id
+ * @property {boolean} [tree] a guide the docs tree places: its `placement` is
+ * read by the tree, so the topic reader accepts it
*/
/**
@@ -116,10 +124,33 @@ export const ROOT_KINDS = Object.freeze({
* @property {string | null} lang
* @property {{provider: string, replaces: string | null, extensions: string[]}} provenance
* @property {Record<string, string>} sourceTitles section key -> authored title
+ * @property {Record<string, string>} sectionProviders section key -> the
+ * provider id that wrote the section: a topic merges sections from its base
+ * and its extensions, and each section's links resolve against its own
+ * provider (spec:AST-047 FR9)
* @property {any} doc the topic: authored fields in authored order, every
* section keyed; a linked node's token references carry `resolved`
*/
+/** Which provider wrote a section, until lowering records it by key. */
+const SECTION_PROVIDER = Symbol('astryx.docs.sectionProvider');
+
+/**
+ * Mark each section of one authored file with the provider that wrote it. The
+ * overlay, the merge, and the key stamp copy the mark with the section.
+ * @param {any} doc
+ * @param {string} provider
+ * @returns {any}
+ */
+function markProvider(doc, provider) {
+ return {
+ ...doc,
+ sections: doc.sections.map((/** @type {any} */ section) =>
+ withSourceTitle({...section, [SECTION_PROVIDER]: provider}, sourceTitle(section)),
+ ),
+ };
+}
+
/**
* Lower one topic: overlay each file, merge the extensions in order, and stamp
* every section with its key.
@@ -127,9 +158,18 @@ export const ROOT_KINDS = Object.freeze({
* @returns {CompiledReferenceNode}
*/
export function lowerReferenceTopic(input) {
- let doc = readAuthoredFile(input.base);
+ let doc = markProvider(
+ readAuthoredFile(input.base, {placement: input.tree === true}),
+ input.providerId ?? input.provider,
+ );
for (const extension of input.extensions) {
- doc = mergeTopic(doc, readAuthoredFile(extension));
+ doc = mergeTopic(
+ doc,
+ markProvider(
+ readAuthoredFile(extension),
+ extension.providerId ?? extension.provider,
+ ),
+ );
// Explicit authored IDs remain strict. Legacy title-derived collisions are
// assigned deterministic compatibility keys after every extension merges.
const problems = sectionKeyErrors(doc.sections);
@@ -143,8 +183,12 @@ export function lowerReferenceTopic(input) {
const keyed = withSectionKeys(doc);
/** @type {Record<string, string>} */
const sourceTitles = {};
+ /** @type {Record<string, string>} */
+ const sectionProviders = {};
for (const section of keyed.sections) {
sourceTitles[section.id] = sourceTitle(section);
+ sectionProviders[section.id] =
+ section[SECTION_PROVIDER] ?? input.providerId ?? input.provider;
}
return {
schemaVersion: COMPILED_DOC_SCHEMA_VERSION,
@@ -158,7 +202,9 @@ export function lowerReferenceTopic(input) {
extensions: input.extensions.map(extension => extension.provider),
},
sourceTitles,
- // The authored title travels in sourceTitles; JSON drops the symbol.
+ sectionProviders,
+ // The authored title and provider travel in sourceTitles and
+ // sectionProviders; JSON drops the symbols.
doc: asJson(keyed, input.id),
};
}
@@ -255,13 +301,13 @@ function asJson(value, topic) {
* @param {AuthoredFile} file
* @returns {any}
*/
-function readAuthoredFile(file) {
+function readAuthoredFile(file, {placement = false} = {}) {
if ('error' in file) throw file.error;
const parsed = file.doc;
if (!('sections' in parsed)) {
throw new Error(`${file.file} is not a reference document.`);
}
- const problems = problemsInTopic(parsed);
+ const problems = problemsInTopic(parsed, {placement});
if (problems.length > 0) {
throw new Error(`${file.file} is invalid: ${problems.join('; ')}`);
}
diff --git a/packages/cli/foundation/doc-compiler/diagnostics.mjs b/packages/cli/foundation/doc-compiler/diagnostics.mjs
index c657b8ec16..659988472e 100644
--- a/packages/cli/foundation/doc-compiler/diagnostics.mjs
+++ b/packages/cli/foundation/doc-compiler/diagnostics.mjs
@@ -123,6 +123,34 @@ export const DIAGNOSTIC_CODES = Object.freeze(
remediation:
'Point the token reference at a topic and section that exist; `astryx docs <topic> --index` lists the section keys.',
},
+ invalid_namespace: {
+ phase: 'link',
+ severity: 'error',
+ scope: 'node',
+ remediation:
+ 'Give each namespace a route-safe name (lowercase letters and digits joined by hyphens) that no other namespace in its package uses.',
+ },
+ invalid_placement: {
+ phase: 'link',
+ severity: 'error',
+ scope: 'node',
+ remediation:
+ 'Point placement.parent at a namespace of the same package ("namespace:<name>"), name one of its slots, and use a slot that accepts the doc\'s kind; `astryx docs authoring namespace-doc` lists the fields.',
+ },
+ overlapping_adoption: {
+ phase: 'link',
+ severity: 'error',
+ scope: 'node',
+ remediation:
+ 'Change the adoption rules so exactly one namespace adopts the doc, or give the doc an explicit placement.',
+ },
+ duplicate_route: {
+ phase: 'link',
+ severity: 'error',
+ scope: 'node',
+ remediation:
+ 'Rename or move one of the two docs, so each route in the docs tree belongs to one doc.',
+ },
not_json: {
phase: 'serialize',
severity: 'error',
diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
index 38866a9325..b68a26c0f8 100644
--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
@@ -252,8 +252,8 @@ const RUNNERS = {
sites: ['importDocModule'],
},
'foundation/discovery/template-adapter.mjs': {
- runs: '@babel/parser, to find the fixture references in template source',
- sites: ['require(@babel/parser)'],
+ runs: '@babel/parser, to find the fixture references in template source; and a template doc that does not validate, to read the replacement it declares',
+ sites: ['importDocModule', 'require(@babel/parser)'],
},
'foundation/discovery/theme-discovery.mjs': {
runs: '@babel/parser and jscodeshift (CommonJS), each on first use, so listing bundled themes never loads jscodeshift',
diff --git a/packages/cli/foundation/doc-compiler/inputs.mjs b/packages/cli/foundation/doc-compiler/inputs.mjs
index 73210338d6..f41d7beb2e 100644
--- a/packages/cli/foundation/doc-compiler/inputs.mjs
+++ b/packages/cli/foundation/doc-compiler/inputs.mjs
@@ -24,6 +24,7 @@ import {
import {discoverHooks, findHookDoc} from '../discovery/hook-discovery.mjs';
import {CLI_ROOT, findCoreDir} from '../fs/paths.mjs';
import {packageSource} from './source.mjs';
+import {treeDocFiles} from './tree.mjs';
export {packageSource};
@@ -42,7 +43,7 @@ const NON_DESCRIPTOR_DIRS = new Set([
]);
/**
- * @typedef {'components' | 'hooks' | 'templates' | 'themes' | 'docs' | 'self-docs'} DocRoot
+ * @typedef {'components' | 'hooks' | 'templates' | 'themes' | 'docs' | 'self-docs' | 'tree'} DocRoot
*/
/**
@@ -125,6 +126,10 @@ export async function collectDocInputs(project) {
}
}
+ // The docs tree's own files: its namespaces and the guides it places.
+ for (const file of treeDocFiles()) {
+ list.add('tree', path.basename(file, '.doc.mjs'), CLI_PACKAGE, file);
+ }
for (const file of selfDocFiles()) {
const name = path
.relative(CLI_ROOT, file)
diff --git a/packages/cli/foundation/doc-compiler/ir.mjs b/packages/cli/foundation/doc-compiler/ir.mjs
index d9cb4d94d1..bfcd1a5975 100644
--- a/packages/cli/foundation/doc-compiler/ir.mjs
+++ b/packages/cli/foundation/doc-compiler/ir.mjs
@@ -27,6 +27,7 @@ const NODE_FIELDS = new Set([
'lang',
'provenance',
'sourceTitles',
+ 'sectionProviders',
'doc',
]);
const RESOLVED_FIELDS = new Set([
@@ -170,6 +171,12 @@ function structureProblems(node) {
'provenance: expected {provider, replaces, extensions} naming packages, not paths',
);
}
+ const providers = isRecord(node.sectionProviders)
+ ? node.sectionProviders
+ : null;
+ if (!providers || !Object.values(providers).every(isText)) {
+ problems.push('sectionProviders: expected section key -> provider id');
+ }
const titles = isRecord(node.sourceTitles) ? node.sourceTitles : null;
if (!titles || !Object.values(titles).every(isText)) {
problems.push('sourceTitles: expected section key -> authored title');
diff --git a/packages/cli/foundation/doc-compiler/lenses.mjs b/packages/cli/foundation/doc-compiler/lenses.mjs
index ced72373f5..32d9b5d949 100644
--- a/packages/cli/foundation/doc-compiler/lenses.mjs
+++ b/packages/cli/foundation/doc-compiler/lenses.mjs
@@ -62,8 +62,9 @@ export function detailView(node) {
/**
* `docs.index`: what the topic is, and each section's key, title and summary.
+ * The index leaf adds the moves.
* @param {import('./compile.mjs').CompiledReferenceNode} node
- * @returns {import('../../api/docs/docs.type.mjs').DocsIndex}
+ * @returns {Omit<import('../../api/docs/docs.type.mjs').DocsIndex, 'links'>}
*/
export function indexView(node) {
return buildDocsIndexData(node.doc);
diff --git a/packages/cli/foundation/doc-compiler/links.mjs b/packages/cli/foundation/doc-compiler/links.mjs
new file mode 100644
index 0000000000..13e2d3a436
--- /dev/null
+++ b/packages/cli/foundation/doc-compiler/links.mjs
@@ -0,0 +1,253 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Links between docs, named by doc identity (spec:AST-047 FR9).
+ *
+ * @input A link target, `[<provider>:]<kind>:<name>`, written as a `reference`
+ * block, in a `workflow` step's `references`, or inline in text as
+ * `{@link <target>}`; and a resolver that finds the doc a target names.
+ * @output The same content with every link resolved: an inline link becomes
+ * the `astryx docs` command that opens its doc, and a block carries a `link`
+ * with the doc's identity, route, title, summary, and command. A link that
+ * names no doc is a problem, never a guess.
+ * @position Pure. The docs adapter owns the resolver (the project's docs tree
+ * and topic catalog) and applies this to every read and every doctor check.
+ */
+
+/** The kinds a link can name: every authored doc kind. */
+export const LINK_KINDS = new Set([
+ 'generic',
+ 'command',
+ 'function',
+ 'schema',
+ 'enum',
+ 'namespace',
+ 'component',
+ 'page',
+ 'block',
+]);
+
+/** An inline link in text: `{@link <target>}`. */
+export const INLINE_LINK = /\{@link\s+([^{}]+?)\s*\}/g;
+
+/** Code spans in text, which show link syntax as written. */
+const CODE_SPAN = /(`[^`]*`)/;
+
+/**
+ * @typedef {object} LinkTarget
+ * @property {string | null} provider the provider id it names, or null for the
+ * linking doc's own provider
+ * @property {string} kind
+ * @property {string} name
+ */
+
+/**
+ * The doc a link opens, as a docs read returns it.
+ * @typedef {object} DocLink
+ * @property {string} target the target as written: `[<provider>:]<kind>:<name>`
+ * @property {string} id the doc's identity (a DocId)
+ * @property {string} route what `astryx docs <route>` opens
+ * @property {string} title
+ * @property {string} summary
+ * @property {string} command the command that opens it, `astryx docs <route>`
+ */
+
+/**
+ * Finds the doc a target names, or says why none matches.
+ * @typedef {(target: string) => Promise<DocLink | {problem: string}>} LinkResolver
+ */
+
+/**
+ * @typedef {object} LinkProblem
+ * @property {string} target the target as written
+ * @property {string} message
+ * @property {string} [section] the key of the section the link sits in
+ */
+
+/**
+ * Parse `[<provider>:]<kind>:<name>`. A name may hold spaces
+ * (`command:theme build`); no part holds a colon.
+ * @param {unknown} target
+ * @returns {LinkTarget | {error: string}}
+ */
+export function parseLinkTarget(target) {
+ if (typeof target !== 'string' || target.trim() === '') {
+ return {
+ error:
+ 'a link target is a non-empty string: `[<provider>:]<kind>:<name>`',
+ };
+ }
+ const parts = target.trim().split(':');
+ 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;
+ const kind = parts[parts.length - 2].trim();
+ const name = parts[parts.length - 1].trim();
+ if (!LINK_KINDS.has(kind)) {
+ return {
+ error: `"${target}" names the kind "${kind}"; a doc kind is one of ${[
+ ...LINK_KINDS,
+ ].join(', ')}`,
+ };
+ }
+ return {provider, kind, name};
+}
+
+/**
+ * Text with each inline link replaced by its name, for indexes that must not
+ * read the link syntax as words.
+ * @param {string} text
+ * @returns {string}
+ */
+export function unlinkText(text) {
+ return text
+ .split(CODE_SPAN)
+ .map(part =>
+ part.startsWith('`')
+ ? part
+ : part.replace(INLINE_LINK, (_, target) => {
+ const parsed = parseLinkTarget(target);
+ return 'error' in parsed ? target : parsed.name;
+ }),
+ )
+ .join('');
+}
+
+/**
+ * Resolve every link in a list of content blocks, in order.
+ * @param {any[]} blocks
+ * @param {LinkResolver} resolve
+ * @param {{section?: string}} [at]
+ * @returns {Promise<{content: any[], problems: LinkProblem[]}>}
+ */
+export async function linkBlocks(blocks, resolve, at = {}) {
+ /** @type {LinkProblem[]} */
+ const problems = [];
+ const where = at.section ? {section: at.section} : {};
+ /**
+ * @param {string} target
+ * @returns {Promise<DocLink | null>}
+ */
+ const find = async target => {
+ const found = await resolve(target);
+ if ('problem' in found) {
+ problems.push({target, message: found.problem, ...where});
+ return null;
+ }
+ return found;
+ };
+ /**
+ * @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;
+ };
+ /**
+ * @param {unknown[]} values
+ * @returns {Promise<any[]>}
+ */
+ const linkAll = async values => {
+ const out = [];
+ for (const value of values) out.push(await linkText(value));
+ return out;
+ };
+
+ const content = [];
+ for (const block of blocks ?? []) {
+ switch (block?.type) {
+ case 'prose':
+ case 'heading':
+ content.push({...block, text: await linkText(block.text)});
+ break;
+ case 'list':
+ content.push({...block, items: await linkAll(block.items ?? [])});
+ break;
+ case 'table': {
+ const rows = [];
+ for (const row of block.rows ?? []) rows.push(await linkAll(row));
+ content.push({
+ ...block,
+ headers: await linkAll(block.headers ?? []),
+ rows,
+ });
+ break;
+ }
+ case 'reference':
+ content.push({...block, link: await find(block.target)});
+ break;
+ case 'workflow': {
+ const steps = [];
+ for (const step of block.steps ?? []) {
+ /** @type {any} */
+ const linked = {...step};
+ if (step.description != null) {
+ linked.description = await linkText(step.description);
+ }
+ if (Array.isArray(step.references)) {
+ const links = [];
+ for (const target of step.references) links.push(await find(target));
+ linked.links = links;
+ }
+ steps.push(linked);
+ }
+ content.push({...block, steps});
+ break;
+ }
+ case 'collection':
+ problems.push({
+ target: `collection:${block.source?.slot ?? ''}`,
+ message:
+ 'a collection block is not rendered yet; link each doc with a reference block instead',
+ ...where,
+ });
+ content.push(block);
+ break;
+ default:
+ content.push(block);
+ }
+ }
+ return {content, problems};
+}
+
+/**
+ * Resolve every link in a topic's sections.
+ * @param {any[]} sections
+ * @param {LinkResolver} resolve
+ * @returns {Promise<{sections: any[], problems: LinkProblem[]}>}
+ */
+export async function linkSections(sections, resolve) {
+ /** @type {LinkProblem[]} */
+ const problems = [];
+ const out = [];
+ for (const section of sections ?? []) {
+ const linked = await linkBlocks(section.content, resolve, {
+ section: section.id ?? section.title,
+ });
+ problems.push(...linked.problems);
+ out.push({...section, content: linked.content});
+ }
+ return {sections: out, problems};
+}
diff --git a/packages/cli/foundation/doc-compiler/links.test.mjs b/packages/cli/foundation/doc-compiler/links.test.mjs
new file mode 100644
index 0000000000..0463de3f6f
--- /dev/null
+++ b/packages/cli/foundation/doc-compiler/links.test.mjs
@@ -0,0 +1,139 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Links between docs (spec:AST-047 FR9): the target grammar, and how a
+ * list of blocks comes back with every link resolved or named as a problem.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {
+ linkBlocks,
+ linkSections,
+ parseLinkTarget,
+ unlinkText,
+} from './links.mjs';
+
+/** A resolver over two docs, the second from another provider. */
+const resolve = async (/** @type {string} */ target) => {
+ const docs = {
+ 'command:doctor': {route: 'cli/commands/doctor', title: 'astryx doctor'},
+ '@acme/kit:generic:setup': {route: 'acme/setup', title: 'Set up Acme'},
+ };
+ const doc = /** @type {any} */ (docs)[target];
+ return doc
+ ? {
+ target,
+ id: `id:${target}`,
+ route: doc.route,
+ title: doc.title,
+ summary: `About ${doc.title}.`,
+ command: `astryx docs ${doc.route}`,
+ }
+ : {problem: `"${target}" names no doc`};
+};
+
+describe('parseLinkTarget', () => {
+ it('reads a doc of the same provider, or of a named one', () => {
+ expect(parseLinkTarget('command:theme build')).toEqual({
+ provider: null,
+ kind: 'command',
+ name: 'theme build',
+ });
+ expect(parseLinkTarget('@astryxdesign/cli:function:search')).toEqual({
+ provider: '@astryxdesign/cli',
+ kind: 'function',
+ name: 'search',
+ });
+ });
+
+ it('refuses a target that is not `[<provider>:]<kind>:<name>`', () => {
+ for (const bad of ['', 'search', 'a:b:c:d', 'command:', 'widget:x']) {
+ expect(parseLinkTarget(bad)).toHaveProperty('error');
+ }
+ });
+});
+
+describe('linkBlocks', () => {
+ it('reads an inline link as the command that opens its doc', async () => {
+ 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: '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[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.
+ expect(content[3].code).toBe('{@link command:doctor}');
+ });
+
+ 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.'}],
+ resolve,
+ );
+ expect(problems).toEqual([]);
+ expect(content[0].text).toBe(
+ 'Write `{@link <target>}` to link; `astryx docs cli/commands/doctor` checks it.',
+ );
+ });
+
+ it('gives a reference block and each workflow step the doc they name', async () => {
+ const {content, problems} = await linkBlocks(
+ [
+ {type: 'reference', target: 'command:doctor'},
+ {
+ type: 'workflow',
+ steps: [{title: 'Check', references: ['command:doctor']}],
+ },
+ ],
+ resolve,
+ );
+ expect(problems).toEqual([]);
+ expect(content[0].link).toMatchObject({
+ route: 'cli/commands/doctor',
+ command: 'astryx docs cli/commands/doctor',
+ title: 'astryx doctor',
+ });
+ expect(content[1].steps[0].links[0].command).toBe(
+ 'astryx docs cli/commands/doctor',
+ );
+ });
+
+ it('names every link that finds no doc, and never guesses', async () => {
+ const {content, problems} = await linkSections(
+ [
+ {
+ id: 'one',
+ title: 'One',
+ content: [
+ {type: 'prose', text: 'See {@link command:nope}.'},
+ {type: 'reference', target: 'generic:gone'},
+ {type: 'collection', source: {slot: 'guides'}},
+ ],
+ },
+ ],
+ resolve,
+ ).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([
+ ['one', 'command:nope'],
+ ['one', 'generic:gone'],
+ ['one', 'collection:guides'],
+ ]);
+ });
+});
+
+describe('unlinkText', () => {
+ it('keeps the name of each link, for an index', () => {
+ expect(unlinkText('Run {@link command:theme build} or {@link x}.')).toBe(
+ 'Run theme build or x.',
+ );
+ });
+});
diff --git a/packages/cli/foundation/doc-compiler/lower-doc.test.mjs b/packages/cli/foundation/doc-compiler/lower-doc.test.mjs
index c4fe880b0c..5e3e25529d 100644
--- a/packages/cli/foundation/doc-compiler/lower-doc.test.mjs
+++ b/packages/cli/foundation/doc-compiler/lower-doc.test.mjs
@@ -386,7 +386,10 @@ describe('parseCompiledDocNode and parseCompiledDocsBundle', () => {
it('accepts a node of every kind and a bundle, as given', () => {
const value = bundle();
expect(parseCompiledDocsBundle(value)).toBe(value);
- expect(COMPILED_DOC_KINDS).toHaveLength(9);
+ expect(COMPILED_DOC_KINDS).toHaveLength(10);
+ // A namespace doc, which the docs tree reads, lowers to a node too.
+ const namespace = {...node(), kind: 'namespace'};
+ expect(parseCompiledDocNode(namespace)).toBe(namespace);
});
it('names schema skew with its own diagnostic, before anything else', () => {
@@ -413,7 +416,7 @@ describe('parseCompiledDocNode and parseCompiledDocsBundle', () => {
],
[
'an unknown kind',
- (/** @type {any} */ n) => (n.kind = 'namespace'),
+ (/** @type {any} */ n) => (n.kind = 'workflow'),
/not a compiled doc kind/,
],
[
diff --git a/packages/cli/foundation/doc-compiler/read.mjs b/packages/cli/foundation/doc-compiler/read.mjs
index a5d25655ce..9ce6065d88 100644
--- a/packages/cli/foundation/doc-compiler/read.mjs
+++ b/packages/cli/foundation/doc-compiler/read.mjs
@@ -45,6 +45,8 @@ export const DOC_EXPORTS = Object.freeze({
hooks: ['default', 'docs'],
templates: ['default', 'doc'],
'self-docs': ['doc', 'docs', 'default'],
+ // The docs tree's own files: namespace docs and the guides it places.
+ tree: ['docs', 'default'],
});
/** How a reader imports a doc module. */
@@ -59,7 +61,7 @@ const LOADERS = Object.freeze({
/**
* @typedef {object} ReadOptions
- * @property {'components' | 'hooks' | 'templates' | 'themes' | 'self-docs'} root
+ * @property {'components' | 'hooks' | 'templates' | 'themes' | 'self-docs' | 'tree'} root
* @property {string | null} [lang] overlay language; null reads the authored
* text
* @property {string} [label] how a parse error names the file (default: its
@@ -307,14 +309,17 @@ export async function loadTopicInput(entry, lang) {
extensions.push({
...(await loadTopicFile(extension.path, lang)),
provider: extension.package,
+ providerId: extension.providerId ?? extension.package,
});
}
return {
id: entry.name,
provider: entry.package,
+ providerId: entry.providerId ?? entry.package,
replaces: entry.replaces ?? null,
lang,
base: await loadTopicFile(entry.path, lang),
extensions,
+ ...(entry.tree === true ? {tree: true} : {}),
};
}
diff --git a/packages/cli/foundation/doc-compiler/tree.mjs b/packages/cli/foundation/doc-compiler/tree.mjs
new file mode 100644
index 0000000000..72fdfbd339
--- /dev/null
+++ b/packages/cli/foundation/doc-compiler/tree.mjs
@@ -0,0 +1,876 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The docs tree: one home for every doc that a namespace places or
+ * adopts (spec:AST-046).
+ *
+ * @input Namespace docs, guides that name a parent with `placement`, and typed
+ * docs that belong to a discovery group (a CLI typed doc's `namespace`).
+ * @output {@link buildDocsTree}: every node by route, each with one parent and
+ * ordered children per slot, plus one diagnostic for each placement that
+ * failed. {@link loadDocsTree} builds the CLI's own tree once per process.
+ * @position Between discovery and the readers: `astryx docs <route>`,
+ * `astryx doctor`, and the docsite build all read this tree. The CLI's docs
+ * and each integration's have a home here, and a flat topic's home is the
+ * generated Unorganized level.
+ * A namespace never scans files and never lists its children: a child names
+ * its parent, or a namespace adopts a discovery group.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {CLI_ROOT} from '../fs/paths.mjs';
+import {loadCliSelfDocs} from '../discovery/cli-self-docs.mjs';
+import {routeSegment} from '../discovery/docs-section-key.mjs';
+import {diagnostic, sortDiagnostics} from './diagnostics.mjs';
+import {readDocView} from './read.mjs';
+import {packageSource} from './source.mjs';
+import {createDocId} from '../identity/provider-identity.mjs';
+import {CLI_PROVIDER_ID} from '../identity/providers.mjs';
+
+export {routeSegment};
+
+/** Where the CLI keeps the docs that only the tree reads. */
+export const TREE_DOCS_DIR = path.join(CLI_ROOT, 'assets', 'docs', 'tree');
+
+/** The package that owns the CLI's own docs. */
+const CLI_PROVIDER = '@astryxdesign/cli';
+
+/** One route segment: lowercase letters and digits joined by single hyphens. */
+export const ROUTE_SEGMENT_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+
+/**
+ * The generated level that `groupBy: 'kind'` makes for each kind: its route
+ * segment, title, and summary.
+ * @type {Readonly<Record<string, {segment: string, title: string, summary: string}>>}
+ */
+export const KIND_GROUPS = Object.freeze({
+ command: {
+ segment: 'commands',
+ title: 'Commands',
+ summary: 'Every command and subcommand.',
+ },
+ function: {
+ segment: 'functions',
+ title: 'Functions',
+ summary: 'Every function: its signature, parameters, returns, and errors.',
+ },
+ schema: {
+ segment: 'schemas',
+ title: 'Schemas',
+ summary: 'Every shape the CLI reads or returns, field by field.',
+ },
+ enum: {
+ segment: 'enums',
+ title: 'Enums',
+ summary:
+ 'Every fixed list of values, such as error codes and response types.',
+ },
+ generic: {segment: 'guides', title: 'Guides', summary: 'Every guide.'},
+});
+
+/**
+ * @typedef {import('../../authoring/doctypes/namespace/type').NamespaceDoc} NamespaceDoc
+ * @typedef {import('../../authoring/doctypes/base/type').DocPlacement} DocPlacement
+ * @typedef {import('./diagnostics.mjs').CompilerDiagnostic} CompilerDiagnostic
+ */
+
+/**
+ * @typedef {object} TreeNamespaceInput
+ * @property {string} provider the package that owns the namespace
+ * @property {string} providerId the provider's ProviderId (its manifest
+ * `providerId`, else its package name); node ids are built from it
+ * @property {number} [rank] which provider wins a contested route: the CLI's
+ * own docs are 0, then each integration in configured order
+ * @property {string} source `<package>/<path>` of its file
+ * @property {NamespaceDoc} doc
+ */
+
+/**
+ * @typedef {object} TreeDocInput
+ * @property {string} provider the package that authored the doc
+ * @property {string} providerId the provider's ProviderId (its manifest
+ * `providerId`, else its package name); node ids are built from it
+ * @property {number} [rank] which provider wins a contested route: the CLI's
+ * own docs are 0, then each integration in configured order
+ * @property {string} source
+ * @property {import('../../authoring/doctypes/base/type').AuthoredDocKind} kind
+ * the authored kind: `generic`, `command`, `function`, `schema`, or `enum`
+ * @property {string} name the doc's stable name
+ * @property {string} title
+ * @property {string} summary
+ * @property {string | null} group the discovery group adoption reads, or null
+ * @property {DocPlacement | undefined} placement
+ * @property {any} [ref] what a reader needs to open the doc, carried as given
+ */
+
+/**
+ * @typedef {object} TreeSlot
+ * @property {string} name
+ * @property {string} title
+ * @property {string[]} children child routes, in reading order
+ */
+
+/**
+ * A flat topic: a reference topic that no namespace places. The tree gives it
+ * a home in the generated Unorganized level, under its own name.
+ * @typedef {object} TreeTopicInput
+ * @property {string} provider the package that owns the topic
+ * @property {string} providerId the provider's ProviderId
+ * @property {string} name the topic's name, which stays its route
+ * @property {string} title
+ * @property {string} summary
+ * @property {string} source where the topic comes from, for diagnostics
+ * @property {string[]} [aliases] every other name the topic answers to: the
+ * topics it replaced, directly or through a chain
+ */
+
+/** The route of the generated level that holds every flat topic. */
+export const UNORGANIZED = 'unorganized';
+
+/**
+ * @typedef {object} TreeNode
+ * @property {string | null} id the doc's DocId, built from its provider's
+ * ProviderId, kind, and name: stable when the route moves; null on a
+ * generated level, which has no authored doc
+ * @property {string} route
+ * @property {string} kind `namespace` or the doc's authored kind
+ * @property {string} provider the package that owns it
+ * @property {string} providerId its provider's ProviderId
+ * @property {string} name
+ * @property {string} title
+ * @property {string} summary
+ * @property {string | null} parent the parent's route; null at the top
+ * @property {string | null} slot the parent slot this node sits in
+ * @property {number | null} order
+ * @property {boolean} generated made by the compiler (a `groupBy: 'kind'`
+ * level, or the Unorganized level), not authored
+ * @property {TreeSlot[]} slots a namespace's slots; empty for a leaf
+ * @property {string} source
+ * @property {any} [ref]
+ */
+
+/**
+ * @typedef {object} DocsTree
+ * @property {Map<string, TreeNode>} nodes by route, in route order
+ * @property {CompilerDiagnostic[]} diagnostics sorted
+ * @property {(route: string) => TreeNode | undefined} get
+ * @property {(route: string) => TreeNode | undefined} getFolded the node at a
+ * route compared without case, as topic names are
+ * @property {() => TreeNode[]} roots the namespaces with no parent
+ * @property {(node: TreeNode) => TreeNode[]} ancestors top first, not the node
+ */
+
+/** @param {string} a @param {string} b */
+const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
+
+/**
+ * The namespace a `placement.parent` names: `namespace:<name>` in the doc's own
+ * package, or `<package>/namespace/<name>` spelled out. In phase 1 a parent
+ * must belong to the doc's own package.
+ * @param {string} parent
+ * @param {string} provider
+ * @param {Map<string, TreeNamespaceInput>} declared by `provider\0name`
+ * @returns {{key: string} | {error: string}}
+ */
+function resolveParent(parent, provider, declared) {
+ let owner = provider;
+ let name;
+ const short = /^namespace:(.+)$/u.exec(parent);
+ const qualified = /^(.+)\/namespace\/([^/]+)$/u.exec(parent);
+ if (short) {
+ name = short[1];
+ } else if (qualified) {
+ [, owner, name] = qualified;
+ } else {
+ return {
+ error: `placement.parent "${parent}" is not a namespace reference. Write "namespace:<name>".`,
+ };
+ }
+ if (owner !== provider) {
+ return {
+ error: `placement.parent "${parent}" belongs to ${owner}. A doc can only be placed in a namespace of its own package (${provider}).`,
+ };
+ }
+ const key = `${owner}\u0000${name}`;
+ if (!declared.has(key)) {
+ return {
+ error: `placement.parent "${parent}" names no namespace; ${provider} declares ${
+ [...declared.values()]
+ .filter(ns => ns.provider === provider)
+ .map(ns => `"${ns.doc.name}"`)
+ .sort(byText)
+ .join(', ') || 'none'
+ }.`,
+ };
+ }
+ return {key};
+}
+
+/**
+ * Build the tree. Pure: the same inputs give the same tree, whatever order
+ * they arrive in.
+ *
+ * A doc's home is decided once, in this order: its explicit `placement`, then
+ * the one adoption rule in its package that matches its group and kind. A
+ * placement that fails withdraws the doc; it never falls back to adoption. A
+ * doc with neither is a flat topic: it keeps its flat name as its route, and its
+ * home is the generated Unorganized level. The CLI keeps its own routes: an
+ * integration's node that would take one is withdrawn with a diagnostic.
+ *
+ * @param {{namespaces: TreeNamespaceInput[], docs: TreeDocInput[], topics?: TreeTopicInput[]}} inputs
+ * @returns {DocsTree}
+ */
+export function buildDocsTree({namespaces, docs, topics = []}) {
+ /** @type {CompilerDiagnostic[]} */
+ const diagnostics = [];
+ /** @param {string} code @param {{provider: string, source: string}} at @param {string} message @param {string} [field] */
+ const report = (code, at, message, field) =>
+ diagnostics.push(
+ diagnostic(code, {
+ provider: at.provider,
+ source: at.source,
+ message,
+ ...(field ? {field} : {}),
+ }),
+ );
+
+ // Routes the CLI's own docs keep (spec:AST-046 FR11): the name of each of
+ // its flat topics, and the generated Unorganized level. Its namespaces keep
+ // theirs by rank, because they go into the tree first. Routes compare
+ // without case, as topic names do, so `CLI` claims `cli`.
+ const cliRoutes = new Set(topics.length > 0 ? [UNORGANIZED] : []);
+ for (const topic of topics) {
+ if (topic.provider === CLI_PROVIDER) cliRoutes.add(topic.name.toLowerCase());
+ }
+ // Every other name a topic answers to (the topics it replaced, directly or
+ // through a chain) is that topic's route too: `astryx docs <name>` opens the
+ // replacement, so no other doc can hold it.
+ /** @type {Map<string, TreeTopicInput>} */
+ const aliasRoutes = new Map();
+ for (const topic of topics) {
+ for (const alias of topic.aliases ?? []) {
+ aliasRoutes.set(alias.toLowerCase(), topic);
+ }
+ }
+
+ // Namespaces by package and name.
+ /** @type {Map<string, TreeNamespaceInput>} */
+ const declared = new Map();
+ const sortedNamespaces = [...namespaces].sort(
+ (a, b) =>
+ (a.rank ?? 0) - (b.rank ?? 0) ||
+ byText(a.provider, b.provider) ||
+ byText(a.doc.name, b.doc.name) ||
+ byText(a.source, b.source),
+ );
+ for (const input of sortedNamespaces) {
+ const {name} = input.doc;
+ if (!ROUTE_SEGMENT_RE.test(name)) {
+ report(
+ 'invalid_namespace',
+ input,
+ `Namespace "${name}" is not a route segment. Use lowercase letters and digits joined by single hyphens.`,
+ 'name',
+ );
+ continue;
+ }
+ const key = `${input.provider}\u0000${name}`;
+ const first = declared.get(key);
+ if (first) {
+ report(
+ 'invalid_namespace',
+ input,
+ `Namespace "${name}" is declared twice in ${input.provider}: ${first.source} and ${input.source}.`,
+ 'name',
+ );
+ continue;
+ }
+ declared.set(key, input);
+ }
+
+ // Each namespace's parent, checked against the parent's slots.
+ /** @type {Map<string, {parentKey: string, slot: string, order: number | null} | null>} */
+ const parentOf = new Map();
+ for (const [key, input] of declared) {
+ const {placement} = input.doc;
+ if (placement == null) {
+ parentOf.set(key, null);
+ continue;
+ }
+ const home = checkPlacement(placement, 'namespace', input, declared);
+ if ('error' in home) {
+ report('invalid_placement', input, home.error, 'placement');
+ continue;
+ }
+ parentOf.set(key, {
+ parentKey: home.key,
+ slot: home.slot,
+ order: placement.order ?? null,
+ });
+ }
+
+ // Routes, top-down. A cycle, or an ancestor that was withdrawn, leaves a
+ // namespace (and everything under it) out of the tree.
+ /** @type {Map<string, string | null>} */
+ const routeOf = new Map();
+ /** @param {string} key @param {Set<string>} seen @returns {string | null} */
+ const routeFor = (key, seen) => {
+ if (routeOf.has(key))
+ return /** @type {string | null} */ (routeOf.get(key));
+ if (!parentOf.has(key) || seen.has(key)) return null;
+ seen.add(key);
+ const home = parentOf.get(key);
+ const name = /** @type {TreeNamespaceInput} */ (declared.get(key)).doc.name;
+ const parentRoute = home == null ? '' : routeFor(home.parentKey, seen);
+ const route =
+ parentRoute == null
+ ? null
+ : parentRoute === ''
+ ? name
+ : `${parentRoute}/${name}`;
+ routeOf.set(key, route);
+ return route;
+ };
+ for (const [key, input] of declared) {
+ if (routeFor(key, new Set()) == null && parentOf.has(key)) {
+ report(
+ 'invalid_placement',
+ input,
+ `Namespace "${input.doc.name}" has no route: its placement forms a cycle, or a namespace above it was withdrawn.`,
+ 'placement',
+ );
+ }
+ }
+
+ /** @type {Map<string, TreeNode>} */
+ const nodes = new Map();
+ /** @type {Map<string, TreeNode>} nodes by route, compared without case */
+ const byFoldedRoute = new Map();
+ /** @param {TreeNode} node */
+ const nodeLabel = node => node.id ?? `the generated level "${node.route}"`;
+ /** @param {TreeNode} node @param {{provider: string, source: string}} at */
+ const addNode = (node, at) => {
+ const folded = node.route.toLowerCase();
+ if (node.provider !== CLI_PROVIDER && cliRoutes.has(folded)) {
+ report(
+ 'duplicate_route',
+ at,
+ `${nodeLabel(node)} takes the route "${node.route}", which the CLI's own docs keep. Rename it.`,
+ );
+ return false;
+ }
+ const alias = aliasRoutes.get(folded);
+ if (
+ alias != null &&
+ node.provider !== CLI_PROVIDER &&
+ node.ref?.flatTopic !== alias.name
+ ) {
+ report(
+ 'duplicate_route',
+ at,
+ `${nodeLabel(node)} takes the route "${node.route}", which the topic "${alias.name}" also answers to, because it replaced a topic of that name. Rename it.`,
+ );
+ return false;
+ }
+ const taken = byFoldedRoute.get(folded);
+ if (taken) {
+ report(
+ 'duplicate_route',
+ at,
+ `${nodeLabel(node)} and ${nodeLabel(taken)} both have the route "${node.route}". Rename or move one of them.`,
+ );
+ return false;
+ }
+ nodes.set(node.route, node);
+ byFoldedRoute.set(folded, node);
+ return true;
+ };
+
+ // Parents before children, so a namespace placed in a withdrawn namespace
+ // is withdrawn before anything is placed in it.
+ const parentsFirst = [...declared].sort(
+ ([a], [b]) =>
+ String(routeOf.get(a) ?? '').split('/').length -
+ String(routeOf.get(b) ?? '').split('/').length,
+ );
+ for (const [key, input] of parentsFirst) {
+ const route = routeOf.get(key);
+ if (route == null) continue;
+ const home = parentOf.get(key);
+ if (home != null && routeOf.get(home.parentKey) == null) {
+ routeOf.set(key, null);
+ report(
+ 'invalid_placement',
+ input,
+ `Namespace "${input.doc.name}" has no route: the namespace it is placed in was withdrawn.`,
+ 'placement',
+ );
+ continue;
+ }
+ const parentRoute =
+ home == null ? null : /** @type {string} */ (routeOf.get(home.parentKey));
+ const added = addNode(
+ {
+ id: createDocId(input.providerId, 'namespace', input.doc.name),
+ route,
+ kind: 'namespace',
+ provider: input.provider,
+ providerId: input.providerId,
+ name: input.doc.name,
+ title: input.doc.title,
+ summary: input.doc.summary,
+ parent: parentRoute,
+ slot: home?.slot ?? null,
+ order: home?.order ?? null,
+ generated: false,
+ slots: Object.entries(input.doc.slots).map(([name, slot]) => ({
+ name,
+ title: slot.title,
+ children: [],
+ })),
+ source: input.source,
+ },
+ input,
+ );
+ // A withdrawn namespace has no route, so a namespace placed in it is
+ // withdrawn too, and a doc placed in it says so.
+ if (!added) routeOf.set(key, null);
+ }
+
+ // Docs: explicit placement, else one adoption rule, else no home.
+ const sortedDocs = [...docs].sort(
+ (a, b) =>
+ (a.rank ?? 0) - (b.rank ?? 0) ||
+ byText(a.provider, b.provider) ||
+ byText(a.kind, b.kind) ||
+ byText(a.name, b.name) ||
+ byText(a.source, b.source),
+ );
+ for (const doc of sortedDocs) {
+ /** @type {{parentRoute: string, slot: string, order: number | null} | null} */
+ let home = null;
+ if (doc.placement != null) {
+ const placed = checkPlacement(doc.placement, doc.kind, doc, declared);
+ if ('error' in placed) {
+ report('invalid_placement', doc, placed.error, 'placement');
+ continue;
+ }
+ const parentRoute = routeOf.get(placed.key);
+ if (parentRoute == null) {
+ report(
+ 'invalid_placement',
+ doc,
+ `placement.parent "${doc.placement.parent}" names a namespace that has no route.`,
+ 'placement',
+ );
+ continue;
+ }
+ home = {
+ parentRoute,
+ slot: placed.slot,
+ order: doc.placement.order ?? null,
+ };
+ } else if (doc.group != null) {
+ const matches = adoptionsFor(doc, declared, routeOf);
+ if (matches.length > 1) {
+ report(
+ 'overlapping_adoption',
+ doc,
+ `${doc.provider}/${doc.kind}/${doc.name} is adopted by ${matches
+ .map(m => `"${m.namespace.doc.name}"`)
+ .join(' and ')}; exactly one namespace may adopt a doc.`,
+ );
+ continue;
+ }
+ if (matches.length === 1) {
+ const [{key, rule, namespace}] = matches;
+ const nsRoute = /** @type {string} */ (routeOf.get(key));
+ if (rule.groupBy === 'kind') {
+ const group = KIND_GROUPS[doc.kind] ?? {
+ segment: `${routeSegment(doc.kind)}s`,
+ title: doc.kind,
+ summary: `Every ${doc.kind} doc.`,
+ };
+ const groupRoute = `${nsRoute}/${group.segment}`;
+ if (!nodes.has(groupRoute)) {
+ const kinds = rule.source.kinds ?? [];
+ addNode(
+ {
+ id: null,
+ route: groupRoute,
+ kind: 'namespace',
+ provider: namespace.provider,
+ providerId: namespace.providerId,
+ name: group.segment,
+ title: group.title,
+ summary: group.summary,
+ parent: nsRoute,
+ slot: rule.into,
+ order: kinds.includes(/** @type {any} */ (doc.kind))
+ ? kinds.indexOf(/** @type {any} */ (doc.kind))
+ : null,
+ generated: true,
+ slots: [{name: 'items', title: group.title, children: []}],
+ source: namespace.source,
+ },
+ namespace,
+ );
+ }
+ const groupNode = nodes.get(groupRoute);
+ if (!groupNode?.generated) continue;
+ home = {parentRoute: groupRoute, slot: 'items', order: null};
+ } else {
+ home = {parentRoute: nsRoute, slot: rule.into, order: null};
+ }
+ }
+ }
+ if (home == null) continue;
+ const segment = routeSegment(doc.name);
+ if (segment === '') {
+ report(
+ 'invalid_placement',
+ doc,
+ `${doc.provider}/${doc.kind}/${doc.name} has no route segment: its name holds no letters or digits.`,
+ 'name',
+ );
+ continue;
+ }
+ addNode(
+ {
+ id: createDocId(doc.providerId, doc.kind, doc.name),
+ route: `${home.parentRoute}/${segment}`,
+ kind: doc.kind,
+ provider: doc.provider,
+ providerId: doc.providerId,
+ name: doc.name,
+ title: doc.title,
+ summary: doc.summary,
+ parent: home.parentRoute,
+ slot: home.slot,
+ order: home.order,
+ generated: false,
+ slots: [],
+ source: doc.source,
+ ...(doc.ref === undefined ? {} : {ref: doc.ref}),
+ },
+ doc,
+ );
+ }
+
+ // The generated Unorganized level (spec:AST-046 FR12): every flat topic sits
+ // here, in the order the topic list reads, so every doc has a home in the
+ // tree. A topic keeps its own name as its route.
+ if (topics.length > 0) {
+ const home = {
+ id: null,
+ route: UNORGANIZED,
+ kind: 'namespace',
+ provider: CLI_PROVIDER,
+ providerId: CLI_PROVIDER_ID,
+ name: UNORGANIZED,
+ title: 'Unorganized',
+ summary:
+ 'Every topic that no section places yet. Each keeps its own name; open one by it.',
+ parent: null,
+ slot: null,
+ order: null,
+ generated: true,
+ slots: [{name: 'topics', title: 'Topics', children: []}],
+ source: 'generated',
+ };
+ if (addNode(home, {provider: CLI_PROVIDER, source: 'generated'})) {
+ topics.forEach((topic, i) => {
+ addNode(
+ {
+ id: createDocId(topic.providerId, 'generic', topic.name),
+ route: topic.name,
+ kind: 'generic',
+ provider: topic.provider,
+ providerId: topic.providerId,
+ name: topic.name,
+ title: topic.title,
+ summary: topic.summary,
+ parent: UNORGANIZED,
+ slot: 'topics',
+ order: i,
+ generated: false,
+ slots: [],
+ source: topic.source,
+ ref: {flatTopic: topic.name},
+ },
+ topic,
+ );
+ });
+ }
+ }
+
+ // Children, per slot, in reading order: order, then title, then id.
+ for (const node of nodes.values()) {
+ if (node.parent == null) continue;
+ const parent = nodes.get(node.parent);
+ parent?.slots
+ .find(slot => slot.name === node.slot)
+ ?.children.push(node.route);
+ }
+ for (const node of nodes.values()) {
+ for (const slot of node.slots) {
+ slot.children.sort((a, b) => {
+ const x = /** @type {TreeNode} */ (nodes.get(a));
+ const y = /** @type {TreeNode} */ (nodes.get(b));
+ return (
+ (x.order ?? Infinity) - (y.order ?? Infinity) ||
+ byText(x.title.toLowerCase(), y.title.toLowerCase()) ||
+ byText(x.id ?? x.route, y.id ?? y.route)
+ );
+ });
+ }
+ }
+
+ // A topic that answers, through `replaces`, to a route the CLI's own docs
+ // keep cannot have it: the CLI's doc opens there. Say so, against the topic.
+ for (const topic of topics) {
+ if (topic.provider === CLI_PROVIDER) continue;
+ for (const alias of topic.aliases ?? []) {
+ const holder = byFoldedRoute.get(alias.toLowerCase());
+ if (holder != null && holder.provider === CLI_PROVIDER) {
+ report(
+ 'duplicate_route',
+ topic,
+ `The topic "${topic.name}" answers to "${alias}" through replaces, but the CLI's own docs keep that route, so \`astryx docs ${alias}\` opens theirs. Drop that replacement.`,
+ );
+ }
+ }
+ }
+
+ const sorted = new Map([...nodes.entries()].sort(([a], [b]) => byText(a, b)));
+ return {
+ nodes: sorted,
+ diagnostics: sortDiagnostics(diagnostics),
+ get: route => sorted.get(route),
+ getFolded: route => byFoldedRoute.get(String(route).toLowerCase()),
+ roots: () => [...sorted.values()].filter(node => node.parent == null),
+ ancestors: node => {
+ /** @type {TreeNode[]} */
+ const chain = [];
+ let parent = node.parent == null ? undefined : sorted.get(node.parent);
+ while (parent) {
+ chain.unshift(parent);
+ parent = parent.parent == null ? undefined : sorted.get(parent.parent);
+ }
+ return chain;
+ },
+ };
+}
+
+/**
+ * Check a placement against the namespace it names: the namespace exists in
+ * the doc's own package, the slot is one it declares, and the slot accepts the
+ * doc's kind.
+ * @param {DocPlacement} placement
+ * @param {string} kind
+ * @param {{provider: string}} at
+ * @param {Map<string, TreeNamespaceInput>} declared
+ * @returns {{key: string, slot: string} | {error: string}}
+ */
+function checkPlacement(placement, kind, at, declared) {
+ const target = resolveParent(placement.parent, at.provider, declared);
+ if ('error' in target) return target;
+ const parent = /** @type {TreeNamespaceInput} */ (declared.get(target.key));
+ const slotNames = Object.keys(parent.doc.slots);
+ const slot = placement.slot ?? (slotNames.length === 1 ? slotNames[0] : null);
+ if (slot == null) {
+ return {
+ error: `placement names no slot, and namespace "${parent.doc.name}" has ${slotNames.length} (${slotNames.join(', ')}). Name one with placement.slot.`,
+ };
+ }
+ const declaredSlot = parent.doc.slots[slot];
+ if (declaredSlot == null) {
+ return {
+ error: `placement.slot "${slot}" is not a slot of namespace "${parent.doc.name}"; it declares ${slotNames.join(', ')}.`,
+ };
+ }
+ if (!declaredSlot.accepts.kinds.includes(/** @type {any} */ (kind))) {
+ return {
+ error: `slot "${slot}" of namespace "${parent.doc.name}" does not accept ${kind} docs; it accepts ${declaredSlot.accepts.kinds.join(', ')}.`,
+ };
+ }
+ return {key: target.key, slot};
+}
+
+/**
+ * Every adoption rule in the doc's own package that matches its group and
+ * kind, from namespaces that have a route.
+ * @param {TreeDocInput} doc
+ * @param {Map<string, TreeNamespaceInput>} declared
+ * @param {Map<string, string | null>} routeOf
+ */
+function adoptionsFor(doc, declared, routeOf) {
+ /** @type {Array<{key: string, namespace: TreeNamespaceInput, rule: NonNullable<NamespaceDoc['adopts']>[number]}>} */
+ const matches = [];
+ for (const [key, namespace] of declared) {
+ if (namespace.provider !== doc.provider || routeOf.get(key) == null)
+ continue;
+ for (const rule of namespace.doc.adopts ?? []) {
+ if (rule.source.group !== doc.group) continue;
+ if (
+ rule.source.kinds &&
+ !rule.source.kinds.includes(/** @type {any} */ (doc.kind))
+ ) {
+ continue;
+ }
+ matches.push({key, namespace, rule});
+ }
+ }
+ return matches;
+}
+
+/**
+ * The files under {@link TREE_DOCS_DIR}, sorted.
+ * @param {string} [dir]
+ * @returns {string[]}
+ */
+export function treeDocFiles(dir = TREE_DOCS_DIR) {
+ if (!fs.existsSync(dir)) return [];
+ return fs
+ .readdirSync(dir)
+ .filter(file => /^[\w-]+\.doc\.mjs$/u.test(file))
+ .sort(byText)
+ .map(file => path.join(dir, file));
+}
+
+/**
+ * The CLI's own tree inputs: the namespace docs and guides under
+ * assets/docs/tree, and, unless left out, every typed self-doc with its
+ * `namespace` group. A file that fails to load or parse is a diagnostic, never
+ * a thrown error.
+ * @param {{selfDocs?: boolean, dir?: string}} [options]
+ * @returns {Promise<{namespaces: TreeNamespaceInput[], docs: TreeDocInput[], diagnostics: CompilerDiagnostic[]}>}
+ */
+export async function loadTreeInputs({
+ selfDocs = true,
+ dir = TREE_DOCS_DIR,
+} = {}) {
+ /** @type {TreeNamespaceInput[]} */
+ const namespaces = [];
+ /** @type {TreeDocInput[]} */
+ const docs = [];
+ /** @type {CompilerDiagnostic[]} */
+ const diagnostics = [];
+ for (const file of treeDocFiles(dir)) {
+ const source = packageSource(file);
+ const at = {provider: CLI_PROVIDER, source};
+ let doc;
+ try {
+ doc = await readDocView(file, {
+ root: 'tree',
+ provider: CLI_PROVIDER,
+ loader: 'native',
+ strict: true,
+ });
+ } catch (error) {
+ diagnostics.push(
+ diagnostic('invalid_doc', {
+ ...at,
+ message: error instanceof Error ? error.message : String(error),
+ }),
+ );
+ continue;
+ }
+ const stem = path.basename(file, '.doc.mjs');
+ if (doc?.name !== stem) {
+ diagnostics.push(
+ diagnostic('invalid_doc', {
+ ...at,
+ field: 'name',
+ message: `${path.basename(file)} declares name "${doc?.name}"; a docs tree file is named after its doc (${doc?.name}.doc.mjs).`,
+ }),
+ );
+ continue;
+ }
+ if (doc.type === 'namespace') {
+ namespaces.push({
+ provider: CLI_PROVIDER,
+ providerId: CLI_PROVIDER_ID,
+ source,
+ doc,
+ });
+ } else if (doc.type === 'generic') {
+ if (doc.placement == null) {
+ diagnostics.push(
+ diagnostic('invalid_placement', {
+ ...at,
+ field: 'placement',
+ message: `${path.basename(file)} has no placement. A guide in the docs tree names its parent namespace with placement.parent.`,
+ }),
+ );
+ continue;
+ }
+ docs.push({
+ provider: CLI_PROVIDER,
+ providerId: CLI_PROVIDER_ID,
+ source,
+ kind: 'generic',
+ name: doc.name,
+ title: doc.title,
+ summary: doc.description,
+ group: null,
+ placement: doc.placement,
+ ref: {topicFile: file},
+ });
+ } else {
+ diagnostics.push(
+ diagnostic('wrong_kind', {
+ ...at,
+ message: `${path.basename(file)} is stamped type ${JSON.stringify(doc?.type)}; the docs tree reads namespace and generic docs.`,
+ }),
+ );
+ }
+ }
+ if (selfDocs) {
+ const {loaded} = await loadCliSelfDocs();
+ for (const {source, doc} of loaded) {
+ docs.push({
+ provider: CLI_PROVIDER,
+ providerId: CLI_PROVIDER_ID,
+ source: `${CLI_PROVIDER}/${source}`,
+ kind: doc.type,
+ name: doc.name,
+ title: doc.displayName ?? doc.name,
+ summary: doc.summary ?? doc.description ?? '',
+ group: typeof doc.namespace === 'string' ? doc.namespace : null,
+ placement: doc.placement,
+ ref: {selfDoc: doc},
+ });
+ }
+ }
+ return {namespaces, docs, diagnostics};
+}
+
+/** @type {Map<string, Promise<DocsTree>>} */
+const built = new Map();
+
+/**
+ * The CLI's own docs tree, built once per process. With `selfDocs: false` it
+ * holds only the namespaces and guides, which is all a topic list needs.
+ * @param {{selfDocs?: boolean, fresh?: boolean}} [options]
+ * @returns {Promise<DocsTree>}
+ */
+export function loadDocsTree({selfDocs = true, fresh = false} = {}) {
+ const key = selfDocs ? 'full' : 'namespaces';
+ let tree = fresh ? undefined : built.get(key);
+ if (!tree) {
+ tree = loadTreeInputs({selfDocs}).then(inputs => {
+ const result = buildDocsTree(inputs);
+ return {
+ ...result,
+ diagnostics: sortDiagnostics([
+ ...inputs.diagnostics,
+ ...result.diagnostics,
+ ]),
+ };
+ });
+ built.set(key, tree);
+ }
+ return tree;
+}
diff --git a/packages/cli/foundation/doc-compiler/tree.test.mjs b/packages/cli/foundation/doc-compiler/tree.test.mjs
new file mode 100644
index 0000000000..e2bb130df2
--- /dev/null
+++ b/packages/cli/foundation/doc-compiler/tree.test.mjs
@@ -0,0 +1,598 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for the docs tree (spec:AST-046): one home per doc, decided by
+ * explicit placement, then one adoption rule; every way a placement can fail;
+ * generated kind levels; deterministic order; and the CLI's own tree.
+ *
+ * @input Plain fixture inputs for the pure builder, and this package's own
+ * tree files and typed docs for the loader.
+ * @output Assertions on routes, parents, slots, children order, and
+ * diagnostics.
+ * @position packages/cli/foundation/doc-compiler — tests for tree.mjs.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {
+ buildDocsTree,
+ KIND_GROUPS,
+ loadDocsTree,
+ loadTreeInputs,
+ routeSegment,
+} from './tree.mjs';
+import {loadCliSelfDocs} from '../discovery/cli-self-docs.mjs';
+import * as api from '../../api/index.mjs';
+import {createDocId} from '../identity/provider-identity.mjs';
+import {CLI_PROVIDER_ID} from '../identity/providers.mjs';
+
+const SLOW = 60_000;
+const P = '@acme/kit';
+
+/**
+ * @param {string} name
+ * @param {object} [extra]
+ * @returns {import('./tree.mjs').TreeNamespaceInput}
+ */
+const ns = (name, extra = {}) => ({
+ provider: P,
+ providerId: P,
+ source: `${P}/tree/${name}.doc.mjs`,
+ doc: /** @type {any} */ ({
+ type: 'namespace',
+ name,
+ title: name.toUpperCase(),
+ summary: `The ${name} level.`,
+ slots: {
+ items: {title: 'Items', accepts: {kinds: ['generic', 'namespace']}},
+ },
+ ...extra,
+ }),
+});
+
+/**
+ * @param {string} name
+ * @param {object} [extra]
+ * @returns {import('./tree.mjs').TreeDocInput}
+ */
+const guide = (name, extra = {}) => ({
+ provider: P,
+ providerId: P,
+ source: `${P}/tree/${name}.doc.mjs`,
+ kind: 'generic',
+ name,
+ title: `Guide ${name}`,
+ summary: `About ${name}.`,
+ group: null,
+ placement: undefined,
+ ...extra,
+});
+
+/**
+ * @param {string} kind
+ * @param {string} name
+ * @param {string} group
+ * @returns {import('./tree.mjs').TreeDocInput}
+ */
+const typed = (kind, name, group) => ({
+ provider: P,
+ providerId: P,
+ source: `${P}/api/${name}.doc.mjs`,
+ kind,
+ name,
+ title: name,
+ summary: `The ${name} ${kind}.`,
+ group,
+ placement: undefined,
+});
+
+/** @param {ReturnType<typeof buildDocsTree>} tree */
+const routes = tree => [...tree.nodes.keys()];
+
+/** @param {ReturnType<typeof buildDocsTree>} tree */
+const problems = tree => tree.diagnostics.map(d => [d.code, d.message]);
+
+describe('buildDocsTree', () => {
+
+ it('withdraws a namespace placed in a withdrawn namespace, and what is placed in it', () => {
+ const CLI = '@astryxdesign/cli';
+ const tree = buildDocsTree({
+ namespaces: [
+ ns('tokens'),
+ ns('alpha', {placement: {parent: 'namespace:tokens', slot: 'items'}}),
+ ],
+ docs: [guide('deep', {placement: {parent: 'namespace:alpha', slot: 'items'}})],
+ topics: [
+ {provider: CLI, providerId: CLI, name: 'tokens', title: 'Tokens', summary: 'Tokens.', source: `${CLI}/tokens.doc.mjs`},
+ ],
+ });
+ expect(tree.get('tokens')?.provider).toBe(CLI);
+ expect(routes(tree).filter(route => route.startsWith('tokens/'))).toEqual([]);
+ expect(problems(tree)).toEqual(
+ expect.arrayContaining([
+ ['duplicate_route', expect.stringContaining('takes the route "tokens"')],
+ ['invalid_placement', 'Namespace "alpha" has no route: the namespace it is placed in was withdrawn.'],
+ ['invalid_placement', expect.stringContaining('names a namespace that has no route')],
+ ]),
+ );
+ });
+
+ it("keeps a name a topic answers to through replaces as that topic's route", () => {
+ const tree = buildDocsTree({
+ namespaces: [ns('tokens')],
+ docs: [],
+ topics: [
+ {provider: '@acme/a', providerId: '@acme/a', name: 'acme-tokens', title: 'Acme tokens', summary: 'Acme tokens.', source: '@acme/a:acme-tokens', aliases: ['tokens', 'old-tokens']},
+ ],
+ });
+ expect(tree.get('tokens')).toBeUndefined();
+ expect(tree.get('acme-tokens')?.provider).toBe('@acme/a');
+ expect(problems(tree)).toEqual([
+ ['duplicate_route', expect.stringContaining('takes the route "tokens", which the topic "acme-tokens" also answers to')],
+ ]);
+ // Every name it answers to is reserved, not only the last one it replaced.
+ const older = buildDocsTree({
+ namespaces: [ns('old-tokens')],
+ docs: [],
+ topics: [
+ {provider: '@acme/a', providerId: '@acme/a', name: 'acme-tokens', title: 'Acme tokens', summary: 'Acme tokens.', source: '@acme/a:acme-tokens', aliases: ['tokens', 'old-tokens']},
+ ],
+ });
+ expect(older.get('old-tokens')).toBeUndefined();
+ });
+
+ it("keeps the CLI's own routes from an integration, compared without case", () => {
+ const CLI = '@astryxdesign/cli';
+ /** @param {string} name @param {string} [provider] */
+ const topic = (name, provider = P) => ({
+ provider,
+ providerId: provider,
+ name,
+ title: name,
+ summary: `The ${name} topic.`,
+ source: `${provider}/${name}.doc.mjs`,
+ });
+ const cliNs = {...ns('cli'), provider: CLI, providerId: CLI, source: `${CLI}/tree/cli.doc.mjs`};
+ // An integration's topics named `CLI` and `UNORGANIZED` claim the CLI's
+ // namespace and the generated level; both are withdrawn.
+ const tree = buildDocsTree({
+ namespaces: [cliNs],
+ docs: [],
+ topics: [topic('theme', CLI), topic('CLI'), topic('UNORGANIZED')],
+ });
+ expect(tree.get('cli')?.provider).toBe(CLI);
+ expect(tree.get('unorganized')?.provider).toBe(CLI);
+ expect(routes(tree)).not.toContain('CLI');
+ expect(routes(tree)).not.toContain('UNORGANIZED');
+ expect(problems(tree)).toEqual(
+ expect.arrayContaining([
+ ['duplicate_route', expect.stringContaining('both have the route "CLI"')],
+ ['duplicate_route', expect.stringContaining('takes the route "UNORGANIZED", which the CLI\'s own docs keep')],
+ ]),
+ );
+ expect(tree.getFolded('THEME')?.provider).toBe(CLI);
+ // A CLI topic whose own name has capitals keeps its route against a
+ // lowercase namespace, although namespaces go into the tree first.
+ const caps = buildDocsTree({namespaces: [ns('tokens')], docs: [], topics: [topic('Tokens', CLI)]});
+ expect(caps.get('Tokens')?.provider).toBe(CLI);
+ expect(caps.get('tokens')).toBeUndefined();
+ expect(problems(caps)).toEqual([
+ ['duplicate_route', expect.stringContaining('takes the route "tokens", which the CLI\'s own docs keep')],
+ ]);
+ });
+ it('builds three authored levels and a guide below them', () => {
+ const tree = buildDocsTree({
+ namespaces: [
+ ns('top'),
+ ns('middle', {placement: {parent: 'namespace:top', slot: 'items'}}),
+ ns('bottom', {placement: {parent: 'namespace:middle'}}),
+ ],
+ docs: [
+ guide('deep', {placement: {parent: 'namespace:bottom', order: 1}}),
+ ],
+ });
+ expect(problems(tree)).toEqual([]);
+ expect(routes(tree)).toEqual([
+ 'top',
+ 'top/middle',
+ 'top/middle/bottom',
+ 'top/middle/bottom/deep',
+ ]);
+ const deep = /** @type {any} */ (tree.get('top/middle/bottom/deep'));
+ expect(deep).toMatchObject({
+ id: 'astryx:artifact:v1/%40acme%2Fkit/generic/deep',
+ parent: 'top/middle/bottom',
+ slot: 'items',
+ order: 1,
+ generated: false,
+ });
+ expect(tree.ancestors(deep).map(node => node.route)).toEqual([
+ 'top',
+ 'top/middle',
+ 'top/middle/bottom',
+ ]);
+ expect(tree.roots().map(node => node.route)).toEqual(['top']);
+ });
+
+ it('adopts typed docs by group, with one generated level per kind', () => {
+ const tree = buildDocsTree({
+ namespaces: [
+ ns('api', {
+ slots: {kinds: {title: 'Reference', accepts: {kinds: ['namespace']}}},
+ adopts: [
+ {
+ source: {group: 'kit/api', kinds: ['function', 'enum']},
+ into: 'kinds',
+ groupBy: 'kind',
+ },
+ ],
+ }),
+ ],
+ docs: [
+ typed('enum', 'errorCodes', 'kit/api'),
+ typed('function', 'search', 'kit/api'),
+ typed('function', 'build', 'kit/api'),
+ typed('schema', 'config', 'kit/api'),
+ typed('function', 'other', 'kit/elsewhere'),
+ ],
+ });
+ expect(problems(tree)).toEqual([]);
+ expect(routes(tree)).toEqual([
+ 'api',
+ 'api/enums',
+ 'api/enums/error-codes',
+ 'api/functions',
+ 'api/functions/build',
+ 'api/functions/search',
+ ]);
+ const functions = /** @type {any} */ (tree.get('api/functions'));
+ expect(functions).toMatchObject({
+ id: null,
+ kind: 'namespace',
+ title: KIND_GROUPS.function.title,
+ generated: true,
+ parent: 'api',
+ slot: 'kinds',
+ });
+ // Kind levels follow the rule's kind order; docs inside sort by title.
+ expect(tree.get('api')?.slots[0].children).toEqual([
+ 'api/functions',
+ 'api/enums',
+ ]);
+ expect(functions.slots[0].children).toEqual([
+ 'api/functions/build',
+ 'api/functions/search',
+ ]);
+ });
+
+ it('adopts without grouping straight into the named slot', () => {
+ const tree = buildDocsTree({
+ namespaces: [
+ ns('commands', {
+ slots: {all: {title: 'All', accepts: {kinds: ['command']}}},
+ adopts: [{source: {group: 'kit/commands'}, into: 'all'}],
+ }),
+ ],
+ docs: [typed('command', 'theme add', 'kit/commands')],
+ });
+ expect(routes(tree)).toEqual(['commands', 'commands/theme-add']);
+ expect(tree.get('commands')?.slots[0].children).toEqual([
+ 'commands/theme-add',
+ ]);
+ });
+
+ it('prefers explicit placement over adoption, and never falls back', () => {
+ const namespaces = [
+ ns('guides'),
+ ns('api', {
+ slots: {all: {title: 'All', accepts: {kinds: ['generic']}}},
+ adopts: [{source: {group: 'kit/api'}, into: 'all'}],
+ }),
+ ];
+ const placed = buildDocsTree({
+ namespaces,
+ docs: [
+ guide('intro', {
+ group: 'kit/api',
+ placement: {parent: 'namespace:guides'},
+ }),
+ ],
+ });
+ expect(routes(placed)).toContain('guides/intro');
+ expect(routes(placed)).not.toContain('api/intro');
+
+ const broken = buildDocsTree({
+ namespaces,
+ docs: [
+ guide('intro', {
+ group: 'kit/api',
+ placement: {parent: 'namespace:nope'},
+ }),
+ ],
+ });
+ expect(routes(broken).some(route => route.endsWith('/intro'))).toBe(false);
+ expect(problems(broken)).toEqual([
+ [
+ 'invalid_placement',
+ 'placement.parent "namespace:nope" names no namespace; @acme/kit declares "api", "guides".',
+ ],
+ ]);
+ });
+
+ it('reports every way a placement can fail', () => {
+ const tree = buildDocsTree({
+ namespaces: [
+ ns('home', {
+ slots: {
+ one: {title: 'One', accepts: {kinds: ['generic']}},
+ two: {title: 'Two', accepts: {kinds: ['command']}},
+ },
+ }),
+ ],
+ docs: [
+ guide('no-slot', {placement: {parent: 'namespace:home'}}),
+ guide('bad-slot', {
+ placement: {parent: 'namespace:home', slot: 'three'},
+ }),
+ guide('wrong-kind', {
+ placement: {parent: 'namespace:home', slot: 'two'},
+ }),
+ guide('other-package', {
+ placement: {parent: '@other/pkg/namespace/home'},
+ }),
+ guide('not-a-ref', {placement: {parent: 'home'}}),
+ ],
+ });
+ expect(routes(tree)).toEqual(['home']);
+ expect(
+ problems(tree)
+ .map(([, message]) => message)
+ .sort(),
+ ).toEqual(
+ [
+ 'placement names no slot, and namespace "home" has 2 (one, two). Name one with placement.slot.',
+ 'placement.slot "three" is not a slot of namespace "home"; it declares one, two.',
+ 'slot "two" of namespace "home" does not accept generic docs; it accepts command.',
+ 'placement.parent "@other/pkg/namespace/home" belongs to @other/pkg. A doc can only be placed in a namespace of its own package (@acme/kit).',
+ 'placement.parent "home" is not a namespace reference. Write "namespace:<name>".',
+ ].sort(),
+ );
+ expect(tree.diagnostics.every(d => d.code === 'invalid_placement')).toBe(
+ true,
+ );
+ expect(tree.diagnostics.every(d => d.severity === 'error')).toBe(true);
+ });
+
+ it('fails a doc two namespaces adopt, naming both', () => {
+ const rule = {source: {group: 'kit/api'}, into: 'items'};
+ const tree = buildDocsTree({
+ namespaces: [ns('a', {adopts: [rule]}), ns('b', {adopts: [rule]})],
+ docs: [guide('shared', {group: 'kit/api'})],
+ });
+ expect(routes(tree)).toEqual(['a', 'b']);
+ expect(problems(tree)).toEqual([
+ [
+ 'overlapping_adoption',
+ '@acme/kit/generic/shared is adopted by "a" and "b"; exactly one namespace may adopt a doc.',
+ ],
+ ]);
+ });
+
+ it('fails two docs at one route, keeping the first by identity', () => {
+ const tree = buildDocsTree({
+ namespaces: [ns('home')],
+ docs: [
+ guide('fooBar', {placement: {parent: 'namespace:home'}}),
+ guide('foo_bar', {placement: {parent: 'namespace:home'}}),
+ ],
+ });
+ expect(routes(tree)).toEqual(['home', 'home/foo-bar']);
+ expect(tree.get('home/foo-bar')?.id).toBe(
+ 'astryx:artifact:v1/%40acme%2Fkit/generic/fooBar',
+ );
+ expect(problems(tree)).toEqual([
+ [
+ 'duplicate_route',
+ 'astryx:artifact:v1/%40acme%2Fkit/generic/foo_bar and astryx:artifact:v1/%40acme%2Fkit/generic/fooBar both have the route "home/foo-bar". Rename or move one of them.',
+ ],
+ ]);
+ });
+
+ it('fails a namespace cycle and everything under it', () => {
+ const tree = buildDocsTree({
+ namespaces: [
+ ns('a', {placement: {parent: 'namespace:b'}}),
+ ns('b', {placement: {parent: 'namespace:a'}}),
+ ],
+ docs: [guide('lost', {placement: {parent: 'namespace:a'}})],
+ });
+ expect(routes(tree)).toEqual([]);
+ expect(problems(tree).map(([code]) => code)).toEqual([
+ 'invalid_placement',
+ 'invalid_placement',
+ 'invalid_placement',
+ ]);
+ });
+
+ it('fails a duplicate or unsafe namespace name', () => {
+ const tree = buildDocsTree({
+ namespaces: [
+ ns('twice'),
+ {...ns('twice'), source: `${P}/other.doc.mjs`},
+ ns('Bad Name'),
+ ],
+ docs: [],
+ });
+ expect(routes(tree)).toEqual(['twice']);
+ expect(tree.diagnostics.map(d => d.code)).toEqual([
+ 'invalid_namespace',
+ 'invalid_namespace',
+ ]);
+ });
+
+ it('leaves a doc with no placement and no adoption out, in phase 1', () => {
+ const tree = buildDocsTree({
+ namespaces: [ns('home')],
+ docs: [guide('loose'), typed('function', 'free', 'kit/nowhere')],
+ });
+ expect(routes(tree)).toEqual(['home']);
+ expect(tree.diagnostics).toEqual([]);
+ });
+
+ it('is the same tree whatever order its inputs arrive in', () => {
+ const namespaces = [
+ ns('top'),
+ ns('child', {placement: {parent: 'namespace:top'}}),
+ ];
+ const docs = [
+ guide('b', {placement: {parent: 'namespace:child'}}),
+ guide('a', {placement: {parent: 'namespace:child'}}),
+ ];
+ const one = buildDocsTree({namespaces, docs});
+ const two = buildDocsTree({
+ namespaces: [...namespaces].reverse(),
+ docs: [...docs].reverse(),
+ });
+ expect(JSON.stringify([...two.nodes])).toBe(JSON.stringify([...one.nodes]));
+ });
+
+ it('orders children by order, then title', () => {
+ const tree = buildDocsTree({
+ namespaces: [ns('home')],
+ docs: [
+ guide('z', {
+ title: 'Zed',
+ placement: {parent: 'namespace:home', order: 1},
+ }),
+ guide('b', {title: 'Beta', placement: {parent: 'namespace:home'}}),
+ guide('a', {title: 'Alpha', placement: {parent: 'namespace:home'}}),
+ ],
+ });
+ expect(tree.get('home')?.slots[0].children).toEqual([
+ 'home/z',
+ 'home/a',
+ 'home/b',
+ ]);
+ });
+});
+
+describe('routeSegment', () => {
+ it('joins lowercase words with hyphens, whatever the name looks like', () => {
+ expect(routeSegment('integrationPackCheck')).toBe('integration-pack-check');
+ expect(routeSegment('doctor integration validate')).toBe(
+ 'doctor-integration-validate',
+ );
+ expect(routeSegment('error-codes')).toBe('error-codes');
+ expect(routeSegment('isError')).toBe('is-error');
+ expect(routeSegment('!!')).toBe('');
+ });
+});
+
+describe("the CLI's own docs tree", () => {
+ it(
+ 'builds with no diagnostic, rooted at cli',
+ async () => {
+ const tree = await loadDocsTree({fresh: true});
+ expect(tree.diagnostics).toEqual([]);
+ expect(tree.roots().map(node => node.route)).toEqual(['cli']);
+ expect(
+ tree.get('cli')?.slots.map(slot => [slot.name, slot.children]),
+ ).toEqual([
+ ['guides', ['cli/integrations', 'cli/writing-docs']],
+ ['reference', ['cli/commands', 'cli/api']],
+ ]);
+ expect(tree.get('cli/api')?.slots[0].children).toEqual([
+ 'cli/api/functions',
+ 'cli/api/schemas',
+ 'cli/api/enums',
+ ]);
+ },
+ SLOW,
+ );
+
+ it(
+ 'gives every CLI typed doc in a cli group one route, by its kind',
+ async () => {
+ const tree = await loadDocsTree();
+ const {loaded} = await loadCliSelfDocs();
+ const inTree = loaded.filter(({doc}) =>
+ String(doc.namespace).startsWith('cli/'),
+ );
+ expect(inTree.length).toBeGreaterThan(0);
+ const expected = inTree.map(({doc}) =>
+ doc.type === 'command'
+ ? `cli/commands/${routeSegment(doc.name)}`
+ : `cli/api/${KIND_GROUPS[doc.type].segment}/${routeSegment(doc.name)}`,
+ );
+ expect(expected.filter(route => tree.get(route) == null)).toEqual([]);
+ // A doc in the authoring group stays a section of `astryx docs authoring`.
+ const authoring = loaded.filter(({doc}) => doc.namespace === 'authoring');
+ expect(authoring.length).toBeGreaterThan(0);
+ const ids = new Set([...tree.nodes.values()].map(node => node.id));
+ expect(
+ authoring.filter(({doc}) =>
+ ids.has(createDocId(CLI_PROVIDER_ID, doc.type, doc.name)),
+ ),
+ ).toEqual([]);
+ },
+ SLOW,
+ );
+
+ it(
+ 'gives every function @astryxdesign/cli/api exports a route',
+ async () => {
+ const tree = await loadDocsTree();
+ const exported = Object.entries(api)
+ .filter(
+ ([, value]) =>
+ typeof value === 'function' &&
+ Object.getOwnPropertyDescriptor(value, 'prototype')?.writable !==
+ false,
+ )
+ .map(([name]) => `cli/api/functions/${routeSegment(name)}`);
+ expect(exported.length).toBeGreaterThan(0);
+ expect(exported.filter(route => tree.get(route) == null)).toEqual([]);
+ },
+ SLOW,
+ );
+
+ it(
+ 'reads only namespace and generic docs from the tree directory, each named after its file',
+ async () => {
+ const inputs = await loadTreeInputs({selfDocs: false});
+ expect(inputs.diagnostics).toEqual([]);
+ expect(inputs.namespaces.map(n => n.doc.name).sort()).toEqual([
+ 'api',
+ 'cli',
+ 'commands',
+ ]);
+ expect(inputs.docs.map(d => [d.name, d.placement?.parent])).toEqual([
+ ['integrations', 'namespace:cli'],
+ ['writing-docs', 'namespace:cli'],
+ ]);
+ },
+ SLOW,
+ );
+});
+
+describe('doc identity', () => {
+ it('builds each id from the provider id, never the package name', () => {
+ const provider = '@acme/tree-provider';
+ const tree = buildDocsTree({
+ namespaces: [{...ns('home'), providerId: provider}],
+ docs: [
+ {
+ ...guide('intro', {placement: {parent: 'namespace:home'}}),
+ providerId: provider,
+ },
+ ],
+ });
+ expect(problems(tree)).toEqual([]);
+ expect(tree.get('home')?.id).toBe(
+ 'astryx:artifact:v1/%40acme%2Ftree-provider/namespace/home',
+ );
+ expect(tree.get('home/intro')).toMatchObject({
+ id: 'astryx:artifact:v1/%40acme%2Ftree-provider/generic/intro',
+ provider: P,
+ });
+ });
+});
diff --git a/packages/cli/foundation/integrations/autolink.test.mjs b/packages/cli/foundation/integrations/autolink.test.mjs
index d9cc3ee14a..b0c7c5e362 100644
--- a/packages/cli/foundation/integrations/autolink.test.mjs
+++ b/packages/cli/foundation/integrations/autolink.test.mjs
@@ -87,7 +87,7 @@ function installPackage(
fs.mkdirSync(componentsDir, {recursive: true});
fs.writeFileSync(
path.join(componentsDir, `${componentName}.doc.mjs`),
- `export const docs = {name: '${componentName}', usage: {description: 'A widget'}};\n`,
+ `export default {type: 'component', name: '${componentName}', usage: {description: 'A widget'}, props: []};\n`,
);
fs.writeFileSync(
path.join(componentsDir, `${componentName}.tsx`),
diff --git a/packages/cli/foundation/integrations/cli-requirement.mjs b/packages/cli/foundation/integrations/cli-requirement.mjs
new file mode 100644
index 0000000000..94408ab677
--- /dev/null
+++ b/packages/cli/foundation/integrations/cli-requirement.mjs
@@ -0,0 +1,154 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The CLI an integration's namespace docs need (spec:AST-046 FR11).
+ *
+ * @input A package.json object.
+ * @output Whether its `peerDependencies` range for `@astryxdesign/cli` admits
+ * only CLIs that read namespace docs, and the package.json that declares it.
+ * @position foundation/integrations; read by `integration add doc --parent`,
+ * which declares the peer, and `integration pack --check`, which requires it.
+ */
+
+import {semverCompare} from '../env/semver.mjs';
+
+export const CLI_PACKAGE = '@astryxdesign/cli';
+
+/**
+ * The first CLI release that reads an integration's docs tree (namespace docs
+ * and placed guides) and its templates' `replaces`. A release before it can
+ * hide every doc topic a package with a namespace doc or a placed guide
+ * ships, with no warning, and it rejects `replaces` and withholds the
+ * package's templates and doc topics.
+ */
+export const DOCS_TREE_CLI = '0.7.0';
+
+const VERSION_RE = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
+
+/**
+ * A version or partial version as MAJOR.MINOR.PATCH, a wildcard part as 0.
+ * @param {string} text
+ * @returns {string | null}
+ */
+function lowerVersion(text) {
+ const m = VERSION_RE.exec(text.trim());
+ if (!m) return null;
+ return [m[1], m[2], m[3]]
+ .map(part => (part == null || /^[xX*]$/.test(part) ? '0' : part))
+ .join('.');
+}
+
+/**
+ * The lowest version one space-joined comparator set admits, or null when it
+ * has no lower bound this can read.
+ * @param {string} set
+ * @returns {string | null}
+ */
+function lowestOfSet(set) {
+ if (set === '' || set === '*' || /^[xX]$/.test(set)) return null;
+ const hyphen = /^(\S+)\s+-\s+\S+$/.exec(set);
+ if (hyphen) return lowerVersion(hyphen[1]);
+ /** @type {string | null} */
+ let lowest = null;
+ for (const comparator of set.split(/\s+/)) {
+ const m = /^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(comparator);
+ if (!m) return null;
+ if (m[1] === '<' || m[1] === '<=') continue;
+ const version = lowerVersion(m[2]);
+ if (version == null) return null;
+ if (lowest == null || semverCompare(version, lowest) > 0) lowest = version;
+ }
+ return lowest;
+}
+
+/**
+ * The lowest version a semver range admits: the least of its `||`
+ * alternatives. Null when an alternative has no lower bound, or the range is
+ * not one this can read, so the caller treats it as admitting every version.
+ * @param {unknown} range
+ * @returns {string | null}
+ */
+export function lowestAdmitted(range) {
+ if (typeof range !== 'string') return null;
+ /** @type {string | null} */
+ let lowest = null;
+ for (const alternative of range.split('||')) {
+ const low = lowestOfSet(alternative.trim());
+ if (low == null) return null;
+ if (lowest == null || semverCompare(low, lowest) < 0) lowest = low;
+ }
+ return lowest;
+}
+
+/**
+ * Why a package that uses a feature an older CLI cannot read would lose it,
+ * or null when its declared CLI range admits only CLIs that read it.
+ * @param {any} pkg package.json
+ * @param {string} feature what the package does, e.g. "ships a namespace doc"
+ * @param {string} loss what an older CLI does with it
+ * @returns {string | null}
+ */
+function cliRangeProblem(pkg, feature, loss) {
+ const range = pkg?.peerDependencies?.[CLI_PACKAGE];
+ const fix = `"${CLI_PACKAGE}": ">=${DOCS_TREE_CLI}" in peerDependencies (optional in peerDependenciesMeta, if the CLI is not required)`;
+ if (typeof range !== 'string') {
+ return `The package ${feature} but declares no ${CLI_PACKAGE} peer. A CLI older than ${DOCS_TREE_CLI} ${loss}. Declare ${fix}.`;
+ }
+ const lowest = lowestAdmitted(range);
+ if (lowest == null || semverCompare(lowest, DOCS_TREE_CLI) < 0) {
+ return `The package ${feature}, but its ${CLI_PACKAGE} peer range "${range}" admits a CLI older than ${DOCS_TREE_CLI}, which ${loss}. Declare ${fix}.`;
+ }
+ return null;
+}
+
+/**
+ * Why a package that ships a namespace doc or a placed guide would lose its
+ * docs on an older CLI, or null when its declared CLI range admits only CLIs
+ * that read the docs tree. Published 0.6.3 hides every topic of a package
+ * with a namespace doc; builds of main before the docs tree also do so for a
+ * placed guide.
+ * @param {any} pkg package.json
+ * @returns {string | null}
+ */
+export function docsTreeCliProblem(pkg) {
+ return cliRangeProblem(
+ pkg,
+ 'ships a namespace doc or a placed guide',
+ 'does not read the docs tree, and can hide every doc topic the package ships',
+ );
+}
+
+/**
+ * Why a package with a template that sets `replaces` would lose its templates
+ * and doc topics on an older CLI (spec:AST-035), or null when its declared CLI
+ * range admits only CLIs that read the field.
+ * @param {any} pkg package.json
+ * @returns {string | null}
+ */
+export function replacesCliProblem(pkg) {
+ return cliRangeProblem(
+ pkg,
+ 'has a template that sets `replaces`',
+ "rejects the field, and withholds the package's templates and doc topics",
+ );
+}
+
+/**
+ * The package.json with a CLI peer that reads namespace docs: optional, unless
+ * the package already says otherwise.
+ * @param {any} pkg package.json
+ * @returns {any}
+ */
+export function withDocsTreeCli(pkg) {
+ const meta = pkg.peerDependenciesMeta ?? {};
+ return {
+ ...pkg,
+ peerDependencies: {
+ ...(pkg.peerDependencies ?? {}),
+ [CLI_PACKAGE]: `>=${DOCS_TREE_CLI}`,
+ },
+ peerDependenciesMeta: meta[CLI_PACKAGE]
+ ? meta
+ : {...meta, [CLI_PACKAGE]: {optional: true}},
+ };
+}
diff --git a/packages/cli/foundation/integrations/cli-requirement.test.mjs b/packages/cli/foundation/integrations/cli-requirement.test.mjs
new file mode 100644
index 0000000000..4fb3273257
--- /dev/null
+++ b/packages/cli/foundation/integrations/cli-requirement.test.mjs
@@ -0,0 +1,109 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {CLI_ROOT} from '../fs/paths.mjs';
+import {semverCompare} from '../env/semver.mjs';
+import {
+ DOCS_TREE_CLI,
+ lowestAdmitted,
+ docsTreeCliProblem,
+ replacesCliProblem,
+ withDocsTreeCli,
+} from './cli-requirement.mjs';
+
+describe('lowestAdmitted', () => {
+ it.each([
+ ['>=0.7.0', '0.7.0'],
+ ['^0.6.0', '0.6.0'],
+ ['~0.7.1', '0.7.1'],
+ ['0.7.x', '0.7.0'],
+ ['>=0.7.0 <0.8.0', '0.7.0'],
+ ['^0.6.0 || >=0.7.0', '0.6.0'],
+ ['0.8.0 - 0.9.0', '0.8.0'],
+ ['*', null],
+ ['<1.0.0', null],
+ ['latest', null],
+ ['workspace:*', null],
+ ])('%s admits %s at the lowest', (range, lowest) => {
+ expect(lowestAdmitted(range)).toBe(lowest);
+ });
+});
+
+describe('docsTreeCliProblem', () => {
+ it('asks for a CLI peer when there is none', () => {
+ expect(docsTreeCliProblem({name: '@acme/kit'})).toContain(
+ 'declares no @astryxdesign/cli peer',
+ );
+ });
+
+ it.each(['^0.6.0', '^0.6.0 || >=0.7.0', '*', '>=0.6.3'])(
+ 'refuses %s, which admits a CLI that cannot read a namespace doc',
+ range => {
+ expect(
+ docsTreeCliProblem({peerDependencies: {'@astryxdesign/cli': range}}),
+ ).toContain('admits a CLI older than');
+ },
+ );
+
+ it.each(['>=0.7.0', '^0.7.2', '>=0.7.0 <2'])('accepts %s', range => {
+ expect(
+ docsTreeCliProblem({peerDependencies: {'@astryxdesign/cli': range}}),
+ ).toBeNull();
+ });
+
+ it('declares the peer as optional, and keeps what the package says of it', () => {
+ const declared = withDocsTreeCli({name: '@acme/kit'});
+ expect(declared.peerDependencies).toEqual({'@astryxdesign/cli': `>=${DOCS_TREE_CLI}`});
+ expect(declared.peerDependenciesMeta).toEqual({'@astryxdesign/cli': {optional: true}});
+ expect(docsTreeCliProblem(declared)).toBeNull();
+ const required = withDocsTreeCli({
+ peerDependencies: {react: '^19.0.0', '@astryxdesign/cli': '^0.6.0'},
+ peerDependenciesMeta: {'@astryxdesign/cli': {optional: false}},
+ });
+ expect(required.peerDependencies.react).toBe('^19.0.0');
+ expect(required.peerDependenciesMeta['@astryxdesign/cli']).toEqual({optional: false});
+ });
+});
+
+describe('replacesCliProblem', () => {
+ it('asks a package that sets replaces for a CLI that reads the field', () => {
+ expect(replacesCliProblem({name: '@acme/kit'})).toContain('sets `replaces`');
+ expect(replacesCliProblem({peerDependencies: {'@astryxdesign/cli': '^0.6.0'}})).toContain(
+ 'admits a CLI older than',
+ );
+ expect(replacesCliProblem({peerDependencies: {'@astryxdesign/cli': '>=0.7.0'}})).toBeNull();
+ });
+});
+
+describe('DOCS_TREE_CLI', () => {
+ it('is no later than the release the pending changesets make', () => {
+ const {version} = JSON.parse(
+ fs.readFileSync(path.join(CLI_ROOT, 'package.json'), 'utf-8'),
+ );
+ const dir = path.join(CLI_ROOT, '..', '..', '.changeset');
+ /** @type {Record<string, number>} */
+ const rank = {patch: 1, minor: 2, major: 3};
+ let bump = 0;
+ for (const file of fs.readdirSync(dir)) {
+ if (!file.endsWith('.md') || file === 'README.md') continue;
+ const head = fs.readFileSync(path.join(dir, file), 'utf-8').split('---')[1] ?? '';
+ const m = /['"]@astryxdesign\/cli['"]\s*:\s*(patch|minor|major)/.exec(head);
+ if (m) bump = Math.max(bump, rank[m[1]]);
+ }
+ const [major, minor, patch] = version.split('-')[0].split('.').map(Number);
+ const next =
+ bump === 3
+ ? `${major + 1}.0.0`
+ : bump === 2
+ ? `${major}.${minor + 1}.0`
+ : bump === 1
+ ? `${major}.${minor}.${patch + 1}`
+ : version;
+ // The first release that reads namespace docs is this one or an earlier
+ // one; a later constant would make every author wait for a CLI that does
+ // not exist yet.
+ expect(semverCompare(DOCS_TREE_CLI, next)).toBeLessThanOrEqual(0);
+ });
+});
diff --git a/packages/cli/foundation/integrations/contribution-inventory.mjs b/packages/cli/foundation/integrations/contribution-inventory.mjs
index 61dffc7dfe..47e60addd9 100644
--- a/packages/cli/foundation/integrations/contribution-inventory.mjs
+++ b/packages/cli/foundation/integrations/contribution-inventory.mjs
@@ -189,7 +189,7 @@ export function computeRequiredFiles(loaded) {
* @typedef {object} ContributionIdentities
* @property {{slug: string, exportName: string}[]} themes
* @property {string[]} components
- * @property {{id: string, type: string, name: string}[]} templates
+ * @property {{id: string, type: string, name: string, replaces?: string}[]} templates
* @property {{version: string, id: string}[]} codemods
* @property {string[]} docs
* @property {string[]} agentDocsAppend
@@ -278,7 +278,12 @@ export async function collectIdentities(loaded) {
errors.push({kind: 'templates', message: templateError.message});
}
identities.templates = templates
- .map(t => ({id: t.dirName, type: t.type, name: t.name}))
+ .map(t => ({
+ id: t.dirName,
+ type: t.type,
+ name: t.name,
+ ...(t.replaces == null ? {} : {replaces: t.replaces}),
+ }))
.sort((a, b) => a.id.localeCompare(b.id));
} catch (err) {
errors.push({
@@ -309,12 +314,13 @@ export async function collectIdentities(loaded) {
if (loaded.docs && fs.existsSync(loaded.docs)) {
try {
- const {records, errors: docErrors} =
+ const {records, guides, errors: docErrors} =
await discoverIntegrationDocs(loaded);
for (const docError of docErrors) {
errors.push({kind: 'docs', message: docError.message});
}
- identities.docs = records.map(r => r.name).sort();
+ // A guide placed in the docs tree is a doc contribution too.
+ identities.docs = [...records, ...guides].map(r => r.name).sort();
} catch (err) {
errors.push({kind: 'docs', message: /** @type {Error} */ (err).message});
}
diff --git a/packages/cli/foundation/integrations/contribution-inventory.test.mjs b/packages/cli/foundation/integrations/contribution-inventory.test.mjs
index 98bf4b78d6..ccfdefa7e5 100644
--- a/packages/cli/foundation/integrations/contribution-inventory.test.mjs
+++ b/packages/cli/foundation/integrations/contribution-inventory.test.mjs
@@ -304,6 +304,25 @@ describe('compareIdentities', () => {
expect(issues[0].message).toContain('dash');
});
+ it('errors when a packed template replaces a different target', () => {
+ const template = {id: 'acme-shell', type: 'page', name: 'Acme shell'};
+ const local = {
+ ...base(),
+ templates: [{...template, replaces: 'shell-side-nav'}],
+ };
+ const packed = {
+ ...base(),
+ templates: [{...template, replaces: 'shell-top-nav'}],
+ };
+
+ expect(compareIdentities(local, packed)).toEqual([
+ expect.objectContaining({
+ code: 'identity_mismatch',
+ message: expect.stringContaining('acme-shell'),
+ }),
+ ]);
+ });
+
it('errors when a codemod is missing from packed', () => {
const local = {
...base(),
diff --git a/packages/cli/foundation/integrations/integration-warnings.mjs b/packages/cli/foundation/integrations/integration-warnings.mjs
index 34702ba1d2..ffbf7b3ef7 100644
--- a/packages/cli/foundation/integrations/integration-warnings.mjs
+++ b/packages/cli/foundation/integrations/integration-warnings.mjs
@@ -10,8 +10,9 @@
* contributions or spamming per-contribution diagnostics.
*
* Design constraints (all enforced here):
- * - Reuses the Doctor integration validators (validateLoadedIntegration);
- * no validation logic is duplicated.
+ * - Reuses Project.issues() when a Project is available, so cross-package
+ * replacement warnings are visible; accepts loaded integrations for legacy
+ * internal callers and tests.
* - Writes to STDERR only, so it never corrupts a --json stdout envelope.
* - Suppressed entirely in --json mode.
* - Best-effort: never throws, never changes the exit code. Broken
@@ -28,38 +29,62 @@ import {validateLoadedIntegration} from './validate-contributions.mjs';
*
* Warning: <pkg> has N integration issue(s). Run: astryx doctor integration validate <pkg>
*
- * @param {Array<import('./integrations.mjs').LoadedIntegration>} loadedIntegrations the Project's loaded integrations
+ * @param {Array<import('./integrations.mjs').LoadedIntegration> | {issues: () => Promise<Array<{package: string, code: string, severity: string, message: string}>>}} source loaded integrations or their Project owner
* @param {{json?: boolean}} [options]
* @returns {Promise<void>}
*/
-export async function warnOnIntegrationIssues(loadedIntegrations, {json = false} = {}) {
+export async function warnOnIntegrationIssues(source, {json = false} = {}) {
try {
- // Cheap guard: only do work when integrations are actually configured.
if (json) return;
- if (!Array.isArray(loadedIntegrations) || loadedIntegrations.length === 0) {
- return;
- }
- for (const integration of loadedIntegrations) {
- if (!integration || typeof integration !== 'object') continue;
- // A package set aside for a provider-ID conflict is fine in isolation,
- // so `doctor integration validate` would not explain it. Say it here.
- if (integration.__providerConflict) {
- console.error(`Warning: ${integration.__providerConflict.message}`);
- continue;
+
+ /** @type {Map<string, number>} */
+ const issueCounts = new Map();
+ const fromProject =
+ source != null &&
+ !Array.isArray(source) &&
+ typeof source.issues === 'function';
+
+ if (fromProject) {
+ const issues = await source.issues();
+ for (const issue of issues) {
+ // A provider-conflict issue carries the specific message that
+ // `doctor integration validate` would not explain. Print it directly.
+ if (issue.code === 'duplicate_provider') {
+ console.error(`Warning: ${issue.message}`);
+ continue;
+ }
+ issueCounts.set(
+ issue.package,
+ (issueCounts.get(issue.package) ?? 0) + 1,
+ );
}
- let issues;
- try {
- issues = await validateLoadedIntegration(integration);
- } catch {
- // Best-effort: a validator throwing must not break the host command.
- continue;
+ } else if (Array.isArray(source)) {
+ for (const integration of source) {
+ if (!integration || typeof integration !== 'object') continue;
+ // A package set aside for a provider-ID conflict is fine in isolation,
+ // so `doctor integration validate` would not explain it. Say it here.
+ if (integration.__providerConflict) {
+ console.error(`Warning: ${integration.__providerConflict.message}`);
+ continue;
+ }
+ let issues;
+ try {
+ issues = await validateLoadedIntegration(integration);
+ } catch {
+ continue;
+ }
+ if (!Array.isArray(issues) || issues.length === 0) continue;
+ const pkg = integration.name ?? integration.__spec ?? '(integration)';
+ issueCounts.set(pkg, issues.length);
}
- if (!Array.isArray(issues) || issues.length === 0) continue;
- const pkg = integration.name ?? integration.__spec ?? '(integration)';
- // Stderr only — keeps stdout (and any --json envelope) clean.
+ }
+
+ for (const [pkg, count] of issueCounts) {
+ const command = fromProject
+ ? 'astryx doctor'
+ : `astryx doctor integration validate ${pkg}`;
console.error(
- `Warning: ${pkg} has ${issues.length} integration issue(s). ` +
- `Run: astryx doctor integration validate ${pkg}`,
+ `Warning: ${pkg} has ${count} integration issue(s). Run: ${command}`,
);
}
} catch {
diff --git a/packages/cli/foundation/integrations/integration-warnings.test.mjs b/packages/cli/foundation/integrations/integration-warnings.test.mjs
index 3ee7cedd46..536ffd3593 100644
--- a/packages/cli/foundation/integrations/integration-warnings.test.mjs
+++ b/packages/cli/foundation/integrations/integration-warnings.test.mjs
@@ -37,7 +37,12 @@ afterEach(() => {
* Build a loaded-integration-shaped object. Roots are absolute (mirrors
* loadIntegrations' resolveRoot).
*/
-function loaded({name = '@acme/widgets', components, templates, codemods} = {}) {
+function loaded({
+ name = '@acme/widgets',
+ components,
+ templates,
+ codemods,
+} = {}) {
return {
name,
version: '1.0.0',
@@ -62,6 +67,25 @@ describe('warnOnIntegrationIssues', () => {
);
});
+ it('surfaces cross-package issues collected by Project', async () => {
+ const project = {
+ issues: async () => [
+ {
+ package: '@acme/later',
+ code: 'ambiguous_template_replacement',
+ severity: 'warning',
+ message: 'Later configured replacement wins.',
+ },
+ ],
+ };
+
+ await warnOnIntegrationIssues(project, {json: false});
+
+ expect(errLines).toEqual([
+ 'Warning: @acme/later has 1 integration issue(s). Run: astryx doctor',
+ ]);
+ });
+
it('emits nothing in --json mode (keeps stdout/JSON clean)', async () => {
const integration = loaded({components: 'does-not-exist'});
await warnOnIntegrationIssues([integration], {json: true});
@@ -116,4 +140,53 @@ describe('warnOnIntegrationIssues', () => {
).resolves.toBeUndefined();
expect(errLines).toHaveLength(0);
});
+
+ it('prints the specific provider-conflict message via the array path', async () => {
+ const conflict = {
+ name: '@acme/charts',
+ version: '2.0.0',
+ __spec: '@acme/charts',
+ __packageDir: tmpDir,
+ __providerConflict: {
+ providerId: '@acme/lab',
+ claimedBy: '@acme/lab',
+ message:
+ '@acme/[email protected] and @acme/[email protected] both claim provider ID ' +
+ '"@acme/lab". @acme/[email protected] loads first and is used; ' +
+ '@acme/[email protected] contributes nothing until one package changes ' +
+ 'its providerId.',
+ },
+ };
+ await warnOnIntegrationIssues([conflict], {json: false});
+
+ expect(errLines).toHaveLength(1);
+ expect(errLines[0]).toBe(`Warning: ${conflict.__providerConflict.message}`);
+ // Must NOT print the generic validate pointer for a provider conflict.
+ expect(errLines[0]).not.toContain('integration issue(s)');
+ });
+
+ it('prints the specific provider-conflict message via the Project path', async () => {
+ const conflictMessage =
+ '@acme/[email protected] and @acme/[email protected] both claim provider ID ' +
+ '"@acme/lab". @acme/[email protected] loads first and is used; ' +
+ '@acme/[email protected] contributes nothing until one package changes ' +
+ 'its providerId.';
+ const project = {
+ issues: async () => [
+ {
+ package: '@acme/[email protected]',
+ code: 'duplicate_provider',
+ severity: 'warning',
+ message: conflictMessage,
+ },
+ ],
+ };
+
+ await warnOnIntegrationIssues(project, {json: false});
+
+ expect(errLines).toHaveLength(1);
+ expect(errLines[0]).toBe(`Warning: ${conflictMessage}`);
+ // Must NOT print the generic validate pointer for a provider conflict.
+ expect(errLines[0]).not.toContain('integration issue(s)');
+ });
});
diff --git a/packages/cli/foundation/integrations/validate-contributions.mjs b/packages/cli/foundation/integrations/validate-contributions.mjs
index ed7f8f7696..1aaf1cc79c 100644
--- a/packages/cli/foundation/integrations/validate-contributions.mjs
+++ b/packages/cli/foundation/integrations/validate-contributions.mjs
@@ -236,7 +236,11 @@ async function checkTemplates(integration, issues) {
try {
const {errors} = await discoverIntegrationTemplatesForOne(integration);
for (const e of errors) {
- issues.push(issueError('invalid_template', e.message));
+ issues.push({
+ code: e.code ?? 'invalid_template',
+ severity: e.severity ?? 'error',
+ message: e.message,
+ });
}
} catch (err) {
issues.push(
@@ -246,41 +250,35 @@ async function checkTemplates(integration, issues) {
}
/**
- * Validate the integration's components via the landed ownership discovery.
- * Feature-detected: if the component-ownership export isn't present in this
- * build (sibling PR not yet merged), component validation is skipped rather
- * than hard-failing.
- *
- * `discoverIntegrationComponents` returns ownership records and does not throw
- * on a missing same-stem source — it records `sourcePath: null`. We surface
- * each such record as an `invalid_component` error.
+ * Validate the integration's components through the same load-and-parse boundary
+ * that component detail uses. Missing source and invalid metadata are reported
+ * per component so valid siblings remain available.
* @param {LoadedIntegration} integration loaded-integration-shaped object
* @param {Issue[]} issues
*/
async function checkComponents(integration, issues) {
if (!integration.components || !fs.existsSync(integration.components)) return;
- const discover = componentDiscovery.discoverIntegrationComponents;
+ const discover = componentDiscovery.discoverValidIntegrationComponents;
if (typeof discover !== 'function') return; // feature not present yet
try {
- const records = (await discover(integration)) ?? [];
+ const {discovered, errors} = await discover(integration);
/** @type {import('./contribution-fixes.mjs').FixContext | undefined} */
let context;
- for (const record of records) {
- if (record?.sourcePath == null) {
- const docPath = record?.docPath;
- let fix = `Fix: add ${record?.name}.tsx beside ${docPath ? path.basename(docPath) : `${record?.name}.doc.mjs`}.`;
- const stamp = docPath ? readContributionStamp(docPath, false) : null;
- if (stamp && stamp.type !== 'component' && integration.__packageDir) {
- context ??= createFixContext(integration.__packageDir, integration);
- fix = notAComponentFix(context, docPath, stamp);
- }
- issues.push(
- issueError(
- 'invalid_component',
- `Component "${record?.name}" is missing its same-stem source file ${record?.name}.tsx. ${fix}`,
- ),
- );
+ const byName = new Map(discovered.map(record => [record.name, record]));
+ for (const error of errors) {
+ const record = byName.get(error.name);
+ if (record == null || record.sourcePath != null) {
+ issues.push(issueError('invalid_component', error.message));
+ continue;
+ }
+ const docPath = record.docPath;
+ let fix = `Fix: add ${record.name}.tsx beside ${docPath ? path.basename(docPath) : `${record.name}.doc.mjs`}.`;
+ const stamp = docPath ? readContributionStamp(docPath, false) : null;
+ if (stamp && stamp.type !== 'component' && integration.__packageDir) {
+ context ??= createFixContext(integration.__packageDir, integration);
+ fix = notAComponentFix(context, docPath, stamp);
}
+ issues.push(issueError('invalid_component', `${error.message} ${fix}`));
}
const overlap = integration.__packageDir
? newComponentDocNote(
@@ -289,7 +287,7 @@ async function checkComponents(integration, issues) {
: '';
for (const name of findSourceOnlyCandidates(
integration.components,
- records.map(record => record.name),
+ discovered.map(record => record.name),
)) {
// A hidden doc still pairs with its source; discovery just skips it.
if (
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 8b738b9d68..c13235accb 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -61,22 +61,27 @@ export const doc = {
{
value: 'docs.list',
description:
- 'All reference-doc topics as DocsListEntry[] ({topic, description}), in discovery order.',
+ '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.',
},
{
value: 'docs.detail',
description:
- "One topic's full ReferenceDoc, with token-ref blocks inlined.",
+ "One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there).",
},
{
value: 'docs.index',
description:
- "One topic's section index (--index): the topic's name, title, and description, plus sections, each {id, title, summary} (pass the id as the section argument; summary is the section's one-line summary).",
+ "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, summary} (pass the id as the section argument; 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).",
},
{
value: 'docs.detail.section',
description:
- 'One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined.',
+ '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).',
+ },
+ {
+ value: 'docs.node',
+ description:
+ "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) 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 (read from the published RSS feed)
@@ -116,7 +121,7 @@ export const doc = {
{
value: 'search',
description:
- 'The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, score, reason, description, command}, plus import (components, hooks), title (docs), or displayName and kind (templates).',
+ 'The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, score, reason, description, command}, plus import (components, hooks), title, parent (the command that opens the level above), package (for a docs-tree hit), and, for a hit on one section, section (docs), or displayName and kind (templates).',
},
// build
@@ -158,7 +163,7 @@ export const doc = {
{
value: 'template.list',
description:
- 'Every discovered template (page + block); each entry carries id, name, description, kind, owning package, optional category and componentsUsed, and readiness flags.',
+ 'The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list.',
},
{
value: 'template.show',
@@ -286,7 +291,7 @@ export const doc = {
{
value: 'integration.template-conflicts',
description:
- 'The integration identity, structural issues, and non-blocking conflicts where an integration template id is also owned by Core; each conflict includes the exact package-qualified command.',
+ 'The integration identity, issues, and conflicts as {severity: info | warning, relationship: replaces | accidental, replaces?, command}.',
},
{
value: 'integration.component-conflicts',
@@ -296,7 +301,7 @@ export const doc = {
{
value: 'integration.doc-conflicts',
description:
- 'The integration identity, structural issues, and Core doc overlaps classified as intentional replacements, intentional extensions, or accidental same-name conflicts.',
+ 'The integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` | `error`) and `relationship` (`replaces` | `extends` | `accidental`).',
},
// layout (XLE/XLO)
diff --git a/packages/cli/foundation/xle/expand.mjs b/packages/cli/foundation/xle/expand.mjs
index c1e064e885..7df2b8a2a2 100644
--- a/packages/cli/foundation/xle/expand.mjs
+++ b/packages/cli/foundation/xle/expand.mjs
@@ -545,7 +545,7 @@ class Emitter {
const flags = hint.flags.length > 0 ? ` (+${hint.flags.join(' +')})` : '';
const arg = hint.arg ? `:${hint.arg}` : '';
return [
- `${pad}{/* TODO(xle): content block '${hint.block.name}'${flags}${arg} — scaffold it with: astryx template ${hint.block.name} */}`,
+ `${pad}{/* TODO(xle): content block '${hint.block.name}'${flags}${arg} — scaffold it with: astryx template ${hint.block.name} --type block */}`,
];
}
this.todos.push(`unresolved hint {${hint.name}}`);
diff --git a/packages/cli/foundation/xle/xle.test.mjs b/packages/cli/foundation/xle/xle.test.mjs
index ae11902344..997bfb42af 100644
--- a/packages/cli/foundation/xle/xle.test.mjs
+++ b/packages/cli/foundation/xle/xle.test.mjs
@@ -10,6 +10,7 @@ import {describe, it, expect} from 'vitest';
import {parse, parseCompact, parseOutline, detectForm, XLEParseError} from './parse.mjs';
import {toCompact, toOutline} from './print.mjs';
import {validate} from './validate.mjs';
+import {expand} from './expand.mjs';
import {parseEnumValues, SPACING_STEPS} from './registry.mjs';
// ─── parser: compact ───────────────────────────────────────────────────────
@@ -309,6 +310,18 @@ describe('validate', () => {
expect(doc.roots[0].hint.block.name).toBe('CardCallout');
});
+ it('includes --type block when a known block source is unavailable', () => {
+ const doc = parse('Bx{card-callout}');
+ expect(validate(doc, registry, BLOCKS).errors).toEqual([]);
+ const result = expand(doc, registry, {
+ componentName: 'Demo',
+ blockModules: new Map(),
+ });
+ expect(result.code).toContain(
+ 'astryx template CardCallout --type block',
+ );
+ });
+
it('enforces structural pairings', () => {
const doc = parse('Bx > Sh');
const {errors} = validate(doc, registry, BLOCKS);
diff --git a/packages/cli/test/__golden__/docs-index.txt b/packages/cli/test/__golden__/docs-index.txt
index c125981495..d716252435 100644
--- a/packages/cli/test/__golden__/docs-index.txt
+++ b/packages/cli/test/__golden__/docs-index.txt
@@ -5,4 +5,6 @@ start Start - Install the kit.
colors Colors - Cards use the core tokens.
Read one section: pnpm exec astryx docs acme-guide <section>
-Read everything: pnpm exec astryx docs acme-guide
+Read everything: pnpm exec astryx docs acme-guide --full
+Up: pnpm exec astryx docs unorganized
+Previous: pnpm exec astryx docs working-with-ai
diff --git a/packages/cli/test/__golden__/docs-list.json b/packages/cli/test/__golden__/docs-list.json
index 6bfa10e584..e784dea173 100644
--- a/packages/cli/test/__golden__/docs-list.json
+++ b/packages/cli/test/__golden__/docs-list.json
@@ -7,5 +7,19 @@
"description": "How zorblax cards fit together.",
"package": "@acme/kit"
}
- ]
+ ],
+ "meta": {
+ "namespaces": [
+ {
+ "topic": "cli",
+ "description": "Commands, programmatic APIs, integration authoring, and output contracts.",
+ "package": "@astryxdesign/cli"
+ },
+ {
+ "topic": "unorganized",
+ "description": "Every topic that no section places yet. Each keeps its own name; open one by it.",
+ "package": "@astryxdesign/cli"
+ }
+ ]
+ }
}
diff --git a/packages/cli/test/__golden__/docs-section.json b/packages/cli/test/__golden__/docs-section.json
index c57e99ab03..88ed522b83 100644
--- a/packages/cli/test/__golden__/docs-section.json
+++ b/packages/cli/test/__golden__/docs-section.json
@@ -13,6 +13,10 @@
"text": "[token-ref: unknown topic \"no-such-topic\"]"
}
],
- "id": "colors"
+ "id": "colors",
+ "links": {
+ "up": "astryx docs acme-guide --index",
+ "previous": "astryx docs acme-guide start"
+ }
}
}
diff --git a/packages/cli/test/__golden__/docs-topic-text.txt b/packages/cli/test/__golden__/docs-topic-text.txt
index 7ace5a8627..3439206e3c 100644
--- a/packages/cli/test/__golden__/docs-topic-text.txt
+++ b/packages/cli/test/__golden__/docs-topic-text.txt
@@ -11,3 +11,6 @@ Install the kit.
Cards use the core tokens.
[token-ref: unknown topic "no-such-topic"]
+
+Up: pnpm exec astryx docs unorganized
+Previous: pnpm exec astryx docs working-with-ai
diff --git a/packages/cli/test/__golden__/docs-topic.json b/packages/cli/test/__golden__/docs-topic.json
index 7cfb5cadf6..bee517996f 100644
--- a/packages/cli/test/__golden__/docs-topic.json
+++ b/packages/cli/test/__golden__/docs-topic.json
@@ -31,6 +31,10 @@
],
"id": "colors"
}
- ]
+ ],
+ "links": {
+ "up": "astryx docs unorganized",
+ "previous": "astryx docs working-with-ai"
+ }
}
}
diff --git a/packages/cli/test/__golden__/search.json b/packages/cli/test/__golden__/search.json
index a06163ed8f..1cd71aef35 100644
--- a/packages/cli/test/__golden__/search.json
+++ b/packages/cli/test/__golden__/search.json
@@ -20,8 +20,10 @@
"score": 50,
"reason": "description mentions \"zorblax\"",
"description": "How zorblax cards fit together.",
- "title": "Acme guide",
- "command": "astryx docs acme-guide"
+ "title": "Unorganized › Acme guide",
+ "command": "astryx docs acme-guide --index",
+ "parent": "astryx docs unorganized",
+ "package": "@acme/kit"
},
{
"domain": "template",
@@ -31,7 +33,7 @@
"description": "A zorblax hero block.",
"displayName": "Zorblax hero",
"kind": "block",
- "command": "astryx template hero"
+ "command": "astryx template hero --type block"
}
]
}
diff --git a/packages/cli/test/authoring-types/reference-content-block.exhaustive.ts b/packages/cli/test/authoring-types/reference-content-block.exhaustive.ts
new file mode 100644
index 0000000000..ad6e61785f
--- /dev/null
+++ b/packages/cli/test/authoring-types/reference-content-block.exhaustive.ts
@@ -0,0 +1,31 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * The published ReferenceContentBlock union keeps its six members: every
+ * exhaustive renderer written against it would break if one were added or
+ * removed. This switch is such a renderer, so `typecheck:authoring` fails the
+ * moment the union changes. Graph-only blocks live in GraphContentBlock.
+ */
+
+import type {ReferenceContentBlock} from '@astryxdesign/cli/authoring';
+
+export function renderBlock(block: ReferenceContentBlock): string {
+ switch (block.type) {
+ case 'prose':
+ return block.text;
+ case 'heading':
+ return block.text;
+ case 'code':
+ return block.code;
+ case 'table':
+ return block.headers.join(' | ');
+ case 'list':
+ return block.items.join('\n');
+ case 'token-ref':
+ return `${block.topic} / ${block.section}`;
+ default: {
+ const unhandled: never = block;
+ return unhandled;
+ }
+ }
+}
diff --git a/packages/cli/test/cli-integrations-doc-drift.test.mjs b/packages/cli/test/cli-integrations-doc-drift.test.mjs
index 1218c32aaa..6497b9c7f6 100644
--- a/packages/cli/test/cli-integrations-doc-drift.test.mjs
+++ b/packages/cli/test/cli-integrations-doc-drift.test.mjs
@@ -9,7 +9,7 @@
*/
import {afterEach, beforeEach, describe, it, expect} from 'vitest';
-import {docs as integrationGuide} from '../assets/docs/cli-integrations.doc.mjs';
+import {docs as integrationGuide} from '../assets/docs/tree/integrations.doc.mjs';
import {doc as upgradeCommandDoc} from '../clients/cli/commands/upgrade.doc.mjs';
import {doc as upgradeFnDoc} from '../api/upgrade/upgrade.doc.mjs';
import {doc as paletteGenerateDoc} from '../clients/cli/commands/theme-palette-generate.doc.mjs';
diff --git a/packages/cli/test/doc-routes.json b/packages/cli/test/doc-routes.json
index 6a663c59d7..3a6ebc1eef 100644
--- a/packages/cli/test/doc-routes.json
+++ b/packages/cli/test/doc-routes.json
@@ -1,6 +1,6 @@
{
"about": [
- "Every current doc route with a PROPOSED docs-graph placement. The docs graph spec is not decided; nothing here moves anything, and doc-routes.test.mjs fails when a current route has no row, a row names a route that no longer exists, or a row breaks the placement rules below.",
+ "Every current doc route with its docs-tree placement. The CLI's own docs are placed (spec:AST-046, phase 1): the namespace rows and the command, function, and enum rows say where the tree puts them, and (d) checks it. Every other row is still a PROPOSED placement that moves nothing. doc-routes.test.mjs fails when a current route has no row, a row names a route that no longer exists, or a row breaks the placement rules below.",
"Rows: one per built-in topic (`astryx docs <topic>`) and per section key (`astryx docs <topic> <key>`); typed descriptors take one row per provider and kind, with `count` and the ids in doc-routes.ids.json under the row id. Placeholders <id> expand per id. Per-item rows would repeat one decision per group hundreds of times (704 templates alone).",
"placement: keep-flat (the route stays where it is), namespace:<path> (the doc becomes <path> in the graph), or generated:<provider>/<kind> (the unorganized bucket for typed descriptors that author no placement). Anything but keep-flat carries a one-line evidence note, and a namespace must be decided `create` under namespaces.",
"aliasNeeded: true when the proposal leaves the old CLI route or docsite URL without its content unless an alias keeps it resolving. Sections move with their topic.",
@@ -11,8 +11,14 @@
{
"name": "cli",
"decision": "create",
- "evidence": "cli-integrations documents the CLI's integration surface (see its row), and the NamespaceDoc contract's own example is a 'cli' namespace for commands, APIs and integration authoring.",
- "note": "`astryx docs cli` is the namespace's first reader: every doc whose namespace is cli/commands or cli/api, one section each. /docs/cli is still the @astryxdesign/cli package page on the docsite; the namespace page must take that URL before the docsite publishes it. Considered and left out: authoring, whose section docs declare namespace 'authoring', a sibling of 'cli' in the SchemaDoc contract."
+ "evidence": "cli/integrations documents the CLI's integration surface (see its row), and the NamespaceDoc contract's own example is a 'cli' namespace for commands, APIs and integration authoring.",
+ "note": "`astryx docs cli` reads the docs tree (spec:AST-046): its guides and the commands and api namespaces, one level at a time. /docs/cli is still the @astryxdesign/cli package page on the docsite; the namespace page must take that URL before the docsite publishes it. Considered and left out: authoring, whose section docs declare namespace 'authoring', a sibling of 'cli' in the SchemaDoc contract."
+ },
+ {
+ "name": "unorganized",
+ "decision": "create",
+ "evidence": "Every flat topic had no home in the tree: no parent, no breadcrumb, and Up went back to the topic list.",
+ "note": "The docs tree generates it (spec:AST-046 FR12). Each topic keeps its own name, so no route changes; the proposed placements in the rows below move topics out of it into real sections."
},
{
"name": "foundations",
@@ -222,1117 +228,424 @@
"status": "proposed"
},
{
- "kind": "topic",
+ "kind": "namespace",
"id": "cli",
"oldCliRoute": "astryx docs cli",
"oldDocsiteUrl": null,
"placement": "namespace:cli",
"aliasNeeded": false,
- "evidence": "Built from every doc whose namespace is cli/commands or cli/api; astryx doctor fails on a CLI doc with no namespace or one no topic reads.",
- "rationale": "The cli namespace page: one section per command, API function, output schema, and enum doc the CLI ships, keyed commands-<name> and api-<name>. The docsite does not publish it yet, because /docs/cli is the @astryxdesign/cli package page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#commands-blog",
- "oldCliRoute": "astryx docs cli commands-blog",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `blog` (command row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#commands-build",
- "oldCliRoute": "astryx docs cli commands-build",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `build` (command row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#commands-component",
- "oldCliRoute": "astryx docs cli commands-component",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `component` (command row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#commands-discover",
- "oldCliRoute": "astryx docs cli commands-discover",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `discover` (command row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#commands-docs",
- "oldCliRoute": "astryx docs cli commands-docs",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `docs` (command row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#commands-doctor",
- "oldCliRoute": "astryx docs cli commands-doctor",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `doctor` (command row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#commands-doctor-integration",
- "oldCliRoute": "astryx docs cli commands-doctor-integration",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `doctor integration` (command row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#commands-doctor-integration-components",
- "oldCliRoute": "astryx docs cli commands-doctor-integration-components",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `doctor integration components` (command row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#commands-doctor-integration-docs",
- "oldCliRoute": "astryx docs cli commands-doctor-integration-docs",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `doctor integration docs` (command row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#commands-doctor-integration-templates",
- "oldCliRoute": "astryx docs cli commands-doctor-integration-templates",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `doctor integration templates` (command row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#commands-doctor-integration-validate",
- "oldCliRoute": "astryx docs cli commands-doctor-integration-validate",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `doctor integration validate` (command row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#commands-gap-report",
- "oldCliRoute": "astryx docs cli commands-gap-report",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `gap-report` (command row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#commands-hook",
- "oldCliRoute": "astryx docs cli commands-hook",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `hook` (command row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#commands-init",
- "oldCliRoute": "astryx docs cli commands-init",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `init` (command row), read as one section of the cli namespace page.",
+ "evidence": "assets/docs/tree/cli.doc.mjs declares it; astryx doctor fails when the tree does not build or a CLI doc in a cli group has no route.",
+ "rationale": "The top of the CLI docs tree: its guides (cli/integrations, cli/writing-docs) and its reference (cli/commands and cli/api), one level at a time. The docsite does not publish it yet, because /docs/cli is the @astryxdesign/cli package page.",
"status": "proposed"
},
{
- "kind": "section",
- "id": "cli#commands-integration",
- "oldCliRoute": "astryx docs cli commands-integration",
+ "kind": "namespace",
+ "id": "cli/commands",
+ "oldCliRoute": "astryx docs cli/commands",
"oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "placement": "namespace:cli/commands",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `integration` (command row), read as one section of the cli namespace page.",
+ "evidence": "assets/docs/tree/commands.doc.mjs declares it.",
+ "rationale": "Adopts every command doc whose namespace is cli/commands, one leaf each at cli/commands/<name>. The docsite does not publish it yet.",
"status": "proposed"
},
{
- "kind": "section",
- "id": "cli#commands-integration-add",
- "oldCliRoute": "astryx docs cli commands-integration-add",
+ "kind": "namespace",
+ "id": "cli/api",
+ "oldCliRoute": "astryx docs cli/api",
"oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "placement": "namespace:cli/api",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `integration add` (command row), read as one section of the cli namespace page.",
+ "evidence": "assets/docs/tree/api.doc.mjs declares it.",
+ "rationale": "Adopts every function, schema, and enum doc whose namespace is cli/api, one generated level per kind. The docsite does not publish it yet.",
"status": "proposed"
},
{
- "kind": "section",
- "id": "cli#commands-integration-pack",
- "oldCliRoute": "astryx docs cli commands-integration-pack",
+ "kind": "namespace",
+ "id": "cli/api/functions",
+ "oldCliRoute": "astryx docs cli/api/functions",
"oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "placement": "namespace:cli/api/functions",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `integration pack` (command row), read as one section of the cli namespace page.",
+ "evidence": "The api namespace adopts cli/api with groupBy kind.",
+ "rationale": "Generated by the api namespace for its function docs, one leaf each at cli/api/functions/<name>. The docsite does not publish it yet.",
"status": "proposed"
},
{
- "kind": "section",
- "id": "cli#commands-layout",
- "oldCliRoute": "astryx docs cli commands-layout",
+ "kind": "namespace",
+ "id": "cli/api/schemas",
+ "oldCliRoute": "astryx docs cli/api/schemas",
"oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "placement": "namespace:cli/api/schemas",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `layout` (command row), read as one section of the cli namespace page.",
+ "evidence": "The api namespace adopts cli/api with groupBy kind.",
+ "rationale": "Generated by the api namespace for its schema docs (the JSON output envelope). The docsite does not publish it yet.",
"status": "proposed"
},
{
- "kind": "section",
- "id": "cli#commands-layout-check",
- "oldCliRoute": "astryx docs cli commands-layout-check",
+ "kind": "namespace",
+ "id": "cli/api/enums",
+ "oldCliRoute": "astryx docs cli/api/enums",
"oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "placement": "namespace:cli/api/enums",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `layout check` (command row), read as one section of the cli namespace page.",
+ "evidence": "The api namespace adopts cli/api with groupBy kind.",
+ "rationale": "Generated by the api namespace for its enum docs (error codes and response types). The docsite does not publish it yet.",
"status": "proposed"
},
{
- "kind": "section",
- "id": "cli#commands-layout-expand",
- "oldCliRoute": "astryx docs cli commands-layout-expand",
+ "kind": "namespace",
+ "id": "unorganized",
+ "oldCliRoute": "astryx docs unorganized",
"oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "placement": "namespace:unorganized",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `layout expand` (command row), read as one section of the cli namespace page.",
+ "evidence": "The docs tree generates it: every flat topic sits in it, in the order the topic list reads.",
+ "rationale": "The home of every topic that no section places yet. Each keeps its own name, so no route changes; placing a topic in a real section takes it out.",
"status": "proposed"
},
{
- "kind": "section",
- "id": "cli#commands-layout-grammar",
- "oldCliRoute": "astryx docs cli commands-layout-grammar",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "kind": "topic",
+ "id": "browser-support",
+ "oldCliRoute": "astryx docs browser-support",
+ "oldDocsiteUrl": "/docs/browser-support",
+ "placement": "keep-flat",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `layout grammar` (command row), read as one section of the cli namespace page.",
+ "rationale": "Standalone guide: no topic links to it, and nothing authored places it under another topic.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#commands-manifest",
- "oldCliRoute": "astryx docs cli commands-manifest",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "browser-support#overview",
+ "oldCliRoute": "astryx docs browser-support overview",
+ "oldDocsiteUrl": "/docs/browser-support#overview",
+ "placement": "keep-flat",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `manifest` (command row), read as one section of the cli namespace page.",
+ "rationale": "Stays a section of browser-support under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#commands-search",
- "oldCliRoute": "astryx docs cli commands-search",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "browser-support#support-tiers",
+ "oldCliRoute": "astryx docs browser-support support-tiers",
+ "oldDocsiteUrl": "/docs/browser-support#support-tiers",
+ "placement": "keep-flat",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `search` (command row), read as one section of the cli namespace page.",
+ "rationale": "Stays a section of browser-support under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#commands-swizzle",
- "oldCliRoute": "astryx docs cli commands-swizzle",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "browser-support#which-features-set-the-floor",
+ "oldCliRoute": "astryx docs browser-support which-features-set-the-floor",
+ "oldDocsiteUrl": "/docs/browser-support#which-features-set-the-floor",
+ "placement": "keep-flat",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `swizzle` (command row), read as one section of the cli namespace page.",
+ "rationale": "Stays a section of browser-support under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#commands-template",
- "oldCliRoute": "astryx docs cli commands-template",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "browser-support#which-components-are-affected",
+ "oldCliRoute": "astryx docs browser-support which-components-are-affected",
+ "oldDocsiteUrl": "/docs/browser-support#which-components-are-affected",
+ "placement": "keep-flat",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `template` (command row), read as one section of the cli namespace page.",
+ "rationale": "Stays a section of browser-support under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#commands-theme",
- "oldCliRoute": "astryx docs cli commands-theme",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "browser-support#what-astryx-guarantees",
+ "oldCliRoute": "astryx docs browser-support what-astryx-guarantees",
+ "oldDocsiteUrl": "/docs/browser-support#what-astryx-guarantees",
+ "placement": "keep-flat",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `theme` (command row), read as one section of the cli namespace page.",
+ "rationale": "Stays a section of browser-support under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#commands-theme-add",
- "oldCliRoute": "astryx docs cli commands-theme-add",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "browser-support#supporting-older-browsers",
+ "oldCliRoute": "astryx docs browser-support supporting-older-browsers",
+ "oldDocsiteUrl": "/docs/browser-support#supporting-older-browsers",
+ "placement": "keep-flat",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `theme add` (command row), read as one section of the cli namespace page.",
+ "rationale": "Stays a section of browser-support under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#commands-theme-build",
- "oldCliRoute": "astryx docs cli commands-theme-build",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "browser-support#how-these-tiers-move-over-time",
+ "oldCliRoute": "astryx docs browser-support how-these-tiers-move-over-time",
+ "oldDocsiteUrl": "/docs/browser-support#how-these-tiers-move-over-time",
+ "placement": "keep-flat",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `theme build` (command row), read as one section of the cli namespace page.",
+ "rationale": "Stays a section of browser-support under the same key.",
"status": "proposed"
},
{
- "kind": "section",
- "id": "cli#commands-theme-list",
- "oldCliRoute": "astryx docs cli commands-theme-list",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "kind": "topic",
+ "id": "cli/integrations",
+ "oldCliRoute": "astryx docs cli/integrations",
+ "oldDocsiteUrl": "/docs/cli-integrations",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `theme list` (command row), read as one section of the cli namespace page.",
+ "evidence": "It places itself: placement {parent: 'namespace:cli', slot: 'guides'}. Its subject is the CLI's integration surface: 10 of its 14 sections drive `astryx integration add|pack`, `astryx doctor integration ...`, `astryx init` or `astryx upgrade`.",
+ "rationale": "Guide for integration authors, read only by its route. `astryx docs cli-integrations` is gone: every reference now names cli/integrations. The docsite keeps /docs/cli-integrations (its route with \"/\" as \"-\") until the site renders the tree.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#commands-theme-palette",
- "oldCliRoute": "astryx docs cli commands-theme-palette",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/integrations#overview",
+ "oldCliRoute": "astryx docs cli/integrations overview",
+ "oldDocsiteUrl": "/docs/cli-integrations#overview",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `theme palette` (command row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#commands-theme-palette-generate",
- "oldCliRoute": "astryx docs cli commands-theme-palette-generate",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/integrations#authoring-with-the-cli",
+ "oldCliRoute": "astryx docs cli/integrations authoring-with-the-cli",
+ "oldDocsiteUrl": "/docs/cli-integrations#authoring-with-the-cli",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `theme palette generate` (command row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#commands-theme-targets",
- "oldCliRoute": "astryx docs cli commands-theme-targets",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/integrations#theme-package-walkthrough",
+ "oldCliRoute": "astryx docs cli/integrations theme-package-walkthrough",
+ "oldDocsiteUrl": "/docs/cli-integrations#theme-package-walkthrough",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `theme targets` (command row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#commands-theme-template",
- "oldCliRoute": "astryx docs cli commands-theme-template",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/integrations#contribution-kinds-at-a-glance",
+ "oldCliRoute": "astryx docs cli/integrations contribution-kinds-at-a-glance",
+ "oldDocsiteUrl": "/docs/cli-integrations#contribution-kinds-at-a-glance",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `theme template` (command row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#commands-upgrade",
- "oldCliRoute": "astryx docs cli commands-upgrade",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/integrations#the-integration-file",
+ "oldCliRoute": "astryx docs cli/integrations the-integration-file",
+ "oldDocsiteUrl": "/docs/cli-integrations#the-integration-file",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/commands.",
- "rationale": "The command doc `upgrade` (command row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-assert-response",
- "oldCliRoute": "astryx docs cli api-assert-response",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/integrations#components",
+ "oldCliRoute": "astryx docs cli/integrations components",
+ "oldDocsiteUrl": "/docs/cli-integrations#components",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `assertResponse` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-blog",
- "oldCliRoute": "astryx docs cli api-blog",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/integrations#templates",
+ "oldCliRoute": "astryx docs cli/integrations templates",
+ "oldDocsiteUrl": "/docs/cli-integrations#templates",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `blog` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-build",
- "oldCliRoute": "astryx docs cli api-build",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/integrations#docs",
+ "oldCliRoute": "astryx docs cli/integrations docs",
+ "oldDocsiteUrl": "/docs/cli-integrations#docs",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `build` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-component",
- "oldCliRoute": "astryx docs cli api-component",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/integrations#themes",
+ "oldCliRoute": "astryx docs cli/integrations themes",
+ "oldDocsiteUrl": "/docs/cli-integrations#themes",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `component` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-discover",
- "oldCliRoute": "astryx docs cli api-discover",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/integrations#agent-docs",
+ "oldCliRoute": "astryx docs cli/integrations agent-docs",
+ "oldDocsiteUrl": "/docs/cli-integrations#agent-docs",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `discover` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-docs",
- "oldCliRoute": "astryx docs cli api-docs",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/integrations#codemods",
+ "oldCliRoute": "astryx docs cli/integrations codemods",
+ "oldDocsiteUrl": "/docs/cli-integrations#codemods",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `docs` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-doctor",
- "oldCliRoute": "astryx docs cli api-doctor",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/integrations#recording-runs",
+ "oldCliRoute": "astryx docs cli/integrations recording-runs",
+ "oldDocsiteUrl": "/docs/cli-integrations#recording-runs",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `doctor` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-gap-report",
- "oldCliRoute": "astryx docs cli api-gap-report",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/integrations#gap-report-handler",
+ "oldCliRoute": "astryx docs cli/integrations gap-report-handler",
+ "oldDocsiteUrl": "/docs/cli-integrations#gap-report-handler",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `gapReport` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-generate-tonal-palette",
- "oldCliRoute": "astryx docs cli api-generate-tonal-palette",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/integrations#how-it-works",
+ "oldCliRoute": "astryx docs cli/integrations how-it-works",
+ "oldDocsiteUrl": "/docs/cli-integrations#how-it-works",
+ "placement": "namespace:cli/integrations",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `generateTonalPalette` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
{
- "kind": "section",
- "id": "cli#api-hook",
- "oldCliRoute": "astryx docs cli api-hook",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "kind": "topic",
+ "id": "cli/writing-docs",
+ "oldCliRoute": "astryx docs cli/writing-docs",
+ "oldDocsiteUrl": "/docs/cli-writing-docs",
+ "placement": "namespace:cli/writing-docs",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `hook` (function row), read as one section of the cli namespace page.",
+ "evidence": "It places itself: placement {parent: 'namespace:cli', slot: 'guides', order: 20}.",
+ "rationale": "Guide to writing docs in the docs graph: homes, links by identity, short reads, search, and the doctor checks. New in this change, so it has no older route.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-init",
- "oldCliRoute": "astryx docs cli api-init",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/writing-docs#how-the-docs-work",
+ "oldCliRoute": "astryx docs cli/writing-docs how-the-docs-work",
+ "oldDocsiteUrl": "/docs/cli-writing-docs#how-the-docs-work",
+ "placement": "namespace:cli/writing-docs",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `init` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/writing-docs.",
+ "rationale": "A section of cli/writing-docs: How the docs work.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-integration-add",
- "oldCliRoute": "astryx docs cli api-integration-add",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/writing-docs#add-a-doc",
+ "oldCliRoute": "astryx docs cli/writing-docs add-a-doc",
+ "oldDocsiteUrl": "/docs/cli-writing-docs#add-a-doc",
+ "placement": "namespace:cli/writing-docs",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `integrationAdd` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/writing-docs.",
+ "rationale": "A section of cli/writing-docs: Add a doc.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-integration-add-agent-doc",
- "oldCliRoute": "astryx docs cli api-integration-add-agent-doc",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/writing-docs#place-a-doc",
+ "oldCliRoute": "astryx docs cli/writing-docs place-a-doc",
+ "oldDocsiteUrl": "/docs/cli-writing-docs#place-a-doc",
+ "placement": "namespace:cli/writing-docs",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `integrationAddAgentDoc` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/writing-docs.",
+ "rationale": "A section of cli/writing-docs: Place a doc.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-integration-add-codemod",
- "oldCliRoute": "astryx docs cli api-integration-add-codemod",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/writing-docs#link-docs",
+ "oldCliRoute": "astryx docs cli/writing-docs link-docs",
+ "oldDocsiteUrl": "/docs/cli-writing-docs#link-docs",
+ "placement": "namespace:cli/writing-docs",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `integrationAddCodemod` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/writing-docs.",
+ "rationale": "A section of cli/writing-docs: Link docs.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-integration-add-component",
- "oldCliRoute": "astryx docs cli api-integration-add-component",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/writing-docs#keep-reads-short",
+ "oldCliRoute": "astryx docs cli/writing-docs keep-reads-short",
+ "oldDocsiteUrl": "/docs/cli-writing-docs#keep-reads-short",
+ "placement": "namespace:cli/writing-docs",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `integrationAddComponent` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/writing-docs.",
+ "rationale": "A section of cli/writing-docs: Keep reads short.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-integration-add-doc",
- "oldCliRoute": "astryx docs cli api-integration-add-doc",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/writing-docs#make-docs-findable",
+ "oldCliRoute": "astryx docs cli/writing-docs make-docs-findable",
+ "oldDocsiteUrl": "/docs/cli-writing-docs#make-docs-findable",
+ "placement": "namespace:cli/writing-docs",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `integrationAddDoc` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/writing-docs.",
+ "rationale": "A section of cli/writing-docs: Make docs findable.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-integration-add-template",
- "oldCliRoute": "astryx docs cli api-integration-add-template",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/writing-docs#docs-from-an-integration",
+ "oldCliRoute": "astryx docs cli/writing-docs docs-from-an-integration",
+ "oldDocsiteUrl": "/docs/cli-writing-docs#docs-from-an-integration",
+ "placement": "namespace:cli/writing-docs",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `integrationAddTemplate` (function row), read as one section of the cli namespace page.",
+ "evidence": "Moves with cli/writing-docs.",
+ "rationale": "A section of cli/writing-docs: Docs from an integration.",
"status": "proposed"
},
{
"kind": "section",
- "id": "cli#api-integration-add-theme",
- "oldCliRoute": "astryx docs cli api-integration-add-theme",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
+ "id": "cli/writing-docs#check-your-docs",
+ "oldCliRoute": "astryx docs cli/writing-docs check-your-docs",
+ "oldDocsiteUrl": "/docs/cli-writing-docs#check-your-docs",
+ "placement": "namespace:cli/writing-docs",
"aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `integrationAddTheme` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-integration-component-conflicts",
- "oldCliRoute": "astryx docs cli api-integration-component-conflicts",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `integrationComponentConflicts` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-integration-doc-conflicts",
- "oldCliRoute": "astryx docs cli api-integration-doc-conflicts",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `integrationDocConflicts` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-integration-pack-check",
- "oldCliRoute": "astryx docs cli api-integration-pack-check",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `integrationPackCheck` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-integration-template-conflicts",
- "oldCliRoute": "astryx docs cli api-integration-template-conflicts",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `integrationTemplateConflicts` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-is-error",
- "oldCliRoute": "astryx docs cli api-is-error",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `isError` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-layout-check",
- "oldCliRoute": "astryx docs cli api-layout-check",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `layoutCheck` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-layout-expand",
- "oldCliRoute": "astryx docs cli api-layout-expand",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `layoutExpand` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-layout-grammar",
- "oldCliRoute": "astryx docs cli api-layout-grammar",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `layoutGrammar` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-list-themes",
- "oldCliRoute": "astryx docs cli api-list-themes",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `listThemes` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-parse-response",
- "oldCliRoute": "astryx docs cli api-parse-response",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `parseResponse` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-search",
- "oldCliRoute": "astryx docs cli api-search",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `search` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-summarize-issues",
- "oldCliRoute": "astryx docs cli api-summarize-issues",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `summarizeIssues` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-swizzle",
- "oldCliRoute": "astryx docs cli api-swizzle",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `swizzle` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-template",
- "oldCliRoute": "astryx docs cli api-template",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `template` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-theme-add",
- "oldCliRoute": "astryx docs cli api-theme-add",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `themeAdd` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-theme-build",
- "oldCliRoute": "astryx docs cli api-theme-build",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `themeBuild` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-theme-list",
- "oldCliRoute": "astryx docs cli api-theme-list",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `themeList` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-theme-list-available",
- "oldCliRoute": "astryx docs cli api-theme-list-available",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `themeListAvailable` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-theme-palette-generate",
- "oldCliRoute": "astryx docs cli api-theme-palette-generate",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `themePaletteGenerate` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-theme-targets",
- "oldCliRoute": "astryx docs cli api-theme-targets",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `themeTargets` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-theme-template",
- "oldCliRoute": "astryx docs cli api-theme-template",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `themeTemplate` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-upgrade",
- "oldCliRoute": "astryx docs cli api-upgrade",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `upgrade` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-validate-integration",
- "oldCliRoute": "astryx docs cli api-validate-integration",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The API function doc `validateIntegration` (function row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-output",
- "oldCliRoute": "astryx docs cli api-output",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The schema doc `output` (schema row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-error-codes",
- "oldCliRoute": "astryx docs cli api-error-codes",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The enum doc `error-codes` (enum row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli#api-response-types",
- "oldCliRoute": "astryx docs cli api-response-types",
- "oldDocsiteUrl": null,
- "placement": "namespace:cli",
- "aliasNeeded": false,
- "evidence": "Its doc declares namespace cli/api.",
- "rationale": "The enum doc `response-types` (enum row), read as one section of the cli namespace page.",
- "status": "proposed"
- },
- {
- "kind": "topic",
- "id": "browser-support",
- "oldCliRoute": "astryx docs browser-support",
- "oldDocsiteUrl": "/docs/browser-support",
- "placement": "keep-flat",
- "aliasNeeded": false,
- "rationale": "Standalone guide: no topic links to it, and nothing authored places it under another topic.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "browser-support#overview",
- "oldCliRoute": "astryx docs browser-support overview",
- "oldDocsiteUrl": "/docs/browser-support#overview",
- "placement": "keep-flat",
- "aliasNeeded": false,
- "rationale": "Stays a section of browser-support under the same key.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "browser-support#support-tiers",
- "oldCliRoute": "astryx docs browser-support support-tiers",
- "oldDocsiteUrl": "/docs/browser-support#support-tiers",
- "placement": "keep-flat",
- "aliasNeeded": false,
- "rationale": "Stays a section of browser-support under the same key.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "browser-support#which-features-set-the-floor",
- "oldCliRoute": "astryx docs browser-support which-features-set-the-floor",
- "oldDocsiteUrl": "/docs/browser-support#which-features-set-the-floor",
- "placement": "keep-flat",
- "aliasNeeded": false,
- "rationale": "Stays a section of browser-support under the same key.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "browser-support#which-components-are-affected",
- "oldCliRoute": "astryx docs browser-support which-components-are-affected",
- "oldDocsiteUrl": "/docs/browser-support#which-components-are-affected",
- "placement": "keep-flat",
- "aliasNeeded": false,
- "rationale": "Stays a section of browser-support under the same key.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "browser-support#what-astryx-guarantees",
- "oldCliRoute": "astryx docs browser-support what-astryx-guarantees",
- "oldDocsiteUrl": "/docs/browser-support#what-astryx-guarantees",
- "placement": "keep-flat",
- "aliasNeeded": false,
- "rationale": "Stays a section of browser-support under the same key.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "browser-support#supporting-older-browsers",
- "oldCliRoute": "astryx docs browser-support supporting-older-browsers",
- "oldDocsiteUrl": "/docs/browser-support#supporting-older-browsers",
- "placement": "keep-flat",
- "aliasNeeded": false,
- "rationale": "Stays a section of browser-support under the same key.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "browser-support#how-these-tiers-move-over-time",
- "oldCliRoute": "astryx docs browser-support how-these-tiers-move-over-time",
- "oldDocsiteUrl": "/docs/browser-support#how-these-tiers-move-over-time",
- "placement": "keep-flat",
- "aliasNeeded": false,
- "rationale": "Stays a section of browser-support under the same key.",
- "status": "proposed"
- },
- {
- "kind": "topic",
- "id": "cli-integrations",
- "oldCliRoute": "astryx docs cli-integrations",
- "oldDocsiteUrl": "/docs/cli-integrations",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Its subject is the CLI's integration surface: 10 of its 14 sections drive `astryx integration add|pack`, `astryx doctor integration ...`, `astryx init` or `astryx upgrade`.",
- "rationale": "Guide for integration authors. `astryx docs cli-integrations` and /docs/cli-integrations must keep resolving. The docsite already serves /docs/cli as the @astryxdesign/cli package page, so the cli namespace page has to take over that URL.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli-integrations#overview",
- "oldCliRoute": "astryx docs cli-integrations overview",
- "oldDocsiteUrl": "/docs/cli-integrations#overview",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Moves with cli-integrations.",
- "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli-integrations#authoring-with-the-cli",
- "oldCliRoute": "astryx docs cli-integrations authoring-with-the-cli",
- "oldDocsiteUrl": "/docs/cli-integrations#authoring-with-the-cli",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Moves with cli-integrations.",
- "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli-integrations#theme-package-walkthrough",
- "oldCliRoute": "astryx docs cli-integrations theme-package-walkthrough",
- "oldDocsiteUrl": "/docs/cli-integrations#theme-package-walkthrough",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Moves with cli-integrations.",
- "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli-integrations#contribution-kinds-at-a-glance",
- "oldCliRoute": "astryx docs cli-integrations contribution-kinds-at-a-glance",
- "oldDocsiteUrl": "/docs/cli-integrations#contribution-kinds-at-a-glance",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Moves with cli-integrations.",
- "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli-integrations#the-integration-file",
- "oldCliRoute": "astryx docs cli-integrations the-integration-file",
- "oldDocsiteUrl": "/docs/cli-integrations#the-integration-file",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Moves with cli-integrations.",
- "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli-integrations#components",
- "oldCliRoute": "astryx docs cli-integrations components",
- "oldDocsiteUrl": "/docs/cli-integrations#components",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Moves with cli-integrations.",
- "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli-integrations#templates",
- "oldCliRoute": "astryx docs cli-integrations templates",
- "oldDocsiteUrl": "/docs/cli-integrations#templates",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Moves with cli-integrations.",
- "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli-integrations#docs",
- "oldCliRoute": "astryx docs cli-integrations docs",
- "oldDocsiteUrl": "/docs/cli-integrations#docs",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Moves with cli-integrations.",
- "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli-integrations#themes",
- "oldCliRoute": "astryx docs cli-integrations themes",
- "oldDocsiteUrl": "/docs/cli-integrations#themes",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Moves with cli-integrations.",
- "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli-integrations#agent-docs",
- "oldCliRoute": "astryx docs cli-integrations agent-docs",
- "oldDocsiteUrl": "/docs/cli-integrations#agent-docs",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Moves with cli-integrations.",
- "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli-integrations#codemods",
- "oldCliRoute": "astryx docs cli-integrations codemods",
- "oldDocsiteUrl": "/docs/cli-integrations#codemods",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Moves with cli-integrations.",
- "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli-integrations#recording-runs",
- "oldCliRoute": "astryx docs cli-integrations recording-runs",
- "oldDocsiteUrl": "/docs/cli-integrations#recording-runs",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Moves with cli-integrations.",
- "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli-integrations#gap-report-handler",
- "oldCliRoute": "astryx docs cli-integrations gap-report-handler",
- "oldDocsiteUrl": "/docs/cli-integrations#gap-report-handler",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Moves with cli-integrations.",
- "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",
- "status": "proposed"
- },
- {
- "kind": "section",
- "id": "cli-integrations#how-it-works",
- "oldCliRoute": "astryx docs cli-integrations how-it-works",
- "oldDocsiteUrl": "/docs/cli-integrations#how-it-works",
- "placement": "namespace:cli/integrations",
- "aliasNeeded": true,
- "evidence": "Moves with cli-integrations.",
- "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",
+ "evidence": "Moves with cli/writing-docs.",
+ "rationale": "A section of cli/writing-docs: Check your docs.",
"status": "proposed"
},
{
@@ -3058,10 +2371,10 @@
"count": 34,
"oldCliRoute": "astryx <id> --help",
"oldDocsiteUrl": null,
- "placement": "generated:@astryxdesign/cli/command",
+ "placement": "namespace:cli/commands",
"aliasNeeded": false,
- "evidence": "No command doc authors a docs-graph placement.",
- "rationale": "Each CommandDoc builds its command's --help, and is also read as the section commands-<name> of `astryx docs cli` (see those rows): every command doc declares namespace cli/commands.",
+ "evidence": "Every command doc declares namespace cli/commands, which the commands namespace adopts.",
+ "rationale": "Each CommandDoc builds its command's --help, and is read as the leaf cli/commands/<name> of the docs tree.",
"status": "proposed"
},
{
@@ -3071,10 +2384,10 @@
"count": 41,
"oldCliRoute": null,
"oldDocsiteUrl": null,
- "placement": "generated:@astryxdesign/cli/function",
+ "placement": "namespace:cli/api/functions",
"aliasNeeded": false,
- "evidence": "No function doc authors a docs-graph placement.",
- "rationale": "API reference for @astryxdesign/cli/api, read as the section api-<name> of `astryx docs cli` (see those rows): every function doc declares namespace cli/api. A wrapping command's --help also reuses its parameter descriptions.",
+ "evidence": "Every function doc declares namespace cli/api, which the api namespace adopts by kind.",
+ "rationale": "API reference for @astryxdesign/cli/api, read as the leaf cli/api/functions/<name> of the docs tree.",
"status": "proposed"
},
{
@@ -3086,8 +2399,8 @@
"oldDocsiteUrl": null,
"placement": "generated:@astryxdesign/cli/schema",
"aliasNeeded": false,
- "evidence": "No schema doc authors a docs-graph placement.",
- "rationale": "17 declare namespace 'authoring' and are read as sections of `astryx docs authoring`; `output` declares cli/api and is read as the section api-output of `astryx docs cli` (see those rows).",
+ "evidence": "No schema doc authors a placement; output declares cli/api and the other 17 declare authoring.",
+ "rationale": "17 declare namespace 'authoring' and are read as sections of `astryx docs authoring`; `output` declares cli/api and is read as the leaf cli/api/schemas/output. Their home in the tree for authoring is a later phase.",
"status": "proposed"
},
{
@@ -3097,10 +2410,10 @@
"count": 2,
"oldCliRoute": null,
"oldDocsiteUrl": null,
- "placement": "generated:@astryxdesign/cli/enum",
+ "placement": "namespace:cli/api/enums",
"aliasNeeded": false,
- "evidence": "No enum doc authors a docs-graph placement.",
- "rationale": "Error codes and response types declare namespace cli/api and are read as the sections api-error-codes and api-response-types of `astryx docs cli`; the CLI README's generated tables also read them.",
+ "evidence": "Both enum docs declare namespace cli/api, which the api namespace adopts by kind.",
+ "rationale": "Error codes and response types, read as the leaves cli/api/enums/error-codes and cli/api/enums/response-types.",
"status": "proposed"
}
]
diff --git a/packages/cli/test/doc-routes.test.mjs b/packages/cli/test/doc-routes.test.mjs
index af252e972a..f765be3126 100644
--- a/packages/cli/test/doc-routes.test.mjs
+++ b/packages/cli/test/doc-routes.test.mjs
@@ -28,6 +28,7 @@ import {program} from '../clients/cli/index.mjs';
import {Project} from '../foundation/config/project.mjs';
import {loadDocs} from '../foundation/discovery/component-loader.mjs';
import {collectDocInputs} from '../foundation/doc-compiler/inputs.mjs';
+import {loadDocsTree} from '../foundation/doc-compiler/tree.mjs';
import {CLI_ROOT} from '../foundation/fs/paths.mjs';
const REPO_ROOT = path.resolve(CLI_ROOT, '..', '..');
@@ -75,10 +76,11 @@ const PLACEMENT = new RegExp(
*/
/**
- * A topic or section route as the CLI and the docsite answer it today.
+ * A topic, section, or docs-tree namespace route as the CLI and the docsite
+ * answer it today.
* @typedef {object} Route
- * @property {'topic' | 'section'} kind
- * @property {string} id `topic` or `topic#key`
+ * @property {'topic' | 'section' | 'namespace'} kind
+ * @property {string} id `topic`, `topic#key`, or a namespace's route
* @property {string} oldCliRoute
* @property {string | null} oldDocsiteUrl
*/
@@ -128,13 +130,6 @@ afterAll(() => {
if (tmpDir) fs.rmSync(tmpDir, {recursive: true, force: true});
});
-/**
- * Topics the docsite does not publish: /docs/cli is the @astryxdesign/cli
- * package page, so apps/docsite/scripts/generate-data.mjs skips the cli topic
- * until the namespace page takes that URL.
- */
-const DOCSITE_SKIPPED_TOPICS = new Set(['cli']);
-
/**
* Every built-in topic and section key, with the docsite URL for each.
* @param {string} cwd
@@ -144,14 +139,52 @@ async function currentTopicRoutes(cwd) {
/** @type {Map<string, Route>} */
const found = new Map();
const list = /** @type {any} */ (await docs(undefined, undefined, {cwd}));
+ /** @type {Array<{topic: string, file: string, page: string | null}>} */
+ const topics = [];
+ /** @type {string[]} */
+ const namespaces = [];
+ for (const {topic} of list.meta?.namespaces ?? []) namespaces.push(topic);
for (const {topic} of list.data) {
- // The docsite builds one page per topic file the CLI ships, except the
- // topics apps/docsite/scripts/generate-data.mjs skips.
+ // The docsite builds one page per topic file the CLI ships.
const file = path.join(CLI_ROOT, 'assets', 'docs', `${topic}.doc.mjs`);
- const page =
- fs.existsSync(file) && !DOCSITE_SKIPPED_TOPICS.has(topic)
- ? `/docs/${topic}`
- : null;
+ topics.push({
+ topic,
+ file,
+ page: fs.existsSync(file) ? `/docs/${topic}` : null,
+ });
+ }
+ // Down the docs tree, one level at a time. A namespace is a route; a guide
+ // is a topic read by its route, published on the docsite at its route with
+ // "/" as "-"; a typed doc is its descriptor group's row.
+ while (namespaces.length > 0) {
+ const route = /** @type {string} */ (namespaces.shift());
+ found.set(route, {
+ kind: 'namespace',
+ id: route,
+ oldCliRoute: `astryx docs ${route}`,
+ oldDocsiteUrl: null,
+ });
+ const node = /** @type {any} */ (await docs(route, undefined, {cwd}));
+ for (const slot of node.data.slots) {
+ for (const child of slot.children) {
+ if (child.kind === 'namespace') namespaces.push(child.route);
+ // A flat topic in the Unorganized level is listed as a topic below.
+ if (child.kind !== 'generic' || !child.route.includes('/')) continue;
+ topics.push({
+ topic: child.route,
+ file: path.join(
+ CLI_ROOT,
+ 'assets',
+ 'docs',
+ 'tree',
+ `${child.name}.doc.mjs`,
+ ),
+ page: `/docs/${child.route.replaceAll('/', '-')}`,
+ });
+ }
+ }
+ }
+ for (const {topic, file, page} of topics) {
found.set(topic, {
kind: 'topic',
id: topic,
@@ -265,8 +298,10 @@ async function currentDescriptorGroups(cwd) {
/** @type {Map<string, Group>} */
const found = new Map();
for (const input of inputs) {
- // A topic's own file is a topic route; everything else is a descriptor.
+ // A topic's own file is a topic route, and a docs-tree file is a
+ // namespace or guide route; everything else is a descriptor.
if (input.root === 'docs' && input.role === 'base') continue;
+ if (input.root === 'tree') continue;
const doc = await authoredDoc(input.file);
let kind = input.root.replace(/s$/u, '');
let id = input.name;
@@ -372,7 +407,8 @@ function commandPaths() {
}
/** @param {RouteRow} row @returns {boolean} */
-const isDescriptorRow = row => row.kind !== 'topic' && row.kind !== 'section';
+const isDescriptorRow = row =>
+ row.kind !== 'topic' && row.kind !== 'section' && row.kind !== 'namespace';
/**
* A row to paste and complete: the rationale and placement stay empty, so
@@ -576,4 +612,39 @@ describe('doc route inventory', () => {
}
expect(bad).toEqual([]);
});
+
+ it(
+ '(d) puts every descriptor a namespace row names where the tree does',
+ async () => {
+ const tree = await loadDocsTree();
+ /** @type {Map<string, string>} */
+ const routeOf = new Map(
+ [...tree.nodes.values()].map(node => [
+ `${node.provider}/${node.kind}/${node.name}`,
+ node.route,
+ ]),
+ );
+ /** @type {string[]} */
+ const bad = [];
+ for (const row of table.rows) {
+ if (!isDescriptorRow(row) || !row.placement.startsWith('namespace:')) {
+ continue;
+ }
+ const under = row.placement.slice('namespace:'.length);
+ for (const id of idsFile[row.id] ?? []) {
+ const route = routeOf.get(`${row.provider}/${row.kind}/${id}`);
+ if (
+ route == null ||
+ route.slice(0, route.lastIndexOf('/')) !== under
+ ) {
+ bad.push(
+ `${row.id} "${id}": the tree puts it at ${route ?? 'no route'}, not under ${under}`,
+ );
+ }
+ }
+ }
+ expect(bad).toEqual([]);
+ },
+ SLOW,
+ );
});
diff --git a/packages/cli/test/docs-graph.test.mjs b/packages/cli/test/docs-graph.test.mjs
new file mode 100644
index 0000000000..8acf7261a4
--- /dev/null
+++ b/packages/cli/test/docs-graph.test.mjs
@@ -0,0 +1,536 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The docs graph stays walkable (spec:AST-047, spec:AST-046).
+ *
+ * The walk starts at the topic list and opens every topic, topic index,
+ * section, namespace, and typed doc the CLI ships, the way a reader would: it
+ * follows each child and each move a read offers (`up`, `previous`, `next`),
+ * and fails on any move that does not open. It then checks the moves agree
+ * with each other, opens every `astryx docs ...` command written in a doc's
+ * own text, and opens every search hit's command and parent. Nothing stores
+ * the moves, so this is what proves they stay right as docs are added, moved,
+ * or removed.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {describe, it, expect, beforeAll} from 'vitest';
+import {docs} from '../api/docs/docs.mjs';
+import {typedEdges} from '../api/docs/node/node.mjs';
+import {
+ builtinCatalog,
+ docsLinkProblems,
+ projectTree,
+} from '../api/docs/_adapter.mjs';
+import {loadDocsCatalog} from '../api/docs/_adapter.mjs';
+import {search} from '../api/search/search.mjs';
+import {loadDocsTree} from '../foundation/doc-compiler/tree.mjs';
+import {
+ discoverCliSelfDocSources,
+ loadCliSelfDocs,
+} from '../foundation/discovery/cli-self-docs.mjs';
+import {routeSegment} from '../foundation/discovery/docs-section-key.mjs';
+import {program, JSON_SUPPORTED} from '../clients/cli/index.mjs';
+import {buildManifest} from '../clients/cli/lib/manifest.mjs';
+import {runCli} from '../test-utils/run-cli.mjs';
+
+const CLI = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+const SLOW = 180_000;
+const TOP = 'astryx docs';
+
+/**
+ * Open one `astryx docs ...` command through the API, as the CLI would.
+ * @param {string} command
+ */
+function open(command) {
+ const words = command.trim().split(/\s+/);
+ if (words[0] !== 'astryx' || words[1] !== 'docs') {
+ throw new Error(`not a docs command: ${command}`);
+ }
+ const rest = words.slice(2);
+ const [topic, section] = rest.filter(w => !w.startsWith('--'));
+ return docs(topic, section, {
+ index: rest.includes('--index'),
+ full: rest.includes('--full'),
+ });
+}
+
+/**
+ * Every place a read leads: its children, and its moves.
+ * @param {any} res
+ * @returns {Array<[string, string]>} [kind of move, command]
+ */
+function movesOf(res) {
+ /** @type {Array<[string, string]>} */
+ const out = [];
+ const {type, data} = res;
+ if (type === 'docs.list') {
+ for (const entry of data) {
+ out.push(['down', `${TOP} ${entry.topic}`]);
+ out.push(['down', `${TOP} ${entry.topic} --index`]);
+ }
+ for (const entry of res.meta?.namespaces ?? []) {
+ out.push(['down', `${TOP} ${entry.topic}`]);
+ }
+ }
+ if (type === 'docs.node') {
+ for (const slot of data.slots) {
+ for (const child of slot.children) out.push(['down', `${TOP} ${child.route}`]);
+ }
+ }
+ if (type === 'docs.index') {
+ for (const section of data.sections) {
+ out.push(['down', `${TOP} ${data.name} ${section.id}`]);
+ }
+ }
+ for (const [kind, value] of Object.entries(data?.links ?? {})) {
+ for (const command of [value].flat()) {
+ out.push([kind, /** @type {string} */ (command)]);
+ }
+ }
+ // Links between docs are moves too: each reference block, and each
+ // workflow step's references.
+ const blocks = [
+ ...(data?.content ?? []),
+ ...(data?.sections ?? []).flatMap((/** @type {any} */ s) => s.content ?? []),
+ ];
+ for (const block of blocks) {
+ if (block?.type === 'reference' && block.link) {
+ out.push(['reference', block.link.command]);
+ }
+ for (const step of block?.type === 'workflow' ? block.steps : []) {
+ for (const link of step.links ?? []) {
+ if (link) out.push(['reference', link.command]);
+ }
+ }
+ }
+ return out;
+}
+
+/**
+ * The words a read says: prose, list items, and table cells.
+ * @param {any} res
+ * @returns {string[]}
+ */
+function textOf(res) {
+ /** @type {string[]} */
+ const out = [];
+ /** @param {any[]} blocks */
+ const scan = blocks => {
+ for (const block of blocks ?? []) {
+ if (block.type === 'prose' && block.text) out.push(block.text);
+ if (block.type === 'list') {
+ for (const item of block.items ?? []) {
+ out.push(typeof item === 'string' ? item : (item?.text ?? ''));
+ }
+ }
+ if (block.type === 'table') {
+ for (const row of block.rows ?? []) out.push(...row.map(String));
+ }
+ if (block.type === 'code' && typeof block.code === 'string') {
+ out.push(block.code);
+ }
+ }
+ };
+ const {type, data} = res;
+ if (type === 'docs.detail') {
+ out.push(data.description ?? '');
+ for (const section of data.sections ?? []) scan(section.content);
+ }
+ if (type === 'docs.index') out.push(data.description ?? '');
+ if (type === 'docs.detail.section') scan(data.content);
+ if (type === 'docs.node') scan(data.content);
+ return out;
+}
+
+/**
+ * Every `astryx ...` command a text shows: in code ticks, or on a line of its
+ * own (a code block line, or a hint line such as `Up: npx astryx docs cli`).
+ * A hint's description, after two spaces or a `#`, is cut off.
+ * @param {string} text
+ * @returns {string[]}
+ */
+function shownCommands(text) {
+ const RUN = '(?:npx |pnpm exec |pnpm dlx |yarn |bunx )?astryx(?: [^`\\n]*)?';
+ /** @param {string} s */
+ const clean = s => s.replace(/\s{2,}.*$/, '').replace(/\s+#.*$/, '').trim();
+ /** @type {Set<string>} */
+ const out = new Set();
+ for (const m of text.matchAll(new RegExp('`(' + RUN + ')`', 'g'))) {
+ out.add(clean(m[1]));
+ }
+ for (const line of text.split('\n')) {
+ const m = new RegExp('^\\s*(?:\\$\\s+|[A-Z][A-Za-z ]*:\\s+)?(' + RUN + ')$').exec(line);
+ if (m) out.add(clean(m[1]));
+ }
+ return [...out];
+}
+
+/**
+ * The CLI's commands and options, from the live manifest: nothing here is a
+ * list someone keeps.
+ */
+function cliSurface() {
+ const manifest = buildManifest(program, {jsonSupported: JSON_SUPPORTED});
+ /** @param {Array<{flag: string}>} options */
+ const flagsOf = options => {
+ /** @type {Map<string, boolean>} flag -> takes a value */
+ const flags = new Map();
+ for (const option of options ?? []) {
+ const takes = /[<[]/.test(option.flag);
+ for (const flag of option.flag.split(/[\s,]+/)) {
+ if (flag.startsWith('-')) flags.set(flag, takes);
+ }
+ }
+ return flags;
+ };
+ /** @type {Map<string, Map<string, boolean>>} */
+ const commands = new Map();
+ /** @param {any[]} list */
+ const add = list => {
+ for (const command of list ?? []) {
+ commands.set(command.name, flagsOf(command.options));
+ add(command.subcommands);
+ }
+ };
+ add(manifest.commands);
+ return {commands, global: flagsOf(manifest.globalOptions)};
+}
+
+/**
+ * What is wrong with one shown command, or null: an unknown command, or an
+ * option its command does not take. Positional arguments are not checked
+ * here; `astryx docs` routes are, by the walk.
+ * @param {string} shown
+ * @param {ReturnType<typeof cliSurface>} surface
+ * @returns {string | null}
+ */
+function problemWith(shown, {commands, global}) {
+ const words = shown.split(/\s+/);
+ const rest = words.slice(words.indexOf('astryx') + 1).filter(Boolean);
+ /** @param {Map<string, boolean>} flags @param {string} token */
+ const known = (flags, token) => {
+ const flag = token.split('=')[0];
+ return (
+ flag === '--help' ||
+ flag === '-h' ||
+ flags.has(flag) ||
+ (flag.startsWith('--no-') && flags.has(`--${flag.slice(5)}`))
+ );
+ };
+ let i = 0;
+ while (i < rest.length && rest[i].startsWith('-')) {
+ if (!known(global, rest[i])) return `unknown global option ${rest[i]}`;
+ if (global.get(rest[i]) && !rest[i].includes('=')) i++;
+ i++;
+ }
+ // `help` is Commander's own command; a placeholder names no command.
+ if (i >= rest.length || rest[i] === 'help' || /^[<[]/.test(rest[i])) return null;
+ let name = null;
+ for (let n = rest.length - i; n > 0; n--) {
+ const candidate = rest.slice(i, i + n).join(' ');
+ if (commands.has(candidate)) {
+ name = candidate;
+ i += n;
+ break;
+ }
+ }
+ if (name == null) return `unknown command "${rest[i]}"`;
+ const flags = new Map([...global, ...(commands.get(name) ?? [])]);
+ for (; i < rest.length; i++) {
+ const token = rest[i];
+ if (!/^--?[a-zA-Z]/.test(token)) continue;
+ if (!known(flags, token)) {
+ return `\`astryx ${name}\` has no option ${token.split('=')[0]}`;
+ }
+ if (flags.get(token) && !token.includes('=')) i++;
+ }
+ return null;
+}
+
+/**
+ * Commands a doc shows on purpose as wrong: the error codes they trigger. Each
+ * must still appear in a doc, or the entry is stale.
+ */
+const WRONG_ON_PURPOSE = new Map([
+ ['astryx bogus', 'the ERR_UNKNOWN_COMMAND example'],
+ ['astryx theme bogus', 'the ERR_UNKNOWN_SUBCOMMAND example'],
+]);
+
+/** The CLI's own reads whose hint lines show commands. */
+const HINT_READS = [
+ ['docs'],
+ ['docs', 'cli'],
+ ['docs', 'cli/api/functions/search'],
+ ['docs', 'theme'],
+ ['docs', 'cli/integrations', 'codemods'],
+ ['search', 'token-ref', '--type', 'doc'],
+ ['--help'],
+ ['docs', '--help'],
+];
+
+/** The `astryx docs ...` commands written in text, placeholders skipped. */
+function docsCommandsIn(text) {
+ /** @type {string[]} */
+ const out = [];
+ for (const m of text.matchAll(/`(?:npx |pnpm exec |yarn |bunx )?astryx docs( [^`]*)?`/g)) {
+ const args = (m[1] ?? '').trim();
+ if (/[<>…]|\.\.\.|\|/.test(args)) continue;
+ out.push(args ? `${TOP} ${args}` : TOP);
+ }
+ return out;
+}
+
+describe('the docs graph', () => {
+ /** @type {Map<string, any>} */
+ const reads = new Map();
+ /** @type {Array<[string, string, string]>} */
+ const moves = [];
+ /** @type {string[]} */
+ const dead = [];
+
+ beforeAll(async () => {
+ const queue = [TOP];
+ while (queue.length > 0) {
+ const command = /** @type {string} */ (queue.shift());
+ if (reads.has(command)) continue;
+ let res;
+ try {
+ res = await open(command);
+ } catch (e) {
+ dead.push(`${command}: ${/** @type {Error} */ (e).message}`);
+ reads.set(command, null);
+ continue;
+ }
+ reads.set(command, res);
+ for (const [kind, to] of movesOf(res)) {
+ moves.push([command, kind, to]);
+ if (!reads.has(to)) queue.push(to);
+ }
+ }
+ }, SLOW);
+
+ it('opens every move a read offers, from the top down', () => {
+ expect(dead).toEqual([]);
+ expect(reads.size).toBeGreaterThan(200);
+ });
+
+ it('reaches every node of the tree', async () => {
+ const tree = await loadDocsTree();
+ const missed = [...tree.nodes.values()]
+ .map(node => `${TOP} ${node.route}`)
+ .filter(command => !reads.get(command));
+ expect(missed).toEqual([]);
+ });
+
+ it('reaches every doc file the CLI ships, and every doc file is one the CLI reads', async () => {
+ const tree = await loadDocsTree();
+ const reached = (/** @type {string} */ command) => Boolean(reads.get(command));
+ /** @type {string[]} */
+ const unreached = [];
+ // Command, API, schema, enum, and authoring docs: a tree leaf, or a section
+ // of `astryx docs authoring`.
+ const {loaded, failed} = await loadCliSelfDocs(discoverCliSelfDocSources(CLI), CLI);
+ expect(failed).toEqual([]);
+ const authoring = reads.get(`${TOP} authoring --index`)?.data.sections ?? [];
+ for (const {source, doc} of loaded) {
+ const leaf = [...tree.nodes.values()].find(
+ node => node.kind === doc.type && node.name === doc.name,
+ );
+ const section = authoring.find(
+ (/** @type {any} */ s) => s.id === routeSegment(doc.name) || s.title === doc.displayName,
+ );
+ const ok = leaf
+ ? reached(`${TOP} ${leaf.route}`)
+ : section
+ ? reached(`${TOP} authoring ${section.id}`)
+ : false;
+ if (!ok) unreached.push(source);
+ }
+ // Topics, and the tree's own files.
+ const catalog = await loadDocsCatalog(CLI);
+ const topicFiles = new Set();
+ for (const entry of catalog.entries()) {
+ topicFiles.add(path.resolve(entry.path));
+ if (!reached(`${TOP} ${entry.name}`)) unreached.push(`topic ${entry.name}`);
+ }
+ const treeFiles = fs
+ .readdirSync(path.join(CLI, 'assets/docs/tree'))
+ .filter(name => name.endsWith('.doc.mjs'))
+ .map(name => `assets/docs/tree/${name}`);
+ for (const file of treeFiles) {
+ const node = [...tree.nodes.values()].find(n =>
+ [n.source, n.ref?.topicFile].some(s => String(s ?? '').endsWith(file)),
+ );
+ if (!node || !reached(`${TOP} ${node.route}`)) unreached.push(file);
+ }
+ expect(unreached).toEqual([]);
+
+ // Every doc file under the docs directory is a topic, an overlay of one
+ // (`.doc.<variant>.mjs`), or a tree file: none sits where nothing reads it.
+ const orphans = fs
+ .readdirSync(path.join(CLI, 'assets/docs'))
+ .filter(name => /\.doc\.mjs$/.test(name))
+ .filter(name => !topicFiles.has(path.resolve(CLI, 'assets/docs', name)));
+ expect(orphans).toEqual([]);
+ expect(loaded.length).toBeGreaterThan(90);
+ });
+
+ it('resolves every typed edge a doc declares: command, fn, and related', async () => {
+ const tree = await loadDocsTree();
+ /** @type {string[]} */
+ const broken = [];
+ for (const node of tree.nodes.values()) {
+ for (const edge of typedEdges(tree, node).unresolved) {
+ broken.push(`${node.route}: ${edge}`);
+ }
+ }
+ expect(broken).toEqual([]);
+ });
+
+ it('resolves every link written in a doc: inline, reference, and workflow', async () => {
+ // The walk opens each resolved link as a move; a link that names no doc
+ // has no command to open, so it is caught here, by the same resolver
+ // `astryx doctor` uses.
+ const catalog = builtinCatalog();
+ expect(await docsLinkProblems(catalog, await projectTree(catalog))).toEqual(
+ [],
+ );
+ for (const [command, res] of reads) {
+ const blocks = [
+ ...(res?.data?.content ?? []),
+ ...(res?.data?.sections ?? []).flatMap(
+ (/** @type {any} */ s) => s.content ?? [],
+ ),
+ ];
+ for (const block of blocks) {
+ if (block?.type === 'reference') {
+ expect(block.link, `${command}: ${block.target}`).toBeTruthy();
+ }
+ for (const text of [block?.text, ...(block?.items ?? [])]) {
+ if (typeof text === 'string') {
+ expect(
+ text.replace(/`[^`]*`/g, ''),
+ `${command} shows an unresolved link`,
+ ).not.toMatch(/\{@link /);
+ }
+ }
+ }
+ }
+ }, SLOW);
+
+ it('offers a way up from every read but the top, and up always ends at the top', () => {
+ const noUp = [...reads]
+ .filter(([command, res]) => res && command !== TOP && !res.data?.links?.up)
+ .map(([command]) => command);
+ expect(noUp).toEqual([]);
+ /** @type {string[]} */
+ const lost = [];
+ for (const [command, res] of reads) {
+ let at = res;
+ let steps = 0;
+ while (at?.data?.links?.up && steps < 10) {
+ at = reads.get(at.data.links.up);
+ steps++;
+ }
+ if (at?.type !== 'docs.list') lost.push(command);
+ }
+ expect(lost).toEqual([]);
+ });
+
+ it('agrees on neighbors: the next read names this one as its previous', async () => {
+ /** @type {string[]} */
+ const broken = [];
+ // A topic's section list and its whole read are one place.
+ /** @param {string | undefined} command */
+ const place = command => command?.replace(/ --index$/, '');
+ for (const [from, kind, to] of moves) {
+ if (kind !== 'next') continue;
+ const back = reads.get(to)?.data?.links?.previous;
+ if (place(back) !== place(from)) broken.push(`${from} -> ${to} <- ${back}`);
+ }
+ expect(broken).toEqual([]);
+ });
+
+ it('opens every `astryx docs ...` command written in a doc', async () => {
+ /** @type {string[]} */
+ const stale = [];
+ const checked = new Set();
+ for (const [command, res] of reads) {
+ if (!res) continue;
+ for (const text of textOf(res)) {
+ for (const link of docsCommandsIn(text)) {
+ if (checked.has(link)) continue;
+ checked.add(link);
+ try {
+ await open(link);
+ } catch (e) {
+ stale.push(`${command} names \`${link}\`: ${/** @type {Error} */ (e).message}`);
+ }
+ }
+ }
+ }
+ expect(stale).toEqual([]);
+ expect(checked.size).toBeGreaterThan(10);
+ }, SLOW);
+
+ it('shows only real commands with real options, in docs, hints, and the agent prompt', async () => {
+ const surface = cliSurface();
+ /** @type {Map<string, string>} command -> where it is shown */
+ const shown = new Map();
+ for (const [command, res] of reads) {
+ if (!res) continue;
+ for (const text of textOf(res)) {
+ for (const each of shownCommands(text)) {
+ if (!shown.has(each)) shown.set(each, command);
+ }
+ }
+ }
+ for (const args of HINT_READS) {
+ const {stdout} = await runCli(args);
+ for (const each of shownCommands(stdout)) {
+ if (!shown.has(each)) shown.set(each, `astryx ${args.join(' ')}`);
+ }
+ }
+ const prompt = fs.readFileSync(path.join(CLI, '..', '..', 'AGENTS.md'), 'utf8');
+ const block = /<!-- ASTRYX-CLI:START -->([\s\S]*?)<!-- ASTRYX-CLI:END -->/.exec(prompt)?.[1] ?? '';
+ for (const each of shownCommands(block)) {
+ if (!shown.has(each)) shown.set(each, 'the agent prompt in AGENTS.md');
+ }
+ /** @type {string[]} */
+ const wrong = [];
+ for (const [command, where] of shown) {
+ if (WRONG_ON_PURPOSE.has(command.replace(/^(?:npx |pnpm exec |yarn |bunx )/, ''))) continue;
+ const problem = problemWith(command, surface);
+ if (problem) wrong.push(`${where} shows \`${command}\`: ${problem}`);
+ }
+ expect(wrong).toEqual([]);
+ const stale = [...WRONG_ON_PURPOSE.keys()].filter(
+ command => ![...shown.keys()].some(each => each.endsWith(command)),
+ );
+ expect(stale).toEqual([]);
+ expect(shown.size).toBeGreaterThan(50);
+ }, SLOW);
+
+ it("opens every search hit's command and parent", async () => {
+ /** @type {string[]} */
+ const broken = [];
+ for (const query of ['assertResponse', 'token-ref', 'codemod protected files', 'agent docs', 'ERR_UNKNOWN_SECTION', 'theme', 'unorganized', 'Astryx CLI']) {
+ const {data} = await search(query, {type: 'doc', limit: 20});
+ for (const hit of data.results) {
+ if (!hit.parent) broken.push(`"${query}": ${hit.name} has no parent`);
+ for (const command of [hit.command, hit.parent].filter(Boolean)) {
+ try {
+ await open(command);
+ } catch (e) {
+ broken.push(`"${query}": ${command}: ${/** @type {Error} */ (e).message}`);
+ }
+ }
+ }
+ }
+ expect(broken).toEqual([]);
+ }, SLOW);
+});
diff --git a/packages/cli/test/golden-reads.test.mjs b/packages/cli/test/golden-reads.test.mjs
index 5f273a648a..7c8e061faa 100644
--- a/packages/cli/test/golden-reads.test.mjs
+++ b/packages/cli/test/golden-reads.test.mjs
@@ -160,8 +160,8 @@ describe('golden reads of integration docs', () => {
['component-zh.json', ['component', 'AcmeCard', '--zh', '--json']],
['component-props.json', ['component', 'AcmeCard', '--props', '--json']],
['template.json', ['template', 'hero', '--type', 'block', '--json']],
- ['docs-topic.json', ['docs', 'acme-guide', '--json']],
- ['docs-topic-text.txt', ['docs', 'acme-guide']],
+ ['docs-topic.json', ['docs', 'acme-guide', '--full', '--json']],
+ ['docs-topic-text.txt', ['docs', 'acme-guide', '--full']],
['docs-index.txt', ['docs', 'acme-guide', '--index']],
['docs-section.json', ['docs', 'acme-guide', 'colors', '--json']],
['search.json', ['search', 'zorblax', '--json']],
diff --git a/packages/cli/test/invalid-component-metadata.regression.test.mjs b/packages/cli/test/invalid-component-metadata.regression.test.mjs
new file mode 100644
index 0000000000..63f38a0fdd
--- /dev/null
+++ b/packages/cli/test/invalid-component-metadata.regression.test.mjs
@@ -0,0 +1,363 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Regression shapes for PR #6265 — syntax-invalid component metadata.
+ *
+ * These tests pin the FR9 contract for component discovery when an
+ * integration contributes a doc file that cannot be imported (syntax error,
+ * runtime error, or missing export). They cover every surface that reads
+ * component records: Project.components(), Project.issues(), the component
+ * CLI (list, detail, source), search, build, and Doctor.
+ *
+ * Fixture: @acme/widgets with two components:
+ * - FooWidget: valid source (.tsx), INVALID doc (.doc.mjs has syntax error)
+ * - BarWidget: valid source (.tsx), valid doc (.doc.mjs)
+ * - Button: valid Core component plus invalid integration owner
+ *
+ * Expected behavior per FR9 (AST-035):
+ * - FooWidget is OMITTED from every component result
+ * - FooWidget's invalidity is REPORTED as an issue
+ * - BarWidget (valid sibling) REMAINS in every result
+ * - Other contribution kinds (templates, themes) REMAIN unaffected
+ * - Doctor reports integration-issues as a warning (a project that passed
+ * keeps passing); `astryx doctor integration` fails on it
+ * - component detail for FooWidget throws a coded error, not a raw SyntaxError
+ *
+ * @position packages/cli/test (regression — cross-surface FR9 pin)
+ */
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+// ── Test subjects ──────────────────────────────────────────────────
+import {Project} from '../foundation/config/project.mjs';
+import {component} from '../api/component/component.mjs';
+import {search} from '../api/search/search.mjs';
+import {build} from '../api/build/build.mjs';
+import {doctor} from '../api/doctor/doctor.mjs';
+
+// ── Fixture ────────────────────────────────────────────────────────
+
+let tmpDir;
+let originalCwd;
+
+/**
+ * Scaffold a consumer with @acme/widgets contributing:
+ * - FooWidget: valid source, broken doc (syntax error)
+ * - BarWidget: valid source, valid doc
+ * - One valid template (hero block)
+ *
+ * @returns {string} pkgDir — the integration package directory
+ */
+function scaffoldInvalidDoc() {
+ // Consumer
+ 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`,
+ );
+
+ // Integration package
+ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');
+ fs.mkdirSync(pkgDir, {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', templates: './templates' };\n`,
+ );
+
+ // ── Components ────────────────────────────────────────────────────
+
+ const compDir = path.join(pkgDir, 'components');
+
+ // FooWidget: valid source, BROKEN doc
+ const fooDir = path.join(compDir, 'FooWidget');
+ fs.mkdirSync(fooDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(fooDir, 'FooWidget.tsx'),
+ `export const FooWidget = () => null;\n`,
+ );
+ // Syntax-invalid: missing commas, unclosed brace
+ fs.writeFileSync(
+ path.join(fooDir, 'FooWidget.doc.mjs'),
+ [
+ `export const docs = {`,
+ ` type: 'component',`,
+ ` name: 'FooWidget',`,
+ ` category: 'Data'`, // ← missing comma
+ ` group: 'Widgets'`, // ← SyntaxError: Unexpected identifier 'group'
+ ` keywords: ['foo' 'widget'],`,
+ ` usage: { description: 'A foo widget.' }`,
+ ``, // ← unclosed brace
+ ].join('\n'),
+ );
+
+ // Button: valid integration source, broken doc, colliding with valid Core.
+ const buttonDir = path.join(compDir, 'Button');
+ fs.mkdirSync(buttonDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(buttonDir, 'Button.tsx'),
+ `export function Button() { return 'BrokenIntegrationButton'; }\n`,
+ );
+ fs.writeFileSync(
+ path.join(buttonDir, 'Button.doc.mjs'),
+ `export default {type: 'component', name: 'Button', props: [};\n`,
+ );
+
+ // BarWidget: valid source, valid doc
+ const barDir = path.join(compDir, 'BarWidget');
+ fs.mkdirSync(barDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(barDir, 'BarWidget.tsx'),
+ `export const BarWidget = () => null;\n`,
+ );
+ fs.writeFileSync(
+ path.join(barDir, 'BarWidget.doc.mjs'),
+ `export const docs = {
+ type: 'component',
+ name: 'BarWidget',
+ category: 'Data',
+ group: 'Widgets',
+ keywords: ['bar', 'widget'],
+ usage: { description: 'A valid bar widget.' },
+ props: [{ name: 'value', type: 'number', description: 'The value.' }],
+ };\n`,
+ );
+
+ // ── Templates (valid, other contribution kind) ────────────────────
+
+ const tDir = path.join(pkgDir, 'templates');
+ fs.mkdirSync(tDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(tDir, 'hero.doc.mjs'),
+ `export default { type: 'block', name: 'Hero', description: 'A hero section' };\n`,
+ );
+ fs.writeFileSync(
+ path.join(tDir, 'hero.tsx'),
+ `export default function Hero() { return null; }\n`,
+ );
+
+ return pkgDir;
+}
+
+beforeEach(() => {
+ originalCwd = process.cwd();
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-fr9-invalid-doc-'));
+ process.chdir(tmpDir);
+});
+
+afterEach(() => {
+ process.chdir(originalCwd);
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+// ── A. Project ─────────────────────────────────────────────────────
+
+describe('Project — invalid component metadata (FR9)', () => {
+ it('omits a component whose doc.mjs has a syntax error', async () => {
+ scaffoldInvalidDoc();
+ const project = await Project.load(tmpDir);
+ const comps = await project.components();
+
+ expect(comps.find(c => c.name === 'FooWidget')).toBeUndefined();
+ });
+
+ it('retains a valid sibling in the same integration', async () => {
+ scaffoldInvalidDoc();
+ const project = await Project.load(tmpDir);
+ const comps = await project.components();
+
+ expect(
+ comps.find(c => c.name === 'BarWidget' && c.package === '@acme/widgets'),
+ ).toBeDefined();
+ });
+
+ it('reports the invalid doc as an invalid_component issue', async () => {
+ scaffoldInvalidDoc();
+ const project = await Project.load(tmpDir);
+ await project.components(); // trigger discovery
+ const issues = await project.issues();
+
+ expect(issues).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ package: '@acme/widgets',
+ code: 'invalid_component',
+ severity: 'error',
+ }),
+ ]),
+ );
+ });
+
+ it('preserves other contribution kinds from the same integration', async () => {
+ scaffoldInvalidDoc();
+ const project = await Project.load(tmpDir);
+
+ const templates = await project.templates();
+ expect(templates.find(t => t.package === '@acme/widgets')).toBeDefined();
+
+ const comps = await project.components();
+ expect(comps.find(c => c.name === 'FooWidget')).toBeUndefined();
+ expect(
+ comps.find(c => c.name === 'BarWidget' && c.package === '@acme/widgets'),
+ ).toBeDefined();
+ });
+});
+
+// ── B. CLI component --list ────────────────────────────────────────
+
+describe('component --list — invalid component metadata (FR9)', () => {
+ it('does not list a component whose doc.mjs has a syntax error', async () => {
+ scaffoldInvalidDoc();
+ const r = await component(undefined, {cwd: tmpDir, list: true});
+ const allNames = Object.values(r.data.components)
+ .flat()
+ .map(c => c.name);
+
+ expect(allNames).not.toContain('FooWidget');
+ });
+
+ it('lists the valid sibling', async () => {
+ scaffoldInvalidDoc();
+ const r = await component(undefined, {cwd: tmpDir, list: true});
+ const allNames = Object.values(r.data.components)
+ .flat()
+ .map(c => c.name);
+
+ expect(allNames).toContain('BarWidget');
+ });
+});
+
+// ── C. Search ──────────────────────────────────────────────────────
+
+describe('search — invalid component metadata (FR9)', () => {
+ it('does not return a component with invalid metadata', async () => {
+ scaffoldInvalidDoc();
+ const r = await search('FooWidget', {cwd: tmpDir, type: 'component'});
+
+ expect(r.data.results.find(x => x.name === 'FooWidget')).toBeUndefined();
+ });
+
+ it('returns the valid sibling', async () => {
+ scaffoldInvalidDoc();
+ const r = await search('BarWidget', {cwd: tmpDir, type: 'component'});
+
+ expect(r.data.results.find(x => x.name === 'BarWidget')).toBeDefined();
+ });
+});
+
+describe('build — invalid component metadata (FR9)', () => {
+ it('omits the invalid component and retains its valid sibling', async () => {
+ scaffoldInvalidDoc();
+ const invalid = await build('FooWidget', {
+ cwd: tmpDir,
+ type: 'component',
+ });
+ const valid = await build('BarWidget', {
+ cwd: tmpDir,
+ type: 'component',
+ });
+ if (invalid.type !== 'build.kit' || valid.type !== 'build.kit') {
+ throw new Error('expected build.kit');
+ }
+
+ expect(invalid.data.domain.some(entry => entry.name === 'FooWidget')).toBe(
+ false,
+ );
+ expect(valid.data.domain.some(entry => entry.name === 'BarWidget')).toBe(
+ true,
+ );
+ });
+});
+
+// ── D. Doctor ──────────────────────────────────────────────────────
+
+describe('doctor — invalid component metadata (FR9)', () => {
+ it('reports integration-issues as a warning when a component doc is invalid', async () => {
+ scaffoldInvalidDoc();
+ const report = await doctor({cwd: tmpDir});
+ const check = report.data.checks.find(c => c.id === 'integration-issues');
+
+ expect(check.status).toBe('warn');
+ expect(check.message).toMatch(
+ /invalid_component|FooWidget|invalid metadata/i,
+ );
+ });
+});
+
+// ── E. Detail ──────────────────────────────────────────────────────
+
+describe('component detail — invalid component metadata (FR9)', () => {
+ it('throws a descriptive error for a component with invalid metadata', async () => {
+ scaffoldInvalidDoc();
+
+ await expect(component('FooWidget', {cwd: tmpDir})).rejects.toThrow(
+ /Cannot load|invalid metadata|FooWidget/i,
+ );
+ });
+
+ it('does not throw a raw SyntaxError (must be wrapped)', async () => {
+ scaffoldInvalidDoc();
+
+ try {
+ await component('FooWidget', {cwd: tmpDir});
+ expect.unreachable('should have thrown');
+ } catch (e) {
+ // A raw SyntaxError from import() is the current broken behavior.
+ // The fix wraps it with context.
+ expect(e.constructor.name).not.toBe('SyntaxError');
+ }
+ });
+
+ it('ignores an invalid integration owner when Core has a valid component', async () => {
+ scaffoldInvalidDoc();
+
+ const detail = await component('Button', {cwd: tmpDir});
+ expect(detail.type).toBe('component.detail');
+ expect(detail.data.package).toBe('@astryxdesign/core');
+
+ const source = await component('Button', {cwd: tmpDir, source: true});
+ expect(source.type).toBe('component.detail.source');
+ expect(source.data.source).not.toContain('BrokenIntegrationButton');
+ });
+
+ it('keeps explicit access to an invalid integration owner diagnostic and source', async () => {
+ scaffoldInvalidDoc();
+
+ await expect(
+ component('Button', {cwd: tmpDir, package: '@acme/widgets'}),
+ ).rejects.toMatchObject({code: 'ERR_INVALID_DOC'});
+
+ const source = await component('Button', {
+ cwd: tmpDir,
+ package: '@acme/widgets',
+ source: true,
+ });
+ expect(source.type).toBe('component.detail.source');
+ expect(source.data.source).toContain('BrokenIntegrationButton');
+ });
+
+ it('loads a valid sibling without error', async () => {
+ scaffoldInvalidDoc();
+ const r = await component('BarWidget', {cwd: tmpDir});
+
+ expect(r.type).toBe('component.detail');
+ expect(r.data.name).toBe('BarWidget');
+ expect(r.data.package).toBe('@acme/widgets');
+ });
+
+ it('returns source for a component with invalid metadata (source is valid)', async () => {
+ scaffoldInvalidDoc();
+ const r = await component('FooWidget', {cwd: tmpDir, source: true});
+
+ expect(r.type).toBe('component.detail.source');
+ expect(r.data.source).toContain('FooWidget');
+ });
+});
diff --git a/scripts/check-cli-structure.mjs b/scripts/check-cli-structure.mjs
index 0e5ab3841f..13ee856976 100644
--- a/scripts/check-cli-structure.mjs
+++ b/scripts/check-cli-structure.mjs
@@ -320,7 +320,7 @@ const INV22_KNOWN_GAPS = new Map([
// remove with the layout command
['layout.mjs', new Set(['fs'])],
['search.mjs', new Set(['project'])],
- ['template.mjs', new Set(['fs', 'project'])],
+ ['template.mjs', new Set(['project'])],
]);
const handlerFiles = walkScopedMjs(HANDLER_DIR);
const inv22Count = checkEnvironmentImports(
@@ -550,7 +550,7 @@ for (const m of apiIndexSrc.matchAll(/export\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)
/** @type {Set<string>} known FR1 gaps: fn values not yet exported.
* Remove an entry when the function is exported; do not add entries. */
-const FR1_KNOWN_GAPS = new Set(['themeTemplate']);
+const FR1_KNOWN_GAPS = new Set();
let fr1Count = 0;
diff --git a/scripts/generate-token-docs.mjs b/scripts/generate-token-docs.mjs
index ed861e2121..b02c3c4832 100644
--- a/scripts/generate-token-docs.mjs
+++ b/scripts/generate-token-docs.mjs
@@ -232,7 +232,7 @@ const styles = stylex.create({
},
{
type: 'prose',
- text: 'See `astryx docs styling` for how to apply tokens via xstyle, className, and compound component patterns. See `astryx docs theme` for overriding tokens with defineTheme.',
+ text: 'See {@link generic:styling} for how to apply tokens via xstyle, className, and compound component patterns. See {@link generic:theme} for overriding tokens with defineTheme.',
},
],
});