An open source design system that's fully customizable and agent ready
TypeScript
[fix] Template and build tell you what the template needs that your project lacks (#7183)
Joeyf9a0f478f440
diff --git a/.changeset/template-setup-notes.md b/.changeset/template-setup-notes.mdnew file mode 100644index 0000000000..d72b2bc2ec--- /dev/null+++ b/.changeset/template-setup-notes.md@@ -0,0 +1,13 @@+---+'@astryxdesign/cli': patch+---++[fix] Template and build tell you what a scaffolded template needs that your project lacks.++When `astryx template <name> <path>` scaffolds a file that imports packages your project does not have (e.g. `@heroicons/react`, `recharts`, `lucide-react`), the receipt now includes a ready-to-run install command with the project's package manager and version ranges from the CLI workspace. `astryx build` shows the same note on its start template.++When a scaffolded template uses StyleX and the project has no compiler plugin configured, the receipt warns and points to `astryx docs styling-overview`. The agent-docs block no longer says "don't use xstyle" flat-out — it acknowledges that some templates need it and links the setup doc.++`detectStylingSystem` now recognizes the official `@stylexjs/rollup-plugin`, `@stylexjs/webpack-plugin`, and `@stylexjs/nextjs-plugin` alongside the existing entries.++@josephfarinadiff --git a/packages/cli/README.md b/packages/cli/README.mdindex 006602e6e8..1ad9e03ec6 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -420,71 +420,71 @@ 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` | Confirmation that the managed agent-docs block was removed (`data.removed: true`) — returned when --remove-agents is set. |-| `component.list` | The component catalog grouped by component group (each component's group field): `detail` (the level: names \| compact \| full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries ({name, package, description, import}), or a full ComponentDoc per entry with its package. |-| `component.batch` | The component specialization of the shared `BatchResponse` and `BatchRow` types. An explicit programmatic selector array, or two or more CLI selectors, returns one ordered receipt: `count` plus `results`, one row per selector including duplicates. Every row carries `selector` and `status` (found \| not_found \| ambiguous \| error). A found row carries `result`, the same {type, data} response as one selector. An ambiguous row carries `code`, `error`, and `candidates` ({package, component, kind, installed}). Other failed rows carry `code`, `error`, and optional `suggestions` ({name, reason}). |-| `component.detail` | One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc). The envelope's package names the same owner. |-| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). The envelope's package names the npm package that owns the component. |-| `component.detail.source` | One component's source file, as {component, source}. The envelope's package names the npm package that owns the component. |-| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. The envelope's package names the npm package that owns the component. |-| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry ({name, package, displayName, description, isShowcase, category}); each block names the package that owns it, and the envelope's package names the component's owner. |-| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description, package, replaces?}), in read order; meta.namespaces lists the docs tree's top-level namespaces, and meta.notLoaded each package whose docs did not load. |-| `docs.detail` | One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined and each section naming the package that wrote it, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |-| `docs.index` | One topic's section index, the text read of a topic with more than one section (and --index): the topic's name, title, and description, plus sections, each {id, title, package, summary} (pass the id as the section argument; package is the npm package that wrote the section; summary is the section's one-line summary), and links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |-| `docs.detail.section` | One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open its topic index and the sections before and after it). The envelope's package names the npm package that wrote the section. |-| `docs.node` | One node of the docs tree, read by its route: its id, kind, package, title, summary, and breadcrumb, plus a namespace's slots with their children (one level down, each naming its package) or a typed doc's content, and links ({up, previous, next, related}: the commands that open its parent, its neighbors, and the docs it names). |-| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |-| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |-| `discover.list` | The integrations the project loads (name, category, components, version, a list per other kind they add, and latest when a source knows it); with a discover source, meta.available lists what the project could add and meta.sources reports each source; when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |-| `discover.detail` | One package, for an @scope/name or @scope/name@version query: what the shown version adds, whether the project has it, and, when a source knows the package, its versions, latest release, and the command that adds it. |-| `discover.detail.doc` | The validated ComponentDoc for one installed component, for an @scope/name/Component query. |-| `discover.item` | One item that is not an installed component, for an @scope/name/<item> query: its kind, name, package, version, and whether the project has the package. |-| `discover.search` | The echoed query plus every matching item and package across all packages, each with its kind and whether the project has it, even when only one matches; total is set when --limit cut the list. |-| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, package, score, reason, description, command} (package is the npm package that owns the result), plus import (components, hooks), title, parent (the command that opens the level above), and, for a hit on one section, section (docs), or displayName and kind (templates). |-| `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. |-| `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, package, command, basis, reason, alternatives, ...} (the start and each alternative name the package that owns the template), pages (search's closest templates), blocks and domain as SearchResultEntry[] (each naming its package), frame and foundation (Core component names), and hint {reason, commands} when thin. |-| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. The envelope's package is @astryxdesign/core. |-| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. The envelope's package names the same owning package. |-| `gap-report.categories` | The fixed gap category values and human-readable labels. |-| `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals. |-| `template.list` | 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, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). 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.add` | The released source-copy receipt: slug, displayName, maintained flag, owner package, outputDir, source entry, exportName, and files. Its additive meta.deprecations entry names DEP-0005 and the source-fork/import replacements. |-| `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, deprecatedFor?}, where props and states are its legal override keys and deprecatedFor names the canonical replacement key. |-| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |-| `upgrade.list` | Every available codemod, oldest→newest, as {name, package, title, version, optional}; returned for --list without running anything. |-| `upgrade.registry` | The copied-composition receipt for --registry: applied, ok, the counts (found, current, wouldUpdate, updated, wouldMerge, merged, wouldRefreshReceipt, receiptsRefreshed, conflicts, missing, invalid, failed), and items. |-| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |-| `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. |-| `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], subcommands?), jsonSupported, and the flat responseTypes index. |-| `help` | Help, in one of two shapes. A bare `astryx --json` returns the root manifest: name, version, commands (the command names), jsonSupported, and manifest (the full payload `astryx manifest --json` returns). `--help --json` on any command, or `astryx help [command] --json`, returns that command's help: command, description, usage, options (each flags, description, and defaultValue and choices when set), and subcommands (each name and description). data.manifest marks the first shape; data.usage marks the second. |-| `version` | The CLI version, for `astryx --version --json`: {version}. |-| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and an optional fix, always present on warn and fail) plus a `summary` of counts per status. |-| `integration.add` | A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun. |-| `integration.pack-check` | The packed-package check: name, version, packable, tarball {filename, fileCount, size, unpackedSize} or null, inventory {manifest, roots [{kind, path, expectedFiles, missingFiles, complete}], expectedFiles, packedFiles}, contributions {local, packed}, each null or {themes [{slug, exportName}], components, templates [{id, type, name}], codemods [{version, id}], docs, agentDocsAppend}, and issues [{code, severity, message}]. |-| `integration.validate` | The validation result: validated (false when no integration manifest was found, so nothing was checked and the empty issues list proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |-| `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. |-| `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`). |-| `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, written (the output path, or null when nothing was written), and demoMediaReplaced (count of demo media placeholders). Carries `meta.deprecations` with DEP-0006 and its replacement commands. |-| `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). Carries `meta.deprecations` with DEP-0006 and its replacement commands. |-| `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. Carries `meta.deprecations` with DEP-0006 and its replacement commands. |+| 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` | Confirmation that the managed agent-docs block was removed (`data.removed: true`) — returned when --remove-agents is set. |+| `component.list` | The component catalog grouped by component group (each component's group field): `detail` (the level: names \| compact \| full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries ({name, package, description, import}), or a full ComponentDoc per entry with its package. |+| `component.batch` | The component specialization of the shared `BatchResponse` and `BatchRow` types. An explicit programmatic selector array, or two or more CLI selectors, returns one ordered receipt: `count` plus `results`, one row per selector including duplicates. Every row carries `selector` and `status` (found \| not_found \| ambiguous \| error). A found row carries `result`, the same {type, data} response as one selector. An ambiguous row carries `code`, `error`, and `candidates` ({package, component, kind, installed}). Other failed rows carry `code`, `error`, and optional `suggestions` ({name, reason}). |+| `component.detail` | One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc). The envelope's package names the same owner. |+| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). The envelope's package names the npm package that owns the component. |+| `component.detail.source` | One component's source file, as {component, source}. The envelope's package names the npm package that owns the component. |+| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. The envelope's package names the npm package that owns the component. |+| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry ({name, package, displayName, description, isShowcase, category}); each block names the package that owns it, and the envelope's package names the component's owner. |+| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description, package, replaces?}), in read order; meta.namespaces lists the docs tree's top-level namespaces, and meta.notLoaded each package whose docs did not load. |+| `docs.detail` | One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined and each section naming the package that wrote it, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |+| `docs.index` | One topic's section index, the text read of a topic with more than one section (and --index): the topic's name, title, and description, plus sections, each {id, title, package, summary} (pass the id as the section argument; package is the npm package that wrote the section; summary is the section's one-line summary), and links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |+| `docs.detail.section` | One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open its topic index and the sections before and after it). The envelope's package names the npm package that wrote the section. |+| `docs.node` | One node of the docs tree, read by its route: its id, kind, package, title, summary, and breadcrumb, plus a namespace's slots with their children (one level down, each naming its package) or a typed doc's content, and links ({up, previous, next, related}: the commands that open its parent, its neighbors, and the docs it names). |+| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |+| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |+| `discover.list` | The integrations the project loads (name, category, components, version, a list per other kind they add, and latest when a source knows it); with a discover source, meta.available lists what the project could add and meta.sources reports each source; when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |+| `discover.detail` | One package, for an @scope/name or @scope/name@version query: what the shown version adds, whether the project has it, and, when a source knows the package, its versions, latest release, and the command that adds it. |+| `discover.detail.doc` | The validated ComponentDoc for one installed component, for an @scope/name/Component query. |+| `discover.item` | One item that is not an installed component, for an @scope/name/<item> query: its kind, name, package, version, and whether the project has the package. |+| `discover.search` | The echoed query plus every matching item and package across all packages, each with its kind and whether the project has it, even when only one matches; total is set when --limit cut the list. |+| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, package, score, reason, description, command} (package is the npm package that owns the result), plus import (components, hooks), title, parent (the command that opens the level above), and, for a hit on one section, section (docs), or displayName and kind (templates). |+| `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. |+| `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, package, command, basis, reason, alternatives, ...} (the start and each alternative name the package that owns the template), pages (search's closest templates), blocks and domain as SearchResultEntry[] (each naming its package), frame and foundation (Core component names), and hint {reason, commands} when thin. |+| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. The envelope's package is @astryxdesign/core. |+| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. The envelope's package names the same owning package. |+| `gap-report.categories` | The fixed gap category values and human-readable labels. |+| `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals. |+| `template.list` | 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). 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.add` | The released source-copy receipt: slug, displayName, maintained flag, owner package, outputDir, source entry, exportName, and files. Its additive meta.deprecations entry names DEP-0005 and the source-fork/import replacements. |+| `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, deprecatedFor?}, where props and states are its legal override keys and deprecatedFor names the canonical replacement key. |+| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |+| `upgrade.list` | Every available codemod, oldest→newest, as {name, package, title, version, optional}; returned for --list without running anything. |+| `upgrade.registry` | The copied-composition receipt for --registry: applied, ok, the counts (found, current, wouldUpdate, updated, wouldMerge, merged, wouldRefreshReceipt, receiptsRefreshed, conflicts, missing, invalid, failed), and items. |+| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |+| `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. |+| `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], subcommands?), jsonSupported, and the flat responseTypes index. |+| `help` | Help, in one of two shapes. A bare `astryx --json` returns the root manifest: name, version, commands (the command names), jsonSupported, and manifest (the full payload `astryx manifest --json` returns). `--help --json` on any command, or `astryx help [command] --json`, returns that command's help: command, description, usage, options (each flags, description, and defaultValue and choices when set), and subcommands (each name and description). data.manifest marks the first shape; data.usage marks the second. |+| `version` | The CLI version, for `astryx --version --json`: {version}. |+| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and an optional fix, always present on warn and fail) plus a `summary` of counts per status. |+| `integration.add` | A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun. |+| `integration.pack-check` | The packed-package check: name, version, packable, tarball {filename, fileCount, size, unpackedSize} or null, inventory {manifest, roots [{kind, path, expectedFiles, missingFiles, complete}], expectedFiles, packedFiles}, contributions {local, packed}, each null or {themes [{slug, exportName}], components, templates [{id, type, name}], codemods [{version, id}], docs, agentDocsAppend}, and issues [{code, severity, message}]. |+| `integration.validate` | The validation result: validated (false when no integration manifest was found, so nothing was checked and the empty issues list proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |+| `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. |+| `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`). |+| `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, written (the output path, or null when nothing was written), and demoMediaReplaced (count of demo media placeholders). Carries `meta.deprecations` with DEP-0006 and its replacement commands. |+| `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). Carries `meta.deprecations` with DEP-0006 and its replacement commands. |+| `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. Carries `meta.deprecations` with DEP-0006 and its replacement commands. |<!-- 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/build/_adapter.mjs b/packages/cli/api/build/_adapter.mjsindex ce1e5ae265..5cc4053f68 100644--- a/packages/cli/api/build/_adapter.mjs+++ b/packages/cli/api/build/_adapter.mjs@@ -21,6 +21,7 @@ import fs from 'node:fs';import {discoverTemplates} from '../template/template.mjs';import {componentKeywords} from '../search/search.mjs';import {findCoreDir} from '../../foundation/fs/paths.mjs';+import {analyzeTemplateNeeds} from '../../foundation/discovery/template-needs.mjs';/*** A page template the kit can recommend starting from.@@ -32,6 +33,7 @@ import {findCoreDir} from '../../foundation/fs/paths.mjs';* @property {string} package The npm package that owns this template.* @property {string} category The template's own `Family - Variant` label; empty when it declares none.* @property {string[]} keywords The ideas the page serves, as its own descriptor names them; empty when it declares none.+ * @property {string} filePath Absolute path to the template source file on disk.*//**@@ -69,6 +71,7 @@ export async function loadPageTemplates(cwd) {package: t.package ?? '@astryxdesign/core',category: t.category || '',keywords: t.keywords ?? [],+ filePath: t.filePath,// The id `template()` resolves back to this entry: an active replacement// owns the Core id it names, so that id selects it, not its own.command: `astryx template ${t.replaces ?? t.dirName} --type page`,@@ -148,3 +151,22 @@ export function isWeightsFile(file) {file.blend.every((/** @type {any} */ x) => Number.isFinite(x)));}++/**+ * Analyze what a start template needs that the project lacks. The kit leaf+ * calls this through the adapter rather than reading the file itself, because+ * file access is environment access (architecture:cli-surface INV21).+ *+ * @param {PageTemplate} template+ * @param {string} cwd Project directory+ * @returns {string[]} Setup notes (empty when the template needs nothing).+ */+export function templateSetupNotes(template, cwd) {+ try {+ const source = fs.readFileSync(template.filePath, 'utf-8');+ return analyzeTemplateNeeds(source, cwd).notes;+ } catch {+ // Best-effort: a read failure does not break the recommendation.+ return [];+ }+}diff --git a/packages/cli/api/build/build.doc.mjs b/packages/cli/api/build/build.doc.mjsindex aaa892f906..03decf67b8 100644--- a/packages/cli/api/build/build.doc.mjs+++ b/packages/cli/api/build/build.doc.mjs@@ -64,7 +64,7 @@ export const doc = {{type: 'build.kit',description:- "The page template to start from and the kit around it: the echoed query, hasResults/matchCount/directMatch fields, `start` (the template to scaffold, the `template <id> --type page <path>` command that selects it, whether the page ranker's pick is also search's direct match, the closest page, or the fallback app shell, and the ranker's next two `alternatives`), search's closest page templates (≤3), drop-in block patterns (≤5), idea-specific components/hooks (≤6), and the always-on frame + foundation component-name arrays. Carries `hint` only when the kit came back thin — what to try instead, so a caller does not read a near-empty kit as \"the package has nothing\".",+ "The page template to start from and the kit around it: the echoed query, hasResults/matchCount/directMatch fields, `start` (the template to scaffold, the `template <id> --type page <path>` command that selects it, whether the page ranker's pick is also search's direct match, the closest page, or the fallback app shell, the ranker's next two `alternatives`, and optional `notes` — setup notes naming what the template needs that the project lacks, such as missing packages or a missing StyleX compiler), search's closest page templates (≤3), drop-in block patterns (≤5), idea-specific components/hooks (≤6), and the always-on frame + foundation component-name arrays. Carries `hint` only when the kit came back thin — what to try instead, so a caller does not read a near-empty kit as \"the package has nothing\".",},],throws: [diff --git a/packages/cli/api/build/build.type.mjs b/packages/cli/api/build/build.type.mjsindex 273a613c71..2e8ab18a53 100644--- a/packages/cli/api/build/build.type.mjs+++ b/packages/cli/api/build/build.type.mjs@@ -47,6 +47,7 @@* @property {'direct' | 'closest' | 'fallback'} basis Why this template. The page ranker picks every start: it weighs each matched word by how rare it is among page templates, favors the family the idea's head names and the container it names ("in a modal"), and discounts words that only modify another. `direct` when its pick is also search's direct match (`directMatch`); `closest` when it is not; `fallback` when no template has the evidence to lead and the page starts from the app shell.* @property {string} reason One sentence saying the same as `basis`, for a reader.* @property {BuildAlternative[]} alternatives The ranker's next closest page templates (≤2), for when the start's layout is wrong.+ * @property {string[]} [notes] Setup notes: what the template needs that the project lacks (missing packages, missing StyleX compiler). Present only when the start template imports packages the project does not have or needs a StyleX compiler the project has not configured.*//**diff --git a/packages/cli/api/build/kit/kit.mjs b/packages/cli/api/build/kit/kit.mjsindex 93ffc22426..3be2e2d673 100644--- a/packages/cli/api/build/kit/kit.mjs+++ b/packages/cli/api/build/kit/kit.mjs@@ -32,7 +32,7 @@ import {findCoreDir} from '../../../foundation/fs/paths.mjs';import {AstryxError} from '../../error.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';import {getResultCoverage} from '../../search/coverage.mjs';-import {loadComponents, loadPageTemplates, loadWeights} from '../_adapter.mjs';+import {loadComponents, loadPageTemplates, loadWeights, templateSetupNotes} from '../_adapter.mjs';import {asksForNewPage,ideaKind,@@ -393,6 +393,17 @@ export async function buildKit(query, options = {}) {}),};+ // Analyze what the start template needs that the project lacks (external+ // packages, StyleX compiler). Only the start — alternatives are suggestions,+ // not commitments, so reporting their needs would be noise.+ if (start) {+ const startTemplate = catalog.find(t => t.name === start.name);+ if (startTemplate) {+ const notes = templateSetupNotes(startTemplate, cwd);+ if (notes.length > 0) start.notes = notes;+ }+ }+// What to try when the kit comes back thin. Keyword search over a design// system misses in a predictable way — the reader's words and the package's// often do not overlap — so name the two commands that browse rather thandiff --git a/packages/cli/api/template/copy/copy.mjs b/packages/cli/api/template/copy/copy.mjsindex a21990247d..c047a3041f 100644--- a/packages/cli/api/template/copy/copy.mjs+++ b/packages/cli/api/template/copy/copy.mjs@@ -19,6 +19,7 @@ import {import {AstryxError, writeFailed} from '../../error.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';import {pkgOf, replaceDemoMedia} from '../../../foundation/discovery/template-adapter.mjs';+import {analyzeTemplateNeeds} from '../../../foundation/discovery/template-needs.mjs';/*** Scaffold an already-resolved template to `targetPath` (relative to `cwd`) and@@ -93,6 +94,14 @@ export function templateCopy(match, {targetPath, cwd, overwrite = false}) {throw writeFailed(outputFilePath, cwd, err);}+ // Analyze what the template needs that the project lacks: external packages+ // and the StyleX compiler. Derived from the source's own imports.+ const {notes, missingPackages, installCommand} = analyzeTemplateNeeds(+ outputSource,+ cwd,+ );+ const missing = missingPackages;+const relOutput = path.relative(cwd, outputDir) || '.';return {type: 'template.copy',@@ -103,6 +112,9 @@ export function templateCopy(match, {targetPath, cwd, overwrite = false}) {fileName: outputFileName,filesCopied: 1,demoMediaReplaced,+ notes,+ missingPackages: missing,+ installCommand,},};}diff --git a/packages/cli/api/template/template.doc.mjs b/packages/cli/api/template/template.doc.mjsindex 923e3fc539..ccd06aaf44 100644--- a/packages/cli/api/template/template.doc.mjs+++ b/packages/cli/api/template/template.doc.mjs@@ -124,7 +124,7 @@ export const doc = {{type: 'template.copy',description:- 'A receipt after scaffolding the template into the project: the template id, output directory, written file name, file count, and `demoMediaReplaced` — how many Astryx demo media references (images, posters, videos) in the written file were replaced with placeholders for you to swap for your own media.',+ 'A receipt after scaffolding the template into the project: the 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).',},{type: 'template.cdn',diff --git a/packages/cli/api/template/template.type.mjs b/packages/cli/api/template/template.type.mjsindex 8f0d1973b2..a217cb20d1 100644--- a/packages/cli/api/template/template.type.mjs+++ b/packages/cli/api/template/template.type.mjs@@ -80,6 +80,9 @@* @property {string} data.fileName* @property {number} data.filesCopied* @property {number} data.demoMediaReplaced Astryx demo media references (images, posters, videos) replaced in the written file: images with a neutral placeholder, videos with an empty source. Swap in your own media at those points; no media is installed. 0 when the template carried none.+ * @property {string[]} data.notes Setup notes: what the template needs that the project lacks (missing packages, missing StyleX compiler). Each note is one actionable line. Empty when the template needs nothing the project lacks.+ * @property {string[]} data.missingPackages External package names the template imports that are not in the project's dependencies. Empty when none are missing.+ * @property {string | null} data.installCommand A ready-to-run install command for the missing packages, using the project's package manager and the CLI workspace's version ranges. Null when no packages are missing.*//**diff --git a/packages/cli/assets/docs/styling-overview.doc.mjs b/packages/cli/assets/docs/styling-overview.doc.mjsindex 0be558b182..7175ba8192 100644--- a/packages/cli/assets/docs/styling-overview.doc.mjs+++ b/packages/cli/assets/docs/styling-overview.doc.mjs@@ -122,7 +122,7 @@ export const docs = {content: [{type: 'prose',- text: 'Only needed when you swizzle a component (`astryx swizzle <Component>`) or write your own StyleX. The plain path already supports `xstyle` overrides \u2014 this path is for editing component internals.',+ text: 'Only needed when you swizzle a component (`astryx swizzle <Component>`) or write your own StyleX. The plain path already supports `xstyle` overrides \u2014 this path is for editing component internals. Some built-in page templates also use StyleX for layout; if you scaffold one and see "Unexpected stylex.create call at runtime", add the compiler plugin for your bundler below.',},{type: 'code',diff --git a/packages/cli/clients/cli/commands/build.mjs b/packages/cli/clients/cli/commands/build.mjsindex 4321c12afa..b0492b3212 100644--- a/packages/cli/clients/cli/commands/build.mjs+++ b/packages/cli/clients/cli/commands/build.mjs@@ -226,6 +226,7 @@ export function registerBuild(program) {}: brief(['name', 'package', 'description', 'command']),),+ ...(start.notes ?? []).map(note => text(note)),);if (start.alternatives.length) {out.push(diff --git a/packages/cli/clients/cli/commands/template.mjs b/packages/cli/clients/cli/commands/template.mjsindex a29ba1b1fc..4b0cdbd925 100644--- a/packages/cli/clients/cli/commands/template.mjs+++ b/packages/cli/clients/cli/commands/template.mjs@@ -220,7 +220,7 @@ export function registerTemplate(program) {}case 'template.copy': {- const {outputDir, fileName, demoMediaReplaced} = result.data;+ const {outputDir, fileName, demoMediaReplaced, notes} = result.data;const file = `${outputDir}/${fileName}`;emit(text(`Copied template to ${file}`),@@ -230,6 +230,7 @@ export function registerTemplate(program) {`Replaced ${demoMediaReplaced} Astryx demo media reference${demoMediaReplaced === 1 ? '' : 's'} in ${file}: ` +'images now show a neutral placeholder and videos have an empty source. Supply your own media there.',),+ ...notes.map(/** @param {string} note */ note => text(note)),);break;}diff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjsindex c1c91f50ef..bfa87dfb3a 100644--- a/packages/cli/foundation/agent-docs/agent-docs.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs@@ -335,6 +335,9 @@ export function detectStylingSystem(targetDir) {// Key off a StyleX *compiler* plugin — the runtime alone won't render.const stylexCompilers = ['@stylexjs/babel-plugin',+ '@stylexjs/rollup-plugin',+ '@stylexjs/webpack-plugin',+ '@stylexjs/nextjs-plugin','vite-plugin-stylex','unplugin-stylex','@stylexswc/unplugin',@@ -452,7 +455,7 @@ export function generateCompressedIndex(} else if (stylingSystem === 'tailwind') {lines.push('- Style with component props first, then Tailwind utilities backed by tokens. No raw hex/px.');} else {- lines.push("- Style with component props first, then tokens (var(--color-*|--spacing-*|--radius-*)). No raw hex/px. No StyleX/Tailwind compiler here — don't use xstyle/utility classes.");+ lines.push("- Style with component props first, then tokens (var(--color-*|--spacing-*|--radius-*)). No raw hex/px. No StyleX/Tailwind compiler here — don't use xstyle/utility classes directly. Some templates use StyleX and need a compiler plugin; see `astryx docs styling-overview`.");}lines.push('- Palettes and custom colors go through the theme, never :root overrides. See `astryx docs theme`.');// Self-check — post-generation pass. Validated via vibe tests (internal/vibe-tests/diff --git a/packages/cli/foundation/agent-docs/agent-docs.test.mjs b/packages/cli/foundation/agent-docs/agent-docs.test.mjsindex 2b87ba05eb..ad448eabf9 100644--- a/packages/cli/foundation/agent-docs/agent-docs.test.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.test.mjs@@ -89,6 +89,9 @@ describe('generateCompressedIndex', () => {expect(result).not.toMatch(/xstyle prop/);// Must warn that no compiler is present.expect(result).toMatch(/No StyleX\/Tailwind compiler/);+ // Must acknowledge that some templates use StyleX and point at the doc.+ expect(result).toMatch(/templates.*StyleX/i);+ expect(result).toMatch(/styling-overview/);});it('recommends xstyle when StyleX is configured', () => {@@ -371,6 +374,21 @@ describe('detectStylingSystem', () => {expect(detectStylingSystem(tmpDir)).toBe('stylex');});+ it('detects the official Rollup/Vite plugin', () => {+ writePkg({'@stylexjs/rollup-plugin': '0.10.0'});+ expect(detectStylingSystem(tmpDir)).toBe('stylex');+ });++ it('detects the official Webpack plugin', () => {+ writePkg({'@stylexjs/webpack-plugin': '0.10.0'});+ expect(detectStylingSystem(tmpDir)).toBe('stylex');+ });++ it('detects the official Next.js plugin', () => {+ writePkg({'@stylexjs/nextjs-plugin': '0.10.0'});+ expect(detectStylingSystem(tmpDir)).toBe('stylex');+ });+it('detects tailwind when tailwindcss is present', () => {writePkg({tailwindcss: '4.0.0'});expect(detectStylingSystem(tmpDir)).toBe('tailwind');diff --git a/packages/cli/foundation/discovery/template-needs.mjs b/packages/cli/foundation/discovery/template-needs.mjsnew file mode 100644index 0000000000..0b7adb3e7e--- /dev/null+++ b/packages/cli/foundation/discovery/template-needs.mjs@@ -0,0 +1,156 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Analyze what a scaffolded template needs that the target project lacks.+ *+ * Derives needs from the template's own source — its bare import specifiers —+ * rather than from a hand-maintained list. Every import that is not an Astryx+ * package, react/react-dom, or @stylexjs/stylex is external; the source is the+ * only authority on what a template uses.+ *+ * Shared between `api/template/copy` (the scaffold receipt) and+ * `api/build/kit` (the start recommendation).+ *+ * @position packages/cli/foundation/discovery — template discovery helpers;+ * consumed by the template and build API leaves.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import module from 'node:module';+import {CLI_ROOT} from '../fs/paths.mjs';+import {detectStylingSystem} from '../agent-docs/agent-docs.mjs';++// ── Known packages that a template may import without the user installing them.+// react and react-dom are the framework; @astryxdesign/* is the design system+// the CLI already told the user to install; @stylexjs/stylex is a peer of Core.+const FRAMEWORK_PREFIXES = ['react', 'react-dom'];+const DESIGN_SYSTEM_SCOPE = '@astryxdesign/';+const STYLEX_RUNTIME = '@stylexjs/stylex';++// Node builtins: anything with a `node:` prefix or in builtinModules.+const NODE_BUILTINS = new Set(module.builtinModules);++/**+ * Extract bare (non-relative) package names from ES import statements.+ *+ * @param {string} source Template source code+ * @returns {Set<string>} Unique package names (scoped packages normalized to+ * `@scope/name`, unscoped to the first path segment).+ */+export function extractImportedPackages(source) {+ // Matches `import … from '<specifier>'`, `import '<specifier>'`, and+ // dynamic `import('<specifier>')`. Only bare specifiers (not starting with+ // `.` or `/`).+ const re = /(?:from\s+|import\s*\(?)['"]((?:@[^/'"]+\/)?[^./'"@][^'"]*)['"]/g;+ /** @type {Set<string>} */+ const pkgs = new Set();+ let m;+ while ((m = re.exec(source)) !== null) {+ const spec = m[1];+ // Skip Node builtins: `node:fs`, `fs`, `fs/promises`, etc.+ if (spec.startsWith('node:')) continue;+ const name = spec.startsWith('@')+ ? spec.split('/').slice(0, 2).join('/')+ : spec.split('/')[0];+ if (NODE_BUILTINS.has(name)) continue;+ pkgs.add(name);+ }+ return pkgs;+}++/**+ * Detect which package manager the project uses, from its lockfile.+ * @param {string} cwd Project root+ * @returns {'pnpm add' | 'yarn add' | 'bun add' | 'npm install'}+ */+function detectInstallCommand(cwd) {+ if (fs.existsSync(path.join(cwd, 'pnpm-lock.yaml'))) return 'pnpm add';+ if (fs.existsSync(path.join(cwd, 'yarn.lock'))) return 'yarn add';+ if (fs.existsSync(path.join(cwd, 'bun.lockb'))) return 'bun add';+ return 'npm install';+}++/**+ * Read the CLI package's own devDependencies for authoritative version ranges+ * of external packages the templates use.+ * @returns {Record<string, string>}+ */+function cliPackageRanges() {+ try {+ const pkgPath = path.join(CLI_ROOT, 'package.json');+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));+ return {...pkg.devDependencies};+ } catch {+ return {};+ }+}++/**+ * Analyze what a template source needs that the target project lacks.+ *+ * Returns a `notes` array of human-readable setup notes, a structured+ * `missingPackages` list, and an `installCommand` string ready to print.+ * Each note is one actionable line.+ *+ * @param {string} source Template source code+ * @param {string} cwd Target project directory+ * @returns {{+ * notes: string[],+ * missingPackages: string[],+ * installCommand: string | null,+ * }}+ */+export function analyzeTemplateNeeds(source, cwd) {+ const imported = extractImportedPackages(source);++ // ── External packages (not framework / design system / stylex runtime) ──+ const external = [...imported].filter(+ name =>+ !FRAMEWORK_PREFIXES.includes(name) &&+ !name.startsWith(DESIGN_SYSTEM_SCOPE) &&+ name !== STYLEX_RUNTIME,+ );++ // Read the project's installed packages.+ /** @type {Record<string, string>} */+ let projectDeps = {};+ try {+ const pkg = JSON.parse(+ fs.readFileSync(path.join(cwd, 'package.json'), 'utf-8'),+ );+ projectDeps = {...pkg.dependencies, ...pkg.devDependencies};+ } catch {+ // No package.json or unreadable — treat everything as missing.+ }++ const missing = external.filter(p => !(p in projectDeps));++ // Build the install command with version ranges from the CLI workspace.+ let installCommand = null;+ if (missing.length > 0) {+ const pm = detectInstallCommand(cwd);+ const ranges = cliPackageRanges();+ const specs = missing.map(p => (ranges[p] ? `${p}@"${ranges[p]}"` : p));+ installCommand = `${pm} ${specs.join(' ')}`;+ }++ // ── StyleX compiler ────────────────────────────────────────────────────+ const usesStylex = imported.has(STYLEX_RUNTIME);+ const stylexCompilerNeeded =+ usesStylex && detectStylingSystem(cwd) !== 'stylex';++ // ── Notes ──────────────────────────────────────────────────────────────+ /** @type {string[]} */+ const notes = [];+ if (missing.length > 0) {+ notes.push(`Install missing dependencies: ${installCommand}`);+ }+ if (stylexCompilerNeeded) {+ notes.push(+ 'This template uses StyleX. Your project needs a StyleX compiler plugin \u2014 see `astryx docs styling-overview` for setup steps.',+ );+ }++ return {notes, missingPackages: missing, installCommand};+}diff --git a/packages/cli/foundation/discovery/template-needs.test.mjs b/packages/cli/foundation/discovery/template-needs.test.mjsnew file mode 100644index 0000000000..e04c1b52df--- /dev/null+++ b/packages/cli/foundation/discovery/template-needs.test.mjs@@ -0,0 +1,203 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Tests for template-needs analysis: external package detection, StyleX+ * compiler warning, and install command generation.+ */++import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {+ extractImportedPackages,+ analyzeTemplateNeeds,+} from './template-needs.mjs';++// ── extractImportedPackages ─────────────────────────────────────────────────++describe('extractImportedPackages', () => {+ it('extracts bare package names from static imports', () => {+ const source = `+ import {Button} from '@astryxdesign/core';+ import {ArrowIcon} from '@heroicons/react/24/outline';+ import * as stylex from '@stylexjs/stylex';+ import {useState} from 'react';+ import recharts from 'recharts';+ `;+ const pkgs = extractImportedPackages(source);+ expect(pkgs).toEqual(+ new Set([+ '@astryxdesign/core',+ '@heroicons/react',+ '@stylexjs/stylex',+ 'react',+ 'recharts',+ ]),+ );+ });++ it('ignores relative and absolute imports', () => {+ const source = `+ import {foo} from './bar';+ import {baz} from '../qux';+ import {thing} from '/absolute/path';+ `;+ expect(extractImportedPackages(source).size).toBe(0);+ });++ it('ignores Node builtins with the node: prefix', () => {+ const source = `+ import * as fs from 'node:fs';+ import * as path from 'node:path';+ import {createRequire} from 'node:module';+ `;+ expect(extractImportedPackages(source).size).toBe(0);+ });++ it('ignores bare Node builtins and their subpaths', () => {+ const source = `+ import * as fs from 'fs';+ import {join} from 'path';+ import {createReadStream} from 'fs/promises';+ `;+ expect(extractImportedPackages(source).size).toBe(0);+ });++ it('handles type imports', () => {+ const source = `import type {Props} from 'some-package';`;+ expect(extractImportedPackages(source)).toEqual(new Set(['some-package']));+ });++ it('deduplicates multiple imports from the same package', () => {+ const source = `+ import {A} from '@heroicons/react/24/outline';+ import {B} from '@heroicons/react/24/solid';+ `;+ expect(extractImportedPackages(source)).toEqual(+ new Set(['@heroicons/react']),+ );+ });++ it('maps subpath imports to the package root', () => {+ const source = `+ import debounce from 'lodash/debounce';+ import {Chart} from 'recharts/es6';+ `;+ const pkgs = extractImportedPackages(source);+ expect(pkgs).toEqual(new Set(['lodash', 'recharts']));+ });+});++// ── analyzeTemplateNeeds ────────────────────────────────────────────────────++describe('analyzeTemplateNeeds', () => {+ let dir;+ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tmpl-needs-'));+ });+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));++ it('reports missing external packages with an install command', () => {+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({dependencies: {'react': '^19.0.0', '@astryxdesign/core': '^0.6.0'}}),+ );+ const source = `+ import {Button} from '@astryxdesign/core';+ import {ArrowIcon} from '@heroicons/react/24/outline';+ import {useState} from 'react';+ `;+ const result = analyzeTemplateNeeds(source, dir);+ expect(result.missingPackages).toEqual(['@heroicons/react']);+ expect(result.installCommand).toMatch(/npm install @heroicons\/react/);+ expect(result.notes.length).toBeGreaterThanOrEqual(1);+ expect(result.notes[0]).toMatch(/Install missing dependencies/);+ });++ it('reports nothing when all packages are installed', () => {+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({+ dependencies: {+ 'react': '^19.0.0',+ '@astryxdesign/core': '^0.6.0',+ '@heroicons/react': '^2.2.0',+ },+ }),+ );+ const source = `+ import {Button} from '@astryxdesign/core';+ import {ArrowIcon} from '@heroicons/react/24/outline';+ `;+ const result = analyzeTemplateNeeds(source, dir);+ expect(result.missingPackages).toEqual([]);+ expect(result.installCommand).toBeNull();+ expect(result.notes).toEqual([]);+ });++ it('warns about StyleX compiler when template uses it and project lacks one', () => {+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({dependencies: {'@stylexjs/stylex': '^0.10.0'}}),+ );+ const source = `import * as stylex from '@stylexjs/stylex';`;+ const result = analyzeTemplateNeeds(source, dir);+ expect(result.notes).toEqual(+ expect.arrayContaining([+ expect.stringContaining('StyleX'),+ expect.stringContaining('styling-overview'),+ ]),+ );+ });++ it('does NOT warn about StyleX when the project has a compiler', () => {+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({+ devDependencies: {+ '@stylexjs/stylex': '^0.10.0',+ '@stylexjs/rollup-plugin': '^0.10.0',+ },+ }),+ );+ const source = `import * as stylex from '@stylexjs/stylex';`;+ const result = analyzeTemplateNeeds(source, dir);+ const stylexNotes = result.notes.filter(n => n.includes('StyleX'));+ expect(stylexNotes).toEqual([]);+ });++ it('detects pnpm from lockfile', () => {+ fs.writeFileSync(path.join(dir, 'package.json'), '{}');+ fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');+ const source = `import {Chart} from 'recharts';`;+ const result = analyzeTemplateNeeds(source, dir);+ expect(result.installCommand).toMatch(/^pnpm add /);+ });++ it('detects yarn from lockfile', () => {+ fs.writeFileSync(path.join(dir, 'package.json'), '{}');+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');+ const source = `import {Chart} from 'recharts';`;+ const result = analyzeTemplateNeeds(source, dir);+ expect(result.installCommand).toMatch(/^yarn add /);+ });++ it('excludes @stylexjs/stylex from missing packages (it is a Core peer)', () => {+ fs.writeFileSync(path.join(dir, 'package.json'), '{}');+ const source = `import * as stylex from '@stylexjs/stylex';`;+ const result = analyzeTemplateNeeds(source, dir);+ expect(result.missingPackages).not.toContain('@stylexjs/stylex');+ });++ it('handles a template with no external imports', () => {+ fs.writeFileSync(path.join(dir, 'package.json'), '{}');+ const source = `+ import {useState} from 'react';+ import {Button} from '@astryxdesign/core';+ `;+ const result = analyzeTemplateNeeds(source, dir);+ expect(result.notes).toEqual([]);+ expect(result.missingPackages).toEqual([]);+ });+});diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex 76fedaa06e..34e99d2a1d 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -194,7 +194,7 @@ export const doc = {{value: 'template.copy',description:- 'A scaffold receipt: template id, output directory, written file name, file count, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). The envelope\'s package names the npm package that owns the template.',+ '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). The envelope\'s package names the npm package that owns the template.',},{