Skip to content

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

TypeScript

feat(cli): validate notes each Astryx command a topic writes with a package runner (#7746)

Joey968130fb0d6d
diff --git a/.changeset/runner-commands.md b/.changeset/runner-commands.md
new file mode 100644
index 0000000000..de185733e6
--- /dev/null
+++ b/.changeset/runner-commands.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] From 0.7.3, `doctor integration validate` (and so `integration check`) lists each Astryx command a topic writes with a package runner as a `runner_command` note in `data.notes`, with its file, line and the bare `astryx <command>` to write. A note fails nothing, so `integration check --strict` exits as before. The unscoped name after a download runner (`npx astryx`) always counts, because it fetches an unrelated package; the scoped `npx @astryxdesign/cli`, for install steps, does not.
+@josephfarina
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 705d497a60..8fbdc23823 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -470,69 +470,69 @@ Every response has a `type` discriminant. The full set is below (generated from
<!-- BEGIN GENERATED: response-types -->
-| Type | What `data` carries |
-| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. |
-| `init.remove` | The removal receipt — returned when --remove-agents is set: `data.removed` is true when a managed agent-docs block was found and removed, and false when there was none to remove. |
-| `init.user` | The computer-level agent text receipt — returned when --user is set: `data.files`, one `{path, action, reason?}` per path acted on, the skill file first and then each link to its folder (action `written` \| `linked` \| `unchanged` \| `removed` \| `absent` \| `kept`; `reason` only on `kept`: `edited` when a person changed the text, `not-astryx` when Astryx did not write it), `data.command` (the command the text names), and `data.warnings`. |
-| `component.list` | The component catalog grouped by component group (each component's group field): `detail` (the level: names \| compact \| full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries ({name, package, description, import}), or a full ComponentDoc per entry with its package. |
-| `component.batch` | The component specialization of the shared `BatchResponse` and `BatchRow` types. An explicit programmatic selector array, or two or more CLI selectors, returns one ordered receipt: `count` plus `results`, one row per selector including duplicates. Every row carries `selector` and `status` (found \| not_found \| ambiguous \| error). A found row carries `result`, the same {type, data} response as one selector. An ambiguous row carries `code`, `error`, and `candidates` ({package, component, kind, installed}). Other failed rows carry `code`, `error`, and optional `suggestions` ({name, reason}). |
-| `component.detail` | One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc). The envelope's package names the same owner. |
-| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). The envelope's package names the npm package that owns the component. |
-| `component.detail.source` | One component's source file, as {component, source}. The envelope's package names the npm package that owns the component. |
-| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. The envelope's package names the npm package that owns the component. |
-| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry ({name, package, displayName, description, isShowcase, category}); each block names the package that owns it, and the envelope's package names the component's owner. |
-| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description, package, replaces?}), in read order; meta.namespaces lists the docs tree's top-level namespaces, and meta.notLoaded each package whose docs did not load. |
-| `docs.detail` | One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined and each section naming the package that wrote it, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
-| `docs.index` | One topic's section index, the text read of a topic with more than one section (and --index): the topic's name, title, and description, plus sections, each {id, title, package, summary} (pass the id as the section argument; package is the npm package that wrote the section; summary is the section's one-line summary), and links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
-| `docs.detail.section` | One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open its topic index and the sections before and after it). The envelope's package names the npm package that wrote the section. |
-| `docs.node` | One node of the docs tree, read by its route: its id, kind, package, title, summary, and breadcrumb, plus a namespace's slots with their children (one level down, each naming its package) or a typed doc's content, and links ({up, previous, next, related}: the commands that open its parent, its neighbors, and the docs it names). |
-| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |
-| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |
-| `discover.list` | What the project has, the integrations it loads and the official packages it declares, official packages first (name, category, components, version, a list per other kind they add, and latest when a source knows it); meta.available lists what the project could add, the official packages first, each with the command that adds it, and meta.sources reports each source, the official list last; when it lists no integration it carries meta.configured to tell "nothing configured" from "nothing discovered". |
-| `discover.detail` | One package, for an @scope/name or @scope/name@version query: what the shown version adds, whether the project has it, and, when a source knows the package, its versions, latest release, and the command that adds it. |
-| `discover.detail.doc` | The validated ComponentDoc for one installed component, for an @scope/name/Component query. |
-| `discover.item` | One item that is not an installed component, for an @scope/name/<item> query: its kind, name, package, version, and whether the project has the package. |
-| `discover.search` | The echoed query plus every matching item and package across all packages, each with its kind and whether the project has it, even when only one matches; total is set when --limit cut the list. |
-| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, package, score, reason, description, command} (package is the npm package that owns the result), plus import (components, hooks), title, parent (the command that opens the level above), and, for a hit on one section, section (docs), or displayName and kind (templates). When a search with no `type` could not obtain @astryxdesign/core, `meta.partial` is {skipped, reason}: the domains it skipped (component, hook, template) and why. |
-| `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. |
-| `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, package, command, basis, reason, alternatives, ...} (the start and each alternative name the package that owns the template), pages (search's closest templates), blocks and domain as SearchResultEntry[] (each naming its package), frame and foundation (Core component names), and hint {reason, commands} when thin. |
-| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. The envelope's package is @astryxdesign/core. |
-| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. The envelope's package names the same owning package. |
-| `gap-report.categories` | The fixed gap category values and human-readable labels; when a loaded integration names its own issues URL, meta.destinations lists every destination ({to, default, issuesUrl}) and meta.ask tells an agent to ask the person. |
-| `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals; without --to, when a loaded integration names its own issues URL, destinations and ask as on gap-report.categories. |
-| `template.list` | The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list. |
-| `template.show` | The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). |
-| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. The envelope's package names the npm package that owns the template. |
-| `template.copy` | A scaffold receipt: template id, output directory, written file name, file count, demoMediaReplaced (how many Astryx demo media references were replaced with placeholders), notes (setup notes naming what the template needs that the project lacks — missing packages, missing StyleX compiler; empty when satisfied), missingPackages (external package names the template imports that are not in the project), and installCommand (a ready-to-run install command with the detected package manager and workspace version ranges; null when nothing is missing, or when several lockfiles leave the package manager undetermined). The envelope's package names the npm package that owns the template. |
-| `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
-| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. The envelope's package is @astryxdesign/core, the only package that ships hooks. |
-| `hook.detail` | One hook's full authored HookDoc. The envelope's package is @astryxdesign/core. |
-| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). The envelope's package is @astryxdesign/core. |
-| `theme.build` | A theme build receipt: name, tokenCount and componentCount (override counts), sizeKB, the written outputs {css, cssDts, js, dts, and variantsDts when applicable}, warnings (defects to fix), and notices (advisories about a correct theme, such as a named font it does not load). |
-| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |
-| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |
-| `theme.list` | Every bundled, installed package, and local theme as a ThemeListEntry[]. Each entry has slug, displayName, description, maintained, owner package or local root, source, added, and default fields. Optional meta.unmigratedCopies names earlier descriptor-less copies, their missing descriptor, and the upgrade command; those copies are not data entries. |
-| `theme.app` | The app theme record after add, remove, or use. It includes every added theme and its built imports, the default slug, generated module path, and the command change. After add, the envelope package names the npm package that owns the added theme; a local theme has none. |
-| `theme.eject` | A local source-fork receipt with the resolved slug, displayName, source theme maintained flag, source-selector package, outputDir, source entry, exportName, and every file written, including the descriptor. The written local descriptor always uses maintained: false. |
-| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
-| `theme.targets` | The whole themeable surface: the echoed filter, componentCount, and targets, one per theming target — {key, className, component, props, states}, where props and states are its legal override keys. |
-| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |
-| `upgrade.list` | Every available codemod, oldest→newest, as {name, package, title, version, optional}; returned for --list without running anything. |
-| `upgrade.registry` | The copied-composition receipt for --registry: applied, ok, the counts (found, current, wouldUpdate, updated, wouldMerge, merged, wouldRefreshReceipt, receiptsRefreshed, conflicts, missing, invalid, failed), and items. |
-| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. no_codemods and config_fixable carry cliBehindCore ({cliVersion, command}) when the installed Core is newer than the CLI, which then has no codemods for the releases after its own version. |
-| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, sourcePathFound (false when the resolved source directory does not exist, so no source file was read), and (apply mode) filesChanged, transformsApplied, and per-codemod errors. When the installed Core is newer than the CLI, it also carries cliBehindCore ({cliVersion, command}): codemods for the releases after cliVersion did not run. |
-| `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], outsideProject? (same, refuse, or own; absent on a group), subcommands?), jsonSupported, globalMode ({docs, summary}: what a run may do beyond its command, such as the hand-off to the project's own CLI, the daily update check, and the agent skill file, and the docs topic that explains it), and the flat responseTypes index. |
-| `help` | Help, in one of two shapes. A bare `astryx --json` returns the root manifest: name, version, commands (the command names), jsonSupported, and manifest (the full payload `astryx manifest --json` returns). `--help --json` on any command, or `astryx help [command] --json`, returns that command's help: command, description, usage, options (each flags, description, and defaultValue and choices when set), and subcommands (each name and description). data.manifest marks the first shape; data.usage marks the second. |
-| `version` | The CLI version, for `astryx --version --json`: {version}. |
-| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and an optional fix, always present on warn and fail) plus a `summary` of counts per status. |
-| `integration.add` | A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun. |
-| `integration.pack-check` | The packed-package check: name, version, packable, tarball {filename, fileCount, size, unpackedSize} or null, inventory {manifest, roots [{kind, path, expectedFiles, missingFiles, complete}], expectedFiles, packedFiles}, contributions {local, packed}, each null or {themes [{slug, exportName}], components, templates [{id, type, name}], codemods [{version, id}], docs, agentDocsAppend}, and issues [{code, severity, message, fix?, file?, line?}] (the issues validation finds in the source and, prefixed packed_, in the packed tree, with the fix and the place when the check knows them). |
-| `integration.validate` | The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message, fix?, file?, line?} (fix: the change that resolves it; file and line: where, relative to the package), and notes when there are any: {code, message} information that fails nothing, such as invalid_cli_command for a malformed cliCommand, and the package layout findings added after the last minor release, each with its fix in the message (duplicate_component_doc, symlinked_root, unreadable_file, invalid_package_json, no_provider_id, source_without_component_doc where a doc and its source still pair), and doc_name_mismatch and unknown_block_component, until they become warnings in the next minor release. When the manifest loads, docTypes checks each doc against its published authoring type: status (checked \| skipped), reason, typescript, docs, findings (all warnings, each naming the field and a fix), unchecked, and fixtures (test fixture docs not checked). When the manifest loads, docNames lists the component doc names it could not judge: status (checked), findings (always empty; a doc name the module its import names provably does not export is a doc_name_mismatch note, with its fix in the message) and unchecked ({file, name, reason}: a doc whose name differs from the name it is listed under and whose source exports cannot all be read, such as a re-export from another package). When the manifest loads, blockComponents lists the component names templates give in exampleFor or componentsUsed that could not be judged: status (checked), findings (always empty; a name neither the package nor Core has, and the template does not import, is an unknown_block_component note, with its fix in the message) and unchecked ({file, name, reason}: a name the template may reach through anything other than named imports and re-exports from Core, React, StyleX, local helpers or the entry of the package itself, such as an import from another package, a default or namespace import, an alias of or member read off an imported binding, require() or a dynamic import(), or a local module that cannot be read, or any name Core would have to resolve when Core is not installed). |
-| `integration.template-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. |
-| `integration.component-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. When the manifest loads and declares a components root, propDrift compares documented props with the TypeScript props: status (checked \| skipped), reason, typescript, components, typesCompared, typesSkipped, findings (all warnings; a default_mismatch carries docDefault, codeDefault, and a fix), unchecked, typesNotCompared, and propsNotChecked. |
-| `integration.doc-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). copiedPassages lists each pair of topics that repeat 10 or more words of prose word for word: topic, section, otherTopic, otherOwner (package \| core), words, passages, owner (the topic that should keep the text), text (the passage as the topic writes it), line (where the copy starts in the topic to change, or null), and message (the exact replacement); each is also a copied_passage warning in issues. fluff lists padding phrases and low-density topics: topic, kind (phrase \| density), phrase, section, file (relative to the package root), line, density, and message (what to cut or write instead); each is also a doc_fluff warning in issues. strayPointers lists each code span that is exactly `astryx docs <name>` for a doc that exists, in the prose, description or summary of a topic or the text fields of a component doc: topic (the topic or component doc), kind (topic \| component), section, field (the field outside any section, such as description or usage.bestPractices[0].description, else null), file (relative to the package root), line, pointer (the written command), link (the {@link} that replaces it), and message; each is also a stray_doc_pointer warning in issues. |
-| `integration.check` | Every source check of an integration package in one result: validated (false when no integration manifest was found, so nothing was checked), the package name and version, strict, and checks, one entry per check (validate, components, templates, docs), each with check, errors, warnings, skipped, failed, and response, the envelope that check returns on its own. The totals are errors, warnings, and skipped; unchecked counts what the checks could not compare. With --strict, failures lists each warning and each piece of skipped work again as an error, in the issue format the checks use; it is empty without --strict. failed decides the exit code. |
+| Type | What `data` carries |
+| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. |
+| `init.remove` | The removal receipt — returned when --remove-agents is set: `data.removed` is true when a managed agent-docs block was found and removed, and false when there was none to remove. |
+| `init.user` | The computer-level agent text receipt — returned when --user is set: `data.files`, one `{path, action, reason?}` per path acted on, the skill file first and then each link to its folder (action `written` \| `linked` \| `unchanged` \| `removed` \| `absent` \| `kept`; `reason` only on `kept`: `edited` when a person changed the text, `not-astryx` when Astryx did not write it), `data.command` (the command the text names), and `data.warnings`. |
+| `component.list` | The component catalog grouped by component group (each component's group field): `detail` (the level: names \| compact \| full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries ({name, package, description, import}), or a full ComponentDoc per entry with its package. |
+| `component.batch` | The component specialization of the shared `BatchResponse` and `BatchRow` types. An explicit programmatic selector array, or two or more CLI selectors, returns one ordered receipt: `count` plus `results`, one row per selector including duplicates. Every row carries `selector` and `status` (found \| not_found \| ambiguous \| error). A found row carries `result`, the same {type, data} response as one selector. An ambiguous row carries `code`, `error`, and `candidates` ({package, component, kind, installed}). Other failed rows carry `code`, `error`, and optional `suggestions` ({name, reason}). |
+| `component.detail` | One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc). The envelope's package names the same owner. |
+| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). The envelope's package names the npm package that owns the component. |
+| `component.detail.source` | One component's source file, as {component, source}. The envelope's package names the npm package that owns the component. |
+| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. The envelope's package names the npm package that owns the component. |
+| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry ({name, package, displayName, description, isShowcase, category}); each block names the package that owns it, and the envelope's package names the component's owner. |
+| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description, package, replaces?}), in read order; meta.namespaces lists the docs tree's top-level namespaces, and meta.notLoaded each package whose docs did not load. |
+| `docs.detail` | One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined and each section naming the package that wrote it, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
+| `docs.index` | One topic's section index, the text read of a topic with more than one section (and --index): the topic's name, title, and description, plus sections, each {id, title, package, summary} (pass the id as the section argument; package is the npm package that wrote the section; summary is the section's one-line summary), and links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
+| `docs.detail.section` | One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open its topic index and the sections before and after it). The envelope's package names the npm package that wrote the section. |
+| `docs.node` | One node of the docs tree, read by its route: its id, kind, package, title, summary, and breadcrumb, plus a namespace's slots with their children (one level down, each naming its package) or a typed doc's content, and links ({up, previous, next, related}: the commands that open its parent, its neighbors, and the docs it names). |
+| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |
+| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |
+| `discover.list` | What the project has, the integrations it loads and the official packages it declares, official packages first (name, category, components, version, a list per other kind they add, and latest when a source knows it); meta.available lists what the project could add, the official packages first, each with the command that adds it, and meta.sources reports each source, the official list last; when it lists no integration it carries meta.configured to tell "nothing configured" from "nothing discovered". |
+| `discover.detail` | One package, for an @scope/name or @scope/name@version query: what the shown version adds, whether the project has it, and, when a source knows the package, its versions, latest release, and the command that adds it. |
+| `discover.detail.doc` | The validated ComponentDoc for one installed component, for an @scope/name/Component query. |
+| `discover.item` | One item that is not an installed component, for an @scope/name/<item> query: its kind, name, package, version, and whether the project has the package. |
+| `discover.search` | The echoed query plus every matching item and package across all packages, each with its kind and whether the project has it, even when only one matches; total is set when --limit cut the list. |
+| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, package, score, reason, description, command} (package is the npm package that owns the result), plus import (components, hooks), title, parent (the command that opens the level above), and, for a hit on one section, section (docs), or displayName and kind (templates). When a search with no `type` could not obtain @astryxdesign/core, `meta.partial` is {skipped, reason}: the domains it skipped (component, hook, template) and why. |
+| `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. |
+| `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, package, command, basis, reason, alternatives, ...} (the start and each alternative name the package that owns the template), pages (search's closest templates), blocks and domain as SearchResultEntry[] (each naming its package), frame and foundation (Core component names), and hint {reason, commands} when thin. |
+| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. The envelope's package is @astryxdesign/core. |
+| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. The envelope's package names the same owning package. |
+| `gap-report.categories` | The fixed gap category values and human-readable labels; when a loaded integration names its own issues URL, meta.destinations lists every destination ({to, default, issuesUrl}) and meta.ask tells an agent to ask the person. |
+| `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals; without --to, when a loaded integration names its own issues URL, destinations and ask as on gap-report.categories. |
+| `template.list` | The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list. |
+| `template.show` | The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). |
+| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. The envelope's package names the npm package that owns the template. |
+| `template.copy` | A scaffold receipt: template id, output directory, written file name, file count, demoMediaReplaced (how many Astryx demo media references were replaced with placeholders), notes (setup notes naming what the template needs that the project lacks — missing packages, missing StyleX compiler; empty when satisfied), missingPackages (external package names the template imports that are not in the project), and installCommand (a ready-to-run install command with the detected package manager and workspace version ranges; null when nothing is missing, or when several lockfiles leave the package manager undetermined). The envelope's package names the npm package that owns the template. |
+| `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
+| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. The envelope's package is @astryxdesign/core, the only package that ships hooks. |
+| `hook.detail` | One hook's full authored HookDoc. The envelope's package is @astryxdesign/core. |
+| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). The envelope's package is @astryxdesign/core. |
+| `theme.build` | A theme build receipt: name, tokenCount and componentCount (override counts), sizeKB, the written outputs {css, cssDts, js, dts, and variantsDts when applicable}, warnings (defects to fix), and notices (advisories about a correct theme, such as a named font it does not load). |
+| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |
+| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |
+| `theme.list` | Every bundled, installed package, and local theme as a ThemeListEntry[]. Each entry has slug, displayName, description, maintained, owner package or local root, source, added, and default fields. Optional meta.unmigratedCopies names earlier descriptor-less copies, their missing descriptor, and the upgrade command; those copies are not data entries. |
+| `theme.app` | The app theme record after add, remove, or use. It includes every added theme and its built imports, the default slug, generated module path, and the command change. After add, the envelope package names the npm package that owns the added theme; a local theme has none. |
+| `theme.eject` | A local source-fork receipt with the resolved slug, displayName, source theme maintained flag, source-selector package, outputDir, source entry, exportName, and every file written, including the descriptor. The written local descriptor always uses maintained: false. |
+| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
+| `theme.targets` | The whole themeable surface: the echoed filter, componentCount, and targets, one per theming target — {key, className, component, props, states}, where props and states are its legal override keys. |
+| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |
+| `upgrade.list` | Every available codemod, oldest→newest, as {name, package, title, version, optional}; returned for --list without running anything. |
+| `upgrade.registry` | The copied-composition receipt for --registry: applied, ok, the counts (found, current, wouldUpdate, updated, wouldMerge, merged, wouldRefreshReceipt, receiptsRefreshed, conflicts, missing, invalid, failed), and items. |
+| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. no_codemods and config_fixable carry cliBehindCore ({cliVersion, command}) when the installed Core is newer than the CLI, which then has no codemods for the releases after its own version. |
+| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, sourcePathFound (false when the resolved source directory does not exist, so no source file was read), and (apply mode) filesChanged, transformsApplied, and per-codemod errors. When the installed Core is newer than the CLI, it also carries cliBehindCore ({cliVersion, command}): codemods for the releases after cliVersion did not run. |
+| `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], outsideProject? (same, refuse, or own; absent on a group), subcommands?), jsonSupported, globalMode ({docs, summary}: what a run may do beyond its command, such as the hand-off to the project's own CLI, the daily update check, and the agent skill file, and the docs topic that explains it), and the flat responseTypes index. |
+| `help` | Help, in one of two shapes. A bare `astryx --json` returns the root manifest: name, version, commands (the command names), jsonSupported, and manifest (the full payload `astryx manifest --json` returns). `--help --json` on any command, or `astryx help [command] --json`, returns that command's help: command, description, usage, options (each flags, description, and defaultValue and choices when set), and subcommands (each name and description). data.manifest marks the first shape; data.usage marks the second. |
+| `version` | The CLI version, for `astryx --version --json`: {version}. |
+| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and an optional fix, always present on warn and fail) plus a `summary` of counts per status. |
+| `integration.add` | A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun. |
+| `integration.pack-check` | The packed-package check: name, version, packable, tarball {filename, fileCount, size, unpackedSize} or null, inventory {manifest, roots [{kind, path, expectedFiles, missingFiles, complete}], expectedFiles, packedFiles}, contributions {local, packed}, each null or {themes [{slug, exportName}], components, templates [{id, type, name}], codemods [{version, id}], docs, agentDocsAppend}, and issues [{code, severity, message, fix?, file?, line?}] (the issues validation finds in the source and, prefixed packed_, in the packed tree, with the fix and the place when the check knows them). |
+| `integration.validate` | The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message, fix?, file?, line?} (fix: the change that resolves it; file and line: where, relative to the package), and notes when there are any: {code, message} information that fails nothing, such as invalid_cli_command for a malformed cliCommand, and the package layout findings added after the last minor release, each with its fix in the message (duplicate_component_doc, symlinked_root, unreadable_file, invalid_package_json, no_provider_id, source_without_component_doc where a doc and its source still pair), and doc_name_mismatch and unknown_block_component, until they become warnings in the next minor release. A runner_command note lists each Astryx command a topic writes with a package runner (its file, line and the bare command to write). When the manifest loads, docTypes checks each doc against its published authoring type: status (checked \| skipped), reason, typescript, docs, findings (all warnings, each naming the field and a fix), unchecked, and fixtures (test fixture docs not checked). When the manifest loads, docNames lists the component doc names it could not judge: status (checked), findings (always empty; a doc name the module its import names provably does not export is a doc_name_mismatch note, with its fix in the message) and unchecked ({file, name, reason}: a doc whose name differs from the name it is listed under and whose source exports cannot all be read, such as a re-export from another package). When the manifest loads, blockComponents lists the component names templates give in exampleFor or componentsUsed that could not be judged: status (checked), findings (always empty; a name neither the package nor Core has, and the template does not import, is an unknown_block_component note, with its fix in the message) and unchecked ({file, name, reason}: a name the template may reach through anything other than named imports and re-exports from Core, React, StyleX, local helpers or the entry of the package itself, such as an import from another package, a default or namespace import, an alias of or member read off an imported binding, require() or a dynamic import(), or a local module that cannot be read, or any name Core would have to resolve when Core is not installed). |
+| `integration.template-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. |
+| `integration.component-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. When the manifest loads and declares a components root, propDrift compares documented props with the TypeScript props: status (checked \| skipped), reason, typescript, components, typesCompared, typesSkipped, findings (all warnings; a default_mismatch carries docDefault, codeDefault, and a fix), unchecked, typesNotCompared, and propsNotChecked. |
+| `integration.doc-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). copiedPassages lists each pair of topics that repeat 10 or more words of prose word for word: topic, section, otherTopic, otherOwner (package \| core), words, passages, owner (the topic that should keep the text), text (the passage as the topic writes it), line (where the copy starts in the topic to change, or null), and message (the exact replacement); each is also a copied_passage warning in issues. fluff lists padding phrases and low-density topics: topic, kind (phrase \| density), phrase, section, file (relative to the package root), line, density, and message (what to cut or write instead); each is also a doc_fluff warning in issues. strayPointers lists each code span that is exactly `astryx docs <name>` for a doc that exists, in the prose, description or summary of a topic or the text fields of a component doc: topic (the topic or component doc), kind (topic \| component), section, field (the field outside any section, such as description or usage.bestPractices[0].description, else null), file (relative to the package root), line, pointer (the written command), link (the {@link} that replaces it), and message; each is also a stray_doc_pointer warning in issues. |
+| `integration.check` | Every source check of an integration package in one result: validated (false when no integration manifest was found, so nothing was checked), the package name and version, strict, and checks, one entry per check (validate, components, templates, docs), each with check, errors, warnings, skipped, failed, and response, the envelope that check returns on its own. The totals are errors, warnings, and skipped; unchecked counts what the checks could not compare. With --strict, failures lists each warning and each piece of skipped work again as an error, in the issue format the checks use; it is empty without --strict. failed decides the exit code. |
<!-- END GENERATED: response-types -->
<!-- Generated by scripts/generate-cli-readme.mjs from the response-types EnumDoc. Run `pnpm -F @astryxdesign/cli readme`. -->
diff --git a/packages/cli/api/integration/_adapter.mjs b/packages/cli/api/integration/_adapter.mjs
index 1b6753c600..21a87b78cd 100644
--- a/packages/cli/api/integration/_adapter.mjs
+++ b/packages/cli/api/integration/_adapter.mjs
@@ -2,7 +2,8 @@
/**
* @file The integration subject's access to the environment (INV21): reading
- * one package's component docs and sources with the project's own TypeScript.
+ * one package's component docs and sources with the project's own TypeScript,
+ * and its topics.
*
* @input a loaded integration and the directory the command runs in
* @output the reports the integration checks attach to their results
@@ -14,9 +15,11 @@ import {
forEachIntegrationDoc,
integrationSourceForDoc,
} from '../../foundation/discovery/component-discovery.mjs';
+import {discoverIntegrationDocs} from '../../foundation/discovery/docs-discovery.mjs';
import {comparePropDocs} from '../../foundation/discovery/prop-drift.mjs';
import {findCopiedPassages} from '../../foundation/discovery/copied-passages.mjs';
import {findFluff} from '../../foundation/discovery/doc-fluff.mjs';
+import {findRunnerCommands} from '../../foundation/discovery/runner-commands.mjs';
import {findStrayPointers} from '../../foundation/discovery/stray-pointers.mjs';
/**
@@ -110,3 +113,20 @@ export async function integrationStrayPointers(discovered, integration) {
}
return findStrayPointers({...discovered, components});
}
+
+/**
+ * Each Astryx command a package's topics write with a package runner. A
+ * package whose topics cannot be discovered has none here: the other checks
+ * report topics that do not load.
+ * @param {any} integration a loaded integration
+ * @returns {Promise<import('../../foundation/discovery/runner-commands.mjs').RunnerCommand[]>}
+ */
+export async function integrationRunnerCommands(integration) {
+ let discovered;
+ try {
+ discovered = await discoverIntegrationDocs(integration);
+ } catch {
+ return [];
+ }
+ return findRunnerCommands(discovered);
+}
diff --git a/packages/cli/api/integration/authoring-checks.test.mjs b/packages/cli/api/integration/authoring-checks.test.mjs
index e875c4c785..da4258f5ae 100644
--- a/packages/cli/api/integration/authoring-checks.test.mjs
+++ b/packages/cli/api/integration/authoring-checks.test.mjs
@@ -14,6 +14,7 @@ vi.mock('../../foundation/discovery/template-conflict-release.mjs', () => ({
}));
import * as fs from 'node:fs';
import * as path from 'node:path';
+import {validateIntegration} from './validate-integration.mjs';
import {discoverCoreTemplates} from '../../foundation/discovery/template-adapter.mjs';
import {discoverOwnedComponents} from '../../foundation/discovery/component-discovery.mjs';
import {discoverBuiltinTopics} from '../../foundation/discovery/docs-discovery.mjs';
@@ -1331,3 +1332,222 @@ describe('links in component docs and topic descriptions', () => {
]);
});
});
+
+describe('validateIntegration runner-command notes', () => {
+ /** The runner-command notes, read back into their parts. */
+ async function runnerNotes() {
+ const {data} = await validateIntegration(undefined, {cwd: tmpDir});
+ const notes = (data.notes ?? [])
+ .filter((/** @type {any} */ note) => note.code === 'runner_command')
+ .map((/** @type {any} */ note) => {
+ const m =
+ /^(\S+): "([^"]+)"(?: \(section "([^"]+)"\))? writes `([^`]+)`(?: \(line (\d+)\))?\./.exec(
+ note.message,
+ );
+ return {
+ file: m?.[1],
+ topic: m?.[2],
+ section: m?.[3] ?? null,
+ command: m?.[4],
+ line: m?.[5] ? Number(m[5]) : null,
+ message: note.message,
+ };
+ });
+ return {data, notes};
+ }
+
+ function writeTopic(/** @type {string} */ text) {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.integration.mjs'),
+ `export default {docs: './docs'};\n`,
+ );
+ fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});
+ const doc = {
+ type: 'generic',
+ name: 'acme-setup',
+ title: 'Fixture',
+ description: 'Fixture topic.',
+ sections: [
+ {
+ title: 'Overview',
+ content: [
+ {type: 'prose', text},
+ {type: 'code', lang: 'bash', code: 'npx @astryxdesign/cli init'},
+ ],
+ },
+ ],
+ };
+ fs.writeFileSync(
+ path.join(tmpDir, 'docs', 'acme-setup.doc.mjs'),
+ `export default ${JSON.stringify(doc)};\n`,
+ );
+ }
+
+ it('lists a runner command with its line and fix, and raises no issue', async () => {
+ writeTopic('Check it with `pnpm exec astryx doctor` first.');
+
+ const {data, notes} = await runnerNotes();
+ const [hit, ...rest] = notes;
+
+ expect(rest).toEqual([]);
+ expect(hit).toMatchObject({
+ topic: 'acme-setup',
+ section: 'Overview',
+ file: 'docs/acme-setup.doc.mjs',
+ line: 1,
+ command: 'pnpm exec astryx doctor',
+ });
+ expect(hit.message).toContain('Write `astryx doctor`');
+ // A note only: no issue, so no exit changes on it.
+ expect(
+ data.issues.map((/** @type {any} */ issue) => issue.code),
+ ).not.toContain('runner_command');
+ });
+
+ it('puts each copy of a repeated command on its own line', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.integration.mjs'),
+ `export default {docs: './docs'};\n`,
+ );
+ fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});
+ const doc = {
+ type: 'generic',
+ name: 'acme-setup',
+ title: 'Fixture',
+ description: 'Fixture topic.',
+ sections: [
+ {
+ title: 'First',
+ content: [{type: 'prose', text: 'Run `npx astryx doctor`.'}],
+ },
+ {
+ title: 'Second',
+ content: [{type: 'prose', text: 'Run `npx astryx doctor` again.'}],
+ },
+ {
+ title: 'Third',
+ content: [{type: 'prose', text: 'Or plain `npx astryx`.'}],
+ },
+ ],
+ };
+ fs.writeFileSync(
+ path.join(tmpDir, 'docs', 'acme-setup.doc.mjs'),
+ `export default ${JSON.stringify(doc, null, 2)};\n`,
+ );
+ const lines = fs
+ .readFileSync(path.join(tmpDir, 'docs', 'acme-setup.doc.mjs'), 'utf8')
+ .split('\n');
+ const lineHolding = (/** @type {string} */ text) =>
+ lines.findIndex(line => line.includes(text)) + 1;
+
+ const {notes} = await runnerNotes();
+
+ expect(
+ notes.map((/** @type {any} */ each) => [
+ each.section,
+ each.line,
+ each.command,
+ ]),
+ ).toEqual([
+ ['First', lineHolding('Run `npx astryx doctor`.'), 'npx astryx doctor'],
+ ['Second', lineHolding('again.'), 'npx astryx doctor'],
+ ['Third', lineHolding('Or plain'), 'npx astryx'],
+ ]);
+ });
+
+ it('puts each copy of an identical one-line string on its own line', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.integration.mjs'),
+ `export default {docs: './docs'};\n`,
+ );
+ fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});
+ const block = {type: 'code', lang: 'bash', code: 'npx astryx doctor'};
+ const doc = {
+ type: 'generic',
+ name: 'acme-setup',
+ title: 'Fixture',
+ description: 'Fixture topic.',
+ sections: [
+ {title: 'First', content: [block]},
+ {title: 'Second', content: [block]},
+ ],
+ };
+ fs.writeFileSync(
+ path.join(tmpDir, 'docs', 'acme-setup.doc.mjs'),
+ `export default ${JSON.stringify(doc, null, 2)};\n`,
+ );
+ const lines = fs
+ .readFileSync(path.join(tmpDir, 'docs', 'acme-setup.doc.mjs'), 'utf8')
+ .split('\n');
+ const copies = lines.flatMap((line, at) =>
+ line.includes('"npx astryx doctor"') ? [at + 1] : [],
+ );
+
+ const {notes} = await runnerNotes();
+
+ expect(copies).toHaveLength(2);
+ expect(
+ notes.map((/** @type {any} */ each) => [each.section, each.line]),
+ ).toEqual([
+ ['First', copies[0]],
+ ['Second', copies[1]],
+ ]);
+ });
+
+ it("places a section's command on its own line when the section sits in a constant above the doc", async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.integration.mjs'),
+ `export default {docs: './docs'};\n`,
+ );
+ fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});
+ fs.writeFileSync(
+ path.join(tmpDir, 'docs', 'acme-setup.doc.mjs'),
+ [
+ "const install = {title: 'Install', content: [{type: 'prose', text: 'Run `npx astryx doctor`.'}]};",
+ '',
+ 'export default {',
+ " type: 'generic',",
+ " name: 'acme-setup',",
+ " title: 'Fixture',",
+ " description: 'Install first: `npx astryx doctor`.',",
+ ' sections: [install],',
+ '};',
+ '',
+ ].join('\n'),
+ );
+
+ const {notes} = await runnerNotes();
+
+ expect(
+ notes.map((/** @type {any} */ each) => [each.section, each.line]),
+ ).toEqual(
+ expect.arrayContaining([
+ [null, 7],
+ ['Install', 1],
+ ]),
+ );
+ });
+
+ it('lists nothing for bare commands and the scoped install step', async () => {
+ writeTopic('Check it with `astryx doctor` first.');
+
+ const {notes} = await runnerNotes();
+ expect((await runnerNotes()).notes).toEqual([]);
+ });
+});
diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjs
index a800c5ffb3..f079a5362a 100644
--- a/packages/cli/api/integration/validate-integration.mjs
+++ b/packages/cli/api/integration/validate-integration.mjs
@@ -37,6 +37,7 @@ import {assertWithin} from '../../foundation/fs/path-safety.mjs';
import {normalizeProviderId} from '../../foundation/identity/provider-identity.mjs';
import {integrationDocTypes} from '../docs/_adapter.mjs';
import {integrationDocConsistency} from '../../foundation/discovery/doc-consistency.mjs';
+import {integrationRunnerCommands} from './_adapter.mjs';
import {
THEME_SLUG_RE,
unreadThemeFolders,
@@ -647,6 +648,24 @@ export async function validateInstalledIntegration(spec, cwd = process.cwd()) {
});
}
+/**
+ * The runner-command notes for a package's topics: each Astryx command a topic
+ * writes with a package runner, where the doc file is, and the bare command to
+ * write.
+ * @param {any} integration a loaded integration
+ * @returns {Promise<Array<{code: string, message: string}>>}
+ */
+async function runnerCommandNotes(integration) {
+ const packageDir = integration.__packageDir;
+ return (await integrationRunnerCommands(integration)).map(each => ({
+ code: 'runner_command',
+ message:
+ typeof packageDir === 'string'
+ ? `${path.relative(packageDir, each.file).split(path.sep).join('/')}: ${each.message}`
+ : each.message,
+ }));
+}
+
/**
* Unified entry: validate the LOCAL integration (no `pkg`) or an INSTALLED one
* (`pkg` given) and return the `integration.validate` envelope. The no-manifest
@@ -697,6 +716,11 @@ export async function validateIntegration(pkg, options = {}) {
...(names ?? []).flatMap(each => each.notes),
]
: [];
+ // Each Astryx command a topic writes with a package runner, as a
+ // `runner_command` note with its fix, the same way.
+ if (integration?.docs) {
+ notes.push(...(await runnerCommandNotes(integration)));
+ }
return {
type: 'integration.validate',
data: {
diff --git a/packages/cli/api/integration/validate-integration.type.mjs b/packages/cli/api/integration/validate-integration.type.mjs
index b3ae9e6531..d70ac53411 100644
--- a/packages/cli/api/integration/validate-integration.type.mjs
+++ b/packages/cli/api/integration/validate-integration.type.mjs
@@ -51,7 +51,8 @@
* whose file name differs from its source only in letter case where the two
* still pair (`source_without_component_doc`); and `doc_name_mismatch` and
* `unknown_block_component` (see `docNames` and `blockComponents`); they
- * become warnings in the next minor release
+ * become warnings in the next minor release; and `runner_command`, an
+ * Astryx command a topic writes with a package runner
*/
/**
diff --git a/packages/cli/api/integration/validateIntegration.doc.mjs b/packages/cli/api/integration/validateIntegration.doc.mjs
index 7647cb6e26..0016dbcc43 100644
--- a/packages/cli/api/integration/validateIntegration.doc.mjs
+++ b/packages/cli/api/integration/validateIntegration.doc.mjs
@@ -62,7 +62,7 @@ export const doc = {
{
type: 'integration.validate',
description:
- 'The result envelope: `data.validated`, false when nothing was validated — with no `package.json` at all, `data.issues` carries one `no_package` error-severity issue so the command exits 1; with a `package.json` but no integration manifest, `data.issues` is empty, which means "not looked at", not "healthy"; `data.name` and `data.version` of the validated package (both null when `data.validated` is false; `data.name` is `(local package)` when the local package.json has no readable name), plus `data.issues`, an AstryxIntegrationIssue[] of {code, severity: `warning` | `error`, message, fix?, file?, line?}: `fix` is the change that resolves the issue, and `file` and `line` where it is, relative to the package, when the check knows them; and `data.notes` when there are any: {code, message} information that fails nothing, such as `invalid_cli_command` for a `cliCommand` that was ignored as malformed, and the package layout findings added after the last minor release, each with its fix in the message: `duplicate_component_doc`, `symlinked_root`, `unreadable_file`, `invalid_package_json` (no `name` or `version`), `no_provider_id`, and `source_without_component_doc` for a doc whose file name differs from its source only in letter case where the two still pair; and `doc_name_mismatch` and `unknown_block_component` (see `docNames` and `blockComponents`); they become warnings in the next minor release. When the manifest loads, `data.docTypes` holds the doc type check: `status` (`checked` | `skipped`), `reason` when skipped, `typescript`, `docs` (doc values checked), `findings` ({doc, line, export, type, field, problem: `unknown_field` | `missing_field` | `wrong_type`, severity: `warning`, message, fix}), `unchecked` ({doc, reason}: a doc that could not be fully checked, or a root its reader cannot read), and `fixtures` when the components or docs root holds test fixture docs under `__tests__`: how many, none of them checked. When the manifest loads, `data.docNames` lists the component doc names it could not judge: `status` (`checked`), `findings` (always empty; a doc name the module its import names provably does not export is a `doc_name_mismatch` note, with its fix in the message) and `unchecked` ({file, name, reason}: a doc whose `name` differs from the name it is listed under and whose source exports cannot all be read, such as a re-export from another package). When the manifest loads, `data.blockComponents` lists the component names templates give in `exampleFor` or `componentsUsed` that could not be judged: `status` (`checked`), `findings` (always empty; a name neither the package nor Core has, and the template does not import, is an `unknown_block_component` note, with its fix in the message) and `unchecked` ({file, name, reason}: a name the template may reach through anything other than named imports and re-exports from Core, React, StyleX, local helpers or the entry of the package itself, such as an import from another package, a default or namespace import, an alias of or member read off an imported binding, require() or a dynamic import(), or a local module that cannot be read, or any name Core would have to resolve when Core is not installed).',
+ 'The result envelope: `data.validated`, false when nothing was validated — with no `package.json` at all, `data.issues` carries one `no_package` error-severity issue so the command exits 1; with a `package.json` but no integration manifest, `data.issues` is empty, which means "not looked at", not "healthy"; `data.name` and `data.version` of the validated package (both null when `data.validated` is false; `data.name` is `(local package)` when the local package.json has no readable name), plus `data.issues`, an AstryxIntegrationIssue[] of {code, severity: `warning` | `error`, message, fix?, file?, line?}: `fix` is the change that resolves the issue, and `file` and `line` where it is, relative to the package, when the check knows them; and `data.notes` when there are any: {code, message} information that fails nothing, such as `invalid_cli_command` for a `cliCommand` that was ignored as malformed, and the package layout findings added after the last minor release, each with its fix in the message: `duplicate_component_doc`, `symlinked_root`, `unreadable_file`, `invalid_package_json` (no `name` or `version`), `no_provider_id`, and `source_without_component_doc` for a doc whose file name differs from its source only in letter case where the two still pair; and `doc_name_mismatch` and `unknown_block_component` (see `docNames` and `blockComponents`); they become warnings in the next minor release. A `runner_command` note lists each Astryx command a topic writes with a package runner, with its file, line and the bare command to write. When the manifest loads, `data.docTypes` holds the doc type check: `status` (`checked` | `skipped`), `reason` when skipped, `typescript`, `docs` (doc values checked), `findings` ({doc, line, export, type, field, problem: `unknown_field` | `missing_field` | `wrong_type`, severity: `warning`, message, fix}), `unchecked` ({doc, reason}: a doc that could not be fully checked, or a root its reader cannot read), and `fixtures` when the components or docs root holds test fixture docs under `__tests__`: how many, none of them checked. When the manifest loads, `data.docNames` lists the component doc names it could not judge: `status` (`checked`), `findings` (always empty; a doc name the module its import names provably does not export is a `doc_name_mismatch` note, with its fix in the message) and `unchecked` ({file, name, reason}: a doc whose `name` differs from the name it is listed under and whose source exports cannot all be read, such as a re-export from another package). When the manifest loads, `data.blockComponents` lists the component names templates give in `exampleFor` or `componentsUsed` that could not be judged: `status` (`checked`), `findings` (always empty; a name neither the package nor Core has, and the template does not import, is an `unknown_block_component` note, with its fix in the message) and `unchecked` ({file, name, reason}: a name the template may reach through anything other than named imports and re-exports from Core, React, StyleX, local helpers or the entry of the package itself, such as an import from another package, a default or namespace import, an alias of or member read off an imported binding, require() or a dynamic import(), or a local module that cannot be read, or any name Core would have to resolve when Core is not installed).',
},
],
examples: [
diff --git a/packages/cli/assets/docs/tree/add-a-topic.doc.mjs b/packages/cli/assets/docs/tree/add-a-topic.doc.mjs
index 20851d5d47..cbb77e8a29 100644
--- a/packages/cli/assets/docs/tree/add-a-topic.doc.mjs
+++ b/packages/cli/assets/docs/tree/add-a-topic.doc.mjs
@@ -79,7 +79,7 @@ export const docs = {
content: [
{
type: 'prose',
- text: 'Start every CLI command in a doc with the word astryx alone, with no runner such as npx or pnpm exec in front. The CLI prefixes each one when it prints the doc, with the command the reader runs: `pnpm exec astryx` or `yarn astryx` from their package manager, or the `cliCommand` an integration sets. See {@link generic:cli-command}.',
+ text: 'Start every CLI command in a doc with the word astryx alone, with no runner such as npx or pnpm exec in front. The CLI prefixes each one when it prints the doc, with the command the reader runs: `pnpm exec astryx` or `yarn astryx` from their package manager, or the `cliCommand` an integration sets. See {@link generic:cli-command}. `doctor integration validate` (and so `integration check`) lists each command written with a runner as a `runner_command` note, with its file, line and the bare command to write. A note fails nothing. An install step, which runs before the CLI is installed, is the one exception: write the scoped package name, `@astryxdesign/cli`, after the download runner. The unscoped name after a download runner is always listed, because it fetches an unrelated package.',
},
{
type: 'code',
diff --git a/packages/cli/assets/docs/tree/checks.doc.mjs b/packages/cli/assets/docs/tree/checks.doc.mjs
index 99ac9cd401..bb744b9ea4 100644
--- a/packages/cli/assets/docs/tree/checks.doc.mjs
+++ b/packages/cli/assets/docs/tree/checks.doc.mjs
@@ -30,7 +30,7 @@ export const docs = {
rows: [
[
'`astryx doctor integration validate`',
- 'The manifest loads, each root holds contributions the CLI can read, and each doc matches its authoring type',
+ 'The manifest loads, each root holds contributions the CLI can read, and each doc matches its authoring type. Notes, which fail nothing, list a malformed `cliCommand` and each command a topic writes with a package runner (`runner_command`)',
'A declared root is missing (`missing_root`), a contribution does not load (`invalid_doc`, `invalid_component`, `invalid_theme`), or two templates in the package replace one Core id (`ambiguous_template_replacement`)',
"The manifest has a key this CLI does not know (`unknown_manifest_key`), or a doc field does not match the doc's authoring type: a field the type does not have, a missing required field, or a value outside the field's type. It also warns on what no reader can serve: a prop listed twice (`duplicate_prop`), a `propDescriptions` key that names no documented prop (`unknown_translated_prop`), a section with no content (`empty_section`), two sections of a topic with one key (`duplicate_section_key`), or a `.doc.zh.mjs` or `.doc.dense.mjs` overlay beside no topic file (`orphan_doc_overlay`). It checks docs with your installed `typescript`, or, where that is missing or has no JavaScript compiler API (TypeScript 7), with an installed `@typescript/typescript6`; without either, it prints `[skip] Docs not type-checked`. With no `astryx.integration.mjs` it prints a hint and exits 0",
],
diff --git a/packages/cli/clients/cli/commands/integration-check.test.mjs b/packages/cli/clients/cli/commands/integration-check.test.mjs
index 104c354dd1..a2d88ce46b 100644
--- a/packages/cli/clients/cli/commands/integration-check.test.mjs
+++ b/packages/cli/clients/cli/commands/integration-check.test.mjs
@@ -439,3 +439,51 @@ describe('a stray doc pointer', () => {
expect(strict.stdout).toContain('stray_doc_pointer');
});
});
+describe('a command written with a runner', () => {
+ it('is a note in doctor integration validate, and integration check --strict still passes', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.integration.mjs'),
+ `export default {docs: './docs'};\n`,
+ );
+ fs.mkdirSync(path.join(tmpDir, 'docs'));
+ const doc = {
+ type: 'generic',
+ name: 'acme-setup',
+ title: 'Fixture',
+ description: 'Fixture topic.',
+ sections: [
+ {
+ title: 'Overview',
+ content: [{type: 'code', lang: 'bash', code: 'npx astryx doctor'}],
+ },
+ ],
+ };
+ fs.writeFileSync(
+ path.join(tmpDir, 'docs', 'acme-setup.doc.mjs'),
+ `export default ${JSON.stringify(doc)};\n`,
+ );
+
+ const doctor = await runCli(['doctor', 'integration', 'validate'], tmpDir);
+ expect(doctor.status).toBe(0);
+ expect(doctor.stdout).toContain(
+ 'note (runner_command): docs/acme-setup.doc.mjs:',
+ );
+ expect(doctor.stdout).toContain('Write `astryx doctor`');
+
+ const strict = await runCli(
+ ['--json', 'integration', 'check', '--strict'],
+ tmpDir,
+ );
+ expect(strict.status).toBe(0);
+ const validate = JSON.parse(strict.stdout).data.checks.find(
+ (/** @type {any} */ each) => each.check === 'validate',
+ ).response.data;
+ expect(validate.notes.map((/** @type {any} */ note) => note.code)).toEqual([
+ 'runner_command',
+ ]);
+ });
+});
diff --git a/packages/cli/foundation/discovery/runner-allowlist.mjs b/packages/cli/foundation/discovery/runner-allowlist.mjs
index be76828ce3..06216fc3a0 100644
--- a/packages/cli/foundation/discovery/runner-allowlist.mjs
+++ b/packages/cli/foundation/discovery/runner-allowlist.mjs
@@ -13,10 +13,8 @@
* command, except in `runnerExamples`, where `npx @astryxdesign/cli …` and a
* project's runner may (still never the unscoped name through npx).
*
- * TODO(doctor-runner-check): the Doctor lane's integration-docs runner check
- * (foundation/discovery/runner-commands.mjs) becomes the single rule; then the
- * repo test runs that check over Core's and the CLI's own docs with this
- * allowlist.
+ * The matcher is runnerCommandsIn (foundation/discovery/runner-commands.mjs),
+ * the rule `doctor integration validate` holds integrations to.
*
* @input nothing
* @output the allowlist
diff --git a/packages/cli/foundation/discovery/runner-commands.mjs b/packages/cli/foundation/discovery/runner-commands.mjs
new file mode 100644
index 0000000000..437d32c0f6
--- /dev/null
+++ b/packages/cli/foundation/discovery/runner-commands.mjs
@@ -0,0 +1,293 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Runner commands in docs: an Astryx command written with a package runner in
+ * front. Docs write the bare `astryx <command>` and the CLI shows it with the
+ * reader's runner, so a written runner is wrong for every reader on another
+ * package manager.
+ *
+ * - A download runner (`npx`, `pnpm dlx`, `yarn dlx`, `bunx`, `bun x`,
+ * `npm exec`) with the unscoped name `astryx`, with or without an
+ * `@<version>` after it, always counts, even with nothing after it: it
+ * fetches an unrelated package of that name.
+ * - A project runner (`pnpm exec`, `pnpm`, `yarn`) counts when one of the
+ * CLI's commands follows on the same line (`pnpm exec astryx docs`). Named
+ * alone, or before a word that is not a command (`yarn astryx runs the
+ * copy…`), it is left alone.
+ * - A runner and what follows it are read within one line; flags between a
+ * download runner and the name are read past.
+ * - The scoped package (`npx @astryxdesign/cli init`) never counts: it is the
+ * one form that runs before the CLI is installed, for install steps.
+ * - Other tools' commands (`npx prettier`) never count.
+ */
+
+import fs from 'node:fs';
+
+import {loadTopicModule} from './docs-discovery.mjs';
+
+/**
+ * @param {string} file
+ * @returns {Promise<any>} the doc, or null for one that does not load (the
+ * load problem is reported elsewhere)
+ */
+async function loadQuietly(file) {
+ try {
+ return await loadTopicModule(file);
+ } catch {
+ return null;
+ }
+}
+
+const DOWNLOAD_RUNNERS = [
+ 'pnpm dlx',
+ 'yarn dlx',
+ 'npm exec --',
+ 'npm exec',
+ 'npx',
+ 'bunx',
+ 'bun x',
+];
+const PROJECT_RUNNERS = ['pnpm exec', 'pnpm', 'yarn'];
+
+/**
+ * The CLI's top-level commands, the words that make a project runner's
+ * `astryx <word>` a command; runner-commands.test.mjs keeps the list equal to
+ * the command docs.
+ */
+export const CLI_COMMANDS = Object.freeze([
+ 'blog',
+ 'build',
+ 'component',
+ 'discover',
+ 'docs',
+ 'doctor',
+ 'gap-report',
+ 'help',
+ 'hook',
+ 'init',
+ 'integration',
+ 'manifest',
+ 'search',
+ 'swizzle',
+ 'template',
+ 'theme',
+ 'upgrade',
+]);
+
+/** Blanks within one line. */
+const BLANK = '[ \\t]+';
+
+/** @param {readonly string[]} words */
+const alternatives = words =>
+ words.map(each => each.replace(/ /g, BLANK)).join('|');
+
+/** After `astryx`: the name ends here (a sentence's period may follow). */
+const NAME_END = '(?![\\w@/-]|\\.\\w)';
+
+const DOWNLOAD_COMMAND = new RegExp(
+ `(?<![\\w@/.-])(?:${alternatives(DOWNLOAD_RUNNERS)})(?:${BLANK}--?[a-z][\\w-]*)*${BLANK}astryx(?:@[\\w^~-]+(?:\\.[\\w^~-]+)*)?${NAME_END}(?:${BLANK}(${alternatives(CLI_COMMANDS)})(?![\\w-]))?`,
+ 'g',
+);
+const PROJECT_COMMAND = new RegExp(
+ `(?<![\\w@/.-])(?:${alternatives(PROJECT_RUNNERS)})${BLANK}astryx${BLANK}(${alternatives(CLI_COMMANDS)})(?![\\w-])`,
+ 'g',
+);
+
+/**
+ * Each runner command in a text, as written, with the bare command to write
+ * instead, in order.
+ *
+ * @param {string} text
+ * @returns {{written: string, bare: string, download: boolean}[]}
+ */
+export function runnerCommandsIn(text) {
+ const found = [
+ ...[...String(text).matchAll(DOWNLOAD_COMMAND)].map(match => ({
+ match,
+ download: true,
+ })),
+ ...[...String(text).matchAll(PROJECT_COMMAND)].map(match => ({
+ match,
+ download: false,
+ })),
+ ];
+ /** @type {{at: number, written: string, bare: string, download: boolean}[]} */
+ const unique = [];
+ for (const {match, download} of found) {
+ if (unique.some(each => each.at === match.index)) continue;
+ unique.push({
+ at: match.index,
+ written: match[0],
+ bare: match[1] ? `astryx ${match[1]}` : 'astryx',
+ download,
+ });
+ }
+ return unique
+ .sort((a, b) => a.at - b.at)
+ .map(({written, bare, download}) => ({written, bare, download}));
+}
+
+/**
+ * Every string in a doc, with the title of the section it is in. Code counts:
+ * most commands sit in code blocks.
+ *
+ * @param {unknown} doc
+ * @returns {{text: string, section: string | null}[]}
+ */
+function allStrings(doc) {
+ /** @type {{text: string, section: string | null}[]} */
+ const strings = [];
+ // A doc that refers back to itself is walked once.
+ const visited = new WeakSet();
+ /**
+ * @param {unknown} value
+ * @param {string | null} section
+ */
+ const walk = (value, section) => {
+ if (typeof value === 'string') {
+ strings.push({text: value, section});
+ } else if (value != null && typeof value === 'object') {
+ if (visited.has(value)) return;
+ visited.add(value);
+ if (Array.isArray(value)) {
+ for (const item of value) walk(item, section);
+ return;
+ }
+ const record = /** @type {Record<string, unknown>} */ (value);
+ for (const [key, field] of Object.entries(record)) {
+ if (key === 'sections' && Array.isArray(field)) {
+ for (const each of field) {
+ walk(each, typeof each?.title === 'string' ? each.title : section);
+ }
+ } else {
+ walk(field, section);
+ }
+ }
+ }
+ };
+ walk(doc, null);
+ return strings;
+}
+
+/**
+ * Where a file next holds the text, at or after a cursor (a 0-based line and
+ * column), else the first place it holds it, else null. A doc's strings are
+ * read in file order, so moving the cursor past each match puts a command the
+ * topic writes twice on its own line.
+ *
+ * @param {string[]} lines
+ * @param {string} written
+ * @param {{line: number, column: number}} cursor
+ * @returns {{line: number, column: number} | null}
+ */
+function locate(lines, written, cursor) {
+ for (let at = cursor.line; at < lines.length; at++) {
+ const column = lines[at].indexOf(
+ written,
+ at === cursor.line ? cursor.column : 0,
+ );
+ if (column >= 0) return {line: at, column};
+ }
+ const first = lines.findIndex(line => line.includes(written));
+ return first < 0
+ ? null
+ : {line: first, column: lines[first].indexOf(written)};
+}
+
+/**
+ * An Astryx command a topic writes with a package runner in front.
+ *
+ * @typedef {object} RunnerCommand
+ * @property {string} topic
+ * @property {string | null} section the title of the section it is in
+ * @property {string} file the doc file
+ * @property {number | null} line the file line that holds it, when found
+ * @property {string} command the command as written
+ * @property {string} message the bare command to write instead
+ */
+
+/**
+ * Runner commands in a package's topics.
+ *
+ * @param {{records: {name: string, path: string}[], guides?: {name: string, ref?: {topicFile?: string}}[]}} discovered
+ * the package's docs, as discoverIntegrationDocs returns them
+ * @returns {Promise<RunnerCommand[]>}
+ */
+export async function findRunnerCommands(discovered) {
+ const topics = [
+ ...discovered.records.map(record => ({
+ name: record.name,
+ file: record.path,
+ })),
+ ...(discovered.guides ?? []).map(guide => ({
+ name: guide.name,
+ file: guide.ref?.topicFile,
+ })),
+ ];
+ /** @type {RunnerCommand[]} */
+ const found = [];
+ for (const {name, file} of topics) {
+ const doc = file ? await loadQuietly(file) : null;
+ if (!doc || !file) continue;
+ /** @type {string[]} */
+ let lines = [];
+ try {
+ lines = fs.readFileSync(file, 'utf8').split('\n');
+ } catch {
+ // The doc loaded, so only the line number is lost.
+ }
+ let cursor = {line: 0, column: 0};
+ for (const {text, section} of allStrings(doc)) {
+ const commands = runnerCommandsIn(text);
+ if (commands.length === 0) continue;
+ // A one-line string's own literal places it, wherever the walk reached
+ // it (a section in a constant above the doc object, say); else the
+ // cursor search, in file order.
+ const forms = [`'${text}'`, `"${text}"`, JSON.stringify(text)];
+ const holds = (/** @type {string} */ line) =>
+ forms.some(form => line.includes(form));
+ // On the cursor's own line, only a copy at or after the cursor counts:
+ // the copy just matched still sits before it.
+ const after = text.includes('\n')
+ ? -1
+ : lines.findIndex((line, at) =>
+ at > cursor.line
+ ? holds(line)
+ : at === cursor.line &&
+ forms.some(form => line.indexOf(form, cursor.column) >= 0),
+ );
+ const literal =
+ after >= 0 || text.includes('\n') ? after : lines.findIndex(holds);
+ const column = after >= 0 && after === cursor.line ? cursor.column : 0;
+ let from = literal >= 0 ? {line: literal, column} : cursor;
+ for (const {written, bare, download} of commands) {
+ const place = locate(lines, written, from);
+ if (place) {
+ from = {line: place.line, column: place.column + written.length};
+ if (
+ place.line > cursor.line ||
+ (place.line === cursor.line && place.column >= cursor.column)
+ ) {
+ cursor = from;
+ }
+ }
+ const line = place ? place.line + 1 : null;
+ const where = section ? ` (section "${section}")` : '';
+ found.push({
+ topic: name,
+ section,
+ file,
+ line,
+ command: written,
+ message:
+ `"${name}"${where} writes \`${written}\`${line == null ? '' : ` (line ${line})`}. ` +
+ `Write \`${bare}\`; the CLI shows it with your project's runner` +
+ (download
+ ? ', and a download runner with the bare name fetches an unrelated package called astryx.'
+ : '.'),
+ });
+ }
+ }
+ }
+ return found;
+}
diff --git a/packages/cli/foundation/discovery/runner-commands.test.mjs b/packages/cli/foundation/discovery/runner-commands.test.mjs
new file mode 100644
index 0000000000..be6d1e14c9
--- /dev/null
+++ b/packages/cli/foundation/discovery/runner-commands.test.mjs
@@ -0,0 +1,128 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {describe, expect, it} from 'vitest';
+
+import {
+ CLI_COMMANDS,
+ findRunnerCommands,
+ runnerCommandsIn,
+} from './runner-commands.mjs';
+
+const COMMAND_DOCS = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../../clients/cli/commands',
+);
+
+describe('runnerCommandsIn', () => {
+ it('finds an Astryx command after a project runner, with the bare command', () => {
+ expect(runnerCommandsIn('Run `pnpm exec astryx docs theme`.')).toEqual([
+ {written: 'pnpm exec astryx docs', bare: 'astryx docs', download: false},
+ ]);
+ expect(runnerCommandsIn('yarn astryx component Button')).toEqual([
+ {
+ written: 'yarn astryx component',
+ bare: 'astryx component',
+ download: false,
+ },
+ ]);
+ });
+
+ it('always flags the unscoped name after a download runner, even alone', () => {
+ expect(runnerCommandsIn('npx astryx doctor; or `bunx astryx`')).toEqual([
+ {written: 'npx astryx doctor', bare: 'astryx doctor', download: true},
+ {written: 'bunx astryx', bare: 'astryx', download: true},
+ ]);
+ });
+
+ it('leaves the scoped package, a project runner named alone, and other tools', () => {
+ expect(
+ runnerCommandsIn(
+ 'Install with `npx @astryxdesign/cli init`. Run it through Yarn (`yarn astryx`). Format with `npx prettier --write`. `npx astryx-tools init`.',
+ ),
+ ).toEqual([]);
+ });
+
+ it('flags `bun x`, a versioned name, and a name that ends a sentence', () => {
+ expect(
+ runnerCommandsIn(
+ 'Run `bun x astryx doctor`, `npx astryx@latest init` or `npx [email protected] docs`. Or just npx astryx.',
+ ),
+ ).toEqual([
+ {written: 'bun x astryx doctor', bare: 'astryx doctor', download: true},
+ {
+ written: 'npx astryx@latest init',
+ bare: 'astryx init',
+ download: true,
+ },
+ {written: 'npx [email protected] docs', bare: 'astryx docs', download: true},
+ {written: 'npx astryx', bare: 'astryx', download: true},
+ ]);
+ expect(
+ runnerCommandsIn('Edit astryx.config, not npx astryx.config.'),
+ ).toEqual([]);
+ });
+
+ it('reads a runner and its command within one line, and needs a CLI command after a project runner', () => {
+ expect(
+ runnerCommandsIn(
+ 'Through Yarn, yarn astryx runs the copy in node_modules.\n```\npnpm astryx\nyarn astryx\n```',
+ ),
+ ).toEqual([]);
+ expect(runnerCommandsIn('npx astryx runs an unrelated package')).toEqual([
+ {written: 'npx astryx', bare: 'astryx', download: true},
+ ]);
+ expect(runnerCommandsIn('pnpm\nastryx docs')).toEqual([]);
+ expect(
+ runnerCommandsIn('Run `npx -y astryx doctor` or `npx --yes astryx`.'),
+ ).toEqual([
+ {written: 'npx -y astryx doctor', bare: 'astryx doctor', download: true},
+ {written: 'npx --yes astryx', bare: 'astryx', download: true},
+ ]);
+ });
+});
+
+describe('findRunnerCommands', () => {
+ it('reads a topic that refers back to itself once, without crashing', async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'runner-self-'));
+ const file = path.join(dir, 'acme-setup.doc.mjs');
+ fs.writeFileSync(
+ file,
+ [
+ 'const section = {',
+ " title: 'Overview',",
+ " content: [{type: 'prose', text: 'Run `yarn astryx docs` first.'}],",
+ '};',
+ "const doc = {type: 'generic', name: 'acme-setup', sections: [section]};",
+ 'section.self = section;',
+ 'doc.again = doc;',
+ 'export default doc;',
+ '',
+ ].join('\n'),
+ );
+
+ const found = await findRunnerCommands({
+ records: [{name: 'acme-setup', path: file}],
+ });
+
+ expect(
+ found.map(({command, section, line}) => ({command, section, line})),
+ ).toEqual([{command: 'yarn astryx docs', section: 'Overview', line: 3}]);
+ });
+});
+
+describe('CLI_COMMANDS', () => {
+ it('names every top-level command the CLI documents, and nothing else', () => {
+ const documented = fs
+ .readdirSync(COMMAND_DOCS)
+ .filter(file => file.endsWith('.doc.mjs'))
+ .map(file => file.slice(0, -'.doc.mjs'.length))
+ .filter(name => !name.includes('-') || name === 'gap-report');
+ expect([...CLI_COMMANDS].sort()).toEqual(
+ [...new Set([...documented, 'help'])].sort(),
+ );
+ });
+});
diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
index f32d1c89d9..47446c2b0f 100644
--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
@@ -276,6 +276,10 @@ const RUNNERS = {
runs: 'a contributed topic, for its catalog fields: name, title, description, category, and relationships',
sites: ['importDocModule'],
},
+ 'foundation/discovery/runner-commands.mjs': {
+ runs: "the package's topics, to find each Astryx command written with a package runner",
+ sites: ['loadTopicModule'],
+ },
'foundation/discovery/stray-pointers.mjs': {
runs: "the CLI's own guides, for their names, to tell which written `astryx docs <name>` points at a doc that exists",
sites: ['builtinGuideFiles'],
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 1e001ca7f7..8192b13bef 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -338,7 +338,7 @@ export const doc = {
{
value: 'integration.validate',
description:
- 'The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning | error, message, fix?, file?, line?} (fix: the change that resolves it; file and line: where, relative to the package), and notes when there are any: {code, message} information that fails nothing, such as invalid_cli_command for a malformed cliCommand, and the package layout findings added after the last minor release, each with its fix in the message (duplicate_component_doc, symlinked_root, unreadable_file, invalid_package_json, no_provider_id, source_without_component_doc where a doc and its source still pair), and doc_name_mismatch and unknown_block_component, until they become warnings in the next minor release. When the manifest loads, docTypes checks each doc against its published authoring type: status (checked | skipped), reason, typescript, docs, findings (all warnings, each naming the field and a fix), unchecked, and fixtures (test fixture docs not checked). When the manifest loads, docNames lists the component doc names it could not judge: status (checked), findings (always empty; a doc name the module its import names provably does not export is a doc_name_mismatch note, with its fix in the message) and unchecked ({file, name, reason}: a doc whose name differs from the name it is listed under and whose source exports cannot all be read, such as a re-export from another package). When the manifest loads, blockComponents lists the component names templates give in exampleFor or componentsUsed that could not be judged: status (checked), findings (always empty; a name neither the package nor Core has, and the template does not import, is an unknown_block_component note, with its fix in the message) and unchecked ({file, name, reason}: a name the template may reach through anything other than named imports and re-exports from Core, React, StyleX, local helpers or the entry of the package itself, such as an import from another package, a default or namespace import, an alias of or member read off an imported binding, require() or a dynamic import(), or a local module that cannot be read, or any name Core would have to resolve when Core is not installed).',
+ 'The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning | error, message, fix?, file?, line?} (fix: the change that resolves it; file and line: where, relative to the package), and notes when there are any: {code, message} information that fails nothing, such as invalid_cli_command for a malformed cliCommand, and the package layout findings added after the last minor release, each with its fix in the message (duplicate_component_doc, symlinked_root, unreadable_file, invalid_package_json, no_provider_id, source_without_component_doc where a doc and its source still pair), and doc_name_mismatch and unknown_block_component, until they become warnings in the next minor release. A runner_command note lists each Astryx command a topic writes with a package runner (its file, line and the bare command to write). When the manifest loads, docTypes checks each doc against its published authoring type: status (checked | skipped), reason, typescript, docs, findings (all warnings, each naming the field and a fix), unchecked, and fixtures (test fixture docs not checked). When the manifest loads, docNames lists the component doc names it could not judge: status (checked), findings (always empty; a doc name the module its import names provably does not export is a doc_name_mismatch note, with its fix in the message) and unchecked ({file, name, reason}: a doc whose name differs from the name it is listed under and whose source exports cannot all be read, such as a re-export from another package). When the manifest loads, blockComponents lists the component names templates give in exampleFor or componentsUsed that could not be judged: status (checked), findings (always empty; a name neither the package nor Core has, and the template does not import, is an unknown_block_component note, with its fix in the message) and unchecked ({file, name, reason}: a name the template may reach through anything other than named imports and re-exports from Core, React, StyleX, local helpers or the entry of the package itself, such as an import from another package, a default or namespace import, an alias of or member read off an imported binding, require() or a dynamic import(), or a local module that cannot be read, or any name Core would have to resolve when Core is not installed).',
},
{
value: 'integration.template-conflicts',
diff --git a/packages/cli/test/integration-check-failures.json b/packages/cli/test/integration-check-failures.json
index b3be172a7c..619d74a354 100644
--- a/packages/cli/test/integration-check-failures.json
+++ b/packages/cli/test/integration-check-failures.json
@@ -62,6 +62,7 @@
"prop_types_skipped",
"required_mismatch",
"root_outside_package",
+ "runner_command",
"shadowed_component_name",
"source_without_component_doc",
"source_without_template_doc",
diff --git a/packages/cli/test/runner-commands.test.mjs b/packages/cli/test/runner-commands.test.mjs
index f98da5cddc..920bcd3333 100644
--- a/packages/cli/test/runner-commands.test.mjs
+++ b/packages/cli/test/runner-commands.test.mjs
@@ -5,8 +5,10 @@
* run the unscoped name through npx (RUNNER_COMMAND_ALLOWLIST says where a
* runner is allowed, and why).
*
- * TODO(doctor-runner-check): replace the matcher below with the Doctor lane's
- * runnerCommandsIn() once it lands, keeping RUNNER_COMMAND_ALLOWLIST.
+ * The matcher is the one `doctor integration validate` holds integrations to
+ * (runnerCommandsIn). Core's own docs are held one step further: outside the
+ * named runner examples they do not write the scoped `npx @astryxdesign/cli`
+ * either, because the docsite and the CLI add the runner.
*/
import {execFileSync} from 'node:child_process';
@@ -15,21 +17,15 @@ import * as path from 'node:path';
import {fileURLToPath} from 'node:url';
import {describe, expect, it} from 'vitest';
import {RUNNER_COMMAND_ALLOWLIST} from '../foundation/discovery/runner-allowlist.mjs';
+import {runnerCommandsIn} from '../foundation/discovery/runner-commands.mjs';
const REPO = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../../..',
);
-const DOWNLOAD = String.raw`(?:npx|pnpm\s+dlx|yarn\s+dlx|bunx|bun\s+x|npm\s+exec)`;
-const PROJECT = String.raw`(?:pnpm\s+exec|pnpm|yarn)`;
-/** npx (or another download runner) with the unscoped name. */
-const UNSCOPED = new RegExp(
- String.raw`(?<![\w@/-])${DOWNLOAD}\s+astryx(?![\w@/-])`,
- 'gu',
-);
-/** Any runner in front of an Astryx command. */
-const RUNNER = new RegExp(
- String.raw`(?<![\w@/-])(?:${DOWNLOAD}\s+(?:astryx|@astryxdesign/cli(?:@[\w.-]+)?)(?![\w/-])|${PROJECT}\s+astryx\s+[a-z][\w-]*)`,
+/** A download runner with the scoped package name, which Core's docs leave to the docsite. */
+const SCOPED = new RegExp(
+ String.raw`(?<![\w@/-])(?:npx|pnpm\s+dlx|yarn\s+dlx|bunx|bun\s+x|npm\s+exec)\s+@astryxdesign/cli(?:@[\w.-]+)?(?![\w/-])`,
'gu',
);
@@ -42,20 +38,33 @@ const files = execFileSync(
.filter(file => /\.(?:[cm]?[jt]sx?|md)$/u.test(file))
.filter(file => !RUNNER_COMMAND_ALLOWLIST.skip.some(re => re.test(file)));
-/** @param {string} file @param {RegExp} re */
-function hits(file, re) {
+/**
+ * @param {string} file
+ * @param {(line: string) => string[]} find the commands a line writes
+ */
+function hits(file, find) {
const text = fs.readFileSync(path.join(REPO, file), 'utf8');
return text
.split('\n')
- .flatMap((line, i) =>
- [...line.matchAll(re)].map(m => `${file}:${i + 1}: ${m[0]}`),
- );
+ .flatMap((line, i) => find(line).map(each => `${file}:${i + 1}: ${each}`));
}
+/** @param {string} line */
+const unscoped = line =>
+ runnerCommandsIn(line)
+ .filter(each => each.download)
+ .map(each => each.written);
+
+/** @param {string} line */
+const withRunner = line => [
+ ...runnerCommandsIn(line).map(each => each.written),
+ ...[...line.matchAll(SCOPED)].map(match => match[0]),
+];
+
describe('runner commands in Astryx docs', () => {
it('never runs the unscoped name through npx', () => {
expect(files.length).toBeGreaterThan(100);
- expect(files.flatMap(file => hits(file, UNSCOPED))).toEqual([]);
+ expect(files.flatMap(file => hits(file, unscoped))).toEqual([]);
});
it('writes commands bare in docs, except the named runner examples', () => {
@@ -65,7 +74,7 @@ describe('runner commands in Astryx docs', () => {
!(file in RUNNER_COMMAND_ALLOWLIST.runnerExamples),
);
expect(docs.length).toBeGreaterThan(100);
- expect(docs.flatMap(file => hits(file, RUNNER))).toEqual([]);
+ expect(docs.flatMap(file => hits(file, withRunner))).toEqual([]);
});
it('names only files that exist', () => {