Skip to content

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

TypeScript

[CLI] Integration checks for component examples, showcases, template categories and packed assets (#7891)

Joey78641f811a4b
diff --git a/.changeset/integration-examples.md b/.changeset/integration-examples.md
new file mode 100644
index 0000000000..bb57f6e9f6
--- /dev/null
+++ b/.changeset/integration-examples.md
@@ -0,0 +1,12 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] `doctor integration validate`, and so `integration check`, lists what a package's examples need to work everywhere they are shown, as notes for the next minor release (`integration check --strict --next` fails on them now):
+
+- `component_without_example`: a published component that no block template shows with `exampleFor: '<Name>'` and `isShowcase: true` (or `alsoShowcaseFor`). A block named like a showcase that sets neither does not count. Hidden docs, family members, docs with `isHiddenFromOverview` and `Utility` components are exempt. The note carries a template doc to paste.
+- `template_category`: a template `category` written as a path, such as `components/X`, with a `"<Group> - <Variant>"` one to write.
+- `showcase_not_standalone`: a showcase (a block with `isShowcase: true` or `alsoShowcaseFor` names) that imports what a browser cannot load (`server-only`, `next/headers`, `next/server`, `next/cache`, a Node built-in) or reads `process.env` past `NODE_ENV`. Type-only imports and comments don't count, and live data through the app is fine.
+- `template_asset_not_packed`: a file or folder a template loads with `new URL(…, import.meta.url)` that does not exist, sits outside the package, or that npm leaves out of the package: by `files` in package.json (the note names a `!` entry that excludes it), or by a `.npmignore` or `.gitignore` line (the note names the line). What `npm pack --dry-run` packs decides; when npm cannot answer, an asset it may pack is listed under `data.exampleAssets` as not checked.
+
+@josephfarina
diff --git a/docs/architecture/cli-surface.md b/docs/architecture/cli-surface.md
index 07bb7cfcb0..1d5125526a 100644
--- a/docs/architecture/cli-surface.md
+++ b/docs/architecture/cli-surface.md
@@ -231,8 +231,8 @@ validate` MUST warn on a PascalCase `.tsx` at the top of the components root
raise a conflict with a package's own name. Each `doctor integration`
subcommand MUST keep its exit codes, and its JSON MAY change only by
additions. Because builds fail on its findings, it MUST NOT report a finding
- the package's code does not contradict, other than the doc faults of DEC-8
- and the doc-syntax findings of DEC-12:
+ the package's code does not contradict, other than the doc faults of DEC-8,
+ the doc-syntax findings of DEC-12 and the example findings of DEC-13:
a check that cannot judge an item lists it as not checked instead (DEC-7).
A finding that would newly fail a build MUST first ship as a note marked
`next` in `validate`'s `data.notes`, which fails nothing by default:
@@ -775,7 +775,8 @@ false finding fails a package for a fault it does not have, and its only way
out, dropping `--strict`, also drops the check for every real fault. A check
that cannot tell whether the code contradicts a doc lists the item as not
checked, which `--strict` does not fail. The exceptions are the doc-quality
-findings of DEC-8 and the doc-syntax findings of DEC-12.
+findings of DEC-8, the doc-syntax findings of DEC-12 and the example findings
+of DEC-13.
Rejected: reporting a doubtful item as a warning (`--strict` fails it).
### DEC-8 — The strict check fails on copied passages, fluff and stray pointers in docs
@@ -785,7 +786,8 @@ Rejected: reporting a doubtful item as a warning (`--strict` fails it).
People and agents read integration docs on a budget. A fact written in two
topics goes stale in one of them at the next edit, and padding costs every
reader. So these doc-quality findings fail `--strict` by owner decision, as
-an exception to DEC-7; DEC-12's doc-syntax findings are the other. A copied passage (a run of identical words, after
+an exception to DEC-7, beside DEC-12's doc-syntax findings and DEC-13's
+example findings. A copied passage (a run of identical words, after
the filters for function-word runs and for boilerplate that three or more
topics share) and a listed padding phrase (outside code and quotes) are exact
matches. The density floor is a threshold, not a contradiction, and a section
@@ -868,6 +870,31 @@ Rejected: failing `--strict` on them in a patch (packages already running the
check would break on an update), and leaving them unchecked (docs drift back
to one package manager).
+### DEC-13 — A package's examples are checked, listed now and failing in the next minor
+
+**Decider:** `josephfarina`, `2026-10-21`
+
+Template lists, docs pages and catalog cards show a package through its
+examples, each block alone and from the packed package, so a package must ship
+what they need, as Core does. `validate` lists, as `next` notes with the fix
+to paste: a published component no block template shows with `exampleFor` and
+`isShowcase: true` or names in `alsoShowcaseFor` (`component_without_example`; hidden docs, family members,
+`isHiddenFromOverview` docs and `Utility` components are exempt), a template
+category written as a path such as `components/X` (`template_category`; INV34
+still lets a package author any category, and this note only names a
+`"<Group> - <Variant>"` one), a showcase that imports server-only code or
+reads `process.env` past `NODE_ENV` (`showcase_not_standalone`; live data
+through the app is fine), and an asset loaded with `new URL(…,
+import.meta.url)` that is missing or that `npm pack --dry-run` leaves out
+(`template_asset_not_packed`; when npm cannot answer, one no `files` entry
+can reach is still reported and any other is listed as not checked, INV35). Each fails `--strict --next` now and `--strict`
+from the next minor release (DEC-11). The CLI finds a component's showcase by
+`exampleFor` first, then by folder and `componentsUsed`.
+
+Rejected: failing them in a patch (packages already running the check would
+break on an update), and per-package special cases (a package that needs one
+is a package the checks should cover).
+
## Verification
| Invariant | Evidence | Failure signal |
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 163e27bca7..5ea05fd8c0 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?, replacedPackage?}), 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). A topic or guide that took another's place carries replaces and replacedPackage, the package whose topic or guide it replaced. |
-| `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); replaces and replacedPackage when the topic or guide took another's place. |
-| `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, and a guide an integration replaced its replaces and replacedPackage) 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 (package, the npm package and always equal to name; 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 its package and 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: its package (the npm package the result is about), 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, plus package, the npm package that owns the component. |
-| `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. The envelope's package names the same 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 response: recipe (`astryx-oklch-v1`), status (`candidate`), familyCount, stopCount, modes, candidate (`TonalPaletteCandidate`), and generationReceipt. The generationReceipt contains schemaVersion (1), recipe, generatorVersion (`palette-generator-v1`), candidateFormatVersion (`palette-typescript-v1` or `palette-json-v1`), candidateSha256, optional preview, resolved request, and diagnostics. File-write fields are output, receipt, preview, written, and reason (`exists` or null). |
-| `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, next?} information beside the issues (text output marks a next note [next minor]); a note fails nothing by default, and one with next: true counts as a warning under integration check --next, fails integration check --strict --next, and fails --strict from the next minor release. Notes include invalid_cli_command for a malformed cliCommand and cli_peer_version when the running CLI is outside the @astryxdesign/cli peer range of the package, 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. For the commands a topic writes, runner_command (written with a package runner), plain_command (written bare), package_manager_command (written for one package manager) and doc_token (a token that does not parse) notes each give the file, line and the token to write. A doc_target_not_found note names a doc whose replaces or extends names no topic and no guide of the CLI docs or the docs of the package (such as a namespace), and a doc_section_unplaced note a section whose before or after names no section of what it extends (it is added at the end), and a duplicate_guide_replacement note two docs of the package that replace one guide; 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). Since 0.7.3 each import apps cannot use is also a note (its fix in the message), listed only and failing --strict from the next minor. publicImports ({status: checked, findings: [], unchecked}) lists each import the check could not judge as {file, specifier, reason}; never counted or failed on. |
-| `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, next (true with --next), 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, and upcoming how many of the validate notes carry next: true. With --next those notes count as warnings in the validate row and the totals. With --strict, failures lists each warning and each piece of skipped work again as an error, in the issue format the checks use, and with --strict --next each next note too; 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?, replacedPackage?}), 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). A topic or guide that took another's place carries replaces and replacedPackage, the package whose topic or guide it replaced. |
+| `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); replaces and replacedPackage when the topic or guide took another's place. |
+| `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, and a guide an integration replaced its replaces and replacedPackage) 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 (package, the npm package and always equal to name; 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 its package and 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: its package (the npm package the result is about), 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, plus package, the npm package that owns the component. |
+| `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. The envelope's package names the same 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 response: recipe (`astryx-oklch-v1`), status (`candidate`), familyCount, stopCount, modes, candidate (`TonalPaletteCandidate`), and generationReceipt. The generationReceipt contains schemaVersion (1), recipe, generatorVersion (`palette-generator-v1`), candidateFormatVersion (`palette-typescript-v1` or `palette-json-v1`), candidateSha256, optional preview, resolved request, and diagnostics. File-write fields are output, receipt, preview, written, and reason (`exists` or null). |
+| `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, next?} information beside the issues (text output marks a next note [next minor]); a note fails nothing by default, and one with next: true counts as a warning under integration check --next, fails integration check --strict --next, and fails --strict from the next minor release. Notes include invalid_cli_command for a malformed cliCommand and cli_peer_version when the running CLI is outside the @astryxdesign/cli peer range of the package, 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. For the commands a topic writes, runner_command (written with a package runner), plain_command (written bare), package_manager_command (written for one package manager) and doc_token (a token that does not parse) notes each give the file, line and the token to write. A doc_target_not_found note names a doc whose replaces or extends names no topic and no guide of the CLI docs or the docs of the package (such as a namespace), and a doc_section_unplaced note a section whose before or after names no section of what it extends (it is added at the end), and a duplicate_guide_replacement note two docs of the package that replace one guide; 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). Since 0.7.3 each import apps cannot use is also a note (its fix in the message), listed only and failing --strict from the next minor. So are the examples a package ships: component_without_example (a published component no block shows with exampleFor and isShowcase: true, or names in alsoShowcaseFor), template_category (a category written as a path, such as components/X), showcase_not_standalone (a showcase importing server-only code or reading process.env past NODE_ENV) and template_asset_not_packed (a new URL(…, import.meta.url) asset missing, or left out by npm pack --dry-run). When npm cannot list the files, an asset no files entry can reach is still a note and any other is listed in exampleAssets ({status: checked, findings: [], unchecked}, only when it lists any) as {file, asset, reason}. publicImports ({status: checked, findings: [], unchecked}) lists each import the check could not judge as {file, specifier, reason}; never counted or failed on. |
+| `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, next (true with --next), 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, and upcoming how many of the validate notes carry next: true. With --next those notes count as warnings in the validate row and the totals. With --strict, failures lists each warning and each piece of skipped work again as an error, in the issue format the checks use, and with --strict --next each next note too; 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/example-checks.no-npm.test.mjs b/packages/cli/api/integration/example-checks.no-npm.test.mjs
new file mode 100644
index 0000000000..b037cdbef6
--- /dev/null
+++ b/packages/cli/api/integration/example-checks.no-npm.test.mjs
@@ -0,0 +1,140 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * When npm cannot list a package's files, `template_asset_not_packed` still
+ * reports an asset no `files` entry can reach and lists every other asset as
+ * not checked (architecture:cli-surface INV35), never passing it silently.
+ */
+
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {Command} from 'commander';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+
+vi.mock('../../foundation/release/cache.mjs', () => ({
+ npmCommand: () => {
+ throw new Error('npm is not installed');
+ },
+}));
+
+const {validateIntegration} = await import('./validate-integration.mjs');
+const {integrationCheck} = await import('./check/check.mjs');
+const {registerDoctor} = await import('../../clients/cli/commands/doctor.mjs');
+
+/** @type {string} */
+let dir;
+
+/** @param {Record<string, string>} files */
+function write(files) {
+ for (const [rel, text] of Object.entries(files)) {
+ const file = path.join(dir, rel);
+ fs.mkdirSync(path.dirname(file), {recursive: true});
+ fs.writeFileSync(file, text);
+ }
+}
+
+/** @param {string[]} files */
+function packageWith(files) {
+ write({
+ 'package.json': JSON.stringify({
+ name: '@acme/kit',
+ version: '1.0.0',
+ files,
+ }),
+ 'astryx.integration.mjs': "export default {templates: './templates'};\n",
+ 'templates/img/hero.png': 'png',
+ 'assets/cat.png': 'png',
+ 'templates/card.doc.mjs':
+ "export default {type: 'block', name: 'card', displayName: 'Card', description: 'A block.'};\n",
+ 'templates/card.tsx': [
+ "const hero = new URL('./img/hero.png', import.meta.url);",
+ "const cat = new URL('../assets/cat.png', import.meta.url);",
+ 'export default () => null;',
+ '',
+ ].join('\n'),
+ });
+}
+
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-no-npm-'));
+});
+
+afterEach(() => {
+ fs.rmSync(dir, {recursive: true, force: true});
+});
+
+describe('template assets when npm gives no answer', () => {
+ it('reports an asset no entry can reach and lists the others as not checked', async () => {
+ packageWith(['templates', '!templates/img']);
+ const {data} = await validateIntegration(undefined, {cwd: dir});
+ const notes = (data.notes ?? []).filter(
+ note => note.code === 'template_asset_not_packed',
+ );
+ expect(notes).toHaveLength(1);
+ expect(notes[0].message).toContain('loads assets/cat.png');
+ expect(data.exampleAssets).toEqual({
+ status: 'checked',
+ findings: [],
+ unchecked: [
+ {
+ file: 'templates/card.tsx',
+ asset: 'templates/img/hero.png',
+ reason: 'npm was not found, and a `files` entry may reach it',
+ },
+ ],
+ });
+
+ const check = await integrationCheck({cwd: dir});
+ expect(check.data.unchecked).toBeGreaterThanOrEqual(1);
+ });
+
+ it('lists an asset not checked when there is no files field but an ignore file', async () => {
+ packageWith(['templates']);
+ const pkg = JSON.parse(
+ fs.readFileSync(path.join(dir, 'package.json'), 'utf8'),
+ );
+ delete pkg.files;
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkg));
+ fs.writeFileSync(path.join(dir, '.npmignore'), 'templates/img\n');
+ const {data} = await validateIntegration(undefined, {cwd: dir});
+ expect(
+ data.exampleAssets?.unchecked.map(each => each.asset).sort(),
+ ).toEqual(['assets/cat.png', 'templates/img/hero.png']);
+ expect(
+ data.exampleAssets?.unchecked.every(each =>
+ each.reason.includes('.npmignore may drop it'),
+ ),
+ ).toBe(true);
+ });
+
+ it('shows the assets it could not check in text output', async () => {
+ packageWith(['templates', '!templates/img']);
+ /** @type {string[]} */
+ const lines = [];
+ vi.spyOn(console, 'log').mockImplementation((...args) => {
+ lines.push(args.join(' '));
+ });
+ const previous = process.cwd();
+ process.chdir(dir);
+ try {
+ const program = new Command();
+ program.exitOverride();
+ program.option('--json', 'Output as typed JSON');
+ registerDoctor(program);
+ await program.parseAsync([
+ 'node',
+ 'astryx',
+ 'doctor',
+ 'integration',
+ 'validate',
+ ]);
+ } finally {
+ process.chdir(previous);
+ vi.restoreAllMocks();
+ }
+ const out = lines.join('\n');
+ expect(out).toContain('Template assets not checked: 1');
+ expect(out).toContain('templates/img/hero.png');
+ });
+});
diff --git a/packages/cli/api/integration/example-checks.test.mjs b/packages/cli/api/integration/example-checks.test.mjs
new file mode 100644
index 0000000000..7670f80e89
--- /dev/null
+++ b/packages/cli/api/integration/example-checks.test.mjs
@@ -0,0 +1,776 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {validateIntegration} from './validate-integration.mjs';
+import {integrationCheck} from './check/check.mjs';
+import {outsideFiles} from '../../foundation/integrations/validate-contributions.mjs';
+import {spawnSync} from 'node:child_process';
+import {npmCommand} from '../../foundation/release/cache.mjs';
+
+/**
+ * Whether the npm the CLI starts packs `rel` from the test package. npm
+ * versions read `files` differently (npm 8 and npm 10 disagree on bare names
+ * and letter case), so the check is held to the npm that runs the suite; the
+ * cases' own flags are what npm 10 does.
+ * @param {string} rel
+ */
+function npmPacks(rel) {
+ const npm = npmCommand();
+ const result = spawnSync(
+ npm.command,
+ [
+ ...npm.prefix,
+ 'pack',
+ '--dry-run',
+ '--json',
+ '--ignore-scripts',
+ '--silent',
+ ],
+ {cwd: dir, encoding: 'utf-8'},
+ );
+ return JSON.parse(result.stdout)[0].files.some(
+ (/** @type {{path: string}} */ file) => file.path === rel,
+ );
+}
+
+/** @type {string} */
+let dir;
+
+/** @param {Record<string, string>} files */
+function write(files) {
+ for (const [rel, text] of Object.entries(files)) {
+ const file = path.join(dir, rel);
+ fs.mkdirSync(path.dirname(file), {recursive: true});
+ fs.writeFileSync(file, text);
+ }
+}
+
+/** @param {string} name @param {string} [extra] */
+const componentDoc = (name, extra = '') =>
+ `export default {type: 'component', name: '${name}', displayName: '${name}', description: 'A part.', props: []${extra}};\n`;
+
+/** @param {string} name */
+const componentSource = name => `export function ${name}() { return null; }\n`;
+
+/** @param {string} name @param {string} fields */
+const blockDoc = (name, fields) =>
+ `export default {type: 'block', name: '${name}', displayName: '${name}', description: 'A block.'${fields}};\n`;
+
+/**
+ * The example notes validate lists, by code.
+ * @param {string[]} [codes]
+ */
+async function notesOf(codes) {
+ const {data} = await validateIntegration(undefined, {cwd: dir});
+ return (data.notes ?? []).filter(note => !codes || codes.includes(note.code));
+}
+
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-examples-'));
+ write({
+ 'package.json': JSON.stringify({name: '@acme/kit', version: '1.0.0'}),
+ 'astryx.integration.mjs':
+ "export default {components: './components', templates: './templates'};\n",
+ 'components/AcmeCard.doc.mjs': componentDoc('AcmeCard'),
+ 'components/AcmeCard.tsx': componentSource('AcmeCard'),
+ });
+});
+
+afterEach(() => {
+ fs.rmSync(dir, {recursive: true, force: true});
+});
+
+describe('component_without_example', () => {
+ it('lists a component no showcase shows, with a template to paste, for the next minor', async () => {
+ write({
+ // Named like a showcase, but sets no exampleFor: a standalone block.
+ 'templates/AcmeCardShowcase.doc.mjs': blockDoc('AcmeCardShowcase', ''),
+ 'templates/AcmeCardShowcase.tsx': 'export default () => null;\n',
+ });
+
+ const notes = await notesOf(['component_without_example']);
+ expect(notes).toHaveLength(1);
+ expect(notes[0].next).toBe(true);
+ expect(notes[0].message).toContain('components/AcmeCard.doc.mjs');
+ expect(notes[0].message).toContain('templates/acme-card-showcase.doc.mjs');
+ expect(notes[0].message).toContain(
+ "exampleFor: 'AcmeCard', isShowcase: true, aspectRatio: 16 / 10",
+ );
+ });
+
+ it('points at alsoShowcaseFor when the composing block already shows another component', async () => {
+ write({
+ 'components/AcmeBadge.doc.mjs': componentDoc('AcmeBadge'),
+ 'components/AcmeBadge.tsx': componentSource('AcmeBadge'),
+ 'templates/badge-demo.doc.mjs': blockDoc(
+ 'badge-demo',
+ ", exampleFor: 'AcmeBadge', isShowcase: true, componentsUsed: ['AcmeBadge', 'AcmeCard']",
+ ),
+ 'templates/badge-demo.tsx': 'export default () => null;\n',
+ });
+ const [note] = await notesOf(['component_without_example']);
+ expect(note.message).toContain(
+ "add 'AcmeCard' to `alsoShowcaseFor` in templates/badge-demo.doc.mjs",
+ );
+ expect(note.message).not.toContain("add `exampleFor: 'AcmeCard'`");
+ });
+
+ it('offers a block only to the component it names, whatever the order', async () => {
+ write({
+ 'components/AcmeAvatar.doc.mjs': componentDoc('AcmeAvatar'),
+ 'components/AcmeAvatar.tsx': componentSource('AcmeAvatar'),
+ 'components/AcmeBadge.doc.mjs': componentDoc('AcmeBadge'),
+ 'components/AcmeBadge.tsx': componentSource('AcmeBadge'),
+ 'templates/acme-badge-showcase.doc.mjs': blockDoc(
+ 'acme-badge-showcase',
+ ", componentsUsed: ['AcmeAvatar', 'AcmeBadge']",
+ ),
+ 'templates/acme-badge-showcase.tsx': 'export default () => null;\n',
+ });
+ const notes = await notesOf(['component_without_example']);
+ const asks = notes.filter(note =>
+ note.message.includes('templates/acme-badge-showcase.doc.mjs'),
+ );
+ expect(asks).toHaveLength(1);
+ expect(asks[0].message).toContain("add `exampleFor: 'AcmeBadge'`");
+ const avatar = notes.find(note =>
+ note.message.includes('AcmeAvatar.doc.mjs'),
+ );
+ expect(avatar?.message).not.toContain('acme-badge-showcase');
+ });
+
+ it('suggests a free file name when the showcase path already shows another component', async () => {
+ write({
+ 'templates/acme-card-showcase.doc.mjs': blockDoc(
+ 'acme-card-showcase',
+ ", exampleFor: 'AcmeOther', isShowcase: true",
+ ),
+ 'templates/acme-card-showcase.tsx': 'export default () => null;\n',
+ });
+ const [note] = await notesOf(['component_without_example']);
+ expect(note.message).toContain('add templates/acme-card-showcase-2.tsx');
+ expect(note.message).not.toContain(
+ 'to templates/acme-card-showcase.doc.mjs',
+ );
+ });
+
+ it('asks for isShowcase when a block already names the component in exampleFor', async () => {
+ write({
+ 'templates/card-demo.doc.mjs': blockDoc(
+ 'card-demo',
+ ", exampleFor: 'AcmeCard'",
+ ),
+ 'templates/card-demo.tsx': 'export default () => null;\n',
+ });
+ const [note] = await notesOf(['component_without_example']);
+ expect(note.message).toContain(
+ 'add `isShowcase: true` to templates/card-demo.doc.mjs',
+ );
+ });
+
+ it('never asks one block to show two components, and prefers the block that names one', async () => {
+ write({
+ 'components/AcmeText.doc.mjs': componentDoc('AcmeText'),
+ 'components/AcmeText.tsx': componentSource('AcmeText'),
+ 'templates/both.doc.mjs': blockDoc(
+ 'both',
+ ", componentsUsed: ['AcmeCard', 'AcmeText']",
+ ),
+ 'templates/both.tsx': 'export default () => null;\n',
+ 'templates/text-sample.doc.mjs': blockDoc(
+ 'text-sample',
+ ", category: 'Text - Sample', componentsUsed: ['AcmeText']",
+ ),
+ 'templates/text-sample.tsx': 'export default () => null;\n',
+ });
+ const notes = await notesOf(['component_without_example']);
+ const card = notes.find(note => note.message.includes('AcmeCard.doc.mjs'));
+ const text = notes.find(note => note.message.includes('AcmeText.doc.mjs'));
+ expect(card?.message).toContain(
+ "add `exampleFor: 'AcmeCard'` and `isShowcase: true` to templates/both.doc.mjs",
+ );
+ expect(text?.message).toContain(
+ "add `exampleFor: 'AcmeText'` and `isShowcase: true` to templates/text-sample.doc.mjs",
+ );
+ });
+
+ it('names the block that already composes the component instead of new files', async () => {
+ write({
+ 'templates/card-demo.doc.mjs': blockDoc(
+ 'card-demo',
+ ", componentsUsed: ['AcmeCard']",
+ ),
+ 'templates/card-demo.tsx': 'export default () => null;\n',
+ });
+ const [note] = await notesOf(['component_without_example']);
+ expect(note.message).toContain(
+ "add `exampleFor: 'AcmeCard'` and `isShowcase: true` to templates/card-demo.doc.mjs, the block that already composes AcmeCard",
+ );
+ expect(note.message).not.toContain('acme-card-showcase.tsx');
+ });
+
+ it.each([
+ ['an exampleFor without isShowcase', ", exampleFor: 'AcmeCard'", 1],
+ [
+ 'an exampleFor with isShowcase',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ 0,
+ ],
+ ['an alsoShowcaseFor', ", alsoShowcaseFor: ['AcmeCard']", 0],
+ ])(
+ 'counts a block with %s as the example: %i note(s)',
+ async (_, fields, count) => {
+ // Each case its own file: a doc module is read once per path.
+ const name = `card-${count}-${fields.length}`;
+ write({
+ [`templates/${name}.doc.mjs`]: blockDoc(name, fields),
+ [`templates/${name}.tsx`]: 'export default () => null;\n',
+ });
+ expect(await notesOf(['component_without_example'])).toHaveLength(count);
+ },
+ );
+
+ it('exempts hidden docs, parts kept off the overview and Utility components', async () => {
+ write({
+ 'templates/.keep': '',
+ 'components/AcmeCard.doc.mjs': componentDoc(
+ 'AcmeCard',
+ ', isHiddenFromOverview: true',
+ ),
+ 'components/AcmeProvider.doc.mjs': componentDoc(
+ 'AcmeProvider',
+ ", category: 'Utility'",
+ ),
+ 'components/AcmeProvider.tsx': componentSource('AcmeProvider'),
+ 'components/AcmeSecret.doc.mjs': componentDoc(
+ 'AcmeSecret',
+ ', hidden: true',
+ ),
+ 'components/AcmeSecret.tsx': componentSource('AcmeSecret'),
+ });
+
+ expect(await notesOf(['component_without_example'])).toEqual([]);
+ });
+
+ it('names the templates root to add when the manifest has none', async () => {
+ write({
+ 'astryx.integration.mjs':
+ "export default {components: './components'};\n",
+ });
+
+ const [note] = await notesOf(['component_without_example']);
+ expect(note.message).toContain("add `templates: './templates'`");
+ });
+});
+
+describe('template_category', () => {
+ it('lists a category written as a path, with a "<Group> - <Variant>" one', async () => {
+ write({
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", category: 'components/AcmeCard', exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': 'export default () => null;\n',
+ 'templates/fine.doc.mjs': blockDoc('fine', ", category: 'Acme - Cards'"),
+ 'templates/fine.tsx': 'export default () => null;\n',
+ 'templates/none.doc.mjs': blockDoc('none', ''),
+ 'templates/none.tsx': 'export default () => null;\n',
+ // Core's own forms: one word, and a variant with a slash.
+ 'templates/word.doc.mjs': blockDoc('word', ", category: 'Settings'"),
+ 'templates/uiux.doc.mjs': blockDoc('uiux', ", category: 'UI/UX'"),
+ 'templates/ab.doc.mjs': blockDoc('ab', ", category: 'A/B Testing'"),
+ 'templates/word.tsx': 'export default () => null;\n',
+ 'templates/slash.doc.mjs': blockDoc(
+ 'slash',
+ ", category: 'Table - Index/Detail'",
+ ),
+ 'templates/slash.tsx': 'export default () => null;\n',
+ });
+
+ const notes = await notesOf(['template_category']);
+ expect(notes).toHaveLength(1);
+ expect(notes[0].message).toContain("category 'components/AcmeCard'");
+ expect(notes[0].message).toContain(
+ "Fix: category: 'Components - AcmeCard'",
+ );
+ });
+});
+
+describe('showcase_not_standalone', () => {
+ it('lists a showcase that imports server-only code or reads process.env, and allows live data', async () => {
+ write({
+ 'package.json': JSON.stringify({
+ name: '@acme/kit',
+ version: '1.0.0',
+ dependencies: {buffer: '^6.0.0'},
+ }),
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': [
+ "import {headers} from 'next/headers';",
+ "import fs from 'node:fs';",
+ 'export default async function Card() {',
+ " const res = await fetch('/api/graphql');",
+ ' return process.env.SECRET;',
+ '}',
+ '',
+ ].join('\n'),
+ 'templates/live.doc.mjs': blockDoc(
+ 'live',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/text.doc.mjs': blockDoc(
+ 'text',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ // Sample code in strings and JSX text, and the npm buffer package.
+ 'templates/text.tsx': [
+ "import {Buffer} from 'buffer';",
+ "const sample = `import fs from 'node:fs'; process.env.SECRET`;",
+ 'const quoted = \'require("next/headers")\';',
+ 'export default function Text() {',
+ ' return <p>Set process.env.API_KEY on the server.</p>;',
+ '}',
+ '',
+ ].join('\n'),
+ 'templates/live.tsx': [
+ "import type {Headers} from 'next/headers';",
+ "export {type IncomingMessage} from 'node:http';",
+ "// import fs from 'node:fs';",
+ '/* const key = process.env.SECRET; */',
+ 'export default function Live() {',
+ " if (process.env.NODE_ENV !== 'production') fetch('/api/graphql');",
+ ' return null;',
+ '}',
+ '',
+ ].join('\n'),
+ });
+
+ const notes = await notesOf(['showcase_not_standalone']);
+ expect(notes).toHaveLength(1);
+ expect(notes[0].message).toContain('templates/card.tsx');
+ expect(notes[0].message).toContain("imports 'next/headers'");
+ expect(notes[0].message).toContain("imports 'node:fs'");
+ expect(notes[0].message).toContain('reads process.env');
+ expect(notes[0].message).toContain(
+ 'Fetching live data through the app is fine',
+ );
+ });
+
+ it('lists a block that shows components only through alsoShowcaseFor', async () => {
+ write({
+ 'package.json': JSON.stringify({name: '@acme/kit', version: '1.0.0'}),
+ 'templates/panel.doc.mjs': blockDoc(
+ 'panel',
+ ", alsoShowcaseFor: ['AcmeCard']",
+ ),
+ 'templates/panel.tsx': [
+ "import {headers} from 'next/headers';",
+ 'export default function Panel() {',
+ ' return null;',
+ '}',
+ '',
+ ].join('\n'),
+ });
+
+ const notes = await notesOf(['showcase_not_standalone']);
+ expect(notes).toHaveLength(1);
+ expect(notes[0].message).toContain('templates/panel.tsx');
+ expect(notes[0].message).toContain("imports 'next/headers'");
+ });
+});
+
+describe('template_asset_not_packed', () => {
+ it('lists an asset the files field leaves out, and one that does not exist', async () => {
+ write({
+ 'package.json': JSON.stringify({
+ name: '@acme/kit',
+ version: '1.0.0',
+ files: ['components', 'templates', 'astryx.integration.mjs'],
+ }),
+ 'assets/cat.png': 'png',
+ 'templates/cat.png': 'png',
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': [
+ "const outside = new URL('../assets/cat.png', import.meta.url);",
+ "const inside = new URL('./cat.png', import.meta.url);",
+ "const missing = new URL('./dog.png', import.meta.url);",
+ "// const old = new URL('./old.png', import.meta.url);",
+ "const sample = `new URL('./sample.png', import.meta.url)`;",
+ 'export default () => (',
+ " <p>Load it with new URL('./text.png', import.meta.url).</p>",
+ ');',
+ '',
+ ].join('\n'),
+ });
+
+ const notes = await notesOf(['template_asset_not_packed']);
+ expect(notes.map(note => note.message)).toEqual([
+ expect.stringContaining(
+ 'loads assets/cat.png, which npm leaves out of the package by its `files` field, so the template breaks once installed. Fix: add "assets" to `files`',
+ ),
+ expect.stringContaining('loads templates/dog.png, which does not exist.'),
+ ]);
+ });
+
+ it('reports an asset a ! entry leaves out, and reads a template-literal path', async () => {
+ write({
+ 'package.json': JSON.stringify({
+ name: '@acme/kit',
+ version: '1.0.0',
+ files: ['components', 'templates', '!templates/*.png'],
+ }),
+ 'templates/cat.png': 'png',
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': [
+ 'const cat = new URL(`./cat.png`, import.meta.url);',
+ 'export default () => null;',
+ '',
+ ].join('\n'),
+ });
+
+ const notes = await notesOf(['template_asset_not_packed']);
+ expect(notes).toHaveLength(1);
+ expect(notes[0].message).toContain(
+ 'the `files` entry "!templates/*.png" leaves out of the package',
+ );
+ expect(notes[0].message).toContain('drop or narrow "!templates/*.png"');
+ });
+
+ it.each([
+ [['templates/**/*', 'astryx.integration.mjs']],
+ [['./assets/', 'templates/']],
+ [['/assets', '/templates']],
+ [['assets', 'templates/*.{tsx,mjs,png}']],
+ [['assets', 'templates/*.[pt][ns][gx]', 'templates/*.mjs']],
+ ])('counts what npm packs under %j', async files => {
+ write({
+ 'package.json': JSON.stringify({
+ name: '@acme/kit',
+ version: '1.0.0',
+ files,
+ }),
+ 'assets/cat.png': 'png',
+ 'templates/cat.png': 'png',
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': [
+ "const inside = new URL('./cat.png', import.meta.url);",
+ files.includes('templates/**/*')
+ ? ''
+ : "const outside = new URL('../assets/cat.png', import.meta.url);",
+ 'export default () => null;',
+ '',
+ ].join('\n'),
+ });
+ expect(await notesOf(['template_asset_not_packed'])).toEqual([]);
+ });
+
+ it.each([
+ [
+ [
+ 'components',
+ 'astryx.integration.mjs',
+ 'templates/*.tsx',
+ 'templates/*.mjs',
+ '*.png',
+ ],
+ true,
+ ],
+ [['templates/**/*.tsx', 'templates/**/*.mjs', '*.png'], true],
+ [['templates/*.tsx', 'templates/*.mjs', 'templates/*.PNG'], true],
+ [['templates/*.tsx', 'templates/*.mjs', 'assets*'], false],
+ ])('under %j, templates/hero.png packed: %s', async (files, packed) => {
+ write({
+ 'package.json': JSON.stringify({
+ name: '@acme/kit',
+ version: '1.0.0',
+ files,
+ }),
+ 'templates/hero.png': 'png',
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': [
+ "const hero = new URL('./hero.png', import.meta.url);",
+ 'export default () => null;',
+ '',
+ ].join('\n'),
+ });
+ void packed;
+ expect(await notesOf(['template_asset_not_packed'])).toHaveLength(
+ npmPacks('templates/hero.png') ? 0 : 1,
+ );
+ });
+
+ it('brings a folder in only for an entry with no glob', async () => {
+ write({
+ 'package.json': JSON.stringify({
+ name: '@acme/kit',
+ version: '1.0.0',
+ files: ['templates', 'assets*'],
+ }),
+ 'assets/cat.png': 'png',
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': [
+ "const cat = new URL('../assets/cat.png', import.meta.url);",
+ 'export default () => null;',
+ '',
+ ].join('\n'),
+ });
+ const notes = await notesOf(['template_asset_not_packed']);
+ expect(notes).toHaveLength(npmPacks('assets/cat.png') ? 0 : 1);
+ });
+
+ it('matches without regard to case, and applies a bare *.png only inside folders another entry packs', async () => {
+ write({
+ 'package.json': JSON.stringify({
+ name: '@acme/kit',
+ version: '1.0.0',
+ files: ['templates', '*.png', 'logos/*.png'],
+ }),
+ 'assets/cat.png': 'png',
+ 'logos/Hero.PNG': 'png',
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': [
+ "const hero = new URL('../logos/Hero.PNG', import.meta.url);",
+ "const cat = new URL('../assets/cat.png', import.meta.url);",
+ 'export default () => null;',
+ '',
+ ].join('\n'),
+ });
+ const notes = await notesOf(['template_asset_not_packed']);
+ expect(notes).toHaveLength(1);
+ expect(notes[0].message).toContain('loads assets/cat.png');
+ });
+});
+
+describe('what npm packs decides', () => {
+ it('reports an asset outside the package root, which npm never packs', async () => {
+ write({
+ 'package.json': JSON.stringify({name: '@acme/kit', version: '1.0.0'}),
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': [
+ "const logo = new URL('../../shared/logo.png', import.meta.url);",
+ 'export default () => null;',
+ '',
+ ].join('\n'),
+ });
+ // Reported before the file is looked for, so none is written outside
+ // the temp folder.
+ const [note] = await notesOf(['template_asset_not_packed']);
+ expect(note.message).toContain('which is outside the package');
+ expect(note.message).not.toContain('to `files`');
+ });
+
+ it('accepts a folder URL when npm packs the files inside it', async () => {
+ write({
+ 'package.json': JSON.stringify({
+ name: '@acme/kit',
+ version: '1.0.0',
+ files: ['templates', 'components'],
+ }),
+ 'templates/img/hero.png': 'png',
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': [
+ "const images = new URL('./img/', import.meta.url);",
+ 'export default () => null;',
+ '',
+ ].join('\n'),
+ });
+ expect(await notesOf(['template_asset_not_packed'])).toEqual([]);
+ });
+
+ it('names a nested ignore file, not files, when files reaches the asset', async () => {
+ write({
+ 'package.json': JSON.stringify({
+ name: '@acme/kit',
+ version: '1.0.0',
+ files: ['components', 'templates'],
+ }),
+ 'templates/img/.npmignore': '*.png\n',
+ 'templates/img/hero.png': 'png',
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': [
+ "const hero = new URL('./img/hero.png', import.meta.url);",
+ 'export default () => null;',
+ '',
+ ].join('\n'),
+ });
+ const notes = await notesOf(['template_asset_not_packed']);
+ expect(notes).toHaveLength(npmPacks('templates/img/hero.png') ? 0 : 1);
+ if (notes.length > 0) {
+ expect(notes[0].message).toContain(
+ 'remove or narrow the line `*.png` in templates/img/.npmignore',
+ );
+ expect(notes[0].message).not.toContain('to `files`');
+ }
+ });
+
+ it('names the ! entry of files that leaves an asset out, not an unrelated ignore file', async () => {
+ write({
+ 'package.json': JSON.stringify({
+ name: '@acme/kit',
+ version: '1.0.0',
+ files: ['components', 'templates', '!templates/img'],
+ }),
+ 'templates/.npmignore': '*.log\n',
+ 'templates/img/hero.png': 'png',
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': [
+ "const hero = new URL('./img/hero.png', import.meta.url);",
+ 'export default () => null;',
+ '',
+ ].join('\n'),
+ });
+ const notes = await notesOf(['template_asset_not_packed']);
+ expect(notes).toHaveLength(npmPacks('templates/img/hero.png') ? 0 : 1);
+ if (notes.length > 0) {
+ expect(notes[0].message).toContain(
+ 'the `files` entry "!templates/img" leaves out of the package',
+ );
+ expect(notes[0].message).not.toContain('.npmignore');
+ }
+ });
+
+ it('names a nested ignore file that drops an asset', async () => {
+ write({
+ 'package.json': JSON.stringify({name: '@acme/kit', version: '1.0.0'}),
+ 'templates/img/.npmignore': 'hero.png\n',
+ 'templates/img/hero.png': 'png',
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': [
+ "const hero = new URL('./img/hero.png', import.meta.url);",
+ 'export default () => null;',
+ '',
+ ].join('\n'),
+ });
+ const notes = await notesOf(['template_asset_not_packed']);
+ expect(notes).toHaveLength(npmPacks('templates/img/hero.png') ? 0 : 1);
+ if (notes.length > 0) {
+ expect(notes[0].message).toContain(
+ 'remove or narrow the line `hero.png` in templates/img/.npmignore',
+ );
+ }
+ });
+
+ it('names the ignore-file line, not files, when a package has no files field', async () => {
+ write({
+ 'package.json': JSON.stringify({name: '@acme/kit', version: '1.0.0'}),
+ '.npmignore': '# local only\ntemplates/img\n',
+ 'templates/img/hero.png': 'png',
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': [
+ "const hero = new URL('./img/hero.png', import.meta.url);",
+ 'export default () => null;',
+ '',
+ ].join('\n'),
+ });
+ const notes = await notesOf(['template_asset_not_packed']);
+ expect(notes).toHaveLength(npmPacks('templates/img/hero.png') ? 0 : 1);
+ if (notes.length > 0) {
+ expect(notes[0].message).toContain(
+ 'remove or narrow the line `templates/img` in .npmignore',
+ );
+ expect(notes[0].message).not.toContain('to `files`');
+ }
+ });
+
+ it.each([
+ [['templates/*'], 'templates/img/hero.png', true],
+ [['templates', '!templates/img'], 'templates/img/hero.png', false],
+ [
+ ['templates/card.tsx', 'templates/card.doc.mjs', 'img'],
+ 'img/a.png',
+ true,
+ ],
+ [['Templates'], 'templates/img/hero.png', false],
+ ])('under %j, %s packed: %s', async (files, asset, packed) => {
+ write({
+ 'package.json': JSON.stringify({
+ name: '@acme/kit',
+ version: '1.0.0',
+ files,
+ }),
+ 'templates/img/hero.png': 'png',
+ 'img/a.png': 'png',
+ 'templates/card.doc.mjs': blockDoc(
+ 'card',
+ ", exampleFor: 'AcmeCard', isShowcase: true",
+ ),
+ 'templates/card.tsx': [
+ `const asset = new URL('${path.posix.relative('templates', asset).startsWith('..') ? '' : './'}${path.posix.relative('templates', asset)}', import.meta.url);`,
+ 'export default () => null;',
+ '',
+ ].join('\n'),
+ });
+ void packed;
+ expect(await notesOf(['template_asset_not_packed'])).toHaveLength(
+ npmPacks(asset) ? 0 : 1,
+ );
+ });
+
+ it('without npm, reports only an asset no files entry can reach', () => {
+ expect(outsideFiles('assets/cat.png', ['templates', '*.svg'])).toBe(true);
+ expect(outsideFiles('assets/cat.png', ['templates', '*.PNG'])).toBe(false);
+ expect(outsideFiles('assets/cat.png', ['Assets'])).toBe(false);
+ expect(outsideFiles('templates/img/a.png', ['templates/*'])).toBe(false);
+ expect(outsideFiles('assets/cat.png', ['{assets,logos}'])).toBe(false);
+ });
+});
+
+describe('integration check', () => {
+ it('fails --strict --next on the example notes, never plain --strict', async () => {
+ // This folder has no TypeScript, so --strict fails on that skip; the
+ // example notes are not among its failures.
+ const strict = await integrationCheck({cwd: dir, strict: true});
+ expect(strict.data.upcoming).toBeGreaterThan(0);
+ expect(strict.data.failures.map(failure => failure.code)).not.toContain(
+ 'component_without_example',
+ );
+
+ const next = await integrationCheck({cwd: dir, strict: true, next: true});
+ expect(next.data.failed).toBe(true);
+ expect(next.data.failures.map(failure => failure.code)).toContain(
+ 'component_without_example',
+ );
+ });
+});
diff --git a/packages/cli/api/integration/validate-integration-case-disk.test.mjs b/packages/cli/api/integration/validate-integration-case-disk.test.mjs
index 75f90f2f33..27505de274 100644
--- a/packages/cli/api/integration/validate-integration-case-disk.test.mjs
+++ b/packages/cli/api/integration/validate-integration-case-disk.test.mjs
@@ -70,7 +70,12 @@ describe('a doc whose name differs from its source only in case, on a case-insen
const {data} = await validateIntegration(undefined, {cwd: tmpDir});
expect(data.issues).toEqual([]);
- expect(data.notes).toEqual([
+ // The component has no example template; that note is tested elsewhere.
+ expect(
+ (data.notes ?? []).filter(
+ note => note.code !== 'component_without_example',
+ ),
+ ).toEqual([
{
code: 'source_without_component_doc',
next: true,
@@ -101,7 +106,12 @@ describe('a doc whose name differs from its source only in case, on a case-insen
const {data} = await validateIntegration(undefined, {cwd: tmpDir});
expect(data.issues).toEqual([]);
- expect(data.notes).toEqual([
+ // The component has no example template; that note is tested elsewhere.
+ expect(
+ (data.notes ?? []).filter(
+ note => note.code !== 'component_without_example',
+ ),
+ ).toEqual([
{
code: 'source_without_component_doc',
next: true,
diff --git a/packages/cli/api/integration/validate-integration-gaps.test.mjs b/packages/cli/api/integration/validate-integration-gaps.test.mjs
index 1a2596a194..63e94ff6f5 100644
--- a/packages/cli/api/integration/validate-integration-gaps.test.mjs
+++ b/packages/cli/api/integration/validate-integration-gaps.test.mjs
@@ -127,7 +127,28 @@ async function issuesOf(dir) {
* @returns {Promise<Array<{code: string, message: string}>>}
*/
async function listedOf(dir) {
- return (await validateIntegration(undefined, {cwd: dir})).data.notes ?? [];
+ return (
+ (await validateIntegration(undefined, {cwd: dir})).data.notes ?? []
+ ).filter(note => !EXAMPLE_CODES.has(note.code));
+}
+
+/**
+ * The example notes, which nearly every fixture here draws (a component with
+ * no example template); authoring-checks.test.mjs covers them.
+ */
+const EXAMPLE_CODES = new Set([
+ 'component_without_example',
+ 'template_category',
+ 'showcase_not_standalone',
+ 'template_asset_not_packed',
+]);
+
+/**
+ * Notes without the example notes.
+ * @param {Array<{code: string, message: string, next?: boolean}> | undefined} notes
+ */
+function others(notes) {
+ return (notes ?? []).filter(note => !EXAMPLE_CODES.has(note.code));
}
/**
@@ -239,7 +260,7 @@ describe('a name that differs from its file name', () => {
});
const {data} = await validateIntegration(undefined, {cwd: dir});
- expect(data.notes ?? []).toEqual([]);
+ expect(others(data.notes)).toEqual([]);
expect(data.docNames).toEqual({
status: 'checked',
findings: [],
@@ -657,7 +678,7 @@ describe('block component names', () => {
});
const {data} = await validateIntegration(undefined, {cwd: dir});
- expect((data.notes ?? []).map(note => note.message)).toEqual([
+ expect(others(data.notes).map(note => note.message)).toEqual([
expect.stringContaining('names "AcmeGizmo" in componentsUsed'),
]);
expect(data.blockComponents?.unchecked).toEqual([]);
@@ -682,7 +703,7 @@ describe('block component names', () => {
});
const {data} = await validateIntegration(undefined, {cwd: dir});
- expect((data.notes ?? []).map(note => note.message)).toEqual([
+ expect(others(data.notes).map(note => note.message)).toEqual([
expect.stringContaining('names "AcmeGizmo" in componentsUsed'),
]);
expect(data.blockComponents?.unchecked).toEqual([]);
@@ -838,7 +859,7 @@ describe('block component names', () => {
});
const {data} = await validateIntegration(undefined, {cwd: dir});
- expect((data.notes ?? []).map(note => note.message)).toEqual([
+ expect(others(data.notes).map(note => note.message)).toEqual([
expect.stringContaining('names "AcmeGizmo" in componentsUsed'),
]);
});
@@ -857,7 +878,7 @@ describe('block component names', () => {
});
const {data} = await validateIntegration(undefined, {cwd: dir});
- expect(data.notes ?? []).toEqual([]);
+ expect(others(data.notes)).toEqual([]);
expect(data.blockComponents?.unchecked).toEqual([
{
file: 'templates/account-card.doc.mjs',
@@ -882,7 +903,7 @@ describe('block component names', () => {
});
const {data} = await validateIntegration(undefined, {cwd: dir});
- expect((data.notes ?? []).map(note => note.message)).toEqual([
+ expect(others(data.notes).map(note => note.message)).toEqual([
expect.stringContaining('names "AcmeGizmo" in componentsUsed'),
]);
expect(data.blockComponents?.unchecked).toEqual([]);
@@ -897,7 +918,7 @@ describe('block component names', () => {
});
const {data} = await validateIntegration(undefined, {cwd: dir});
- expect(data.notes ?? []).toEqual([]);
+ expect(others(data.notes)).toEqual([]);
expect(data.blockComponents?.unchecked).toEqual([
{
file: 'templates/account-card.doc.mjs',
@@ -917,7 +938,7 @@ describe('block component names', () => {
});
const {data} = await validateIntegration(undefined, {cwd: dir});
- expect((data.notes ?? []).map(note => note.message)).toEqual([
+ expect(others(data.notes).map(note => note.message)).toEqual([
expect.stringContaining('names "AcmeGizmo" in componentsUsed'),
]);
expect(data.blockComponents?.unchecked).toEqual([]);
@@ -960,7 +981,7 @@ describe('block component names', () => {
);
const {data} = await validateIntegration(undefined, {cwd: outside});
- expect(data.notes ?? []).toEqual([]);
+ expect(others(data.notes)).toEqual([]);
const reason =
'Core is not installed, so its component names cannot be checked.';
expect(data.blockComponents).toEqual({
@@ -1366,7 +1387,7 @@ describe('package.json', () => {
).toEqual([['invalid_component', 'error']]);
}
const validate = result.data.checks[0].response.data;
- expect('notes' in validate ? validate.notes : undefined).toEqual([
+ expect('notes' in validate ? others(validate.notes) : undefined).toEqual([
{
code: 'invalid_package_json',
next: true,
@@ -1891,8 +1912,8 @@ describe('layout findings 0.7.2 did not fail on', () => {
const validate = /** @type {any} */ (
result.data.checks[0].response.data
);
- expect(validate.notes.length).toBeGreaterThan(0);
- for (const note of validate.notes) {
+ expect(others(validate.notes).length).toBeGreaterThan(0);
+ for (const note of others(validate.notes)) {
// Listed now, a warning from the next minor release: `next`.
expect(Object.keys(note).sort()).toEqual(['code', 'message', 'next']);
expect(note.next).toBe(true);
@@ -1953,8 +1974,8 @@ describe('name findings listed until the next minor release', () => {
const {data} = await validateIntegration(undefined, {cwd: dir});
expect(data.issues).toEqual([]);
expect(/** @type {any} */ (data)[report].findings).toEqual([]);
- expect(data.notes?.map(note => note.code)).toEqual([code]);
- expect(data.notes?.[0].message).toContain('Fix: ');
+ expect(others(data.notes).map(note => note.code)).toEqual([code]);
+ expect(others(data.notes)[0].message).toContain('Fix: ');
const result = await integrationCheck({cwd: dir, strict: true});
expect(result.data.failures).toEqual([]);
diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjs
index b1ea033be3..0ab793005c 100644
--- a/packages/cli/api/integration/validate-integration.mjs
+++ b/packages/cli/api/integration/validate-integration.mjs
@@ -62,6 +62,7 @@ import {
// integration-warnings need them too, and foundation must not depend on api.
import {
blockComponentsCheck,
+ componentExamplesCheck,
componentDocNamesCheck,
INVALID_CLI_COMMAND,
isListedIssue,
@@ -807,6 +808,10 @@ export async function validateIntegration(pkg, options = {}) {
await blockComponentsCheck(integration),
]
: undefined;
+ // Components no block template shows.
+ const examples = integration
+ ? await componentExamplesCheck(integration)
+ : undefined;
const docNames = names?.[0].report;
const blockComponents = names?.[1].report;
// Notes fail nothing: a malformed `cliCommand`, and the findings added
@@ -830,6 +835,7 @@ export async function validateIntegration(pkg, options = {}) {
...(names ?? []).flatMap(each =>
each.notes.map(note => ({...note, next: true})),
),
+ ...(examples?.notes ?? []).map(note => ({...note, next: true})),
]
: [];
// The doc-syntax findings in the package's topics, as `next` notes with
@@ -863,6 +869,16 @@ export async function validateIntegration(pkg, options = {}) {
...(docTypes ? {docTypes} : {}),
...(docNames ? {docNames} : {}),
...(blockComponents ? {blockComponents} : {}),
+ // Template assets npm could not place, when there are any.
+ ...(examples && examples.unchecked.length > 0
+ ? {
+ exampleAssets: {
+ status: 'checked',
+ findings: [],
+ unchecked: examples.unchecked,
+ },
+ }
+ : {}),
// What the public-import check could not judge: listed, never failed on.
...(result.found && result.publicImports
? {publicImports: result.publicImports}
diff --git a/packages/cli/api/integration/validate-integration.type.mjs b/packages/cli/api/integration/validate-integration.type.mjs
index 92754f9c59..07c9f2f967 100644
--- a/packages/cli/api/integration/validate-integration.type.mjs
+++ b/packages/cli/api/integration/validate-integration.type.mjs
@@ -39,12 +39,16 @@
* "healthy" — the two are otherwise byte-identical.
* @typedef {object} ValidateIntegrationResponse
* @property {'integration.validate'} type
- * @property {{validated: boolean, name: string | null, version: string | null, issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[], notes?: Array<{code: string, message: string, next?: boolean}>, docTypes?: DocTypesReport, docNames?: DocNamesReport, blockComponents?: BlockComponentsReport, publicImports?: PublicImportsReport}} data
+ * @property {{validated: boolean, name: string | null, version: string | null, issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[], notes?: Array<{code: string, message: string, next?: boolean}>, docTypes?: DocTypesReport, docNames?: DocNamesReport, blockComponents?: BlockComponentsReport, exampleAssets?: {status: 'checked', findings: [], unchecked: Array<{file: string, asset: string, reason: string}>}, publicImports?: PublicImportsReport}} data
* `notes`: information beside the issues. A note fails nothing by default;
* one with `next: true` counts as a warning under `integration check
* --next`, fails `integration check --strict --next`, and fails `--strict`
* from the next minor release. Notes include `invalid_cli_command`, a
* `cliCommand` that was ignored as malformed;
+ * `component_without_example`, `template_category`,
+ * `showcase_not_standalone` and `template_asset_not_packed`, what a
+ * package's examples need (next minor; a block's `alsoShowcaseFor` names
+ * count as shown);
* `cli_peer_version`, the running CLI outside the package's
* `@astryxdesign/cli` peer range; and
* the package layout findings added after the last minor release, each with
diff --git a/packages/cli/api/integration/validateIntegration.doc.mjs b/packages/cli/api/integration/validateIntegration.doc.mjs
index ac40feea5a..93da19c981 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, next?} information beside the issues; a note fails nothing by default, and one with `next: true` counts as a warning under `integration check --next`, fails `integration check --strict --next`, and fails `--strict` from the next minor release. Notes include `invalid_cli_command` for a `cliCommand` that was ignored as malformed and `cli_peer_version` when the running CLI is outside the `@astryxdesign/cli` peer range of the package, 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. For the commands a topic writes, `runner_command` (written with a package runner), `plain_command` (written bare), `package_manager_command` (written for one package manager) and `doc_token` (a token that does not parse) notes each give the file, line and the token to write. A `doc_target_not_found` note names a doc whose `replaces` or `extends` names no topic and no guide of the CLI's docs or the package's own (such as a namespace, with the guides below it), so it changes nothing unless an app also installs a package that provides it, and a `doc_section_unplaced` note a section whose `before` or `after` names no section of the topic or guide it extends, so it is added at the end, and a `duplicate_guide_replacement` note two docs of the package that replace one guide, of which only the last is read; 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). Since 0.7.3 each import apps cannot use is a note in `data.notes`, its fix inside the message, listed only: it does not fail this command or `integration check --strict`, and fails `--strict` from the next minor release. The codes are `component_import_not_exported`, `component_import_other_package`, `component_import_missing_name`, `example_import_not_exported`, `example_import_missing_name`, `template_import_not_exported`, `template_import_outside_root`, `template_private_import`, `template_import_missing_name` and `template_no_default_export`. When the manifest loads, `data.publicImports` is `{status: 'checked', findings: [], unchecked}`: `unchecked` lists each import the check could not judge, as {file, specifier, reason}, the reason starting `example <label>:` for an import in a component example: an `exports` target not built yet; a module whose export list cannot be read in full (CommonJS, or a declaration file it cannot read); a root import in a package with no `exports` (the root module `main` names is not read); every name an import (other than a component doc's own component) names that its module does not export, while a TypeScript file in the package has a `declare module` block for a relative path or the package's own name or a subpath of it, which can add names to that module (a `declare module` in a comment, `declare global`, a wildcard such as `'*.css'`, and another package's name do not count; a file whose text has `declare module` but that cannot be parsed counts); the same for every such name when the package has more than 5,000 files to search for that block; a deep path into build output not built yet in a package with no `exports`; a template import of Core when `@astryxdesign/core` is not installed beside the package (a `packages/core` of the workspace under another name does not count); every import of the package's own name when package.json has no `name` or a `name` that is not a bare package name; one entry for the whole check when package.json cannot be read; and an import of a subpath whose `exports` entry has only a `types` target, unless it is `import type`, every binding is an inline `type`, or every name it imports is a type its types file declares: a value import of a name that file does not declare as a type, a namespace or side-effect import, or any import when the types file cannot be read (it may be build output). `integration check` counts the unchecked as not compared; they never fail it.",
+ "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, next?} information beside the issues; a note fails nothing by default, and one with `next: true` counts as a warning under `integration check --next`, fails `integration check --strict --next`, and fails `--strict` from the next minor release. Notes include `invalid_cli_command` for a `cliCommand` that was ignored as malformed and `cli_peer_version` when the running CLI is outside the `@astryxdesign/cli` peer range of the package, 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. For the commands a topic writes, `runner_command` (written with a package runner), `plain_command` (written bare), `package_manager_command` (written for one package manager) and `doc_token` (a token that does not parse) notes each give the file, line and the token to write. A `doc_target_not_found` note names a doc whose `replaces` or `extends` names no topic and no guide of the CLI's docs or the package's own (such as a namespace, with the guides below it), so it changes nothing unless an app also installs a package that provides it, and a `doc_section_unplaced` note a section whose `before` or `after` names no section of the topic or guide it extends, so it is added at the end, and a `duplicate_guide_replacement` note two docs of the package that replace one guide, of which only the last is read; 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). Since 0.7.3 each import apps cannot use is a note in `data.notes`, its fix inside the message, listed only: it does not fail this command or `integration check --strict`, and fails `--strict` from the next minor release. The codes are `component_import_not_exported`, `component_import_other_package`, `component_import_missing_name`, `example_import_not_exported`, `example_import_missing_name`, `template_import_not_exported`, `template_import_outside_root`, `template_private_import`, `template_import_missing_name` and `template_no_default_export`. Since 0.7.4 the examples a package ships are checked the same way: `component_without_example` (a published component no block template shows with `exampleFor` and `isShowcase: true`, or names in `alsoShowcaseFor`), `template_category` (a template category written as a path, such as `components/X`), `showcase_not_standalone` (a showcase that imports server-only code or reads `process.env` past `NODE_ENV`) and `template_asset_not_packed` (a `new URL(…, import.meta.url)` asset that is missing, or that `npm pack --dry-run` leaves out of the package). When npm cannot list the package's files, an asset no `files` entry can reach is still a note, and any other is listed in `data.exampleAssets` (`{status: 'checked', findings: [], unchecked}`, present only when it lists any) as {file, asset, reason}; `integration check` counts them as not compared. When the manifest loads, `data.publicImports` is `{status: 'checked', findings: [], unchecked}`: `unchecked` lists each import the check could not judge, as {file, specifier, reason}, the reason starting `example <label>:` for an import in a component example: an `exports` target not built yet; a module whose export list cannot be read in full (CommonJS, or a declaration file it cannot read); a root import in a package with no `exports` (the root module `main` names is not read); every name an import (other than a component doc's own component) names that its module does not export, while a TypeScript file in the package has a `declare module` block for a relative path or the package's own name or a subpath of it, which can add names to that module (a `declare module` in a comment, `declare global`, a wildcard such as `'*.css'`, and another package's name do not count; a file whose text has `declare module` but that cannot be parsed counts); the same for every such name when the package has more than 5,000 files to search for that block; a deep path into build output not built yet in a package with no `exports`; a template import of Core when `@astryxdesign/core` is not installed beside the package (a `packages/core` of the workspace under another name does not count); every import of the package's own name when package.json has no `name` or a `name` that is not a bare package name; one entry for the whole check when package.json cannot be read; and an import of a subpath whose `exports` entry has only a `types` target, unless it is `import type`, every binding is an inline `type`, or every name it imports is a type its types file declares: a value import of a name that file does not declare as a type, a namespace or side-effect import, or any import when the types file cannot be read (it may be build output). `integration check` counts the unchecked as not compared; they never fail it.",
},
],
examples: [
diff --git a/packages/cli/api/template/template-suffix.test.mjs b/packages/cli/api/template/template-suffix.test.mjs
index 5808a7c77e..a495fb0214 100644
--- a/packages/cli/api/template/template-suffix.test.mjs
+++ b/packages/cli/api/template/template-suffix.test.mjs
@@ -250,6 +250,32 @@ describe('external showcase blocks: canonical .doc.* plus released .template.* c
expect(result.name).toBe('Bar — Showcase');
});
+ it('findShowcase prefers the showcase that names the component in exampleFor', async () => {
+ makeShowcaseFixture();
+ // Bar's showcase also uses Chip; Chip's own showcase sits in a folder
+ // that does not carry its name and says so only through exampleFor.
+ const dir = path.join(
+ tmpDir,
+ 'node_modules',
+ '@test',
+ 'ext',
+ 'blocks',
+ 'components',
+ 'Gallery',
+ );
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(
+ path.join(dir, 'ChipCard.doc.mjs'),
+ "export default {type: 'block', name: 'Chip — Card', description: 'Chip showcase.', category: 'Test - Showcases', exampleFor: 'Chip', isShowcase: true, componentsUsed: ['Chip']};\n",
+ );
+ fs.writeFileSync(
+ path.join(dir, 'ChipCard.tsx'),
+ "'use client';\nexport default function ChipCard() { return <div>Chip</div>; }",
+ );
+ const result = await findShowcase('Chip', tmpDir);
+ expect(result?.name).toBe('Chip — Card');
+ });
+
it('findRelatedBlocks finds both suffix families', async () => {
makeShowcaseFixture();
const foo = await findRelatedBlocks('Foo', tmpDir);
diff --git a/packages/cli/clients/cli/commands/doctor.mjs b/packages/cli/clients/cli/commands/doctor.mjs
index 2e740be8a4..d473e38577 100644
--- a/packages/cli/clients/cli/commands/doctor.mjs
+++ b/packages/cli/clients/cli/commands/doctor.mjs
@@ -235,6 +235,16 @@ function printIntegrationValidation(data) {
...docTypesBlocks(data.docTypes, errors > 0),
...docNamesBlocks(data.docNames),
...blockComponentsBlocks(data.blockComponents),
+ ...(data.exampleAssets && data.exampleAssets.unchecked.length > 0
+ ? [
+ text(
+ `[info] Template assets not checked: ${data.exampleAssets.unchecked.length}:`,
+ ),
+ records(data.exampleAssets.unchecked, {
+ fields: ['file', 'asset', 'reason'],
+ }),
+ ]
+ : []),
...(data.publicImports && data.publicImports.unchecked.length > 0
? [
text(
diff --git a/packages/cli/foundation/discovery/template-adapter.mjs b/packages/cli/foundation/discovery/template-adapter.mjs
index e8116ccbbb..f99fd4c5f3 100644
--- a/packages/cli/foundation/discovery/template-adapter.mjs
+++ b/packages/cli/foundation/discovery/template-adapter.mjs
@@ -696,6 +696,9 @@ async function discoverBlocks() {
aspectRatio: doc?.aspectRatio ?? 1,
componentsUsed: doc?.componentsUsed ?? [],
isShowcase: doc?.isShowcase ?? false,
+ ...(typeof doc?.exampleFor === 'string'
+ ? {exampleFor: doc.exampleFor}
+ : {}),
filePath: tsxPath,
docPath,
category: relPath,
@@ -738,6 +741,9 @@ async function discoverExternalBlocks(cwd = process.cwd()) {
aspectRatio: doc?.aspectRatio ?? 1,
componentsUsed: doc?.componentsUsed ?? [],
isShowcase: doc?.isShowcase ?? false,
+ ...(typeof doc?.exampleFor === 'string'
+ ? {exampleFor: doc.exampleFor}
+ : {}),
filePath: tsxPath,
docPath,
category: relPath,
@@ -1427,6 +1433,11 @@ export async function findShowcase(componentName, cwd, options) {
docPath: b.docPath,
});
+ // Priority 0: the showcase that names the component (`exampleFor`), the
+ // way packages declare it; a category no longer has to carry the name.
+ const named = showcases.find(b => (b.exampleFor ?? '').toLowerCase() === lc);
+ if (named) return toResult(named);
+
// Priority 1: own directory (components/Badge/ for "Badge")
const dirMatch = showcases.find(b => {
const catDir = path.basename(b.category ?? '').toLowerCase();
diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
index aab6cfa123..dab9b50a2b 100644
--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
@@ -343,6 +343,10 @@ const RUNNERS = {
runs: "each installed integration's manifest",
sites: ['importUserModule'],
},
+ 'foundation/integrations/validate-contributions.mjs': {
+ runs: "`npm pack --dry-run --json --ignore-scripts`, to read which files an integration's package holds when a template loads an asset (no lifecycle script runs, nothing is written)",
+ sites: ['child_process.spawnSync'],
+ },
'foundation/release/cache.mjs': {
runs: 'npm (under npm-guard.mjs), to install and look up CLI releases in the per-user cache; each installed release once, to check it starts and reports its version; and ps (tasklist on Windows), to confirm the process a stale lock records is node or npm before ending it',
sites: ['child_process.spawnSync ×5'],
diff --git a/packages/cli/foundation/integrations/validate-contributions.mjs b/packages/cli/foundation/integrations/validate-contributions.mjs
index d81dbc7b0a..7727d82898 100644
--- a/packages/cli/foundation/integrations/validate-contributions.mjs
+++ b/packages/cli/foundation/integrations/validate-contributions.mjs
@@ -23,6 +23,8 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
+import {spawnSync} from 'node:child_process';
+import {builtinModules} from 'node:module';
import {parse as parseModule} from '@babel/parser';
import {isValidSemver} from '../env/semver.mjs';
import {findProjectCoreDir} from '../fs/paths.mjs';
@@ -49,6 +51,7 @@ import {
TEMPLATE_CANDIDATE_RE,
} from './contribution-fixes.mjs';
import {MANIFEST_BASENAMES} from './integrations.mjs';
+import {npmCommand} from '../release/cache.mjs';
import {discoverIntegrationCodemods} from '../../assets/codemods/integration-discovery.mjs';
import {discoverIntegrationTemplatesForOne} from '../discovery/template-adapter.mjs';
import * as componentDiscovery from '../discovery/component-discovery.mjs';
@@ -1023,6 +1026,791 @@ export async function blockComponentsCheck(integration) {
};
}
+/** A package's own template category: `"<Group> - <Variant>"`. */
+/**
+ * A category written as a path, such as `components/Button`: a slash with no
+ * " - " between a group and a variant. Single words (`Settings`) and
+ * `"<Group> - <Variant>"` (`Table - Index/Detail`) are fine.
+ */
+// A category written as a path: lowercase first segment and no spaces
+// (`components/X`, `blocks/forms`), not a name with a slash in it (`UI/UX`,
+// `A/B Testing`).
+const PATH_CATEGORY = /^[a-z0-9][\w.-]*(?:\/[\w.-]+)+$/u;
+
+/** Imports a browser cannot load, which a showcase must not make. */
+const SERVER_ONLY_IMPORTS =
+ /^(?:server-only|next\/headers|next\/server|next\/cache|node:.+)$/u;
+
+/**
+ * Every spelling a glob's `{a,b}` braces stand for, nested braces included.
+ * @param {string} pattern
+ * @returns {string[]}
+ */
+function expandBraces(pattern) {
+ let depth = 0;
+ let open = -1;
+ for (let i = 0; i < pattern.length; i++) {
+ const ch = pattern[i];
+ if (ch === '\\') {
+ i++;
+ } else if (ch === '{') {
+ if (depth++ === 0) open = i;
+ } else if (ch === '}' && depth > 0 && --depth === 0) {
+ const body = pattern.slice(open + 1, i);
+ /** @type {string[]} */
+ const parts = [];
+ let level = 0;
+ let from = 0;
+ for (let j = 0; j < body.length; j++) {
+ if (body[j] === '{') level++;
+ else if (body[j] === '}') level--;
+ else if (body[j] === ',' && level === 0) {
+ parts.push(body.slice(from, j));
+ from = j + 1;
+ }
+ }
+ parts.push(body.slice(from));
+ if (parts.length < 2) continue;
+ const head = pattern.slice(0, open);
+ const tail = pattern.slice(i + 1);
+ return parts.flatMap(part => expandBraces(head + part + tail));
+ }
+ }
+ return [pattern];
+}
+
+/**
+ * One brace-free glob as a regular expression source: `**`, `*`, `?` and
+ * `[…]` classes (`[!…]` negated), as npm's `files` matching reads them.
+ * @param {string} pattern
+ */
+function globSource(pattern) {
+ let out = '';
+ for (let i = 0; i < pattern.length; i++) {
+ const ch = pattern[i];
+ if (ch === '*') {
+ if (pattern[i + 1] === '*') {
+ const slashAfter = pattern[i + 2] === '/';
+ const atStart = i === 0 || pattern[i - 1] === '/';
+ if (atStart && slashAfter) {
+ out += '(?:.*/)?';
+ i += 2;
+ } else if (atStart && i + 2 === pattern.length) {
+ out = out.replace(/\/$/u, '') + '(?:/.*)?';
+ i += 1;
+ } else {
+ out += '.*';
+ i += 1;
+ }
+ } else {
+ out += '[^/]*';
+ }
+ } else if (ch === '?') {
+ out += '[^/]';
+ } else if (ch === '[') {
+ const close = pattern.indexOf(']', i + 2);
+ if (close === -1) {
+ out += '\\[';
+ } else {
+ let body = pattern.slice(i + 1, close);
+ const negated = body.startsWith('!') || body.startsWith('^');
+ if (negated) body = body.slice(1);
+ out += `[${negated ? '^' : ''}${body.replace(/[\\\]]/gu, '\\$&')}]`;
+ i = close;
+ }
+ } else if (ch === '\\' && i + 1 < pattern.length) {
+ out += pattern[++i].replace(/[.+^${}()|[\]\\*?/]/gu, '\\$&');
+ } else {
+ out += ch.replace(/[.+^${}()|[\]\\]/gu, '\\$&');
+ }
+ }
+ return out;
+}
+
+/**
+ * The paths npm packs for the package in `base`, read from
+ * `npm pack --dry-run --json --ignore-scripts` (nothing runs, nothing is
+ * written), started the way the CLI starts npm everywhere else, or why npm
+ * could not answer.
+ * @param {string} base
+ * @returns {{paths: Set<string>} | {error: string}}
+ */
+function npmPackedPaths(base) {
+ let npm;
+ try {
+ npm = npmCommand();
+ } catch {
+ return {error: 'npm was not found'};
+ }
+ const result = spawnSync(
+ npm.command,
+ [
+ ...npm.prefix,
+ 'pack',
+ '--dry-run',
+ '--json',
+ '--ignore-scripts',
+ '--silent',
+ ],
+ {
+ cwd: base,
+ encoding: 'utf-8',
+ shell: false,
+ timeout: 60_000,
+ // One line per packed file: room for a very large package.
+ maxBuffer: 256 * 1024 * 1024,
+ },
+ );
+ if (result.error) return {error: `npm did not run (${result.error.message})`};
+ if (result.status !== 0) {
+ let code = '';
+ try {
+ code = JSON.parse(result.stdout)?.error?.code ?? '';
+ } catch {
+ // not JSON
+ }
+ return {
+ error: `npm pack failed${code ? ` (${code})` : ` with exit ${result.status}`}`,
+ };
+ }
+ try {
+ const [info] = JSON.parse(result.stdout);
+ if (Array.isArray(info?.files)) {
+ return {
+ paths: new Set(
+ info.files.map((/** @type {{path: string}} */ f) => f.path),
+ ),
+ };
+ }
+ } catch {
+ // fall through
+ }
+ return {error: 'npm pack printed no file list'};
+}
+
+/**
+ * The ignore files npm reads for one path in a package with no `files`
+ * field: in the root and each folder down to the path's own, `.npmignore`,
+ * or `.gitignore` where that folder has none. Root first, each relative to
+ * the package root.
+ * @param {string} base
+ * @param {string} rel POSIX, relative to the package root
+ * @returns {string[]}
+ */
+function ignoreFilesFor(base, rel) {
+ /** @type {string[]} */
+ const found = [];
+ const folders = rel.split('/').slice(0, -1);
+ for (let depth = 0; depth <= folders.length; depth++) {
+ const folder = folders.slice(0, depth).join('/');
+ const file = ['.npmignore', '.gitignore'].find(name =>
+ fs.existsSync(path.join(base, folder, name)),
+ );
+ if (file) found.push(folder ? `${folder}/${file}` : file);
+ }
+ return found;
+}
+
+/**
+ * The note for an asset a package with no `files` field leaves out through
+ * an ignore file, naming the line that drops it, never a `files` field,
+ * which would leave out everything else. The deepest file with a matching
+ * line is named; an entry is read relative to its own folder.
+ * @param {string} base
+ * @param {string} template
+ * @param {string} asset
+ * @param {boolean} [nestedOnly] with a `files` field npm skips the root's
+ * ignore file but still reads those in folders below it
+ */
+function ignoreFix(base, template, asset, nestedOnly = false) {
+ const files = ignoreFilesFor(base, asset).filter(
+ file => !nestedOnly || file.includes('/'),
+ );
+ for (const file of [...files].reverse()) {
+ const folder = path.posix.dirname(file);
+ const within = folder === '.' ? asset : asset.slice(folder.length + 1);
+ /** @type {string[]} */
+ let lines;
+ try {
+ lines = fs.readFileSync(path.join(base, file), 'utf8').split(/\r?\n/);
+ } catch {
+ continue;
+ }
+ const line = lines.find(
+ entry =>
+ entry.trim() !== '' &&
+ !entry.trim().startsWith('#') &&
+ !entry.trim().startsWith('!') &&
+ !outsideFiles(within, [entry.trim()]),
+ );
+ if (line) {
+ return `${template}: loads ${asset}, which npm leaves out of the package because ${file} drops it, so the template breaks once installed. Fix: remove or narrow the line \`${line.trim()}\` in ${file}, and confirm with \`npm pack --dry-run\`.`;
+ }
+ }
+ const file = files.at(-1) ?? '.npmignore';
+ return `${template}: loads ${asset}, which npm leaves out of the package because an ignore file drops it, so the template breaks once installed. Fix: remove the line in ${file} (or another ignore file on its path) that matches ${asset}, and confirm with \`npm pack --dry-run\`.`;
+}
+
+/**
+ * Whether no `files` entry can reach a path, read case-insensitively and
+ * generously (`{a,b}` braces, globs, a no-slash entry at any depth, an entry
+ * for the path or any folder above it), for when npm cannot say what it
+ * packs: a path this misses is out of the package however npm reads the list.
+ * @param {string} rel POSIX, relative to the package root
+ * @param {unknown} files
+ */
+export function outsideFiles(rel, files) {
+ if (!Array.isArray(files)) return false;
+ const parts = rel.split('/');
+ const paths = parts.map((_, i) => parts.slice(0, i + 1).join('/'));
+ return !files.some(entry => {
+ if (typeof entry !== 'string' || entry.startsWith('!')) return false;
+ const trimmed = entry
+ .replace(/^\.?\//u, '')
+ .replace(/\/+$/u, '')
+ .replace(/\/\*$/u, '/**');
+ return expandBraces(trimmed).some(spelling => {
+ const pattern = new RegExp(`^${globSource(spelling)}$`, 'iu');
+ return spelling.includes('/') || /^\.?\//u.test(entry)
+ ? paths.some(at => pattern.test(at))
+ : parts.some(name => pattern.test(name));
+ });
+ });
+}
+
+/**
+ * The `!` entry of a `files` field that leaves out `rel` or a folder above
+ * it, as written; null when none does.
+ * @param {string} rel package-relative path
+ * @param {unknown} files the `files` field
+ * @returns {string | null}
+ */
+export function negatedFilesEntry(rel, files) {
+ if (!Array.isArray(files)) return null;
+ const parts = rel.split('/');
+ const paths = parts.map((_, i) => parts.slice(0, i + 1).join('/'));
+ for (const entry of files) {
+ if (typeof entry !== 'string' || !entry.startsWith('!')) continue;
+ const trimmed = entry
+ .slice(1)
+ .replace(/^\.?\//u, '')
+ .replace(/\/+$/u, '')
+ .replace(/\/\*$/u, '/**');
+ const hit = expandBraces(trimmed).some(spelling => {
+ const pattern = new RegExp(`^${globSource(spelling)}$`, 'iu');
+ return spelling.includes('/') || /^!\.?\//u.test(entry)
+ ? paths.some(at => pattern.test(at))
+ : parts.some(name => pattern.test(name));
+ });
+ if (hit) return entry;
+ }
+ return null;
+}
+
+/**
+ * The path a `new URL()` argument spells out: a string, or a template
+ * literal with no expressions. Anything computed is not read.
+ * @param {any} node
+ * @returns {string | null}
+ */
+function literalPath(node) {
+ if (node?.type === 'StringLiteral') return node.value;
+ if (node?.type === 'TemplateLiteral' && node.expressions.length === 0) {
+ return node.quasis[0]?.value?.cooked ?? null;
+ }
+ return null;
+}
+
+/**
+ * A template module, parsed, so strings, JSX text, comments and type-only
+ * imports and exports never count. `server` is what a browser cannot run: an
+ * import, re-export or `require()` of a server-only module or an uninstalled
+ * Node builtin, a read of `process.env` other than `process.env.NODE_ENV`
+ * (which bundlers replace). `assets` are the relative paths it loads with `new URL('./x', import.meta.url)`. A module
+ * that does not parse reports nothing; the template check owns that.
+ * @param {string} source
+ * @param {Set<string>} builtins
+ * @returns {{server: string[], assets: string[]}}
+ */
+function readModule(source, builtins) {
+ /** @type {any} */
+ let ast;
+ try {
+ ast = parseModule(source, {
+ sourceType: 'module',
+ plugins: ['jsx', 'typescript'],
+ errorRecovery: true,
+ });
+ } catch {
+ return {server: [], assets: []};
+ }
+ /** @type {string[]} */
+ const assets = [];
+ /** @type {string[]} */
+ const found = [];
+ /** @param {unknown} spec */
+ const checkSpec = spec => {
+ if (
+ typeof spec === 'string' &&
+ (SERVER_ONLY_IMPORTS.test(spec) || builtins.has(spec))
+ ) {
+ found.push(`imports '${spec}'`);
+ }
+ };
+ /** @param {any} node */
+ const visit = node => {
+ if (!node || typeof node.type !== 'string') return;
+ switch (node.type) {
+ case 'ImportDeclaration':
+ if (
+ node.importKind !== 'type' &&
+ !(
+ node.specifiers.length > 0 &&
+ node.specifiers.every(
+ (/** @type {any} */ s) => s.importKind === 'type',
+ )
+ )
+ ) {
+ checkSpec(node.source.value);
+ }
+ return;
+ case 'ExportNamedDeclaration':
+ case 'ExportAllDeclaration':
+ if (
+ node.source &&
+ node.exportKind !== 'type' &&
+ !(
+ node.specifiers?.length > 0 &&
+ node.specifiers.every(
+ (/** @type {any} */ s) => s.exportKind === 'type',
+ )
+ )
+ ) {
+ checkSpec(node.source.value);
+ }
+ break;
+ case 'CallExpression':
+ if (
+ (node.callee.type === 'Identifier' &&
+ node.callee.name === 'require') ||
+ node.callee.type === 'Import'
+ ) {
+ checkSpec(node.arguments[0]?.value);
+ }
+ break;
+ case 'ImportExpression':
+ checkSpec(node.source?.value);
+ break;
+ case 'NewExpression': {
+ const [first, second] = node.arguments ?? [];
+ if (
+ node.callee.type === 'Identifier' &&
+ node.callee.name === 'URL' &&
+ literalPath(first) != null &&
+ /^\.{1,2}\//u.test(/** @type {string} */ (literalPath(first))) &&
+ second?.type === 'MemberExpression' &&
+ second.object?.type === 'MetaProperty' &&
+ second.object.meta?.name === 'import' &&
+ second.object.property?.name === 'meta' &&
+ !second.computed &&
+ second.property?.name === 'url'
+ ) {
+ assets.push(/** @type {string} */ (literalPath(first)));
+ }
+ break;
+ }
+ case 'MemberExpression': {
+ const object = node.object;
+ if (
+ object.type === 'Identifier' &&
+ object.name === 'process' &&
+ !node.computed &&
+ node.property.name === 'env'
+ ) {
+ found.push('reads process.env');
+ return;
+ }
+ if (
+ object.type === 'MemberExpression' &&
+ object.object.type === 'Identifier' &&
+ object.object.name === 'process' &&
+ !object.computed &&
+ object.property.name === 'env'
+ ) {
+ if (!node.computed && node.property.name === 'NODE_ENV') return;
+ found.push('reads process.env');
+ return;
+ }
+ break;
+ }
+ default:
+ break;
+ }
+ for (const key of Object.keys(node)) {
+ if (
+ key === 'loc' ||
+ key === 'start' ||
+ key === 'end' ||
+ key === 'leadingComments' ||
+ key === 'trailingComments' ||
+ key === 'innerComments'
+ ) {
+ continue;
+ }
+ const value = node[key];
+ if (Array.isArray(value)) value.forEach(visit);
+ else if (value && typeof value === 'object') visit(value);
+ }
+ };
+ visit(ast.program);
+ return {server: found, assets};
+}
+
+/**
+ * What a package's examples need to work everywhere they are shown: template
+ * lists, docs pages and catalog cards, which render each block alone from
+ * the packed package. Four `next` notes, each with a fix to paste
+ * (architecture:cli-surface INV35, DEC-11):
+ * - `component_without_example`: a published component no block template
+ * shows, as its `exampleFor` with `isShowcase: true` (or in
+ * `alsoShowcaseFor`). A block named like a showcase that sets neither is a
+ * standalone block and does not count. Exempt, because an example cannot
+ * fix them: a hidden doc (`hidden: true`), a member of a family (its
+ * family's example covers it), a doc kept off the overview
+ * (`isHiddenFromOverview: true`, for parts that only make sense inside a
+ * parent), and a `Utility` component (providers and context).
+ * - `template_category`: a template `category` written as a path, such as
+ * `components/X`, with a `"<Group> - <Variant>"` one to write.
+ * - `showcase_not_standalone`: a showcase that imports what a browser cannot
+ * load (`server-only`, `next/headers`, `next/server`, `next/cache`, a Node
+ * built-in) or reads `process.env` past `NODE_ENV`. Type-only imports and
+ * comments don't count, and live data is fine: a showcase may fetch
+ * through the app. Only the showcase's own file is read.
+ * - `template_asset_not_packed`: a file a template loads with `new URL(…,
+ * import.meta.url)` that does not exist, or that npm leaves out of the
+ * package (`npm pack --dry-run`). When npm cannot answer, an asset no
+ * `files` entry can reach is still a note, and any other is returned in
+ * `unchecked`.
+ * @param {LoadedIntegration} integration
+ * @returns {Promise<{notes: Note[], unchecked: Array<{file: string, asset: string, reason: string}>}>}
+ */
+export async function componentExamplesCheck(integration) {
+ /** @type {Note[]} */
+ const notes = [];
+ const base = integration.__packageDir ?? integration.components ?? '';
+ const root = integration.templates;
+ /** @type {any[]} */
+ let templates = [];
+ if (root && !rootProblem(root)) {
+ try {
+ ({templates} = await discoverIntegrationTemplatesForOne(integration));
+ } catch {
+ // Templates that cannot be read are reported by the template check.
+ return {notes, unchecked: []};
+ }
+ }
+ const rel = (/** @type {string} */ file) => slash(path.relative(base, file));
+ /** @type {unknown} */
+ let packedFiles;
+ /** @type {Set<string>} */
+ const declared = new Set();
+ try {
+ const pkg = JSON.parse(
+ fs.readFileSync(path.join(base, 'package.json'), 'utf8'),
+ );
+ packedFiles = pkg.files;
+ for (const field of [
+ 'dependencies',
+ 'peerDependencies',
+ 'optionalDependencies',
+ 'devDependencies',
+ ]) {
+ for (const name of Object.keys(pkg[field] ?? {})) declared.add(name);
+ }
+ } catch {
+ packedFiles = undefined;
+ }
+ /** @type {{paths: Set<string>} | {error: string} | undefined} what npm packs, read once */
+ let packed;
+ /** @type {Array<{file: string, asset: string, reason: string}>} */
+ const unchecked = [];
+ // A bare builtin name the package installs from npm (`buffer`, `events`)
+ // is that package, which bundlers ship to the browser.
+ const builtins = new Set(builtinModules.filter(name => !declared.has(name)));
+ /** @type {Set<string>} */
+ const shown = new Set();
+ for (const template of templates) {
+ const docFile = rel(template.docPath ?? template.filePath);
+ if (template.type === 'block') {
+ if (typeof template.exampleFor === 'string' && template.isShowcase) {
+ shown.add(template.exampleFor);
+ }
+ for (const name of template.alsoShowcaseFor ?? []) shown.add(name);
+ }
+ if (
+ typeof template.category === 'string' &&
+ template.category !== '' &&
+ PATH_CATEGORY.test(template.category)
+ ) {
+ const [group, ...rest] = template.category.split('/');
+ const variant =
+ rest.join(' ').trim() || template.displayName || template.id;
+ const suggested = `${group.charAt(0).toUpperCase()}${group.slice(1)} - ${variant}`;
+ notes.push({
+ code: 'template_category',
+ message: `${docFile}: category '${template.category}' reads as a file path, and \`astryx template\` lists templates under their category as written. Fix: category: '${suggested}', a "<Group> - <Variant>" name.`,
+ });
+ }
+ /** @type {string} */
+ let source;
+ try {
+ source = fs.readFileSync(template.filePath, 'utf8');
+ } catch {
+ continue;
+ }
+ const parsed = readModule(source, builtins);
+ // A block is a showcase when it says so, or when it shows components
+ // through `alsoShowcaseFor`, which counts them as shown above.
+ const showcase =
+ template.isShowcase === true ||
+ (Array.isArray(template.alsoShowcaseFor) &&
+ template.alsoShowcaseFor.length > 0);
+ if (template.type === 'block' && showcase) {
+ const blocked = parsed.server;
+ if (blocked.length > 0) {
+ notes.push({
+ code: 'showcase_not_standalone',
+ message: `${rel(template.filePath)}: the showcase ${[...new Set(blocked)].join(', ')}, which cannot run in a browser, so a docs page or catalog card cannot render it. Fix: move that code into the app; pass values in as props or a sample-data provider the showcase renders itself. Fetching live data through the app is fine.`,
+ });
+ }
+ }
+ for (const loaded of new Set(parsed.assets)) {
+ const asset = path.resolve(path.dirname(template.filePath), loaded);
+ const assetRel = rel(asset);
+ const exists = fs.existsSync(asset);
+ // npm packs nothing outside the package root, whatever `files` says.
+ const fromBase = path.relative(base, asset);
+ if (fromBase.startsWith('..') || path.isAbsolute(fromBase)) {
+ notes.push({
+ code: 'template_asset_not_packed',
+ message: `${rel(template.filePath)}: loads ${assetRel}, which is outside the package, so npm never packs it and the template breaks once installed. Fix: move it inside the package (beside the template is simplest), point \`new URL()\` at the new place, and confirm with \`npm pack --dry-run\`.`,
+ });
+ continue;
+ }
+ // A folder URL is packed when npm packs anything inside it.
+ const isFolder = exists && fs.statSync(asset).isDirectory();
+ if (exists) {
+ // With no `files` field npm packs everything but what an ignore file
+ // drops, in the package root or any folder down to the asset, so
+ // with no ignore file on that path there is nothing to ask.
+ if (
+ !Array.isArray(packedFiles) &&
+ ignoreFilesFor(base, assetRel).length === 0
+ ) {
+ continue;
+ }
+ // What npm packs decides. Without npm's answer, an asset no entry
+ // can reach is reported, and any other is listed as not checked.
+ packed ??= npmPackedPaths(base);
+ if ('paths' in packed) {
+ if (packed.paths.has(assetRel)) continue;
+ if (
+ isFolder &&
+ [...packed.paths].some(each => each.startsWith(`${assetRel}/`))
+ ) {
+ continue;
+ }
+ } else if (
+ !Array.isArray(packedFiles) ||
+ !outsideFiles(assetRel, packedFiles)
+ ) {
+ unchecked.push({
+ file: rel(template.filePath),
+ asset: assetRel,
+ reason: Array.isArray(packedFiles)
+ ? `${packed.error}, and a \`files\` entry may reach it`
+ : `${packed.error}, and ${ignoreFilesFor(base, assetRel).at(-1) ?? '.npmignore'} may drop it`,
+ });
+ continue;
+ }
+ }
+ const folder =
+ path.posix.dirname(assetRel) === '.'
+ ? assetRel
+ : path.posix.dirname(assetRel);
+ const negated = negatedFilesEntry(assetRel, packedFiles);
+ notes.push({
+ code: 'template_asset_not_packed',
+ message: !exists
+ ? `${rel(template.filePath)}: loads ${assetRel}, which does not exist. Fix: add the file, or point \`new URL()\` at one that does.`
+ : negated != null && !outsideFiles(assetRel, packedFiles)
+ ? `${rel(template.filePath)}: loads ${assetRel}, which the \`files\` entry "${negated}" leaves out of the package, so the template breaks once installed. Fix: drop or narrow "${negated}" so it no longer matches ${assetRel}, and confirm with \`npm pack --dry-run\`.`
+ : Array.isArray(packedFiles) &&
+ (outsideFiles(assetRel, packedFiles) ||
+ !ignoreFilesFor(base, assetRel).some(file => file.includes('/')))
+ ? `${rel(template.filePath)}: loads ${assetRel}, which npm leaves out of the package by its \`files\` field, so the template breaks once installed. Fix: add "${folder}" to \`files\`, drop any \`!\` entry that excludes it, and confirm with \`npm pack --dry-run\`.`
+ : ignoreFix(
+ base,
+ rel(template.filePath),
+ assetRel,
+ Array.isArray(packedFiles),
+ ),
+ });
+ }
+ }
+ if (!integration.components || rootProblem(integration.components)) {
+ return {notes, unchecked};
+ }
+ /** @type {any[]} */
+ let records;
+ try {
+ records = componentDiscovery.discoverIntegrationComponents(integration);
+ } catch {
+ return {notes, unchecked};
+ }
+ const templatesDir = root ? rel(root) || '.' : 'templates';
+ /** @type {Set<unknown>} blocks a note has already asked to show one component */
+ const claimed = new Set();
+ // A block that names a component, by its category, name, display name or
+ // file (`acme-badge-showcase`), is offered to that component alone, so two
+ // notes never ask one block to show two components. The longest matching
+ // name wins (`AcmeBadgeGroup` over `AcmeBadge`).
+ const key = (/** @type {string} */ value) =>
+ value.toLowerCase().replace(/[-_\s]/g, '');
+ const componentNames = records
+ .map(record => record.name)
+ .filter(name => typeof name === 'string')
+ .sort((a, b) => b.length - a.length);
+ /** @type {Map<unknown, string>} */
+ const ownerOf = new Map();
+ for (const template of templates) {
+ if (template.type !== 'block' || typeof template.exampleFor === 'string') {
+ continue;
+ }
+ const words = [
+ template.category,
+ template.name,
+ template.displayName,
+ typeof template.filePath === 'string'
+ ? path.basename(template.filePath).replace(/\.[^.]+$/u, '')
+ : undefined,
+ ]
+ .filter(value => typeof value === 'string')
+ .map(key);
+ const owner = componentNames.find(name =>
+ words.some(word => word.includes(key(name))),
+ );
+ if (owner) ownerOf.set(template, owner);
+ }
+ for (const record of records) {
+ if (componentDiscovery.isIntegrationMember(record)) continue;
+ if (shown.has(record.name)) continue;
+ let doc;
+ try {
+ doc = await loadComponentDoc(record.docPath);
+ } catch {
+ continue;
+ }
+ if (doc?.hidden === true || doc?.isHiddenFromOverview === true) continue;
+ if (doc?.category === 'Utility') continue;
+ const name = record.name;
+ const stem = `${name.replace(/([a-z0-9])([A-Z])/gu, '$1-$2').toLowerCase()}-showcase`;
+ // A block that already composes the component only needs the fields.
+ // A block that composes the component and shows nothing else takes the
+ // fields; one that is already another component's showcase takes
+ // `alsoShowcaseFor` instead, so it keeps its own.
+ // A block whose `exampleFor` already names the component only needs
+ // `isShowcase: true`.
+ const named = templates.find(
+ template => template.type === 'block' && template.exampleFor === name,
+ );
+ if (named) {
+ notes.push({
+ code: 'component_without_example',
+ message: `${rel(record.docPath)}: no block template shows "${name}" (\`exampleFor: '${name}'\` with \`isShowcase: true\`), so template lists, docs pages and catalog cards have no example of it. Fix: add \`isShowcase: true\` to ${rel(named.docPath ?? named.filePath)}, whose \`exampleFor\` already names ${name}.`,
+ });
+ continue;
+ }
+ // Among the blocks that compose it, prefer the one that names it, then
+ // one that names no component and shows nothing yet; a block that names
+ // another component is that component's.
+ const namesIt = (/** @type {any} */ template) =>
+ ownerOf.get(template) === name;
+ const composing = templates
+ .filter(
+ template =>
+ template.type === 'block' &&
+ Array.isArray(template.componentsUsed) &&
+ template.componentsUsed.includes(name) &&
+ (!ownerOf.has(template) || ownerOf.get(template) === name),
+ )
+ .sort(
+ (a, b) =>
+ Number(namesIt(b)) - Number(namesIt(a)) ||
+ Number(typeof a.exampleFor === 'string') -
+ Number(typeof b.exampleFor === 'string'),
+ );
+ const existing =
+ composing.find(
+ template =>
+ typeof template.exampleFor !== 'string' && !claimed.has(template),
+ ) ?? composing.find(template => typeof template.exampleFor === 'string');
+ const showsAnother =
+ existing != null && typeof existing.exampleFor === 'string';
+ if (existing && !showsAnother) claimed.add(existing);
+ // The stem path is free to suggest unless a block there already shows
+ // another component; then the new files take the next free stem.
+ const stemTemplate = templates.find(
+ template =>
+ typeof template.filePath === 'string' &&
+ path.basename(template.filePath).replace(/\.[^.]+$/u, '') === stem,
+ );
+ const stemShowsAnother =
+ stemTemplate != null &&
+ typeof stemTemplate.exampleFor === 'string' &&
+ stemTemplate.exampleFor !== name;
+ let freeStem = stem;
+ if (stemShowsAnother && root && !rootProblem(root)) {
+ for (
+ let n = 2;
+ fs.existsSync(path.join(root, `${freeStem}.tsx`)) ||
+ fs.existsSync(path.join(root, `${freeStem}.doc.mjs`));
+ n++
+ ) {
+ freeStem = `${stem}-${n}`;
+ }
+ }
+ const taken =
+ !existing &&
+ !stemShowsAnother &&
+ root &&
+ !rootProblem(root) &&
+ fs.existsSync(path.join(root, `${stem}.tsx`));
+ if (existing || taken) {
+ const doc = existing
+ ? rel(existing.docPath ?? existing.filePath)
+ : `${templatesDir}/${stem}.doc.mjs`;
+ notes.push({
+ code: 'component_without_example',
+ message: `${rel(record.docPath)}: no block template shows "${name}" (\`exampleFor: '${name}'\` with \`isShowcase: true\`), so template lists, docs pages and catalog cards have no example of it. Fix: ${showsAnother ? `add '${name}' to \`alsoShowcaseFor\` in ${doc}, the block that already composes ${name} as the showcase of ${existing.exampleFor}` : `add \`exampleFor: '${name}'\` and \`isShowcase: true\` to ${doc}${existing ? `, the block that already composes ${name}` : ''}`}. A doc set to \`hidden\`, \`isHiddenFromOverview\` or category \`Utility\` needs no example.`,
+ });
+ continue;
+ }
+ notes.push({
+ code: 'component_without_example',
+ message:
+ `${rel(record.docPath)}: no block template shows "${name}" (\`exampleFor: '${name}'\` with \`isShowcase: true\`), so template lists, docs pages and catalog cards have no example of it.` +
+ (root
+ ? ''
+ : " The manifest sets no `templates` root; add `templates: './templates'` to it.") +
+ ` Fix: add ${templatesDir}/${freeStem}.tsx, a small composition that renders ${name}, and beside it ${templatesDir}/${freeStem}.doc.mjs:` +
+ ` export default {type: 'block', name: '${freeStem}', displayName: '${name} showcase', description: 'A ${name} in use.', exampleFor: '${name}', isShowcase: true, aspectRatio: 16 / 10};` +
+ ' A doc set to `hidden`, `isHiddenFromOverview` or category `Utility` needs no example.',
+ });
+ }
+ return {notes, unchecked};
+}
+
/**
* Warn about a `.tsx` directly in the templates root with no same-stem template
* metadata: template discovery pairs sources with docs, so `astryx template`
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index f645d77c70..cd36ce869e 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, next?} information beside the issues (text output marks a next note [next minor]); a note fails nothing by default, and one with next: true counts as a warning under integration check --next, fails integration check --strict --next, and fails --strict from the next minor release. Notes include invalid_cli_command for a malformed cliCommand and cli_peer_version when the running CLI is outside the @astryxdesign/cli peer range of the package, 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. For the commands a topic writes, runner_command (written with a package runner), plain_command (written bare), package_manager_command (written for one package manager) and doc_token (a token that does not parse) notes each give the file, line and the token to write. A doc_target_not_found note names a doc whose replaces or extends names no topic and no guide of the CLI docs or the docs of the package (such as a namespace), and a doc_section_unplaced note a section whose before or after names no section of what it extends (it is added at the end), and a duplicate_guide_replacement note two docs of the package that replace one guide; 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). Since 0.7.3 each import apps cannot use is also a note (its fix in the message), listed only and failing --strict from the next minor. publicImports ({status: checked, findings: [], unchecked}) lists each import the check could not judge as {file, specifier, reason}; never counted or failed on.',
+ '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, next?} information beside the issues (text output marks a next note [next minor]); a note fails nothing by default, and one with next: true counts as a warning under integration check --next, fails integration check --strict --next, and fails --strict from the next minor release. Notes include invalid_cli_command for a malformed cliCommand and cli_peer_version when the running CLI is outside the @astryxdesign/cli peer range of the package, 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. For the commands a topic writes, runner_command (written with a package runner), plain_command (written bare), package_manager_command (written for one package manager) and doc_token (a token that does not parse) notes each give the file, line and the token to write. A doc_target_not_found note names a doc whose replaces or extends names no topic and no guide of the CLI docs or the docs of the package (such as a namespace), and a doc_section_unplaced note a section whose before or after names no section of what it extends (it is added at the end), and a duplicate_guide_replacement note two docs of the package that replace one guide; 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). Since 0.7.3 each import apps cannot use is also a note (its fix in the message), listed only and failing --strict from the next minor. So are the examples a package ships: component_without_example (a published component no block shows with exampleFor and isShowcase: true, or names in alsoShowcaseFor), template_category (a category written as a path, such as components/X), showcase_not_standalone (a showcase importing server-only code or reading process.env past NODE_ENV) and template_asset_not_packed (a new URL(…, import.meta.url) asset missing, or left out by npm pack --dry-run). When npm cannot list the files, an asset no files entry can reach is still a note and any other is listed in exampleAssets ({status: checked, findings: [], unchecked}, only when it lists any) as {file, asset, reason}. publicImports ({status: checked, findings: [], unchecked}) lists each import the check could not judge as {file, specifier, reason}; never counted or failed on.',
},
{
value: 'integration.template-conflicts',
diff --git a/packages/cli/test/integration-check-failures.json b/packages/cli/test/integration-check-failures.json
index 907e3a60eb..788c6efe4e 100644
--- a/packages/cli/test/integration-check-failures.json
+++ b/packages/cli/test/integration-check-failures.json
@@ -25,6 +25,7 @@
"block_components_skipped",
"codemod_outside_version",
"component_name_conflict",
+ "component_without_example",
"copied_passage",
"core_not_found",
"default_mismatch",
@@ -75,9 +76,12 @@
"root_outside_package",
"runner_command",
"shadowed_component_name",
+ "showcase_not_standalone",
"source_without_component_doc",
"source_without_template_doc",
"stray_doc_pointer",
+ "template_asset_not_packed",
+ "template_category",
"template_id_conflict",
"type_mismatch",
"unknown_field",
diff --git a/packages/cli/test/integration-check-failures.test.mjs b/packages/cli/test/integration-check-failures.test.mjs
index 127a065748..bbd5ee980a 100644
--- a/packages/cli/test/integration-check-failures.test.mjs
+++ b/packages/cli/test/integration-check-failures.test.mjs
@@ -192,6 +192,15 @@ beforeAll(async () => {
'templates/acme-page.tsx',
'export default function Fixture() { return null; }\n',
);
+ // The button's example, so the fixture draws no note.
+ write(
+ 'templates/acme-button-showcase.doc.mjs',
+ "export default {type: 'block', name: 'acme-button-showcase', displayName: 'Acme Button showcase', description: 'A button in use.', category: 'Acme - Actions', exampleFor: 'AcmeButton', isShowcase: true};\n",
+ );
+ write(
+ 'templates/acme-button-showcase.tsx',
+ "import {AcmeButton} from '@acme/widgets';\nexport default function Showcase() { return <AcmeButton />; }\n",
+ );
write(
'docs/acme-guide.doc.mjs',
"export default {type: 'generic', name: 'acme-guide', title: 'Acme guide', description: 'A guide.', sections: [{title: 'One', content: [{type: 'prose', text: 'One.'}]}]};\n",