Skip to content

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

TypeScript

feat(cli): `astryx docs --depth` reads as far down the docs tree as you ask (#6875)

Joeyaa0134e6109e
diff --git a/.changeset/cli-docs-depth.md b/.changeset/cli-docs-depth.md
new file mode 100644
index 0000000000..03ae4382e4
--- /dev/null
+++ b/.changeset/cli-docs-depth.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] `astryx docs <route> --depth <levels>` reads as far down the docs tree as you ask, from one doc to everything below it.
+
+`--depth 0` reads only the namespace you name, `--depth 1` adds the docs right below it (what a read without `--depth` shows), and `--depth all` goes to the bottom. With `--depth`, `--detail` sets how much of each doc below shows: `brief` (the default) is one line each, named by where it sits so you can open it, `compact` adds its sections, and `full` prints it whole. So `astryx docs cli --depth all` is a map of every CLI doc, and `astryx docs cli/integrations --depth all --detail full` prints the integration guides as one read. Where a read stops, a namespace says how many docs sit below it. `--json` returns the same tree as `docs.node`: each child carries its own `slots` while the read goes deeper, `childCount` where it stops, and its text at `compact` or `full`. `docs()` takes the same `depth` and `detail` options. Reads without `--depth` are unchanged.
+
+@josephfarina
diff --git a/packages/cli/api/docs/docs.depth.test.mjs b/packages/cli/api/docs/docs.depth.test.mjs
new file mode 100644
index 0000000000..8e261d3ea1
--- /dev/null
+++ b/packages/cli/api/docs/docs.depth.test.mjs
@@ -0,0 +1,132 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {docs} from './docs.mjs';
+
+const SLOW = 60_000;
+
+/**
+ * @param {any} node
+ * @param {string} route
+ * @returns {any}
+ */
+function findRoute(node, route) {
+ if (node.route === route) return node;
+ for (const slot of node.slots ?? []) {
+ for (const child of slot.children) {
+ const found = findRoute(child, route);
+ if (found) return found;
+ }
+ }
+ return undefined;
+}
+
+/**
+ * @param {any} node
+ * @returns {any[]}
+ */
+function children(node) {
+ return (node.slots ?? []).flatMap((/** @type {any} */ slot) => slot.children);
+}
+
+describe('docs() depth', () => {
+ it(
+ 'reads one level down, as it always has, without a depth',
+ async () => {
+ const plain = await docs('cli/api');
+ expect(plain.type).toBe('docs.node');
+ if (plain.type !== 'docs.node') return;
+ expect(plain.data).not.toHaveProperty('childCount');
+ for (const child of children(plain.data)) {
+ expect(Object.keys(child).sort()).toEqual([
+ 'kind',
+ 'name',
+ 'route',
+ 'summary',
+ 'title',
+ ]);
+ }
+ },
+ SLOW,
+ );
+
+ it(
+ 'goes as many levels down as asked, each doc below as its identity',
+ async () => {
+ const result = await docs('cli/api', undefined, {depth: 2});
+ if (result.type !== 'docs.node') throw new Error(result.type);
+ const functions = findRoute(result.data, 'cli/api/functions');
+ expect(functions).not.toHaveProperty('childCount');
+ expect(findRoute(result.data, 'cli/api/functions/search')).toEqual({
+ route: 'cli/api/functions/search',
+ name: 'search',
+ kind: 'function',
+ title: 'search()',
+ summary: expect.any(String),
+ });
+ },
+ SLOW,
+ );
+
+ it(
+ 'says how many docs sit below where the read stops',
+ async () => {
+ const one = await docs('cli/api', undefined, {depth: 1});
+ if (one.type !== 'docs.node') throw new Error(one.type);
+ const functions = findRoute(one.data, 'cli/api/functions');
+ expect(functions).not.toHaveProperty('slots');
+ expect(functions.childCount).toBeGreaterThan(1);
+
+ const zero = await docs('cli/api', undefined, {depth: 0});
+ if (zero.type !== 'docs.node') throw new Error(zero.type);
+ expect(zero.data.slots).toEqual([]);
+ expect(zero.data.childCount).toBe(children(one.data).length);
+ },
+ SLOW,
+ );
+
+ it(
+ "reads every level with 'all', and each doc's text at full detail",
+ async () => {
+ const result = await docs('cli/api', undefined, {
+ depth: 'all',
+ detail: 'full',
+ });
+ if (result.type !== 'docs.node') throw new Error(result.type);
+ expect(JSON.stringify(result.data)).not.toContain('"childCount"');
+ const search = findRoute(result.data, 'cli/api/functions/search');
+ expect(JSON.stringify(search.content)).toContain(
+ '`astryx search` runs it. Read it with `astryx docs cli/commands/search`.',
+ );
+ },
+ SLOW,
+ );
+
+ it(
+ 'reads a doc with nothing below it the same at any depth',
+ async () => {
+ expect(
+ await docs('cli/api/functions/search', undefined, {depth: 3}),
+ ).toEqual(await docs('cli/api/functions/search'));
+ },
+ SLOW,
+ );
+
+ it(
+ 'refuses a depth that is not a number of levels, and an unknown detail',
+ async () => {
+ for (const depth of [-1, 1.5, 'deep', '2']) {
+ await expect(
+ docs('cli/api', undefined, {depth: /** @type {any} */ (depth)}),
+ ).rejects.toMatchObject({code: 'ERR_INVALID_ARGUMENT'});
+ }
+ await expect(
+ docs('cli/api', undefined, {
+ depth: 1,
+ detail: /** @type {any} */ ('huge'),
+ }),
+ ).rejects.toMatchObject({code: 'ERR_INVALID_DETAIL'});
+ },
+ SLOW,
+ );
+});
diff --git a/packages/cli/api/docs/docs.doc.mjs b/packages/cli/api/docs/docs.doc.mjs
index 2872e8abb3..798e600baf 100644
--- a/packages/cli/api/docs/docs.doc.mjs
+++ b/packages/cli/api/docs/docs.doc.mjs
@@ -25,7 +25,8 @@ export const doc = {
'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` returns its children one level down (`depth` reads as many ' +
+ 'levels as asked, and `detail` how much of each doc below), a typed doc such as ' +
"`cli/api/functions/search` returns its content, and a guide the tree " +
'places (`cli/integrations/quick-start`) reads like any topic. ' +
'Every read but the list carries `links`, the commands that move from it: ' +
@@ -82,6 +83,18 @@ export const doc = {
description:
"Return the topic's section index (each section's key, title, and summary), even for a topic with one section.",
},
+ {
+ name: 'options.depth',
+ type: "number | 'all'",
+ description:
+ "How many levels below a docs-tree namespace to read: 0 for the namespace alone, 1 for its children (the default), 'all' for every level. Where a read stops, a child with docs below it carries childCount. A doc with nothing below it reads the same at any depth.",
+ },
+ {
+ name: 'options.detail',
+ type: "'brief' | 'compact' | 'full'",
+ description:
+ "How much of each doc below the named one a depth read returns: brief (the default) is its identity; compact and full add its text (a guide's sections, a namespace's or typed doc's content). Given alone, it reads one level down.",
+ },
{
name: 'options.cwd',
type: 'string',
@@ -113,10 +126,18 @@ export const doc = {
{
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.",
+ "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, or as deep as depth asks, each child carrying its own slots, childCount where the read stops, and its text at compact or full detail; a typed doc carries its content.",
},
],
throws: [
+ {
+ code: 'ERR_INVALID_ARGUMENT',
+ when: "depth is not a whole number of levels or 'all'",
+ },
+ {
+ code: 'ERR_INVALID_DETAIL',
+ when: 'detail is not brief, compact, or full',
+ },
{
code: 'ERR_UNKNOWN_TOPIC',
when: 'the topic is not a string, or matches no topic and no docs-tree route',
@@ -134,6 +155,14 @@ export const doc = {
code: "await docs('principles', undefined, {index: true});",
},
{label: 'A docs-tree namespace', code: "await docs('cli/api');"},
+ {
+ label: 'Every doc below a namespace, one entry each',
+ code: "await docs('cli', undefined, {depth: 'all'});",
+ },
+ {
+ label: 'A namespace and everything below it, in full',
+ code: "await docs('cli/integrations', undefined, {depth: 'all', detail: 'full'});",
+ },
{label: 'One API function', code: "await docs('cli/api/functions/search');"},
{
label: 'A whole guide from the docs tree',
diff --git a/packages/cli/api/docs/docs.mjs b/packages/cli/api/docs/docs.mjs
index f3e3352f2c..e065be9240 100644
--- a/packages/cli/api/docs/docs.mjs
+++ b/packages/cli/api/docs/docs.mjs
@@ -11,6 +11,7 @@
* docs(topic, undefined, {index: true}) -> index -> docs.index
* docs(topic, section) -> section -> docs.detail.section
* docs(route) -> node -> docs.node
+ * docs(route, undefined, {depth: 2}) -> node -> docs.node, two levels
*
* 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
@@ -33,6 +34,43 @@ import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
export {list, index, detail, sectionLeaf as section, nodeLeaf as node};
+const DETAILS = ['brief', 'compact', 'full'];
+
+/**
+ * How far a docs-tree read goes, from the options: `depth` levels below the
+ * node, or every level for `'all'`, and `detail` for each doc below it (brief
+ * by default). `detail` alone reads one level down. Neither: the plain read.
+ * @param {import('./docs.type.mjs').DocsOptions} options
+ * @returns {import('./node/node.mjs').DepthRead | undefined}
+ */
+function depthRead(options) {
+ const {depth, detail} = options;
+ if (detail != null && !DETAILS.includes(detail)) {
+ throw new AstryxError(
+ `detail is brief, compact, or full, not ${JSON.stringify(detail)}.`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_DETAIL,
+ );
+ }
+ if (
+ depth != null &&
+ depth !== 'all' &&
+ !(Number.isInteger(depth) && /** @type {number} */ (depth) >= 0)
+ ) {
+ throw new AstryxError(
+ `depth is a number of levels (0, 1, 2, ...) or "all", not ${JSON.stringify(depth)}.`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ if (depth == null && detail == null) return undefined;
+ return {
+ depth: depth === 'all' ? Infinity : (depth ?? 1),
+ detail: /** @type {'brief' | 'compact' | 'full'} */ (detail ?? 'brief'),
+ lang: options.lang || (options.dense ? 'dense' : options.zh ? 'zh' : null),
+ };
+}
+
/**
* @param {string} [topic]
* @param {string} [section]
@@ -42,6 +80,10 @@ export {list, index, detail, sectionLeaf as section, nodeLeaf as node};
* @param {boolean} [options.dense]
* @param {boolean} [options.index] return the topic's section index instead of
* the whole doc
+ * @param {number | 'all'} [options.depth] how many levels below a docs-tree
+ * namespace to read; a doc with nothing below it reads the same at any depth
+ * @param {'brief' | 'compact' | 'full'} [options.detail] how much of each doc
+ * below the named one a depth read returns (brief by default)
* @param {string} [options.cwd]
* @returns {Promise<
* import('./docs.type.mjs').DocsListResponse |
@@ -52,6 +94,7 @@ export {list, index, detail, sectionLeaf as section, nodeLeaf as node};
* >}
*/
export async function docs(topic, section, options = {}) {
+ const read = depthRead(options);
if (!topic) return list(options);
const found = await resolveDocsArgument(topic, options);
if (found.kind === 'node') {
@@ -77,7 +120,7 @@ export async function docs(topic, section, options = {}) {
}
return {
type: 'docs.node',
- data: await nodeView(found.catalog, found.tree, found.node),
+ data: await nodeView(found.catalog, found.tree, found.node, read),
};
}
if (section) return sectionLeaf(topic, section, options);
diff --git a/packages/cli/api/docs/docs.type.mjs b/packages/cli/api/docs/docs.type.mjs
index 6ba3c5490e..1eabba1a0d 100644
--- a/packages/cli/api/docs/docs.type.mjs
+++ b/packages/cli/api/docs/docs.type.mjs
@@ -153,7 +153,9 @@
* @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
+ * order; empty for a typed doc, and for a depth read of 0
+ * @property {number} [childCount] with a depth read of 0, how many docs sit
+ * right below the namespace
* @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
@@ -181,6 +183,15 @@
* @property {string} kind
* @property {string} title
* @property {string} summary
+ * @property {DocsNodeSlot[]} [slots] with a depth read, its own slots, while
+ * the read goes deeper
+ * @property {number} [childCount] with a depth read, how many docs sit right
+ * below it where the read stops
+ * @property {import('@astryxdesign/cli/authoring').ReferenceContentBlock[]} [content]
+ * with a depth read at compact or full detail: a namespace's intro or a typed
+ * doc's content
+ * @property {DocsReadSection[]} [sections] with a depth read at compact or full
+ * detail: a guide's sections
*/
/**
@@ -191,6 +202,12 @@
* @property {boolean} [dense]
* @property {boolean} [index] return a topic's section index instead of its
* whole doc
+ * @property {number | 'all'} [depth] how many levels below a docs-tree
+ * namespace to read: 0 for the namespace alone, 1 for its children (the
+ * default), 'all' for every level
+ * @property {'brief' | 'compact' | 'full'} [detail] how much of each doc below
+ * the named one a depth read returns: brief (the default) is its identity,
+ * compact and full add its text
* @property {string} [cwd] project directory whose configured integrations
* contribute topics; defaults to process.cwd()
*/
diff --git a/packages/cli/api/docs/node/node.mjs b/packages/cli/api/docs/node/node.mjs
index 0a6ec9041a..72cf3cb648 100644
--- a/packages/cli/api/docs/node/node.mjs
+++ b/packages/cli/api/docs/node/node.mjs
@@ -7,14 +7,18 @@
* 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>`.
+ * children (a namespace) or its content (a typed doc). By default a
+ * namespace lists its children one level down; a depth read goes as far
+ * down as asked, with each doc below as its identity (brief) or with its
+ * text (compact, full). Matches `astryx --json docs <route> [--depth <n>]`.
* @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 {detailView} from '../../../foundation/doc-compiler/lenses.mjs';
import {
+ compileTopic,
+ guideEntry,
nodeContent,
placeLinks,
resolveDocsArgument,
@@ -24,18 +28,34 @@ import {
/**
* @typedef {import('../../../foundation/doc-compiler/tree.mjs').DocsTree} DocsTree
* @typedef {import('../../../foundation/doc-compiler/tree.mjs').TreeNode} TreeNode
+ * @typedef {import('../../../foundation/discovery/docs-discovery.mjs').DocsCatalog} DocsCatalog
*/
/**
- * The docs.node view of one tree node.
- * @param {import('../../../foundation/discovery/docs-discovery.mjs').DocsCatalog} catalog
+ * How far a read goes below the node it names, and how much of each doc below
+ * it shows: `depth` levels (Infinity for every level), and `detail` brief (its
+ * identity), or compact or full (with its text: a namespace's intro, a guide's
+ * sections, a typed doc's content). `lang` selects the guides' language.
+ * @typedef {object} DepthRead
+ * @property {number} depth
+ * @property {'brief' | 'compact' | 'full'} detail
+ * @property {string | null} lang
+ */
+
+/**
+ * The docs.node view of one tree node. Without a depth read, a namespace lists
+ * its children one level down.
+ * @param {DocsCatalog} catalog
* @param {DocsTree} tree
* @param {TreeNode} node
+ * @param {DepthRead} [read] how far down to go, and how much of each doc below
* @returns {Promise<import('../docs.type.mjs').DocsNode>}
*/
-export async function nodeView(catalog, tree, node) {
+export async function nodeView(catalog, tree, node, read) {
const {content} = await nodeContent(catalog, tree, node);
- return {
+ const slots = node.slots.filter(slot => slot.children.length > 0);
+ /** @type {import('../docs.type.mjs').DocsNode} */
+ const view = {
id: node.id,
route: node.route,
kind: node.kind,
@@ -45,25 +65,128 @@ export async function nodeView(catalog, tree, node) {
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,
- };
- }),
- })),
+ slots: !read
+ ? slots.map(slot => ({
+ name: slot.name,
+ title: slot.title,
+ children: slot.children.map(route =>
+ childIdentity(/** @type {TreeNode} */ (tree.get(route))),
+ ),
+ }))
+ : read.depth >= 1
+ ? await slotsBelow(catalog, tree, slots, 1, read)
+ : [],
content,
links: nodeLinks(tree, node),
};
+ if (read && read.depth < 1 && slots.length > 0) {
+ view.childCount = countChildren(slots);
+ }
+ return view;
+}
+
+/**
+ * The fields every child carries: what it is, and the route that opens it.
+ * @param {TreeNode} child
+ * @returns {import('../docs.type.mjs').DocsNodeChild}
+ */
+function childIdentity(child) {
+ return {
+ route: child.route,
+ name: child.route.slice(child.route.lastIndexOf('/') + 1),
+ kind: child.kind,
+ title: child.title,
+ summary: child.summary,
+ };
+}
+
+/**
+ * @param {TreeNode['slots']} slots
+ * @returns {number}
+ */
+function countChildren(slots) {
+ return slots.reduce((count, slot) => count + slot.children.length, 0);
+}
+
+/**
+ * Slots read `level` levels below the named node: each child at the read's
+ * detail, and its own slots while the read goes deeper.
+ * @param {DocsCatalog} catalog
+ * @param {DocsTree} tree
+ * @param {TreeNode['slots']} slots
+ * @param {number} level
+ * @param {DepthRead} read
+ * @returns {Promise<import('../docs.type.mjs').DocsNodeSlot[]>}
+ */
+async function slotsBelow(catalog, tree, slots, level, read) {
+ return Promise.all(
+ slots.map(async slot => ({
+ name: slot.name,
+ title: slot.title,
+ children: await Promise.all(
+ slot.children.map(route =>
+ childBelow(
+ catalog,
+ tree,
+ /** @type {TreeNode} */ (tree.get(route)),
+ level,
+ read,
+ ),
+ ),
+ ),
+ })),
+ );
+}
+
+/**
+ * One child of a depth read. Where the read stops, a child with docs below it
+ * says how many, so a reader knows to go deeper.
+ * @param {DocsCatalog} catalog
+ * @param {DocsTree} tree
+ * @param {TreeNode} child
+ * @param {number} level
+ * @param {DepthRead} read
+ * @returns {Promise<import('../docs.type.mjs').DocsNodeChild>}
+ */
+async function childBelow(catalog, tree, child, level, read) {
+ const view = childIdentity(child);
+ if (read.detail !== 'brief') {
+ Object.assign(view, await childText(catalog, tree, child, read.lang));
+ }
+ const slots = child.slots.filter(slot => slot.children.length > 0);
+ if (slots.length > 0) {
+ if (level < read.depth) {
+ view.slots = await slotsBelow(catalog, tree, slots, level + 1, read);
+ } else {
+ view.childCount = countChildren(slots);
+ }
+ }
+ return view;
+}
+
+/**
+ * A child's text: a guide's compiled sections, or the content of a namespace
+ * or typed doc.
+ * @param {DocsCatalog} catalog
+ * @param {DocsTree} tree
+ * @param {TreeNode} child
+ * @param {string | null} lang
+ * @returns {Promise<{content?: any[], sections?: any[]}>}
+ */
+async function childText(catalog, tree, child, lang) {
+ if (child.kind === 'generic') {
+ const entry = child.ref?.topicFile
+ ? guideEntry(child)
+ : child.ref?.flatTopic
+ ? catalog.resolve(child.ref.flatTopic)
+ : null;
+ if (!entry) return {};
+ return {
+ sections: detailView(await compileTopic(catalog, entry, lang)).sections,
+ };
+ }
+ const {content} = await nodeContent(catalog, tree, child);
+ return {content};
}
/**
diff --git a/packages/cli/clients/cli/commands/docs.depth.test.mjs b/packages/cli/clients/cli/commands/docs.depth.test.mjs
new file mode 100644
index 0000000000..086d34d474
--- /dev/null
+++ b/packages/cli/clients/cli/commands/docs.depth.test.mjs
@@ -0,0 +1,219 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+
+const SLOW = 60_000;
+
+/** @type {string} */
+let tmpDir;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-docs-depth-test-'));
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+/** An app with an integration that places one guide under its namespace. */
+function scaffoldGuide() {
+ 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 packageDir = path.join(tmpDir, 'node_modules', '@acme', 'kit');
+ fs.mkdirSync(path.join(packageDir, 'docs'), {recursive: true});
+ fs.writeFileSync(
+ path.join(packageDir, 'package.json'),
+ JSON.stringify({name: '@acme/kit', version: '1.0.0'}),
+ );
+ fs.writeFileSync(
+ path.join(packageDir, 'astryx.integration.mjs'),
+ "export default {docs: './docs'};\n",
+ );
+ const namespace = {
+ type: 'namespace',
+ name: 'acme',
+ title: 'Acme docs',
+ summary: 'Build with the Acme kit.',
+ slots: {guides: {title: 'Guides', accepts: {kinds: ['generic']}}},
+ };
+ const guide = {
+ type: 'generic',
+ name: 'themes',
+ title: 'Theme building',
+ description: 'Build an Acme theme.',
+ placement: {parent: 'namespace:acme', slot: 'guides'},
+ sections: [
+ {
+ title: 'Create the theme',
+ content: [
+ {
+ type: 'prose',
+ text: 'Child guide body marker: compile the ocean palette.',
+ },
+ {type: 'code', lang: 'bash', code: 'npx acme theme build ocean'},
+ ],
+ },
+ ],
+ };
+ for (const [file, doc] of [
+ ['acme.doc.mjs', namespace],
+ ['themes.doc.mjs', guide],
+ ]) {
+ fs.writeFileSync(
+ path.join(packageDir, 'docs', file),
+ `export const docs = ${JSON.stringify(doc, null, 2)};\n`,
+ );
+ }
+}
+
+describe('astryx docs --depth', () => {
+ it(
+ 'lists every doc below a namespace, one line each, by where it sits',
+ async () => {
+ const result = await runCli(['docs', 'cli/api', '--depth', 'all']);
+ expect(result.status).toBe(0);
+ expect(result.stdout).toMatch(/^functions\s+\S/m);
+ expect(result.stdout).toMatch(/^functions\/search\s+search\(\): /m);
+ expect(result.stdout).toContain('Open one: ');
+ expect(result.stdout).toContain('docs cli/api/<name>');
+ // One line each: no doc's body.
+ expect(result.stdout).not.toContain('`astryx search` runs it.');
+ },
+ SLOW,
+ );
+
+ it(
+ 'says how many docs sit below where the read stops',
+ async () => {
+ const zero = await runCli(['docs', 'cli/api', '--depth', '0']);
+ expect(zero.status).toBe(0);
+ expect(zero.stdout).toMatch(
+ /^\d+ docs below\. Read them: .*docs cli\/api --depth 1$/m,
+ );
+ expect(zero.stdout).not.toMatch(/^functions\s/m);
+
+ const one = await runCli(['docs', 'cli/api', '--depth', '1']);
+ expect(one.status).toBe(0);
+ expect(one.stdout).toMatch(/^functions\s+.*\(\d+ docs below\)$/m);
+ expect(one.stdout).not.toMatch(/^functions\/search\s/m);
+ },
+ SLOW,
+ );
+
+ it(
+ 'prints each doc below whole with --detail full, and drops code at compact',
+ async () => {
+ scaffoldGuide();
+ const full = await runCli(
+ ['docs', 'acme', '--depth', 'all', '--detail', 'full'],
+ tmpDir,
+ );
+ expect(full.status).toBe(0);
+ expect(full.stdout).toMatch(/^## Theme building \(themes\)$/m);
+ expect(full.stdout).toMatch(/^### Create the theme$/m);
+ expect(full.stdout).toContain(
+ 'Child guide body marker: compile the ocean palette.',
+ );
+ expect(full.stdout).toContain('npx acme theme build ocean');
+
+ const compact = await runCli(
+ ['docs', 'acme', '--depth', '1', '--detail', 'compact'],
+ tmpDir,
+ );
+ expect(compact.status).toBe(0);
+ expect(compact.stdout).toContain('Child guide body marker');
+ expect(compact.stdout).not.toContain('npx acme theme build ocean');
+
+ // Without --depth, the namespace still lists the guide by one line.
+ const plain = await runCli(['docs', 'acme'], tmpDir);
+ expect(plain.status).toBe(0);
+ expect(plain.stdout).toMatch(/^themes\s+Build an Acme theme\./m);
+ expect(plain.stdout).not.toContain('Child guide body marker');
+ },
+ SLOW,
+ );
+
+ it(
+ 'returns the same tree as JSON, with text only when --detail asks',
+ async () => {
+ const brief = await runCli(['--json', 'docs', 'cli/api', '--depth', '2']);
+ expect(brief.status).toBe(0);
+ const briefData = JSON.parse(brief.stdout);
+ expect(briefData.type).toBe('docs.node');
+ const functions = briefData.data.slots
+ .flatMap((/** @type {any} */ slot) => slot.children)
+ .find(
+ (/** @type {any} */ child) => child.route === 'cli/api/functions',
+ );
+ const search = functions.slots
+ .flatMap((/** @type {any} */ slot) => slot.children)
+ .find(
+ (/** @type {any} */ child) =>
+ child.route === 'cli/api/functions/search',
+ );
+ expect(search).not.toHaveProperty('content');
+
+ const full = await runCli([
+ '--json',
+ 'docs',
+ 'cli/api',
+ '--depth',
+ '2',
+ '--detail',
+ 'full',
+ ]);
+ expect(full.status).toBe(0);
+ expect(full.stdout).toContain('`astryx search` runs it.');
+ },
+ SLOW,
+ );
+
+ it(
+ 'composes with --index and --full, and leaves a topic read as it was',
+ async () => {
+ const depth = await runCli(['docs', 'cli/api', '--depth', '1']);
+ expect(depth.status).toBe(0);
+ for (const flag of ['--index', '--full']) {
+ const both = await runCli(['docs', 'cli/api', '--depth', '1', flag]);
+ expect(both.status).toBe(0);
+ expect(both.stdout).toBe(depth.stdout);
+ }
+ for (const args of [
+ ['docs', 'theme'],
+ ['docs', 'theme', '--index'],
+ ['docs', 'theme', '--full'],
+ ]) {
+ const plain = await runCli(args);
+ const withDepth = await runCli([...args, '--depth', '2']);
+ expect(withDepth.status).toBe(plain.status);
+ expect(withDepth.stdout).toBe(plain.stdout);
+ }
+ },
+ SLOW,
+ );
+
+ it(
+ 'refuses a depth that is not a number of levels',
+ async () => {
+ const result = await runCli([
+ '--json',
+ 'docs',
+ 'cli/api',
+ '--depth',
+ 'deep',
+ ]);
+ expect(result.status).toBe(1);
+ expect(JSON.parse(result.stdout).code).toBe('ERR_INVALID_ARGUMENT');
+ },
+ SLOW,
+ );
+});
diff --git a/packages/cli/clients/cli/commands/docs.doc.mjs b/packages/cli/clients/cli/commands/docs.doc.mjs
index dedb18f245..7ccced889f 100644
--- a/packages/cli/clients/cli/commands/docs.doc.mjs
+++ b/packages/cli/clients/cli/commands/docs.doc.mjs
@@ -22,7 +22,9 @@ export const doc = {
'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.',
+ 'one. `--depth` reads as far down the tree as you ask, from the doc alone (0) to ' +
+ 'everything below it (all), and with it `--detail` sets how much of each doc below ' +
+ 'shows: one line (brief, the default), its sections (compact), or all of it (full).',
fn: 'docs',
args: [
{name: 'topic', param: 'topic', required: false},
@@ -39,6 +41,12 @@ export const doc = {
description:
'Print the whole topic instead of its sections (text; `--json` returns the whole topic unless --index). Cannot be set with --index',
},
+ {
+ flag: '--depth <levels>',
+ param: 'options.depth',
+ description:
+ 'How many levels of the docs tree to read below a namespace: 0 for the namespace alone, 1 for its children (what a read without --depth shows), all for everything below it. With it, --detail sets how much of each doc below shows: brief (one line each, the default), compact (with its sections), or full',
+ },
],
examples: [
{label: 'List topics', cli: 'astryx docs'},
@@ -46,6 +54,11 @@ export const doc = {
{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: 'Every CLI doc, one line each', cli: 'astryx docs cli --depth all'},
+ {
+ label: 'The integration guides as one read',
+ cli: 'astryx docs cli/integrations --depth all --detail full',
+ },
{label: 'One API function', cli: 'astryx docs cli/api/functions/search'},
{label: 'A whole guide', cli: 'astryx docs cli/integrations/quick-start --full'},
],
@@ -53,7 +66,7 @@ export const doc = {
{code: 0, when: 'success'},
{
code: 1,
- when: 'unknown topic or route, or a section that matches no section or more than one',
+ when: 'unknown topic or route, a section that matches no section or more than one, or a --depth that is not a number of levels or all',
},
],
related: ['search', 'component', 'hook', 'template'],
diff --git a/packages/cli/clients/cli/commands/docs.mjs b/packages/cli/clients/cli/commands/docs.mjs
index b719855de0..556be9be7e 100644
--- a/packages/cli/clients/cli/commands/docs.mjs
+++ b/packages/cli/clients/cli/commands/docs.mjs
@@ -4,9 +4,10 @@
* @file docs command — Print Astryx reference docs
*
* 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.
+ * open one section by its key, and `--full` prints the whole topic. `--depth`
+ * reads a docs-tree namespace as many levels down as asked, each doc below it
+ * at --detail (brief by default: one line each). `--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). A code
* block's label prints above its fence, and table cells escape their pipes.
*
@@ -18,6 +19,7 @@
* 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
+ * astryx docs <route> --depth <n|all> Read that many levels below it
*/
import {
@@ -181,6 +183,202 @@ function formatReferenceFull(docs, detail) {
return `${header}\n\n${sections.join(sep)}`;
}
+/**
+ * @param {string} title
+ * @param {number} level
+ * @returns {string}
+ */
+function treeHeading(title, level) {
+ return `${'#'.repeat(Math.max(1, Math.min(6, level)))} ${title}`;
+}
+
+/**
+ * A doc's blocks at one depth: its headings move down with it.
+ * @param {import('@astryxdesign/cli/authoring').ReferenceContentBlock[]} blocks
+ * @param {'full' | 'compact' | 'brief'} detail
+ * @param {number} headingOffset
+ * @returns {string[]}
+ */
+function formatTreeBlocks(blocks, detail, headingOffset) {
+ /** @type {string[]} */
+ const formatted = [];
+ for (const block of blocks) {
+ const value =
+ block.type === 'heading'
+ ? treeHeading(block.text, (block.level || 3) + headingOffset)
+ : formatBlock(block, detail);
+ if (value) formatted.push(value);
+ }
+ return formatted;
+}
+
+/**
+ * @param {import('../../../api/docs/docs.type.mjs').DocsReadSection} docSection
+ * @param {'full' | 'compact' | 'brief'} detail
+ * @param {number} headingLevel
+ * @returns {string}
+ */
+function formatTreeSection(docSection, detail, headingLevel) {
+ const heading = treeHeading(docSection.title, headingLevel);
+ const blocks = formatTreeBlocks(docSection.content, detail, headingLevel - 2);
+ return blocks.length > 0 ? `${heading}\n\n${blocks.join('\n\n')}` : heading;
+}
+
+/**
+ * Where a route sits below the namespace a read names.
+ * @param {string} route
+ * @param {string} root
+ * @returns {string}
+ */
+function belowRoot(route, root) {
+ return route.startsWith(`${root}/`) ? route.slice(root.length + 1) : route;
+}
+
+/**
+ * @param {number} count
+ * @returns {string}
+ */
+function docsBelow(count) {
+ return `${count} ${count === 1 ? 'doc' : 'docs'} below`;
+}
+
+/**
+ * Every child of a depth read, one row each in reading order, named by where
+ * it sits below the read's namespace.
+ * @param {import('../../../api/docs/docs.type.mjs').DocsNodeChild[]} children
+ * @param {string} root
+ * @returns {{name: string, summary: string}[]}
+ */
+function treeRows(children, root) {
+ return children.flatMap(child => [
+ {
+ name: belowRoot(child.route, root),
+ summary: child.childCount
+ ? `${childRow(child).summary} (${docsBelow(child.childCount)})`
+ : childRow(child).summary,
+ },
+ ...(child.slots ?? []).flatMap(slot => treeRows(slot.children, root)),
+ ]);
+}
+
+/**
+ * One child of a depth read with its text, under a heading for its level, and
+ * its own children below it.
+ * @param {import('../../../api/docs/docs.type.mjs').DocsNodeChild} child
+ * @param {'full' | 'compact'} detail
+ * @param {number} level
+ * @param {string} root
+ * @param {string} run
+ * @returns {string}
+ */
+function formatTreeChild(child, detail, level, root, run) {
+ const parts = [
+ `${treeHeading(child.title, level)} (${belowRoot(child.route, root)})`,
+ ];
+ if (
+ child.summary &&
+ (child.kind === 'namespace' || child.kind === 'generic')
+ ) {
+ parts.push(child.summary);
+ }
+ const content = formatTreeBlocks(child.content ?? [], detail, level - 2);
+ if (content.length > 0) parts.push(content.join('\n\n'));
+ parts.push(
+ ...(child.sections ?? []).map(docSection =>
+ formatTreeSection(docSection, detail, level + 1),
+ ),
+ );
+ if (child.childCount) {
+ parts.push(
+ `${docsBelow(child.childCount)}: ${run} docs ${child.route} --depth 1`,
+ );
+ }
+ for (const slot of child.slots ?? []) {
+ parts.push(
+ ...slot.children.map(each =>
+ formatTreeChild(each, detail, level + 1, root, run),
+ ),
+ );
+ }
+ return parts.join('\n\n');
+}
+
+/**
+ * A depth read of a namespace: its intro, then each slot's docs as deep as
+ * asked, one line each (brief) or with their text (compact, full). A typed doc
+ * has nothing below it, so it reads as it always does.
+ * @param {import('../../../api/docs/docs.type.mjs').DocsNode} node
+ * @param {'full' | 'compact' | 'brief'} detail how the named node reads
+ * @param {'full' | 'compact' | 'brief'} childDetail how each doc below reads
+ * @param {string} run
+ */
+function emitTree(node, detail, childDetail, run) {
+ if (node.kind !== 'namespace') {
+ emitNode(node, detail, run);
+ return;
+ }
+ /**
+ * @param {import('../../../api/docs/docs.type.mjs').DocsNodeChild[]} children
+ * @returns {string[]}
+ */
+ const routes = children =>
+ children.flatMap(child => [
+ child.route,
+ ...(child.slots ?? []).flatMap(slot => routes(slot.children)),
+ ]);
+ const allBelow = node.slots
+ .flatMap(slot => routes(slot.children))
+ .every(route => route.startsWith(`${node.route}/`));
+ const root = allBelow ? node.route : '';
+ emit(
+ section(node.title, wrapText(node.summary)),
+ ...(node.content?.length
+ ? [
+ text(
+ node.content
+ .map(b => formatBlock(b, detail))
+ .filter(Boolean)
+ .join('\n\n'),
+ ),
+ ]
+ : []),
+ ...(node.childCount
+ ? [
+ text(
+ `${docsBelow(node.childCount)}. Read them: ${run} docs ${node.route} --depth 1`,
+ ),
+ ]
+ : []),
+ ...node.slots.flatMap(slot => [
+ ...(node.slots.length === 1 && slot.title === node.title
+ ? []
+ : [section(slot.title)]),
+ childDetail === 'brief'
+ ? records(treeRows(slot.children, root), {
+ fields: ['name', 'summary'],
+ layout: 'inline',
+ })
+ : code(
+ slot.children
+ .map(child => formatTreeChild(child, childDetail, 2, root, run))
+ .join('\n\n'),
+ ),
+ ]),
+ text(
+ [
+ ...(node.slots.length > 0
+ ? [
+ allBelow
+ ? `Open one: ${run} docs ${node.route}/<name>`
+ : `Open one: ${run} docs <name>`,
+ ]
+ : []),
+ ...linkLines(node.links),
+ ].join('\n'),
+ ),
+ );
+}
+
/**
* 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.
@@ -331,7 +529,7 @@ export function registerDocs(program) {
action: async (
/** @type {string | undefined} */ topic,
/** @type {string | undefined} */ sectionName,
- /** @type {{index?: boolean, full?: boolean}} */ options = {},
+ /** @type {{index?: boolean, full?: boolean, depth?: string}} */ options = {},
) => {
const run = getCliInvocation();
const lang = program.opts().lang || null;
@@ -346,6 +544,22 @@ export function registerDocs(program) {
{code: ERROR_CODES.ERR_INVALID_ARGUMENT},
);
}
+ /** @type {number | 'all' | undefined} */
+ let depth;
+ if (options.depth != null) {
+ if (options.depth === 'all') depth = 'all';
+ else if (/^\d+$/.test(options.depth)) depth = Number(options.depth);
+ else {
+ return cliError(
+ `--depth takes a number of levels (0, 1, 2, ...) or all, not "${options.depth}".`,
+ {code: ERROR_CODES.ERR_INVALID_ARGUMENT},
+ );
+ }
+ }
+ // With --depth, --detail is how much of each doc below shows; left at
+ // its default, each is one line.
+ const childDetail =
+ program.getOptionValueSource('detail') === 'default' ? 'brief' : detail;
// 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.
@@ -363,6 +577,7 @@ export function registerDocs(program) {
zh,
dense,
index: listSections,
+ ...(depth != null ? {depth, detail: childDetail} : {}),
});
if (
!options.index &&
@@ -417,6 +632,7 @@ export function registerDocs(program) {
` ${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`,
+ ` ${run} docs cli --depth all every doc below cli, one line each`,
`With --json, a topic returns its whole doc; add --index for its section list.`,
].join('\n'),
),
@@ -462,7 +678,8 @@ export function registerDocs(program) {
}
case 'docs.node': {
- emitNode(result.data, detail, run);
+ if (depth != null) emitTree(result.data, detail, childDetail, run);
+ else emitNode(result.data, detail, run);
break;
}
}
diff --git a/packages/cli/test/docs-graph.test.mjs b/packages/cli/test/docs-graph.test.mjs
index 172dd7e593..5c4d7b9e39 100644
--- a/packages/cli/test/docs-graph.test.mjs
+++ b/packages/cli/test/docs-graph.test.mjs
@@ -52,10 +52,36 @@ function open(command) {
throw new Error(`not a docs command: ${command}`);
}
const rest = words.slice(2);
- const [topic, section] = rest.filter(w => !w.startsWith('--'));
+ /** @type {string[]} */
+ const positional = [];
+ /** @type {Record<string, string>} */
+ const valued = {};
+ for (let i = 0; i < rest.length; i++) {
+ const word = rest[i];
+ if (word === '--depth' || word === '--detail' || word === '--lang') {
+ valued[word.slice(2)] = rest[++i];
+ } else if (!word.startsWith('--')) {
+ positional.push(word);
+ }
+ }
+ const [topic, section] = positional;
+ const depth =
+ valued.depth == null
+ ? undefined
+ : valued.depth === 'all'
+ ? 'all'
+ : Number(valued.depth);
return docs(topic, section, {
index: rest.includes('--index'),
full: rest.includes('--full'),
+ ...(depth == null
+ ? {}
+ : {
+ depth,
+ ...(valued.detail
+ ? {detail: /** @type {any} */ (valued.detail)}
+ : {}),
+ }),
});
}