An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): experimental icon sets — icon definitions, `astryx experimental icon`, templates that use the installed set (#7759)
Joey4fc0c4a484e4
diff --git a/.changeset/cli-doc-stability-field.md b/.changeset/cli-doc-stability-field.mdnew file mode 100644index 0000000000..f77fa482c2--- /dev/null+++ b/.changeset/cli-doc-stability-field.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[feat] Docs can mark an experimental surface: every doc type except `ThemeDoc` and `IconSetDoc`, and every schema field and enum value, accepts `stability: 'experimental'`. A marked command shows `[experimental]` in help, a marked schema field or enum value is left out of its stable table so its feature's own docs describe it, and `astryx search` leaves out a marked doc, which is read on its own route. For the package being authored, `doctor integration validate` (and so `integration check`) adds `olderCliNotes`, each `{file, kind, field, message}`: a template or namespace doc that sets `stability`, or a template that declares `icons`, while the package's CLI peer range admits a release before 0.7.4, which drops that descriptor. A note is never an error or a warning and never fails a check, under `--strict` or `--next`; text output prints "Notes for older CLIs". Docs and findings that use none of these read exactly as before.++@josephfarinadiff --git a/.changeset/cli-icon-sets.md b/.changeset/cli-icon-sets.mdnew file mode 100644index 0000000000..297448dac4--- /dev/null+++ b/.changeset/cli-icon-sets.md@@ -0,0 +1,12 @@+---+'@astryxdesign/cli': patch+---++[experimental] Icon sets: an integration can ship an icon set, agents find icons by meaning and get the exact import line, and copied templates use the project's icons. Everything here is experimental and may change or be removed in a patch release; a project that does not set `experimental.iconSet` sees no change in any stable command, apart from: the marked `experimental` group in help and in `astryx manifest` (its command, and its `responseTypes` and `jsonSupported` entries); the marked experimental entries in the `astryx docs cli` listings; and a search for "experimental", which also finds the new stable `stability` field of the field reference. `astryx search` returns no icon and no experimental doc. With a package that ships icon sets installed and no opt-in, the warnings an older CLI gives about the manifest key `experimental` (in `astryx doctor` and `astryx doctor integration validate <package>`, and the one-line nudge other commands print to stderr) are gone, and `doctor integration` checks that package's icon sets only in a project that sets `experimental.iconSet`; and `astryx integration check` reports icon-set findings for a package that declares `experimental.iconSets` (below).++- **Commands.** The new `astryx experimental` group holds experimental commands; icon sets are its first. `astryx experimental icon <words>` ranks icons across the installed sets (`icon.search`), `<set>/<id>` reads one icon with every variant's import line (`icon.detail`), and `--list` lists each set with its definition coverage (`icon.list`). Authoring: `experimental icon new-set <name>` starts a set (`--from <module>` wraps every icon a library exports, `--exclude` drops exports that are not icons), `experimental icon new-definition <name>` adds a set's own icon definition, `experimental icon add <Export> --from <module>` verifies an export and lists the definitions that fit it or adds and maps it (`--variant <name>` adds it as a variant the set declares, a named look such as solid; size comes from CSS), `experimental icon map <definition> <icon>` edits one map entry, and `experimental icon use <set>` picks the project's set. The API gains `icon`, `iconAdd`, `iconMap`, `iconUse`, `iconNewSet`, and `iconNewDefinition`, all marked `@experimental`.+- **Configuration.** The project's set is `experimental.iconSet` in astryx.config; an integration declares its sets folder as `experimental.iconSets` in its manifest. Each set has a typed `<name>.doc.mjs` (`IconSetDoc`), a `<name>.icons.json` data file, and an optional `definitions/` folder; `@astryxdesign/cli/authoring` exports `IconSetDoc`, `IconSetData`, `IconDefinitionDoc`, and their parsers. An older CLI warns that `experimental` is a manifest key it does not know, and a CLI before 0.7.4 refuses an astryx.config that sets `experimental.iconSet` ("Unrecognized key"), so commands that load the project configuration, such as `doctor` and `discover`, fail in that project; `astryx experimental icon use` says so in its receipt (`warning`) when the project's `@astryxdesign/cli` range admits such a release.+- **Where icon sets show up.** Icon lookup by meaning is only `astryx experimental icon`: `astryx search` never returns icons or experimental docs, with or without a set. A project that sets `experimental.iconSet` also gets `astryx template` replacing each icon a template declares in its new `icons` field (a named import by the name it imports, a default import by its local name) with that set's icon, every key reported as mapped or kept in an `icons` receipt field, `astryx discover` reading `icon-set` as a kind (`--type icon-set`, and catalog entries of that kind), and an `icon-sets` check in `astryx doctor`. Without it, none of these change: templates are copied as they are, `--type icon-set` is an unknown type and catalog `icon-set` entries are ignored, and Doctor reports nothing about icon sets, even an invalid one. `astryx integration check` reports icon-set findings for a package that declares `experimental.iconSets`, and lists, in the validate result's additive `iconSets` field, the optional Astryx definitions each set leaves unmapped, with the icons that fit, and what it cannot judge (`unchecked`: an icon whose module is an `exports` target not built yet, an icon or adapter export it cannot prove either way, such as one behind a re-export it cannot follow or bound to a default import, and a theme map or entry it cannot read; only an export it proves absent fails), printed under "Not checked"; neither list is ever counted or fails a check, even under `--strict` or `--next`. It also notes each template `icons` key the template's source never imports (`template_icon_not_imported`), which fails nothing, under `--next` too.+- **Docs.** The guide and every icon definition live under `astryx docs cli/experimental`, and every icon-set doc is marked `stability: 'experimental'`. The experimental icon-definitions namespace adopts definition docs from every package (`source.packages: 'all'`, read only on a CLI namespace marked experimental).++@josephfarinadiff --git a/apps/docsite/src/__tests__/route-resolution.test.ts b/apps/docsite/src/__tests__/route-resolution.test.tsindex 7046fe6d80..88c8c0eb92 100644--- a/apps/docsite/src/__tests__/route-resolution.test.ts+++ b/apps/docsite/src/__tests__/route-resolution.test.ts@@ -102,6 +102,8 @@ describe('route resolution', () => {'authoring','browser-support','cli-component-lookups',+ 'cli-experimental-icon-set-files',+ 'cli-experimental-icon-sets','cli-host-entry','global','internationalization',diff --git a/docs/architecture/cli-surface.md b/docs/architecture/cli-surface.mdindex 1d5125526a..0cbb8abaa7 100644--- a/docs/architecture/cli-surface.md+++ b/docs/architecture/cli-surface.md@@ -226,7 +226,10 @@ validate` MUST warn on a PascalCase `.tsx` at the top of the components rootMAY join it only in a minor release that names the addition, and a changethat can fail a build that passes, including a stricter rule for an existingfinding, MAY ship only in a minor release that names it. Before that- release, its checks and failure codes MAY change in any release. A name a+ release, its checks and failure codes MAY change in any release. A failure+ code that fires only for a package declaring an experimental manifest key+ (`spec:AST-017/FR27`, `spec:AST-084`) MAY join in a patch release, since a+ package without the key never sees it. A name apatch release adds to Core or the CLI (a component, template, or topic) MAYraise a conflict with a package's own name. Each `doctor integration`subcommand MUST keep its exit codes, and its JSON MAY change only bydiff --git a/docs/specs/AST-046-docs-tree/spec.md b/docs/specs/AST-046-docs-tree/spec.mdindex cad1f4affe..9298cf07f0 100644--- a/docs/specs/AST-046-docs-tree/spec.md+++ b/docs/specs/AST-046-docs-tree/spec.md@@ -86,6 +86,11 @@ and references from other packages are an open question (OQ2).the doc's kind. A placement that fails MUST withdraw the doc with adiagnostic; it MUST NOT fall back to adoption. A doc that two rules adopt MUSTbe withdrawn with a diagnostic that names both namespaces.+ The one exception is a CLI namespace marked `stability: 'experimental'`,+ which MAY adopt a doc group from every package with `source.packages: 'all'`+ (`spec:AST-084/DEC-7`); it applies only to the experimental icon sets behind+ the project's opt-in, and every stable namespace keeps one adoption rule per+ package with unchanged output.- **FR3 — Namespaces never list or scan their children.** A namespace docdeclares its slots and its adoption rules. It MUST NOT enumerate itschildren, and the compiler MUST NOT infer a parent from a folder. A childdiff --git a/docs/specs/AST-051-discover-integration-manager/spec.md b/docs/specs/AST-051-discover-integration-manager/spec.mdindex c02e2a0e65..1f9d903c8f 100644--- a/docs/specs/AST-051-discover-integration-manager/spec.md+++ b/docs/specs/AST-051-discover-integration-manager/spec.md@@ -96,6 +96,9 @@ discover sources follow it except where this record says otherwise.`ERR_INVALID_OPTION`. `--limit <n>` caps search results (default 20) and theresponse reports the total when it cut the list. An unknown kind or a limitthat is not a positive integer MUST fail with `ERR_INVALID_OPTION`.+ In a project that sets `experimental.iconSet`, `icon-set` is an additional+ kind (`spec:AST-084/DEC-8`); without it discover keeps the six kinds and+ refuses `--type icon-set` with `ERR_INVALID_OPTION`.- **FR6 — Sources are functions a project, an integration, or a doorprovides.** A source is an async function that receives`{signal, package?, version?}` and resolves to a catalog; `package` asks for@@ -121,6 +124,9 @@ source, packages}`. `source` has `name`, `generatedAt`, and `complete`. EachMUST refuse any other `schemaVersion`, and MUST show versions newest first bypublish time whatever order the source returned them in. When two sourceslist the same package, the earlier source's entry is used.+ In a project that sets `experimental.iconSet`, an `icon-set` contribution+ MAY also carry `iconCount` and `definitions` (`spec:AST-084/DEC-8`); without+ it discover ignores `icon-set` entries and those fields as unknown.- **FR8 — A saved copy covers an unreachable source.** After a source answers,discover MUST save that answer, per source and per request, in the per-usercache directory of the platform, never in the project. When the source laterdiff --git a/docs/specs/AST-084-icon-sets/spec.md b/docs/specs/AST-084-icon-sets/spec.mdnew file mode 100644index 0000000000..aed4b811b7--- /dev/null+++ b/docs/specs/AST-084-icon-sets/spec.md@@ -0,0 +1,465 @@+---+schema_version: 4+template_version: 2+kind: system-spec+id: spec:AST-084+authority: current+archive_reason: null+superseded_by: null+approved_by: josephfarina+approved_at: 2026-10-20+phase: accepted+owners: [josephfarina]+affects_architecture: [architecture:cli-surface]+affects_families: []+affects_contributing: [contributing:cli-conventions]+affects_consumer_docs: [cli/experimental]+---++# Icon set integrations system spec++<!-- Describe the system, not the project: present tense, what it does. No proposals, history, pull requests, or research in the record; see docs/contributing/spec-writing.md and report its rubric results in the pull request. -->++## Intent++An icon set is an experimental integration item: icon components a package+exports, plus one data file that says which icon draws each icon definition.+Astryx ships icon definitions, one typed doc file per thing an icon can stand+for (`close`, `delete`, `rocket`). A set registers its icons against them, and+may add definitions of its own. With a set installed:++- an agent or engineer finds an icon by meaning with+ `astryx experimental icon <words>` and gets the exact import line;+- a template copied into a project that opts in with `experimental.iconSet`+ uses the set's icons for the definitions the template declares; and+- a theme points the shared semantic icon names at the set's artwork.++The CLI encodes no icon library: the author, or the author's agent, picks each+icon, and the CLI verifies it, writes the files, and checks the set.++## Non-goals++- Choose a variant at render time; that belongs to the Icon component+ contract.+- Declare sizes in the data file: icon size is CSS, and the artwork scales+ with its box.+- Grow the shared `IconName` set: the built-in definitions are exactly its+ values.+- Make each icon its own discoverable item: the set is the item.+- Edit, redraw, or bundle artwork: every icon is a component the package+ exports.+- Equivalent internal implementations remain valid when they satisfy this+ contract.++## Requirements++### Experimental placement++- **FR0 — Every icon-set surface is experimental and isolated.** Under+ `spec:AST-017/FR21`–FR27:+ - the commands are `astryx experimental icon` and its subcommands, under the+ `experimental` command group; no stable command gains an icon-set+ subcommand or option value, and the one icon-set kind on a stable command+ is discover's `icon-set`, read only with the opt-in (FR17, DEC-8);+ - `astryx experimental` is a top-level command group admitted here under+ `spec:AST-042/FR4`. It answers one question: where does a CLI control live+ while it may still change in a patch release? No existing command can hold+ such controls, because `spec:AST-017/FR27` keeps experimental controls off+ every stable command and its output; extending `help` or any stable family+ would change that command. Its one job is to group experimental+ commands. It performs no operation itself, so `spec:AST-042/FR1` names no+ function for it; each command under it names its own. It has no result of+ its own: each command under it returns data, a typed JSON response that+ agents and tools act on, while the reasons behind experimental features+ are prose in their docs under `cli/experimental`;+ - configuration is `experimental.iconSet` in `astryx.config`, the project's+ opt-in, and `experimental.iconSets` in the integration manifest;+ - the guides and schemas live under `cli/experimental` (the guide, the+ `icon-set-files` reference of the descriptor, data file, and definition+ schemas, which the stable field reference never lists, and the+ `icon-definitions` namespace); the reference docs of the experimental+ commands and API functions live with every other command and function+ reference (`cli/api/functions/...` and the command docs), listed only in+ the `astryx docs cli` listing, the same exception this requirement makes+ for help; every one of these docs carries `stability: 'experimental'`, and+ API functions and authoring types carry `@experimental`; and+ - every change ships as an `[experimental]` patch Changeset. Promotion to+ stable needs the owner's approval and a `[feat]` Changeset+ (`spec:AST-017/FR23`).++ Without `experimental.iconSet`, help (apart from the marked `experimental`+ group line), `astryx manifest` (apart from that group: its command, and its+ `responseTypes` and `jsonSupported` entries), the `astryx docs cli`+ listings (apart from the marked `experimental` namespace and the+ experimental command and function references), `astryx template`, `astryx discover`, and Doctor,+ its `doctor integration` subcommands for an installed package included,+ give the output they give without this feature, whatever sets are+ installed, and so do `integration check` and `verify` for a package that+ declares no `experimental.iconSets`, with two differences, both because a+ CLI without this feature does not know the manifest key `experimental`.+ With a package that declares `experimental.iconSets` installed, that CLI+ warns about the key in Doctor's `integration-issues` check and in+ `doctor integration validate <package>`, and in text mode every command+ that prints the integration-issue nudge (`component`,+ `discover`, `search`, `template`, `theme list`, `theme add`, `theme remove`,+ `theme use`, `theme eject`, and `upgrade`) prints "Warning: <package> has 1+ integration issue(s)" to stderr; this CLI does neither. Discover refuses+ `--type icon-set` and ignores `icon-set` catalog items and their fields+ exactly as it does any unknown kind or field. With the opt-in, `icon-set`+ is a discover kind (FR17). `astryx search` never reads icon sets, with or+ without the opt-in, and returns no experimental doc. No stable doc names an+ experimental route, an icon set, or an icon definition, and a stable docs+ node's previous and next links skip experimental neighbors; the one stable+ addition is the field reference's `stability` field (FR18), which a search+ for "experimental" finds.++### What a set declares++- **FR1 — One manifest root.** The manifest MAY set `experimental.iconSets`,+ a relative directory. Each lower-kebab directory under it is one set, named+ by the directory; the manifest never lists sets or icons+ (`spec:AST-039/FR11`).+- **FR2 — One typed descriptor.** Each set directory holds `<name>.doc.mjs`, a+ default-exported `IconSetDoc` (`type: 'icon-set'`, `name` equal to the+ directory, `displayName`, `description`, `maintained`, and `license`, an+ SPDX expression for the artwork).+- **FR3 — One data file, read by every icon surface.** Each set directory+ holds `<name>.icons.json` (`schemaVersion: 1`):+ - `module`: the import specifier every export is read from, the package's+ name or one of its `exports` subpaths;+ - `icons`: each with a unique lower-kebab `id`, an `export`, at least one+ search word in `words`, optional `variants` (each a declared variant and+ the export that draws it, at most one export per variant),+ and optional `matches`, reviewed equivalents in other installed sets with+ a confidence of `exact`, `strong`, or `likely`;+ - `map`: icon definition name to icon `id`; one icon MAY draw several+ definitions;+ - optional `variants`, the lower-kebab variant names the set declares, and+ `default.variant`, the one each icon's own `export` draws. A variant is a+ named look the set supplies (for example outline or solid); size comes+ from CSS;+ - optional `source` (the upstream library and version), `generated`+ (FR13), `adapter` (FR13), and `themeMap` (FR12).++ A data file that fails this shape, repeats an `id`, maps a name that is+ neither an Astryx definition nor one of the set's own, maps to a missing+ icon, or names a variant the set does not declare is invalid, and the set+ is withdrawn from every surface.++- **FR4 — Icon definitions are typed doc files in folders.** An+ `IconDefinitionDoc` (`type: 'icon-definition'`) has a camelCase `name`, a+ one-sentence `description`, `words`, and `builtIn: true` exactly for an+ `IconName`. Astryx ships one file per definition in the CLI's definitions+ folder; a set adds its own in `<set>/definitions/<name>.doc.mjs`. The doc+ compiler reads every file in a folder; there is no index. A set's own+ definition needs no change to Astryx and maps only within that set;+ proposing it for every set is a pull request that copies its file into the+ CLI's folder. When names collide, Astryx's wins. The experimental+ `icon-definitions` namespace lists Astryx's definitions and, in a project+ that sets `experimental.iconSet`, each installed set's own.+- **FR5 — The directory is the boundary.** Discovery reads the descriptor,+ data file, and definitions statically, never runs the icon module, and+ rejects a path that escapes the package (`spec:AST-039/FR5`, FR6).++### Finding and choosing++- **FR6 — `astryx experimental icon <words>` ranks icons by meaning.** It+ answers `icon.search`, each match with its `set`, `id`, `package`, `module`,+ `export`, `import` line, `words`, `definitions`, `variants`, `reason`, and+ `score`: 100 for a definition the set maps to the icon, 90 or 80 for an+ exact name or meaning match (the reading most of the searched icons use+ leads), 60 when the query starts one of its words, 40 for a partial match.+ An icon also answers to the name and words of every definition it draws.+ Equal scores are ordered by set order (FR8), so the project's set leads;+ then, within a set, an exact name match on the whole id before one on an id+ part and an exact meaning match by its tag position; then by `id`. `--set`+ keeps one set and `--limit` caps the list.+- **FR7 — One icon and the installed sets.** `<set>/<id>` answers+ `icon.detail` with every variant's import line; `--list` answers `icon.list`+ with each set's coverage of built-in, Astryx, and its own definitions, the+ project's icon-set state, and each withdrawn set. A set is named by its name+ or `<package>/<set>`; a name two packages ship needs the qualified form.+- **FR8 — The project's set.** `experimental.iconSet` names the project's set+ (`"<set>"` or `"<package>/<set>"`) and opts the project in. Within+ `astryx experimental icon`, a project without it treats its only installed+ set as its set. A name two installed packages ship names no set. Lookups put+ the project's set first, then the integration load order.++### Templates and themes++- **FR9 — Templates declare definitions.** A template or block descriptor+ declares, in `icons`, the definition each imported icon draws (`{TrashIcon:+'delete'}`), keyed by the name a named import reads (`{Trash as TrashIcon}`+ is `Trash`) or by a default import's local name. In a project with a set+ (FR8, opted in), `astryx template` (printed or copied) rewrites each+ declared icon, and each icon another installed set ships, to the project+ set's icon that names it in an `exact` or `strong` match, else the icon its+ `map` names for the definition. Every reference uses the mapped export,+ under an alias when the name is taken; a mapped default import becomes the+ set's named import aliased to its local name. Nothing is guessed from names,+ and a `likely` match is only suggested.+- **FR10 — The template reports every icon.** The result, and the copy+ receipt, gain `icons`: the set state, each icon `mapped` (source, target,+ and the rule) or `kept` (with why, and a `likely` suggestion when one+ exists). With a set, every declared key is mapped or kept: a key bound only+ by a namespace import, a type-only import, a re-export, or an import from an+ Astryx package or the project's set, or by no import at all (`module` null),+ is kept with the reason; a side-effect import binds nothing. An unmapped+ icon keeps its import, and its library stays a needed dependency. Printed+ source keeps the report on stderr. Without the opt-in there is no `icons`+ field and no rewrite. `integration check` notes each key a template's source+ never imports (`template_icon_not_imported`), never counted or failing,+ under `--strict` or `--next`.+- **FR11 — Search stays stable.** `astryx search` has no icon domain and no+ `--type icon`, and returns no experimental doc, with or without the opt-in.+ Icons join it only at promotion.+- **FR12 — The theme map.** A set exports the map `themeMap` names: one entry+ per built-in definition in `map`, each its icon's artwork, so a theme sets+ `icons: themeIcons`.++### Authoring++- **FR13 — The CLI writes the set, one verified icon at a time.** Every+ command reads modules statically and leaves files unchanged when it fails:+ - `experimental icon new-set <name>` writes the descriptor, an empty data+ file, the generated module (`generated`) with its declaration file and an+ empty theme map, and the manifest root. `--from <module>` wraps every+ component the module exports, and every data export through the set's+ `adapter`, as `<Name>Icon` exports, filling `map` only where a definition's+ name or word is an icon's whole `id`; a shared library prefix is left out+ of ids and names, and `--exclude` drops exports that are not icons. Run+ again, it refreshes the icons and keeps `map` entries whose icon exists.+ - `experimental icon add <Export> --from <module>` verifies the export,+ lists the definitions that fit it, and with `--definition` or+ `--new-definition` adds it and maps it; `--variant <name>` adds it as+ that declared variant of an existing icon.+ - `experimental icon map <definition> <icon>` writes one `map` entry, and+ `--remove` removes one;+ `new-definition` writes one of the set's own definitions; `use <set>`+ writes `experimental.iconSet`.+ - The generated module re-exports each library component, or wraps a data+ export with the adapter, and rewrites its declaration file and theme map+ with every change.+- **FR14 — The export contract.** Every icon and variant is a named+ `<Name>Icon` export of the package's public entry: a React component, or an+ adapter call, that takes SVG props, draws with `currentColor`, and fills its+ box. The module, name, and component shape are checked statically; color and+ size are documented with a render test authors can copy.++### Checks and catalogs++- **FR15 — `integration check` proves the set matches the package.** For each+ set it reports, without running the package:++ | Code | Severity | When |+ | --------------------------------- | -------- | ------------------------------------------------------------------------------ |+ | `invalid_icon_set` | error | the descriptor, data file, or a definition file is invalid |+ | `icon_builtin_definition_missing` | error | a built-in definition is not in `map` |+ | `icon_definition_unused` | warning | a definition the set declares is not in `map` |+ | `icon_definition_shadowed` | warning | a definition the set declares has an Astryx definition's name |+ | `icon_module_not_public` | error | an icon is read from outside the package's public entry |+ | `icon_export_name` | warning | an export is not named `<Name>Icon` |+ | `icon_not_component` | error | an export is a literal, not a component or adapter call |+ | `icon_export_missing` | error | an export, the generated module, or the adapter does not exist |+ | `icon_module_invalid` | error | the set's module, a file it re-exports, or the generated module does not parse |+ | `icon_generated_types_mismatch` | error | the generated declaration file is missing or stale |+ | `icon_theme_map_mismatch` | error | the theme map disagrees with the built-in entries of `map` |+ | `icon_source_version_drift` | warning | the data names another upstream version than the package depends on |+ | `icon_license_notice_missing` | warning | a set with an upstream ships no license notice |++ A definition finding names the definition's description and words, and+ suggests an `icon map` command only when an icon's whole `id` is the+ definition's name or one of its words. Errors fail the check; warnings fail+ under `--strict`. Re-exports are followed through relative files and+ installed packages for these checks only, and an export fails only when the+ reader proves it absent. Neither of these is an issue, never counted and+ never failing, even under `--strict` or `--next`, in the validate result's+ additive+ field `iconSets` (each `{set, unmappedDefinitions, suggestions,+unchecked}`): the optional Astryx definitions a set leaves unmapped, printed+ as "Unmapped icon definitions (optional)"; and what a check cannot judge,+ each `{icon}`, `{adapter}`, or `{entry}` with its `reason`, printed under+ "Not checked" (`architecture:cli-surface` INV35, DEC-7): an icon export+ whose module is a package `exports` target not built yet; an icon or adapter+ export the reader cannot prove either way (behind a re-export it cannot+ follow, bound to a default or namespace import, or imported from a package+ that does not resolve); and a theme map or theme-map entry the reader cannot+ read. An export a module the reader fully reads lacks is still+ `icon_export_missing`.++- **FR16 — Older CLIs.** Published CLI 0.7.3 refuses `stability` on page and+ block templates, namespace docs, and theme descriptors, and refuses a+ template's `icons`, dropping the descriptor. No integration descriptor this+ feature writes sets `stability` there. For the package being authored, the+ validate result's additive field `olderCliNotes` (each `{file, kind, field,+message}`) names each template or namespace doc that sets `stability`, and+ each template that declares `icons`, while the package's CLI peer range+ admits a release before 0.7.4; a note is never counted and never fails a+ check (DEC-9). A CLI before 0.7.4 also refuses an astryx.config that sets+ `experimental.iconSet` ("Unrecognized key"), so commands that load the+ project configuration, such as `doctor` and `discover`, fail in that+ project. `experimental icon use` adds `warning` to its receipt, printed as a+ `[warn]` line, when the project declares an `@astryxdesign/cli` range (in+ any dependency field) that admits such a release; a project that declares no+ range, or a `workspace:`, `file:`, or `link:` one, gets none.+- **FR17 — Doctor and discover read sets only with the opt-in.** In a project+ that sets `experimental.iconSet`, the project's set is one of: valid+ (`selected`), not installed (`missing`), or installed but withdrawn+ (`withdrawn`: invalid, or its module does not resolve, with that reason).+ Doctor's `icon-sets` check fails when it names a set that is not installed+ or one that was withdrawn, saying which and why, and warns when two packages+ ship that name or another set is withdrawn. The template `icons` report and+ `experimental icon --list` carry the same status and reason, and+ `experimental icon` with `--set` or `<set>/<id>`, `experimental icon use`,+ and `discover <package>/<set>` name a withdrawn set as withdrawn, with its+ reason, rather than as not installed. `astryx discover` reads `icon-set` as+ a kind: `--type icon-set`, catalog entries with `iconCount` and+ `definitions`, and `discover <package>/<set>`; a withdrawn set is not+ listed. Without the opt-in, Doctor has no such check and reports no icon-set+ issue, `doctor integration` checks an installed package's icon sets only+ with it (the package being authored, read by `doctor integration validate`+ with no package, `integration check`, and `verify`, is always checked), and+ discover treats `icon-set` as an unknown kind and `iconCount` and+ `definitions` as unknown fields before it validates a catalog, so a+ malformed icon-set item never fails a source (`spec:AST-051/FR7`).++### Supporting pieces++- **FR18 — Additive docs support.** Every doc type except `ThemeDoc` and+ `IconSetDoc`, and every schema field and enum value, accepts+ `stability: 'experimental'`: help shows a marked command as+ `[experimental]`, stable tables leave out a marked field or value, search+ leaves out a marked doc, and Doctor's doc counts leave marked docs out. A+ namespace's `source.packages: 'all'` adopts a doc group from every package+ only on a CLI namespace marked experimental (the icon definitions); DEC-7+ owns that exception to `spec:AST-046/FR2`.++### Platform support++- Supported engines: the CLI's Node floor.+- Unsupported behavior: a set whose module does not resolve does not answer+ lookups, and templates keep their icons.+- Browser evidence: none; every behavior is CLI output, written source, or a+ module's exports.++## Current-state impact++- `architecture:cli-surface`: the `experimental` command group and+ `experimental icon` commands with their response types, the+ `experimental.iconSets` manifest root, the `icon-set` and `icon-definition`+ descriptor kinds, the `cli/experimental` docs namespace, the `icon-sets`+ Doctor check, the icon-set checks and the `iconSets` and `olderCliNotes`+ validate fields.+- `contributing:cli-conventions`: `IconSetDoc`, `IconSetData`, and+ `IconDefinitionDoc` join the authoring types.+- Consumer docs: `cli/experimental/icon-sets`,+ `cli/experimental/icon-set-files`, and `cli/experimental/icon-definitions`.+- `spec:AST-051`: discover's `icon-set` kind, read only with the opt-in.++## Verification++| Contract | Verification | Representative states | Mutation or failure expectation |+| --------- | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| FR0, FR11 | experimental-isolation tests against the output of the CLI without the feature | help; the manifest; every stable docs topic and tree node, the `cli` listings, and every stable `cli` docs node; search for `delete`, `close`, `icon`, `trash can`, `search`, `experimental`, and `icon set`, with no set and with a set opted in; template printed and copied; discover, Doctor, and `doctor integration validate <package>` with a set and no opt-in; stderr of every command that prints the integration-issue nudge, with a set and no opt-in. Goldens hold identities, structure, counts, every `stability`, and every sentence or link that names an experimental surface, an icon set, or an icon definition, not prose | a stable output gains a result, field, section, count, `stability`, or a sentence or link naming an experimental surface that the CLI without the feature lacks (apart from FR18's `stability` field); or a stable command gains an icon-set subcommand or kind |+| FR1–FR5 | descriptor, data-file, and definition parser and discovery tests | valid set; invalid data; definitions Astryx and the set both have | an invalid set answers, or a definition file is not read |+| FR6–FR8 | `experimental icon` text and JSON tests | definition, name, and meaning matches; `<set>/<id>`; `--list`; two sets of one name | ranking or tie order changes, or a bare ambiguous name answers |+| FR9–FR10 | template mapping tests | mapped by match and by definition; kept with a suggestion; no opt-in | a name is guessed, or a project without the opt-in gets a rewrite |+| FR12–FR14 | writer and command tests | wrap and refresh; adapter; generated types and theme map | a write is left half done, or the theme map drifts from `map` |+| FR15 | `integration check` tests, with and without `--strict` | every code; unmapped optional definitions | an export the module lacks passes, or the optional list fails a check |+| FR16 | validate tests; a scratch project on published CLI 0.7.3 | `stability` on a template and namespace doc; template `icons`; peer range from 0.7.4 | a note fails a check, or a dropped descriptor goes unnoted |+| FR17 | Doctor and discover tests | opted in; installed set and no opt-in; invalid set and no opt-in | a project without the opt-in sees an icon-set check, issue, or kind |+| FR18 | docs tree, help, and search tests | marked command; stable and experimental namespace with `packages: 'all'` | a stable namespace adopts another package's doc, or a marked doc reaches search |++## Decision log++### DEC-1 — The set is the item; its data file is the payload++**Reference:** `spec:AST-084/DEC-1`+**Decider:** `josephfarina`, `2026-10-20`++One descriptor per set keeps the no-catalog rule, and every surface reads the+one data file, so lookup, templates, and themes agree on what an icon means.++Rejected: one doc file per icon, which thousands of hand-kept files cannot keep in step with a library.++### DEC-2 — Find icons with a dedicated command++**Reference:** `spec:AST-084/DEC-2`+**Decider:** `josephfarina`, `2026-10-20`++An icon answer needs its import line, variants, and definitions, so+`astryx experimental icon` answers with the full record. `astryx search` is a+stable surface the experiment never feeds; icons join it at promotion.++### DEC-3 — Templates keep their icon when nothing maps++**Reference:** `spec:AST-084/DEC-3`+**Decider:** `josephfarina`, `2026-10-20`++A wrong icon is worse than a familiar one, so an unmapped icon keeps its+import and the report says so.++### DEC-4 — Astryx owns the definitions; sets map to them++**Reference:** `spec:AST-084/DEC-4`+**Decider:** `josephfarina`, `2026-10-20`++Shared definitions let templates name meanings, not libraries. A set extends+them with its own files, and the CLI never encodes a library.++### DEC-5 — Every icon is a component the package exports++**Reference:** `spec:AST-084/DEC-5`+**Decider:** `josephfarina`, `2026-10-20`++Apps, templates, and theme maps import every icon from the set's package; the+generated module and adapter make data-only libraries work the same way.++### DEC-6 — Icon sets ship experimental++**Reference:** `spec:AST-084/DEC-6`+**Decider:** `josephfarina`, `2026-10-20`++The commands, keys, data file, and output may change in a patch release while+real sets prove the design. Each surface uses its kind's experimental+boundary, and a project that does not opt in sees the output it saw before.++### DEC-7 — Experimental namespaces may adopt docs from every package++**Reference:** `spec:AST-084/DEC-7`+**Decider:** `josephfarina`, `2026-10-20`++A set adds its own icon definitions, and they belong beside the Astryx ones,+so a namespace's `source.packages: 'all'` adopts a doc group from every+package. It is an experimental exception to `spec:AST-046/FR2`, read only on a+CLI namespace marked `stability: 'experimental'`; every stable namespace+adopts only its own package's docs, exactly as `spec:AST-046/FR2` says.++Rejected: placing each set's definitions under its own package, which splits+one vocabulary across as many namespaces as there are sets.++### DEC-8 — `icon-set` is a seventh discover kind, behind the opt-in++**Reference:** `spec:AST-084/DEC-8`+**Decider:** `josephfarina`, `2026-10-20`++A set is an item a package adds, so discover lists it like the six kinds of+`spec:AST-051/FR5`, with the additive catalog fields `iconCount` and+`definitions`. Only a project that sets `experimental.iconSet` reads them.+Without it, `--type icon-set` fails with `ERR_INVALID_OPTION`, unknown-kind+errors list the six kinds, and the kind and its fields are unknown under+`spec:AST-051/FR7`, so the output matches a CLI without icon sets.++### DEC-9 — `olderCliNotes` is additive and never fails++**Reference:** `spec:AST-084/DEC-9`+**Decider:** `josephfarina`, `2026-10-20`++An author whose peer range admits an older CLI needs to know what that CLI+drops, but the package is valid for the CLI that checks it. So validate adds+the field `olderCliNotes`: it is never counted in a summary and never fails a+check, with or without `--strict` or `--next`.++## Open questions++None.diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 5ea05fd8c0..581cfc6024 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -96,23 +96,24 @@ Each command declares what it does in a folder outside any project, and `astryx<!-- BEGIN GENERATED: commands -->-| Command | Description | Outside a project |-| ------------- | ----------------------------------------------------------------------------- | ----------------- |-| `blog` | Read the Astryx blog from the published feed | `same` |-| `build` | Build a page: the template to start from, or the workflow playbook (no query) | `same` |-| `component` | List components or print component docs | `same` |-| `discover` | Browse and search integrations: the ones you have and the ones you could add | `same` |-| `docs` | Print reference docs | `same` |-| `doctor` | Diagnose Astryx projects and integration packages | `own` |-| `gap-report` | Report a missing component or feature to the package that owns it | `same` |-| `hook` | List hooks or print hook docs | `same` |-| `init` | Initialize the design system in your project | `own` |-| `integration` | Author and verify an Astryx integration package | by subcommand |-| `search` | Search components, hooks, docs, templates, and themes in one ranked list | `same` |-| `swizzle` | Copy component source for customization | `refuse` |-| `template` | List, show, or scaffold page and block templates | `same` |-| `theme` | Add, switch, build, and author themes | by subcommand |-| `upgrade` | Update your code after upgrading Astryx, and refresh ShadCN-copied components | `own` |+| Command | Description | Outside a project |+| -------------- | ----------------------------------------------------------------------------- | ----------------- |+| `blog` | Read the Astryx blog from the published feed | `same` |+| `build` | Build a page: the template to start from, or the workflow playbook (no query) | `same` |+| `component` | List components or print component docs | `same` |+| `discover` | Browse and search integrations: the ones you have and the ones you could add | `same` |+| `docs` | Print reference docs | `same` |+| `doctor` | Diagnose Astryx projects and integration packages | `own` |+| `experimental` | [experimental] Try features that may change or be removed in a patch release | by subcommand |+| `gap-report` | Report a missing component or feature to the package that owns it | `same` |+| `hook` | List hooks or print hook docs | `same` |+| `init` | Initialize the design system in your project | `own` |+| `integration` | Author and verify an Astryx integration package | by subcommand |+| `search` | Search components, hooks, docs, templates, and themes in one ranked list | `same` |+| `swizzle` | Copy component source for customization | `refuse` |+| `template` | List, show, or scaffold page and block templates | `same` |+| `theme` | Add, switch, build, and author themes | by subcommand |+| `upgrade` | Update your code after upgrading Astryx, and refresh ShadCN-copied components | `own` |<!-- END GENERATED: commands --><!-- Generated by scripts/generate-cli-readme.mjs from `astryx manifest`. Run `pnpm -F @astryxdesign/cli readme`. -->@@ -470,69 +471,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. 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. |+| 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. For the package being authored, olderCliNotes ({file, kind: template \| namespace, field, message}) lists each descriptor field a CLI before 0.7.4 refuses, such as stability on a template or namespace doc; it is present only when it has entries, and is never counted or fails a check. |+| `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/discover/_adapter.mjs b/packages/cli/api/discover/_adapter.mjsindex 2e5ab9aad6..863390fa55 100644--- a/packages/cli/api/discover/_adapter.mjs+++ b/packages/cli/api/discover/_adapter.mjs@@ -30,12 +30,16 @@ import {hostedRun} from '../../foundation/runtime/package-root.mjs';import {scanAllPackages, findComponentInPackages} from './_package-scanner.mjs';import {loadDocs} from '../../foundation/discovery/component-loader.mjs';import {collectIdentities} from '../../foundation/integrations/contribution-inventory.mjs';+import {discoverIntegrationIconSets} from '../../foundation/discovery/icon-set-discovery.mjs';import {detectPackageManager} from '../../foundation/env/package-manager.mjs';import {isValidSemver, semverCompare} from '../../foundation/env/semver.mjs';import {assertWithin} from '../../foundation/fs/path-safety.mjs';import {userCacheDir} from '../../foundation/env/user-dirs.mjs';import {CLI_ROOT, findInstalledPackage} from '../../foundation/fs/paths.mjs';-import {parseDiscoverCatalog} from '../../authoring/discover/parse.mjs';+import {+ DISCOVER_KINDS,+ parseDiscoverCatalog,+} from '../../authoring/discover/parse.mjs';import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';@@ -99,9 +103,24 @@ const DEPENDENCY_FIELDS = [* docs?: string[],* themes?: string[],* codemods?: string[],+ * iconSets?: string[],+ * iconSetDetails?: IconSetSummary[],+ * withdrawnIconSets?: Array<{name: string, reason: string}>,* }} InstalledPackage*/+/**+ * What discover shows about one installed icon set (spec:AST-084 FR17).+ * @typedef {object} IconSetSummary+ * @property {string} name+ * @property {string} displayName+ * @property {string} description+ * @property {string} license+ * @property {number} iconCount+ * @property {{variant?: string}} [default]+ * @property {string[]} definitions the icon definitions its `map` covers+ */+/*** What one source did on this run.* @typedef {object} SourceState@@ -218,16 +237,44 @@ export async function describeInstalled(project, scanned) {);// Components come from the scan above; loading every component doc again// here would only slow the list down.+ // Icon sets are read below, only with the opt-in.const {identities} = await collectIdentities({...integration,components: undefined,+ iconSets: undefined,});+ // Icon sets are listed the way every icon surface sees them: a set that+ // is invalid or whose module does not resolve answers nothing (FR9).+ // They are experimental (spec:AST-017 FR27), so discover lists them only+ // in a project that opts in with `experimental.iconSet`.+ const {sets, withdrawn} = optedIntoIconSets(project)+ ? discoverIntegrationIconSets(integration, {projectDir: project.cwd})+ : {sets: [], withdrawn: []};installed.push({...base,templates: identities.templates.map(t => t.id),docs: identities.docs,themes: identities.themes.map(t => t.slug),codemods: identities.codemods.map(c => `${c.version}/${c.id}`),+ iconSets: sets.map(set => set.name),+ iconSetDetails: sets.map(set => ({+ name: set.name,+ displayName: set.displayName,+ description: set.description,+ license: set.license,+ iconCount: set.data.icons.length,+ ...(set.data.default ? {default: set.data.default} : {}),+ definitions: [...Object.keys(set.data.map ?? {})].sort(),+ })),+ // Never listed; named only to say why a lookup of one answers nothing.+ ...(withdrawn.length > 0+ ? {+ withdrawnIconSets: withdrawn.map(each => ({+ name: each.name,+ reason: each.reason,+ })),+ }+ : {}),});}return installed;@@ -505,13 +552,14 @@ function savedCopyPath(cacheDir, from, request) {/*** @param {string} file* @param {string} label+ * @param {boolean} iconSets the project opts into icon sets*/-function readSavedCopy(file, label) {+function readSavedCopy(file, label, iconSets) {try {const saved = JSON.parse(fs.readFileSync(file, 'utf8'));return {savedAt: String(saved.savedAt),- catalog: parseDiscoverCatalog(saved.catalog, label),+ catalog: parseDiscoverCatalog(saved.catalog, label, {iconSets}),};} catch {return null;@@ -541,8 +589,9 @@ function writeSavedCopy(file, catalog) {* @param {{package?: string, version?: string}} request* @param {string} label* @param {number} timeoutMs+ * @param {boolean} iconSets the project opts into icon sets*/-async function callSource(source, request, label, timeoutMs) {+async function callSource(source, request, label, timeoutMs, iconSets) {const controller = new AbortController();/** @type {ReturnType<typeof setTimeout> | undefined} */let timer;@@ -561,7 +610,7 @@ async function callSource(source, request, label, timeoutMs) {),timedOut,]);- return parseDiscoverCatalog(answer, label);+ return parseDiscoverCatalog(answer, label, {iconSets});} finally {clearTimeout(timer);}@@ -586,6 +635,9 @@ async function callOwnSources(project, request = {}, options = {}) {const result = {sources: [], packages: []};const fromDoor = doorSources();if (project == null && fromDoor.length === 0) return result;+ // Without the opt-in, icon-set items and fields are unknown before the+ // catalog is checked, so one cannot fail a source (spec:AST-051 FR7).+ const iconSets = optedIntoIconSets(project);/** @type {Array<{from: string, key?: string, source?: DiscoverSource, error?: string}>} */const origins = [];@@ -635,7 +687,7 @@ async function callOwnSources(project, request = {}, options = {}) {/** @type {import('../../authoring/discover/type').DiscoverCatalog} */let catalog;try {- catalog = await callSource(source, ask, label, timeoutMs);+ catalog = await callSource(source, ask, label, timeoutMs, iconSets);writeSavedCopy(file, catalog);result.sources.push({name: catalog.source.name,@@ -646,7 +698,7 @@ async function callOwnSources(project, request = {}, options = {}) {});} catch (err) {const message = err instanceof Error ? err.message : String(err);- const saved = readSavedCopy(file, label);+ const saved = readSavedCopy(file, label, iconSets);if (saved == null) {result.sources.push({name: from,@@ -724,10 +776,66 @@ export async function callSources(project, request = {}, options = {}) {],// Source order: the first entry per integration is the one discover// keeps. Official packages are put first only where discover shows them.- packages: [...own.packages, ...added],+ // An experimental kind is a kind this project does not read unless it+ // opts in, so its items are ignored like any unknown kind (FR7).+ packages: withoutUnreadKinds(project, [...own.packages, ...added]),};}+/**+ * The experimental item kinds a catalog may list (spec:AST-017 FR27):+ * `icon-set`, read only in a project that sets `experimental.iconSet`.+ */+export const EXPERIMENTAL_KINDS = /** @type {const} */ (['icon-set']);++/** The item kinds every project reads: the catalog kinds, less experimental ones. */+export const STABLE_KINDS = DISCOVER_KINDS.filter(+ kind =>+ !(/** @type {readonly string[]} */ (EXPERIMENTAL_KINDS).includes(kind)),+);++/**+ * The item kinds discover reads in the project at the working directory, or+ * the stable kinds when it cannot be read.+ * @returns {Promise<readonly string[]>}+ */+export async function loadReadKinds() {+ return readKinds(await Project.load().catch(() => undefined));+}++/**+ * The item kinds discover reads in this project: every stable kind, and the+ * experimental ones when the project opts in.+ * @param {Project | undefined} project+ * @returns {readonly string[]}+ */+export function readKinds(project) {+ return optedIntoIconSets(project) ? DISCOVER_KINDS : STABLE_KINDS;+}++/**+ * Whether the project opts into icon sets with `experimental.iconSet`.+ * @param {Project | undefined} project+ */+export function optedIntoIconSets(project) {+ return Boolean(project?.config?.experimental?.iconSet);+}++/**+ * @template {{contributions: Array<{kind: string}>}} P+ * @param {Project | undefined} project+ * @param {P[]} packages+ * @returns {P[]}+ */+function withoutUnreadKinds(project, packages) {+ if (optedIntoIconSets(project)) return packages;+ const kinds = readKinds(project);+ return packages.map(pkg => ({+ ...pkg,+ contributions: pkg.contributions.filter(c => kinds.includes(c.kind)),+ }));+}+/*** Official packages first, in the official list's order; the rest keep theirs.* @template T@@ -935,6 +1043,7 @@ export const KIND_FIELDS = /** @type {const} */ ([['theme', 'themes'],['codemod', 'codemods'],['agent-doc', 'agentDocs'],+ ['icon-set', 'iconSets'],]);/**diff --git a/packages/cli/api/discover/detail/item/item.mjs b/packages/cli/api/discover/detail/item/item.mjsindex ea6ea5c134..3774af413f 100644--- a/packages/cli/api/discover/detail/item/item.mjs+++ b/packages/cli/api/discover/detail/item/item.mjs@@ -37,6 +37,30 @@ export function item(packages, packageName, itemName, options = {}) {if (kind === 'component') continue;const names = /** @type {Record<string, unknown>} */ (pkg)[field];if (Array.isArray(names) && names.includes(itemName)) {+ const set =+ kind === 'icon-set'+ ? pkg.iconSetDetails?.find(entry => entry.name === itemName)+ : undefined;+ if (set) {+ return {+ type: 'discover.item',+ package: packageName,+ data: {+ package: packageName,+ ...(pkg.version ? {version: pkg.version} : {}),+ kind,+ name: itemName,+ title: set.displayName,+ summary: set.description,+ license: set.license,+ iconCount: set.iconCount,+ ...(set.default ? {default: set.default} : {}),+ definitions: set.definitions,+ command: `astryx experimental icon <words> --set ${packageName}/${itemName}`,+ installed: true,+ },+ };+ }return {type: 'discover.item',package: packageName,@@ -69,6 +93,13 @@ export function item(packages, packageName, itemName, options = {}) {...(found.title ? {title: found.title} : {}),...(found.summary ? {summary: found.summary} : {}),...(found.keywords ? {keywords: found.keywords} : {}),+ ...(found.iconCount != null ? {iconCount: found.iconCount} : {}),+ ...(found.definitions ? {definitions: found.definitions} : {}),+ ...(found.kind === 'icon-set' && pkg != null+ ? {+ command: `astryx experimental icon <words> --set ${packageName}/${found.name}`,+ }+ : {}),installed: pkg != null,...(pkg == null && installedAs ? {installedAs} : {}),...(pkg == null && !installedAs && adddiff --git a/packages/cli/api/discover/discover.mjs b/packages/cli/api/discover/discover.mjsindex 9428479ca2..eb6ec72fe6 100644--- a/packages/cli/api/discover/discover.mjs+++ b/packages/cli/api/discover/discover.mjs@@ -33,7 +33,9 @@ import {discoverPackages,findComponent,hasSources,+ loadReadKinds,officialDeclarations,+ STABLE_KINDS,officialFirst,officialList,withDeclaredOfficial,@@ -52,7 +54,6 @@ import {search} from './search/search.mjs';import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';-import {DISCOVER_KINDS} from '../../authoring/discover/parse.mjs';const DEFAULT_LIMIT = 20;@@ -88,15 +89,13 @@ function splitTarget(query) {/*** @param {{type?: unknown, installed?: boolean, available?: boolean, limit?: unknown}} options+ * @param {readonly string[]} kinds the item kinds this project reads*/-function checkOptions({type, installed, available, limit}) {- if (- type != null &&- !(/** @type {readonly unknown[]} */ (DISCOVER_KINDS).includes(type))- ) {+function checkOptions({type, installed, available, limit}, kinds) {+ if (type != null && !kinds.includes(/** @type {string} */ (type))) {throw new AstryxError(`Unknown --type "${String(type)}"`,- DISCOVER_KINDS.map(kind => ({name: kind, reason: 'item kind'})),+ kinds.map(kind => ({name: kind, reason: 'item kind'})),ERROR_CODES.ERR_INVALID_OPTION,);}@@ -178,7 +177,14 @@ export function answersQueries(project) {*/export async function discover(query, options = {}) {const {lang = null, zh = false, type, limit} = options;- checkOptions(options);+ // An experimental kind is read only in a project that opts in (spec:AST-017+ // FR27); only then does `--type` take it, or an error name it.+ const kinds =+ options.type != null &&+ !(/** @type {readonly unknown[]} */ (STABLE_KINDS).includes(options.type))+ ? await loadReadKinds()+ : STABLE_KINDS;+ checkOptions(options, kinds);const only = options.installed? /** @type {const} */ ('installed'): options.available@@ -308,6 +314,18 @@ export async function discover(query, options = {}) {if (!target.item) return detail(packages, target.name, context);const found = item(packages, target.name, target.item, context);if (found) return found;+ // An installed icon set that was withdrawn answers nothing; say why+ // rather than that the package has no such item (spec:AST-084 FR17).+ const gone = packages+ .find(p => p.name === target.name)+ ?.withdrawnIconSets?.find(each => each.name === target.item);+ if (gone) {+ throw new AstryxError(+ `Icon set "${target.item}" in ${target.name} is installed but withdrawn: ${gone.reason}`,+ [],+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,+ );+ }if (officialOnly) {throw new AstryxError(`"${target.item}" not found in ${target.name}`,diff --git a/packages/cli/api/discover/discover.type.mjs b/packages/cli/api/discover/discover.type.mjsindex 39d38354fe..635df2b3ad 100644--- a/packages/cli/api/discover/discover.type.mjs+++ b/packages/cli/api/discover/discover.type.mjs@@ -55,6 +55,7 @@* @property {string[]} [themes] Theme slugs, when it adds any.* @property {string[]} [codemods] `<version>/<id>`, when it adds any.* @property {string[]} [agentDocs] Agent guidance, when a source lists any.+ * @property {string[]} [iconSets] Icon set names, when it adds any. Experimental: may change or be removed in a patch release.* @property {string} [latest] The latest release a discover source knows.*/@@ -70,6 +71,7 @@* @property {string[]} [themes]* @property {string[]} [codemods]* @property {string[]} [agentDocs]+ * @property {string[]} [iconSets] Icon set names, when it adds any. Experimental: may change or be removed in a patch release.* @property {string} [description]* @property {string[]} [aliases] The integration's other package names.* @property {string} source The discover source that lists it; `Astryx` for@@ -136,11 +138,23 @@* title?: string,* summary?: string,* keywords?: string[],+ * license?: string,+ * iconCount?: number,+ * default?: {variant?: string},+ * definitions?: string[],+ * command?: string,* installed: boolean,* installedAs?: string,* install?: string,* source?: string,- * }} data+ * }} data For an icon set, `title` and `summary` are its display name and+ * description, and it carries `license`, `iconCount`, `default` (the variant+ * an icon's own export draws, when the set names one), the shared icon names+ * its `map` covers (`definitions`), and `command`, which searches the set's icons. A source's+ * entry carries `iconCount` and `definitions` when the source lists them.+ * The icon-set fields (`license`, `iconCount`, `default`, `definitions`,+ * and `command`) are experimental: they may change or be removed in a patch+ * release.*//**diff --git a/packages/cli/api/docs/_adapter.mjs b/packages/cli/api/docs/_adapter.mjsindex 793d3bac64..c80d238f5b 100644--- a/packages/cli/api/docs/_adapter.mjs+++ b/packages/cli/api/docs/_adapter.mjs@@ -39,6 +39,7 @@ import {} from '../../foundation/doc-compiler/read.mjs';import {buildDocsTree,+ isExperimentalTreeNode,loadTreeInputs,} from '../../foundation/doc-compiler/tree.mjs';import {sortDiagnostics} from '../../foundation/doc-compiler/diagnostics.mjs';@@ -58,6 +59,8 @@ import {} from '../../foundation/discovery/cli-self-docs.mjs';import {AUTHORING_REFERENCE_ROUTE,+ EXPERIMENTAL_AUTHORING_ROUTE,+ isExperimentalSelfDoc,loadAuthoringSelfDocs,schemaFieldTable,selfDocSection,@@ -672,14 +675,20 @@ function docFinderOver(catalog, tree, fromProvider, summaries = true) {? await authoringDoc(parsed.kind, parsed.name): null;if (authored) {+ // An experimental schema is a section of its experimental route, not+ // of the field reference (spec:AST-084 FR0).+ const experimental = isExperimentalSelfDoc(authored);+ const route = experimental+ ? EXPERIMENTAL_AUTHORING_ROUTE+ : AUTHORING_REFERENCE_ROUTE;return {link: {target,id: createDocId(provider, authored.type, authored.name),- route: AUTHORING_REFERENCE_ROUTE,+ route,title: authored.displayName ?? authored.name,summary: renderTokens(authored.description ?? ''),- command: `astryx docs authoring ${authored.name}`,+ command: `astryx docs ${experimental ? route : 'authoring'} ${authored.name}`,},kind: parsed.kind,typed: {doc: authored, providerId: CLI_PROVIDER_ID, tree: false},@@ -1668,9 +1677,20 @@ export function placeLinks(tree, node) {up: node.parent == null ? 'astryx docs' : `astryx docs ${node.parent}`,};const parent = node.parent == null ? undefined : tree.get(node.parent);- const siblings =+ // A stable node moves only to stable neighbors, so its links read as they+ // do without experimental features (spec:AST-017 FR27, spec:AST-084 FR0),+ // and an experimental node only to experimental ones, so each next read+ // still names this one as its previous.+ const experimental = isExperimentalTreeNode(tree, node);+ const siblings = (parent?.slots.find(slot => slot.children.includes(node.route))?.children ??- [];+ []+ ).filter(route => {+ const sibling = tree.get(route);+ return (+ sibling == null || isExperimentalTreeNode(tree, sibling) === experimental+ );+ });const at = siblings.indexOf(node.route);if (at > 0) links.previous = `astryx docs ${siblings[at - 1]}`;if (at !== -1 && at < siblings.length - 1) {diff --git a/packages/cli/api/docs/docs.type.mjs b/packages/cli/api/docs/docs.type.mjsindex 61bdd9cc2c..e710209d96 100644--- a/packages/cli/api/docs/docs.type.mjs+++ b/packages/cli/api/docs/docs.type.mjs@@ -176,6 +176,8 @@* @property {string} package the package that owns the node* @property {string} title* @property {string} summary+ * @property {'experimental'} [stability] Present only when the node's doc is+ * marked experimental: it may change or be removed in a patch release.* @property {DocsNodeLink[]} breadcrumb the namespaces above it, top first* @property {DocsNodeSlot[]} slots a namespace's slots that hold children, in* order; empty for a typed doc, and for a depth read of 0@@ -213,6 +215,8 @@* @property {string} kind* @property {string} title* @property {string} summary+ * @property {'experimental'} [stability] Present only when the child's doc is+ * marked experimental: it may change or be removed in a patch release.* @property {DocsNodeSlot[]} [slots] with a depth read, its own slots, while* the read goes deeper* @property {number} [childCount] with a depth read, how many docs sit rightdiff --git a/packages/cli/api/docs/node/node.mjs b/packages/cli/api/docs/node/node.mjsindex 65810eda45..396fd20f14 100644--- a/packages/cli/api/docs/node/node.mjs+++ b/packages/cli/api/docs/node/node.mjs@@ -16,6 +16,7 @@*/import {detailView} from '../../../foundation/doc-compiler/lenses.mjs';+import {isExperimentalTreeNode} from '../../../foundation/doc-compiler/tree.mjs';import {compileTopic,guideEntry,@@ -62,6 +63,7 @@ export async function nodeView(catalog, tree, node, read) {package: node.provider,title: node.title,summary: node.summary,+ ...stabilityOf(tree, node),breadcrumb: tree.ancestors(node).map(ancestor => ({route: ancestor.route, title: ancestor.title})),@@ -70,7 +72,7 @@ export async function nodeView(catalog, tree, node, read) {name: slot.name,title: slot.title,children: slot.children.map(route =>- childIdentity(/** @type {TreeNode} */ (tree.get(route))),+ childIdentity(tree, /** @type {TreeNode} */ (tree.get(route))),),})): read.depth >= 1@@ -85,12 +87,26 @@ export async function nodeView(catalog, tree, node, read) {return view;}+/**+ * `stability: 'experimental'` for a node whose doc is marked experimental, or+ * that sits under an experimental namespace (spec:AST-017 FR27), the way help+ * marks an experimental command; nothing for a stable one, so stable entries+ * read as they always have.+ * @param {DocsTree} tree+ * @param {TreeNode} node+ * @returns {{stability?: 'experimental'}}+ */+function stabilityOf(tree, node) {+ return isExperimentalTreeNode(tree, node) ? {stability: 'experimental'} : {};+}+/*** The fields every child carries: what it is, and the route that opens it.+ * @param {DocsTree} tree* @param {TreeNode} child* @returns {import('../docs.type.mjs').DocsNodeChild}*/-function childIdentity(child) {+function childIdentity(tree, child) {return {route: child.route,name: child.route.slice(child.route.lastIndexOf('/') + 1),@@ -106,6 +122,7 @@ function childIdentity(child) {kind: child.kind,title: child.title,summary: child.summary,+ ...stabilityOf(tree, child),};}@@ -158,7 +175,7 @@ async function slotsBelow(catalog, tree, slots, level, read) {* @returns {Promise<import('../docs.type.mjs').DocsNodeChild>}*/async function childBelow(catalog, tree, child, level, read) {- const view = childIdentity(child);+ const view = childIdentity(tree, child);if (read.detail !== 'brief') {Object.assign(view, await childText(catalog, tree, child, read.lang));}diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjsindex b7ea1c0f96..513e1d6b3e 100644--- a/packages/cli/api/doctor/doctor.mjs+++ b/packages/cli/api/doctor/doctor.mjs@@ -63,6 +63,7 @@ import {} from '../docs/_adapter.mjs';import {typedEdges} from '../docs/node/node.mjs';import {detailView, indexView} from '../../foundation/doc-compiler/lenses.mjs';+import {isExperimentalTreeNode} from '../../foundation/doc-compiler/tree.mjs';import {semverCompare, isValidSemver, satisfiesRange} from '../../foundation/env/semver.mjs';import {checkAppThemes, checkThemes} from './theme-checks.mjs';import {availableLine, RUN_FROM_PROJECT, upgradeLine} from '../../foundation/release/notices.mjs';@@ -112,6 +113,9 @@ import {checkBuilt} from './built-checks.mjs';* Combined project-level integration issues, including cross-package template replacement warnings.* @property {Error|null} [configError] - Error thrown while resolving the config* path (e.g. multiple config files present), surfaced by checkConfig as a FAIL.+ * @property {{sets: Array<{name: string, package: string}>, withdrawn: Array<{name: string, package: string, reason: string}>, choice: {status: 'selected'|'none'|'ambiguous'|'missing'|'withdrawn', reason: string, configured?: string}}|null} [iconSets]+ * The project's icon sets (AST-084 FR17), or null when they could not be read.+ * Experimental: may change or be removed in a patch release.* @property {string|null} [projectError] - Why the CLI could not load the* project from its config, when it could not. Checks that need the loaded* project quote it when they skip, so a skip says what was found.@@ -509,9 +513,15 @@ export function checkImplicitIntegrations(ctx) {: '';// A declared root counts only when it exists: the manifest's keys are a// claim, and `integration-issues` reports the ones that are not true.- const declared = ['components', 'templates', 'themes', 'docs', 'codemods'].filter(- root => integration[/** @type {'components'} */ (root)],- );+ const declared = [+ 'components',+ 'templates',+ 'themes',+ 'docs',+ 'codemods',+ // An experimental root counts only in a project that opts in.+ ...(ctx.iconSets?.choice?.configured ? ['iconSets'] : []),+ ].filter(root => integration[/** @type {'components'} */ (root)]);const missing = declared.filter(root => {const dir = integration[/** @type {'components'} */ (root)];if (typeof dir !== 'string') return false;@@ -907,6 +917,66 @@ export function checkIntegrationIssues(ctx) {};}+/**+ * The project's icon sets (AST-084 FR17). Fails when `experimental.iconSet` names a set+ * that is not installed, or one that is installed but withdrawn (with why);+ * warns when two or more sets are installed and none is the project's, and+ * for each other installed set that was withdrawn, with why.+ * Icon sets are experimental (spec:AST-017 FR27): only a project that sets+ * `experimental.iconSet` gets the check, so every other report is unchanged.+ * @param {DoctorContext} ctx+ * @returns {DoctorCheck | null}+ */+export function checkIconSets(ctx) {+ const state = ctx.iconSets;+ const id = 'icon-sets';+ const label = 'Icon sets';+ if (state == null) return null;+ const {sets, withdrawn, choice} = state;+ // Only a project that opts in with `experimental.iconSet` gets the check.+ if (!choice.configured) return null;+ if (choice.status === 'missing') {+ return {+ id,+ label,+ status: 'fail',+ message: choice.reason,+ fix: 'Install the package that ships the set, or set experimental.iconSet in astryx.config to an installed set (`astryx experimental icon --list` names them).',+ };+ }+ if (choice.status === 'withdrawn') {+ return {+ id,+ label,+ status: 'fail',+ message: choice.reason,+ fix: 'Run `astryx integration check` in the package that ships the set, or install the module its data names; or set experimental.iconSet in astryx.config to a valid installed set (`astryx experimental icon --list` names them).',+ };+ }+ /** @type {string[]} */+ const problems = [];+ if (choice.status === 'ambiguous') problems.push(choice.reason);+ for (const each of withdrawn) problems.push(each.reason);+ if (problems.length > 0) {+ return {+ id,+ label,+ status: 'warn',+ message: problems.join(' | '),+ fix:+ choice.status === 'ambiguous'+ ? 'Set experimental.iconSet in astryx.config to "<package>/<set>" so templates use one set.'+ : 'Run `astryx integration check` in the package that ships the set, or install its module.',+ };+ }+ return {+ id,+ label,+ status: 'pass',+ message: `${sets.length} icon set${sets.length === 1 ? '' : 's'} installed. ${choice.reason}`,+ };+}+/*** Check 10 — report the detected package manager, and say so when the project's* own declaration disagrees with what is on disk.@@ -1207,6 +1277,9 @@ export async function checkAuthoringDocs(_ctx, options = {}) {id,label,status: 'pass',+ // Experimental schemas are checked like every other but are sections+ // of their experimental route, so the count is unchanged without them+ // (spec:AST-017 FR27).message: `All ${audit.sections} authoring schemas are readable in \`${formatCliCommand('docs authoring/field-reference')}\`.`,};} catch (err) {@@ -1275,7 +1348,9 @@ export async function checkCliDocs(_ctx, options = {}) {id,label,status: 'pass',- message: `All ${audit.docs} CLI docs are readable: ${audit.tree} in the \`${formatCliCommand('docs cli')}\` tree and ${audit.authoring} in \`${formatCliCommand('docs authoring/field-reference')}\`.`,+ // Experimental docs are checked like every other but not counted+ // (spec:AST-017 FR27).+ message: `All ${audit.docs - audit.experimental.docs} CLI docs are readable: ${audit.tree - audit.experimental.tree} in the \`${formatCliCommand('docs cli')}\` tree and ${audit.authoring - audit.experimental.authoring} in \`${formatCliCommand('docs authoring/field-reference')}\`.`,};} catch (err) {return {@@ -1348,7 +1423,11 @@ export async function checkDocsTree(_ctx, options = {}) {fix: DOCS_TREE_FIX,};}- const nodes = [...tree.nodes.values()];+ // Experimental docs are checked like every other but not counted+ // (spec:AST-017 FR27).+ const nodes = [...tree.nodes.values()].filter(+ node => !isExperimentalTreeNode(tree, node),+ );const namespaces = nodes.filter(node => node.kind === 'namespace').length;return {id,@@ -1367,6 +1446,7 @@ export async function checkDocsTree(_ctx, options = {}) {}}+/*** Every topic reads progressively, in every language it ships: it loads, its* section index and each of its sections fit in one read, and no contributed@@ -1391,16 +1471,23 @@ export async function checkDocsProgressiveDisclosure(ctx) {if (catalog) {// A guide the docs tree places is a topic read by its route; it is held// to the same budget as every flat topic.- const guides = [...(await projectTree(catalog)).nodes.values()]+ const tree = await projectTree(catalog);+ const placed = [...tree.nodes.values()]// A flat topic in a topic level is checked above, as a topic.- .filter(node => node.kind === 'generic' && !node.ref?.flatTopic)- .map(guideEntry);+ .filter(node => node.kind === 'generic' && !node.ref?.flatTopic);+ // An experimental guide is checked but not counted (spec:AST-017 FR27).+ const uncounted = new Set(+ placed+ .filter(node => isExperimentalTreeNode(tree, node))+ .map(node => node.route),+ );+ const guides = placed.map(guideEntry);for (const entry of [...catalog.entries(), ...guides]) {for (const lang of [null, ...overlayLanguages(entry)]) {const where = lang ? `${entry.name} [${lang}]` : entry.name;try {const doc = detailView(await compileTopic(catalog, entry, lang));- if (lang == null) topics += 1;+ if (lang == null && !uncounted.has(entry.name)) topics += 1;const indexBytes = docsIndexBytes(buildDocsIndexData(doc));if (indexBytes > DOC_OUTPUT_BUDGET_BYTES) {problems.push(@@ -1890,7 +1977,8 @@ async function runComputerChecks(cwd) {/*** Ordered list of synchronous check functions. Append here to add a check.* (checkConfig is async and is awaited separately by {@link runChecks}.)- * @type {Array<(ctx: DoctorContext) => DoctorCheck>}+ * A check that returns null does not apply to the project and is left out.+ * @type {Array<(ctx: DoctorContext) => DoctorCheck | null>}*/export const SYNC_CHECKS = [checkNodeVersion,@@ -1900,6 +1988,7 @@ export const SYNC_CHECKS = [checkConfiguredIntegrations,checkProviderIdentity,checkIntegrationIssues,+ checkIconSets,checkAgentDocs,checkPeerDeps,checkPackageManager,@@ -1962,6 +2051,8 @@ export async function runChecks(options = {}) {let configuredIntegrations = null;/** @type {string|null} */let projectError = null;+ /** @type {DoctorContext['iconSets']} */+ let iconSets = null;/** @type {import('../../foundation/config/project.mjs').Project | null} */let project = null;try {@@ -2057,6 +2148,11 @@ export async function runChecks(options = {}) {docsCatalog = null;docsCatalogError = err instanceof Error ? err.message : String(err);}+ try {+ iconSets = await project.iconSets();+ } catch {+ iconSets = null;+ }integrationIssues = await project.issues();} catch {// Best-effort: once the project has loaded, a later read that throws@@ -2082,6 +2178,7 @@ export async function runChecks(options = {}) {configuredIntegrations,configError,projectError,+ iconSets,};/** @type {DoctorCheck[]} */@@ -2089,7 +2186,8 @@ export async function runChecks(options = {}) {// Run the theme checks and config check after the environment checks. The// released `themes` check keeps its place, ahead of the app-theme checks.for (const fn of SYNC_CHECKS) {- checks.push(fn(ctx));+ const check = fn(ctx);+ if (check) checks.push(check);if (fn === checkVersionAlignment) {const appThemeChecks = await checkAppThemes(cwd);checks.push(checkThemes(cwd, appThemeChecks), ...appThemeChecks);diff --git a/packages/cli/api/doctor/doctor.test.mjs b/packages/cli/api/doctor/doctor.test.mjsindex a477ec68d8..bbc9fecb9b 100644--- a/packages/cli/api/doctor/doctor.test.mjs+++ b/packages/cli/api/doctor/doctor.test.mjs@@ -738,7 +738,8 @@ describe('checkCliDocs', () => {id: 'cli-docs',label: 'CLI docs',status: 'pass',- message: `All ${audit.docs} CLI docs are readable: ${audit.tree} in the \`${formatCliCommand('docs cli')}\` tree and ${audit.authoring} in \`${formatCliCommand('docs authoring/field-reference')}\`.`,+ // Experimental docs are checked but not counted (spec:AST-017 FR27).+ message: `All ${audit.docs - audit.experimental.docs} CLI docs are readable: ${audit.tree - audit.experimental.tree} in the \`${formatCliCommand('docs cli')}\` tree and ${audit.authoring - audit.experimental.authoring} in \`${formatCliCommand('docs authoring/field-reference')}\`.`,});},SLOW,@@ -878,7 +879,9 @@ describe('checkAuthoringDocs against the public authoring surface', () => {id: 'authoring-docs',label: 'Authoring docs',status: 'pass',- message: `All ${AUTHORING_SELF_DOCS.length} authoring schemas are readable in \`${formatCliCommand('docs authoring/field-reference')}\`.`,+ // The three experimental icon-set schemas are checked but not+ // counted (spec:AST-017 FR27).+ message: `All ${AUTHORING_SELF_DOCS.length - 3} authoring schemas are readable in \`${formatCliCommand('docs authoring/field-reference')}\`.`,});},SLOW,@@ -995,7 +998,8 @@ describe('checkAuthoringDocs against the public authoring surface', () => {fs.rmSync(path.join(root, source));const sources = without(source);expect(await auditAuthoringSelfDocs({root, sources})).toEqual({- sections: sources.length,+ sections: sources.length - 3,+ experimental: 3,unreachable: [],failed: [],oversized: [],diff --git a/packages/cli/api/doctor/icon-sets.test.mjs b/packages/cli/api/doctor/icon-sets.test.mjsnew file mode 100644index 0000000000..8f098b540b--- /dev/null+++ b/packages/cli/api/doctor/icon-sets.test.mjs@@ -0,0 +1,111 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Doctor's `icon-sets` check (AST-084 FR17).+ */++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 {checkIconSets, runChecks} from './doctor.mjs';+import {+ glyphsData,+ writeIconSetProject,+} from '../../test-utils/icon-set-fixture.mjs';++/** @type {string} */+let tmp;+beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-doctor-icons-'));+});+afterEach(() => {+ fs.rmSync(tmp, {recursive: true, force: true});+});++/** @param {Parameters<typeof writeIconSetProject>[1]} options */+async function iconCheckOf(options) {+ const cwd = writeIconSetProject(tmp, options);+ // A project declares Core, so doctor checks the project, not the computer.+ const pkgFile = path.join(cwd, 'package.json');+ const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));+ pkg.dependencies = {...pkg.dependencies, '@astryxdesign/core': '*'};+ fs.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2));+ const report = await runChecks({cwd});+ return report.checks.find(check => check.id === 'icon-sets');+}++describe('icon-sets check', () => {+ it('a project without experimental.iconSet has no check, sets installed or not', async () => {+ // Icon sets are experimental (spec:AST-017 FR27): the report is unchanged+ // until the project opts in.+ expect(await iconCheckOf({packages: []})).toBeUndefined();+ expect(await iconCheckOf({})).toBeUndefined();+ expect(+ await iconCheckOf({packages: [{}, {name: '@acme/lines'}]}),+ ).toBeUndefined();+ });++ it('the configured set installed passes', async () => {+ const check = await iconCheckOf({+ config: {experimental: {iconSet: 'glyphs'}},+ });+ expect(check).toMatchObject({status: 'pass'});+ expect(check?.message).toMatch(/experimental.iconSet names "glyphs"/);+ });++ it('experimental.iconSet that two packages ship warns, naming the qualified form', async () => {+ const check = await iconCheckOf({+ packages: [{}, {name: '@acme/lines', set: 'glyphs'}],+ config: {experimental: {iconSet: 'glyphs'}},+ });+ expect(check).toMatchObject({status: 'warn'});+ expect(check?.fix).toMatch(/experimental.iconSet/);+ });++ it('experimental.iconSet naming a set that is not installed fails', async () => {+ expect(+ await iconCheckOf({config: {experimental: {iconSet: 'nope'}}}),+ ).toMatchObject({+ status: 'fail',+ });+ });++ it('experimental.iconSet naming an installed set that was withdrawn fails, saying withdrawn and why', async () => {+ const invalid = await iconCheckOf({+ packages: [{data: '{nope'}],+ config: {experimental: {iconSet: 'glyphs'}},+ });+ expect(invalid).toMatchObject({status: 'fail'});+ expect(invalid?.message).toMatch(+ /names "glyphs", which is installed but withdrawn: .*not valid JSON/,+ );+ expect(invalid?.message).not.toMatch(/no installed set has that name/);+ fs.rmSync(tmp, {recursive: true, force: true});+ fs.mkdirSync(tmp);+ const unresolved = await iconCheckOf({+ packages: [{data: {...glyphsData(), module: '@acme/not-installed'}}],+ config: {experimental: {iconSet: '@acme/glyphs/glyphs'}},+ });+ expect(unresolved).toMatchObject({status: 'fail'});+ expect(unresolved?.message).toMatch(+ /installed but withdrawn: .*does not resolve from the project/,+ );+ });++ it('an invalid data file warns with the reason', async () => {+ const check = await iconCheckOf({+ packages: [{}, {name: '@acme/lines', data: '{nope'}],+ config: {experimental: {iconSet: 'glyphs'}},+ });+ expect(check).toMatchObject({status: 'warn'});+ expect(check?.message).toMatch(/not valid JSON/);+ });++ it('has no check when the project could not be read', () => {+ const check = checkIconSets(+ /** @type {any} */ ({cwd: tmp, iconSets: null, projectError: 'boom'}),+ );+ expect(check).toBeNull();+ });+});diff --git a/packages/cli/api/icon/_adapter.mjs b/packages/cli/api/icon/_adapter.mjsnew file mode 100644index 0000000000..4468e7ab25--- /dev/null+++ b/packages/cli/api/icon/_adapter.mjs@@ -0,0 +1,173 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The `icon` subject's adapter: its only access to the environment.+ * Loads the project and reads its icon sets through the `Project` seam.+ *+ * @position api/icon — adapter for api/icon/{search,detail,list,use,map,add,+ * new-set,new-definition}; it also carries the icon ranking, the icon-set+ * writer, the set and definition authoring writes, and the config writer+ * the leaves use+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {Project} from '../../foundation/config/project.mjs';+import {AstryxError} from '../error.mjs';+import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';+import {IconSetAuthoringError} from '../../foundation/discovery/icon-set-writer.mjs';+import {PathSafetyError} from '../../foundation/fs/path-safety.mjs';+import {isOutsideProject} from '../../foundation/env/project-scope.mjs';+import {projectIconSetCliWarning} from '../../foundation/integrations/cli-requirement.mjs';++export {+ iconRecord,+ importLine,+ leadingReading,+ matchIcon,+ rankIcons,+ scoreIcon,+} from '../../foundation/discovery/icon-ranking.mjs';+export {astryxIconDefinitions} from '../../foundation/discovery/icon-definition-discovery.mjs';+export {iconSetKey} from '../../foundation/discovery/icon-set-discovery.mjs';+export {setConfigString} from '../../foundation/config/config-writer.mjs';+export {+ assertIconExport,+ checkNewDefinition,+ definitionFile,+ findLocalIconSet,+ writeDefinitionFile,+ iconIdOf,+ closestNames,+ libraryIcons,+ mappableDefinitions,+ resolveIconSource,+ generatedModulePath,+ generatedNamesOf,+ iconExportName,+ iconNaming,+ modulePrefix,+ setModuleNote,+ variantExportName,+ writeGeneratedIcons,+ writeIconSetData,+ THEME_MAP_NAME,+} from '../../foundation/discovery/icon-set-writer.mjs';+export {exportValueKind} from '../../foundation/discovery/module-exports.mjs';+export {addIconDefinition, addIconSet} from './_authoring.mjs';++/**+ * Refuse a command that writes to a project or package when `cwd` is outside+ * any project and no package.json is at or above it (spec AST-081 FR3): it+ * writes nothing and says what it needs.+ * @param {string} cwd+ * @param {string} command the command, without `astryx`+ * @param {string} where what to run it in+ */+export function refuseOutsideProject(cwd, command, where) {+ // A folder with a package.json at or above it is a package being authored,+ // even before it declares Astryx; that package's own checks answer there.+ if (!isOutsideProject(cwd) || hasPackageJsonAbove(cwd)) return;+ throw new AstryxError(+ `astryx ${command} works only in a project. Run it in ${where}.`,+ [],+ ERROR_CODES.ERR_PROJECT_REQUIRED,+ );+}++/**+ * Is there a package.json in `dir` or a folder above it?+ * @param {string} dir+ */+function hasPackageJsonAbove(dir) {+ for (let at = path.resolve(dir); ; at = path.dirname(at)) {+ if (fs.existsSync(path.join(at, 'package.json'))) return true;+ if (path.dirname(at) === at) return false;+ }+}++/**+ * Run one authoring step, turning its errors into AstryxErrors.+ * @template T+ * @param {() => T | Promise<T>} step+ * @returns {Promise<T>}+ */+export async function authoring(step) {+ try {+ return await step();+ } catch (error) {+ if (error instanceof IconSetAuthoringError) {+ throw new AstryxError(+ error.message,+ error.suggestions,+ /** @type {any} */ (ERROR_CODES)[error.code] ??+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ // A path that leaves the package (a source, the sets root) is refused+ // with the stable code every writer uses.+ if (error instanceof PathSafetyError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_PATH_TRAVERSAL,+ );+ }+ throw error;+ }+}++/**+ * The project's installed icon sets, in tie order, with the sets withdrawn+ * and the project's icon-set choice.+ * @param {string} cwd+ */+export async function loadIconSets(cwd) {+ const project = await Project.load(cwd);+ return project.iconSets({experimental: true});+}++/**+ * The project directory, its installed icon sets, and the sets withdrawn,+ * for `experimental icon use`.+ * @param {string} cwd+ */+export async function loadIconProject(cwd) {+ const project = await Project.load(cwd);+ const {sets, withdrawn} = await project.iconSets({experimental: true});+ return {projectDir: findProjectDir(cwd), sets, withdrawn};+}++/**+ * The nearest directory at or above `cwd` with a package.json, else `cwd`.+ * @param {string} cwd+ */+function findProjectDir(cwd) {+ let dir = path.resolve(cwd);+ for (let depth = 0; depth < 50; depth++) {+ if (fs.existsSync(path.join(dir, 'package.json'))) return dir;+ const parent = path.dirname(dir);+ if (parent === dir) break;+ dir = parent;+ }+ return path.resolve(cwd);+}++/**+ * Why a CLI the project may run would refuse its astryx.config once it sets+ * `experimental.iconSet`, read from the project's package.json; null when+ * nothing says so.+ * @param {string} projectDir+ * @returns {string | null}+ */+export function iconSetConfigCliWarning(projectDir) {+ let pkg;+ try {+ pkg = JSON.parse(+ fs.readFileSync(path.join(projectDir, 'package.json'), 'utf-8'),+ );+ } catch {+ return null;+ }+ return projectIconSetCliWarning(pkg);+}diff --git a/packages/cli/api/icon/_authoring.mjs b/packages/cli/api/icon/_authoring.mjsnew file mode 100644index 0000000000..9061dc56c6--- /dev/null+++ b/packages/cli/api/icon/_authoring.mjs@@ -0,0 +1,628 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Icon-set authoring writes (spec:AST-084 FR13): start a set and add+ * one of its own icon definitions in the local integration package. Every+ * file it reads or writes goes through here; it is imported only by the+ * `icon` subject's adapter (architecture:cli-surface INV21).+ *+ * @position api/icon — helper of api/icon/_adapter.mjs, read by+ * api/icon/new-set and api/icon/new-definition+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {AstryxError} from '../error.mjs';+import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';+import {+ assertWithin,+ PathSafetyError,+ sanitizeName,+} from '../../foundation/fs/path-safety.mjs';+import {+ findLocalIntegrationManifestOrNull,+ IntegrationRootConflictError,+ patchIntegrationRoot,+} from '../../foundation/integrations/manifest-writer.mjs';+import {loadManifestObject} from '../../foundation/integrations/integrations.mjs';+import {assertContributionVisible} from '../../foundation/integrations/contribution-inventory.mjs';+import {+ IconSetAuthoringError,+ checkNewDefinition,+ definitionFile,+ findLocalIconSet,+ generatedModulePath,+ generatedModuleText,+ generatedTypesPath,+ THEME_MAP_NAME,+ iconSetDataText,+ libraryIcons,+ resolveIconSource,+ setModuleNote,+ writeDefinitionFile,+ writeGeneratedIcons,+ writeIconSetData,+} from '../../foundation/discovery/icon-set-writer.mjs';+import {astryxIconDefinitions} from '../../foundation/discovery/icon-definition-discovery.mjs';+import {+ KEBAB_NAME_RE,+ applyWrites,+ kebabToTitle,+ loadCurrentManifest,+ packageJsonUpdate,+ projectPath,+ receipt,+ resolvePackage,+} from '../integration/add-helpers.mjs';++/** Where a package's icon sets go when its manifest declares none. */+const DEFAULT_ICON_SETS_ROOT = './icon-sets';++/** Where an icon set's root is declared: an experimental manifest key. */+const ICON_SETS_ROOT_KEY = 'experimental.iconSets';++// ── Icon set ────────────────────────────────────────────────────────++/**+ * A single-quoted JavaScript string literal for any text.+ * @param {string} value+ */+function quoteJs(value) {+ return `'${value+ .replace(/\\/gu, '\\\\')+ .replace(/'/gu, "\\'")+ .replace(/\n/gu, '\\n')+ .replace(/\r/gu, '\\r')}'`;+}++/**+ * Write one icon set (spec:AST-084 FR1–FR3): `<root>/<name>/<name>.doc.mjs`,+ * a typed IconSetDoc, and a starter `<name>.icons.json` whose `module` is the+ * package itself, with no icons and an empty `map`. The set is valid and+ * discoverable; `integration check` then names every built-in icon+ * definition it still has to map.+ * @param {string} name icon set name (kebab-case)+ * @param {{cwd?: string, dryRun?: boolean, from?: string, exclude?: string[] | string}} options+ * @returns {Promise<{type: 'integration.add', data: import('./icon.type.mjs').IconNewData}>}+ */+export async function addIconSet(name, options) {+ const {cwd = process.cwd(), dryRun = false, from} = options;+ const exclude =+ typeof options.exclude === 'string'+ ? options.exclude+ .split(',')+ .map(each => each.trim())+ .filter(Boolean)+ : (options.exclude ?? []);+ if (exclude.length > 0 && from == null) {+ throw new AstryxError(+ '--exclude names library exports to leave out, so it needs --from.',+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ if (!KEBAB_NAME_RE.test(name)) {+ throw new AstryxError(+ `Invalid icon set name "${name}": use lowercase kebab-case starting with a letter.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ try {+ sanitizeName(name, {label: 'icon set name'});+ } catch (error) {+ if (error instanceof PathSafetyError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ throw error;+ }++ const {packageDir, packageFile, pkg, owner, manifestFile, manifestExists} =+ resolvePackage(cwd);+ if (typeof pkg.name !== 'string' || pkg.name.trim() === '') {+ throw new AstryxError(+ 'package.json has no name. An icon set imports its icons from its own package, so the package needs a name first.',+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ const manifest = await loadCurrentManifest(manifestFile, manifestExists);+ const rootPath = manifest.experimental?.iconSets ?? DEFAULT_ICON_SETS_ROOT;+ /** @type {string} */+ let root;+ try {+ root = assertWithin(rootPath, packageDir, {+ label: 'experimental.iconSets root',+ });+ } catch (error) {+ if (error instanceof PathSafetyError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_PATH_TRAVERSAL,+ );+ }+ throw error;+ }++ try {+ await patchIntegrationRoot(packageDir, ICON_SETS_ROOT_KEY, rootPath, {+ dryRun: true,+ createIfMissing: true,+ });+ } catch (error) {+ if (error instanceof IntegrationRootConflictError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,+ );+ }+ throw error;+ }++ const setDir = assertWithin(name, root, {label: 'icon set directory'});+ const docFile = assertWithin(`${name}.doc.mjs`, setDir, {+ label: 'icon set descriptor',+ });+ const dataFile = assertWithin(`${name}.icons.json`, setDir, {+ label: 'icon set data file',+ });+ // Wrapping a library again refreshes the set's icons in place.+ if (from != null && fs.existsSync(docFile) && fs.existsSync(dataFile)) {+ return refreshIconSet(name, {+ cwd,+ dryRun,+ from,+ exclude,+ packageDir,+ rootPath,+ manifestPath: projectPath(path.relative(packageDir, manifestFile)),+ });+ }+ for (const file of [docFile, dataFile]) {+ if (fs.existsSync(file)) {+ throw new AstryxError(+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, file))}.`,+ undefined,+ ERROR_CODES.ERR_FILE_EXISTS,+ );+ }+ }++ // The set's generated icons module, with its theme map, starts empty; with+ // --from, every component the library exports becomes an icon in it.+ const generated = `./${projectPath(path.relative(packageDir, path.join(setDir, `${name}.generated.js`)))}`;+ /** @type {Array<{id: string, export: string, words: string[]}>} */+ let icons = [];+ /** @type {Record<string, string>} */+ let map = {};+ /** @type {import('../../foundation/discovery/icon-set-writer.mjs').GeneratedIcon[]} */+ let exportsToWrite = [];+ if (from != null) {+ const source = await iconAuthoring(() =>+ resolveIconSource(from, {packageDir, pkg}),+ );+ const found = libraryIcons(source.file, {exclude});+ if (found.length === 0) {+ throw new AstryxError(+ `"${from}" exports no icon components this command can read. If its icons are data (objects or SVG strings), run \`astryx experimental icon new-set ${name}\`, declare an "adapter" in ${name}.icons.json, and run this command again; or add icons one at a time with \`astryx experimental icon add <Export> --from ${from}\`.`,+ undefined,+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }+ icons = found.map(icon => ({+ id: icon.id,+ export: icon.name,+ words: icon.id.split('-'),+ }));+ map = exactDefinitionMap(icons, {});+ exportsToWrite = found.map(icon => ({+ name: icon.name,+ from: source.module,+ source: icon.export,+ adapt: icon.adapt,+ }));+ }+ const data = {+ schemaVersion: /** @type {const} */ (1),+ module: pkg.name,+ generated,+ themeMap: THEME_MAP_NAME,+ map,+ icons,+ };+ const generatedText = await iconAuthoring(() =>+ generatedModuleText(packageDir, generated, null, data, exportsToWrite),+ );++ const displayName = kebabToTitle(name);+ // The artwork license defaults to the package's own license; the author+ // edits it when the artwork comes from elsewhere.+ const license =+ typeof pkg.license === 'string' && pkg.license.trim() !== ''+ ? pkg.license+ : 'UNLICENSED';+ const docContents = [+ "/** @type {import('@astryxdesign/cli/authoring').IconSetDoc} */",+ 'export default {',+ " type: 'icon-set',",+ ` name: ${quoteJs(name)},`,+ ` displayName: ${quoteJs(displayName)},`,+ ` description: ${quoteJs(`${displayName} icons.`)},`,+ ' maintained: true,',+ ` license: ${quoteJs(license)},`,+ '};',+ '',+ ].join('\n');+ const dataContents = iconSetDataText(data);++ /** @type {import('../integration/add-helpers.mjs').WritePlan[]} */+ const plans = [+ {path: docFile, contents: docContents, createOnly: true},+ {path: dataFile, contents: dataContents, createOnly: true},+ ];+ plans.push({+ path: assertWithin(generated, packageDir, {+ label: 'generated icons module',+ }),+ contents: generatedText.js,+ createOnly: true,+ });+ const typesPath = generatedTypesPath(generated);+ if (typesPath && generatedText.dts != null) {+ plans.push({+ path: assertWithin(typesPath, packageDir, {+ label: 'generated icon types',+ }),+ contents: generatedText.dts,+ createOnly: true,+ });+ }+ const pkgUpdate = packageJsonUpdate(+ packageFile,+ rootPath,+ path.basename(manifestFile),+ );+ if (pkgUpdate != null) {+ plans.push({+ path: packageFile,+ contents: pkgUpdate.contents,+ createOnly: false,+ expectedOriginal: pkgUpdate.expectedOriginal,+ });+ }++ const writtenFiles = plans.map(p =>+ projectPath(path.relative(packageDir, p.path)),+ );+ const manifestPath = projectPath(path.relative(packageDir, manifestFile));++ let rootReceipt = {+ path: rootPath,+ created: !manifest.experimental?.iconSets,+ };+ if (!dryRun) {+ let rollback = () => {};+ try {+ rollback = applyWrites(plans);+ rootReceipt = await patchIntegrationRoot(+ packageDir,+ ICON_SETS_ROOT_KEY,+ rootPath,+ {+ createIfMissing: true,+ verify: async () => {+ const m = await loadManifestObject(manifestFile, 'verify', {+ fresh: true,+ });+ const declared = m.experimental?.iconSets;+ if (!declared)+ throw new Error(+ 'experimental.iconSets root not visible after writing.',+ );+ const setsRoot = assertWithin(declared, packageDir, {+ label: 'experimental.iconSets root',+ });+ await assertContributionVisible(+ {name: owner, iconSets: setsRoot},+ 'icon-set',+ name,+ );+ },+ },+ );+ } catch (error) {+ rollback();+ if (error instanceof IntegrationRootConflictError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,+ );+ }+ if (error instanceof AstryxError) throw error;+ throw new AstryxError(+ `Failed to write icon-set contribution: ${error instanceof Error ? error.message : String(error)}`,+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }+ }+ if (rootReceipt.created && !writtenFiles.includes(manifestPath)) {+ writtenFiles.push(manifestPath);+ }+ const result = receipt(+ 'icon-set',+ name,+ rootReceipt,+ manifestPath,+ writtenFiles,+ dryRun,+ );+ {+ result.data.icons = icons.length;+ // The line goes in the package's entry file, relative to it: the+ // generated path is relative to the package root, which the entry need+ // not be (exports → ./src/index.js).+ const moduleNote = setModuleNote(+ /** @type {import('../../foundation/discovery/icon-set-discovery.mjs').DiscoveredIconSet} */ (+ /** @type {unknown} */ ({data: {module: pkg.name}})+ ),+ {packageDir, pkg},+ generated,+ THEME_MAP_NAME,+ );+ result.data.notes = [+ ...(moduleNote ? [moduleNote] : []),+ 'Run `astryx integration check` to see the icon definitions still to map.',+ ];+ }+ return result;+}++/**+ * The `map` entries an exact hit gives: each Astryx definition whose name, or+ * one of whose words, is an icon's id. Entries the map already has are kept.+ * @param {Array<{id: string}>} icons+ * @param {Record<string, string>} map+ */+function exactDefinitionMap(icons, map) {+ const ids = new Set(icons.map(icon => icon.id));+ /** @type {Record<string, string>} */+ const next = {...map};+ for (const {doc} of astryxIconDefinitions().definitions) {+ if (next[doc.name]) continue;+ const kebab = doc.name+ .replace(/([a-z0-9])([A-Z])/gu, '$1-$2')+ .toLowerCase();+ const hit = [+ kebab,+ ...doc.words.map(word => word.replace(/\s+/gu, '-')),+ ].find(candidate => ids.has(candidate));+ if (hit) next[doc.name] = hit;+ }+ return next;+}++/**+ * Run an icon-set authoring step, turning its errors into AstryxErrors.+ * @template T+ * @param {() => T | Promise<T>} step+ * @returns {Promise<T>}+ */+async function iconAuthoring(step) {+ try {+ return await step();+ } catch (error) {+ if (error instanceof IconSetAuthoringError) {+ throw new AstryxError(+ error.message,+ error.suggestions,+ /** @type {any} */ (ERROR_CODES)[error.code] ??+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ if (error instanceof PathSafetyError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_PATH_TRAVERSAL,+ );+ }+ throw error;+ }+}++/**+ * Wrap a library into an existing set again: its icons are replaced by what+ * the library exports now (an icon whose words the author extended keeps+ * them), the generated module gains the new exports, `map` keeps every entry+ * whose icon still exists, and the receipt names the entries that lost theirs.+ * @param {string} name+ * @param {{cwd: string, dryRun: boolean, from: string, exclude: string[], packageDir: string, rootPath: string, manifestPath: string}} options+ */+async function refreshIconSet(+ name,+ {cwd, dryRun, from, exclude, packageDir, rootPath, manifestPath},+) {+ return iconAuthoring(async () => {+ const where = await findLocalIconSet(cwd, name);+ const {set} = where;+ const source = resolveIconSource(from, where);+ const found = libraryIcons(source.file, {+ adapter: Boolean(set.data.adapter),+ exclude,+ });+ const previous = new Map(set.data.icons.map(icon => [icon.id, icon]));+ const icons = found.map(icon => {+ const prior = previous.get(icon.id);+ return {+ ...(prior ?? {}),+ id: icon.id,+ export: icon.name,+ words: [...new Set([...icon.id.split('-'), ...(prior?.words ?? [])])],+ };+ });+ const ids = new Set(icons.map(icon => icon.id));+ /** @type {Record<string, string>} */+ const kept = {};+ /** @type {string[]} */+ const lost = [];+ for (const [definition, id] of Object.entries(set.data.map ?? {})) {+ if (ids.has(id)) kept[definition] = id;+ else lost.push(`${definition} -> "${id}"`);+ }+ const generated = generatedModulePath(set, packageDir);+ const next = {+ ...set.data,+ generated,+ ...(set.data.themeMap ? {} : {themeMap: THEME_MAP_NAME}),+ map: exactDefinitionMap(icons, kept),+ icons,+ };+ /** @type {string[]} */+ const files = [];+ if (!dryRun) {+ const written = writeGeneratedIcons(+ packageDir,+ generated,+ next,+ found.map(icon => ({+ name: icon.name,+ from: source.module,+ source: icon.export,+ adapt: icon.adapt,+ })),+ // The icons the library no longer has leave the module too.+ set.data.icons+ .filter(icon => !ids.has(icon.id))+ .map(icon => icon.export),+ );+ files.push(...written.files);+ try {+ writeIconSetData(set, next);+ } catch (error) {+ written.undo();+ throw error;+ }+ }+ files.push(projectPath(path.relative(packageDir, set.dataPath)));+ const result = receipt(+ 'icon-set',+ name,+ {path: rootPath, created: false},+ manifestPath,+ files,+ dryRun,+ );+ result.data.icons = icons.length;+ result.data.notes = [+ ...(lost.length > 0+ ? [+ `These map entries named icons the library no longer exports and were removed: ${lost.join(', ')}.`,+ ]+ : []),+ 'Run `astryx integration check` to see the icon definitions still to map.',+ ];+ return result;+ });+}++// ── Icon definition ─────────────────────────────────────────────────++/**+ * Add one of an icon set's own icon definitions (AST-084):+ * `<set>/definitions/<name>.doc.mjs`, a typed IconDefinitionDoc, and, with+ * `icon`, the set's `map` entry for it. A name Astryx already has is refused:+ * map to Astryx's definition instead.+ * @param {string} name camelCase definition name+ * @param {{cwd?: string, dryRun?: boolean, set?: string, description?: string, words?: string[] | string, icon?: string}} options+ * @returns {Promise<{type: 'integration.add', data: import('./icon.type.mjs').IconNewData}>}+ */+export async function addIconDefinition(name, options) {+ const {+ cwd = process.cwd(),+ dryRun = false,+ set: selector,+ description,+ icon,+ } = options;+ const words =+ typeof options.words === 'string'+ ? options.words.split(',')+ : options.words;+ return iconAuthoring(async () => {+ const where = await findLocalIconSet(cwd, selector);+ const {packageDir, set} = where;+ const doc = checkNewDefinition(set, {name, description, words});+ const file = definitionFile(set, doc.name);+ if (fs.existsSync(file)) {+ throw new AstryxError(+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, file))}.`,+ undefined,+ ERROR_CODES.ERR_FILE_EXISTS,+ );+ }+ if (icon != null && !set.data.icons.some(each => each.id === icon)) {+ throw new AstryxError(+ `Icon set "${set.name}" has no icon "${icon}".`,+ set.data.icons+ .map(each => each.id)+ .filter(id => id.includes(icon) || icon.includes(id))+ .slice(0, 5)+ .map(id => ({name: id, reason: 'an icon in this set'})),+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }+ const files = [projectPath(path.relative(packageDir, file))];+ if (icon != null)+ files.push(projectPath(path.relative(packageDir, set.dataPath)));+ if (!dryRun) {+ const undo = writeDefinitionFile(set, doc);+ let undoMap = () => {};+ if (icon != null) {+ try {+ undoMap = writeIconSetData(+ set,+ {...set.data, map: {...(set.data.map ?? {}), [doc.name]: icon}},+ {extraDefinitions: [doc.name]},+ );+ } catch (error) {+ undo();+ throw error;+ }+ }+ // Discovery reads the set, its new definition included, or every+ // write is undone: the data file first, then the definition.+ try {+ await findLocalIconSet(cwd, set.name);+ } catch (error) {+ undoMap();+ undo();+ throw error;+ }+ }+ return receipt(+ 'icon-definition',+ doc.name,+ {+ path: `./${projectPath(path.relative(packageDir, where.root))}`,+ created: false,+ },+ projectPath(+ path.relative(+ packageDir,+ findLocalIntegrationManifestOrNull(packageDir) ??+ path.join(packageDir, 'astryx.integration.mjs'),+ ),+ ),+ files,+ dryRun,+ );+ });+}diff --git a/packages/cli/api/icon/_options.mjs b/packages/cli/api/icon/_options.mjsnew file mode 100644index 0000000000..3cf33b2976--- /dev/null+++ b/packages/cli/api/icon/_options.mjs@@ -0,0 +1,41 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The options each icon authoring call takes; any other is refused, so+ * a caller never gets a silent success that did not do what it asked.+ *+ * @position api/icon — read by api/icon/new-set and api/icon/new-definition+ */++import {AstryxError} from '../error.mjs';+import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';++/** The options each call takes. */+const ALLOWED = {+ 'icon-set': new Set(['cwd', 'dryRun', 'from', 'exclude']),+ 'icon-definition': new Set([+ 'cwd',+ 'dryRun',+ 'set',+ 'description',+ 'words',+ 'icon',+ ]),+};++/**+ * Refuse an option the call does not take.+ * @param {keyof typeof ALLOWED} kind+ * @param {Record<string, unknown>} options+ */+export function refuseOtherOptions(kind, options) {+ for (const [key, value] of Object.entries(options)) {+ if (value !== undefined && !ALLOWED[kind].has(key)) {+ throw new AstryxError(+ `Option "${key}" does not apply to integration kind "${kind}".`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ }+}diff --git a/packages/cli/api/icon/_records.mjs b/packages/cli/api/icon/_records.mjsnew file mode 100644index 0000000000..a4c7729ef5--- /dev/null+++ b/packages/cli/api/icon/_records.mjs@@ -0,0 +1,69 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Pure icon records, ranking, and lookups for the `icon` leaves+ * (AST-084 FR6, FR7). No environment access: the leaves pass in the sets the+ * adapter read.+ *+ * The ranking itself lives in foundation/discovery/icon-ranking.mjs, which+ * the icon-set checks' suggestions read too; this module re-exports it.+ *+ * @position api/icon — shared by the search, detail, and list leaves+ */++import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';+export {+ iconRecord,+ importLine,+ leadingReading,+ matchIcon,+ rankIcons,+ scoreIcon,+} from './_adapter.mjs';++/** @typedef {import('../../foundation/discovery/icon-set-discovery.mjs').DiscoveredIconSet} DiscoveredIconSet */+/** @typedef {import('../../authoring/doctypes/icon-set/type').IconSetIcon} IconSetIcon */+/** @typedef {import('./icon.type.mjs').IconRecord} IconRecord */+/** @typedef {import('./icon.type.mjs').IconMatchEntry} IconMatchEntry */++/**+ * The installed sets a selector names: `<package>/<set>`, else a set name.+ * @template {{name: string, package: string}} T+ * @param {T[]} sets+ * @param {string} selector+ * @returns {T[]}+ */+export function setsNamed(sets, selector) {+ const exact = sets.filter(set => `${set.package}/${set.name}` === selector);+ return exact.length > 0 ? exact : sets.filter(set => set.name === selector);+}++/**+ * Why a selector that names no valid set names nothing usable, when it names+ * an installed set that was withdrawn (invalid, or its module does not+ * resolve); null when it names no installed set at all (FR17).+ * @param {Array<{name: string, package: string, reason: string}>} withdrawn+ * @param {string} selector+ * @returns {string | null}+ */+export function withdrawnReason(withdrawn, selector) {+ const named = setsNamed(withdrawn, selector);+ return named.length > 0+ ? `Icon set "${selector}" is installed but withdrawn: ${named.map(each => each.reason).join(' ')}`+ : null;+}++/**+ * Suggestions for a name that matched nothing: the closest candidates first.+ * @param {string} wanted+ * @param {string[]} candidates+ * @param {string} reason+ * @param {number} [max]+ */+export function closest(wanted, candidates, reason, max = 5) {+ return [...new Set(candidates)]+ .map(name => ({name, distance: levenshteinDistance(wanted, name)}))+ .sort((a, b) => a.distance - b.distance || a.name.localeCompare(b.name))+ .slice(0, max)+ .map(({name}) => ({name, reason}));+}diff --git a/packages/cli/api/icon/add/add.mjs b/packages/cli/api/icon/add/add.mjsnew file mode 100644index 0000000000..959042e7c7--- /dev/null+++ b/packages/cli/api/icon/add/add.mjs@@ -0,0 +1,416 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `icon.add` and `icon.definitionMatches` leaf (AST-084 FR13): register+ * one icon the caller chose from a source module, against an icon+ * definition.+ *+ * The caller (usually an agent that knows the library) picks the export; the+ * CLI never searches the source library. It proves the export is a runtime+ * component of the source module, read statically, and then:+ * - with no definition flag, answers the definitions that fit the export+ * (`icon.definitionMatches`), Astryx's and the set's own, ranked by the+ * icon lookup's scorer, and writes nothing;+ * - with `definition`, adds the icon (or a variant of an existing icon)+ * and maps the definition to it. The icon becomes an export of the set's+ * generated icons module (`generated`): a re-export of a component, or,+ * for anything else, the set's `adapter` applied to it. The data file+ * names the set's own module, so every reader gets a component;+ * - with `newDefinition`, writes the set's own definition file first.+ * Running it again with the same arguments changes nothing.+ *+ * @output the `icon.add` or `icon.definitionMatches` envelope+ * @position api/icon/add — dispatched by the `experimental icon add` command+ */++import * as path from 'node:path';+import {AstryxError} from '../../error.mjs';+import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';+import {+ assertIconExport,+ astryxIconDefinitions,+ authoring,+ checkNewDefinition,+ closestNames,+ findLocalIconSet,+ iconIdOf,+ mappableDefinitions,+ exportValueKind,+ generatedModulePath,+ generatedNamesOf,+ iconNaming,+ modulePrefix,+ variantExportName,+ rankIcons,+ resolveIconSource,+ setModuleNote,+ writeGeneratedIcons,+ THEME_MAP_NAME,+ writeDefinitionFile,+ writeIconSetData,+ refuseOutsideProject,+} from '../_adapter.mjs';++/** The lowest score a definition match needs: an exact word or name. */+const FIT_FLOOR = 80;++/** How many definition matches the answer lists. */+const MATCH_LIMIT = 10;++/**+ * Register one icon in the set being authored, or list the definitions that+ * fit it.+ * Experimental (spec:AST-017 FR27): may change or be removed in a patch+ * release.+ * @experimental+ * @param {string} exportName the export the set exposes the icon as+ * @param {import('../icon.type.mjs').IconAddOptions} options+ * @returns {Promise<import('../icon.type.mjs').IconAddResponse | import('../icon.type.mjs').IconDefinitionMatchesResponse>}+ */+export async function iconAdd(exportName, options) {+ const {+ cwd = process.cwd(),+ from,+ set: selector,+ definition,+ newDefinition,+ description,+ words,+ useDefault = false,+ variant,+ id: givenId,+ } = options ?? {};+ refuseOutsideProject(cwd, 'experimental icon add', 'the icon-set package');+ return authoring(async () => {+ if (+ typeof exportName !== 'string' ||+ !/^[$A-Z_a-z][$\w]*$/u.test(exportName)+ ) {+ throw new AstryxError(+ `Name the icon's export, such as TrashIcon; received "${String(exportName)}".`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ if (typeof from !== 'string' || from.trim() === '') {+ throw new AstryxError(+ 'Pass --from with the module the icon is exported from: a package, a package subpath, or a relative path in this package.',+ undefined,+ ERROR_CODES.ERR_MISSING_ARGUMENT,+ );+ }+ if (definition != null && newDefinition != null) {+ throw new AstryxError(+ 'Pass --definition or --new-definition, not both.',+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ const where = await findLocalIconSet(cwd, selector);+ const {packageDir, set} = where;+ const source = resolveIconSource(from, where);+ const sourceExport = useDefault ? 'default' : exportName;+ assertIconExport(source.file, source.module, sourceExport);++ // A component is re-exported; anything else goes through the set's+ // adapter. Either way the icon is an export of the set's own module.+ const adapt = exportValueKind(source.file, sourceExport) !== 'component';+ if (adapt && !set.data.adapter) {+ throw new AstryxError(+ `"${sourceExport}" in "${source.module}" is not a component, so this set needs an adapter: a function in your package that turns it into one. Declare "adapter": {"module": "./src/adapt.js", "export": "adapt"} in ${set.name}.icons.json (astryx docs cli/experimental/icon-sets library-shapes).`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ const generated = generatedModulePath(set, packageDir);+ const module = set.data.module;+ // A library prefix every icon export shares (`feather` in `featherEye`)+ // is left out of the id and the set's export name, as the bulk wrap does.+ const shared = useDefault+ ? []+ : modulePrefix(source.file, {adapter: Boolean(set.data.adapter)});+ const nameWords = iconIdOf(exportName).split('-');+ const prefix =+ shared.length > 0 &&+ nameWords.length > shared.length &&+ shared.every((word, index) => nameWords[index] === word)+ ? shared+ : [];+ // A library export the set already has keeps its icon's name and id.+ const already = generatedNamesOf(+ packageDir,+ generated,+ source.module,+ sourceExport,+ );+ const known = set.data.icons.find(each => already.includes(each.export));+ const naming = known+ ? {id: known.id, name: known.export}+ : iconNaming(exportName, prefix);+ const id = givenId ?? naming.id;+ const asVariant = variant != null;+ // The name the set exports it as: `<Name>Icon`, or for a variant the+ // icon's name with the variant's name.+ const baseIcon = set.data.icons.find(each => each.id === id);+ const setName = asVariant+ ? variantExportName(baseIcon?.export ?? naming.name, variant)+ : naming.name;+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(id)) {+ throw new AstryxError(+ `"${exportName}" gives no icon id; pass --id with a lower-kebab id.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }++ if (definition == null && newDefinition == null && !asVariant) {+ return definitionMatches(set, exportName, from, id);+ }++ /** @type {{name: string, description: string, words: string[]} | null} */+ let created = null;+ let mapped = definition ?? newDefinition ?? null;+ if (newDefinition != null) {+ const own = set.definitions.find(each => each.doc.name === newDefinition);+ if (own) {+ mapped = own.doc.name;+ } else {+ created = checkNewDefinition(set, {+ name: newDefinition,+ description,+ words,+ });+ }+ } else if (+ definition != null &&+ !mappableDefinitions(set).has(definition)+ ) {+ throw new AstryxError(+ `"${definition}" is not an icon definition.`,+ [+ ...closestNames(definition, [...mappableDefinitions(set)]).map(+ name => ({+ name: `--definition ${name}`,+ reason: 'a known icon definition',+ }),+ ),+ {+ name: `--new-definition ${definition} --description '<what it is for>' --words a,b`,+ reason: 'add it as your own definition',+ },+ ],+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }+ // The icon keeps only its own words: search also matches it by the+ // words of every definition it is mapped to, so they are not copied.+ const icons = set.data.icons.map(each => ({...each}));+ const existing = icons.find(each => each.id === id);+ if (asVariant) {+ if (!existing) {+ throw new AstryxError(+ `Icon set "${set.name}" has no icon "${id}" to add a variant to. Add the icon first, or pass --id.`,+ closestNames(+ id,+ icons.map(each => each.id),+ ).map(name => ({+ name: `--id ${name}`,+ reason: 'an icon in this set',+ })),+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }+ const variants = [...(existing.variants ?? [])];+ const same = variants.find(each => each.export === setName);+ if (!same) {+ variants.push({variant, export: setName});+ existing.variants = variants;+ }+ } else if (existing) {+ if (+ existing.export !== setName ||+ (existing.module ?? set.data.module) !== module+ ) {+ throw new AstryxError(+ `Icon set "${set.name}" already has an icon "${id}" (${existing.export}). Pass --id to add this one under another id.`,+ undefined,+ ERROR_CODES.ERR_FILE_EXISTS,+ );+ }+ } else {+ icons.push({+ id,+ export: setName,+ words: id.split('-'),+ });+ }+ const map = {...(set.data.map ?? {})};+ if (mapped) map[mapped] = id;++ const next = {+ ...set.data,+ ...(set.data.generated ? {} : {generated}),+ ...(set.data.themeMap ? {} : {themeMap: THEME_MAP_NAME}),+ map,+ icons,+ };+ /** @type {string[]} */+ const files = [];+ // Every write happens inside this try, so any failure undoes the ones+ // before it and leaves every file as it was (AST-084 FR13).+ let undoDefinition = () => {};+ let undoGenerated = () => {};+ /** @type {boolean} */+ let generatedChanged;+ try {+ if (created) undoDefinition = writeDefinitionFile(set, created);+ const written = writeGeneratedIcons(packageDir, generated, next, [+ {name: setName, from: source.module, source: sourceExport, adapt},+ ]);+ undoGenerated = written.undo;+ generatedChanged = written.changed;+ files.push(...written.files);+ if (created) {+ files.push(+ path+ .relative(+ packageDir,+ path.join(set.dir, 'definitions', `${created.name}.doc.mjs`),+ )+ .split(path.sep)+ .join('/'),+ );+ }+ if (JSON.stringify(next) !== JSON.stringify(set.data)) {+ writeIconSetData(set, next, {+ extraDefinitions: created ? [created.name] : [],+ });+ files.push(+ path.relative(packageDir, set.dataPath).split(path.sep).join('/'),+ );+ }+ } catch (error) {+ undoGenerated();+ undoDefinition();+ if (error instanceof Error && /is not in variants/u.test(error.message)) {+ throw new AstryxError(+ `${error.message} Declare it in "variants" in ${set.name}.icons.json first.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ throw error;+ }+ const changed =+ JSON.stringify(next) !== JSON.stringify(set.data) ||+ created != null ||+ generatedChanged;+ const note = setModuleNote(set, where, generated, setName);+ return {+ type: /** @type {const} */ ('icon.add'),+ data: {+ set: set.name,+ package: set.package,+ icon: {id, export: setName, module},+ ...(asVariant ? {variant} : {}),+ definition: mapped,+ ...(created ? {newDefinition: created.name} : {}),+ files,+ changed,+ ...(note ? {note} : {}),+ },+ };+ });+}++/**+ * The definitions that fit an export, Astryx's and the set's own, ranked by+ * the icon lookup's scorer: each word of the export's name is a query+ * against every definition's name and words; a definition keeps its best.+ * @param {import('../../../foundation/discovery/icon-set-discovery.mjs').DiscoveredIconSet} set+ * @param {string} exportName+ * @param {string} from+ * @param {string} id+ * @returns {import('../icon.type.mjs').IconDefinitionMatchesResponse}+ */+function definitionMatches(set, exportName, from, id) {+ const astryx = astryxIconDefinitions().definitions.map(each => ({+ doc: each.doc,+ source: /** @type {const} */ ('astryx'),+ }));+ const own = set.definitions+ .filter(each => !astryx.some(a => a.doc.name === each.doc.name))+ .map(each => ({doc: each.doc, source: /** @type {const} */ ('set')}));+ const all = [...astryx, ...own];+ // Each definition reads as an icon: its name's words as the id, then its+ // words, so the lookup's tiers apply unchanged.+ const asSet = /** @type {any} */ ({+ name: 'definitions',+ package: set.package,+ data: {+ module: set.data.module,+ icons: all.map(({doc}) => ({+ id: doc.name.replace(/([a-z0-9])([A-Z])/gu, '$1-$2').toLowerCase(),+ export: doc.name,+ words: [+ ...doc.name+ .replace(/([a-z0-9])([A-Z])/gu, '$1 $2')+ .toLowerCase()+ .split(' '),+ ...doc.words,+ ],+ })),+ },+ });+ const queries = [+ id.replace(/-/gu, ' '),+ ...id.split('-').filter(word => /[a-z]/u.test(word)),+ ];+ /** @type {Map<string, {score: number, reason: string}>} */+ const best = new Map();+ for (const query of queries) {+ for (const match of rankIcons([asSet], query)) {+ const prior = best.get(match.export);+ if (!prior || match.score > prior.score) {+ best.set(match.export, {score: match.score, reason: match.reason});+ }+ }+ }+ const base = `astryx experimental icon add ${exportName} --from ${from}`;+ const matches = all+ .filter(({doc}) => best.has(doc.name))+ .map(({doc, source}) => {+ const hit = /** @type {{score: number, reason: string}} */ (+ best.get(doc.name)+ );+ return {+ name: doc.name,+ description: doc.description,+ source,+ score: hit.score,+ reason: hit.reason,+ command: `${base} --definition ${doc.name}`,+ };+ })+ .sort(+ (a, b) =>+ b.score - a.score ||+ (a.source === b.source ? 0 : a.source === 'astryx' ? -1 : 1) ||+ (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),+ )+ .slice(0, MATCH_LIMIT);+ const fits = matches.some(match => match.score >= FIT_FLOOR);+ const name = id.replace(/-([a-z0-9])/gu, (_, c) => c.toUpperCase());+ return {+ type: 'icon.definitionMatches',+ data: {+ export: exportName,+ from,+ id,+ matches,+ newDefinition: fits+ ? null+ : `${base} --new-definition ${/^[a-z]/u.test(name) ? name : `icon${name}`} --description '<what the icon is for>' --words <word>,<word>`,+ },+ };+}diff --git a/packages/cli/api/icon/detail/detail.mjs b/packages/cli/api/icon/detail/detail.mjsnew file mode 100644index 0000000000..dc470e4c2c--- /dev/null+++ b/packages/cli/api/icon/detail/detail.mjs@@ -0,0 +1,88 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `icon.detail` leaf (AST-084 FR7): one icon by `<set>/<id>`, with every+ * variant's import line.+ *+ * @input `<set>/<id>`, where `<set>` is a set name or `<package>/<set>`+ * @output the `icon.detail` envelope, naming the set's package+ * @position api/icon/detail — dispatched by ../icon.mjs+ */++import {AstryxError} from '../../error.mjs';+import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';+import {loadIconSets} from '../_adapter.mjs';+import {+ closest,+ iconRecord,+ importLine,+ rankIcons,+ setsNamed,+ withdrawnReason,+} from '../_records.mjs';++/**+ * Read one icon.+ * @param {string} reference `<set>/<id>` or `<package>/<set>/<id>`+ * @param {{cwd: string}} options+ * @returns {Promise<import('../icon.type.mjs').IconDetailResponse>}+ */+export async function iconDetail(reference, {cwd}) {+ const slash = reference.lastIndexOf('/');+ const selector = reference.slice(0, slash);+ const id = reference.slice(slash + 1);+ const {sets, withdrawn} = await loadIconSets(cwd);+ const named = setsNamed(sets, selector);+ if (named.length === 0) {+ throw new AstryxError(+ withdrawnReason(withdrawn, selector) ??+ `No installed icon set named "${selector}"`,+ closest(+ selector,+ sets.flatMap(each => [each.name, `${each.package}/${each.name}`]),+ 'installed icon set',+ ),+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }+ if (named.length > 1) {+ throw new AstryxError(+ `Icon set name "${selector}" is installed by ${named.map(each => each.package).join(' and ')}`,+ named.map(each => ({+ name: `${each.package}/${each.name}/${id}`,+ reason: 'name the package',+ })),+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ const set = named[0];+ const icon = set.data.icons.find(each => each.id === id);+ if (!icon) {+ const nearby = rankIcons([set], id.replace(/-/g, ' ')).map(+ match => `${set.name}/${match.id}`,+ );+ throw new AstryxError(+ `No icon "${id}" in icon set "${set.name}"`,+ nearby.length > 0+ ? nearby.slice(0, 5).map(name => ({name, reason: 'similar icon'}))+ : closest(+ id,+ set.data.icons.map(each => each.id),+ 'icon in this set',+ ).map(each => ({...each, name: `${set.name}/${each.name}`})),+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }+ const record = iconRecord(set, icon);+ return {+ type: 'icon.detail',+ package: set.package,+ data: {+ ...record,+ variants: record.variants.map(variant => ({+ ...variant,+ import: importLine(variant.export, variant.module),+ })),+ },+ };+}diff --git a/packages/cli/api/icon/error-codes.test.mjs b/packages/cli/api/icon/error-codes.test.mjsnew file mode 100644index 0000000000..5b6647263b--- /dev/null+++ b/packages/cli/api/icon/error-codes.test.mjs@@ -0,0 +1,334 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Every error code each icon API function documents (spec:AST-042 FR2,+ * AST-084): one case per function and code, each asserting the code the+ * function's reference doc lists, and a check that the docs list exactly the+ * codes these cases raise.+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {+ writeIconPackage,+ writeIconSetProject,+} from '../../test-utils/icon-set-fixture.mjs';++// The manifest's root changes between the dry run and the write when a case+// sets `conflict.root`: the write then meets a root it did not plan for.+const conflict = vi.hoisted(() => ({+ root: /** @type {string | null} */ (null),+}));+vi.mock(+ '../../foundation/integrations/manifest-writer.mjs',+ async importOriginal => {+ const actual =+ /** @type {typeof import('../../foundation/integrations/manifest-writer.mjs')} */ (+ await importOriginal()+ );+ return {+ ...actual,+ /** @type {typeof actual.patchIntegrationRoot} */+ patchIntegrationRoot: async (packageDir, key, rootPath, options) => {+ if (conflict.root && !options?.dryRun) {+ fs.writeFileSync(+ path.join(packageDir, 'astryx.integration.mjs'),+ `export default {experimental: {iconSets: '${conflict.root}'}};\n`,+ );+ }+ return actual.patchIntegrationRoot(packageDir, key, rootPath, options);+ },+ };+ },+);++const {icon} = await import('./icon.mjs');+const {iconAdd} = await import('./add/add.mjs');+const {iconMap} = await import('./map/map.mjs');+const {iconUse} = await import('./use/use.mjs');+const {iconNewSet} = await import('./new-set/new-set.mjs');+const {iconNewDefinition} = await import('./new-definition/new-definition.mjs');++/** @type {string} */+let tmp;+/** @type {string[]} */+let locked;+beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-icon-errors-'));+ locked = [];+ conflict.root = null;+});+afterEach(() => {+ for (const dir of locked) fs.chmodSync(dir, 0o755);+ fs.rmSync(tmp, {recursive: true, force: true});+});++/** A fresh folder: no package.json above it and no project. */+function outside() {+ return fs.mkdtempSync(path.join(tmp, 'outside-'));+}++/** The icon-set package `@acme/glyphs`, with its set `glyphs`. */+function pkg() {+ const dir = path.join(fs.mkdtempSync(path.join(tmp, 'pkg-')), 'glyphs');+ writeIconPackage(dir);+ return dir;+}++/** A package with a name and no icon set yet. @returns {string} */+function bare() {+ const dir = fs.mkdtempSync(path.join(tmp, 'bare-'));+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name: '@acme/bare', version: '1.0.0'}),+ );+ return dir;+}++/** @param {Parameters<typeof writeIconSetProject>[1]} [options] */+function app(options) {+ return writeIconSetProject(fs.mkdtempSync(path.join(tmp, 'app-')), options);+}++/** A folder nothing may write into, unlocked after the test. @param {string} dir */+function lock(dir) {+ fs.mkdirSync(dir, {recursive: true});+ fs.chmodSync(dir, 0o555);+ locked.push(dir);+}++/** @param {string} dir @param {string} text */+function manifest(dir, text) {+ fs.writeFileSync(path.join(dir, 'astryx.integration.mjs'), text);+}++/** @param {string} dir */+function withSecondSet(dir) {+ const from = path.join(dir, 'icon-sets', 'glyphs');+ const to = path.join(dir, 'icon-sets', 'extra');+ fs.mkdirSync(to);+ fs.writeFileSync(+ path.join(to, 'extra.doc.mjs'),+ fs+ .readFileSync(path.join(from, 'glyphs.doc.mjs'), 'utf8')+ .replace('"glyphs"', '"extra"'),+ );+ fs.copyFileSync(+ path.join(from, 'glyphs.icons.json'),+ path.join(to, 'extra.icons.json'),+ );+ return dir;+}++const DEFINITION = {description: 'Turn something.', words: ['turn']};++/**+ * Each function's cases, by the code each raises.+ * @type {Record<string, Record<string, () => Promise<unknown>>>}+ */+const CASES = {+ icon: {+ ERR_MISSING_ARGUMENT: () => icon('', {cwd: app()}),+ ERR_INVALID_ARGUMENT: () => icon('close', {cwd: app(), limit: 0}),+ ERR_NOT_FOUND: () => icon('glyphs/nope', {cwd: app()}),+ },+ iconAdd: {+ ERR_PROJECT_REQUIRED: () =>+ iconAdd('XIcon', {cwd: outside(), from: './x.js'}),+ ERR_INVALID_ARGUMENT: () =>+ iconAdd('not a name', {cwd: pkg(), from: './icons/x.js'}),+ ERR_MISSING_ARGUMENT: () =>+ iconAdd('XIcon', /** @type {any} */ ({cwd: pkg()})),+ ERR_NOT_FOUND: () =>+ iconAdd('NopeIcon', {+ cwd: pkg(),+ from: './icons/x.js',+ definition: 'close',+ }),+ ERR_FILE_NOT_FOUND: () =>+ iconAdd('XIcon', {cwd: pkg(), from: './icons/missing.js'}),+ ERR_FILE_EXISTS: () =>+ iconAdd('XIcon', {+ cwd: pkg(),+ from: './icons/x.js',+ definition: 'close',+ id: 'search',+ }),+ ERR_PATH_TRAVERSAL: () =>+ iconAdd('XIcon', {cwd: pkg(), from: '../outside.js'}),+ ERR_WRITE_FAILED: () => {+ const dir = pkg();+ lock(path.join(dir, 'icon-sets', 'glyphs'));+ return iconAdd('XIcon', {+ cwd: dir,+ from: './icons/x.js',+ definition: 'close',+ id: 'x-again',+ });+ },+ },+ iconMap: {+ ERR_PROJECT_REQUIRED: () => iconMap('close', 'x', {cwd: outside()}),+ ERR_MISSING_ARGUMENT: () => iconMap('', 'x', {cwd: pkg()}),+ ERR_INVALID_ARGUMENT: () =>+ iconMap('close', 'x', {cwd: withSecondSet(pkg())}),+ ERR_NOT_FOUND: () => iconMap('notADefinition', 'x', {cwd: pkg()}),+ ERR_PATH_TRAVERSAL: () => {+ const dir = pkg();+ manifest(dir, "export default {experimental: {iconSets: '../out'}};\n");+ return iconMap('close', 'x', {cwd: dir});+ },+ ERR_WRITE_FAILED: () => {+ const dir = pkg();+ lock(path.join(dir, 'icon-sets', 'glyphs'));+ return iconMap('home', 'x', {cwd: dir});+ },+ },+ iconUse: {+ ERR_PROJECT_REQUIRED: () => iconUse('glyphs', {cwd: outside()}),+ ERR_MISSING_ARGUMENT: () => iconUse('', {cwd: app()}),+ ERR_NOT_FOUND: () => iconUse('nope', {cwd: app()}),+ ERR_INVALID_ARGUMENT: () =>+ iconUse('glyphs', {+ cwd: app({packages: [{}, {name: '@acme/lines', set: 'glyphs'}]}),+ }),+ // A config whose default export is not an object literal.+ ERR_WRITE_FAILED: () => {+ const dir = app();+ fs.writeFileSync(+ path.join(dir, 'astryx.config.mjs'),+ 'function make() {\n return {};\n}\nexport default make();\n',+ );+ return iconUse('glyphs', {cwd: dir});+ },+ ERR_CODEMOD_PROTECTED: () => {+ const dir = app();+ fs.writeFileSync(+ path.join(dir, '.gitattributes'),+ 'astryx.config.mjs linguist-generated\n',+ );+ return iconUse('glyphs', {cwd: dir});+ },+ // A .gitattributes rule with no attribute cannot be read.+ ERR_CODEMOD_PROTECTION_SOURCE: () => {+ const dir = app();+ fs.writeFileSync(path.join(dir, '.gitattributes'), 'astryx.config.mjs\n');+ return iconUse('glyphs', {cwd: dir});+ },+ },+ iconNewSet: {+ ERR_PROJECT_REQUIRED: () => iconNewSet('outline', {cwd: outside()}),+ ERR_INVALID_ARGUMENT: () => iconNewSet('Outline', {cwd: bare()}),+ ERR_FILE_EXISTS: async () => {+ const dir = bare();+ await iconNewSet('outline', {cwd: dir});+ return iconNewSet('outline', {cwd: dir});+ },+ ERR_PATH_TRAVERSAL: () => {+ const dir = bare();+ manifest(dir, "export default {experimental: {iconSets: '../x'}};\n");+ return iconNewSet('outline', {cwd: dir});+ },+ // The manifest names another root by the time the set is written.+ ERR_INTEGRATION_ROOT_CONFLICT: () => {+ conflict.root = './elsewhere';+ return iconNewSet('outline', {cwd: bare()});+ },+ ERR_WRITE_FAILED: () => {+ const dir = bare();+ manifest(dir, "export default {experimental: {iconSets: './taken'}};\n");+ fs.writeFileSync(path.join(dir, 'taken'), 'not a directory');+ return iconNewSet('outline', {cwd: dir});+ },+ ERR_NOT_FOUND: () =>+ iconNewSet('outline', {cwd: bare(), from: 'not-installed-library'}),+ ERR_FILE_NOT_FOUND: () =>+ iconNewSet('outline', {cwd: bare(), from: './missing.js'}),+ },+ iconNewDefinition: {+ ERR_PROJECT_REQUIRED: () =>+ iconNewDefinition('rotate', {cwd: outside(), ...DEFINITION}),+ ERR_INVALID_ARGUMENT: () =>+ iconNewDefinition('Not-Camel', {cwd: pkg(), ...DEFINITION}),+ ERR_MISSING_ARGUMENT: () =>+ iconNewDefinition('rotate', {cwd: pkg(), words: ['turn']}),+ ERR_FILE_EXISTS: async () => {+ const dir = pkg();+ await iconNewDefinition('rotate', {cwd: dir, ...DEFINITION});+ return iconNewDefinition('rotate', {cwd: dir, ...DEFINITION});+ },+ ERR_NOT_FOUND: () =>+ iconNewDefinition('rotate', {cwd: pkg(), ...DEFINITION, icon: 'nope'}),+ ERR_PATH_TRAVERSAL: () => {+ const dir = pkg();+ manifest(dir, "export default {experimental: {iconSets: '../out'}};\n");+ return iconNewDefinition('rotate', {cwd: dir, ...DEFINITION});+ },+ ERR_WRITE_FAILED: () => {+ const dir = pkg();+ lock(path.join(dir, 'icon-sets', 'glyphs', 'definitions'));+ return iconNewDefinition('rotate', {cwd: dir, ...DEFINITION});+ },+ },+};++/** The codes a function's reference doc lists. @param {string} name */+async function documented(name) {+ const {doc} = await import(`./${name}.doc.mjs`);+ return (doc.throws ?? []).map((/** @type {any} */ each) => each.code).sort();+}++describe.each(Object.entries(CASES))('%s', (name, cases) => {+ it('documents exactly the codes it raises', async () => {+ expect(await documented(name)).toEqual(Object.keys(cases).sort());+ });++ it.each(Object.entries(cases))('raises %s', async (code, run) => {+ await expect(run()).rejects.toMatchObject({code});+ });+});++describe('a write that fails leaves the package as it was', () => {+ it('iconNewSet: a root that changes before the write rolls back package.json', async () => {+ const dir = bare();+ const before = fs.readFileSync(path.join(dir, 'package.json'), 'utf8');+ conflict.root = './elsewhere';+ await expect(iconNewSet('outline', {cwd: dir})).rejects.toMatchObject({+ code: 'ERR_INTEGRATION_ROOT_CONFLICT',+ });+ expect(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).toBe(+ before,+ );+ // No file of the set is left (the shared write transaction keeps the+ // folders it made).+ const left = fs.existsSync(path.join(dir, 'icon-sets'))+ ? fs+ .readdirSync(path.join(dir, 'icon-sets'), {recursive: true})+ .filter(each =>+ fs.statSync(path.join(dir, 'icon-sets', String(each))).isFile(),+ )+ : [];+ expect(left).toEqual([]);+ });+});++describe('iconUse beside a spread', () => {+ it('refuses with ERR_WRITE_FAILED and leaves a config that spreads another object as it was', async () => {+ const dir = app();+ const file = path.join(dir, 'astryx.config.mjs');+ fs.writeFileSync(+ path.join(dir, 'base.mjs'),+ "export default {integrations: ['@acme/glyphs']};\n",+ );+ const before =+ "import base from './base.mjs';\n\nexport default {\n ...base,\n};\n";+ fs.writeFileSync(file, before);+ await expect(iconUse('glyphs', {cwd: dir})).rejects.toMatchObject({+ code: 'ERR_WRITE_FAILED',+ message: expect.stringContaining('spreads another object'),+ });+ expect(fs.readFileSync(file, 'utf8')).toBe(before);+ });+});diff --git a/packages/cli/api/icon/experimental-markers.test.mjs b/packages/cli/api/icon/experimental-markers.test.mjsnew file mode 100644index 0000000000..20f98f2f68--- /dev/null+++ b/packages/cli/api/icon/experimental-markers.test.mjs@@ -0,0 +1,93 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Every public icon-set export is marked `@experimental` (spec:AST-084+ * FR0): each icon function the API entry exports, each type the icon-set and+ * icon-definition declarations export, and each icon parser the authoring+ * entry exports. A new export fails here until its JSDoc carries the marker.+ *+ * @input the API entry, the authoring entries, and the doc-type declarations+ * @output assertions only+ * @position api/icon — beside the functions it reads+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {describe, expect, it} from 'vitest';++const CLI = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '..',+ '..',+);+/** @param {string} file */+const read = file => fs.readFileSync(path.join(CLI, file), 'utf8');++/**+ * The JSDoc block that ends right before `index` in `text`, or ''.+ * @param {string} text+ * @param {number} index+ */+function docBefore(text, index) {+ const head = text.slice(0, index).trimEnd();+ if (!head.endsWith('*/')) return '';+ return head.slice(head.lastIndexOf('/**'));+}++describe('icon-set exports carry @experimental', () => {+ it('every icon function the API entry exports', () => {+ const entry = read('api/index.mjs');+ const exports = [+ ...entry.matchAll(/^export \{(icon\w*)\} from '(\.\/icon\/[^']+)';/gmu),+ ];+ expect(exports.map(([, name]) => name).sort()).toEqual([+ 'icon',+ 'iconAdd',+ 'iconMap',+ 'iconNewDefinition',+ 'iconNewSet',+ 'iconUse',+ ]);+ for (const [, name, from] of exports) {+ const source = read(path.join('api', from));+ const at = source.search(+ new RegExp(`^export (?:async )?function ${name}\\b`, 'mu'),+ );+ expect(at, `${name} in ${from}`).toBeGreaterThan(0);+ expect(docBefore(source, at), name).toMatch(/@experimental\b/u);+ }+ });++ it.each([+ 'authoring/doctypes/icon-set/type.ts',+ 'authoring/doctypes/icon-definition/type.ts',+ ])('every type %s exports', file => {+ const source = read(file);+ const found = [...source.matchAll(/^export (?:interface|type) (\w+)/gmu)];+ expect(found.length).toBeGreaterThan(0);+ for (const match of found) {+ expect(+ docBefore(source, /** @type {number} */ (match.index)),+ match[1],+ ).toMatch(/@experimental\b/u);+ }+ });++ it.each(['authoring/index.mjs', 'authoring/index.d.ts'])(+ 'every icon parser %s exports',+ file => {+ const source = read(file);+ const found = [+ ...source.matchAll(/^export \{([^}]*\bparseIcon\w*[^}]*)\} from/gmu),+ ];+ expect(found.length).toBe(2);+ for (const match of found) {+ expect(+ docBefore(source, /** @type {number} */ (match.index)),+ match[1],+ ).toMatch(/@experimental\b/u);+ }+ },+ );+});diff --git a/packages/cli/api/icon/icon.doc.mjs b/packages/cli/api/icon/icon.doc.mjsnew file mode 100644index 0000000000..6cbd1a0087--- /dev/null+++ b/packages/cli/api/icon/icon.doc.mjs@@ -0,0 +1,91 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file FunctionDoc for `icon()` / `astryx experimental icon` (AST-084 FR6, FR7).+ * @position packages/cli/api/icon — function documentation+ */++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'icon',+ namespace: 'cli/api',+ stability: 'experimental',+ displayName: 'icon()',+ summary:+ 'Find an icon by meaning in the installed icon sets, read one icon, or list the sets.',+ description:+ "Reads every installed icon set's data file, never the icon modules. With words it ranks icons by meaning: an icon definition the set's `map` names the icon for, then exact matches on its id or words, then a word that starts with the query, then partial matches; equal scores keep the project's set first, then integration load order; within a set, a whole-id name match before an id-part one and a meaning match by its tag position; then id order. With `<set>/<id>` it reads one icon with every variant's import line. With `list` it lists the installed sets, how many icon definitions each one's `map` covers (built-in and all of Astryx's) and its own definitions, and any set withdrawn and why. Experimental: it may change or be removed in a patch release.",+ importPath: '@astryxdesign/cli/api',+ signature:+ 'icon(query?: string, options?: IconOptions): Promise<IconSearchResponse | IconDetailResponse | IconListResponse>',+ keywords: ['icon', 'icons', 'icon set', 'glyph', 'import', 'svg'],+ params: [+ {+ name: 'query',+ type: 'string',+ description:+ 'Words to search for, or `<set>/<id>` (`<package>/<set>/<id>` when two packages ship a set with one name). Omit with `list`.',+ },+ {+ name: 'options.list',+ type: 'boolean',+ description: 'List the installed icon sets instead of searching.',+ },+ {+ name: 'options.set',+ type: 'string',+ description: 'Search one set, by name or `<package>/<set>`.',+ },+ {+ name: 'options.limit',+ type: 'number',+ description:+ 'Max matches, a positive integer (default 10). `matchCount` counts every match.',+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'Project directory (default: the current directory).',+ },+ ],+ returns: [+ {+ type: 'icon.search',+ description:+ 'The query, how many icons matched, and the ranked matches, each with its set, id, package, module, export, import line, words, filled names, variants, reason, and score. No match is an empty list.',+ },+ {+ type: 'icon.detail',+ description:+ "One icon's fields, as a match names them, with every variant's import line. The envelope names the set's package.",+ },+ {+ type: 'icon.list',+ description:+ "The project's icon-set state, each installed set with its package, license, icon count, default variant, declared variants, and the icon definitions its `map` covers, and each withdrawn set with its reason.",+ },+ ],+ throws: [+ {+ code: 'ERR_MISSING_ARGUMENT',+ when: 'no query is given and `list` is not set',+ },+ {+ code: 'ERR_INVALID_ARGUMENT',+ when: 'a query is given with `list`, `limit` is not a positive integer, or a set name two packages share is not qualified with its package',+ },+ {+ code: 'ERR_NOT_FOUND',+ when: 'the set named by `<set>/<id>` or `options.set` is not installed, or the set has no such icon; suggestions name the closest',+ },+ ],+ examples: [+ {label: 'Find by meaning', code: "const {data} = await icon('delete');"},+ {label: 'One icon', code: "await icon('outline/trash');"},+ {label: 'Installed sets', code: 'await icon(undefined, {list: true});'},+ ],+ command: 'experimental icon',+ related: ['search', 'template'],+};diff --git a/packages/cli/api/icon/icon.mjs b/packages/cli/api/icon/icon.mjsnew file mode 100644index 0000000000..1adbad2437--- /dev/null+++ b/packages/cli/api/icon/icon.mjs@@ -0,0 +1,96 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Programmatic API for the `icon` command (AST-084 FR6, FR7):+ * dispatcher over three leaves.+ *+ * icon('<words>') icon.search: icons ranked by meaning+ * icon('<set>/<id>') icon.detail: one icon and every variant's import+ * icon('', {list}) icon.list: the installed sets+ *+ * Every read comes from installed icon sets' data files, through the+ * `Project` seam; nothing executes an icon module.+ *+ * @input a query or `<set>/<id>`, and options+ * @output icon.search | icon.detail | icon.list envelope+ * @position api/icon — dispatcher; command wrapper in clients/cli/commands/icon.mjs+ */++import {AstryxError} from '../error.mjs';+import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';+import {iconSearch} from './search/search.mjs';+import {iconDetail} from './detail/detail.mjs';+import {iconList} from './list/list.mjs';++/** The default `limit` for `icon.search`. */+export const DEFAULT_ICON_LIMIT = 10;++/** `<set>/<id>` or `<package>/<set>/<id>`: no spaces, and an id after a slash. */+const REFERENCE_RE = /^[^\s/][^\s]*\/[a-z0-9]+(?:-[a-z0-9]+)*$/u;++/**+ * Find icons by meaning, read one icon, or list the installed icon sets.+ *+ * Experimental (spec:AST-017 FR27): may change or be removed in a patch+ * release.+ * @experimental+ * @param {string} [query] words to search for, or `<set>/<id>`+ * @param {import('./icon.type.mjs').IconOptions} [options]+ * @returns {Promise<import('./icon.type.mjs').IconSearchResponse | import('./icon.type.mjs').IconDetailResponse | import('./icon.type.mjs').IconListResponse>}+ */+export async function icon(query, options = {}) {+ const {+ cwd = process.cwd(),+ list = false,+ set,+ limit = DEFAULT_ICON_LIMIT,+ } = options;+ if (query != null && typeof query !== 'string') {+ throw new AstryxError(+ `Invalid icon query: ${String(query)}`,+ [],+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ const term = (query ?? '').trim();+ if (list) {+ if (term) {+ throw new AstryxError(+ '--list takes no query',+ [+ {+ name: 'astryx experimental icon --list',+ reason: 'list the installed sets',+ },+ ],+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ return iconList({cwd});+ }+ if (!term) {+ throw new AstryxError(+ 'An icon query is required',+ [+ {+ name: 'astryx experimental icon delete',+ reason: 'find icons by meaning',+ },+ {+ name: 'astryx experimental icon --list',+ reason: 'list the installed sets',+ },+ ],+ ERROR_CODES.ERR_MISSING_ARGUMENT,+ );+ }+ if (limit != null && (!Number.isInteger(limit) || limit <= 0)) {+ throw new AstryxError(+ `Invalid limit "${limit}". Must be a positive integer.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ if (REFERENCE_RE.test(term)) return iconDetail(term, {cwd});+ return iconSearch(term, {cwd, set, limit});+}diff --git a/packages/cli/api/icon/icon.test.mjs b/packages/cli/api/icon/icon.test.mjsnew file mode 100644index 0000000000..f4a0a64b27--- /dev/null+++ b/packages/cli/api/icon/icon.test.mjs@@ -0,0 +1,374 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `icon()` (AST-084 FR6, FR7): ranking, set and limit options, one+ * icon, the set list, and errors, over the synthetic fixture.+ */++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 {icon} from './icon.mjs';+import {iconUse} from './use/use.mjs';+import {ICON_NAMES} from '../../authoring/doctypes/icon-set/icon-names.mjs';+import {rankIcons, scoreIcon} from './_records.mjs';+import {+ glyphsData,+ writeIconSetProject,+} from '../../test-utils/icon-set-fixture.mjs';++/** @type {string} */+let tmp;+/** @type {string} */+let cwd;+beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-icon-api-'));+ cwd = writeIconSetProject(tmp);+});+afterEach(() => {+ fs.rmSync(tmp, {recursive: true, force: true});+});++/** @param {string} query @param {object} [options] */+async function search(query, options = {}) {+ const result = await icon(query, {cwd, ...options});+ if (result.type !== 'icon.search') throw new Error(result.type);+ return result.data;+}++describe('icon.search ranking', () => {+ const icons = glyphsData().icons;+ const byId = (/** @type {string} */ id) =>+ /** @type {any} */ (icons.find(each => each.id === id));++ it('scores each tier: definition, exact in the leading reading, exact in the other, prefix, partial', () => {+ expect(scoreIcon('close', byId('x'), 'meaning', ['close'])).toEqual({+ score: 100,+ reason: 'definition "close"',+ });+ expect(scoreIcon('trash', byId('trash'), 'name')).toEqual({+ score: 90,+ reason: 'id "trash"',+ });+ expect(scoreIcon('trash', byId('trash'), 'meaning')).toEqual({+ score: 80,+ reason: 'id "trash"',+ });+ expect(scoreIcon('delete', byId('trash'))).toEqual({+ score: 90,+ reason: 'word "delete"',+ });+ expect(scoreIcon('delete', byId('trash'), 'name')?.score).toBe(80);+ expect(scoreIcon('garb', byId('trash'))?.score).toBe(60);+ expect(scoreIcon('arbag', byId('trash'))?.score).toBe(40);+ expect(scoreIcon('ma', byId('search'))?.score).toBe(60);+ expect(scoreIcon('zebra', byId('trash'))).toBeNull();+ });++ it('a fill outranks a word match of the same text', async () => {+ const data = await search('search');+ expect(data.matches[0]).toMatchObject({id: 'search', score: 100});+ });++ it('ties keep id order, so the answer is stable', async () => {+ const data = await search('remove');+ expect(data.matches.map(match => match.id)).toEqual(['trash', 'x']);+ });++ it('ties keep set order: the project set first', () => {+ const set = (/** @type {string} */ name) =>+ /** @type {any} */ ({+ name,+ package: `@acme/${name}`,+ data: {module: `@acme/${name}`, icons: [byId('x')]},+ });+ expect(rankIcons([set('b'), set('a')], 'close').map(m => m.set)).toEqual([+ 'b',+ 'a',+ ]);+ });++ it("equal scores keep set order before tag position: the project's set leads", () => {+ const glyphs = /** @type {any} */ ({+ name: 'glyphs',+ package: '@acme/glyphs',+ data: {+ module: '@acme/glyphs',+ icons: [{id: 'bin', export: 'BinIcon', words: ['garbage', 'delete']}],+ },+ });+ const other = /** @type {any} */ ({+ name: 'other',+ package: '@acme/other',+ data: {+ module: '@acme/other',+ icons: [{id: 'trash', export: 'TrashIcon', words: ['delete']}],+ },+ });+ const ranked = rankIcons([glyphs, other], 'delete');+ expect(ranked.map(m => [m.set, m.id])).toEqual([+ ['glyphs', 'bin'],+ ['other', 'trash'],+ ]);+ expect(ranked[0].score).toBe(ranked[1].score);+ });++ it('returns every field, with the import line', async () => {+ const data = await search('delete');+ expect(data).toMatchObject({query: 'delete', matchCount: 1});+ expect(data.matches[0]).toEqual({+ set: 'glyphs',+ id: 'trash',+ package: '@acme/glyphs',+ module: '@acme/glyphs',+ export: 'TrashIcon',+ import: "import {TrashIcon} from '@acme/glyphs';",+ words: ['delete', 'remove', 'bin', 'garbage'],+ definitions: [],+ variants: [+ {variant: 'solid', module: '@acme/glyphs', export: 'TrashSolidIcon'},+ ],+ reason: 'word "delete"',+ score: 90,+ });+ });++ it('no match is an empty list, not an error', async () => {+ expect(await search('zebra')).toEqual({+ query: 'zebra',+ matchCount: 0,+ matches: [],+ });+ });++ it('--limit caps the list; matchCount counts every match', async () => {+ const data = await search('remove', {limit: 1});+ expect(data.matches).toHaveLength(1);+ expect(data.matchCount).toBe(2);+ await expect(icon('remove', {cwd, limit: 0})).rejects.toMatchObject({+ code: 'ERR_INVALID_ARGUMENT',+ });+ });++ it('--set keeps one set, and an unknown set is ERR_NOT_FOUND', async () => {+ expect(+ (await search('close', {set: '@acme/glyphs/glyphs'})).matchCount,+ ).toBe(1);+ await expect(icon('close', {cwd, set: 'glyps'})).rejects.toMatchObject({+ code: 'ERR_NOT_FOUND',+ suggestions: expect.arrayContaining([+ expect.objectContaining({name: 'glyphs'}),+ ]),+ });+ });++ it('a project with no icon set answers an empty list', async () => {+ fs.rmSync(path.join(cwd, 'node_modules'), {recursive: true});+ expect((await search('close')).matches).toEqual([]);+ });+});++describe('icon.search: an exact query reads as a name or a meaning', () => {+ /**+ * @param {Array<[string, string[]]>} icons id and words+ * @returns {any}+ */+ const set = icons => ({+ name: 'lines',+ package: '@acme/lines',+ data: {+ module: '@acme/lines',+ icons: icons.map(([id, words]) => ({+ id,+ export: `${id.replace(/(^|-)(\w)/g, (_, _s, c) => c.toUpperCase())}Icon`,+ words,+ })),+ },+ });+ /** @param {any} s @param {string} q */+ const ranked = (s, q) =>+ rankIcons([s], q).map(m => [m.id, m.score, m.reason]);++ it('meaning wins: `delete` finds trash before the icon that draws the Delete key', () => {+ // The shape of a large outline library's data: an icon's own id words+ // come first, then its tags.+ const lines = set([+ ['delete', ['delete', 'backspace', 'key']],+ ['trash', ['trash', 'delete', 'remove', 'bin']],+ ]);+ expect(ranked(lines, 'delete')).toEqual([+ ['trash', 90, 'word "delete"'],+ ['delete', 80, 'id "delete"'],+ ]);+ });++ it('a word many icons are named for stays a name: `user` keeps the user icon ahead of one only tagged user', () => {+ const lines = set([+ ['contact', ['contact', 'user', 'person']],+ ['user', ['user', 'person', 'account']],+ ['user-plus', ['user', 'plus', 'add']],+ ]);+ expect(ranked(lines, 'user')).toEqual([+ ['user', 90, 'id "user"'],+ ['user-plus', 90, 'word "user"'],+ ['contact', 80, 'word "user"'],+ ]);+ });++ it('within the leading reading the tag listed earlier wins, and a tie in counts lets meaning lead', () => {+ const lines = set([+ ['eraser', ['eraser', 'rubber', 'clear', 'delete']],+ ['trash', ['trash', 'delete', 'remove', 'bin']],+ ['delete', ['delete', 'backspace', 'key']],+ ['x', ['x', 'close', 'delete']],+ ]);+ expect(ranked(lines, 'delete').map(([id, score]) => [id, score])).toEqual([+ ['trash', 90],+ ['x', 90],+ ['eraser', 90],+ ['delete', 80],+ ]);+ const both = set([+ ['bin', ['bin', 'trash']],+ ['trash', ['trash', 'bin']],+ ]);+ // 1 name (trash) and 1 meaning (bin, tagged trash): meaning leads.+ expect(ranked(both, 'trash').map(([id, score]) => [id, score])).toEqual([+ ['bin', 90],+ ['trash', 80],+ ]);+ });++ it("an icon definition the set's map names comes first", () => {+ const lines = set([['trash', ['trash', 'delete']]]);+ lines.data.icons.push({+ id: 'x',+ export: 'XIcon',+ words: ['x', 'close'],+ });+ lines.data.map = {close: 'x'};+ expect(ranked(lines, 'close')[0]).toEqual(['x', 100, 'definition "close"']);+ });++ it('an icon matches the words of every definition it is mapped to, after its own words', () => {+ // The data file lists only the icon's own name; `delete`'s words+ // (trash, bin, discard) and its name come from the definition.+ const lines = set([+ ['basket', ['basket']],+ ['pile', ['pile', 'discard']],+ ]);+ lines.data.map = {delete: 'basket'};+ expect(ranked(lines, 'bin')).toEqual([['basket', 90, 'word "bin"']]);+ // The icon's own tag ranks before a definition word.+ expect(ranked(lines, 'discard').map(([id]) => id)).toEqual([+ 'pile',+ 'basket',+ ]);+ // The record still shows the icon's own words.+ expect(rankIcons([lines], 'bin')[0].words).toEqual(['basket']);+ });+});++describe('icon.detail', () => {+ it('reads one icon with every variant import and the envelope package', async () => {+ const result = await icon('glyphs/trash', {cwd});+ expect(result.type).toBe('icon.detail');+ if (result.type !== 'icon.detail') return;+ expect(result.package).toBe('@acme/glyphs');+ expect(result.data.variants).toEqual([+ {+ variant: 'solid',+ module: '@acme/glyphs',+ export: 'TrashSolidIcon',+ import: "import {TrashSolidIcon} from '@acme/glyphs';",+ },+ ]);+ expect((await icon('@acme/glyphs/glyphs/x', {cwd})).type).toBe(+ 'icon.detail',+ );+ });++ it('an unknown set or icon is ERR_NOT_FOUND with suggestions', async () => {+ await expect(icon('nope/trash', {cwd})).rejects.toMatchObject({+ code: 'ERR_NOT_FOUND',+ });+ const error = await icon('glyphs/trashcan', {cwd}).catch(e => e);+ expect(error.suggestions[0].name).toBe('glyphs/trash');+ await expect(icon('glyphs/trashcan', {cwd})).rejects.toMatchObject({+ code: 'ERR_NOT_FOUND',+ suggestions: expect.arrayContaining([+ expect.objectContaining({name: 'glyphs/trash'}),+ ]),+ });+ });+});++describe('icon.list', () => {+ it('lists each set with how many icon definitions its map covers', async () => {+ const result = await icon(undefined, {cwd, list: true});+ if (result.type !== 'icon.list') throw new Error(result.type);+ expect(result.data).toMatchObject({+ status: 'selected',+ projectSet: '@acme/glyphs/glyphs',+ withdrawn: [],+ });+ const [set] = result.data.sets;+ expect(set).toMatchObject({+ name: 'glyphs',+ package: '@acme/glyphs',+ license: 'MIT',+ iconCount: 4,+ default: {variant: 'outline'},+ variants: ['outline', 'solid'],+ project: true,+ });+ expect(set.coverage.builtIn.mapped).toBe(2);+ expect(set.coverage.builtIn.total).toBe(ICON_NAMES.length);+ expect(set.coverage.builtIn.missing).toContain('chevronDown');+ expect(set.coverage.builtIn.missing).not.toContain('close');+ expect(set.coverage.astryx.total).toBeGreaterThan(ICON_NAMES.length);+ expect(set.coverage.own).toEqual([]);+ });++ it('refuses a query with --list and no query without it', async () => {+ await expect(icon('x', {cwd, list: true})).rejects.toMatchObject({+ code: 'ERR_INVALID_ARGUMENT',+ });+ await expect(icon('', {cwd})).rejects.toMatchObject({+ code: 'ERR_MISSING_ARGUMENT',+ });+ });+});++describe('a withdrawn set, named', () => {+ it('search --set, detail, use, and list say it is withdrawn and why, not that no set has the name', async () => {+ const dir = writeIconSetProject(path.join(tmp, 'withdrawn'), {+ packages: [{}, {name: '@acme/lines', data: '{nope'}],+ config: {experimental: {iconSet: 'lines'}},+ });+ const withdrawn =+ /Icon set "lines" is installed but withdrawn: .*not valid JSON/;+ await expect(icon('close', {cwd: dir, set: 'lines'})).rejects.toMatchObject(+ {code: 'ERR_NOT_FOUND', message: expect.stringMatching(withdrawn)},+ );+ await expect(icon('lines/x', {cwd: dir})).rejects.toMatchObject({+ code: 'ERR_NOT_FOUND',+ message: expect.stringMatching(withdrawn),+ });+ await expect(iconUse('lines', {cwd: dir})).rejects.toMatchObject({+ code: 'ERR_NOT_FOUND',+ message: expect.stringMatching(withdrawn),+ });+ const listed = await icon(undefined, {cwd: dir, list: true});+ if (listed.type !== 'icon.list') throw new Error(listed.type);+ expect(listed.data.status).toBe('withdrawn');+ expect(listed.data.reason).toMatch(+ /names "lines", which is installed but withdrawn: .*not valid JSON/,+ );+ // A name no installed set has, valid or withdrawn, still says so.+ await expect(icon('close', {cwd: dir, set: 'nope'})).rejects.toMatchObject({+ message: expect.stringMatching(/No installed icon set named "nope"/),+ });+ });+});diff --git a/packages/cli/api/icon/icon.type.mjs b/packages/cli/api/icon/icon.type.mjsnew file mode 100644index 0000000000..e64080312d--- /dev/null+++ b/packages/cli/api/icon/icon.type.mjs@@ -0,0 +1,290 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Colocated types for the `icon` command (AST-084 FR6, FR7): the source+ * of truth for its response shapes.+ *+ * @position api/icon — typedefs for api/icon/{icon,search,detail,list}+ */++/**+ * The variant an icon's own export draws.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconSetDefaultVariant+ * @property {string} [variant] - One of the set's declared variants.+ */++/**+ * One variant of an icon.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconVariantEntry+ * @property {string} variant - Which of the set's declared variants it draws.+ * @property {string} module - The import specifier the variant is read from.+ * @property {string} export - The named export that draws the variant.+ */++/**+ * One variant of an icon, with its import line.+ * @experimental May change or be removed in a patch release.+ * @typedef {IconVariantEntry & {import: string}} IconDetailVariantEntry+ */++/**+ * One icon, as every icon read names it.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconRecord+ * @property {string} set - The set's name.+ * @property {string} id - The icon's id, unique in its set.+ * @property {string} package - The integration package that ships the set.+ * @property {string} module - The import specifier of the icon's default export.+ * @property {string} export - The named export that draws the default variant.+ * @property {string} import - The import line for the default variant.+ * @property {string[]} words - Terms a person might search for.+ * @property {string[]} definitions - The icon definitions the set's `map` names this icon for.+ * @property {IconVariantEntry[]} variants - Other variants.+ */++/**+ * One ranked icon match.+ * @experimental May change or be removed in a patch release.+ * @typedef {IconRecord & {reason: string, score: number}} IconMatchEntry+ */++/**+ * `astryx --json experimental icon <words>`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconSearchResponse+ * @property {'icon.search'} type+ * @property {object} data+ * @property {string} data.query+ * @property {number} data.matchCount - Every match, before `limit`.+ * @property {IconMatchEntry[]} data.matches - The ranked matches, at most `limit`.+ */++/**+ * `astryx --json experimental icon <set>/<id>`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconDetailResponse+ * @property {'icon.detail'} type+ * @property {string} package - The integration package that ships the set.+ * @property {Omit<IconRecord, 'variants'> & {variants: IconDetailVariantEntry[]}} data+ */++/**+ * One installed set.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconSetEntry+ * @property {string} name+ * @property {string} displayName+ * @property {string} description+ * @property {string} package+ * @property {string} license+ * @property {number} iconCount+ * @property {IconSetDefaultVariant | null} default+ * @property {string[] | null} variants - The variants the set declares: named looks such as outline or solid; size comes from CSS.+ * @property {IconSetCoverage} coverage - Which icon definitions the set's `map` covers.+ * @property {boolean} project - Whether this is the project's icon set.+ */++/**+ * Which icon definitions one set's `map` covers.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconSetCoverage+ * @property {{mapped: number, total: number, missing: string[]}} builtIn - Built-in definitions: every set maps them all.+ * @property {{mapped: number, total: number}} astryx - Every Astryx definition, built in or not.+ * @property {string[]} own - The definitions the set declares itself, in its `definitions` folder.+ */++/**+ * A set that answers nothing, and why.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconWithdrawnEntry+ * @property {string} name+ * @property {string} package+ * @property {string} reason+ */++/**+ * `astryx --json experimental icon --list`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconListResponse+ * @property {'icon.list'} type+ * @property {object} data+ * @property {'selected' | 'none' | 'ambiguous' | 'missing' | 'withdrawn'} data.status - The project's icon-set state.+ * @property {string | null} data.projectSet - The project's set, as `<package>/<set>`, when selected.+ * @property {string} data.reason - Why the project has that set, or none.+ * @property {IconSetEntry[]} data.sets - Installed sets, the project's first.+ * @property {IconWithdrawnEntry[]} data.withdrawn - Sets found but withdrawn.+ */++/**+ * `astryx --json experimental icon use <set>`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconUseResponse+ * @property {'icon.use'} type+ * @property {object} data+ * @property {string} data.iconSet - The value written to `experimental.iconSet`.+ * @property {string} data.set - The set it names, as `<package>/<set>`.+ * @property {string} data.config - The config file, relative to the project.+ * @property {boolean} data.created - Whether the config file was created.+ * @property {string | null} data.previous - The `experimental.iconSet` value it replaced.+ * @property {boolean} data.changed - Whether anything was written.+ * @property {string} [data.warning] - Present when the project's+ * `@astryxdesign/cli` range admits a release before 0.7.4, which refuses+ * an astryx.config that sets `experimental.iconSet`: what fails, and the+ * range to require.+ */++/**+ * Options for `iconMap()`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconMapOptions+ * @property {string} [cwd]+ * @property {string} [set] - The set to edit, when the package ships several.+ * @property {boolean} [remove] - Remove the definition's entry instead.+ */++/**+ * `astryx --json experimental icon map <definition> <icon>`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconMapResponse+ * @property {'icon.map'} type+ * @property {object} data+ * @property {string} data.set+ * @property {string} data.package+ * @property {string} data.file - The data file, relative to the package.+ * @property {string} data.definition+ * @property {string | null} data.icon - The icon id now mapped; null after `remove`.+ * @property {string | null} data.previous - The icon id it replaced.+ * @property {boolean} data.changed - Whether the file was written.+ * @property {string[]} [data.files] - The generated module and its types, when its theme map was rewritten.+ */++/**+ * Options for `iconAdd()`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconAddOptions+ * @property {string} [cwd]+ * @property {string} from - The module the icon is exported from: a package, a package subpath, or a relative path in this package.+ * @property {string} [set] - The set to edit, when the package ships several.+ * @property {string} [definition] - The icon definition to map the icon to.+ * @property {string} [newDefinition] - Add the set's own definition with this name and map the icon to it.+ * @property {string} [description] - With `newDefinition`: what the icon is for.+ * @property {string[]} [words] - With `newDefinition`: words people search for.+ * @property {boolean} [useDefault] - The module's default export is the icon.+ * @property {string} [variant] - Add the export as this declared variant of an existing icon.+ * @property {string} [id] - The icon's id, instead of the one its name gives.+ */++/**+ * `astryx --json experimental icon add <Export> --from <module> --definition <name>`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconAddResponse+ * @property {'icon.add'} type+ * @property {object} data+ * @property {string} data.set+ * @property {string} data.package+ * @property {{id: string, export: string, module: string}} data.icon+ * @property {string} [data.variant] - The variant, when the export was added as one.+ * @property {string | null} data.definition - The definition mapped to the icon.+ * @property {string} [data.newDefinition] - The set's own definition the command wrote.+ * @property {string[]} data.files - Files written, relative to the package.+ * @property {boolean} data.changed - Whether anything was written.+ * @property {string} [data.note] - What the set's module still needs to export the icon.+ */++/**+ * One icon definition that fits an export.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconDefinitionMatch+ * @property {string} name+ * @property {string} description+ * @property {'astryx' | 'set'} source - Astryx's definition, or the set's own.+ * @property {number} score+ * @property {string} reason+ * @property {string} command - The `experimental icon add` command that maps the icon to it.+ */++/**+ * `astryx --json experimental icon add <Export> --from <module>` with no definition.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconDefinitionMatchesResponse+ * @property {'icon.definitionMatches'} type+ * @property {object} data+ * @property {string} data.export+ * @property {string} data.from+ * @property {string} data.id - The id the icon would get.+ * @property {IconDefinitionMatch[]} data.matches - At most 10, best first.+ * @property {string | null} data.newDefinition - The command that adds the set's own definition, when no match fits.+ */++/**+ * Options for `icon()`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconOptions+ * @property {string} [cwd]+ * @property {boolean} [list] - List the installed sets.+ * @property {string} [set] - Keep one set, by name or `<package>/<set>`.+ * @property {number} [limit] - Max matches (default 10).+ */++/**+ * Options for `iconNewSet()`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconNewSetOptions+ * @property {string} [cwd] - A directory inside the integration package.+ * @property {boolean} [dryRun] - Return the receipt without writing.+ * @property {string} [from] - A module whose every icon component the set wraps: a package, a package subpath, or a ./ path in the package.+ * @property {string[] | string} [exclude] - With `from`: export names that are not icons; a string is split on commas.+ */++/**+ * Options for `iconNewDefinition()`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconNewDefinitionOptions+ * @property {string} [cwd] - A directory inside the icon-set package.+ * @property {boolean} [dryRun] - Return the receipt without writing.+ * @property {string} [set] - The set, when the package ships several.+ * @property {string} [description] - What an icon with this definition is for.+ * @property {string[] | string} [words] - Words people search for; a string is split on commas.+ * @property {string} [icon] - An icon id to map the definition to.+ */++/**+ * What `iconNewSet()` and `iconNewDefinition()` wrote.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconNewData+ * @property {'icon-set' | 'icon-definition'} kind+ * @property {string} name+ * @property {{path: string, created: boolean} | null} root - The manifest's `experimental.iconSets` root, when the call declared or used it.+ * @property {string} manifest - The manifest file, relative to the package.+ * @property {string[]} files - Files written, relative to the package.+ * @property {boolean} written+ * @property {boolean} dryRun+ * @property {string} [from]+ * @property {number} [icons] - With `from`: how many icons it wrote.+ * @property {string[]} [notes] - What the author does next.+ */++/**+ * `astryx --json experimental icon new-set <name>`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconNewSetResponse+ * @property {'icon.newSet'} type+ * @property {IconNewData} data+ */++/**+ * `astryx --json experimental icon new-definition <name>`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconNewDefinitionResponse+ * @property {'icon.newDefinition'} type+ * @property {IconNewData} data+ */++/**+ * @experimental May change or be removed in a patch release.+ * @typedef {IconNewSetResponse | IconNewDefinitionResponse} IconNewResponse+ */++export {};diff --git a/packages/cli/api/icon/iconAdd.doc.mjs b/packages/cli/api/icon/iconAdd.doc.mjsnew file mode 100644index 0000000000..ee3e273cd0--- /dev/null+++ b/packages/cli/api/icon/iconAdd.doc.mjs@@ -0,0 +1,146 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file FunctionDoc for `iconAdd()` / `astryx experimental icon add` (AST-084 FR13). */++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'iconAdd',+ namespace: 'cli/api',+ stability: 'experimental',+ displayName: 'iconAdd()',+ summary:+ 'Register one icon you chose from a library in the set being authored.',+ description:+ "Run inside an icon-set package. The caller picks the export; the CLI never searches the library. It proves the export is a runtime component of `from` (a package, a package subpath, or a relative path this package exports), read without running it. With no definition it answers the icon definitions that fit the export, Astryx's and the set's own, and writes nothing. With `definition` it adds the icon (id from its name, `module` the source unless the set's own module already exports it, words from its name and the definition) and maps the definition to it. With `newDefinition` it first writes the set's own definition file. A `variant` adds the export as that declared variant of an existing icon. Running it again changes nothing. Experimental: it may change or be removed in a patch release.",+ importPath: '@astryxdesign/cli/api',+ signature:+ 'iconAdd(exportName: string, options: IconAddOptions): Promise<IconAddResponse | IconDefinitionMatchesResponse>',+ keywords: [+ 'icon',+ 'icon set',+ 'add icon',+ 'register',+ 'icon library',+ 'icon definition',+ ],+ params: [+ {+ name: 'exportName',+ type: 'string',+ description:+ 'The export the set exposes the icon as, such as `Bin`; the set exports it as `<Name>Icon`.',+ required: true,+ },+ {+ name: 'options.from',+ type: 'string',+ description: 'The module the icon is exported from.',+ required: true,+ },+ {+ name: 'options.set',+ type: 'string',+ description: 'The set, when the package ships several.',+ },+ {+ name: 'options.definition',+ type: 'string',+ description: 'The icon definition to map the icon to.',+ },+ {+ name: 'options.newDefinition',+ type: 'string',+ description:+ "Add the set's own definition with this name, then map the icon to it.",+ },+ {+ name: 'options.description',+ type: 'string',+ description: 'With `newDefinition`: what the icon is for.',+ },+ {+ name: 'options.words',+ type: 'string[]',+ description: 'With `newDefinition`: the words people search for.',+ },+ {+ name: 'options.useDefault',+ type: 'boolean',+ description:+ "The module's default export is the icon; the set's module must re-export it as `exportName`.",+ },+ {+ name: 'options.variant',+ type: 'string',+ description:+ "Add the export as this variant of an existing icon: one of the set's declared variants, such as `solid`.",+ },+ {+ name: 'options.id',+ type: 'string',+ description: "The icon's id, instead of the one its name gives.",+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'A directory inside the icon-set package.',+ },+ ],+ returns: [+ {+ type: 'icon.add',+ description:+ 'The icon registered, the definition mapped, and the files written.',+ },+ {+ type: 'icon.definitionMatches',+ description:+ 'Without a definition: the definitions that fit the export, and the commands that add it.',+ },+ ],+ throws: [+ {+ code: 'ERR_NOT_FOUND',+ when: 'the module does not export the name, or the definition is unknown',+ },+ {+ code: 'ERR_INVALID_ARGUMENT',+ when: 'the export is data rather than a component, a new definition is named like an Astryx one, or the variant is not one the set declares',+ },+ {code: 'ERR_FILE_EXISTS', when: 'another icon already has the id'},+ {+ code: 'ERR_PROJECT_REQUIRED',+ when: 'the folder is outside any project and has no package.json at or above it',+ },+ {+ code: 'ERR_MISSING_ARGUMENT',+ when: '`from` is missing',+ },+ {+ code: 'ERR_FILE_NOT_FOUND',+ when: 'a relative `from` resolves to no module file in the package',+ },+ {+ code: 'ERR_PATH_TRAVERSAL',+ when: '`from`, or the declared `experimental.iconSets` root, escapes the package',+ },+ {+ code: 'ERR_WRITE_FAILED',+ when: 'a file cannot be written; every write before it is undone',+ },+ ],+ examples: [+ {+ label: 'Which definitions fit',+ code: "await iconAdd('Bin', {from: '@acme/glyph-library'});",+ },+ {+ label: 'Add and map',+ code: "await iconAdd('Bin', {from: '@acme/glyph-library', definition: 'delete'});",+ },+ ],+ command: 'experimental icon add',+ related: ['iconMap', 'iconNewDefinition', 'validateIntegration'],+};diff --git a/packages/cli/api/icon/iconMap.doc.mjs b/packages/cli/api/icon/iconMap.doc.mjsnew file mode 100644index 0000000000..95d86e4fe8--- /dev/null+++ b/packages/cli/api/icon/iconMap.doc.mjs@@ -0,0 +1,92 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file FunctionDoc for `iconMap()` / `astryx experimental icon map` (AST-084 FR13). */++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'iconMap',+ namespace: 'cli/api',+ stability: 'experimental',+ displayName: 'iconMap()',+ summary:+ 'Register which icon of the set being authored draws an icon definition.',+ description:+ "Run inside an icon-set package. Sets `map[definition] = icon` in the set's data file, or removes the entry. The definition must be Astryx's or one the set declares, and the icon an id in the file. The file is written in one fixed shape, `map` keys sorted. `integration check` suggests these commands for definitions the set has a fitting icon for. Experimental: it may change or be removed in a patch release.",+ importPath: '@astryxdesign/cli/api',+ signature:+ 'iconMap(definition: string, icon?: string, options?: IconMapOptions): Promise<IconMapResponse>',+ keywords: ['icon', 'icon set', 'map', 'icon definition', 'register'],+ params: [+ {+ name: 'definition',+ type: 'string',+ description: 'The icon definition.',+ required: true,+ },+ {+ name: 'icon',+ type: 'string',+ description: 'An icon id in the set. Omit with `remove`.',+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'A directory inside the icon-set package.',+ },+ {+ name: 'options.set',+ type: 'string',+ description: 'The set, when the package ships several.',+ },+ {+ name: 'options.remove',+ type: 'boolean',+ description: "Remove the definition's entry.",+ default: 'false',+ },+ ],+ returns: [+ {+ type: 'icon.map',+ description:+ 'The set, the data file, the definition, the icon now mapped, the icon it replaced, and whether the file changed.',+ },+ ],+ throws: [+ {+ code: 'ERR_NOT_FOUND',+ when: 'the definition is unknown, or the set has no such icon',+ },+ {+ code: 'ERR_INVALID_ARGUMENT',+ when: 'the package ships several sets and none is named',+ },+ {+ code: 'ERR_PROJECT_REQUIRED',+ when: 'the folder is outside any project and has no package.json at or above it',+ },+ {+ code: 'ERR_MISSING_ARGUMENT',+ when: 'the definition is missing, or the icon id without `remove`',+ },+ {+ code: 'ERR_PATH_TRAVERSAL',+ when: 'the declared `experimental.iconSets` root escapes the package',+ },+ {+ code: 'ERR_WRITE_FAILED',+ when: 'the data file or generated module cannot be written; every write before it is undone',+ },+ ],+ examples: [+ {label: 'Map a definition', code: "await iconMap('delete', 'trash');"},+ {+ label: 'Remove an entry',+ code: "await iconMap('delete', undefined, {remove: true});",+ },+ ],+ command: 'experimental icon map',+ related: ['iconAdd', 'iconNewDefinition', 'validateIntegration'],+};diff --git a/packages/cli/api/icon/iconNewDefinition.doc.mjs b/packages/cli/api/icon/iconNewDefinition.doc.mjsnew file mode 100644index 0000000000..16d0f9c9f1--- /dev/null+++ b/packages/cli/api/icon/iconNewDefinition.doc.mjs@@ -0,0 +1,101 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'iconNewDefinition',+ namespace: 'cli/api',+ stability: 'experimental',+ displayName: 'iconNewDefinition()',+ summary: "Add one of an icon set's own icon definitions.",+ description:+ "Run inside an icon-set package. Writes `<set>/definitions/<name>.doc.mjs`, a strongly typed IconDefinitionDoc with the description and words, and, with `icon`, the set's `map` entry for it. A name Astryx already has is refused: map to Astryx's definition instead. The file is never overwritten, and a write that fails is undone. Experimental: it may change or be removed in a patch release.",+ importPath: '@astryxdesign/cli/api',+ signature:+ 'iconNewDefinition(name: string, options?: IconNewDefinitionOptions): Promise<IconNewDefinitionResponse>',+ keywords: ['integration', 'add', 'icon definition', 'icon set', 'author'],+ params: [+ {+ name: 'name',+ type: 'string',+ description: 'camelCase definition name.',+ required: true,+ },+ {+ name: 'options.description',+ type: 'string',+ description: 'One sentence on what an icon with this definition is for.',+ required: true,+ },+ {+ name: 'options.words',+ type: 'string[] | string',+ description: 'Words people search for; a string is split on commas.',+ required: true,+ },+ {+ name: 'options.icon',+ type: 'string',+ description: 'An icon id in the set to map the definition to.',+ },+ {+ name: 'options.set',+ type: 'string',+ description: 'The set, when the package ships several.',+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'A directory inside the icon-set package.',+ },+ {+ name: 'options.dryRun',+ type: 'boolean',+ description: 'Return the receipt without writing.',+ default: 'false',+ },+ ],+ returns: [+ {+ type: 'icon.newDefinition',+ description:+ 'What it wrote: the manifest root, the files, and what to do next.',+ },+ ],+ throws: [+ {+ code: 'ERR_INVALID_ARGUMENT',+ when: 'the name is not camelCase, or Astryx already has it',+ },+ {+ code: 'ERR_MISSING_ARGUMENT',+ when: 'the description or words are missing',+ },+ {code: 'ERR_FILE_EXISTS', when: 'the definition file already exists'},+ {+ code: 'ERR_NOT_FOUND',+ when: 'the package ships no icon set, or the set has no such icon',+ },+ {+ code: 'ERR_PROJECT_REQUIRED',+ when: 'the folder is outside any project and has no package.json at or above it',+ },+ {+ code: 'ERR_PATH_TRAVERSAL',+ when: 'the declared `experimental.iconSets` root escapes the package',+ },+ {+ code: 'ERR_WRITE_FAILED',+ when: 'the definition file or data file cannot be written; every write before it is undone',+ },+ ],+ examples: [+ {+ label: 'Add and map a definition',+ code: "await iconNewDefinition('rotate', {description: 'Rotate an image or shape.', words: ['turn', 'spin'], icon: 'rotate-cw'});",+ },+ ],+ command: 'experimental icon new-definition',+ related: ['iconNewSet', 'iconMap', 'iconAdd'],+};diff --git a/packages/cli/api/icon/iconNewSet.doc.mjs b/packages/cli/api/icon/iconNewSet.doc.mjsnew file mode 100644index 0000000000..1032db8e53--- /dev/null+++ b/packages/cli/api/icon/iconNewSet.doc.mjs@@ -0,0 +1,103 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'iconNewSet',+ namespace: 'cli/api',+ stability: 'experimental',+ displayName: 'iconNewSet()',+ summary: 'Add an icon set to an integration package.',+ description:+ "Creates an integration manifest when the package has none, writes the set directory with its strongly typed same-stem IconSetDoc and a starter data file (schemaVersion 1, module set to the package name, no icons and an empty map yet), and the set's generated module with its declaration file and an empty themeIcons theme map; with from, it wraps a library's icons into them. It declares the manifest's `experimental.iconSets` root on first use, and includes the manifest and root in package.json files when the package already uses an allowlist. Every path is confined to the package and existing files are never overwritten. Experimental: it may change or be removed in a patch release.",+ importPath: '@astryxdesign/cli/api',+ signature:+ 'iconNewSet(name: string, options?: IconNewSetOptions): Promise<IconNewSetResponse>',+ keywords: ['integration', 'add', 'icon', 'icon-set', 'author', 'scaffold'],+ params: [+ {+ name: 'name',+ type: 'string',+ description: 'Lowercase kebab-case icon set name and directory name.',+ required: true,+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'Directory inside the integration package.',+ },+ {+ name: 'options.dryRun',+ type: 'boolean',+ description:+ 'Validate and return the same receipt without writing; data.written is false and data.dryRun is true.',+ default: 'false',+ },+ {+ name: 'options.from',+ type: 'string',+ description:+ "A module whose every icon the set wraps: a package, a subpath, or a ./ path in the package. Components always; data exports too once the set declares an adapter. Run again to refresh the set's icons.",+ },+ {+ name: 'options.exclude',+ type: 'string[] | string',+ description:+ 'With from: export names that are not icons; a string is split on commas. SCREAMING_CASE names and number or boolean exports are always left out.',+ },+ ],+ returns: [+ {+ type: 'icon.newSet',+ description:+ 'What it wrote: the manifest root, the files, and what to do next.',+ },+ ],+ throws: [+ {+ code: 'ERR_INVALID_ARGUMENT',+ when: 'the name is not lowercase kebab-case, or package.json has no name',+ },+ {+ code: 'ERR_FILE_EXISTS',+ when: 'the set descriptor or data file already exists',+ },+ {+ code: 'ERR_PATH_TRAVERSAL',+ when: 'a declared `experimental.iconSets` root escapes the package',+ },+ {+ code: 'ERR_INTEGRATION_ROOT_CONFLICT',+ when: 'the manifest root changed to another path while the command was writing',+ },+ {+ code: 'ERR_WRITE_FAILED',+ when: 'a staged write fails and prior writes are rolled back',+ },+ {+ code: 'ERR_PROJECT_REQUIRED',+ when: 'the folder is outside any project and has no package.json at or above it',+ },+ {+ code: 'ERR_NOT_FOUND',+ when: '`from` does not resolve from the package, or exports no icon component',+ },+ {+ code: 'ERR_FILE_NOT_FOUND',+ when: 'a relative `from` resolves to no module file in the package',+ },+ ],+ examples: [+ {+ label: 'Add an icon set',+ code: "await iconNewSet('outline');",+ },+ {+ label: 'Preview writes',+ code: "await iconNewSet('outline', {dryRun: true});",+ },+ ],+ command: 'experimental icon new-set',+ related: ['icon', 'validateIntegration'],+};diff --git a/packages/cli/api/icon/iconUse.doc.mjs b/packages/cli/api/icon/iconUse.doc.mjsnew file mode 100644index 0000000000..ec02695048--- /dev/null+++ b/packages/cli/api/icon/iconUse.doc.mjs@@ -0,0 +1,70 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file FunctionDoc for `iconUse()` / `astryx experimental icon use` (AST-084 FR8). */++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'iconUse',+ namespace: 'cli/api',+ stability: 'experimental',+ displayName: 'iconUse()',+ summary: "Choose the project's icon set.",+ description:+ "Writes `experimental.iconSet` in the project's astryx.config (creating astryx.config.mjs when there is none), so templates and blocks the project copies use that set's icons. The set must be installed; a name two installed packages both ship is refused with each `<package>/<set>` form. Experimental: it may change or be removed in a patch release.",+ importPath: '@astryxdesign/cli/api',+ signature:+ 'iconUse(set: string, options?: {cwd?: string}): Promise<IconUseResponse>',+ keywords: ['icon', 'icon set', 'use', 'experimental.iconSet', 'config'],+ params: [+ {+ name: 'set',+ type: 'string',+ description: 'An installed set, by name or `<package>/<set>`.',+ required: true,+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'The project directory.',+ },+ ],+ returns: [+ {+ type: 'icon.use',+ description:+ "The value written, the set it names, the config file, whether it was created, the value it replaced, and a `warning` when the project's @astryxdesign/cli range admits a release before 0.7.4, which refuses the key.",+ },+ ],+ throws: [+ {code: 'ERR_NOT_FOUND', when: 'no installed set has the name'},+ {+ code: 'ERR_INVALID_ARGUMENT',+ when: 'two installed packages ship a set with the name',+ },+ {+ code: 'ERR_WRITE_FAILED',+ when: 'the config cannot be updated safely: its default export is not a static object literal, or it or its `experimental` object spreads another object, whose keys the written value could replace',+ },+ {+ code: 'ERR_CODEMOD_PROTECTED',+ when: 'the config is reached through a symbolic link, marked generated or vendored, or ignored; the error names the declaration that protects it',+ },+ {+ code: 'ERR_CODEMOD_PROTECTION_SOURCE',+ when: 'a protection declaration in the project cannot be read',+ },+ {+ code: 'ERR_PROJECT_REQUIRED',+ when: 'the folder is outside any project and has no package.json at or above it',+ },+ {+ code: 'ERR_MISSING_ARGUMENT',+ when: 'the set name is missing',+ },+ ],+ examples: [{label: 'Use a set', code: "await iconUse('outline');"}],+ command: 'experimental icon use',+ related: ['icon', 'iconMap', 'iconAdd'],+};diff --git a/packages/cli/api/icon/list/list.mjs b/packages/cli/api/icon/list/list.mjsnew file mode 100644index 0000000000..aaab494996--- /dev/null+++ b/packages/cli/api/icon/list/list.mjs@@ -0,0 +1,64 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `icon.list` leaf (AST-084 FR7): every installed icon set with the+ * icon definitions its `map` covers, the project's set, and the sets+ * withdrawn with why.+ *+ * @output the `icon.list` envelope+ * @position api/icon/list — dispatched by ../icon.mjs+ */++import {astryxIconDefinitions, loadIconSets} from '../_adapter.mjs';++/**+ * List the installed icon sets.+ * @param {{cwd: string}} options+ * @returns {Promise<import('../icon.type.mjs').IconListResponse>}+ */+export async function iconList({cwd}) {+ const {sets, withdrawn, choice} = await loadIconSets(cwd);+ const astryx = astryxIconDefinitions().definitions.map(each => each.doc);+ const builtIn = astryx.filter(doc => doc.builtIn).map(doc => doc.name);+ return {+ type: 'icon.list',+ data: {+ status: choice.status,+ projectSet: choice.set+ ? `${choice.set.package}/${choice.set.name}`+ : null,+ reason: choice.reason,+ sets: sets.map(set => {+ const mapped = new Set(Object.keys(set.data.map ?? {}));+ return {+ name: set.name,+ displayName: set.displayName,+ description: set.description,+ package: set.package,+ license: set.license,+ iconCount: set.data.icons.length,+ default: set.data.default ?? null,+ variants: set.data.variants ?? null,+ coverage: {+ builtIn: {+ mapped: builtIn.filter(name => mapped.has(name)).length,+ total: builtIn.length,+ missing: builtIn.filter(name => !mapped.has(name)),+ },+ astryx: {+ mapped: astryx.filter(doc => mapped.has(doc.name)).length,+ total: astryx.length,+ },+ own: set.definitions.map(each => each.doc.name),+ },+ project: set === choice.set,+ };+ }),+ withdrawn: withdrawn.map(each => ({+ name: each.name,+ package: each.package,+ reason: each.reason,+ })),+ },+ };+}diff --git a/packages/cli/api/icon/map/map.mjs b/packages/cli/api/icon/map/map.mjsnew file mode 100644index 0000000000..3054ed1d23--- /dev/null+++ b/packages/cli/api/icon/map/map.mjs@@ -0,0 +1,122 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `icon.map` leaf (AST-084 FR13): register which icon of the set being+ * authored draws one icon definition, or remove that entry.+ *+ * @output the `icon.map` envelope+ * @position api/icon/map — dispatched by the `experimental icon map` command+ */++import * as path from 'node:path';+import {AstryxError} from '../../error.mjs';+import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';+import {+ authoring,+ closestNames,+ findLocalIconSet,+ mappableDefinitions,+ refuseOutsideProject,+ writeGeneratedIcons,+ writeIconSetData,+} from '../_adapter.mjs';++/**+ * Set `map[definition] = icon` in the set's data file, or remove the entry.+ * Experimental (spec:AST-017 FR27): may change or be removed in a patch+ * release.+ * @experimental+ * @param {string} definition+ * @param {string | undefined} icon an icon id in the set; omit with `remove`+ * @param {import('../icon.type.mjs').IconMapOptions} [options]+ * @returns {Promise<import('../icon.type.mjs').IconMapResponse>}+ */+export async function iconMap(definition, icon, options = {}) {+ const {cwd = process.cwd(), set: selector, remove = false} = options;+ refuseOutsideProject(cwd, 'experimental icon map', 'the icon-set package');+ return authoring(async () => {+ if (typeof definition !== 'string' || definition.trim() === '') {+ throw new AstryxError(+ 'Name the icon definition to map',+ [+ {+ name: 'astryx docs cli/experimental/icon-definitions',+ reason: 'every icon definition',+ },+ ],+ ERROR_CODES.ERR_MISSING_ARGUMENT,+ );+ }+ if (!remove && (typeof icon !== 'string' || icon.trim() === '')) {+ throw new AstryxError(+ 'Name the icon id to map it to, or pass --remove',+ undefined,+ ERROR_CODES.ERR_MISSING_ARGUMENT,+ );+ }+ const {packageDir, set} = await findLocalIconSet(cwd, selector);+ const map = {...(set.data.map ?? {})};+ const previous = map[definition] ?? null;+ if (remove) {+ delete map[definition];+ } else {+ if (!mappableDefinitions(set).has(definition)) {+ throw new AstryxError(+ `"${definition}" is not an icon definition.`,+ [+ ...closestNames(definition, [...mappableDefinitions(set)]).map(+ name => ({name, reason: 'a known icon definition'}),+ ),+ {+ name: `astryx experimental icon new-definition ${definition} --set ${set.name}`,+ reason: 'add it as your own definition',+ },+ ],+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }+ const ids = set.data.icons.map(each => each.id);+ if (!ids.includes(/** @type {string} */ (icon))) {+ throw new AstryxError(+ `Icon set "${set.name}" has no icon "${icon}".`,+ closestNames(/** @type {string} */ (icon), ids).map(name => ({+ name,+ reason: 'an icon in this set',+ })),+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }+ map[definition] = /** @type {string} */ (icon);+ }+ const changed = remove ? previous != null : previous !== icon;+ /** @type {string[]} */+ const files = [];+ if (changed) {+ const next = {...set.data, map};+ // A set with a generated module gets its theme map rewritten too.+ const written = set.data.generated+ ? writeGeneratedIcons(packageDir, set.data.generated, next, [])+ : null;+ try {+ writeIconSetData(set, next);+ } catch (error) {+ written?.undo();+ throw error;+ }+ files.push(...(written?.files ?? []));+ }+ return {+ type: /** @type {const} */ ('icon.map'),+ data: {+ set: set.name,+ package: set.package,+ file: path.relative(packageDir, set.dataPath).split(path.sep).join('/'),+ definition,+ icon: remove ? null : /** @type {string} */ (icon),+ previous,+ changed,+ ...(files.length > 0 ? {files} : {}),+ },+ };+ });+}diff --git a/packages/cli/api/icon/new-definition/new-definition.mjs b/packages/cli/api/icon/new-definition/new-definition.mjsnew file mode 100644index 0000000000..aadf08f6a2--- /dev/null+++ b/packages/cli/api/icon/new-definition/new-definition.mjs@@ -0,0 +1,32 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `icon.newDefinition` leaf (AST-084 FR13): add one of an icon set's+ * own icon definitions.+ *+ * @output the `icon.newDefinition` envelope+ * @position api/icon/new-definition — dispatched by the `experimental icon+ * new-definition` command+ */++import {addIconDefinition, refuseOutsideProject} from '../_adapter.mjs';+import {refuseOtherOptions} from '../_options.mjs';++/**+ * Add an icon set's own icon definition: `astryx experimental icon+ * new-definition` (AST-084). Experimental (spec:AST-017 FR27).+ * @experimental+ * @param {string} name+ * @param {import('../icon.type.mjs').IconNewDefinitionOptions} [options]+ * @returns {Promise<import('../icon.type.mjs').IconNewDefinitionResponse>}+ */+export async function iconNewDefinition(name, options = {}) {+ refuseOtherOptions('icon-definition', options);+ refuseOutsideProject(+ options.cwd ?? process.cwd(),+ 'experimental icon new-definition',+ 'the icon-set package',+ );+ const {data} = await addIconDefinition(name, options);+ return {type: 'icon.newDefinition', data};+}diff --git a/packages/cli/api/icon/new-definition/new-definition.undo.test.mjs b/packages/cli/api/icon/new-definition/new-definition.undo.test.mjsnew file mode 100644index 0000000000..860ecd8ef1--- /dev/null+++ b/packages/cli/api/icon/new-definition/new-definition.undo.test.mjs@@ -0,0 +1,97 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `iconNewDefinition` with `icon` (AST-084 FR13): when the set fails to+ * read back after both writes, the data file and the definition file are+ * both undone, so every file is as it was.+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';++const reread = vi.hoisted(() => ({calls: 0, failOn: 0}));++vi.mock(+ '../../../foundation/discovery/icon-set-writer.mjs',+ async importOriginal => {+ const actual =+ /** @type {typeof import('../../../foundation/discovery/icon-set-writer.mjs')} */ (+ await importOriginal()+ );+ return {+ ...actual,+ /** @type {typeof actual.findLocalIconSet} */+ findLocalIconSet: async (...args) => {+ reread.calls += 1;+ if (reread.calls === reread.failOn) {+ throw new Error('the set did not read back');+ }+ return actual.findLocalIconSet(...args);+ },+ };+ },+);++const {iconNewSet} = await import('../new-set/new-set.mjs');+const {iconNewDefinition} = await import('./new-definition.mjs');++/** @type {string} */+let tmpDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-add-icon-definition-undo-'),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ `${JSON.stringify({name: '@acme/icons', version: '1.0.0', license: 'MIT'}, null, 2)}\n`,+ );+ reread.calls = 0;+ reread.failOn = 0;+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('iconNewDefinition --icon', () => {+ it('a failed re-read undoes the map write and the definition file', async () => {+ await iconNewSet('outline', {cwd: tmpDir});+ const set = path.join(tmpDir, 'icon-sets', 'outline');+ const dataPath = path.join(set, 'outline.icons.json');+ const data = JSON.parse(fs.readFileSync(dataPath, 'utf-8'));+ data.icons = [{id: 'cross', export: 'CrossIcon', words: ['cross']}];+ fs.writeFileSync(dataPath, `${JSON.stringify(data, null, 2)}\n`);+ const before = fs.readFileSync(dataPath, 'utf-8');++ reread.calls = 0;+ // The first lookup finds the set; the read-back after the writes fails.+ reread.failOn = 2;+ await expect(+ iconNewDefinition('crossOut', {+ cwd: tmpDir,+ description: 'Cross something out.',+ words: ['strike', 'cross'],+ icon: 'cross',+ }),+ ).rejects.toThrow('the set did not read back');+ expect(reread.calls).toBe(2);+ expect(fs.readFileSync(dataPath, 'utf-8')).toBe(before);+ expect(+ fs.existsSync(path.join(set, 'definitions', 'crossOut.doc.mjs')),+ ).toBe(false);++ // With the read-back passing, the same call writes both.+ reread.failOn = 0;+ await iconNewDefinition('crossOut', {+ cwd: tmpDir,+ description: 'Cross something out.',+ words: ['strike', 'cross'],+ icon: 'cross',+ });+ expect(JSON.parse(fs.readFileSync(dataPath, 'utf-8')).map).toEqual({+ crossOut: 'cross',+ });+ });+});diff --git a/packages/cli/api/icon/new-set/new-set.mjs b/packages/cli/api/icon/new-set/new-set.mjsnew file mode 100644index 0000000000..63c1890686--- /dev/null+++ b/packages/cli/api/icon/new-set/new-set.mjs@@ -0,0 +1,32 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `icon.newSet` leaf (AST-084 FR13): start an icon set in the local+ * integration package.+ *+ * @output the `icon.newSet` envelope+ * @position api/icon/new-set — dispatched by the `experimental icon new-set`+ * command+ */++import {addIconSet, refuseOutsideProject} from '../_adapter.mjs';+import {refuseOtherOptions} from '../_options.mjs';++/**+ * Start an icon set in the local integration package: `astryx experimental+ * icon new-set` (AST-084). Experimental (spec:AST-017 FR27).+ * @experimental+ * @param {string} name+ * @param {import('../icon.type.mjs').IconNewSetOptions} [options]+ * @returns {Promise<import('../icon.type.mjs').IconNewSetResponse>}+ */+export async function iconNewSet(name, options = {}) {+ refuseOtherOptions('icon-set', options);+ refuseOutsideProject(+ options.cwd ?? process.cwd(),+ 'experimental icon new-set',+ 'the integration package',+ );+ const {data} = await addIconSet(name, options);+ return {type: 'icon.newSet', data};+}diff --git a/packages/cli/api/icon/new-set/new-set.test.mjs b/packages/cli/api/icon/new-set/new-set.test.mjsnew file mode 100644index 0000000000..0c16fbc700--- /dev/null+++ b/packages/cli/api/icon/new-set/new-set.test.mjs@@ -0,0 +1,348 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {integrationAdd} from '../../integration/add-contribution.mjs';+import {iconNewSet} from './new-set.mjs';+import {discoverIconSetDirectory} from '../../../foundation/discovery/icon-set-discovery.mjs';++/** @type {string} */+let tmpDir;++/**+ * @param {{manifest?: string | null, files?: string[] | null, name?: string | null, license?: string}} [opts]+ */+function setup({+ manifest = 'export default {};\n',+ files = ['dist'],+ name = '@acme/icons',+ license,+} = {}) {+ /** @type {Record<string, unknown>} */+ const pkg = {version: '1.0.0'};+ if (name != null) pkg.name = name;+ if (license != null) pkg.license = license;+ if (files != null) pkg.files = files;+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ `${JSON.stringify(pkg, null, 2)}\n`,+ );+ if (manifest != null) {+ fs.writeFileSync(path.join(tmpDir, 'astryx.integration.mjs'), manifest);+ }+}++/** @param {string} file */+const read = file => fs.readFileSync(path.join(tmpDir, file), 'utf-8');++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-add-icon-set-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('iconNewSet (experimental icon new-set)', () => {+ it('refuses a package.json whose files is not an array of strings, and writes nothing', async () => {+ setup({license: 'MIT'});+ const pkgFile = path.join(tmpDir, 'package.json');+ fs.writeFileSync(+ pkgFile,+ `${JSON.stringify({...JSON.parse(read('package.json')), files: 'dist'}, null, 2)}\n`,+ );+ const pkgBefore = read('package.json');+ const manifestBefore = read('astryx.integration.mjs');+ await expect(iconNewSet('outline', {cwd: tmpDir})).rejects.toThrow(+ /files must be an array of strings/u,+ );+ expect(read('package.json')).toBe(pkgBefore);+ expect(read('astryx.integration.mjs')).toBe(manifestBefore);+ expect(fs.existsSync(path.join(tmpDir, 'icon-sets'))).toBe(false);+ });++ it('refuses a manifest that spreads another object where experimental would go, and writes nothing', async () => {+ setup({+ license: 'MIT',+ manifest:+ "const shared = {experimental: {other: './other'}};\n\nexport default {\n ...shared,\n};\n",+ });+ const pkgBefore = read('package.json');+ const manifestBefore = read('astryx.integration.mjs');+ await expect(iconNewSet('outline', {cwd: tmpDir})).rejects.toThrow(+ /spreads another object/u,+ );+ expect(read('package.json')).toBe(pkgBefore);+ expect(read('astryx.integration.mjs')).toBe(manifestBefore);+ const left = fs.existsSync(path.join(tmpDir, 'icon-sets'))+ ? fs+ .readdirSync(path.join(tmpDir, 'icon-sets'), {recursive: true})+ .filter(each =>+ fs.statSync(path.join(tmpDir, 'icon-sets', String(each))).isFile(),+ )+ : [];+ expect(left).toEqual([]);+ });++ it('names the line for the entry file, relative to it, when the entry is not at the package root', async () => {+ setup({license: 'MIT'});+ const pkgFile = path.join(tmpDir, 'package.json');+ fs.writeFileSync(+ pkgFile,+ JSON.stringify({+ ...JSON.parse(read('package.json')),+ type: 'module',+ exports: {'.': './src/index.js'},+ }),+ );+ fs.mkdirSync(path.join(tmpDir, 'src'));+ fs.writeFileSync(path.join(tmpDir, 'src', 'index.js'), 'export {};\n');+ const result = await iconNewSet('outline', {cwd: tmpDir});+ expect(result.data.notes).toEqual([+ "Add `export * from '../icon-sets/outline/outline.generated.js';` to src/index.js, so the icons import from @acme/icons.",+ 'Run `astryx integration check` to see the icon definitions still to map.',+ ]);+ });++ it('adds no export line when the entry already exports the generated module', async () => {+ setup({license: 'MIT'});+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({+ ...JSON.parse(read('package.json')),+ type: 'module',+ exports: {'.': './src/index.js'},+ }),+ );+ fs.mkdirSync(path.join(tmpDir, 'src'));+ fs.writeFileSync(+ path.join(tmpDir, 'src', 'index.js'),+ "export * from '../icon-sets/outline/outline.generated.js';\n",+ );+ const result = await iconNewSet('outline', {cwd: tmpDir});+ expect(result.data.notes).toEqual([+ 'Run `astryx integration check` to see the icon definitions still to map.',+ ]);+ });++ it('writes a typed descriptor and a starter data file, declares the root, and adds it to files', async () => {+ setup({license: 'MIT'});+ const result = await iconNewSet('outline', {cwd: tmpDir});++ expect(result).toEqual({+ type: 'icon.newSet',+ data: {+ kind: 'icon-set',+ name: 'outline',+ root: {path: './icon-sets', created: true},+ manifest: 'astryx.integration.mjs',+ files: [+ 'icon-sets/outline/outline.doc.mjs',+ 'icon-sets/outline/outline.icons.json',+ 'icon-sets/outline/outline.generated.js',+ 'icon-sets/outline/outline.generated.d.ts',+ 'package.json',+ 'astryx.integration.mjs',+ ],+ written: true,+ dryRun: false,+ icons: 0,+ notes: [+ // No exports and no root file: nothing to add the line to yet.+ '"@acme/icons" does not resolve yet: point its package.json "exports" at a file that has `export * from \'./icon-sets/outline/outline.generated.js\';`.',+ 'Run `astryx integration check` to see the icon definitions still to map.',+ ],+ },+ });+ // The generated module starts with an empty theme map, and its types.+ expect(read('icon-sets/outline/outline.generated.js')).toContain(+ 'export const themeIcons = {};',+ );+ expect(read('icon-sets/outline/outline.generated.d.ts')).toContain(+ 'export declare const themeIcons: {};',+ );++ const doc = read('icon-sets/outline/outline.doc.mjs');+ expect(doc).toContain(+ "/** @type {import('@astryxdesign/cli/authoring').IconSetDoc} */",+ );+ expect(doc).toContain("type: 'icon-set'");+ expect(doc).toContain("name: 'outline'");+ expect(doc).toContain("license: 'MIT'");+ expect(JSON.parse(read('icon-sets/outline/outline.icons.json'))).toEqual({+ schemaVersion: 1,+ module: '@acme/icons',+ generated: './icon-sets/outline/outline.generated.js',+ themeMap: 'themeIcons',+ map: {},+ icons: [],+ });+ expect(read('astryx.integration.mjs')).toMatch(+ /iconSets:\s*['"]\.\/icon-sets['"]/u,+ );+ expect(JSON.parse(read('package.json')).files).toEqual([+ 'dist',+ 'icon-sets',+ 'astryx.integration.mjs',+ ]);++ // The written set is a valid, discoverable set.+ const {sets, errors} = discoverIconSetDirectory(+ path.join(tmpDir, 'icon-sets'),+ '@acme/icons',+ );+ expect(errors).toEqual([]);+ expect(sets.map(set => [set.name, set.displayName, set.license])).toEqual([+ ['outline', 'Outline', 'MIT'],+ ]);+ });++ it('creates the manifest on first add and never creates a files field', async () => {+ setup({manifest: null, files: null});+ const result = await iconNewSet('brand-glyphs', {cwd: tmpDir});+ expect(result.data.root).toEqual({path: './icon-sets', created: true});+ expect(result.data.files).toContain('astryx.integration.mjs');+ expect(read('astryx.integration.mjs')).toContain('experimental: {');+ expect(read('astryx.integration.mjs')).toContain("iconSets: './icon-sets'");+ expect(JSON.parse(read('package.json')).files).toBeUndefined();+ // No package license: the descriptor says so instead of guessing one.+ expect(read('icon-sets/brand-glyphs/brand-glyphs.doc.mjs')).toContain(+ "license: 'UNLICENSED'",+ );+ });++ it('uses an existing custom root and does not redeclare it', async () => {+ setup({+ manifest: "export default {experimental: {iconSets: './glyphs'}};\n",+ });+ const result = await iconNewSet('outline', {cwd: tmpDir});+ expect(result.data.root).toEqual({path: './glyphs', created: false});+ expect(result.data.files).not.toContain('astryx.integration.mjs');+ expect(+ fs.existsSync(path.join(tmpDir, 'glyphs/outline/outline.icons.json')),+ ).toBe(true);+ });++ it('dry run predicts the real write without changing files', async () => {+ setup();+ const before = read('astryx.integration.mjs');+ const plan = await iconNewSet('outline', {+ cwd: tmpDir,+ dryRun: true,+ });+ expect(plan.data.written).toBe(false);+ expect(plan.data.dryRun).toBe(true);+ expect(fs.existsSync(path.join(tmpDir, 'icon-sets'))).toBe(false);+ expect(read('astryx.integration.mjs')).toBe(before);++ const real = await iconNewSet('outline', {cwd: tmpDir});+ expect(real.data.files).toEqual(plan.data.files);+ expect(real.data.root).toEqual(plan.data.root);+ });++ it('refuses to overwrite an existing descriptor or data file', async () => {+ setup();+ await iconNewSet('outline', {cwd: tmpDir});+ const doc = read('icon-sets/outline/outline.doc.mjs');+ await expect(iconNewSet('outline', {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_FILE_EXISTS',+ });+ expect(read('icon-sets/outline/outline.doc.mjs')).toBe(doc);++ fs.mkdirSync(path.join(tmpDir, 'icon-sets/solid'));+ fs.writeFileSync(+ path.join(tmpDir, 'icon-sets/solid/solid.icons.json'),+ '{}',+ );+ await expect(iconNewSet('solid', {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_FILE_EXISTS',+ });+ expect(+ fs.existsSync(path.join(tmpDir, 'icon-sets/solid/solid.doc.mjs')),+ ).toBe(false);+ });++ it('rolls back every write when the written set does not verify', async () => {+ // Another set under the root is invalid, but only the new set must+ // verify; an invalid neighbour does not block the write.+ setup();+ fs.mkdirSync(path.join(tmpDir, 'icon-sets/broken'), {recursive: true});+ const ok = await iconNewSet('outline', {cwd: tmpDir});+ expect(ok.data.written).toBe(true);++ // A root that resolves to a file cannot hold a set: nothing is left behind.+ setup({+ manifest: "export default {experimental: {iconSets: './taken'}};\n",+ });+ fs.writeFileSync(path.join(tmpDir, 'taken'), 'not a directory');+ const pkgBefore = read('package.json');+ await expect(iconNewSet('outline', {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_WRITE_FAILED',+ });+ expect(read('package.json')).toBe(pkgBefore);+ expect(read('taken')).toBe('not a directory');+ });++ it('rejects a name that is not lower-kebab, a root outside the package, and an unnamed package', async () => {+ setup();+ for (const bad of ['Outline', '../x', 'a_b', '']) {+ await expect(iconNewSet(bad, {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_INVALID_ARGUMENT',+ });+ }+ setup({+ manifest: "export default {experimental: {iconSets: '../outside'}};\n",+ });+ await expect(iconNewSet('outline', {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_PATH_TRAVERSAL',+ });+ setup({name: null});+ await expect(iconNewSet('outline', {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_INVALID_ARGUMENT',+ });+ });++ it('refuses an option of another kind', async () => {+ setup();+ await expect(+ iconNewSet('outline', {+ cwd: tmpDir,+ .../** @type {any} */ ({to: '1.0.0'}),+ }),+ ).rejects.toMatchObject({code: 'ERR_INVALID_ARGUMENT'});+ });++ it('is not an integrationAdd kind: the stable command gains no experimental kind', async () => {+ setup();+ for (const kind of ['icon-set', 'icon-definition']) {+ await expect(+ integrationAdd(/** @type {any} */ (kind), 'outline', {cwd: tmpDir}),+ ).rejects.toMatchObject({+ code: 'ERR_INVALID_ARGUMENT',+ message: expect.stringContaining('Unknown contribution kind'),+ });+ }+ });++ it('nests the root in an existing experimental object', async () => {+ setup({+ manifest: "export default {themes: './themes', experimental: {}};\n",+ });+ await iconNewSet('outline', {cwd: tmpDir});+ const manifest = read('astryx.integration.mjs');+ expect(manifest).toContain("themes: './themes'");+ expect(manifest.match(/experimental:/g)).toHaveLength(1);+ expect(manifest).toContain("iconSets: './icon-sets'");+ });+});++describe('experimental icon authoring API', () => {+ it('exports iconNewSet and iconNewDefinition, and no integrationAdd icon kind', async () => {+ const api = await import('../../index.mjs');+ expect(api.iconNewSet).toBeTypeOf('function');+ expect(api.iconNewDefinition).toBeTypeOf('function');+ expect(api).not.toHaveProperty('integrationAddIconSet');+ expect(api).not.toHaveProperty('integrationAddIconDefinition');+ });+});diff --git a/packages/cli/api/icon/search/search.mjs b/packages/cli/api/icon/search/search.mjsnew file mode 100644index 0000000000..08963a3885--- /dev/null+++ b/packages/cli/api/icon/search/search.mjs@@ -0,0 +1,50 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `icon.search` leaf (AST-084 FR6): find icons by meaning across every+ * installed set, ranked, with each match's import line.+ *+ * @input a query, an optional set selector, and a limit+ * @output the `icon.search` envelope+ * @position api/icon/search — dispatched by ../icon.mjs+ */++import {AstryxError} from '../../error.mjs';+import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';+import {loadIconSets} from '../_adapter.mjs';+import {closest, rankIcons, setsNamed, withdrawnReason} from '../_records.mjs';++/**+ * Rank every installed icon against a query.+ * @param {string} query+ * @param {{cwd: string, set?: string, limit: number}} options+ * @returns {Promise<import('../icon.type.mjs').IconSearchResponse>}+ */+export async function iconSearch(query, {cwd, set, limit}) {+ const {sets, withdrawn} = await loadIconSets(cwd);+ let searched = sets;+ if (set != null) {+ searched = setsNamed(sets, set);+ if (searched.length === 0) {+ throw new AstryxError(+ withdrawnReason(withdrawn, set) ??+ `No installed icon set named "${set}"`,+ closest(+ set,+ sets.flatMap(each => [each.name, `${each.package}/${each.name}`]),+ 'installed icon set',+ ),+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }+ }+ const matches = rankIcons(searched, query);+ return {+ type: 'icon.search',+ data: {+ query: query.trim(),+ matchCount: matches.length,+ matches: matches.slice(0, limit),+ },+ };+}diff --git a/packages/cli/api/icon/use/use.mjs b/packages/cli/api/icon/use/use.mjsnew file mode 100644index 0000000000..d8a9a29f5b--- /dev/null+++ b/packages/cli/api/icon/use/use.mjs@@ -0,0 +1,101 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `icon.use` leaf (AST-084 FR8): choose the project's icon set by+ * writing `experimental.iconSet` in astryx.config.+ *+ * @output the `icon.use` envelope+ * @position api/icon/use — dispatched by the `experimental icon use` command+ */++import * as path from 'node:path';+import {AstryxError} from '../../error.mjs';+import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';+import {+ iconSetConfigCliWarning,+ iconSetKey,+ loadIconProject,+ refuseOutsideProject,+ setConfigString,+} from '../_adapter.mjs';+import {closest, setsNamed, withdrawnReason} from '../_records.mjs';++/**+ * Make an installed set the project's icon set.+ * Experimental (spec:AST-017 FR27): may change or be removed in a patch+ * release.+ * @experimental+ * @param {string} selector a set name, or `<package>/<set>`+ * @param {{cwd?: string}} [options]+ * @returns {Promise<import('../icon.type.mjs').IconUseResponse>}+ */+export async function iconUse(selector, {cwd = process.cwd()} = {}) {+ if (typeof selector !== 'string' || selector.trim() === '') {+ throw new AstryxError(+ 'Name the icon set to use',+ [+ {+ name: 'astryx experimental icon --list',+ reason: 'list the installed sets',+ },+ ],+ ERROR_CODES.ERR_MISSING_ARGUMENT,+ );+ }+ refuseOutsideProject(cwd, 'experimental icon use', 'the app project');+ const {projectDir, sets, withdrawn} = await loadIconProject(cwd);+ const named = setsNamed(sets, selector);+ if (named.length === 0) {+ throw new AstryxError(+ withdrawnReason(withdrawn, selector) ??+ `No installed icon set is named "${selector}".`,+ closest(+ selector,+ sets.flatMap(set => [set.name, iconSetKey(set)]),+ 'an installed icon set',+ ),+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }+ if (named.length > 1) {+ throw new AstryxError(+ `Two installed packages ship an icon set named "${selector}"; name it with its package.`,+ named.map(set => ({+ name: iconSetKey(set),+ reason: `the set in ${set.package}`,+ })),+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ let written;+ try {+ written = setConfigString(projectDir, 'experimental.iconSet', selector);+ } catch (error) {+ // A protected config, or an unreadable protection source, keeps the+ // stable code every consumer-file writer uses (spec:AST-040 FR4, FR6).+ const code = /** @type {{code?: unknown}} */ (error)?.code;+ const stable = [+ ERROR_CODES.ERR_CODEMOD_PROTECTED,+ ERROR_CODES.ERR_CODEMOD_PROTECTION_SOURCE,+ ].find(each => each === code);+ throw new AstryxError(+ error instanceof Error ? error.message : String(error),+ undefined,+ stable ?? ERROR_CODES.ERR_WRITE_FAILED,+ );+ }+ // An older CLI the project may still run refuses the key just written.+ const warning = iconSetConfigCliWarning(projectDir);+ return {+ type: 'icon.use',+ data: {+ iconSet: selector,+ set: iconSetKey(named[0]),+ config: path.relative(projectDir, written.file).split(path.sep).join('/'),+ created: written.created,+ previous: written.previous,+ changed: written.changed,+ ...(warning ? {warning} : {}),+ },+ };+}diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjsindex 7f5b08e34e..a91c9a6628 100644--- a/packages/cli/api/index.mjs+++ b/packages/cli/api/index.mjs@@ -23,6 +23,12 @@export {component} from './component/component.mjs';export {docs} from './docs/docs.mjs';export {blog} from './blog/blog.mjs';+export {icon} from './icon/icon.mjs';+export {iconAdd} from './icon/add/add.mjs';+export {iconMap} from './icon/map/map.mjs';+export {iconUse} from './icon/use/use.mjs';+export {iconNewSet} from './icon/new-set/new-set.mjs';+export {iconNewDefinition} from './icon/new-definition/new-definition.mjs';export {discover} from './discover/discover.mjs';export {template} from './template/template.mjs';export {diff --git a/packages/cli/api/integration/_adapter.mjs b/packages/cli/api/integration/_adapter.mjsindex f42e2bef02..aa9ec256c0 100644--- a/packages/cli/api/integration/_adapter.mjs+++ b/packages/cli/api/integration/_adapter.mjs@@ -15,6 +15,7 @@ import {forEachIntegrationDoc,integrationSourceForDoc,} from '../../foundation/discovery/component-discovery.mjs';+import {Project} from '../../foundation/config/project.mjs';import {discoverIntegrationDocs} from '../../foundation/discovery/docs-discovery.mjs';import {packageDocTargets} from '../docs/_adapter.mjs';import {comparePropDocs} from '../../foundation/discovery/prop-drift.mjs';@@ -156,3 +157,20 @@ export async function integrationDocCommands(integration) {}return findDocCommands(discovered);}++/**+ * Whether the project at `cwd` opts in to icon sets (`experimental.iconSet`).+ * An installed package's experimental root is read only then+ * (spec:AST-017 FR27, spec:AST-084 FR0): a project without it gets what a CLI+ * without icon sets reports. A config that does not load opts in to nothing.+ * @param {string} cwd+ * @returns {Promise<boolean>}+ */+export async function projectUsesIconSets(cwd) {+ try {+ const project = await Project.load(cwd);+ return Boolean(project.config?.experimental?.iconSet);+ } catch {+ return false;+ }+}diff --git a/packages/cli/api/integration/add-contribution.mjs b/packages/cli/api/integration/add-contribution.mjsindex 0cc81b445c..97f66f9ca6 100644--- a/packages/cli/api/integration/add-contribution.mjs+++ b/packages/cli/api/integration/add-contribution.mjs@@ -25,7 +25,6 @@ import {findManifestObject,unwrapManifestExpression,patchIntegrationRoot,- findLocalIntegrationManifestOrNull,IntegrationRootConflictError,} from '../../foundation/integrations/manifest-writer.mjs';import {@@ -43,7 +42,11 @@ import {findIntegrationComponentDoc} from '../../foundation/discovery/component-import {parseAgentDocsField} from '../../authoring/integration/schema.mjs';import {integrationAddTheme} from './add-theme.mjs';import {- findPackageDir,+ KEBAB_NAME_RE,+ kebabToTitle,+ loadCurrentManifest,+ receipt,+ resolvePackage,projectPath,packageJsonUpdate,packageJsonFilesUpdate,@@ -53,7 +56,6 @@ import {// ── Name grammars ───────────────────────────────────────────────────const COMPONENT_NAME_RE = /^[A-Z][A-Za-z0-9]*$/;-const KEBAB_NAME_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;const TOPIC_NAME_RE = /^[\w-]+$/;// ── Default roots (used when the manifest declares nothing) ─────────@@ -67,91 +69,6 @@ const DEFAULT_ROOTS = {// ── Shared manifest / package plumbing ──────────────────────────────-/**- * Read package identity + resolve the manifest path.- * @param {string} cwd- */-function resolvePackage(cwd) {- const packageDir = findPackageDir(cwd);- const packageFile = path.join(packageDir, 'package.json');- /** @type {any} */- let pkg;- try {- pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- throw new AstryxError(- `Cannot read package.json: ${message}`,- undefined,- ERROR_CODES.ERR_INVALID_ARGUMENT,- );- }- const owner = typeof pkg.name === 'string' ? pkg.name : '(local integration)';- const existingManifest = findLocalIntegrationManifestOrNull(packageDir);- // The nearest package.json above the cwd may belong to another package (an- // app that contains the folder). Only a package that is already an- // integration is found from a subfolder; the first add runs in the package.- const here = path.resolve(cwd ?? process.cwd());- if (existingManifest == null && path.resolve(packageDir) !== here) {- throw new AstryxError(- `${here} has no package.json. The nearest is ${packageFile} (${owner}), which is not an Astryx integration yet. Run this in your integration package's own directory, next to its package.json.`,- undefined,- ERROR_CODES.ERR_INVALID_ARGUMENT,- );- }- const manifestFile =- existingManifest ?? path.join(packageDir, 'astryx.integration.mjs');- return {- packageDir,- packageFile,- pkg,- owner,- manifestFile,- manifestExists: existingManifest != null,- };-}--/**- * Load the current manifest's parsed object (or an empty object when no- * manifest exists yet).- * @param {string} manifestFile- * @param {boolean} manifestExists- * @returns {Promise<import('../../authoring/integration/type').AstryxIntegration>}- */-async function loadCurrentManifest(manifestFile, manifestExists) {- if (!manifestExists) return {};- return loadManifestObject(- manifestFile,- `Integration manifest ${path.basename(manifestFile)}`,- {fresh: true},- );-}--/**- * Build and return the common receipt shape.- * @param {import('./integration-authoring.type.mjs').IntegrationAddResponse['data']['kind']} kind- * @param {string} name- * @param {{path: string, created: boolean}|null} root- * @param {string} manifestPath- * @param {string[]} files- * @param {boolean} dryRun- * @returns {import('./integration-authoring.type.mjs').IntegrationAddResponse}- */-function receipt(kind, name, root, manifestPath, files, dryRun) {- return {- type: 'integration.add',- data: {- kind,- name,- root,- manifest: manifestPath,- files,- written: !dryRun,- dryRun,- },- };-}-// ── Helpers ─────────────────────────────────────────────────────────/** @param {string} slug */@@ -159,13 +76,6 @@ function kebabToPascal(slug) {return slug.replace(/(^|-)([a-z0-9])/gu, (_, _sep, ch) => ch.toUpperCase());}-/** @param {string} slug */-function kebabToTitle(slug) {- const words = slug.split(/[-_]+/u).filter(Boolean);- if (words.length === 0) return slug;- return words.map(word => word[0].toUpperCase() + word.slice(1)).join(' ');-}-// ── AST helper (for agent-doc manifest patching) ────────────────────/** @param {any} prop @param {string} name */@@ -1240,9 +1150,9 @@ function validateKindOptions(kind, options) {/*** Add one contribution to the local integration package.*- * @param {'component'|'doc'|'template'|'codemod'|'agent-doc'|'theme'} kind+ * @param {import('./integration-authoring.type.mjs').IntegrationAddKind} kind* @param {string} name- * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string, parent?: string, from?: string}} [options]+ * @param {import('./integration-authoring.type.mjs').IntegrationAddOptions} [options]* @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}*/export async function integrationAdd(kind, name, options = {}) {diff --git a/packages/cli/api/integration/add-contribution.test.mjs b/packages/cli/api/integration/add-contribution.test.mjsindex a0430ae707..408f17ae9c 100644--- a/packages/cli/api/integration/add-contribution.test.mjs+++ b/packages/cli/api/integration/add-contribution.test.mjs@@ -11,6 +11,7 @@ import {integrationAddDoc,integrationAddTemplate,} from './add-contribution.mjs';+import {iconNewSet} from '../icon/new-set/new-set.mjs';import {validateLocalIntegration} from './validate-integration.mjs';import {NAMESPACE_DOCS_CLI} from '../../foundation/integrations/cli-requirement.mjs';@@ -826,6 +827,7 @@ describe('typed descriptor conformance', () => {await integrationAdd('doc', 'my-guide', {cwd: tmpDir});await integrationAdd('template', 'my-page', {cwd: tmpDir});await integrationAdd('theme', 'ocean', {cwd: tmpDir});+ await iconNewSet('outline', {cwd: tmpDir});// Codemod and agent-doc keep their released formats for compatibility;// no new kind may copy those exceptions.@@ -834,6 +836,7 @@ describe('typed descriptor conformance', () => {['docs/my-guide.doc.mjs', 'ReferenceDoc'],['templates/my-page.doc.mjs', 'IntegrationTemplateDoc'],['themes/ocean/oceanTheme.doc.mjs', 'ThemeDoc'],+ ['icon-sets/outline/outline.doc.mjs', 'IconSetDoc'],]) {const source = fs.readFileSync(path.join(tmpDir, relativePath), 'utf-8');expect(source).toContain(`@astryxdesign/cli/authoring').${type}`);@@ -865,6 +868,7 @@ describe('public per-kind APIs', () => {to: '1.0.0',}),integrationAddAgentDoc('Use MyWidget.', {cwd: tmpDir, dryRun: true}),+ iconNewSet('outline', {cwd: tmpDir, dryRun: true}),]);expect(results.map(result => result.data.kind)).toEqual([@@ -873,6 +877,7 @@ describe('public per-kind APIs', () => {'template','codemod','agent-doc',+ 'icon-set',]);});});@@ -913,7 +918,7 @@ describe('dry-run receipts match the real write', () => {'declared roots and an exports map': {pkg: {files: ['dist'], exports: {'.': './dist/index.js'}},manifest:- "export default {\n components: './components',\n docs: './docs',\n templates: './templates',\n codemods: './codemods',\n themes: './themes',\n};\n",+ "export default {\n components: './components',\n docs: './docs',\n templates: './templates',\n codemods: './codemods',\n themes: './themes',\n experimental: {iconSets: './icon-sets'},\n};\n",},};/** @type {Array<[any, string, Record<string, unknown>]>} */@@ -925,6 +930,7 @@ describe('dry-run receipts match the real write', () => {['codemod', 'rename-widget', {to: '1.2.0'}],['agent-doc', 'Run acme verify before finishing.', {}],['theme', 'ocean', {}],+ ['icon-set', 'outline', {}],];/** Every file under the package, keyed by project path, with its bytes. */@@ -961,17 +967,15 @@ describe('dry-run receipts match the real write', () => {}const before = snapshot();- const plan = await integrationAdd(kind, name, {- cwd: tmpDir,- dryRun: true,- ...options,- });+ // An icon set is experimental: its own call, not an integrationAdd kind.+ const add = (/** @type {Record<string, unknown>} */ more) =>+ kind === 'icon-set'+ ? iconNewSet(name, {cwd: tmpDir, ...options, ...more})+ : integrationAdd(kind, name, {cwd: tmpDir, ...options, ...more});+ const plan = await add({dryRun: true});expect(snapshot()).toEqual(before);- const written = await integrationAdd(kind, name, {- cwd: tmpDir,- ...options,- });+ const written = await add({});const after = snapshot();const changed = Object.keys(after).filter(file => after[file] !== before[file])diff --git a/packages/cli/api/integration/add-helpers.mjs b/packages/cli/api/integration/add-helpers.mjsindex ad050715f3..697389aef5 100644--- a/packages/cli/api/integration/add-helpers.mjs+++ b/packages/cli/api/integration/add-helpers.mjs@@ -4,10 +4,12 @@* @file Shared helpers for integration contribution writers.** Hosts the atomic staged-write transaction, package.json files-array- * maintenance, package-dir resolution, and project-path normalization that- * every `integration add <kind>` command needs. `theme add` and `theme build`- * write through the same transaction. Stateless and side-effect-free- * outside of {@link applyWrites}.+ * maintenance, package-dir resolution, project-path normalization, and the+ * package and manifest plumbing (resolve the package, load its manifest, the+ * receipt shape, name grammar) that every `integration add <kind>` command+ * and the icon authoring writes (`experimental icon new-set`,+ * `new-definition`) need. `theme add` and `theme build` write through the+ * same transaction. Side-effect-free outside of {@link applyWrites}.*/import * as fs from 'node:fs';@@ -16,6 +18,8 @@ import {randomUUID} from 'node:crypto';import {AstryxError} from '../error.mjs';import {publishNewFile} from '../../foundation/fs/publish-file.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';+import {findLocalIntegrationManifestOrNull} from '../../foundation/integrations/manifest-writer.mjs';+import {loadManifestObject} from '../../foundation/integrations/integrations.mjs';/** @param {string} value */export function projectPath(value) {@@ -404,3 +408,101 @@ export function applyWrites(plans) {throw error;}}++// ── Shared by every contribution writer (integration add, icon authoring) ──++/** A lower-kebab name: an item id, a set name. */+export const KEBAB_NAME_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;++/**+ * Read package identity + resolve the manifest path.+ * @param {string} cwd+ */+export function resolvePackage(cwd) {+ const packageDir = findPackageDir(cwd);+ const packageFile = path.join(packageDir, 'package.json');+ /** @type {any} */+ let pkg;+ try {+ pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new AstryxError(+ `Cannot read package.json: ${message}`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ const owner = typeof pkg.name === 'string' ? pkg.name : '(local integration)';+ const existingManifest = findLocalIntegrationManifestOrNull(packageDir);+ // The nearest package.json above the cwd may belong to another package (an+ // app that contains the folder). Only a package that is already an+ // integration is found from a subfolder; the first add runs in the package.+ const here = path.resolve(cwd ?? process.cwd());+ if (existingManifest == null && path.resolve(packageDir) !== here) {+ throw new AstryxError(+ `${here} has no package.json. The nearest is ${packageFile} (${owner}), which is not an Astryx integration yet. Run this in your integration package's own directory, next to its package.json.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ const manifestFile =+ existingManifest ?? path.join(packageDir, 'astryx.integration.mjs');+ return {+ packageDir,+ packageFile,+ pkg,+ owner,+ manifestFile,+ manifestExists: existingManifest != null,+ };+}++/**+ * Load the current manifest's parsed object (or an empty object when no+ * manifest exists yet).+ * @param {string} manifestFile+ * @param {boolean} manifestExists+ * @returns {Promise<import('../../authoring/integration/type').AstryxIntegration>}+ */+export async function loadCurrentManifest(manifestFile, manifestExists) {+ if (!manifestExists) return {};+ return loadManifestObject(+ manifestFile,+ `Integration manifest ${path.basename(manifestFile)}`,+ {fresh: true},+ );+}++/**+ * Build and return the common receipt shape.+ * @template {import('./integration-authoring.type.mjs').IntegrationAddData['kind'] | import('../icon/icon.type.mjs').IconNewData['kind']} K+ * @param {K} kind+ * @param {string} name+ * @param {{path: string, created: boolean}|null} root+ * @param {string} manifestPath+ * @param {string[]} files+ * @param {boolean} dryRun+ * @returns {{type: 'integration.add', data: Omit<import('./integration-authoring.type.mjs').IntegrationAddData, 'kind'> & {kind: K, icons?: number, notes?: string[]}}}+ */+export function receipt(kind, name, root, manifestPath, files, dryRun) {+ return {+ type: 'integration.add',+ data: {+ kind,+ name,+ root,+ manifest: manifestPath,+ files,+ written: !dryRun,+ dryRun,+ },+ };+}++/** @param {string} slug */+export function kebabToTitle(slug) {+ const words = slug.split(/[-_]+/u).filter(Boolean);+ if (words.length === 0) return slug;+ return words.map(word => word[0].toUpperCase() + word.slice(1)).join(' ');+}diff --git a/packages/cli/api/integration/doc-stability.test.mjs b/packages/cli/api/integration/doc-stability.test.mjsnew file mode 100644index 0000000000..58d449fa09--- /dev/null+++ b/packages/cli/api/integration/doc-stability.test.mjs@@ -0,0 +1,216 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `doctor integration validate` (and so `integration check`) notes a+ * template or namespace doc that sets `stability`, which a CLI before 0.7.4+ * refuses and drops (spec:AST-017 FR27), unless the package's CLI peer range+ * admits only CLIs that read it. A note is additive data, never an issue: it+ * is not counted and never fails a check. A component doc or guide that sets+ * the field is not noted: older CLIs ignore it there.+ */++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 {runCli} from '../../test-utils/run-cli.mjs';++/** @type {string} */+let dir;++beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-doc-stability-'));+});+afterEach(() => {+ fs.rmSync(dir, {recursive: true, force: true});+});++/**+ * @param {Record<string, unknown>} pkgExtra+ * @param {string} stability the field, or '' for none+ */+function writePackage(pkgExtra, stability) {+ /** @param {string} rel @param {string} text */+ const write = (rel, text) => {+ fs.mkdirSync(path.dirname(path.join(dir, rel)), {recursive: true});+ fs.writeFileSync(path.join(dir, rel), text);+ };+ write(+ 'package.json',+ JSON.stringify({name: '@acme/stab', version: '1.0.0', ...pkgExtra}),+ );+ write(+ 'astryx.integration.mjs',+ "export default {templates: './templates', docs: './docs', components: './components'};\n",+ );+ write(+ 'templates/stab-hero.tsx',+ 'export default function StabHero() { return null; }\n',+ );+ write(+ 'templates/stab-hero.doc.mjs',+ `export default {type: 'block', name: 'Stab hero', description: 'A hero block.', aspectRatio: 2, componentsUsed: []${stability}};\n`,+ );+ write(+ 'docs/stabns.doc.mjs',+ `export default {type: 'namespace', name: 'stabns', title: 'Stab', summary: 'Stab docs.'${stability}, slots: {guides: {title: 'Guides', accepts: {kinds: ['generic']}}}};\n`,+ );+ write(+ 'components/StabWidget.tsx',+ 'export function StabWidget() { return null; }\n',+ );+ write(+ 'components/StabWidget.doc.mjs',+ `/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */\nexport default {type: 'component', name: 'StabWidget', displayName: 'Stab Widget', category: 'Layout', usage: {description: 'A widget.', bestPractices: []}, props: []${stability}};\n`,+ );+}++/** @returns {Promise<any>} */+async function validated() {+ return (await validateIntegration(undefined, {cwd: dir})).data;+}++describe('olderCliNotes', () => {+ it('notes each template and namespace doc that sets stability, never as an issue', async () => {+ writePackage({}, ", stability: 'experimental'");+ const data = await validated();+ expect(+ data.olderCliNotes.map((/** @type {any} */ note) => [+ note.file,+ note.kind,+ ]),+ ).toEqual(+ expect.arrayContaining([+ ['docs/stabns.doc.mjs', 'namespace'],+ ['templates/stab-hero.doc.mjs', 'template'],+ ]),+ );+ expect(data.olderCliNotes).toHaveLength(2);+ for (const note of data.olderCliNotes) {+ expect(note.message).toContain('CLIs before 0.7.4 drop this descriptor');+ expect(note.message).toContain('">=0.7.4"');+ }+ expect(+ data.olderCliNotes.find(+ (/** @type {any} */ note) => note.kind === 'namespace',+ ).message,+ ).toContain("hide the package's doc topics");+ // Not an issue: nothing about stability is counted.+ expect(JSON.stringify(data.issues)).not.toContain('stability');+ });++ it('never fails integration check --strict, with or without --next', async () => {+ writePackage(+ {peerDependencies: {'@astryxdesign/cli': '>=0.6.4'}},+ ", stability: 'experimental'",+ );+ // Not a `next` finding either: no minor release turns it into a warning.+ const ahead = await integrationCheck({cwd: dir, strict: true, next: true});+ expect(JSON.stringify(ahead.data.failures)).not.toContain('stability');+ const strict = await integrationCheck({cwd: dir, strict: true});+ expect(JSON.stringify(strict.data.failures)).not.toContain('stability');+ const validate = strict.data.checks.find(each => each.check === 'validate');+ expect(+ /** @type {any} */ (validate).response.data.olderCliNotes,+ ).toHaveLength(2);+ const text = await runCli(['integration', 'check', '--strict'], dir);+ expect(text.stdout).toContain('Notes for older CLIs');+ expect(text.stdout).toContain('templates/stab-hero.doc.mjs');+ }, 60_000);++ it('notes a template that declares icons, which 0.7.2 drops', async () => {+ writePackage({}, '');+ const doc = path.join(dir, 'templates', 'stab-hero.doc.mjs');+ fs.writeFileSync(+ doc,+ fs+ .readFileSync(doc, 'utf-8')+ .replace(+ 'componentsUsed: []',+ "componentsUsed: [], icons: {XIcon: 'close'}",+ ),+ );+ const data = await validated();+ expect(data.olderCliNotes).toEqual([+ expect.objectContaining({+ file: 'templates/stab-hero.doc.mjs',+ kind: 'template',+ field: 'icons',+ message: expect.stringContaining('declares `icons`: CLIs before 0.7.4'),+ }),+ ]);+ });++ it('notes a CLI peer range that starts at 0.7.3, which drops the descriptor', async () => {+ writePackage(+ {peerDependencies: {'@astryxdesign/cli': '>=0.7.3'}},+ ", stability: 'experimental'",+ );+ const data = await validated();+ expect(data.olderCliNotes).toEqual(+ expect.arrayContaining([+ expect.objectContaining({kind: 'template', field: 'stability'}),+ ]),+ );+ });++ it('says nothing when the CLI peer range starts at 0.7.4', async () => {+ writePackage(+ {peerDependencies: {'@astryxdesign/cli': '>=0.7.4'}},+ ", stability: 'experimental'",+ );+ expect(await validated()).not.toHaveProperty('olderCliNotes');+ });++ it('says nothing when no descriptor sets stability', async () => {+ writePackage({}, '');+ expect(await validated()).not.toHaveProperty('olderCliNotes');+ });+});++describe('template icons a template never imports', () => {+ it('notes each `icons` key the source does not import, never as an issue', async () => {+ writePackage({peerDependencies: {'@astryxdesign/cli': '>=0.7.4'}}, '');+ const doc = path.join(dir, 'templates', 'stab-hero.doc.mjs');+ fs.writeFileSync(+ doc,+ fs+ .readFileSync(doc, 'utf-8')+ .replace(+ 'componentsUsed: []',+ "componentsUsed: [], icons: {BinGlyph: 'delete', XIcon: 'close'}",+ ),+ );+ fs.writeFileSync(+ path.join(dir, 'templates', 'stab-hero.tsx'),+ "import {BinGlyph} from '@acme/library';\nexport default function StabHero() { return <BinGlyph />; }\n",+ );+ const data = await validated();+ expect(+ data.notes.filter(+ (/** @type {any} */ note) => note.code === 'template_icon_not_imported',+ ),+ ).toEqual([+ {+ code: 'template_icon_not_imported',+ message: expect.stringContaining(+ 'templates/stab-hero.doc.mjs declares icon "XIcon" in `icons`, which templates/stab-hero.tsx does not import',+ ),+ },+ ]);+ expect(JSON.stringify(data.issues)).not.toContain('XIcon');+ const strict = await integrationCheck({cwd: dir, strict: true});+ expect(JSON.stringify(strict.data.failures)).not.toContain('XIcon');+ // A note that is never counted: no `next`, so --next does not count it.+ const ahead = await integrationCheck({cwd: dir, strict: true, next: true});+ expect(JSON.stringify(ahead.data.failures)).not.toContain('XIcon');+ const validate = ahead.data.checks.find(each => each.check === 'validate');+ expect(+ /** @type {any} */ (validate).response.data.notes.find(+ (/** @type {any} */ note) => note.code === 'template_icon_not_imported',+ ),+ ).not.toHaveProperty('next');+ }, 60_000);+});diff --git a/packages/cli/api/integration/integration-authoring.type.mjs b/packages/cli/api/integration/integration-authoring.type.mjsindex ae1e455068..3beb79f55a 100644--- a/packages/cli/api/integration/integration-authoring.type.mjs+++ b/packages/cli/api/integration/integration-authoring.type.mjs@@ -55,6 +55,7 @@* @property {string} [extends]* @property {string} [parent]* @property {string} [to]+ * @property {string} [from]*//**diff --git a/packages/cli/api/integration/pack-check.mjs b/packages/cli/api/integration/pack-check.mjsindex 5b9826b16e..621599aecd 100644--- a/packages/cli/api/integration/pack-check.mjs+++ b/packages/cli/api/integration/pack-check.mjs@@ -1635,9 +1635,12 @@ export async function integrationPackCheck(options = {}) {}// Validate the extracted tree as an installed integration+ // The packed tree is the package being authored: its icon sets are+ // checked whatever the scratch folder's config says.const packedResult = await validateInstalledIntegration(pkgName,scratchBase,+ {iconSets: true},);for (const issue of packedResult.issues) {diff --git a/packages/cli/api/integration/pack-check.type.mjs b/packages/cli/api/integration/pack-check.type.mjsindex d114e02174..e7d446607f 100644--- a/packages/cli/api/integration/pack-check.type.mjs+++ b/packages/cli/api/integration/pack-check.type.mjs@@ -28,6 +28,7 @@* @property {{version: string, id: string}[]} codemods* @property {string[]} docs* @property {string[]} agentDocsAppend+ * @property {string[]} [iconSets] - Icon set names; present only when the package declares `experimental.iconSets`. Experimental: may change or be removed in a patch release.*//**@@ -59,7 +60,9 @@/*** @typedef {object} PackCheckInventoryRoot- * @property {'themes'|'components'|'templates'|'codemods'|'docs'} kind+ * @property {'themes'|'components'|'templates'|'codemods'|'docs'|'iconSets'} kind+ * `iconSets` is the experimental icon-set root: it may change or be removed+ * in a patch release.* @property {string} path* @property {number} expectedFiles* @property {string[]} missingFilesdiff --git a/packages/cli/api/integration/validate-installed-icon-sets.test.mjs b/packages/cli/api/integration/validate-installed-icon-sets.test.mjsnew file mode 100644index 0000000000..9e9a20760e--- /dev/null+++ b/packages/cli/api/integration/validate-installed-icon-sets.test.mjs@@ -0,0 +1,67 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `validateInstalledIntegration` reads an installed package's icon sets+ * only when the project opts in with `experimental.iconSet` (spec:AST-017+ * FR27, spec:AST-084 FR0, FR17); `iconSets: true` (pack-check's packed copy)+ * checks them whatever the project says.+ */++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 {validateInstalledIntegration} from './validate-integration.mjs';+import {writeIconSetProject} from '../../test-utils/icon-set-fixture.mjs';++/** @type {string} */+let tmp;+beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-validate-installed-'));+});+afterEach(() => {+ fs.rmSync(tmp, {recursive: true, force: true});+});++/** @param {boolean} optIn */+function project(optIn) {+ // Each project its own folder: a config module is imported once per path.+ return writeIconSetProject(path.join(tmp, optIn ? 'opted-in' : 'without'), {+ config: {+ integrations: ['@acme/glyphs'],+ ...(optIn ? {experimental: {iconSet: 'glyphs'}} : {}),+ },+ });+}++/** @param {{issues: Array<{code: string}>}} result */+const iconCodes = result =>+ result.issues.map(issue => issue.code).filter(code => /icon/u.test(code));++describe('an installed package with icon sets', () => {+ it('is checked for them only when the project sets experimental.iconSet', async () => {+ const without = await validateInstalledIntegration(+ '@acme/glyphs',+ project(false),+ );+ expect(iconCodes(without)).toEqual([]);+ expect(without).not.toHaveProperty('iconSets');+ expect(without.integration?.iconSets).toBeUndefined();++ const opted = await validateInstalledIntegration(+ '@acme/glyphs',+ project(true),+ );+ expect(iconCodes(opted)).toContain('icon_builtin_definition_missing');+ expect(opted.iconSets).toEqual([expect.objectContaining({set: 'glyphs'})]);+ });++ it('is checked with iconSets: true whatever the project says', async () => {+ const forced = await validateInstalledIntegration(+ '@acme/glyphs',+ project(false),+ {iconSets: true},+ );+ expect(iconCodes(forced)).toContain('icon_builtin_definition_missing');+ });+});diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjsindex 0ab793005c..4929827f47 100644--- a/packages/cli/api/integration/validate-integration.mjs+++ b/packages/cli/api/integration/validate-integration.mjs@@ -36,10 +36,17 @@ import * as path from 'node:path';import {assertWithin} from '../../foundation/fs/path-safety.mjs';import {normalizeProviderId} from '../../foundation/identity/provider-identity.mjs';import {integrationDocTypes} from '../docs/_adapter.mjs';+import {+ iconSetCoverage,+ iconSetIssues,+} from '../../foundation/discovery/icon-set-checks.mjs';+import {olderCliNotes} from '../../foundation/discovery/doc-stability.mjs';+import {templateIconNotes} from '../../foundation/discovery/template-icon-notes.mjs';import {integrationDocConsistency} from '../../foundation/discovery/doc-consistency.mjs';import {integrationDocCommands,integrationDocTargets,+ projectUsesIconSets,} from './_adapter.mjs';import {THEME_SLUG_RE,@@ -111,6 +118,9 @@ export {validateLoadedIntegration, isListedIssue};* may not fail `--strict` until the next (architecture:cli-surface INV35);* `integration verify` still fails on a package.json npm cannot pack.* @property {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} [integration]+ * @property {import('../../foundation/discovery/icon-set-checks.mjs').IconSetCoverage[]} [iconSets]+ * Which definitions each icon set leaves unmapped (spec:AST-084 FR15).+ * @property {import('../../foundation/discovery/doc-stability.mjs').OlderCliNote[]} [olderCliNotes]* @property {import('./validate-integration.type.mjs').PublicImportsReport} [publicImports]* what the public-import check could not judge*/@@ -299,15 +309,23 @@ async function findUnreachableContributionIssues(* Shared core for the local and installed entry points.* @param {string} packageDir* @param {{name: string, version?: string}} identity- * @param {{scanUnreachable?: boolean, own?: boolean, cwd?: string}} [options]+ * @param {{scanUnreachable?: boolean, own?: boolean, cwd?: string, iconSets?: boolean}} [options]* `own`: the package is the one being authored in the current folder;- * `cwd`: the folder whose package manager an install command names+ * `cwd`: the folder whose package manager an install command names;+ * `iconSets`: read the experimental `experimental.iconSets` root (default+ * true). Off, the root is not resolved or checked and `iconSets` is not+ * filled, as in a CLI without icon sets.* @returns {Promise<ValidateResult>}*/async function validateAtPackageDir(packageDir,identity,- {scanUnreachable = false, own = false, cwd = packageDir} = {},+ {+ scanUnreachable = false,+ own = false,+ cwd = packageDir,+ iconSets = true,+ } = {},) {/** @type {Issue[]} */const issues = [];@@ -420,6 +438,9 @@ async function validateAtPackageDir(codemods: resolveRoot(manifest.codemods, 'codemods'),docs: resolveRoot(manifest.docs, 'docs'),themes: resolveRoot(manifest.themes, 'themes'),+ iconSets: iconSets+ ? resolveRoot(manifest.experimental?.iconSets, 'experimental.iconSets')+ : undefined,issuesUrl: manifest.issuesUrl,agentDocs: manifest.agentDocs,cliCommand: manifest.cliCommand,@@ -469,6 +490,16 @@ async function validateAtPackageDir(}if (loaded.themes && !rootProblem(loaded.themes))issues.push(...unreadThemeFolderIssues(packageDir, loaded));+ // The icon-set checks (AST-084 FR15): data against descriptor, module+ // exports, and theme map, all read statically.+ if (loaded.iconSets && !rootProblem(loaded.iconSets)) {+ /** @type {Map<string, import('../../foundation/discovery/icon-set-checks.mjs').IconSetUnchecked[]>} */+ const unchecked = new Map();+ issues.push(...iconSetIssues(packageDir, loaded, unchecked));+ // Which definitions each set leaves unmapped, and what the checks could+ // not judge: listed, never an issue.+ result.iconSets = iconSetCoverage(loaded, unchecked);+ }// What the docs say that no reader serves: a prop listed twice, an// overlay's text for a prop the doc lacks, an empty or unreachable section,// and an overlay of no topic.@@ -505,6 +536,25 @@ async function validateAtPackageDir()),);}+ // Authoring only: a template or namespace doc that sets `stability` is+ // dropped by a CLI before the release that reads it. Noted, never an issue.+ if (scanUnreachable) {+ /** @type {any} */+ let pkg = {};+ try {+ pkg = JSON.parse(+ fs.readFileSync(path.join(packageDir, 'package.json'), 'utf-8'),+ );+ } catch {+ // package.json problems are reported by their own check.+ }+ const notes = await olderCliNotes(loaded, pkg, packageDir);+ if (notes.length > 0) result.olderCliNotes = notes;+ // Each template `icons` key the template's source never imports: a note+ // with its fix, never an issue (spec:AST-084 FR10).+ const iconNotes = await templateIconNotes(loaded, packageDir);+ if (iconNotes.length > 0) (result.notes ??= []).push(...iconNotes);+ }return result;}@@ -652,9 +702,16 @@ function packageJsonFieldIssues(pkg, pkgJsonPath) {* at or above `cwd`, resolved the way the project loads it.* @param {string} spec package name* @param {string} [cwd]+ * @param {{iconSets?: boolean}} [options] `iconSets`: check the package's+ * experimental icon sets; by default only when the project at `cwd` sets+ * `experimental.iconSet`* @returns {Promise<ValidateResult>}*/-export async function validateInstalledIntegration(spec, cwd = process.cwd()) {+export async function validateInstalledIntegration(+ spec,+ cwd = process.cwd(),+ {iconSets} = {},+) {// The resolver throws (path-safety guard) on a spec with path segments,// `..`, or an absolute path. Every other malformed input to this command// degrades into a diagnostic — so catch it here and return an issue instead@@ -697,7 +754,7 @@ export async function validateInstalledIntegration(spec, cwd = process.cwd()) {return validateAtPackageDir(packageDir,{name: pkg.name ?? spec, version: pkg.version},- {cwd},+ {cwd, iconSets: iconSets ?? (await projectUsesIconSets(cwd))},);}@@ -869,6 +926,12 @@ export async function validateIntegration(pkg, options = {}) {...(docTypes ? {docTypes} : {}),...(docNames ? {docNames} : {}),...(blockComponents ? {blockComponents} : {}),+ // Additive, never counted: present only for a package with icon sets,+ // or with descriptors an older CLI drops.+ ...(result.found && result.iconSets ? {iconSets: result.iconSets} : {}),+ ...(result.found && result.olderCliNotes+ ? {olderCliNotes: result.olderCliNotes}+ : {}),// Template assets npm could not place, when there are any....(examples && examples.unchecked.length > 0? {diff --git a/packages/cli/api/integration/validate-integration.type.mjs b/packages/cli/api/integration/validate-integration.type.mjsindex 07c9f2f967..64f896f632 100644--- a/packages/cli/api/integration/validate-integration.type.mjs+++ b/packages/cli/api/integration/validate-integration.type.mjs@@ -39,7 +39,9 @@* "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, exampleAssets?: {status: 'checked', findings: [], unchecked: Array<{file: string, asset: string, reason: string}>}, 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, iconSets?: IconSetCoverage[], olderCliNotes?: OlderCliNote[]}} data+ * `iconSets` is experimental: it may change or be removed in a patch+ * release.* `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`@@ -110,6 +112,43 @@* @typedef {{status: 'checked', findings: [], unchecked: Array<{file: string, name: string, reason: string}>}} BlockComponentsReport*/+/**+ * Experimental (spec:AST-084 FR15): for a package that declares+ * `experimental.iconSets`, which icon definitions each valid set leaves+ * unmapped, and what the checks could not judge. Listed beside the issues and+ * never counted: mapping an optional definition is optional, an item not+ * checked is not a failure, and nothing here fails a check, even under+ * `--strict`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconSetCoverage+ * @property {string} set The set's name.+ * @property {Array<{name: string, description: string, words: string[]}>} unmappedDefinitions+ * Astryx's optional (not built-in) definitions the set's `map` does not+ * name. An unmapped built-in definition is an error issue instead.+ * @property {Array<{definition: string, icon: string}>} suggestions For each+ * unmapped definition (built-in, optional, or the set's own), the icon+ * whose whole id is the definition's name or one of its words, when one is.+ * @property {Array<{icon?: string, adapter?: string, entry?: string, reason: string}>} unchecked+ * What the checks could not judge, each with the reason: an icon export+ * whose module is an `exports` target not built yet, or that the reader+ * cannot prove either way (`icon`); an adapter export it cannot prove+ * (`adapter`); and a theme map or theme-map entry it cannot read+ * (`entry`).+ */++/**+ * A descriptor an older CLI drops: a page or block template, or a namespace+ * doc, that sets `stability`, or a template that declares `icons`, while the+ * package's `@astryxdesign/cli` peer range admits a release before 0.7.4.+ * Listed beside the issues for the package being authored, and never counted+ * or failing a check.+ * @typedef {object} OlderCliNote+ * @property {string} file The descriptor, relative to the package.+ * @property {'template' | 'namespace'} kind+ * @property {'stability' | 'icons'} field The field an older CLI refuses.+ * @property {string} message What an older CLI does with it, and the fix.+ */+export {};/**diff --git a/packages/cli/api/integration/validateIntegration.doc.mjs b/packages/cli/api/integration/validateIntegration.doc.mjsindex 93da19c981..57c8f7718a 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`. 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.",+ "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. `data.olderCliNotes` ({file, kind: `template` | `namespace`, field, message}), for the local package, lists each descriptor field a release before 0.7.4 refuses while the package's CLI peer range admits one, such as `stability` on a template or namespace doc; it is present only when it has entries, is never counted, and never fails a check.",},],examples: [diff --git a/packages/cli/api/search/_gather-docs.mjs b/packages/cli/api/search/_gather-docs.mjsindex e3ccafba08..5b4c02961c 100644--- a/packages/cli/api/search/_gather-docs.mjs+++ b/packages/cli/api/search/_gather-docs.mjs@@ -19,6 +19,7 @@ import {sectionSummary,} from '../../foundation/discovery/docs-section-key.mjs';import {sectionProse, codeTerms, headings, plain} from './_doc-text.mjs';+import {loadAuthoringSelfDocs} from '../../foundation/discovery/authoring-self-docs.mjs';/** @typedef {import('./_lexical.mjs').Candidate} Candidate */@@ -39,6 +40,13 @@ import {sectionProse, codeTerms, headings, plain} from './_doc-text.mjs';export async function gatherDocs(cwd) {/** @type {Candidate[]} */const candidates = [];+ // Experimental docs (spec:AST-017 FR27) are never search results: they are+ // read on their own routes, so search answers as it would without them.+ const hidden = new Set(+ (await loadAuthoringSelfDocs()).loaded+ .filter(({doc}) => isExperimentalDoc(doc))+ .map(({doc}) => doc.name),+ );let catalog;try {catalog = await loadDocsCatalog(cwd);@@ -63,7 +71,17 @@ export async function gatherDocs(cwd) {// A topic that cannot be loaded is reported by the commands that own// integration issues; search just cannot index it.}- const doc = lowered?.doc ?? null;+ const read = lowered?.doc ?? null;+ if (isExperimentalDoc(read)) continue;+ const doc =+ read && hidden.size > 0 && Array.isArray(read.sections)+ ? {+ ...read,+ sections: read.sections.filter(+ (/** @type {any} */ section) => !hidden.has(section.id),+ ),+ }+ : read;// A flat topic lives in its topic level; its hits say so, and name// the package each section came from.const home = tree?.get(entry.name);@@ -102,6 +120,7 @@ export async function gatherDocs(cwd) {for (const node of tree.nodes.values()) {// A flat topic is indexed above, as a topic.if (node.ref?.flatTopic) continue;+ if (isExperimentalNode(tree, node)) continue;// A tree hit names where it lives: its ancestors' titles, then its own.const path = [...tree.ancestors(node).map(a => a.title), node.title];if (node.kind === 'generic') {@@ -175,6 +194,26 @@ export async function gatherDocs(cwd) {return candidates;}+/**+ * Is this doc an experimental surface's (spec:AST-017 FR21)?+ * @param {any} doc+ */+function isExperimentalDoc(doc) {+ return doc?.stability === 'experimental';+}++/**+ * Does this tree node document an experimental surface: a typed doc marked+ * experimental, or anything under an experimental namespace?+ * @param {any} tree+ * @param {any} node+ */+function isExperimentalNode(tree, node) {+ return [...tree.ancestors(node), node].some((/** @type {any} */ each) =>+ isExperimentalDoc(each.ref?.selfDoc),+ );+}+/*** The candidates one topic yields: the topic itself, and one per section when* it has more than one. A topic's command lists its sections, and a section'sdiff --git a/packages/cli/api/template/_adapter.mjs b/packages/cli/api/template/_adapter.mjsnew file mode 100644index 0000000000..49de3ea26e--- /dev/null+++ b/packages/cli/api/template/_adapter.mjs@@ -0,0 +1,36 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The `template` subject's adapter for icon mapping (AST-084 FR9):+ * reads the project's icon sets through the `Project` seam.+ *+ * @position api/template — adapter read by the template dispatcher+ */++import {Project} from '../../foundation/config/project.mjs';+import {NO_ICON_SETS} from '../../foundation/discovery/template-icons.mjs';++/**+ * The installed icon sets and the project's choice. A project the CLI cannot+ * read has no icon set, so templates are written unchanged.+ * @param {string} cwd+ * @returns {Promise<{sets: import('../../foundation/discovery/icon-set-discovery.mjs').DiscoveredIconSet[], choice: import('../../foundation/discovery/icon-set-discovery.mjs').IconSetChoice}>}+ */+export async function loadTemplateIconSets(cwd) {+ try {+ const project = await Project.load(cwd);+ const {sets, choice} = await project.iconSets();+ // Icon sets are experimental (spec:AST-017 FR27): a copied template+ // follows one only when the project opts in with `experimental.iconSet`.+ if (!choice.configured) return NO_ICON_SETS;+ return {sets, choice};+ } catch (error) {+ return {+ sets: [],+ choice: {+ status: 'none',+ reason: `The project could not be read, so no icon set applies: ${error instanceof Error ? error.message : String(error)}`,+ },+ };+ }+}diff --git a/packages/cli/api/template/copy/copy.mjs b/packages/cli/api/template/copy/copy.mjsindex c047a3041f..b2b947cfce 100644--- a/packages/cli/api/template/copy/copy.mjs+++ b/packages/cli/api/template/copy/copy.mjs@@ -20,15 +20,23 @@ 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';+import {+ NO_ICON_SETS,+ mapTemplateIcons,+} from '../../../foundation/discovery/template-icons.mjs';/*** Scaffold an already-resolved template to `targetPath` (relative to `cwd`) and* return the `template.copy` receipt.* @param {import('../../../foundation/discovery/template-adapter.mjs').DiscoveredTemplate} match- * @param {{targetPath: string, cwd: string, overwrite?: boolean}} ctx+ * @param {{targetPath: string, cwd: string, overwrite?: boolean, iconSets?: Parameters<typeof mapTemplateIcons>[1]}} ctx+ * `iconSets`: the project's icon sets; without them the icons are unchanged* @returns {import('../template.type.mjs').TemplateCopyResponse}*/-export function templateCopy(match, {targetPath, cwd, overwrite = false}) {+export function templateCopy(+ match,+ {targetPath, cwd, overwrite = false, iconSets = NO_ICON_SETS},+) {if (!fs.existsSync(match.filePath)) {throw new AstryxError(`No source file found for template "${match.dirName}"`,@@ -84,9 +92,16 @@ export function templateCopy(match, {targetPath, cwd, overwrite = false}) {// Strip demo image references so the scaffolded file renders without a// Meta-only network dependency. Read before any write, so a failure below// leaves nothing behind.- const {source: outputSource, demoMediaReplaced} = replaceDemoMedia(+ const {source: withMedia, demoMediaReplaced} = replaceDemoMedia(fs.readFileSync(match.filePath, 'utf-8'),);+ // Icons follow the project's icon set (AST-084 FR9). An icon with no match+ // keeps its import, so its library stays a needed dependency below.+ const {source: outputSource, icons} = mapTemplateIcons(+ withMedia,+ iconSets,+ match.icons,+ );try {fs.mkdirSync(outputDir, {recursive: true});fs.writeFileSync(outputFilePath, outputSource);@@ -115,6 +130,7 @@ export function templateCopy(match, {targetPath, cwd, overwrite = false}) {notes,missingPackages: missing,installCommand,+ ...(icons ? {icons} : {}),},};}diff --git a/packages/cli/api/template/show/show.mjs b/packages/cli/api/template/show/show.mjsindex f18fd319a3..fd493a23c4 100644--- a/packages/cli/api/template/show/show.mjs+++ b/packages/cli/api/template/show/show.mjs@@ -16,13 +16,19 @@ import {pkgOf,replaceDemoMedia,} from '../../../foundation/discovery/template-adapter.mjs';+import {+ NO_ICON_SETS,+ mapTemplateIcons,+} from '../../../foundation/discovery/template-icons.mjs';/*** Build the `template.show` envelope for an already-resolved template.* @param {import('../../../foundation/discovery/template-adapter.mjs').DiscoveredTemplate} match+ * @param {{iconSets?: Parameters<typeof mapTemplateIcons>[1]}} [options]+ * the project's icon sets; without them the template's icons are unchanged* @returns {import('../template.type.mjs').TemplateShowResponse}*/-export function templateShow(match) {+export function templateShow(match, {iconSets = NO_ICON_SETS} = {}) {if (!fs.existsSync(match.filePath)) {throw new AstryxError(`No source file found for template "${match.dirName}"`,@@ -34,9 +40,11 @@ export function templateShow(match) {// The source template.copy writes (spec:AST-028 FR7): a template printed and// pasted must not keep a media path only Astryx's previews serve, and the// caller is told how many it replaced, the way the copy receipt tells it.- const {source, demoMediaReplaced} = replaceDemoMedia(+ const {source: withMedia, demoMediaReplaced} = replaceDemoMedia(fs.readFileSync(match.filePath, 'utf-8'),);+ // Icons follow the project's icon set, as template.copy writes them.+ const {source, icons} = mapTemplateIcons(withMedia, iconSets, match.icons);return {type: 'template.show',@@ -48,6 +56,7 @@ export function templateShow(match) {components: extractComponents(match.filePath),source,demoMediaReplaced,+ ...(icons ? {icons} : {}),},};}diff --git a/packages/cli/api/template/template.mjs b/packages/cli/api/template/template.mjsindex a334861419..5b1f684134 100644--- a/packages/cli/api/template/template.mjs+++ b/packages/cli/api/template/template.mjs@@ -30,6 +30,7 @@ import {templateShow} from './show/show.mjs';import {templateSkeleton} from './skeleton/skeleton.mjs';import {templateCopy} from './copy/copy.mjs';import {templateCdn} from './cdn/cdn.mjs';+import {loadTemplateIconSets} from './_adapter.mjs';// Re-export the shared discovery/IO + cross-command helpers so this module// stays the single import surface for the template family (same exports as@@ -212,9 +213,12 @@ export async function template(name, options = {}) {return templateSkeleton(match, templates);}+ // The project's icon set decides how the template's icons are written+ // (AST-084 FR9): both the printed source and the copied file follow it.+ const iconSets = await loadTemplateIconSets(cwd);if (show || !targetPath) {- return templateShow(match);+ return templateShow(match, {iconSets});}- return templateCopy(match, {targetPath, cwd, overwrite});+ return templateCopy(match, {targetPath, cwd, overwrite, iconSets});}diff --git a/packages/cli/api/template/template.type.mjs b/packages/cli/api/template/template.type.mjsindex f2e78a833b..0508e58fa7 100644--- a/packages/cli/api/template/template.type.mjs+++ b/packages/cli/api/template/template.type.mjs@@ -55,6 +55,7 @@* @property {string[]} data.components* @property {string} data.source* @property {number} data.demoMediaReplaced Astryx demo media references (images, posters, videos) replaced in the returned source: 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 {TemplateIconsReport} [data.icons] Experimental, present only when the project sets `experimental.iconSet`: how the template's icons follow the project's icon set, each icon `mapped` (source and target) or `kept`, and the icon-set state. It may change or be removed in a patch release.*//**@@ -83,6 +84,20 @@* @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, or when several lockfiles leave the package manager undetermined; missingPackages still names the packages.+ * @property {TemplateIconsReport} [data.icons] Experimental, present only when the project sets `experimental.iconSet`: how the written file's icons follow the project's icon set, each icon `mapped` (source and target) or `kept`, and the icon-set state. It may change or be removed in a patch release.+ */++/**+ * How a template's icons follow the project's icon set (AST-084 FR10).+ * Without a project icon set (`status` `none`, `ambiguous`, or `missing`)+ * the source is unchanged and both lists are empty.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} TemplateIconsReport+ * @property {'selected' | 'none' | 'ambiguous' | 'missing' | 'withdrawn'} status The project's icon-set state.+ * @property {string | null} set The project's icon set as `<package>/<set>`, when selected.+ * @property {string} reason Why the project has that set, or none.+ * @property {Array<{source: {module: string, export: string}, target: {set: string, package: string, id: string, module: string, export: string}, by: 'match' | 'definition'}>} mapped Icons rewritten to the project's set, and the rule that chose each one: a reviewed `exact` or `strong` match, or the icon the set's `map` names for the icon definition the template declares.+ * @property {Array<{module: string | null, export: string, reason: string, suggestion?: {set: string, id: string, module: string, export: string, confidence: 'likely'}}>} kept Icons left as the template wrote them, with why, and a `likely` reviewed match as a suggestion when the project set has one. Every declared key is mapped or kept; `module` is null for a key the template does not import, and `export` is `default` for a default import and `*` for a namespace import.*//**diff --git a/packages/cli/api/upgrade/_adapter.mjs b/packages/cli/api/upgrade/_adapter.mjsindex b30a6675c8..a0bff6727d 100644--- a/packages/cli/api/upgrade/_adapter.mjs+++ b/packages/cli/api/upgrade/_adapter.mjs@@ -642,7 +642,8 @@ export async function runCoreCodemods(** @param {string} cwd* @param {string[]} [extraIntegrationSpecs] explicit `--integration` specs- * @returns {Promise<{postCodemodHooks: import('../../authoring/config/type').PostCodemodHook[], integrations: import('../../foundation/integrations/integrations.mjs').LoadedIntegration[], ledger: import('../../foundation/integrations/provider-resolution.mjs').ProviderLedger}>}+ * @returns {Promise<{postCodemodHooks: import('../../authoring/config/type').PostCodemodHook[], integrations: import('../../foundation/integrations/integrations.mjs').LoadedIntegration[], ledger: import('../../foundation/integrations/provider-resolution.mjs').ProviderLedger, iconSets: boolean}>}+ * `iconSets`: the project sets `experimental.iconSet`*/export async function loadProjectContext(cwd, extraIntegrationSpecs = []) {// The CLI debug preflight may already have imported this config before core@@ -711,7 +712,12 @@ export async function loadProjectContext(cwd, extraIntegrationSpecs = []) {],{codemods: true, prior: providerLedgerOf(project)},);- return {postCodemodHooks, integrations, ledger};+ return {+ postCodemodHooks,+ integrations,+ ledger,+ iconSets: Boolean(project.config.experimental?.iconSet),+ };}/**@@ -719,11 +725,24 @@ export async function loadProjectContext(cwd, extraIntegrationSpecs = []) {* nudge must not fail the upgrade) and is suppressed for --json/programmatic* callers (the silent logger).* @param {Array<import('../../foundation/integrations/integrations.mjs').LoadedIntegration>} integrations+ * @param {{iconSets?: boolean}} [options] `iconSets`: the project sets+ * `experimental.iconSet`. Without it a package's experimental icon-set root+ * is not checked (spec:AST-017 FR27, spec:AST-084 FR0), as in the project's+ * own issues.* @returns {Promise<void>}*/-export async function warnIntegrationIssues(integrations) {+export async function warnIntegrationIssues(integrations, {iconSets} = {}) {try {- await warnOnIntegrationIssues(integrations, {json: logger.silent});+ await warnOnIntegrationIssues(+ iconSets+ ? integrations+ : integrations.map(each =>+ each && typeof each === 'object'+ ? {...each, iconSets: undefined}+ : each,+ ),+ {json: logger.silent},+ );} catch {// Never let the nudge break the upgrade.}diff --git a/packages/cli/api/upgrade/run/run.mjs b/packages/cli/api/upgrade/run/run.mjsindex c6f2d39ae0..2cc10c17f3 100644--- a/packages/cli/api/upgrade/run/run.mjs+++ b/packages/cli/api/upgrade/run/run.mjs@@ -285,6 +285,8 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {let integrations;/** @type {import('../../../authoring/config/type').PostCodemodHook[]} */let postCodemodHooks;+ /** @type {boolean} */+ let iconSets;try {const projectContext = await loadProjectContext(cwd,@@ -292,6 +294,7 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {);postCodemodHooks = projectContext.postCodemodHooks;integrations = projectContext.integrations;+ iconSets = projectContext.iconSets;} catch (err) {const configErr = /** @type {Error} */ (err);const allProtected = coreResult?.protectedFiles ?? [];@@ -380,7 +383,7 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {// Non-blocking nudge for integration validation issues (suppressed for// programmatic/--json callers, i.e. the silent logger).- await warnIntegrationIssues(integrations);+ await warnIntegrationIssues(integrations, {iconSets});const integrationVersionGroups = await selectIntegrationCodemodsFor(integrations,diff --git a/packages/cli/assets/docs/tree/experimental.doc.mjs b/packages/cli/assets/docs/tree/experimental.doc.mjsnew file mode 100644index 0000000000..5bde723d8b--- /dev/null+++ b/packages/cli/assets/docs/tree/experimental.doc.mjs@@ -0,0 +1,31 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs cli/experimental`: the one docs route for experimental+ * features (spec:AST-017 FR27). Each experimental feature's docs place+ * themselves here, so nothing under this route reads as stable.+ */++/** @type {import('@astryxdesign/cli/authoring').NamespaceDoc} */+export const docs = {+ type: 'namespace',+ name: 'experimental',+ placement: {parent: 'namespace:cli', slot: 'guides', order: 90},+ stability: 'experimental',+ title: 'Experimental features',+ summary:+ 'Features you can try now that may change or be removed in a patch release.',+ keywords: ['experimental', 'experiment', 'preview', 'unstable'],+ slots: {+ guides: {+ title: 'Experimental features',+ accepts: {kinds: ['generic', 'namespace']},+ },+ },+ blocks: [+ {+ type: 'prose',+ text: 'Everything here is experimental: its commands (under `astryx experimental`), configuration (under `experimental` in astryx.config and in an integration manifest), output, and docs may change or be removed in any patch release, with no deprecation period. Nothing here changes what the rest of Astryx does unless you use it. A feature leaves this section when it becomes stable.',+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/icon-definitions.doc.mjs b/packages/cli/assets/docs/tree/icon-definitions.doc.mjsnew file mode 100644index 0000000000..679df3ba62--- /dev/null+++ b/packages/cli/assets/docs/tree/icon-definitions.doc.mjs@@ -0,0 +1,48 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs cli/experimental/icon-definitions`: every icon+ * definition, Astryx's and, in a project that sets `experimental.iconSet`,+ * each installed icon set's own. Experimental+ * (spec:AST-017 FR27), with the icon sets that use them.+ *+ * It never lists its children: it adopts every icon definition doc from every+ * package, so a new definition file appears here with no edit to this file.+ */++/** @type {import('@astryxdesign/cli/authoring').NamespaceDoc} */+export const docs = {+ type: 'namespace',+ name: 'icon-definitions',+ placement: {parent: 'namespace:experimental', slot: 'guides', order: 20},+ stability: 'experimental',+ title: 'Icon definitions',+ summary:+ 'Experimental. Every icon definition: what an icon stands for, and the shared name icon sets map their icons to.',+ keywords: [+ 'icon definition',+ 'icon definitions',+ 'icon names',+ 'which icon',+ 'icon map',+ ],+ slots: {+ definitions: {title: 'Definitions', accepts: {kinds: ['icon-definition']}},+ },+ adopts: [+ {+ source: {+ group: 'icon-definitions',+ kinds: ['icon-definition'],+ packages: 'all',+ },+ into: 'definitions',+ },+ ],+ blocks: [+ {+ type: 'prose',+ text: "An icon definition is one thing an icon stands for, such as `close` or `delete`. Every icon set registers its icons against definitions in its data file's `map`, and templates are written against definitions, so a project that switches icon sets gets the same definition from the new set. Built-in definitions are the shared names Core renders; every set maps them. A set may add its own definitions; in a project that sets `experimental.iconSet`, they are listed here with the package that ships them. `astryx experimental icon <definition>` finds the icon each installed set draws for it. Icon definitions are experimental: they may change or be removed in a patch release.",+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/icon-set-files.doc.mjs b/packages/cli/assets/docs/tree/icon-set-files.doc.mjsnew file mode 100644index 0000000000..2c67a48102--- /dev/null+++ b/packages/cli/assets/docs/tree/icon-set-files.doc.mjs@@ -0,0 +1,33 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs cli/experimental/icon-set-files`: every field of the+ * files an icon set is made of (the descriptor, the data file, and an icon+ * definition), one section each. Experimental (spec:AST-017 FR27): built+ * from the experimental authoring self-docs, which stable `astryx docs+ * authoring` never lists.+ */++import {buildExperimentalAuthoringSections} from '../../../foundation/discovery/authoring-self-docs.mjs';++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'icon-set-files',+ placement: {parent: 'namespace:experimental', slot: 'guides', order: 15},+ stability: 'experimental',+ title: 'Icon set files',+ category: 'guide',+ keywords: [+ 'icon set doc',+ 'icons.json',+ 'icon set data',+ 'icon definition doc',+ 'IconSetDoc',+ 'IconSetData',+ 'IconDefinitionDoc',+ ],+ description:+ 'Experimental. Every field of the files an icon set is made of: the descriptor, the data file, and an icon definition.',+ sections: await buildExperimentalAuthoringSections(),+};diff --git a/packages/cli/assets/docs/tree/icon-sets.doc.mjs b/packages/cli/assets/docs/tree/icon-sets.doc.mjsnew file mode 100644index 0000000000..a82377ea9b--- /dev/null+++ b/packages/cli/assets/docs/tree/icon-sets.doc.mjs@@ -0,0 +1,377 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs cli/experimental/icon-sets`: make an+ * icon set: register icons against icon definitions with the CLI, check the+ * set, and know how apps find its icons and how templates follow it.+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'icon-sets',+ placement: {parent: 'namespace:experimental', slot: 'guides', order: 10},+ stability: 'experimental',+ title: 'Icon sets',+ category: 'guide',+ keywords: [+ 'icon set',+ 'add icons',+ 'ship icons',+ 'icon library',+ 'icon definition',+ 'icons.json',+ 'integration icons',+ ],+ description:+ 'Experimental. Ship an icon set: register each icon against an icon definition, so apps find icons by meaning and templates use your icons.',+ sections: [+ {+ id: 'experimental',+ title: 'Experimental',+ content: [+ {+ type: 'prose',+ text: 'Icon sets are experimental: the `astryx experimental icon` commands, the `experimental.iconSet` key in astryx.config, the `experimental.iconSets` key in an integration manifest, the data file, icon definitions, and the output and JSON of all of them can change, or go away, in any patch release without a deprecation period. A project that does not set `experimental.iconSet` sees no change in any stable command, apart from: the marked `experimental` group in help and in `astryx manifest` (its command, and its `responseTypes` and `jsonSupported` entries); the marked experimental entries in the CLI reference listings; and a search for \"experimental\", which also finds the stable `stability` field of the field reference. Templates, discover, and doctor answer as they do with no icon set installed. With a package that ships icon sets installed and no opt-in, the warnings an older CLI gives about the manifest key `experimental` (in `astryx doctor` and `astryx doctor integration validate <package>`, and the one-line nudge other commands print to stderr) are gone. `astryx search` never returns icons or these docs; to find an icon by meaning, use `astryx experimental icon <words>`.',+ },+ ],+ },+ {+ id: 'how-it-works',+ title: 'How it works',+ content: [+ {+ type: 'prose',+ text: 'Astryx keeps a list of icon definitions: one file per meaning, like `close` or `delete` (`astryx docs cli/experimental/icon-definitions`). An icon set registers which of its icons draws each definition, in the `map` of its data file. Templates say which definition each of their icons draws, so a project that uses your set gets your icon for every definition you map. Every set maps the built-in definitions, the names Core renders itself.',+ },+ {+ type: 'prose',+ text: 'The CLI knows no icon library. You, or your agent, pick each icon from the library you wrap; the commands below verify it, write the files, and check the set.',+ },+ ],+ },+ {+ id: 'add-an-icon-set',+ title: 'Add an icon set',+ content: [+ {+ type: 'code',+ lang: 'bash',+ code: 'astryx experimental icon new-set outline',+ },+ {+ type: 'prose',+ text: "`outline.doc.mjs` is the descriptor: name, display name, description, and `license`, the SPDX license of the artwork (it starts as your package's own). `outline.icons.json` starts with no icons and an empty `map`; its `module` is your package name. `outline.generated.js` is the set's generated module, with its declaration file `outline.generated.d.ts`: the CLI writes both, and every icon and the theme map are exports of it. Every field is in {@link schema:icon-set-doc} and {@link schema:icon-set-data}.",+ },+ ],+ },+ {+ id: 'add-icons',+ title: 'Add icons one at a time',+ content: [+ {+ type: 'prose',+ text: 'Pick an icon from the library and ask which definitions fit it. Nothing is written yet:',+ },+ {+ type: 'code',+ lang: 'bash',+ code: 'astryx experimental icon add Bin --from @acme/glyph-library',+ },+ {+ type: 'prose',+ text: 'Each row is an Astryx definition (or one your set declares) with the exact command that adds the icon for it. Run one:',+ },+ {+ type: 'code',+ lang: 'bash',+ code: 'astryx experimental icon add Bin --from @acme/glyph-library --definition delete',+ },+ {+ type: 'prose',+ text: "The CLI reads the library's exports without running them and refuses a name the module does not export, suggesting close names. It adds the icon as `BinIcon` (id `bin`, words from its name), writes `export {Bin as BinIcon} from '@acme/glyph-library';` to the set's generated module, and sets `map.delete = \"bin\"`. Running it again changes nothing. Do not copy the definition's words into the icon: `astryx experimental icon` matches an icon by its own words and by the name and words of every definition it is mapped to.",+ },+ {+ type: 'prose',+ text: 'When no Astryx definition fits, add your own in the same command. It needs no pull request:',+ },+ {+ type: 'code',+ lang: 'bash',+ code: "astryx experimental icon add RotateCw --from @acme/glyph-library --new-definition rotate --description 'Rotate an image or shape.' --words turn,spin",+ },+ {+ type: 'prose',+ text: '`experimental icon map <definition> <icon>` points a definition at an icon the set already has, and `--remove` drops an entry. `experimental icon new-definition <name> --description ... --words ... --icon <id>` adds your own definition for an icon you already have.',+ },+ ],+ },+ {+ id: 'wrap-a-library',+ title: 'Or wrap a whole library',+ content: [+ {+ type: 'code',+ lang: 'bash',+ code: 'astryx experimental icon new-set outline --from @acme/glyph-library',+ },+ {+ type: 'prose',+ text: "Every component the library exports becomes an icon (an alias of one component is recorded once), named `<Name>Icon`, and `map` is filled only where a definition's name or one of its words is an icon's id. Run it again after a library release to refresh the icons; `map` entries whose icon still exists are kept, and the receipt names any that lost theirs.",+ },+ {+ type: 'prose',+ text: 'A library whose icons are data (objects or SVG strings) has no components to find: create the set, declare an `adapter` in its data file (see library shapes), and run the command again; every data export then becomes an icon through the adapter. When every icon export shares a leading word, such as `feather` in `featherEye` and `featherSun`, ids and export names leave it out: `featherEye` becomes id `eye`, exported as `EyeIcon`. The prefix is read over icon-like exports only: SCREAMING_CASE constants (`README`, `VERSION`), number and boolean exports, and, next to components or icon objects, plain strings are never icons. Leave out any other export that is not an icon with `--exclude meta,version`. `experimental icon add` reads the prefix the same way, and reuses the icon an export already has, so its commands need no `--id`.',+ },+ ],+ },+ {+ id: 'export-the-icons',+ title: 'How icons are exported',+ content: [+ {+ type: 'prose',+ text: "Every icon is a named export of your package's public entry, so apps, templates, and theme maps all import components from one place:",+ },+ {+ type: 'list',+ style: 'unordered',+ items: [+ "The data file's `module` is your package name or one of its package.json `exports` subpaths, never a file path. `integration check` fails otherwise.",+ "A variant is a named look the set supplies (for example outline or solid); size comes from CSS. List the names in `variants` in the data file and the one each icon's own export draws in `default`.",+ 'Each export is named `<Name>Icon`, and a variant `<Name><Variant>Icon`, such as `TrashSolidIcon`. `experimental icon add` names them that way; `integration check` warns on another name.',+ 'Each export is a React component: a function, a class, `forwardRef` or `memo`, or what your adapter returns. `integration check` fails on a plain object or string.',+ 'It accepts SVG props (`className`, `style`, `aria-*`, `width`, `height`), draws with `currentColor`, and fills its box (`1em` or `100%`), so `<Icon icon={TrashIcon} size="sm" />` sizes and colors it like a built-in icon. The CLI cannot check this statically; the test below can.',+ ],+ },+ {+ type: 'prose',+ text: "`experimental icon add` writes the set's generated module (`generated` in the data file) and its declaration file, which re-exports each component's own types and types each adapted icon as `ComponentType<SVGProps<SVGSVGElement>>`. Add one line to the file your package's entry points at, and to its types; the receipt names it:",+ },+ {+ type: 'code',+ lang: 'js',+ code: "export * from './icon-sets/outline/outline.generated.js';",+ },+ {+ type: 'prose',+ text: 'An optional render test you can copy:',+ },+ {+ type: 'code',+ lang: 'js',+ code: `import {renderToStaticMarkup} from 'react-dom/server';+import {createElement} from 'react';+import * as icons from '@acme/icons';++for (const [name, Icon] of Object.entries(icons)) {+ if (!name.endsWith('Icon')) continue;+ const html = renderToStaticMarkup(createElement(Icon, {className: 'x'}));+ if (!html.includes('class="x"')) throw new Error(\`\${name} drops className\`);+ if (!html.includes('currentColor')) throw new Error(\`\${name} has a fixed color\`);+}`,+ },+ ],+ },+ {+ id: 'library-shapes',+ title: 'Library shapes',+ content: [+ {+ type: 'prose',+ text: '`--from` is any import specifier: a package, a package subpath, or a `./` path inside your package. Use the row that matches the library:',+ },+ {+ type: 'table',+ headers: ['Library ships', 'Command'],+ rows: [+ [+ 'Components in one module',+ '`experimental icon add Bin --from @acme/glyph-library --definition delete`',+ ],+ [+ 'A subpath per style',+ '`experimental icon add Bin --from @acme/glyph-library/solid --id bin --variant solid` (a variant of an icon you added; the set must declare it in `variants`)',+ ],+ [+ 'One file per icon, default export',+ '`experimental icon add Rocket --from @acme/glyph-library/rocket --default --definition rocket`',+ ],+ [+ 'Icon data objects',+ 'Declare an `adapter`, then `experimental icon add Rocket --from @acme/glyph-data --definition rocket`',+ ],+ [+ 'SVG strings or URLs',+ 'Declare an `adapter` that renders them, then `experimental icon add` as above',+ ],+ [+ 'Your own component files',+ '`experimental icon add Rocket --from ./src/icons/rocket.js --definition rocket`',+ ],+ ],+ },+ {+ type: 'prose',+ text: 'An export that is not a component goes through your adapter: a function in your package that turns it into one. Declare it in the data file, `"adapter": {"module": "./src/adapt.js", "export": "adapt"}`, and `experimental icon add` writes `export const RocketIcon = adaptIcon(RocketIconSource);`:',+ },+ {+ type: 'code',+ lang: 'js',+ code: `// src/adapt.js+import {createElement} from 'react';++/** Turn one icon data object ({path}) into an icon component. */+export function adapt(data) {+ return function AdaptedIcon(props) {+ return createElement(+ 'svg',+ {'viewBox': '0 0 24 24', 'width': '1em', 'height': '1em', 'fill': 'currentColor', ...props},+ createElement('path', {d: data.path}),+ );+ };+}`,+ },+ ],+ },+ {+ id: 'theme-map',+ title: 'The theme map',+ content: [+ {+ type: 'prose',+ text: 'The generated module also exports `themeIcons`: one entry per built-in definition in `map`, each an element of your own icon, hidden from assistive technology and sized `1em`. The CLI rewrites it on every `experimental icon add` and `experimental icon map`, so you never write it by hand, and `integration check` proves it matches `map`. A theme uses it in one line:',+ },+ {+ type: 'code',+ lang: 'tsx',+ code: `import {defineTheme} from '@astryxdesign/core/theme';+import {themeIcons} from '@acme/icons';++export const brand = defineTheme({name: 'brand', icons: themeIcons});`,+ },+ ],+ },+ {+ id: 'check-the-set',+ title: 'Check the set',+ content: [+ {+ type: 'prose',+ text: "`astryx integration check` reads the set without running your icons. An unmapped built-in definition is an error that names the definition's description and words, so you or your agent can pick the icon; the message suggests an `experimental icon map` command only when one of your icons has the definition's name or one of its words as its whole id, and never guesses. Its icon-set codes:",+ },+ {+ type: 'list',+ style: 'unordered',+ items: [+ '`invalid_icon_set` (error): the descriptor, data file, or a definition file is invalid, for example a repeated `id`, an icon with no words, or a `map` key that is neither an Astryx definition nor one in your `definitions` folder. The set is withdrawn: apps do not see it.',+ '`icon_builtin_definition_missing` (error): a built-in definition is not in `map`.',+ '`icon_definition_unused` (warning): a definition you declared is not in `map`.',+ "`icon_definition_shadowed` (warning): a definition you declared now exists in Astryx; map to Astryx's and remove yours.",+ '`icon_module_not_public` (error), `icon_export_name` (warning), `icon_not_component` (error): the export contract above.',+ '`icon_export_missing` (error): an export, the generated module, or the adapter does not exist.',+ "`icon_module_invalid` (error): the set's module, a file it re-exports, or the generated module does not parse; reported once, instead of a missing export per icon.",+ "`icon_generated_types_mismatch` (error): the generated module's declaration file is missing or does not match it.",+ '`icon_theme_map_mismatch` (error): the theme map disagrees with the built-in entries of `map`.',+ '`icon_source_version_drift` and `icon_license_notice_missing` (warnings): the data names another library version than the package depends on, or a set with an upstream ships no license notice.',+ ],+ },+ {+ type: 'prose',+ text: 'The other Astryx definitions your set leaves unmapped are not issues: a library need not draw every definition. They are listed under "Unmapped icon definitions (optional)", and in the JSON as the validate result\'s `iconSets`: for each set, `unmappedDefinitions` (each `{name, description, words}`) and `suggestions` (each `{definition, icon}`, for any unmapped definition one of your icons fits). They are never counted and never fail a check.',+ },+ {+ type: 'prose',+ text: 'An export fails only when the reader proves it absent; what it cannot judge it does not fail either. An icon export whose module is an `exports` target you have not built yet; an icon or adapter export it cannot prove either way (behind a re-export it cannot follow, bound to a default or namespace import, or imported from a package that is not installed); and a theme map or theme-map entry it cannot read are listed under "Not checked", and in the JSON as each set\'s `unchecked` (each `{icon}`, `{adapter}`, or `{entry}`, with its `reason`). Build the package, install the package it imports from, export the icon by name, or write the entry as a binding or element to have it checked. An export your built module lacks is still an error.',+ },+ {+ type: 'prose',+ text: 'Errors fail the check. Warnings fail only with `--strict`. A set that maps every built-in definition and every definition it declares passes `--strict`, which integrations run in their build ({@link generic:checks}). The flow, start to finish: `experimental icon new-set` → `integration check` → `experimental icon add` (or `experimental icon map`) for each definition it lists → `integration check` passes.',+ },+ ],+ },+ {+ id: 'publish',+ title: 'Before you publish',+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ 'Run `astryx integration verify` yourself before publishing. Do not put it in `prepublishOnly`: under `npm publish --dry-run` its own `npm pack` becomes a dry run too, and it checks nothing.',+ "Declare `@astryxdesign/cli` as an optional peer (`peerDependenciesMeta`). A required peer an app cannot satisfy makes npm remove the app's CLI without a word. Icon sets are experimental, so no version range promises them: any CLI release that has `astryx experimental icon` reads a set, and the format may change in a patch release. A CLI without it reads `experimental` as a manifest key it does not know: `astryx doctor` there warns that your package was published against a newer Astryx CLI, other commands print a one-line nudge to run it, and your icons, icon definitions, and template icon mapping do not appear ({@link generic:versioning}).",+ 'Your package needs `react` (the theme map and adapter use it): declare it as a peer, as Core does.',+ ],+ },+ ],+ },+ {+ id: 'share-a-definition',+ title: 'Share a definition with every set',+ content: [+ {+ type: 'prose',+ text: "Your own definitions need no change to Astryx. To share one with every set, open a pull request that copies its file into the CLI's icon definitions folder, with a description and words. Its name must not clash with another definition.",+ },+ ],+ },+ {+ id: 'how-apps-use-it',+ title: 'How apps use it',+ content: [+ {+ type: 'code',+ lang: 'bash',+ code: `astryx experimental icon delete # ranked matches with import lines+astryx experimental icon outline/bin # one icon and every variant+astryx experimental icon --list # installed sets and their definition coverage+astryx experimental icon use outline # make it the project's icon set`,+ },+ {+ type: 'prose',+ text: "A template declares, in its descriptor's `icons`, the definition each imported icon draws (`{TrashIcon: 'delete'}`). Once the project sets `experimental.iconSet` in astryx.config (`experimental icon use` writes it), each declared icon becomes the set's icon for that definition. An icon the set does not map keeps its original import, and the copy reports every icon as mapped or kept. Nothing is guessed from names.",+ },+ ],+ },+ {+ id: 'reference',+ title: 'Where icon sets show up',+ content: [+ {+ type: 'prose',+ text: 'Every place the CLI reads or reports icon sets, all experimental. Outside `astryx experimental icon`, each appears only in a project that sets `experimental.iconSet`; `astryx search` never returns icons:',+ },+ {+ type: 'table',+ headers: ['Where', 'What'],+ rows: [+ [+ '`experimental.iconSet` in astryx.config',+ "The project's icon set, by set name or as `<package>/<set>`, and the opt-in: templates, discover, and doctor read icon sets only when it is set. `astryx experimental icon` ranks its icons first, and without it treats the only installed set as the project's. `astryx experimental icon use` writes it.",+ ],+ [+ '`experimental.iconSets` in the integration manifest',+ "The folder that holds the package's icon sets, relative to package.json. `astryx experimental icon new-set` declares it.",+ ],+ [+ "A template descriptor's `icons`",+ "The icon definition each imported icon draws (`{TrashIcon: 'delete'}`): a named import by the name it imports, a default import by its local name. `astryx template`, shown or copied, then writes the set's icons and reports `icons` (status, set, mapped, kept): every key is mapped, or kept with why (no match, a namespace or type-only import, a re-export, an Astryx or project-set import, or no import at all). `integration check` notes a key the template's source never imports (`template_icon_not_imported`), never failing.",+ ],+ [+ '`astryx discover`',+ "A package's sets (`iconSets`) and, for `@scope/name/<set>`, the set's display name, license, icon count, and definitions; `--type icon-set` keeps only sets.",+ ],+ [+ '`astryx doctor`',+ 'The `icon-sets` check: fails when `experimental.iconSet` names a set that is not installed or was withdrawn (an invalid set, or one whose module does not resolve), saying why, and warns when two packages ship a set by that name or a set was withdrawn.',+ ],+ [+ 'JSON types',+ '`icon.search`, `icon.detail`, `icon.list`, `icon.use`, `icon.map`, `icon.add`, `icon.definitionMatches`, `icon.newSet`, and `icon.newDefinition`, from the matching `astryx experimental icon` command.',+ ],+ ],+ },+ ],+ },+ ],+};diff --git a/packages/cli/assets/icons/definitions/activity.doc.mjs b/packages/cli/assets/icons/definitions/activity.doc.mjsnew file mode 100644index 0000000000..b68002886e--- /dev/null+++ b/packages/cli/assets/icons/definitions/activity.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'activity',+ description: 'Activity or live status over time.',+ words: ['pulse', 'monitor', 'live'],+};diff --git a/packages/cli/assets/icons/definitions/add.doc.mjs b/packages/cli/assets/icons/definitions/add.doc.mjsnew file mode 100644index 0000000000..44694b6ce8--- /dev/null+++ b/packages/cli/assets/icons/definitions/add.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'add',+ description: 'Add or create a new item.',+ words: ['create', 'new', 'plus'],+};diff --git a/packages/cli/assets/icons/definitions/adjustments.doc.mjs b/packages/cli/assets/icons/definitions/adjustments.doc.mjsnew file mode 100644index 0000000000..fb82d212c2--- /dev/null+++ b/packages/cli/assets/icons/definitions/adjustments.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'adjustments',+ description: 'Adjust options such as view or filters.',+ words: ['sliders', 'tune', 'options'],+};diff --git a/packages/cli/assets/icons/definitions/announcement.doc.mjs b/packages/cli/assets/icons/definitions/announcement.doc.mjsnew file mode 100644index 0000000000..7e1479da1c--- /dev/null+++ b/packages/cli/assets/icons/definitions/announcement.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'announcement',+ description: 'An announcement or broadcast.',+ words: ['broadcast', 'news', 'megaphone'],+};diff --git a/packages/cli/assets/icons/definitions/apps.doc.mjs b/packages/cli/assets/icons/definitions/apps.doc.mjsnew file mode 100644index 0000000000..06cc021ace--- /dev/null+++ b/packages/cli/assets/icons/definitions/apps.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'apps',+ description: 'Add or browse apps and widgets.',+ words: ['grid', 'widgets', 'apps'],+};diff --git a/packages/cli/assets/icons/definitions/archive.doc.mjs b/packages/cli/assets/icons/definitions/archive.doc.mjsnew file mode 100644index 0000000000..1c299d7fcb--- /dev/null+++ b/packages/cli/assets/icons/definitions/archive.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'archive',+ description: 'Archive an item.',+ words: ['store', 'box'],+};diff --git a/packages/cli/assets/icons/definitions/arrowDown.doc.mjs b/packages/cli/assets/icons/definitions/arrowDown.doc.mjsnew file mode 100644index 0000000000..134e93c84e--- /dev/null+++ b/packages/cli/assets/icons/definitions/arrowDown.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'arrowDown',+ description: 'Sort descending or move down.',+ words: ['descending', 'down', 'decrease'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/arrowLeft.doc.mjs b/packages/cli/assets/icons/definitions/arrowLeft.doc.mjsnew file mode 100644index 0000000000..974f90d36b--- /dev/null+++ b/packages/cli/assets/icons/definitions/arrowLeft.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'arrowLeft',+ description: 'Go back to the previous page.',+ words: ['back', 'previous'],+};diff --git a/packages/cli/assets/icons/definitions/arrowRight.doc.mjs b/packages/cli/assets/icons/definitions/arrowRight.doc.mjsnew file mode 100644index 0000000000..8cde5ea178--- /dev/null+++ b/packages/cli/assets/icons/definitions/arrowRight.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'arrowRight',+ description: 'Continue to the next step or page.',+ words: ['next', 'continue', 'forward'],+};diff --git a/packages/cli/assets/icons/definitions/arrowUp.doc.mjs b/packages/cli/assets/icons/definitions/arrowUp.doc.mjsnew file mode 100644index 0000000000..efb49d3505--- /dev/null+++ b/packages/cli/assets/icons/definitions/arrowUp.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'arrowUp',+ description: 'Sort ascending or move up.',+ words: ['ascending', 'up', 'increase'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/arrowsUpDown.doc.mjs b/packages/cli/assets/icons/definitions/arrowsUpDown.doc.mjsnew file mode 100644index 0000000000..7e9762b47c--- /dev/null+++ b/packages/cli/assets/icons/definitions/arrowsUpDown.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'arrowsUpDown',+ description: 'Show that a column can be sorted.',+ words: ['sort', 'sortable', 'reorder'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/attach.doc.mjs b/packages/cli/assets/icons/definitions/attach.doc.mjsnew file mode 100644index 0000000000..ce58b55b03--- /dev/null+++ b/packages/cli/assets/icons/definitions/attach.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'attach',+ description: 'Attach a file.',+ words: ['attachment', 'paperclip'],+};diff --git a/packages/cli/assets/icons/definitions/audio.doc.mjs b/packages/cli/assets/icons/definitions/audio.doc.mjsnew file mode 100644index 0000000000..70116ee2e4--- /dev/null+++ b/packages/cli/assets/icons/definitions/audio.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'audio',+ description: 'Sound or volume.',+ words: ['sound', 'volume', 'speaker'],+};diff --git a/packages/cli/assets/icons/definitions/bank.doc.mjs b/packages/cli/assets/icons/definitions/bank.doc.mjsnew file mode 100644index 0000000000..74b981e220--- /dev/null+++ b/packages/cli/assets/icons/definitions/bank.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'bank',+ description: 'A bank or other institution.',+ words: ['institution', 'library', 'finance'],+};diff --git a/packages/cli/assets/icons/definitions/bold.doc.mjs b/packages/cli/assets/icons/definitions/bold.doc.mjsnew file mode 100644index 0000000000..8808d110f0--- /dev/null+++ b/packages/cli/assets/icons/definitions/bold.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'bold',+ description: 'Bold text.',+ words: ['strong', 'text format'],+};diff --git a/packages/cli/assets/icons/definitions/bolt.doc.mjs b/packages/cli/assets/icons/definitions/bolt.doc.mjsnew file mode 100644index 0000000000..ca1c0dc1c0--- /dev/null+++ b/packages/cli/assets/icons/definitions/bolt.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'bolt',+ description: 'Speed, power or quick actions.',+ words: ['fast', 'power', 'lightning'],+};diff --git a/packages/cli/assets/icons/definitions/book.doc.mjs b/packages/cli/assets/icons/definitions/book.doc.mjsnew file mode 100644index 0000000000..3b5ca69461--- /dev/null+++ b/packages/cli/assets/icons/definitions/book.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'book',+ description: 'Documentation or a guide.',+ words: ['docs', 'guide', 'read', 'learn'],+};diff --git a/packages/cli/assets/icons/definitions/bookmark.doc.mjs b/packages/cli/assets/icons/definitions/bookmark.doc.mjsnew file mode 100644index 0000000000..d0744fe697--- /dev/null+++ b/packages/cli/assets/icons/definitions/bookmark.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'bookmark',+ description: 'Save something to read later.',+ words: ['save', 'later'],+};diff --git a/packages/cli/assets/icons/definitions/bug.doc.mjs b/packages/cli/assets/icons/definitions/bug.doc.mjsnew file mode 100644index 0000000000..70e0778eb3--- /dev/null+++ b/packages/cli/assets/icons/definitions/bug.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'bug',+ description: 'A bug or issue.',+ words: ['issue', 'defect', 'error'],+};diff --git a/packages/cli/assets/icons/definitions/building.doc.mjs b/packages/cli/assets/icons/definitions/building.doc.mjsnew file mode 100644index 0000000000..fd8021f124--- /dev/null+++ b/packages/cli/assets/icons/definitions/building.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'building',+ description: 'A company or office.',+ words: ['company', 'office', 'organization'],+};diff --git a/packages/cli/assets/icons/definitions/calendar.doc.mjs b/packages/cli/assets/icons/definitions/calendar.doc.mjsnew file mode 100644index 0000000000..10a6b91d53--- /dev/null+++ b/packages/cli/assets/icons/definitions/calendar.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'calendar',+ description: 'Pick or show a date.',+ words: ['date', 'schedule', 'day'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/cart.doc.mjs b/packages/cli/assets/icons/definitions/cart.doc.mjsnew file mode 100644index 0000000000..7add31abe6--- /dev/null+++ b/packages/cli/assets/icons/definitions/cart.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'cart',+ description: 'A shopping cart.',+ words: ['shop', 'buy', 'checkout'],+};diff --git a/packages/cli/assets/icons/definitions/chart.doc.mjs b/packages/cli/assets/icons/definitions/chart.doc.mjsnew file mode 100644index 0000000000..5462243eda--- /dev/null+++ b/packages/cli/assets/icons/definitions/chart.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'chart',+ description: 'A chart or analytics.',+ words: ['analytics', 'graph', 'stats', 'metrics'],+};diff --git a/packages/cli/assets/icons/definitions/check.doc.mjs b/packages/cli/assets/icons/definitions/check.doc.mjsnew file mode 100644index 0000000000..db31aacc85--- /dev/null+++ b/packages/cli/assets/icons/definitions/check.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'check',+ description: 'Mark something done, selected or confirmed.',+ words: ['done', 'tick', 'confirm', 'selected'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/checkDouble.doc.mjs b/packages/cli/assets/icons/definitions/checkDouble.doc.mjsnew file mode 100644index 0000000000..7c70bc0093--- /dev/null+++ b/packages/cli/assets/icons/definitions/checkDouble.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'checkDouble',+ description: 'Show that something was copied or read.',+ words: ['copied', 'read', 'seen'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/chevronDown.doc.mjs b/packages/cli/assets/icons/definitions/chevronDown.doc.mjsnew file mode 100644index 0000000000..d500477ae8--- /dev/null+++ b/packages/cli/assets/icons/definitions/chevronDown.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'chevronDown',+ description: 'Open a dropdown or expand a section.',+ words: ['expand', 'dropdown', 'caret'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/chevronLeft.doc.mjs b/packages/cli/assets/icons/definitions/chevronLeft.doc.mjsnew file mode 100644index 0000000000..699d8efa8a--- /dev/null+++ b/packages/cli/assets/icons/definitions/chevronLeft.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'chevronLeft',+ description: 'Go back or to the previous item.',+ words: ['back', 'previous'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/chevronRight.doc.mjs b/packages/cli/assets/icons/definitions/chevronRight.doc.mjsnew file mode 100644index 0000000000..77fc842bd9--- /dev/null+++ b/packages/cli/assets/icons/definitions/chevronRight.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'chevronRight',+ description: 'Go forward, to the next item, or into a nested item.',+ words: ['forward', 'next'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/chevronUp.doc.mjs b/packages/cli/assets/icons/definitions/chevronUp.doc.mjsnew file mode 100644index 0000000000..d4697764f8--- /dev/null+++ b/packages/cli/assets/icons/definitions/chevronUp.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'chevronUp',+ description: 'Collapse a section or move up.',+ words: ['collapse', 'up'],+};diff --git a/packages/cli/assets/icons/definitions/chevronsLeft.doc.mjs b/packages/cli/assets/icons/definitions/chevronsLeft.doc.mjsnew file mode 100644index 0000000000..50ff5d71cb--- /dev/null+++ b/packages/cli/assets/icons/definitions/chevronsLeft.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'chevronsLeft',+ description: 'Jump to the first item or page.',+ words: ['first', 'start'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/chevronsRight.doc.mjs b/packages/cli/assets/icons/definitions/chevronsRight.doc.mjsnew file mode 100644index 0000000000..0eb5f99d27--- /dev/null+++ b/packages/cli/assets/icons/definitions/chevronsRight.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'chevronsRight',+ description: 'Jump to the last item or page.',+ words: ['last', 'end'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/click.doc.mjs b/packages/cli/assets/icons/definitions/click.doc.mjsnew file mode 100644index 0000000000..d463c0d2e5--- /dev/null+++ b/packages/cli/assets/icons/definitions/click.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'click',+ description: 'Click or select something on the screen.',+ words: ['cursor', 'pointer', 'select'],+};diff --git a/packages/cli/assets/icons/definitions/clipboard.doc.mjs b/packages/cli/assets/icons/definitions/clipboard.doc.mjsnew file mode 100644index 0000000000..c0ec438436--- /dev/null+++ b/packages/cli/assets/icons/definitions/clipboard.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'clipboard',+ description:+ 'Show or use the clipboard, such as a paste action or copied content.',+ words: ['paste', 'clipboard'],+};diff --git a/packages/cli/assets/icons/definitions/clock.doc.mjs b/packages/cli/assets/icons/definitions/clock.doc.mjsnew file mode 100644index 0000000000..6467c6d839--- /dev/null+++ b/packages/cli/assets/icons/definitions/clock.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'clock',+ description: 'Pick or show a time.',+ words: ['time', 'hour', 'recent'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/close.doc.mjs b/packages/cli/assets/icons/definitions/close.doc.mjsnew file mode 100644index 0000000000..6ce30429be--- /dev/null+++ b/packages/cli/assets/icons/definitions/close.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'close',+ description: 'Dismiss or close a dialog, panel, tag or banner.',+ words: ['dismiss', 'cancel', 'remove'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/code.doc.mjs b/packages/cli/assets/icons/definitions/code.doc.mjsnew file mode 100644index 0000000000..e349e2a73e--- /dev/null+++ b/packages/cli/assets/icons/definitions/code.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'code',+ description: 'Source code or a developer view.',+ words: ['developer', 'brackets', 'source'],+};diff --git a/packages/cli/assets/icons/definitions/collapse.doc.mjs b/packages/cli/assets/icons/definitions/collapse.doc.mjsnew file mode 100644index 0000000000..c3f1f9a1a8--- /dev/null+++ b/packages/cli/assets/icons/definitions/collapse.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'collapse',+ description: 'Make something smaller or exit full screen.',+ words: ['minimize', 'shrink'],+};diff --git a/packages/cli/assets/icons/definitions/compose.doc.mjs b/packages/cli/assets/icons/definitions/compose.doc.mjsnew file mode 100644index 0000000000..58fbc12d79--- /dev/null+++ b/packages/cli/assets/icons/definitions/compose.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'compose',+ description: 'Write something new, such as a message or post.',+ words: ['write', 'new message', 'draft'],+};diff --git a/packages/cli/assets/icons/definitions/conversation.doc.mjs b/packages/cli/assets/icons/definitions/conversation.doc.mjsnew file mode 100644index 0000000000..4f7690c50d--- /dev/null+++ b/packages/cli/assets/icons/definitions/conversation.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'conversation',+ description: 'A conversation between people.',+ words: ['chat', 'discussion', 'thread'],+};diff --git a/packages/cli/assets/icons/definitions/copy.doc.mjs b/packages/cli/assets/icons/definitions/copy.doc.mjsnew file mode 100644index 0000000000..df44baaa2f--- /dev/null+++ b/packages/cli/assets/icons/definitions/copy.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'copy',+ description: 'Copy to the clipboard.',+ words: ['duplicate', 'clipboard'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/creditCard.doc.mjs b/packages/cli/assets/icons/definitions/creditCard.doc.mjsnew file mode 100644index 0000000000..6dc5a3b647--- /dev/null+++ b/packages/cli/assets/icons/definitions/creditCard.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'creditCard',+ description: 'A payment card or billing.',+ words: ['billing', 'payment', 'card'],+};diff --git a/packages/cli/assets/icons/definitions/database.doc.mjs b/packages/cli/assets/icons/definitions/database.doc.mjsnew file mode 100644index 0000000000..60a8c7596e--- /dev/null+++ b/packages/cli/assets/icons/definitions/database.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'database',+ description: 'A database or stored data.',+ words: ['data', 'storage', 'table'],+};diff --git a/packages/cli/assets/icons/definitions/delete.doc.mjs b/packages/cli/assets/icons/definitions/delete.doc.mjsnew file mode 100644index 0000000000..73b68052c6--- /dev/null+++ b/packages/cli/assets/icons/definitions/delete.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'delete',+ description: 'Delete something permanently.',+ words: ['trash', 'bin', 'discard'],+};diff --git a/packages/cli/assets/icons/definitions/desktop.doc.mjs b/packages/cli/assets/icons/definitions/desktop.doc.mjsnew file mode 100644index 0000000000..a92d2d8b35--- /dev/null+++ b/packages/cli/assets/icons/definitions/desktop.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'desktop',+ description: 'A desktop computer, or the desktop layout of a page.',+ words: ['computer', 'monitor', 'screen'],+};diff --git a/packages/cli/assets/icons/definitions/discount.doc.mjs b/packages/cli/assets/icons/definitions/discount.doc.mjsnew file mode 100644index 0000000000..0d4cd06837--- /dev/null+++ b/packages/cli/assets/icons/definitions/discount.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'discount',+ description: 'A discount, coupon, or percentage off.',+ words: ['coupon', 'sale', 'percent'],+};diff --git a/packages/cli/assets/icons/definitions/document.doc.mjs b/packages/cli/assets/icons/definitions/document.doc.mjsnew file mode 100644index 0000000000..222b5cdac1--- /dev/null+++ b/packages/cli/assets/icons/definitions/document.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'document',+ description: 'A document or file.',+ words: ['file', 'page', 'doc'],+};diff --git a/packages/cli/assets/icons/definitions/download.doc.mjs b/packages/cli/assets/icons/definitions/download.doc.mjsnew file mode 100644index 0000000000..550832880e--- /dev/null+++ b/packages/cli/assets/icons/definitions/download.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'download',+ description: 'Download a file.',+ words: ['export', 'save file'],+};diff --git a/packages/cli/assets/icons/definitions/drag.doc.mjs b/packages/cli/assets/icons/definitions/drag.doc.mjsnew file mode 100644index 0000000000..89c37b87fd--- /dev/null+++ b/packages/cli/assets/icons/definitions/drag.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'drag',+ description: 'A handle to drag an item and reorder it.',+ words: ['grip', 'handle', 'reorder', 'move'],+};diff --git a/packages/cli/assets/icons/definitions/edit.doc.mjs b/packages/cli/assets/icons/definitions/edit.doc.mjsnew file mode 100644index 0000000000..16a88994fd--- /dev/null+++ b/packages/cli/assets/icons/definitions/edit.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'edit',+ description: 'Edit or change something.',+ words: ['pencil', 'change', 'modify'],+};diff --git a/packages/cli/assets/icons/definitions/emoji.doc.mjs b/packages/cli/assets/icons/definitions/emoji.doc.mjsnew file mode 100644index 0000000000..dedb908f46--- /dev/null+++ b/packages/cli/assets/icons/definitions/emoji.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'emoji',+ description: 'Add an emoji or a reaction.',+ words: ['smile', 'reaction', 'face'],+};diff --git a/packages/cli/assets/icons/definitions/error.doc.mjs b/packages/cli/assets/icons/definitions/error.doc.mjsnew file mode 100644index 0000000000..ceddca9084--- /dev/null+++ b/packages/cli/assets/icons/definitions/error.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'error',+ description: 'Show that something failed.',+ words: ['failed', 'invalid', 'problem'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/expand.doc.mjs b/packages/cli/assets/icons/definitions/expand.doc.mjsnew file mode 100644index 0000000000..d79af6cb44--- /dev/null+++ b/packages/cli/assets/icons/definitions/expand.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'expand',+ description: 'Make something larger or full screen.',+ words: ['maximize', 'fullscreen', 'enlarge'],+};diff --git a/packages/cli/assets/icons/definitions/experiment.doc.mjs b/packages/cli/assets/icons/definitions/experiment.doc.mjsnew file mode 100644index 0000000000..bfc1ea8aea--- /dev/null+++ b/packages/cli/assets/icons/definitions/experiment.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'experiment',+ description: 'An experiment, test, or lab feature.',+ words: ['lab', 'test', 'beta'],+};diff --git a/packages/cli/assets/icons/definitions/externalLink.doc.mjs b/packages/cli/assets/icons/definitions/externalLink.doc.mjsnew file mode 100644index 0000000000..868c3fa34a--- /dev/null+++ b/packages/cli/assets/icons/definitions/externalLink.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'externalLink',+ description: 'Open a link in a new tab or another site.',+ words: ['open', 'new tab', 'external'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/eye.doc.mjs b/packages/cli/assets/icons/definitions/eye.doc.mjsnew file mode 100644index 0000000000..205656e2f4--- /dev/null+++ b/packages/cli/assets/icons/definitions/eye.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'eye',+ description: 'Show or preview something.',+ words: ['view', 'visible', 'preview'],+};diff --git a/packages/cli/assets/icons/definitions/eyeSlash.doc.mjs b/packages/cli/assets/icons/definitions/eyeSlash.doc.mjsnew file mode 100644index 0000000000..1bceb06d20--- /dev/null+++ b/packages/cli/assets/icons/definitions/eyeSlash.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'eyeSlash',+ description: 'Hide something, or show that it is hidden.',+ words: ['hide', 'hidden', 'invisible'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/file.doc.mjs b/packages/cli/assets/icons/definitions/file.doc.mjsnew file mode 100644index 0000000000..b5184eb309--- /dev/null+++ b/packages/cli/assets/icons/definitions/file.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'file',+ description: 'A file of any type.',+ words: ['file', 'attachment', 'document'],+};diff --git a/packages/cli/assets/icons/definitions/flag.doc.mjs b/packages/cli/assets/icons/definitions/flag.doc.mjsnew file mode 100644index 0000000000..a020bc979c--- /dev/null+++ b/packages/cli/assets/icons/definitions/flag.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'flag',+ description: 'Flag or report something.',+ words: ['report', 'mark'],+};diff --git a/packages/cli/assets/icons/definitions/folder.doc.mjs b/packages/cli/assets/icons/definitions/folder.doc.mjsnew file mode 100644index 0000000000..12a901f96f--- /dev/null+++ b/packages/cli/assets/icons/definitions/folder.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'folder',+ description: 'A folder or collection.',+ words: ['directory', 'collection'],+};diff --git a/packages/cli/assets/icons/definitions/folderAdd.doc.mjs b/packages/cli/assets/icons/definitions/folderAdd.doc.mjsnew file mode 100644index 0000000000..19d8155054--- /dev/null+++ b/packages/cli/assets/icons/definitions/folderAdd.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'folderAdd',+ description: 'Create a new folder.',+ words: ['new folder'],+};diff --git a/packages/cli/assets/icons/definitions/funnel.doc.mjs b/packages/cli/assets/icons/definitions/funnel.doc.mjsnew file mode 100644index 0000000000..9a85b8aa32--- /dev/null+++ b/packages/cli/assets/icons/definitions/funnel.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'funnel',+ description: 'Filter a list.',+ words: ['filter', 'refine'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/globe.doc.mjs b/packages/cli/assets/icons/definitions/globe.doc.mjsnew file mode 100644index 0000000000..ad1100f25c--- /dev/null+++ b/packages/cli/assets/icons/definitions/globe.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'globe',+ description: 'The web, a language or the world.',+ words: ['world', 'web', 'language', 'internet'],+};diff --git a/packages/cli/assets/icons/definitions/gridView.doc.mjs b/packages/cli/assets/icons/definitions/gridView.doc.mjsnew file mode 100644index 0000000000..9bc369dbc9--- /dev/null+++ b/packages/cli/assets/icons/definitions/gridView.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'gridView',+ description: 'Show items as a grid of tiles.',+ words: ['grid', 'tiles', 'gallery view'],+};diff --git a/packages/cli/assets/icons/definitions/heart.doc.mjs b/packages/cli/assets/icons/definitions/heart.doc.mjsnew file mode 100644index 0000000000..d62c9dc1e3--- /dev/null+++ b/packages/cli/assets/icons/definitions/heart.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'heart',+ description: 'Like something.',+ words: ['like', 'love'],+};diff --git a/packages/cli/assets/icons/definitions/home.doc.mjs b/packages/cli/assets/icons/definitions/home.doc.mjsnew file mode 100644index 0000000000..068200762f--- /dev/null+++ b/packages/cli/assets/icons/definitions/home.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'home',+ description: 'Go to the home page.',+ words: ['house', 'start', 'dashboard'],+};diff --git a/packages/cli/assets/icons/definitions/image.doc.mjs b/packages/cli/assets/icons/definitions/image.doc.mjsnew file mode 100644index 0000000000..7d5f19ead1--- /dev/null+++ b/packages/cli/assets/icons/definitions/image.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'image',+ description: 'An image or photo.',+ words: ['photo', 'picture', 'media'],+};diff --git a/packages/cli/assets/icons/definitions/inbox.doc.mjs b/packages/cli/assets/icons/definitions/inbox.doc.mjsnew file mode 100644index 0000000000..0e0bd81ae0--- /dev/null+++ b/packages/cli/assets/icons/definitions/inbox.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'inbox',+ description: 'An inbox of incoming items.',+ words: ['incoming', 'tray'],+};diff --git a/packages/cli/assets/icons/definitions/info.doc.mjs b/packages/cli/assets/icons/definitions/info.doc.mjsnew file mode 100644index 0000000000..d75199779e--- /dev/null+++ b/packages/cli/assets/icons/definitions/info.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'info',+ description: 'Give more information or help.',+ words: ['information', 'help', 'about'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/italic.doc.mjs b/packages/cli/assets/icons/definitions/italic.doc.mjsnew file mode 100644index 0000000000..94e9a3583c--- /dev/null+++ b/packages/cli/assets/icons/definitions/italic.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'italic',+ description: 'Italic text.',+ words: ['emphasis', 'text format'],+};diff --git a/packages/cli/assets/icons/definitions/key.doc.mjs b/packages/cli/assets/icons/definitions/key.doc.mjsnew file mode 100644index 0000000000..7314820067--- /dev/null+++ b/packages/cli/assets/icons/definitions/key.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'key',+ description: 'Keys, passwords or access.',+ words: ['password', 'access', 'credential'],+};diff --git a/packages/cli/assets/icons/definitions/language.doc.mjs b/packages/cli/assets/icons/definitions/language.doc.mjsnew file mode 100644index 0000000000..5fc6b1b2ae--- /dev/null+++ b/packages/cli/assets/icons/definitions/language.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'language',+ description: 'Choose a language, or translate.',+ words: ['translate', 'locale', 'i18n'],+};diff --git a/packages/cli/assets/icons/definitions/lightbulb.doc.mjs b/packages/cli/assets/icons/definitions/lightbulb.doc.mjsnew file mode 100644index 0000000000..850a61d977--- /dev/null+++ b/packages/cli/assets/icons/definitions/lightbulb.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'lightbulb',+ description: 'An idea or tip.',+ words: ['idea', 'tip', 'hint'],+};diff --git a/packages/cli/assets/icons/definitions/link.doc.mjs b/packages/cli/assets/icons/definitions/link.doc.mjsnew file mode 100644index 0000000000..a7f38f4cd0--- /dev/null+++ b/packages/cli/assets/icons/definitions/link.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'link',+ description: 'Add or show a link.',+ words: ['url', 'chain', 'hyperlink'],+};diff --git a/packages/cli/assets/icons/definitions/list.doc.mjs b/packages/cli/assets/icons/definitions/list.doc.mjsnew file mode 100644index 0000000000..184dca1f9f--- /dev/null+++ b/packages/cli/assets/icons/definitions/list.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'list',+ description: 'A list view.',+ words: ['bullets', 'items', 'rows'],+};diff --git a/packages/cli/assets/icons/definitions/location.doc.mjs b/packages/cli/assets/icons/definitions/location.doc.mjsnew file mode 100644index 0000000000..f2d9d7b250--- /dev/null+++ b/packages/cli/assets/icons/definitions/location.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'location',+ description: 'A place or address.',+ words: ['place', 'address', 'map'],+};diff --git a/packages/cli/assets/icons/definitions/lock.doc.mjs b/packages/cli/assets/icons/definitions/lock.doc.mjsnew file mode 100644index 0000000000..ab975cde72--- /dev/null+++ b/packages/cli/assets/icons/definitions/lock.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'lock',+ description: 'Locked, private or secure.',+ words: ['secure', 'private', 'locked'],+};diff --git a/packages/cli/assets/icons/definitions/mail.doc.mjs b/packages/cli/assets/icons/definitions/mail.doc.mjsnew file mode 100644index 0000000000..8dbc860586--- /dev/null+++ b/packages/cli/assets/icons/definitions/mail.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'mail',+ description: 'Email or a message inbox.',+ words: ['email', 'envelope', 'message'],+};diff --git a/packages/cli/assets/icons/definitions/mention.doc.mjs b/packages/cli/assets/icons/definitions/mention.doc.mjsnew file mode 100644index 0000000000..179ffd4605--- /dev/null+++ b/packages/cli/assets/icons/definitions/mention.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'mention',+ description: 'Mention someone or show an email address.',+ words: ['at', 'email', 'handle'],+};diff --git a/packages/cli/assets/icons/definitions/menu.doc.mjs b/packages/cli/assets/icons/definitions/menu.doc.mjsnew file mode 100644index 0000000000..9e87147e31--- /dev/null+++ b/packages/cli/assets/icons/definitions/menu.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'menu',+ description: 'Open the main navigation menu.',+ words: ['hamburger', 'navigation'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/message.doc.mjs b/packages/cli/assets/icons/definitions/message.doc.mjsnew file mode 100644index 0000000000..357b4cc33b--- /dev/null+++ b/packages/cli/assets/icons/definitions/message.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'message',+ description: 'A chat message or comment.',+ words: ['chat', 'comment', 'conversation'],+};diff --git a/packages/cli/assets/icons/definitions/microphone.doc.mjs b/packages/cli/assets/icons/definitions/microphone.doc.mjsnew file mode 100644index 0000000000..cdc6f543e2--- /dev/null+++ b/packages/cli/assets/icons/definitions/microphone.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'microphone',+ description: 'Start voice input or audio recording.',+ words: ['voice', 'audio', 'record'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/mobile.doc.mjs b/packages/cli/assets/icons/definitions/mobile.doc.mjsnew file mode 100644index 0000000000..6467fa5f30--- /dev/null+++ b/packages/cli/assets/icons/definitions/mobile.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'mobile',+ description: 'A phone, or the mobile layout of a page.',+ words: ['phone', 'smartphone', 'device'],+};diff --git a/packages/cli/assets/icons/definitions/money.doc.mjs b/packages/cli/assets/icons/definitions/money.doc.mjsnew file mode 100644index 0000000000..cb70d3a300--- /dev/null+++ b/packages/cli/assets/icons/definitions/money.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'money',+ description: 'Money, prices or payments.',+ words: ['price', 'payment', 'cost', 'currency'],+};diff --git a/packages/cli/assets/icons/definitions/moon.doc.mjs b/packages/cli/assets/icons/definitions/moon.doc.mjsnew file mode 100644index 0000000000..49e92b95e1--- /dev/null+++ b/packages/cli/assets/icons/definitions/moon.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'moon',+ description: 'Dark mode or night.',+ words: ['dark mode', 'night'],+};diff --git a/packages/cli/assets/icons/definitions/moreHorizontal.doc.mjs b/packages/cli/assets/icons/definitions/moreHorizontal.doc.mjsnew file mode 100644index 0000000000..84ed897780--- /dev/null+++ b/packages/cli/assets/icons/definitions/moreHorizontal.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'moreHorizontal',+ description: 'Open more actions for an item.',+ words: ['more', 'overflow', 'actions'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/notification.doc.mjs b/packages/cli/assets/icons/definitions/notification.doc.mjsnew file mode 100644index 0000000000..28618e87da--- /dev/null+++ b/packages/cli/assets/icons/definitions/notification.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'notification',+ description: 'Notifications or alerts.',+ words: ['bell', 'alerts', 'notify'],+};diff --git a/packages/cli/assets/icons/definitions/notificationActive.doc.mjs b/packages/cli/assets/icons/definitions/notificationActive.doc.mjsnew file mode 100644index 0000000000..12b33e2bfb--- /dev/null+++ b/packages/cli/assets/icons/definitions/notificationActive.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'notificationActive',+ description: 'New or unread notifications.',+ words: ['ringing', 'unread', 'new alert'],+};diff --git a/packages/cli/assets/icons/definitions/notificationOff.doc.mjs b/packages/cli/assets/icons/definitions/notificationOff.doc.mjsnew file mode 100644index 0000000000..bd2fd65775--- /dev/null+++ b/packages/cli/assets/icons/definitions/notificationOff.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'notificationOff',+ description: 'Turn notifications off, or show that they are muted.',+ words: ['mute', 'silence', 'notifications off'],+};diff --git a/packages/cli/assets/icons/definitions/package.doc.mjs b/packages/cli/assets/icons/definitions/package.doc.mjsnew file mode 100644index 0000000000..2a75fe255e--- /dev/null+++ b/packages/cli/assets/icons/definitions/package.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'package',+ description: 'A package, product or shipment.',+ words: ['box', 'product', 'module', 'cube'],+};diff --git a/packages/cli/assets/icons/definitions/pause.doc.mjs b/packages/cli/assets/icons/definitions/pause.doc.mjsnew file mode 100644index 0000000000..3d26f131e8--- /dev/null+++ b/packages/cli/assets/icons/definitions/pause.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'pause',+ description: 'Pause media or a running task.',+ words: ['hold', 'wait'],+};diff --git a/packages/cli/assets/icons/definitions/pin.doc.mjs b/packages/cli/assets/icons/definitions/pin.doc.mjsnew file mode 100644index 0000000000..cf04a90571--- /dev/null+++ b/packages/cli/assets/icons/definitions/pin.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'pin',+ description: 'Pin an item to the top.',+ words: ['pinned', 'keep'],+};diff --git a/packages/cli/assets/icons/definitions/play.doc.mjs b/packages/cli/assets/icons/definitions/play.doc.mjsnew file mode 100644index 0000000000..631fe561a6--- /dev/null+++ b/packages/cli/assets/icons/definitions/play.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'play',+ description: 'Play media or start something.',+ words: ['start', 'run', 'video'],+};diff --git a/packages/cli/assets/icons/definitions/raiseHand.doc.mjs b/packages/cli/assets/icons/definitions/raiseHand.doc.mjsnew file mode 100644index 0000000000..e1a53c527e--- /dev/null+++ b/packages/cli/assets/icons/definitions/raiseHand.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'raiseHand',+ description: 'Raise a hand to ask or speak.',+ words: ['hand', 'ask', 'stop'],+};diff --git a/packages/cli/assets/icons/definitions/redo.doc.mjs b/packages/cli/assets/icons/definitions/redo.doc.mjsnew file mode 100644index 0000000000..12ef0329ba--- /dev/null+++ b/packages/cli/assets/icons/definitions/redo.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'redo',+ description: 'Redo the last change that was undone.',+ words: ['again', 'repeat', 'forward'],+};diff --git a/packages/cli/assets/icons/definitions/refresh.doc.mjs b/packages/cli/assets/icons/definitions/refresh.doc.mjsnew file mode 100644index 0000000000..b26ebcd1e5--- /dev/null+++ b/packages/cli/assets/icons/definitions/refresh.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'refresh',+ description: 'Reload or refresh data.',+ words: ['reload', 'sync', 'retry'],+};diff --git a/packages/cli/assets/icons/definitions/remove.doc.mjs b/packages/cli/assets/icons/definitions/remove.doc.mjsnew file mode 100644index 0000000000..3081974baf--- /dev/null+++ b/packages/cli/assets/icons/definitions/remove.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'remove',+ description: 'Remove an item or reduce a value.',+ words: ['minus', 'subtract', 'less'],+};diff --git a/packages/cli/assets/icons/definitions/rocket.doc.mjs b/packages/cli/assets/icons/definitions/rocket.doc.mjsnew file mode 100644index 0000000000..5d273c3464--- /dev/null+++ b/packages/cli/assets/icons/definitions/rocket.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'rocket',+ description: 'Launch or get started.',+ words: ['launch', 'start', 'deploy'],+};diff --git a/packages/cli/assets/icons/definitions/save.doc.mjs b/packages/cli/assets/icons/definitions/save.doc.mjsnew file mode 100644index 0000000000..21a170bc37--- /dev/null+++ b/packages/cli/assets/icons/definitions/save.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'save',+ description: 'Save changes.',+ words: ['store', 'keep', 'floppy'],+};diff --git a/packages/cli/assets/icons/definitions/search.doc.mjs b/packages/cli/assets/icons/definitions/search.doc.mjsnew file mode 100644index 0000000000..a02ac33fb1--- /dev/null+++ b/packages/cli/assets/icons/definitions/search.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'search',+ description: 'Search or find something.',+ words: ['find', 'lookup', 'magnifier'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/send.doc.mjs b/packages/cli/assets/icons/definitions/send.doc.mjsnew file mode 100644index 0000000000..e921123687--- /dev/null+++ b/packages/cli/assets/icons/definitions/send.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'send',+ description: 'Send a message.',+ words: ['submit', 'post'],+};diff --git a/packages/cli/assets/icons/definitions/server.doc.mjs b/packages/cli/assets/icons/definitions/server.doc.mjsnew file mode 100644index 0000000000..6c373c0c1c--- /dev/null+++ b/packages/cli/assets/icons/definitions/server.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'server',+ description: 'A server or backend service.',+ words: ['backend', 'host', 'infrastructure'],+};diff --git a/packages/cli/assets/icons/definitions/settings.doc.mjs b/packages/cli/assets/icons/definitions/settings.doc.mjsnew file mode 100644index 0000000000..bc61671b36--- /dev/null+++ b/packages/cli/assets/icons/definitions/settings.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'settings',+ description: 'Open settings or preferences.',+ words: ['gear', 'preferences', 'options'],+};diff --git a/packages/cli/assets/icons/definitions/share.doc.mjs b/packages/cli/assets/icons/definitions/share.doc.mjsnew file mode 100644index 0000000000..24b7b149f9--- /dev/null+++ b/packages/cli/assets/icons/definitions/share.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'share',+ description: 'Share with other people.',+ words: ['send to', 'forward'],+};diff --git a/packages/cli/assets/icons/definitions/shield.doc.mjs b/packages/cli/assets/icons/definitions/shield.doc.mjsnew file mode 100644index 0000000000..ddb2096d35--- /dev/null+++ b/packages/cli/assets/icons/definitions/shield.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'shield',+ description: 'Security or protection.',+ words: ['security', 'verified', 'protected'],+};diff --git a/packages/cli/assets/icons/definitions/shipping.doc.mjs b/packages/cli/assets/icons/definitions/shipping.doc.mjsnew file mode 100644index 0000000000..98d60984a7--- /dev/null+++ b/packages/cli/assets/icons/definitions/shipping.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'shipping',+ description: 'Shipping or delivery.',+ words: ['delivery', 'truck', 'ship'],+};diff --git a/packages/cli/assets/icons/definitions/shoppingBag.doc.mjs b/packages/cli/assets/icons/definitions/shoppingBag.doc.mjsnew file mode 100644index 0000000000..7a90423ad6--- /dev/null+++ b/packages/cli/assets/icons/definitions/shoppingBag.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'shoppingBag',+ description: 'A store, a purchase, or a shopping bag.',+ words: ['shop', 'store', 'purchase'],+};diff --git a/packages/cli/assets/icons/definitions/sparkles.doc.mjs b/packages/cli/assets/icons/definitions/sparkles.doc.mjsnew file mode 100644index 0000000000..84a97e9e4f--- /dev/null+++ b/packages/cli/assets/icons/definitions/sparkles.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'sparkles',+ description: 'AI or something new and special.',+ words: ['ai', 'magic', 'new'],+};diff --git a/packages/cli/assets/icons/definitions/star.doc.mjs b/packages/cli/assets/icons/definitions/star.doc.mjsnew file mode 100644index 0000000000..b1ac05a6ce--- /dev/null+++ b/packages/cli/assets/icons/definitions/star.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'star',+ description: 'Favorite or rate something.',+ words: ['favorite', 'rating', 'bookmark'],+};diff --git a/packages/cli/assets/icons/definitions/stop.doc.mjs b/packages/cli/assets/icons/definitions/stop.doc.mjsnew file mode 100644index 0000000000..c16430e912--- /dev/null+++ b/packages/cli/assets/icons/definitions/stop.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'stop',+ description: 'Stop or cancel a running action.',+ words: ['halt', 'end', 'cancel'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/strikethrough.doc.mjs b/packages/cli/assets/icons/definitions/strikethrough.doc.mjsnew file mode 100644index 0000000000..3052b78d08--- /dev/null+++ b/packages/cli/assets/icons/definitions/strikethrough.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'strikethrough',+ description: 'Strike text through.',+ words: ['strike', 'cross out', 'text format'],+};diff --git a/packages/cli/assets/icons/definitions/success.doc.mjs b/packages/cli/assets/icons/definitions/success.doc.mjsnew file mode 100644index 0000000000..fb7ec393a6--- /dev/null+++ b/packages/cli/assets/icons/definitions/success.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'success',+ description: 'Show that something worked.',+ words: ['ok', 'complete', 'passed'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/sun.doc.mjs b/packages/cli/assets/icons/definitions/sun.doc.mjsnew file mode 100644index 0000000000..f476618d0b--- /dev/null+++ b/packages/cli/assets/icons/definitions/sun.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'sun',+ description: 'Light mode or daytime.',+ words: ['light mode', 'day', 'bright'],+};diff --git a/packages/cli/assets/icons/definitions/swatch.doc.mjs b/packages/cli/assets/icons/definitions/swatch.doc.mjsnew file mode 100644index 0000000000..cadd0fe31d--- /dev/null+++ b/packages/cli/assets/icons/definitions/swatch.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'swatch',+ description: 'Pick colors, a palette, or a theme.',+ words: ['color', 'palette', 'theme'],+};diff --git a/packages/cli/assets/icons/definitions/table.doc.mjs b/packages/cli/assets/icons/definitions/table.doc.mjsnew file mode 100644index 0000000000..b927162a3e--- /dev/null+++ b/packages/cli/assets/icons/definitions/table.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'table',+ description: 'A table or grid of data.',+ words: ['grid', 'spreadsheet', 'rows'],+};diff --git a/packages/cli/assets/icons/definitions/tag.doc.mjs b/packages/cli/assets/icons/definitions/tag.doc.mjsnew file mode 100644index 0000000000..a55cd7ce37--- /dev/null+++ b/packages/cli/assets/icons/definitions/tag.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'tag',+ description: 'A tag or label.',+ words: ['label', 'category'],+};diff --git a/packages/cli/assets/icons/definitions/thumbsDown.doc.mjs b/packages/cli/assets/icons/definitions/thumbsDown.doc.mjsnew file mode 100644index 0000000000..108365f50f--- /dev/null+++ b/packages/cli/assets/icons/definitions/thumbsDown.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'thumbsDown',+ description: 'Give negative feedback.',+ words: ['dislike', 'bad'],+};diff --git a/packages/cli/assets/icons/definitions/thumbsUp.doc.mjs b/packages/cli/assets/icons/definitions/thumbsUp.doc.mjsnew file mode 100644index 0000000000..4dece26d42--- /dev/null+++ b/packages/cli/assets/icons/definitions/thumbsUp.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'thumbsUp',+ description: 'Approve or give positive feedback.',+ words: ['approve', 'good', 'like'],+};diff --git a/packages/cli/assets/icons/definitions/trendDown.doc.mjs b/packages/cli/assets/icons/definitions/trendDown.doc.mjsnew file mode 100644index 0000000000..c475e5e3da--- /dev/null+++ b/packages/cli/assets/icons/definitions/trendDown.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'trendDown',+ description: 'Show a value going down.',+ words: ['decrease', 'decline', 'down'],+};diff --git a/packages/cli/assets/icons/definitions/trendUp.doc.mjs b/packages/cli/assets/icons/definitions/trendUp.doc.mjsnew file mode 100644index 0000000000..49fcc4f9aa--- /dev/null+++ b/packages/cli/assets/icons/definitions/trendUp.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'trendUp',+ description: 'Show a value going up.',+ words: ['increase', 'growth', 'up'],+};diff --git a/packages/cli/assets/icons/definitions/underline.doc.mjs b/packages/cli/assets/icons/definitions/underline.doc.mjsnew file mode 100644index 0000000000..d2f1f0700e--- /dev/null+++ b/packages/cli/assets/icons/definitions/underline.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'underline',+ description: 'Underlined text.',+ words: ['text format'],+};diff --git a/packages/cli/assets/icons/definitions/undo.doc.mjs b/packages/cli/assets/icons/definitions/undo.doc.mjsnew file mode 100644index 0000000000..b3d109bcd9--- /dev/null+++ b/packages/cli/assets/icons/definitions/undo.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'undo',+ description: 'Undo the last change.',+ words: ['revert', 'back'],+};diff --git a/packages/cli/assets/icons/definitions/unlock.doc.mjs b/packages/cli/assets/icons/definitions/unlock.doc.mjsnew file mode 100644index 0000000000..6cca49fb31--- /dev/null+++ b/packages/cli/assets/icons/definitions/unlock.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'unlock',+ description: 'Unlocked or public.',+ words: ['open', 'public', 'unlocked'],+};diff --git a/packages/cli/assets/icons/definitions/upload.doc.mjs b/packages/cli/assets/icons/definitions/upload.doc.mjsnew file mode 100644index 0000000000..321a10799e--- /dev/null+++ b/packages/cli/assets/icons/definitions/upload.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'upload',+ description: 'Upload a file or content.',+ words: ['import', 'attach file'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/user.doc.mjs b/packages/cli/assets/icons/definitions/user.doc.mjsnew file mode 100644index 0000000000..831a7eb1f1--- /dev/null+++ b/packages/cli/assets/icons/definitions/user.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'user',+ description: "A person or the current user's profile.",+ words: ['person', 'profile', 'account'],+};diff --git a/packages/cli/assets/icons/definitions/userAdd.doc.mjs b/packages/cli/assets/icons/definitions/userAdd.doc.mjsnew file mode 100644index 0000000000..e04341ec05--- /dev/null+++ b/packages/cli/assets/icons/definitions/userAdd.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'userAdd',+ description: 'Invite or add a person.',+ words: ['invite', 'add person'],+};diff --git a/packages/cli/assets/icons/definitions/userCircle.doc.mjs b/packages/cli/assets/icons/definitions/userCircle.doc.mjsnew file mode 100644index 0000000000..ec1d203c32--- /dev/null+++ b/packages/cli/assets/icons/definitions/userCircle.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'userCircle',+ description: "The signed-in user's avatar or account.",+ words: ['avatar', 'account', 'me'],+};diff --git a/packages/cli/assets/icons/definitions/users.doc.mjs b/packages/cli/assets/icons/definitions/users.doc.mjsnew file mode 100644index 0000000000..5cd08cdf21--- /dev/null+++ b/packages/cli/assets/icons/definitions/users.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'users',+ description: 'A group of people or a team.',+ words: ['team', 'group', 'people', 'members'],+};diff --git a/packages/cli/assets/icons/definitions/video.doc.mjs b/packages/cli/assets/icons/definitions/video.doc.mjsnew file mode 100644index 0000000000..6e14cb09af--- /dev/null+++ b/packages/cli/assets/icons/definitions/video.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'video',+ description: 'A video or camera recording.',+ words: ['camera', 'record', 'movie'],+};diff --git a/packages/cli/assets/icons/definitions/viewColumns.doc.mjs b/packages/cli/assets/icons/definitions/viewColumns.doc.mjsnew file mode 100644index 0000000000..209cf64116--- /dev/null+++ b/packages/cli/assets/icons/definitions/viewColumns.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'viewColumns',+ description: 'Choose which columns are shown.',+ words: ['columns', 'layout'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/warning.doc.mjs b/packages/cli/assets/icons/definitions/warning.doc.mjsnew file mode 100644index 0000000000..e77ea3c760--- /dev/null+++ b/packages/cli/assets/icons/definitions/warning.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'warning',+ description: 'Warn about something that needs attention.',+ words: ['caution', 'alert'],+ builtIn: true,+};diff --git a/packages/cli/assets/icons/definitions/work.doc.mjs b/packages/cli/assets/icons/definitions/work.doc.mjsnew file mode 100644index 0000000000..f81324c764--- /dev/null+++ b/packages/cli/assets/icons/definitions/work.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'work',+ description: 'Work, a job, or business.',+ words: ['job', 'business', 'briefcase'],+};diff --git a/packages/cli/assets/icons/definitions/wrench.doc.mjs b/packages/cli/assets/icons/definitions/wrench.doc.mjsnew file mode 100644index 0000000000..c10e807232--- /dev/null+++ b/packages/cli/assets/icons/definitions/wrench.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'wrench',+ description: 'Open settings or configuration tools.',+ words: ['tools', 'configure', 'fix'],+ builtIn: true,+};diff --git a/packages/cli/assets/templates/blocks/components/AppShell/AppShellShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/AppShell/AppShellShowcase.doc.mjsindex a602c66287..c7ee44a002 100644--- a/packages/cli/assets/templates/blocks/components/AppShell/AppShellShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/AppShell/AppShellShowcase.doc.mjs@@ -9,7 +9,20 @@ export const doc = {isReady: true,aspectRatio: 4 / 3,isShowcase: true,- description:- 'A basic app shell with content padding.',- componentsUsed: ['AppShell', 'SideNav', 'Heading', 'Text', 'VStack', 'NavIcon'],+ description: 'A basic app shell with content padding.',+ componentsUsed: [+ 'AppShell',+ 'SideNav',+ 'Heading',+ 'Text',+ 'VStack',+ 'NavIcon',+ ],+ icons: {+ ChartBarIcon: 'chart',+ CubeIcon: 'package',+ DocumentTextIcon: 'document',+ HomeIcon: 'home',+ UsersIcon: 'users',+ },};diff --git a/packages/cli/assets/templates/blocks/components/AppShell/AppShellSideNavOnly.doc.mjs b/packages/cli/assets/templates/blocks/components/AppShell/AppShellSideNavOnly.doc.mjsindex 87540c10d2..70410fb251 100644--- a/packages/cli/assets/templates/blocks/components/AppShell/AppShellSideNavOnly.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/AppShell/AppShellSideNavOnly.doc.mjs@@ -10,5 +10,20 @@ export const doc = {'App shell with SideNav header providing app identity, no TopNav needed.',isReady: true,aspectRatio: 4 / 3,- componentsUsed: ['AppShell', 'SideNav', 'Heading', 'Text', 'VStack', 'NavIcon'],+ componentsUsed: [+ 'AppShell',+ 'SideNav',+ 'Heading',+ 'Text',+ 'VStack',+ 'NavIcon',+ ],+ icons: {+ ChartBarIcon: 'chart',+ Cog6ToothIcon: 'settings',+ CubeIcon: 'package',+ FolderIcon: 'folder',+ HomeIcon: 'home',+ UsersIcon: 'users',+ },};diff --git a/packages/cli/assets/templates/blocks/components/AppShell/AppShellTopNavOnly.doc.mjs b/packages/cli/assets/templates/blocks/components/AppShell/AppShellTopNavOnly.doc.mjsindex 2d810dd2f7..b2012bb93e 100644--- a/packages/cli/assets/templates/blocks/components/AppShell/AppShellTopNavOnly.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/AppShell/AppShellTopNavOnly.doc.mjs@@ -10,5 +10,13 @@ export const doc = {'Simple layout with TopNav and no side navigation, suitable for landing pages.',isReady: true,aspectRatio: 4 / 3,- componentsUsed: ['AppShell', 'TopNav', 'Heading', 'Text', 'VStack', 'NavIcon'],+ componentsUsed: [+ 'AppShell',+ 'TopNav',+ 'Heading',+ 'Text',+ 'VStack',+ 'NavIcon',+ ],+ icons: {CubeIcon: 'package'},};diff --git a/packages/cli/assets/templates/blocks/components/AppShell/AppShellTopNavWithSideNav.doc.mjs b/packages/cli/assets/templates/blocks/components/AppShell/AppShellTopNavWithSideNav.doc.mjsindex 2df4dd3bae..8370ccb2c5 100644--- a/packages/cli/assets/templates/blocks/components/AppShell/AppShellTopNavWithSideNav.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/AppShell/AppShellTopNavWithSideNav.doc.mjs@@ -10,5 +10,21 @@ export const doc = {'The most common layout with TopNav for app identity and SideNav for page-level navigation.',isReady: true,aspectRatio: 4 / 3,- componentsUsed: ['AppShell', 'TopNav', 'SideNav', 'Heading', 'Text', 'VStack', 'NavIcon'],+ componentsUsed: [+ 'AppShell',+ 'TopNav',+ 'SideNav',+ 'Heading',+ 'Text',+ 'VStack',+ 'NavIcon',+ ],+ icons: {+ ChartBarIcon: 'chart',+ Cog6ToothIcon: 'settings',+ CubeIcon: 'package',+ FolderIcon: 'folder',+ HomeIcon: 'home',+ UsersIcon: 'users',+ },};diff --git a/packages/cli/assets/templates/blocks/components/AppShell/AppShellWithBanner.doc.mjs b/packages/cli/assets/templates/blocks/components/AppShell/AppShellWithBanner.doc.mjsindex b6f0109f1e..7db4c4b542 100644--- a/packages/cli/assets/templates/blocks/components/AppShell/AppShellWithBanner.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/AppShell/AppShellWithBanner.doc.mjs@@ -10,5 +10,22 @@ export const doc = {'Full layout with TopNav, SideNav, and a dismissable info banner between the nav and content.',isReady: true,aspectRatio: 4 / 3,- componentsUsed: ['AppShell', 'TopNav', 'SideNav', 'Banner', 'Heading', 'Text', 'VStack', 'NavIcon'],+ componentsUsed: [+ 'AppShell',+ 'TopNav',+ 'SideNav',+ 'Banner',+ 'Heading',+ 'Text',+ 'VStack',+ 'NavIcon',+ ],+ icons: {+ ChartBarIcon: 'chart',+ Cog6ToothIcon: 'settings',+ CubeIcon: 'package',+ FolderIcon: 'folder',+ HomeIcon: 'home',+ UsersIcon: 'users',+ },};diff --git a/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.doc.mjs b/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.doc.mjsindex 4b23438b3a..888a2bba65 100644--- a/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.doc.mjs@@ -12,4 +12,5 @@ export const doc = {isShowcase: true,aspectRatio: 16 / 9,componentsUsed: ['BaseTypeahead', 'Icon', 'Layout', 'Text'],+ icons: {MagnifyingGlassIcon: 'search'},};diff --git a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSnapPoints.doc.mjs b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSnapPoints.doc.mjsindex 61b6e6747d..eb08ef22a5 100644--- a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSnapPoints.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSnapPoints.doc.mjs@@ -20,4 +20,12 @@ export const doc = {'Stack','Text',],+ icons: {+ ArrowLeftIcon: 'arrowLeft',+ ArrowRightIcon: 'arrowRight',+ ArrowUpIcon: 'arrowUp',+ ArrowUturnLeftIcon: 'undo',+ FlagIcon: 'flag',+ MapPinIcon: 'location',+ },};diff --git a/packages/cli/assets/templates/blocks/components/BreadcrumbItem/BreadcrumbItemShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/BreadcrumbItem/BreadcrumbItemShowcase.doc.mjsindex 822181778f..438838e006 100644--- a/packages/cli/assets/templates/blocks/components/BreadcrumbItem/BreadcrumbItemShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/BreadcrumbItem/BreadcrumbItemShowcase.doc.mjs@@ -12,4 +12,5 @@ export const doc = {isShowcase: true,aspectRatio: 16 / 9,componentsUsed: ['Breadcrumbs', 'BreadcrumbItem'],+ icons: {HomeIcon: 'home'},};diff --git a/packages/cli/assets/templates/blocks/components/Breadcrumbs/BreadcrumbsDeepHierarchy.doc.mjs b/packages/cli/assets/templates/blocks/components/Breadcrumbs/BreadcrumbsDeepHierarchy.doc.mjsindex 1eb546797b..32bde92960 100644--- a/packages/cli/assets/templates/blocks/components/Breadcrumbs/BreadcrumbsDeepHierarchy.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Breadcrumbs/BreadcrumbsDeepHierarchy.doc.mjs@@ -10,4 +10,5 @@ export const doc = {isReady: true,aspectRatio: 4 / 1,componentsUsed: ['Breadcrumbs', 'Icon'],+ icons: {HomeIcon: 'home'},};diff --git a/packages/cli/assets/templates/blocks/components/Breadcrumbs/BreadcrumbsWithIcons.doc.mjs b/packages/cli/assets/templates/blocks/components/Breadcrumbs/BreadcrumbsWithIcons.doc.mjsindex 7266bf0356..0bdf1cb198 100644--- a/packages/cli/assets/templates/blocks/components/Breadcrumbs/BreadcrumbsWithIcons.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Breadcrumbs/BreadcrumbsWithIcons.doc.mjs@@ -10,4 +10,5 @@ export const doc = {isReady: true,aspectRatio: 4 / 1,componentsUsed: ['Breadcrumbs', 'Icon'],+ icons: {Cog6ToothIcon: 'settings', HomeIcon: 'home'},};diff --git a/packages/cli/assets/templates/blocks/components/Button/ButtonFloating.doc.mjs b/packages/cli/assets/templates/blocks/components/Button/ButtonFloating.doc.mjsindex e27684b9ec..b50f025e75 100644--- a/packages/cli/assets/templates/blocks/components/Button/ButtonFloating.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Button/ButtonFloating.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['Button', 'Icon', 'Layout', 'Text'],+ icons: {PlusIcon: 'add'},};diff --git a/packages/cli/assets/templates/blocks/components/Button/ButtonWithIcon.doc.mjs b/packages/cli/assets/templates/blocks/components/Button/ButtonWithIcon.doc.mjsindex d4309b5a6b..ad263bc5e0 100644--- a/packages/cli/assets/templates/blocks/components/Button/ButtonWithIcon.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Button/ButtonWithIcon.doc.mjs@@ -10,4 +10,10 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['Button', 'Icon', 'Layout'],+ icons: {+ ArrowDownTrayIcon: 'download',+ PencilSquareIcon: 'compose',+ PlusIcon: 'add',+ TrashIcon: 'delete',+ },};diff --git a/packages/cli/assets/templates/blocks/components/ButtonGroup/ButtonGroupShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/ButtonGroup/ButtonGroupShowcase.doc.mjsindex 794356e62a..40d2cf85b8 100644--- a/packages/cli/assets/templates/blocks/components/ButtonGroup/ButtonGroupShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ButtonGroup/ButtonGroupShowcase.doc.mjs@@ -10,4 +10,9 @@ export const doc = {aspectRatio: 16 / 9,isShowcase: true,componentsUsed: ['Button', 'ButtonGroup', 'Icon', 'IconButton', 'Layout'],+ icons: {+ ChevronDownIcon: 'chevronDown',+ ClipboardDocumentIcon: 'clipboard',+ ClipboardIcon: 'clipboard',+ },};diff --git a/packages/cli/assets/templates/blocks/components/Center/CenterHorizontal.doc.mjs b/packages/cli/assets/templates/blocks/components/Center/CenterHorizontal.doc.mjsindex 378d09b6fc..07364ac168 100644--- a/packages/cli/assets/templates/blocks/components/Center/CenterHorizontal.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Center/CenterHorizontal.doc.mjs@@ -11,4 +11,12 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['Center', 'Card', 'Icon', 'IconButton', 'Layout'],+ icons: {+ BoldIcon: 'bold',+ ItalicIcon: 'italic',+ LinkIcon: 'link',+ ListBulletIcon: 'list',+ PhotoIcon: 'image',+ UnderlineIcon: 'underline',+ },};diff --git a/packages/cli/assets/templates/blocks/components/Center/CenterInsideACard.doc.mjs b/packages/cli/assets/templates/blocks/components/Center/CenterInsideACard.doc.mjsindex 33922aa7d3..e8ff6f4715 100644--- a/packages/cli/assets/templates/blocks/components/Center/CenterInsideACard.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Center/CenterInsideACard.doc.mjs@@ -10,4 +10,5 @@ export const doc = {isReady: true,aspectRatio: 4 / 3,componentsUsed: ['Center', 'Card', 'Icon', 'Layout', 'Text'],+ icons: {InboxIcon: 'inbox'},};diff --git a/packages/cli/assets/templates/blocks/components/ChatComposer/ChatComposerFlat.doc.mjs b/packages/cli/assets/templates/blocks/components/ChatComposer/ChatComposerFlat.doc.mjsindex 0264d46a59..4a35f0a7ac 100644--- a/packages/cli/assets/templates/blocks/components/ChatComposer/ChatComposerFlat.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ChatComposer/ChatComposerFlat.doc.mjs@@ -11,4 +11,9 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['ChatComposer', 'Layout', 'Text'],+ icons: {+ Cog6ToothIcon: 'settings',+ MicrophoneIcon: 'microphone',+ SparklesIcon: 'sparkles',+ },};diff --git a/packages/cli/assets/templates/blocks/components/ChatComposer/ChatComposerFooterActions.doc.mjs b/packages/cli/assets/templates/blocks/components/ChatComposer/ChatComposerFooterActions.doc.mjsindex fbc896fb5a..58af0412ef 100644--- a/packages/cli/assets/templates/blocks/components/ChatComposer/ChatComposerFooterActions.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ChatComposer/ChatComposerFooterActions.doc.mjs@@ -9,5 +9,17 @@ export const doc = {description: 'Chat composer with dropdown menus for a model selector and settings in the footer, and a mic button in the send actions slot.',isReady: true,aspectRatio: 16 / 9,- componentsUsed: ['ChatComposer', 'Button', 'DropdownMenu', 'Icon', 'Layout', 'Text'],+ componentsUsed: [+ 'ChatComposer',+ 'Button',+ 'DropdownMenu',+ 'Icon',+ 'Layout',+ 'Text',+ ],+ icons: {+ Cog6ToothIcon: 'settings',+ MicrophoneIcon: 'microphone',+ SparklesIcon: 'sparkles',+ },};diff --git a/packages/cli/assets/templates/blocks/components/ChatComposer/ChatComposerFullFeatured.doc.mjs b/packages/cli/assets/templates/blocks/components/ChatComposer/ChatComposerFullFeatured.doc.mjsindex 6abd0c1210..23f1375261 100644--- a/packages/cli/assets/templates/blocks/components/ChatComposer/ChatComposerFullFeatured.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ChatComposer/ChatComposerFullFeatured.doc.mjs@@ -9,5 +9,21 @@ export const doc = {description: 'Chat composer with all slots populated: collapsible attachment drawer, header actions, context progress bar, footer dropdown menus, and mic button. Shows the maximum composer configuration.',isReady: true,aspectRatio: 4 / 3,- componentsUsed: ['ChatComposer', 'Token', 'Button', 'DropdownMenu', 'Icon', 'ProgressBar', 'Layout', 'Text'],+ componentsUsed: [+ 'ChatComposer',+ 'Token',+ 'Button',+ 'DropdownMenu',+ 'Icon',+ 'ProgressBar',+ 'Layout',+ 'Text',+ ],+ icons: {+ AtSymbolIcon: 'mention',+ Cog6ToothIcon: 'settings',+ MicrophoneIcon: 'microphone',+ PaperClipIcon: 'attach',+ SparklesIcon: 'sparkles',+ },};diff --git a/packages/cli/assets/templates/blocks/components/ChatComposerDrawer/ChatComposerDrawerShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/ChatComposerDrawer/ChatComposerDrawerShowcase.doc.mjsindex 4754749f53..89cc06d4a2 100644--- a/packages/cli/assets/templates/blocks/components/ChatComposerDrawer/ChatComposerDrawerShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ChatComposerDrawer/ChatComposerDrawerShowcase.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isShowcase: true,aspectRatio: 16 / 9,componentsUsed: ['Chat', 'Token', 'Icon', 'Button', 'Layout'],+ icons: {PaperClipIcon: 'attach'},};diff --git a/packages/cli/assets/templates/blocks/components/ChatComposerDrawer/ChatComposerDrawerWithProgress.doc.mjs b/packages/cli/assets/templates/blocks/components/ChatComposerDrawer/ChatComposerDrawerWithProgress.doc.mjsindex 1335411275..1cce0ea92c 100644--- a/packages/cli/assets/templates/blocks/components/ChatComposerDrawer/ChatComposerDrawerWithProgress.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ChatComposerDrawer/ChatComposerDrawerWithProgress.doc.mjs@@ -10,4 +10,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['Chat', 'Token', 'ProgressBar', 'Icon', 'Button', 'Layout'],+ icons: {AtSymbolIcon: 'mention', PaperClipIcon: 'attach'},};diff --git a/packages/cli/assets/templates/blocks/components/ChatMessageMetadata/ChatMessageMetadataFooter.doc.mjs b/packages/cli/assets/templates/blocks/components/ChatMessageMetadata/ChatMessageMetadataFooter.doc.mjsindex 6f8ac21288..4a7c8cfaab 100644--- a/packages/cli/assets/templates/blocks/components/ChatMessageMetadata/ChatMessageMetadataFooter.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ChatMessageMetadata/ChatMessageMetadataFooter.doc.mjs@@ -9,5 +9,19 @@ export const doc = {description: 'Assistant message with footer actions: copy, retry, thumbs up/down, and model label. Use for AI responses that need feedback or utility controls.',isReady: true,aspectRatio: 16 / 9,- componentsUsed: ['Chat', 'ChatMessageMetadata', 'Timestamp', 'Button', 'Icon', 'Text', 'Layout'],+ componentsUsed: [+ 'Chat',+ 'ChatMessageMetadata',+ 'Timestamp',+ 'Button',+ 'Icon',+ 'Text',+ 'Layout',+ ],+ icons: {+ ArrowPathIcon: 'refresh',+ ClipboardDocumentIcon: 'clipboard',+ HandThumbDownIcon: 'thumbsDown',+ HandThumbUpIcon: 'thumbsUp',+ },};diff --git a/packages/cli/assets/templates/blocks/components/ChatMessageMetadata/ChatMessageMetadataShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/ChatMessageMetadata/ChatMessageMetadataShowcase.doc.mjsindex 0dc188a6f3..9b5c23bb9b 100644--- a/packages/cli/assets/templates/blocks/components/ChatMessageMetadata/ChatMessageMetadataShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ChatMessageMetadata/ChatMessageMetadataShowcase.doc.mjs@@ -10,5 +10,19 @@ export const doc = {isReady: true,isShowcase: true,aspectRatio: 4 / 3,- componentsUsed: ['Chat', 'ChatMessageMetadata', 'Timestamp', 'Button', 'Icon', 'Text', 'Layout'],+ componentsUsed: [+ 'Chat',+ 'ChatMessageMetadata',+ 'Timestamp',+ 'Button',+ 'Icon',+ 'Text',+ 'Layout',+ ],+ icons: {+ ArrowPathIcon: 'refresh',+ ClipboardDocumentIcon: 'clipboard',+ HandThumbDownIcon: 'thumbsDown',+ HandThumbUpIcon: 'thumbsUp',+ },};diff --git a/packages/cli/assets/templates/blocks/components/ChatSendButton/ChatSendButtonCustomIcon.doc.mjs b/packages/cli/assets/templates/blocks/components/ChatSendButton/ChatSendButtonCustomIcon.doc.mjsindex 365d534248..a99249ecba 100644--- a/packages/cli/assets/templates/blocks/components/ChatSendButton/ChatSendButtonCustomIcon.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ChatSendButton/ChatSendButtonCustomIcon.doc.mjs@@ -10,4 +10,10 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['Chat', 'ChatSendButton', 'Icon', 'Layout', 'Text'],+ icons: {+ CheckIcon: 'check',+ PaperAirplaneIcon: 'send',+ SparklesIcon: 'sparkles',+ XCircleIcon: 'error',+ },};diff --git a/packages/cli/assets/templates/blocks/components/ChatSendButton/ChatSendButtonShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/ChatSendButton/ChatSendButtonShowcase.doc.mjsindex b48a195e1a..82037c2791 100644--- a/packages/cli/assets/templates/blocks/components/ChatSendButton/ChatSendButtonShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ChatSendButton/ChatSendButtonShowcase.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isShowcase: true,aspectRatio: 16 / 9,componentsUsed: ['Chat', 'ChatSendButton', 'Icon', 'Layout'],+ icons: {SparklesIcon: 'sparkles'},};diff --git a/packages/cli/assets/templates/blocks/components/ChatSystemMessage/ChatSystemMessageStatusUpdates.doc.mjs b/packages/cli/assets/templates/blocks/components/ChatSystemMessage/ChatSystemMessageStatusUpdates.doc.mjsindex 94bf153308..f0b7fdd7f5 100644--- a/packages/cli/assets/templates/blocks/components/ChatSystemMessage/ChatSystemMessageStatusUpdates.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ChatSystemMessage/ChatSystemMessageStatusUpdates.doc.mjs@@ -10,4 +10,5 @@ export const doc = {isReady: true,aspectRatio: 4 / 3,componentsUsed: ['Chat', 'Icon'],+ icons: {CheckCircleIcon: 'success', UserPlusIcon: 'userAdd'},};diff --git a/packages/cli/assets/templates/blocks/components/ChatSystemMessage/ChatSystemMessageWithIcon.doc.mjs b/packages/cli/assets/templates/blocks/components/ChatSystemMessage/ChatSystemMessageWithIcon.doc.mjsindex 0773a946f2..53530ad934 100644--- a/packages/cli/assets/templates/blocks/components/ChatSystemMessage/ChatSystemMessageWithIcon.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ChatSystemMessage/ChatSystemMessageWithIcon.doc.mjs@@ -10,4 +10,10 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['Chat', 'Icon', 'Layout', 'Text'],+ icons: {+ LockClosedIcon: 'lock',+ ShieldCheckIcon: 'shield',+ SparklesIcon: 'sparkles',+ UserPlusIcon: 'userAdd',+ },};diff --git a/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBottomSheet.doc.mjs b/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBottomSheet.doc.mjsindex c4eacc4e85..fad3b16161 100644--- a/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBottomSheet.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ContextMenu/ContextMenuBottomSheet.doc.mjs@@ -11,4 +11,10 @@ export const doc = {isReady: true,aspectRatio: 4 / 3,componentsUsed: ['ContextMenu'],+ icons: {+ DocumentDuplicateIcon: 'copy',+ PencilIcon: 'edit',+ ShareIcon: 'share',+ TrashIcon: 'delete',+ },};diff --git a/packages/cli/assets/templates/blocks/components/DropdownMenu/DropdownMenuBottomSheet.doc.mjs b/packages/cli/assets/templates/blocks/components/DropdownMenu/DropdownMenuBottomSheet.doc.mjsindex ec7b7e0e85..b7686fd677 100644--- a/packages/cli/assets/templates/blocks/components/DropdownMenu/DropdownMenuBottomSheet.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/DropdownMenu/DropdownMenuBottomSheet.doc.mjs@@ -12,4 +12,10 @@ export const doc = {isReady: true,aspectRatio: 3 / 4,componentsUsed: ['DropdownMenu', 'Stack', 'Text', 'useMediaQuery'],+ icons: {+ ArchiveBoxIcon: 'archive',+ DocumentDuplicateIcon: 'copy',+ PencilIcon: 'edit',+ ShareIcon: 'share',+ },};diff --git a/packages/cli/assets/templates/blocks/components/DropdownMenu/DropdownMenuNoChevron.doc.mjs b/packages/cli/assets/templates/blocks/components/DropdownMenu/DropdownMenuNoChevron.doc.mjsindex 74057b74d8..2c85a4d59d 100644--- a/packages/cli/assets/templates/blocks/components/DropdownMenu/DropdownMenuNoChevron.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/DropdownMenu/DropdownMenuNoChevron.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['DropdownMenu', 'Icon', 'Layout', 'Text'],+ icons: {EllipsisHorizontalIcon: 'moreHorizontal'},};diff --git a/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateActions.doc.mjs b/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateActions.doc.mjsindex 2a0fffb396..ebd435d872 100644--- a/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateActions.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateActions.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['EmptyState', 'Button', 'Icon'],+ icons: {MagnifyingGlassIcon: 'search'},};diff --git a/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateCompact.doc.mjs b/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateCompact.doc.mjsindex 2c6ec1f342..1924280d1f 100644--- a/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateCompact.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateCompact.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['EmptyState', 'Button', 'Layout', 'Icon'],+ icons: {InboxIcon: 'inbox'},};diff --git a/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateContainer.doc.mjs b/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateContainer.doc.mjsindex 318bccb537..18ca2133ec 100644--- a/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateContainer.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateContainer.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['EmptyState', 'Button', 'Card', 'Icon'],+ icons: {FolderPlusIcon: 'folderAdd'},};diff --git a/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateShowcase.doc.mjsindex a178eb8360..35983cfb42 100644--- a/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/EmptyState/EmptyStateShowcase.doc.mjs@@ -12,4 +12,5 @@ export const doc = {isShowcase: true,aspectRatio: 1,componentsUsed: ['EmptyState', 'Button', 'Icon'],+ icons: {MagnifyingGlassIcon: 'search'},};diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.doc.mjsindex 34ae03c838..7a692ccc2d 100644--- a/packages/cli/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['Item', 'Button', 'Icon', 'Card', 'Text', 'Layout'],+ icons: {PencilIcon: 'edit', TrashIcon: 'delete'},};diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage.doc.mjsindex 15318bbc7a..6117da3e4b 100644--- a/packages/cli/assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage.doc.mjs@@ -10,5 +10,14 @@ export const doc = {'Toolbar shows an ephemeral "← → to navigate" hint on first keyboard focus via useKeyboardHint, teaching sighted keyboard users that arrows move within the group.',isReady: true,aspectRatio: 16 / 9,- componentsUsed: ['Toolbar', 'Button', 'Icon', 'Card', 'Section', 'Text', 'Layout'],+ componentsUsed: [+ 'Toolbar',+ 'Button',+ 'Icon',+ 'Card',+ 'Section',+ 'Text',+ 'Layout',+ ],+ icons: {BoldIcon: 'bold', ItalicIcon: 'italic', UnderlineIcon: 'underline'},};diff --git a/packages/cli/assets/templates/blocks/components/HoverCard/HoverCardInteractiveContent.doc.mjs b/packages/cli/assets/templates/blocks/components/HoverCard/HoverCardInteractiveContent.doc.mjsindex af3a147c42..552802d43b 100644--- a/packages/cli/assets/templates/blocks/components/HoverCard/HoverCardInteractiveContent.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/HoverCard/HoverCardInteractiveContent.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['HoverCard', 'Icon', 'Layout', 'Link', 'Text'],+ icons: {LinkIcon: 'link'},};diff --git a/packages/cli/assets/templates/blocks/components/HoverCard/HoverCardProfileHoverCard.doc.mjs b/packages/cli/assets/templates/blocks/components/HoverCard/HoverCardProfileHoverCard.doc.mjsindex 6bac83c94d..00819fb0c3 100644--- a/packages/cli/assets/templates/blocks/components/HoverCard/HoverCardProfileHoverCard.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/HoverCard/HoverCardProfileHoverCard.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['HoverCard', 'Button', 'Layout', 'Text'],+ icons: {CalendarIcon: 'calendar'},};diff --git a/packages/cli/assets/templates/blocks/components/IconButton/IconButtonFloating.doc.mjs b/packages/cli/assets/templates/blocks/components/IconButton/IconButtonFloating.doc.mjsindex 82d7e25def..1b617a621a 100644--- a/packages/cli/assets/templates/blocks/components/IconButton/IconButtonFloating.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/IconButton/IconButtonFloating.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 4 / 3,componentsUsed: ['IconButton', 'Icon', 'Layout', 'Text'],+ icons: {PlusIcon: 'add'},};diff --git a/packages/cli/assets/templates/blocks/components/Item/ItemDocumentTabs.doc.mjs b/packages/cli/assets/templates/blocks/components/Item/ItemDocumentTabs.doc.mjsindex e86737afd9..fad01cd4c7 100644--- a/packages/cli/assets/templates/blocks/components/Item/ItemDocumentTabs.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Item/ItemDocumentTabs.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 4,componentsUsed: ['Item', 'Divider', 'Icon', 'IconButton', 'Layout'],+ icons: {DocumentIcon: 'file', PlusIcon: 'add', XMarkIcon: 'close'},};diff --git a/packages/cli/assets/templates/blocks/components/Item/ItemShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/Item/ItemShowcase.doc.mjsindex 4a7846da17..6e8571d7c7 100644--- a/packages/cli/assets/templates/blocks/components/Item/ItemShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Item/ItemShowcase.doc.mjs@@ -10,4 +10,5 @@ export const doc = {aspectRatio: 16 / 9,isShowcase: true,componentsUsed: ['Item', 'Avatar', 'Badge', 'Icon', 'Text', 'Layout'],+ icons: {BellIcon: 'notification', DocumentIcon: 'file', UserIcon: 'user'},};diff --git a/packages/cli/assets/templates/blocks/components/MobileNav/MobileNavBasicMobileNav.doc.mjs b/packages/cli/assets/templates/blocks/components/MobileNav/MobileNavBasicMobileNav.doc.mjsindex 0e68e8b630..5244a202a2 100644--- a/packages/cli/assets/templates/blocks/components/MobileNav/MobileNavBasicMobileNav.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/MobileNav/MobileNavBasicMobileNav.doc.mjs@@ -10,4 +10,11 @@ export const doc = {isReady: true,aspectRatio: 4 / 3,componentsUsed: ['MobileNav', 'SideNav', 'Button', 'Icon'],+ icons: {+ ChartBarIcon: 'chart',+ Cog6ToothIcon: 'settings',+ FolderIcon: 'folder',+ HomeIcon: 'home',+ UsersIcon: 'users',+ },};diff --git a/packages/cli/assets/templates/blocks/components/MobileNav/MobileNavEndSideMobileNav.doc.mjs b/packages/cli/assets/templates/blocks/components/MobileNav/MobileNavEndSideMobileNav.doc.mjsindex 24e91fac1f..e72ad5fc7b 100644--- a/packages/cli/assets/templates/blocks/components/MobileNav/MobileNavEndSideMobileNav.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/MobileNav/MobileNavEndSideMobileNav.doc.mjs@@ -10,4 +10,5 @@ export const doc = {isReady: true,aspectRatio: 4 / 3,componentsUsed: ['MobileNav', 'SideNav', 'Button'],+ icons: {Cog6ToothIcon: 'settings', UsersIcon: 'users'},};diff --git a/packages/cli/assets/templates/blocks/components/MobileNav/MobileNavWithoutTitleMobileNav.doc.mjs b/packages/cli/assets/templates/blocks/components/MobileNav/MobileNavWithoutTitleMobileNav.doc.mjsindex 4ca5e6d4b5..be6fdcc10b 100644--- a/packages/cli/assets/templates/blocks/components/MobileNav/MobileNavWithoutTitleMobileNav.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/MobileNav/MobileNavWithoutTitleMobileNav.doc.mjs@@ -10,4 +10,5 @@ export const doc = {isReady: true,aspectRatio: 4 / 3,componentsUsed: ['MobileNav', 'SideNav', 'Button', 'Icon'],+ icons: {FolderIcon: 'folder', HomeIcon: 'home'},};diff --git a/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuBottomSheet.doc.mjs b/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuBottomSheet.doc.mjsindex cec5baa4bf..d4cc9589db 100644--- a/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuBottomSheet.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuBottomSheet.doc.mjs@@ -11,4 +11,10 @@ export const doc = {isReady: true,aspectRatio: 4 / 3,componentsUsed: ['MoreMenu'],+ icons: {+ DocumentDuplicateIcon: 'copy',+ PencilIcon: 'edit',+ ShareIcon: 'share',+ TrashIcon: 'delete',+ },};diff --git a/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuWithDividers.doc.mjs b/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuWithDividers.doc.mjsindex b6c1a07925..739b5200a3 100644--- a/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuWithDividers.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuWithDividers.doc.mjs@@ -11,4 +11,9 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['MoreMenu'],+ icons: {+ DocumentDuplicateIcon: 'copy',+ PencilIcon: 'edit',+ TrashIcon: 'delete',+ },};diff --git a/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuWithSections.doc.mjs b/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuWithSections.doc.mjsindex 7691947a7e..777463bd88 100644--- a/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuWithSections.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/MoreMenu/MoreMenuWithSections.doc.mjs@@ -11,4 +11,9 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['MoreMenu'],+ icons: {+ DocumentDuplicateIcon: 'copy',+ PencilIcon: 'edit',+ TrashIcon: 'delete',+ },};diff --git a/packages/cli/assets/templates/blocks/components/Pagination/PaginationDotsCarousel.doc.mjs b/packages/cli/assets/templates/blocks/components/Pagination/PaginationDotsCarousel.doc.mjsindex dd44281900..1474aac057 100644--- a/packages/cli/assets/templates/blocks/components/Pagination/PaginationDotsCarousel.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Pagination/PaginationDotsCarousel.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 4 / 3,componentsUsed: ['Pagination', 'Card', 'Text', 'Layout', 'Icon', 'Avatar'],+ icons: {StarIcon: 'star'},};diff --git a/packages/cli/assets/templates/blocks/components/Popover/PopoverBottomSheetAlternative.doc.mjs b/packages/cli/assets/templates/blocks/components/Popover/PopoverBottomSheetAlternative.doc.mjsindex 4b333ecbcf..63cee830cc 100644--- a/packages/cli/assets/templates/blocks/components/Popover/PopoverBottomSheetAlternative.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Popover/PopoverBottomSheetAlternative.doc.mjs@@ -19,4 +19,5 @@ export const doc = {'Text','List',],+ icons: {CalendarIcon: 'calendar', TagIcon: 'tag', UserIcon: 'user'},};diff --git a/packages/cli/assets/templates/blocks/components/Section/SectionWashHighlight.doc.mjs b/packages/cli/assets/templates/blocks/components/Section/SectionWashHighlight.doc.mjsindex c7eb3a5191..5be393774d 100644--- a/packages/cli/assets/templates/blocks/components/Section/SectionWashHighlight.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Section/SectionWashHighlight.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 4 / 3,componentsUsed: ['Section', 'Layout', 'Text', 'Button', 'Icon'],+ icons: {CheckIcon: 'check'},};diff --git a/packages/cli/assets/templates/blocks/components/Selector/SelectorOptionDescriptions.doc.mjs b/packages/cli/assets/templates/blocks/components/Selector/SelectorOptionDescriptions.doc.mjsindex 5f6643bf29..e2bd9b6339 100644--- a/packages/cli/assets/templates/blocks/components/Selector/SelectorOptionDescriptions.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Selector/SelectorOptionDescriptions.doc.mjs@@ -10,5 +10,12 @@ export const doc = {'Options carry a description, so the dropdown draws a two-line row. The closed trigger is sized by padding, so it is the size token for a one-line value and exactly one line taller for a two-line one; both on the 4px rhythm. An InputGroup pins the row, so the value folds back onto one line there.',isReady: true,aspectRatio: 16 / 9,- componentsUsed: ['Selector', 'SelectorOption', 'InputGroup', 'Button', 'Stack'],+ componentsUsed: [+ 'Selector',+ 'SelectorOption',+ 'InputGroup',+ 'Button',+ 'Stack',+ ],+ icons: {GlobeAltIcon: 'globe', LockClosedIcon: 'lock'},};diff --git a/packages/cli/assets/templates/blocks/components/SelectorOption/SelectorOptionShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/SelectorOption/SelectorOptionShowcase.doc.mjsindex 4e462cf9f6..83bd65d61c 100644--- a/packages/cli/assets/templates/blocks/components/SelectorOption/SelectorOptionShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/SelectorOption/SelectorOptionShowcase.doc.mjs@@ -12,4 +12,5 @@ export const doc = {isShowcase: true,aspectRatio: 16 / 9,componentsUsed: ['Selector', 'SelectorOption'],+ icons: {UserIcon: 'user'},};diff --git a/packages/cli/assets/templates/blocks/components/TextArea/TextAreaWithIcon.doc.mjs b/packages/cli/assets/templates/blocks/components/TextArea/TextAreaWithIcon.doc.mjsindex 7f704c108f..cdc813258a 100644--- a/packages/cli/assets/templates/blocks/components/TextArea/TextAreaWithIcon.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TextArea/TextAreaWithIcon.doc.mjs@@ -10,4 +10,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['TextArea'],+ icons: {PencilSquareIcon: 'compose'},};diff --git a/packages/cli/assets/templates/blocks/components/TextInput/TextInputIcon.doc.mjs b/packages/cli/assets/templates/blocks/components/TextInput/TextInputIcon.doc.mjsindex c5c75bbc8b..4f885520bc 100644--- a/packages/cli/assets/templates/blocks/components/TextInput/TextInputIcon.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TextInput/TextInputIcon.doc.mjs@@ -10,4 +10,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['TextInput', 'Layout'],+ icons: {EnvelopeIcon: 'mail', LockClosedIcon: 'lock', UserIcon: 'user'},};diff --git a/packages/cli/assets/templates/blocks/components/TextInput/TextInputSearch.doc.mjs b/packages/cli/assets/templates/blocks/components/TextInput/TextInputSearch.doc.mjsindex ee6199f0ac..af1c4c1ed0 100644--- a/packages/cli/assets/templates/blocks/components/TextInput/TextInputSearch.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TextInput/TextInputSearch.doc.mjs@@ -10,4 +10,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['TextInput', 'Layout'],+ icons: {MagnifyingGlassIcon: 'search'},};diff --git a/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonColor.doc.mjs b/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonColor.doc.mjsindex 3403044035..9259d9bcbe 100644--- a/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonColor.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonColor.doc.mjs@@ -10,4 +10,15 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['ToggleButton', 'Layout', 'Text', 'Icon'],+ icons: {+ BellIcon: 'notification',+ BoldIcon: 'bold',+ BookmarkIcon: 'bookmark',+ HeartIcon: 'heart',+ ItalicIcon: 'italic',+ LinkIcon: 'link',+ StarIcon: 'star',+ StrikethroughIcon: 'strikethrough',+ UnderlineIcon: 'underline',+ },};diff --git a/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonGroup.doc.mjs b/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonGroup.doc.mjsindex 84761a2400..3fc2465581 100644--- a/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonGroup.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonGroup.doc.mjs@@ -9,5 +9,20 @@ export const doc = {description: 'Toggle button groups in single-select and multi-select modes. Single selection acts as a view mode switcher; multiple selection forms a formatting toolbar.',isReady: true,aspectRatio: 16 / 9,- componentsUsed: ['ToggleButton', 'ToggleButtonGroup', 'Layout', 'Text', 'Icon'],+ componentsUsed: [+ 'ToggleButton',+ 'ToggleButtonGroup',+ 'Layout',+ 'Text',+ 'Icon',+ ],+ icons: {+ BoldIcon: 'bold',+ ItalicIcon: 'italic',+ ListBulletIcon: 'list',+ Squares2X2Icon: 'gridView',+ StrikethroughIcon: 'strikethrough',+ TableCellsIcon: 'table',+ UnderlineIcon: 'underline',+ },};diff --git a/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonIconSwap.doc.mjs b/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonIconSwap.doc.mjsindex b6cd0bf980..aab70fca96 100644--- a/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonIconSwap.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonIconSwap.doc.mjs@@ -10,4 +10,10 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['ToggleButton', 'Layout', 'Text', 'Icon'],+ icons: {+ BellIcon: 'notification',+ BellSlashIcon: 'notificationOff',+ BookmarkIcon: 'bookmark',+ StarIcon: 'star',+ },};diff --git a/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonLabel.doc.mjs b/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonLabel.doc.mjsindex 0670d0c1c9..0745e172ed 100644--- a/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonLabel.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonLabel.doc.mjs@@ -9,5 +9,17 @@ export const doc = {description: 'Toggle buttons with visible text labels that show a font weight shift on press. Use when the icon alone is not enough to communicate the action.',isReady: true,aspectRatio: 16 / 9,- componentsUsed: ['ToggleButton', 'ToggleButtonGroup', 'Layout', 'Text', 'Icon'],+ componentsUsed: [+ 'ToggleButton',+ 'ToggleButtonGroup',+ 'Layout',+ 'Text',+ 'Icon',+ ],+ icons: {+ EyeIcon: 'eye',+ EyeSlashIcon: 'eyeSlash',+ FunnelIcon: 'funnel',+ MapPinIcon: 'location',+ },};diff --git a/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonShowcase.doc.mjsindex 6dcff9f42c..499fa09ef3 100644--- a/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonShowcase.doc.mjs@@ -10,4 +10,10 @@ export const doc = {aspectRatio: 16 / 9,isShowcase: true,componentsUsed: ['Icon', 'Layout', 'ToggleButton'],+ icons: {+ BellIcon: 'notification',+ BellSlashIcon: 'notificationOff',+ BookmarkIcon: 'bookmark',+ StarIcon: 'star',+ },};diff --git a/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonStates.doc.mjs b/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonStates.doc.mjsindex 591ccae5fc..4a4f09a733 100644--- a/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonStates.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/ToggleButton/ToggleButtonStates.doc.mjs@@ -10,4 +10,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['ToggleButton', 'Layout', 'Text', 'Icon'],+ icons: {StarIcon: 'star'},};diff --git a/packages/cli/assets/templates/blocks/components/Token/TokenIcon.doc.mjs b/packages/cli/assets/templates/blocks/components/Token/TokenIcon.doc.mjsindex c23eb9f73a..deee04080c 100644--- a/packages/cli/assets/templates/blocks/components/Token/TokenIcon.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Token/TokenIcon.doc.mjs@@ -10,4 +10,10 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['Token', 'Icon', 'Layout', 'Text'],+ icons: {+ ShieldCheckIcon: 'shield',+ StarIcon: 'star',+ TagIcon: 'tag',+ UserIcon: 'user',+ },};diff --git a/packages/cli/assets/templates/blocks/components/Token/TokenShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/Token/TokenShowcase.doc.mjsindex 90fe4defd0..28e44ef535 100644--- a/packages/cli/assets/templates/blocks/components/Token/TokenShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Token/TokenShowcase.doc.mjs@@ -10,4 +10,5 @@ export const doc = {aspectRatio: 1,isShowcase: true,componentsUsed: ['Icon', 'Layout', 'Token'],+ icons: {TagIcon: 'tag'},};diff --git a/packages/cli/assets/templates/blocks/components/Tokenizer/TokenizerIcon.doc.mjs b/packages/cli/assets/templates/blocks/components/Tokenizer/TokenizerIcon.doc.mjsindex a4fc294e6f..334122476f 100644--- a/packages/cli/assets/templates/blocks/components/Tokenizer/TokenizerIcon.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Tokenizer/TokenizerIcon.doc.mjs@@ -10,4 +10,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['Tokenizer', 'Layout', 'Text'],+ icons: {MagnifyingGlassIcon: 'search'},};diff --git a/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarBulkActions.doc.mjs b/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarBulkActions.doc.mjsindex cac5d78ae1..4417e22d2a 100644--- a/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarBulkActions.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarBulkActions.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['Toolbar', 'Button', 'Icon', 'Badge', 'Table'],+ icons: {ArchiveBoxIcon: 'archive', TrashIcon: 'delete'},};diff --git a/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarCardHeader.doc.mjs b/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarCardHeader.doc.mjsindex b8efb98107..abae99c608 100644--- a/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarCardHeader.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarCardHeader.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['Toolbar', 'Button', 'Icon', 'Text', 'Card', 'Section'],+ icons: {FunnelIcon: 'funnel', PlusIcon: 'add'},};diff --git a/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarSizes.doc.mjs b/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarSizes.doc.mjsindex 6d901c71ab..d3cf4a3dbb 100644--- a/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarSizes.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarSizes.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['Toolbar', 'Button', 'Icon', 'Text', 'Layout', 'Card'],+ icons: {FunnelIcon: 'funnel', PlusIcon: 'add'},};diff --git a/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarTableFilter.doc.mjs b/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarTableFilter.doc.mjsindex b130be16e7..8167938d4a 100644--- a/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarTableFilter.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarTableFilter.doc.mjs@@ -27,4 +27,5 @@ export const doc = {'Table','EmptyState',],+ icons: {Columns3Cog: 'viewColumns', Search: 'search'},};diff --git a/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarThreeSlot.doc.mjs b/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarThreeSlot.doc.mjsindex 7eead7b608..562e2d7c5d 100644--- a/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarThreeSlot.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarThreeSlot.doc.mjs@@ -12,4 +12,5 @@ export const doc = {isShowcase: true,aspectRatio: 16 / 9,componentsUsed: ['Toolbar', 'Button', 'Icon', 'Text', 'Card', 'Section'],+ icons: {ArrowLeftIcon: 'arrowLeft'},};diff --git a/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarWithTabs.doc.mjs b/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarWithTabs.doc.mjsindex 6d99168314..5a13b265f3 100644--- a/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarWithTabs.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Toolbar/ToolbarWithTabs.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['Toolbar', 'TabList', 'Button', 'Icon', 'Card', 'Section'],+ icons: {PlusIcon: 'add'},};diff --git a/packages/cli/assets/templates/blocks/components/TopNav/TopNavCenteredNavigation.doc.mjs b/packages/cli/assets/templates/blocks/components/TopNav/TopNavCenteredNavigation.doc.mjsindex f1ce83a33d..2f804252f9 100644--- a/packages/cli/assets/templates/blocks/components/TopNav/TopNavCenteredNavigation.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TopNav/TopNavCenteredNavigation.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['TopNav', 'NavIcon', 'Button'],+ icons: {CubeIcon: 'package', UserCircleIcon: 'userCircle'},};diff --git a/packages/cli/assets/templates/blocks/components/TopNav/TopNavEnterpriseDashboard.doc.mjs b/packages/cli/assets/templates/blocks/components/TopNav/TopNavEnterpriseDashboard.doc.mjsindex 626d9ea4fb..3756f6186f 100644--- a/packages/cli/assets/templates/blocks/components/TopNav/TopNavEnterpriseDashboard.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TopNav/TopNavEnterpriseDashboard.doc.mjs@@ -11,4 +11,10 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['TopNav', 'NavIcon', 'Button'],+ icons: {+ BellIcon: 'notification',+ CubeIcon: 'package',+ DocumentTextIcon: 'document',+ HomeIcon: 'home',+ },};diff --git a/packages/cli/assets/templates/blocks/components/TopNav/TopNavHoverMenu.doc.mjs b/packages/cli/assets/templates/blocks/components/TopNav/TopNavHoverMenu.doc.mjsindex c3038b6a3b..f3b6643805 100644--- a/packages/cli/assets/templates/blocks/components/TopNav/TopNavHoverMenu.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TopNav/TopNavHoverMenu.doc.mjs@@ -11,4 +11,12 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['TopNav', 'TopNavMenu', 'NavIcon', 'Button'],+ icons: {+ BoltIcon: 'bolt',+ ChartBarIcon: 'chart',+ CodeBracketIcon: 'code',+ CubeIcon: 'package',+ ShieldCheckIcon: 'shield',+ UserCircleIcon: 'userCircle',+ },};diff --git a/packages/cli/assets/templates/blocks/components/TopNav/TopNavMegaMenu.doc.mjs b/packages/cli/assets/templates/blocks/components/TopNav/TopNavMegaMenu.doc.mjsindex d4d7d9abf1..76f9f442bc 100644--- a/packages/cli/assets/templates/blocks/components/TopNav/TopNavMegaMenu.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TopNav/TopNavMegaMenu.doc.mjs@@ -11,4 +11,12 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['TopNav', 'TopNavMegaMenu', 'NavIcon', 'Button'],+ icons: {+ BoltIcon: 'bolt',+ ChartBarIcon: 'chart',+ CodeBracketIcon: 'code',+ CubeIcon: 'package',+ GlobeAltIcon: 'globe',+ ShieldCheckIcon: 'shield',+ },};diff --git a/packages/cli/assets/templates/blocks/components/TopNav/TopNavMultipleDropdowns.doc.mjs b/packages/cli/assets/templates/blocks/components/TopNav/TopNavMultipleDropdowns.doc.mjsindex aeeaf64e20..b8b9962b02 100644--- a/packages/cli/assets/templates/blocks/components/TopNav/TopNavMultipleDropdowns.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TopNav/TopNavMultipleDropdowns.doc.mjs@@ -11,4 +11,9 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['TopNav', 'TopNavMenu'],+ icons: {+ ChartBarIcon: 'chart',+ CubeIcon: 'package',+ ShieldCheckIcon: 'shield',+ },};diff --git a/packages/cli/assets/templates/blocks/components/TopNav/TopNavShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/TopNav/TopNavShowcase.doc.mjsindex e382fc5923..270cdf2466 100644--- a/packages/cli/assets/templates/blocks/components/TopNav/TopNavShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TopNav/TopNavShowcase.doc.mjs@@ -10,4 +10,9 @@ export const doc = {aspectRatio: 3,isShowcase: true,componentsUsed: ['Button', 'Icon', 'TopNav'],+ icons: {+ BellIcon: 'notification',+ CubeIcon: 'package',+ UserCircleIcon: 'userCircle',+ },};diff --git a/packages/cli/assets/templates/blocks/components/TopNav/TopNavWithLogo.doc.mjs b/packages/cli/assets/templates/blocks/components/TopNav/TopNavWithLogo.doc.mjsindex e7eee5c769..ceb1204be8 100644--- a/packages/cli/assets/templates/blocks/components/TopNav/TopNavWithLogo.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TopNav/TopNavWithLogo.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['TopNav', 'NavIcon', 'Button'],+ icons: {CubeIcon: 'package', UserCircleIcon: 'userCircle'},};diff --git a/packages/cli/assets/templates/blocks/components/TopNavMegaMenu/TopNavMegaMenuBasic.doc.mjs b/packages/cli/assets/templates/blocks/components/TopNavMegaMenu/TopNavMegaMenuBasic.doc.mjsindex 749c468b49..715b6ec0cc 100644--- a/packages/cli/assets/templates/blocks/components/TopNavMegaMenu/TopNavMegaMenuBasic.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TopNavMegaMenu/TopNavMegaMenuBasic.doc.mjs@@ -17,4 +17,5 @@ export const doc = {'TopNavMegaMenu','TopNavMegaMenuItem',],+ icons: {BookOpenIcon: 'book', RocketLaunchIcon: 'rocket'},};diff --git a/packages/cli/assets/templates/blocks/components/TopNavMegaMenu/TopNavMegaMenuShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/TopNavMegaMenu/TopNavMegaMenuShowcase.doc.mjsindex 0c0646977b..cf2c21642b 100644--- a/packages/cli/assets/templates/blocks/components/TopNavMegaMenu/TopNavMegaMenuShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TopNavMegaMenu/TopNavMegaMenuShowcase.doc.mjs@@ -10,5 +10,17 @@ export const doc = {isReady: true,isShowcase: true,aspectRatio: 16 / 9,- componentsUsed: ['TopNav', 'TopNavMegaMenu', 'TopNavMegaMenuItem', 'TopNavMegaMenuFeaturedCard'],+ componentsUsed: [+ 'TopNav',+ 'TopNavMegaMenu',+ 'TopNavMegaMenuItem',+ 'TopNavMegaMenuFeaturedCard',+ ],+ icons: {+ BookOpenIcon: 'book',+ CodeBracketIcon: 'code',+ MagnifyingGlassIcon: 'search',+ RocketLaunchIcon: 'rocket',+ ShieldCheckIcon: 'shield',+ },};diff --git a/packages/cli/assets/templates/blocks/components/TopNavMegaMenuItem/TopNavMegaMenuItemBasic.doc.mjs b/packages/cli/assets/templates/blocks/components/TopNavMegaMenuItem/TopNavMegaMenuItemBasic.doc.mjsindex aef8c7e760..06a37376c3 100644--- a/packages/cli/assets/templates/blocks/components/TopNavMegaMenuItem/TopNavMegaMenuItemBasic.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TopNavMegaMenuItem/TopNavMegaMenuItemBasic.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['TopNavMegaMenuItem', 'Grid'],+ icons: {BoltIcon: 'bolt', CircleStackIcon: 'database'},};diff --git a/packages/cli/assets/templates/blocks/components/TopNavMenu/TopNavMenuBasic.doc.mjs b/packages/cli/assets/templates/blocks/components/TopNavMenu/TopNavMenuBasic.doc.mjsindex 7f70c1dc35..7df337968e 100644--- a/packages/cli/assets/templates/blocks/components/TopNavMenu/TopNavMenuBasic.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TopNavMenu/TopNavMenuBasic.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,componentsUsed: ['TopNav', 'TopNavHeading', 'TopNavItem', 'TopNavMenu'],+ icons: {ChartBarIcon: 'chart', Cog6ToothIcon: 'settings'},};diff --git a/packages/cli/assets/templates/blocks/components/TopNavMenu/TopNavMenuShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/TopNavMenu/TopNavMenuShowcase.doc.mjsindex 430e91d817..9408195a5c 100644--- a/packages/cli/assets/templates/blocks/components/TopNavMenu/TopNavMenuShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TopNavMenu/TopNavMenuShowcase.doc.mjs@@ -11,4 +11,10 @@ export const doc = {isShowcase: true,aspectRatio: 16 / 9,componentsUsed: ['TopNav', 'TopNavMenu', 'TopNavItem'],+ icons: {+ ChartBarIcon: 'chart',+ Cog6ToothIcon: 'settings',+ MagnifyingGlassIcon: 'search',+ UsersIcon: 'users',+ },};diff --git a/packages/cli/assets/templates/blocks/components/TreeList/TreeListFileTreeWithIcons.doc.mjs b/packages/cli/assets/templates/blocks/components/TreeList/TreeListFileTreeWithIcons.doc.mjsindex a3c7b52ce5..94652c64da 100644--- a/packages/cli/assets/templates/blocks/components/TreeList/TreeListFileTreeWithIcons.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TreeList/TreeListFileTreeWithIcons.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 4 / 3,componentsUsed: ['TreeList', 'Icon'],+ icons: {DocumentIcon: 'file', FolderIcon: 'folder'},};diff --git a/packages/cli/assets/templates/blocks/components/TreeList/TreeListInteractiveSettings.doc.mjs b/packages/cli/assets/templates/blocks/components/TreeList/TreeListInteractiveSettings.doc.mjsindex 75fe7f1a15..96c70d68bc 100644--- a/packages/cli/assets/templates/blocks/components/TreeList/TreeListInteractiveSettings.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TreeList/TreeListInteractiveSettings.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 4 / 3,componentsUsed: ['TreeList', 'Icon'],+ icons: {ChevronRightIcon: 'chevronRight', Cog6ToothIcon: 'settings'},};diff --git a/packages/cli/assets/templates/blocks/components/Typeahead/TypeaheadSearchField.doc.mjs b/packages/cli/assets/templates/blocks/components/Typeahead/TypeaheadSearchField.doc.mjsindex 5df4ee23a5..04cd42b556 100644--- a/packages/cli/assets/templates/blocks/components/Typeahead/TypeaheadSearchField.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/Typeahead/TypeaheadSearchField.doc.mjs@@ -11,4 +11,5 @@ export const doc = {isReady: true,aspectRatio: 4 / 3,componentsUsed: ['Typeahead', 'Center'],+ icons: {MagnifyingGlassIcon: 'search'},};diff --git a/packages/cli/assets/templates/blocks/components/VisuallyHidden/VisuallyHiddenShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/VisuallyHidden/VisuallyHiddenShowcase.doc.mjsindex 38740bec8e..8c592f8cfb 100644--- a/packages/cli/assets/templates/blocks/components/VisuallyHidden/VisuallyHiddenShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/VisuallyHidden/VisuallyHiddenShowcase.doc.mjs@@ -9,5 +9,19 @@ export const doc = {isReady: true,aspectRatio: 16 / 9,isShowcase: true,- componentsUsed: ['VisuallyHidden', 'IconButton', 'Card', 'HStack', 'VStack', 'Text', 'Icon'],+ componentsUsed: [+ 'VisuallyHidden',+ 'IconButton',+ 'Card',+ 'HStack',+ 'VStack',+ 'Text',+ 'Icon',+ ],+ icons: {+ ArrowDownTrayIcon: 'download',+ ShareIcon: 'share',+ SpeakerWaveIcon: 'audio',+ TrashIcon: 'delete',+ },};diff --git a/packages/cli/assets/templates/blocks/components/VisuallyHidden/VisuallyHiddenSupplementaryContext.doc.mjs b/packages/cli/assets/templates/blocks/components/VisuallyHidden/VisuallyHiddenSupplementaryContext.doc.mjsindex ca11ad82dc..966fb7f4db 100644--- a/packages/cli/assets/templates/blocks/components/VisuallyHidden/VisuallyHiddenSupplementaryContext.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/VisuallyHidden/VisuallyHiddenSupplementaryContext.doc.mjs@@ -10,5 +10,13 @@ export const doc = {'Add screen-reader-only context to terse visual data, like spelling out what a trend arrow means.',isReady: true,aspectRatio: 4 / 3,- componentsUsed: ['VisuallyHidden', 'Card', 'HStack', 'VStack', 'Text', 'Icon'],+ componentsUsed: [+ 'VisuallyHidden',+ 'Card',+ 'HStack',+ 'VStack',+ 'Text',+ 'Icon',+ ],+ icons: {ArrowDownIcon: 'arrowDown', ArrowUpIcon: 'arrowUp'},};diff --git a/packages/cli/assets/templates/pages/ai-chat-landing/template.doc.mjs b/packages/cli/assets/templates/pages/ai-chat-landing/template.doc.mjsindex ea45c4ab85..f8fd9b91cf 100644--- a/packages/cli/assets/templates/pages/ai-chat-landing/template.doc.mjs+++ b/packages/cli/assets/templates/pages/ai-chat-landing/template.doc.mjs@@ -16,4 +16,15 @@ export const doc = {],isReady: true,category: 'AI Chat - Landing',+ icons: {+ AtSymbolIcon: 'mention',+ ClockIcon: 'clock',+ CodeBracketIcon: 'code',+ Cog6ToothIcon: 'settings',+ LightBulbIcon: 'lightbulb',+ LockClosedIcon: 'lock',+ MagnifyingGlassIcon: 'search',+ PencilSquareIcon: 'compose',+ SparklesIcon: 'sparkles',+ },};diff --git a/packages/cli/assets/templates/pages/ai-chat/template.doc.mjs b/packages/cli/assets/templates/pages/ai-chat/template.doc.mjsindex 28fe67d237..44d50affca 100644--- a/packages/cli/assets/templates/pages/ai-chat/template.doc.mjs+++ b/packages/cli/assets/templates/pages/ai-chat/template.doc.mjs@@ -23,4 +23,13 @@ export const doc = {],isReady: true,category: 'AI Chat - Conversation',+ icons: {+ AtSymbolIcon: 'mention',+ ChevronRightIcon: 'chevronRight',+ ClipboardDocumentIcon: 'clipboard',+ DocumentTextIcon: 'document',+ PaperClipIcon: 'attach',+ ShareIcon: 'share',+ XMarkIcon: 'close',+ },};diff --git a/packages/cli/assets/templates/pages/canvas-editor/template.doc.mjs b/packages/cli/assets/templates/pages/canvas-editor/template.doc.mjsindex 14457a9d2b..0be68ee934 100644--- a/packages/cli/assets/templates/pages/canvas-editor/template.doc.mjs+++ b/packages/cli/assets/templates/pages/canvas-editor/template.doc.mjs@@ -17,4 +17,21 @@ export const doc = {],isReady: true,category: 'Tools - Canvas Editor',+ icons: {+ Download: 'download',+ File: 'file',+ Grip: 'drag',+ Image: 'image',+ Italic: 'italic',+ Lock: 'lock',+ LockOpen: 'unlock',+ Menu: 'menu',+ Minus: 'remove',+ Plus: 'add',+ Redo2: 'redo',+ Strikethrough: 'strikethrough',+ Underline: 'underline',+ Undo2: 'undo',+ X: 'close',+ },};diff --git a/packages/cli/assets/templates/pages/centered-hero/template.doc.mjs b/packages/cli/assets/templates/pages/centered-hero/template.doc.mjsindex e2ad85e124..972eac8402 100644--- a/packages/cli/assets/templates/pages/centered-hero/template.doc.mjs+++ b/packages/cli/assets/templates/pages/centered-hero/template.doc.mjs@@ -10,4 +10,5 @@ export const doc = {keywords: ['hero', 'banner', 'splash', 'landing image', 'marketing masthead'],isReady: true,category: 'Gallery - Hero',+ icons: {ArrowRightIcon: 'arrowRight'},};diff --git a/packages/cli/assets/templates/pages/checkout-wizard/template.doc.mjs b/packages/cli/assets/templates/pages/checkout-wizard/template.doc.mjsindex 1f8acef0a4..c7dbaa9b03 100644--- a/packages/cli/assets/templates/pages/checkout-wizard/template.doc.mjs+++ b/packages/cli/assets/templates/pages/checkout-wizard/template.doc.mjs@@ -10,4 +10,11 @@ export const doc = {keywords: ['checkout', 'cart', 'order', 'payment'],isReady: true,category: 'Form - Checkout',+ icons: {+ CreditCardIcon: 'creditCard',+ LockClosedIcon: 'lock',+ MapPinIcon: 'location',+ ShoppingCartIcon: 'cart',+ TruckIcon: 'shipping',+ },};diff --git a/packages/cli/assets/templates/pages/contact-form/template.doc.mjs b/packages/cli/assets/templates/pages/contact-form/template.doc.mjsindex d8ebc369e7..802c44d01c 100644--- a/packages/cli/assets/templates/pages/contact-form/template.doc.mjs+++ b/packages/cli/assets/templates/pages/contact-form/template.doc.mjs@@ -23,4 +23,9 @@ export const doc = {],isReady: true,category: 'Form - Basic',+ icons: {+ AdjustmentsHorizontalIcon: 'adjustments',+ HandRaisedIcon: 'raiseHand',+ RocketLaunchIcon: 'rocket',+ },};diff --git a/packages/cli/assets/templates/pages/dashboard-alert-rail/template.doc.mjs b/packages/cli/assets/templates/pages/dashboard-alert-rail/template.doc.mjsindex 2039941f02..a8b827b5e4 100644--- a/packages/cli/assets/templates/pages/dashboard-alert-rail/template.doc.mjs+++ b/packages/cli/assets/templates/pages/dashboard-alert-rail/template.doc.mjs@@ -31,4 +31,12 @@ export const doc = {],isReady: true,category: 'Dashboard - Monitoring',+ icons: {+ ArrowDownIcon: 'arrowDown',+ ArrowUpIcon: 'arrowUp',+ BellAlertIcon: 'notificationActive',+ CheckCircleIcon: 'success',+ ServerStackIcon: 'server',+ StopIcon: 'stop',+ },};diff --git a/packages/cli/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs b/packages/cli/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjsindex 29402d9e7f..4d168bf91b 100644--- a/packages/cli/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs+++ b/packages/cli/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs@@ -18,4 +18,11 @@ export const doc = {],isReady: true,category: 'Dashboard - Funnel & Cohort',+ icons: {+ ArrowDownIcon: 'arrowDown',+ ArrowDownTrayIcon: 'download',+ ArrowTrendingDownIcon: 'trendDown',+ ArrowUpIcon: 'arrowUp',+ StopIcon: 'stop',+ },};diff --git a/packages/cli/assets/templates/pages/dashboard-comparison/template.doc.mjs b/packages/cli/assets/templates/pages/dashboard-comparison/template.doc.mjsindex a1ee039008..0120639f78 100644--- a/packages/cli/assets/templates/pages/dashboard-comparison/template.doc.mjs+++ b/packages/cli/assets/templates/pages/dashboard-comparison/template.doc.mjs@@ -17,4 +17,12 @@ export const doc = {],isReady: true,category: 'Dashboard - Comparison',+ icons: {+ ArrowDownIcon: 'arrowDown',+ ArrowDownTrayIcon: 'download',+ ArrowUpIcon: 'arrowUp',+ CursorArrowRaysIcon: 'click',+ StopIcon: 'stop',+ UsersIcon: 'users',+ },};diff --git a/packages/cli/assets/templates/pages/dashboard-composition/template.doc.mjs b/packages/cli/assets/templates/pages/dashboard-composition/template.doc.mjsindex 9d80168695..3572f5c3e0 100644--- a/packages/cli/assets/templates/pages/dashboard-composition/template.doc.mjs+++ b/packages/cli/assets/templates/pages/dashboard-composition/template.doc.mjs@@ -18,4 +18,5 @@ export const doc = {],isReady: true,category: 'Dashboard - Portfolio',+ icons: {ArrowDownIcon: 'arrowDown', ArrowUpIcon: 'arrowUp'},};diff --git a/packages/cli/assets/templates/pages/dashboard-progress/template.doc.mjs b/packages/cli/assets/templates/pages/dashboard-progress/template.doc.mjsindex 4ad3ca45c3..1567539619 100644--- a/packages/cli/assets/templates/pages/dashboard-progress/template.doc.mjs+++ b/packages/cli/assets/templates/pages/dashboard-progress/template.doc.mjs@@ -25,4 +25,11 @@ export const doc = {],isReady: true,category: 'Dashboard - Project Status',+ icons: {+ ArrowDownTrayIcon: 'download',+ CheckCircleIcon: 'success',+ ExclamationTriangleIcon: 'warning',+ FlagIcon: 'flag',+ StopIcon: 'stop',+ },};diff --git a/packages/cli/assets/templates/pages/dashboard-scorecard/template.doc.mjs b/packages/cli/assets/templates/pages/dashboard-scorecard/template.doc.mjsindex 01535297b7..6dc5c27c53 100644--- a/packages/cli/assets/templates/pages/dashboard-scorecard/template.doc.mjs+++ b/packages/cli/assets/templates/pages/dashboard-scorecard/template.doc.mjs@@ -10,4 +10,11 @@ export const doc = {keywords: ['executive summary', 'business review', 'readout', 'reporting'],isReady: true,category: 'Dashboard - Scorecard',+ icons: {+ ArrowDownIcon: 'arrowDown',+ ArrowDownTrayIcon: 'download',+ ArrowRightIcon: 'arrowRight',+ ArrowUpIcon: 'arrowUp',+ StopIcon: 'stop',+ },};diff --git a/packages/cli/assets/templates/pages/dashboard/template.doc.mjs b/packages/cli/assets/templates/pages/dashboard/template.doc.mjsindex 3b89d74991..d279114dba 100644--- a/packages/cli/assets/templates/pages/dashboard/template.doc.mjs+++ b/packages/cli/assets/templates/pages/dashboard/template.doc.mjs@@ -23,4 +23,10 @@ export const doc = {],isReady: true,category: 'Dashboard - Analytics',+ icons: {+ ArrowDownIcon: 'arrowDown',+ ArrowPathIcon: 'refresh',+ ArrowUpIcon: 'arrowUp',+ StopIcon: 'stop',+ },};diff --git a/packages/cli/assets/templates/pages/detail-page/template.doc.mjs b/packages/cli/assets/templates/pages/detail-page/template.doc.mjsindex 7916c01e4f..2570da92b5 100644--- a/packages/cli/assets/templates/pages/detail-page/template.doc.mjs+++ b/packages/cli/assets/templates/pages/detail-page/template.doc.mjs@@ -16,4 +16,14 @@ export const doc = {],isReady: true,category: 'Content - Order Detail',+ icons: {+ ArrowLeftIcon: 'arrowLeft',+ CalendarIcon: 'calendar',+ FlagIcon: 'flag',+ FunnelIcon: 'funnel',+ HandThumbUpIcon: 'thumbsUp',+ HeartIcon: 'heart',+ PencilSquareIcon: 'compose',+ ViewColumnsIcon: 'viewColumns',+ },};diff --git a/packages/cli/assets/templates/pages/documentation-design/template.doc.mjs b/packages/cli/assets/templates/pages/documentation-design/template.doc.mjsindex 39d10eb9c4..a5ea536bff 100644--- a/packages/cli/assets/templates/pages/documentation-design/template.doc.mjs+++ b/packages/cli/assets/templates/pages/documentation-design/template.doc.mjs@@ -6,7 +6,7 @@ export const doc = {name: 'Documentation Design',displayName: 'Documentation Design',description:- 'Reference article alternating prose with live rendered examples: an interactive preview, a property table, paired do and don\'t comparisons, and copyable code blocks.',+ "Reference article alternating prose with live rendered examples: an interactive preview, a property table, paired do and don't comparisons, and copyable code blocks.",keywords: ['documentation','docs',@@ -17,4 +17,9 @@ export const doc = {],isReady: true,category: 'Content - Documentation Design',+ icons: {+ ArrowTopRightOnSquareIcon: 'externalLink',+ ArrowsPointingOutIcon: 'expand',+ PlusIcon: 'add',+ },};diff --git a/packages/cli/assets/templates/pages/documentation-technical/template.doc.mjs b/packages/cli/assets/templates/pages/documentation-technical/template.doc.mjsindex eecebbe370..85d2b67051 100644--- a/packages/cli/assets/templates/pages/documentation-technical/template.doc.mjs+++ b/packages/cli/assets/templates/pages/documentation-technical/template.doc.mjs@@ -17,4 +17,9 @@ export const doc = {],isReady: true,category: 'Content - Documentation Technical',+ icons: {+ ChevronDownIcon: 'chevronDown',+ ClipboardDocumentIcon: 'clipboard',+ SparklesIcon: 'sparkles',+ },};diff --git a/packages/cli/assets/templates/pages/editor/template.doc.mjs b/packages/cli/assets/templates/pages/editor/template.doc.mjsindex bbbbe8f3a4..37226d83f0 100644--- a/packages/cli/assets/templates/pages/editor/template.doc.mjs+++ b/packages/cli/assets/templates/pages/editor/template.doc.mjs@@ -16,4 +16,29 @@ export const doc = {],isReady: true,category: 'Tools - Page Editor',+ icons: {+ AdjustmentsHorizontalIcon: 'adjustments',+ BanknotesIcon: 'money',+ ChatBubbleLeftIcon: 'message',+ ChevronDownIcon: 'chevronDown',+ ChevronUpIcon: 'chevronUp',+ ComputerDesktopIcon: 'desktop',+ CursorArrowRaysIcon: 'click',+ DevicePhoneMobileIcon: 'mobile',+ DocumentTextIcon: 'document',+ EllipsisHorizontalIcon: 'moreHorizontal',+ EyeIcon: 'eye',+ LockClosedIcon: 'lock',+ MegaphoneIcon: 'announcement',+ PhotoIcon: 'image',+ PlayCircleIcon: 'play',+ PlusCircleIcon: 'add',+ ShoppingBagIcon: 'shoppingBag',+ ShoppingCartIcon: 'cart',+ SparklesIcon: 'sparkles',+ Squares2X2Icon: 'gridView',+ TrashIcon: 'delete',+ ViewColumnsIcon: 'viewColumns',+ XMarkIcon: 'close',+ },};diff --git a/packages/cli/assets/templates/pages/file-explorer/template.doc.mjs b/packages/cli/assets/templates/pages/file-explorer/template.doc.mjsindex 7cb7486f29..80f72debbd 100644--- a/packages/cli/assets/templates/pages/file-explorer/template.doc.mjs+++ b/packages/cli/assets/templates/pages/file-explorer/template.doc.mjs@@ -10,4 +10,19 @@ export const doc = {keywords: ['files', 'folders', 'directory', 'tree', 'finder-style navigator'],isReady: true,category: 'Tools - File Explorer',+ icons: {+ AdjustmentsHorizontalIcon: 'adjustments',+ Bars4Icon: 'list',+ ChevronLeftIcon: 'chevronLeft',+ ChevronRightIcon: 'chevronRight',+ DocumentIcon: 'file',+ EllipsisHorizontalIcon: 'moreHorizontal',+ FolderIcon: 'folder',+ MagnifyingGlassIcon: 'search',+ ShareIcon: 'share',+ Squares2X2Icon: 'gridView',+ TableCellsIcon: 'table',+ TagIcon: 'tag',+ ViewColumnsIcon: 'viewColumns',+ },};diff --git a/packages/cli/assets/templates/pages/form-wizard-inline/template.doc.mjs b/packages/cli/assets/templates/pages/form-wizard-inline/template.doc.mjsindex 2b8edf00ac..9df9f663c8 100644--- a/packages/cli/assets/templates/pages/form-wizard-inline/template.doc.mjs+++ b/packages/cli/assets/templates/pages/form-wizard-inline/template.doc.mjs@@ -9,4 +9,5 @@ export const doc = {'Accordion wizard stacking every step in one column: the active step expands in place while finished ones collapse to a single line carrying their result and a way back in. Steps that run themselves expand into a nested stepper that ticks check by check and halts the column where one fails. Best when later steps depend on what earlier ones decided.',isReady: true,category: 'Form - Wizard Inline',+ icons: {BeakerIcon: 'experiment', BoltIcon: 'bolt', CubeIcon: 'package'},};diff --git a/packages/cli/assets/templates/pages/form-wizard-vertical/template.doc.mjs b/packages/cli/assets/templates/pages/form-wizard-vertical/template.doc.mjsindex bb5e9117aa..c08bba3139 100644--- a/packages/cli/assets/templates/pages/form-wizard-vertical/template.doc.mjs+++ b/packages/cli/assets/templates/pages/form-wizard-vertical/template.doc.mjs@@ -9,4 +9,16 @@ export const doc = {'Multi-step wizard with the steps in a fixed left rail that stays visible while the form scrolls, plus a side panel whose guidance follows the focused field. Suits long or unequal steps carrying uploads, previews, and dense review metadata. As width tightens the guidance drops first, then the rail rotates into a horizontal stepper above the form.',isReady: true,category: 'Form - Wizard Vertical',+ icons: {+ BookOpenIcon: 'book',+ BuildingLibraryIcon: 'bank',+ CalendarIcon: 'calendar',+ CheckBadgeIcon: 'checkDouble',+ CurrencyDollarIcon: 'money',+ ExclamationTriangleIcon: 'warning',+ GlobeAltIcon: 'globe',+ LanguageIcon: 'language',+ TagIcon: 'tag',+ UserIcon: 'user',+ },};diff --git a/packages/cli/assets/templates/pages/gallery-hero/template.doc.mjs b/packages/cli/assets/templates/pages/gallery-hero/template.doc.mjsindex a49d952293..5dbc15f70b 100644--- a/packages/cli/assets/templates/pages/gallery-hero/template.doc.mjs+++ b/packages/cli/assets/templates/pages/gallery-hero/template.doc.mjs@@ -17,4 +17,5 @@ export const doc = {],isReady: true,category: 'Gallery - Hero',+ icons: {ArrowRightIcon: 'arrowRight'},};diff --git a/packages/cli/assets/templates/pages/ide/template.doc.mjs b/packages/cli/assets/templates/pages/ide/template.doc.mjsindex 58c29efae9..cf6a1dfd0c 100644--- a/packages/cli/assets/templates/pages/ide/template.doc.mjs+++ b/packages/cli/assets/templates/pages/ide/template.doc.mjs@@ -16,4 +16,9 @@ export const doc = {],isReady: true,category: 'Tools - IDE',+ icons: {+ DocumentTextIcon: 'document',+ FolderIcon: 'folder',+ MagnifyingGlassIcon: 'search',+ },};diff --git a/packages/cli/assets/templates/pages/incident-console/template.doc.mjs b/packages/cli/assets/templates/pages/incident-console/template.doc.mjsindex dfa6762710..a04786a820 100644--- a/packages/cli/assets/templates/pages/incident-console/template.doc.mjs+++ b/packages/cli/assets/templates/pages/incident-console/template.doc.mjs@@ -17,4 +17,5 @@ export const doc = {],isReady: false,category: 'Tools - Incident Console',+ icons: {BellAlertIcon: 'notificationActive', PlusIcon: 'add'},};diff --git a/packages/cli/assets/templates/pages/kanban-board/template.doc.mjs b/packages/cli/assets/templates/pages/kanban-board/template.doc.mjsindex 2ea42925ca..1918a3623b 100644--- a/packages/cli/assets/templates/pages/kanban-board/template.doc.mjs+++ b/packages/cli/assets/templates/pages/kanban-board/template.doc.mjs@@ -18,4 +18,15 @@ export const doc = {],isReady: true,category: 'Tools - Kanban Board',+ icons: {+ ArrowPathIcon: 'refresh',+ ArrowsUpDownIcon: 'arrowsUpDown',+ CheckCircleIcon: 'success',+ ClipboardDocumentCheckIcon: 'clipboard',+ FunnelIcon: 'funnel',+ InboxIcon: 'inbox',+ InformationCircleIcon: 'info',+ MagnifyingGlassIcon: 'search',+ PlusIcon: 'add',+ },};diff --git a/packages/cli/assets/templates/pages/library/template.doc.mjs b/packages/cli/assets/templates/pages/library/template.doc.mjsindex 27e11c98ac..31999d616b 100644--- a/packages/cli/assets/templates/pages/library/template.doc.mjs+++ b/packages/cli/assets/templates/pages/library/template.doc.mjs@@ -22,4 +22,5 @@ export const doc = {],isReady: true,category: 'Content - Card Grid',+ icons: {MagnifyingGlassIcon: 'search'},};diff --git a/packages/cli/assets/templates/pages/login-card/template.doc.mjs b/packages/cli/assets/templates/pages/login-card/template.doc.mjsindex 4f8fb15e50..b2aeaba926 100644--- a/packages/cli/assets/templates/pages/login-card/template.doc.mjs+++ b/packages/cli/assets/templates/pages/login-card/template.doc.mjs@@ -18,4 +18,5 @@ export const doc = {],isReady: true,category: 'Login - Card',+ icons: {CubeIcon: 'package'},};diff --git a/packages/cli/assets/templates/pages/login-split/template.doc.mjs b/packages/cli/assets/templates/pages/login-split/template.doc.mjsindex 795cd25f46..5b2ec29dd4 100644--- a/packages/cli/assets/templates/pages/login-split/template.doc.mjs+++ b/packages/cli/assets/templates/pages/login-split/template.doc.mjs@@ -17,4 +17,5 @@ export const doc = {],isReady: true,category: 'Login - Split',+ icons: {CheckCircleIcon: 'success', SquaresPlusIcon: 'apps'},};diff --git a/packages/cli/assets/templates/pages/login-sso/template.doc.mjs b/packages/cli/assets/templates/pages/login-sso/template.doc.mjsindex afa4ad6a93..dc7f58b6ce 100644--- a/packages/cli/assets/templates/pages/login-sso/template.doc.mjs+++ b/packages/cli/assets/templates/pages/login-sso/template.doc.mjs@@ -17,4 +17,5 @@ export const doc = {],isReady: true,category: 'Login - SSO',+ icons: {ShieldCheckIcon: 'shield'},};diff --git a/packages/cli/assets/templates/pages/login/template.doc.mjs b/packages/cli/assets/templates/pages/login/template.doc.mjsindex 875dfd060d..2a94008eff 100644--- a/packages/cli/assets/templates/pages/login/template.doc.mjs+++ b/packages/cli/assets/templates/pages/login/template.doc.mjs@@ -18,4 +18,5 @@ export const doc = {isReady: true,isHiddenFromOverview: true,category: 'Login - Basic',+ icons: {CubeIcon: 'package'},};diff --git a/packages/cli/assets/templates/pages/messaging-shell/template.doc.mjs b/packages/cli/assets/templates/pages/messaging-shell/template.doc.mjsindex 1461b2991b..4fc82eb734 100644--- a/packages/cli/assets/templates/pages/messaging-shell/template.doc.mjs+++ b/packages/cli/assets/templates/pages/messaging-shell/template.doc.mjs@@ -18,4 +18,17 @@ export const doc = {],isReady: false,category: 'Shell - Messaging',+ icons: {+ BellIcon: 'notification',+ BookmarkIcon: 'bookmark',+ ChatBubbleLeftRightIcon: 'conversation',+ Cog6ToothIcon: 'settings',+ HashtagIcon: 'tag',+ HomeIcon: 'home',+ InboxIcon: 'inbox',+ MagnifyingGlassIcon: 'search',+ PencilSquareIcon: 'compose',+ UserGroupIcon: 'users',+ XMarkIcon: 'close',+ },};diff --git a/packages/cli/assets/templates/pages/payment-form/template.doc.mjs b/packages/cli/assets/templates/pages/payment-form/template.doc.mjsindex 17c9eb04d0..49fe3d846b 100644--- a/packages/cli/assets/templates/pages/payment-form/template.doc.mjs+++ b/packages/cli/assets/templates/pages/payment-form/template.doc.mjs@@ -10,4 +10,10 @@ export const doc = {keywords: ['checkout', 'payment', 'billing', 'cart', 'buyer', 'purchase'],isReady: true,category: 'Form - Checkout',+ icons: {+ CheckCircleIcon: 'success',+ LockClosedIcon: 'lock',+ ShieldCheckIcon: 'shield',+ TruckIcon: 'shipping',+ },};diff --git a/packages/cli/assets/templates/pages/product-detail/template.doc.mjs b/packages/cli/assets/templates/pages/product-detail/template.doc.mjsindex 8fe28b68d1..15cfbabc2e 100644--- a/packages/cli/assets/templates/pages/product-detail/template.doc.mjs+++ b/packages/cli/assets/templates/pages/product-detail/template.doc.mjs@@ -16,4 +16,5 @@ export const doc = {],isReady: true,category: 'Content - Product Detail',+ icons: {MinusIcon: 'remove', PlusIcon: 'add', StarIcon: 'star'},};diff --git a/packages/cli/assets/templates/pages/product-gallery/template.doc.mjs b/packages/cli/assets/templates/pages/product-gallery/template.doc.mjsindex 70299618b9..8e0b073e3c 100644--- a/packages/cli/assets/templates/pages/product-gallery/template.doc.mjs+++ b/packages/cli/assets/templates/pages/product-gallery/template.doc.mjs@@ -17,4 +17,5 @@ export const doc = {type: 'page',isReady: true,category: 'Gallery - Product',+ icons: {ArrowRightIcon: 'arrowRight'},};diff --git a/packages/cli/assets/templates/pages/settings-dialog/template.doc.mjs b/packages/cli/assets/templates/pages/settings-dialog/template.doc.mjsindex c4690f01a2..b5e88233d8 100644--- a/packages/cli/assets/templates/pages/settings-dialog/template.doc.mjs+++ b/packages/cli/assets/templates/pages/settings-dialog/template.doc.mjs@@ -16,4 +16,53 @@ export const doc = {],isReady: true,category: 'Settings - Dialog',+ icons: {+ ArrowDownOnSquareIcon: 'save',+ ArrowDownTrayIcon: 'download',+ ArrowUturnLeftIcon: 'undo',+ AtSymbolIcon: 'mention',+ Bars3Icon: 'menu',+ BeakerIcon: 'experiment',+ BellIcon: 'notification',+ BriefcaseIcon: 'work',+ CalendarDaysIcon: 'calendar',+ ChatBubbleLeftRightIcon: 'conversation',+ ChevronRightIcon: 'chevronRight',+ ClockIcon: 'clock',+ CodeBracketIcon: 'code',+ Cog6ToothIcon: 'settings',+ CommandLineIcon: 'code',+ ComputerDesktopIcon: 'desktop',+ CreditCardIcon: 'creditCard',+ CubeIcon: 'package',+ DevicePhoneMobileIcon: 'mobile',+ DocumentMagnifyingGlassIcon: 'search',+ DocumentTextIcon: 'document',+ EnvelopeIcon: 'mail',+ EyeIcon: 'eye',+ FolderIcon: 'folder',+ GlobeAltIcon: 'globe',+ HandRaisedIcon: 'raiseHand',+ KeyIcon: 'key',+ LanguageIcon: 'language',+ LinkIcon: 'link',+ LockClosedIcon: 'lock',+ MagnifyingGlassIcon: 'search',+ MapPinIcon: 'location',+ MoonIcon: 'moon',+ PencilSquareIcon: 'compose',+ QuestionMarkCircleIcon: 'info',+ ReceiptPercentIcon: 'discount',+ ShieldCheckIcon: 'shield',+ SignalIcon: 'activity',+ SparklesIcon: 'sparkles',+ SpeakerWaveIcon: 'audio',+ SunIcon: 'sun',+ SwatchIcon: 'swatch',+ TagIcon: 'tag',+ TrashIcon: 'delete',+ UserCircleIcon: 'userCircle',+ UserIcon: 'user',+ UsersIcon: 'users',+ },};diff --git a/packages/cli/assets/templates/pages/settings-sidebar/template.doc.mjs b/packages/cli/assets/templates/pages/settings-sidebar/template.doc.mjsindex a0d0829ddf..8c74772b85 100644--- a/packages/cli/assets/templates/pages/settings-sidebar/template.doc.mjs+++ b/packages/cli/assets/templates/pages/settings-sidebar/template.doc.mjs@@ -16,4 +16,20 @@ export const doc = {],isReady: true,category: 'Settings - Panels',+ icons: {+ ArrowLeftIcon: 'arrowLeft',+ BellIcon: 'notification',+ BriefcaseIcon: 'work',+ ChevronRightIcon: 'chevronRight',+ ComputerDesktopIcon: 'desktop',+ CreditCardIcon: 'creditCard',+ DocumentTextIcon: 'document',+ GlobeAltIcon: 'globe',+ LockClosedIcon: 'lock',+ PencilSquareIcon: 'compose',+ ShareIcon: 'share',+ ShieldCheckIcon: 'shield',+ UserIcon: 'user',+ WrenchScrewdriverIcon: 'wrench',+ },};diff --git a/packages/cli/assets/templates/pages/settings/template.doc.mjs b/packages/cli/assets/templates/pages/settings/template.doc.mjsindex 0bfe436c87..4defa575a3 100644--- a/packages/cli/assets/templates/pages/settings/template.doc.mjs+++ b/packages/cli/assets/templates/pages/settings/template.doc.mjs@@ -10,4 +10,5 @@ export const doc = {keywords: ['settings', 'preferences', 'configuration', 'options', 'account'],isReady: true,category: 'Settings - Form',+ icons: {MagnifyingGlassIcon: 'search'},};diff --git a/packages/cli/assets/templates/pages/shell-nav/template.doc.mjs b/packages/cli/assets/templates/pages/shell-nav/template.doc.mjsindex 5531e064d9..be102cf257 100644--- a/packages/cli/assets/templates/pages/shell-nav/template.doc.mjs+++ b/packages/cli/assets/templates/pages/shell-nav/template.doc.mjs@@ -17,4 +17,10 @@ export const doc = {],isReady: true,category: 'Shell - Top Nav + Left Sidebar',+ icons: {+ DocumentTextIcon: 'document',+ FolderIcon: 'folder',+ MagnifyingGlassIcon: 'search',+ PlayIcon: 'play',+ },};diff --git a/packages/cli/assets/templates/pages/shell-side-nav/template.doc.mjs b/packages/cli/assets/templates/pages/shell-side-nav/template.doc.mjsindex 3909330c42..b314fdf6a9 100644--- a/packages/cli/assets/templates/pages/shell-side-nav/template.doc.mjs+++ b/packages/cli/assets/templates/pages/shell-side-nav/template.doc.mjs@@ -21,4 +21,15 @@ export const doc = {],isReady: true,category: 'Shell - Left Sidebar',+ icons: {+ BookOpenIcon: 'book',+ BuildingOffice2Icon: 'building',+ CodeBracketIcon: 'code',+ Cog6ToothIcon: 'settings',+ MagnifyingGlassIcon: 'search',+ PlusIcon: 'add',+ SparklesIcon: 'sparkles',+ UserCircleIcon: 'userCircle',+ UserIcon: 'user',+ },};diff --git a/packages/cli/assets/templates/pages/shell-top-nav/template.doc.mjs b/packages/cli/assets/templates/pages/shell-top-nav/template.doc.mjsindex 198de5af90..d867230d15 100644--- a/packages/cli/assets/templates/pages/shell-top-nav/template.doc.mjs+++ b/packages/cli/assets/templates/pages/shell-top-nav/template.doc.mjs@@ -18,4 +18,20 @@ export const doc = {],isReady: true,category: 'Shell - Top Nav',+ icons: {+ BoltIcon: 'bolt',+ FaceSmileIcon: 'emoji',+ GlobeAltIcon: 'globe',+ HomeModernIcon: 'home',+ MagnifyingGlassIcon: 'search',+ MoonIcon: 'moon',+ ReceiptPercentIcon: 'discount',+ ShoppingBagIcon: 'shoppingBag',+ ShoppingCartIcon: 'cart',+ SparklesIcon: 'sparkles',+ StarIcon: 'star',+ SunIcon: 'sun',+ SwatchIcon: 'swatch',+ TagIcon: 'tag',+ },};diff --git a/packages/cli/assets/templates/pages/table-collapsible/template.doc.mjs b/packages/cli/assets/templates/pages/table-collapsible/template.doc.mjsindex ce34391830..8d0f86e7f6 100644--- a/packages/cli/assets/templates/pages/table-collapsible/template.doc.mjs+++ b/packages/cli/assets/templates/pages/table-collapsible/template.doc.mjs@@ -9,4 +9,9 @@ export const doc = {'Several tables on one page, each in a collapsible card with its own columns — for groups that do not share a schema, where one table would stand full of empty cells. One time range drives them all, and rows expand into a history chart. Accounts, integrations, sections, sort, expand, or collapse.',isReady: true,category: 'Table - Grouped',+ icons: {+ BuildingLibraryIcon: 'bank',+ CreditCardIcon: 'creditCard',+ PresentationChartLineIcon: 'activity',+ },};diff --git a/packages/cli/assets/templates/pages/table-comparison/template.doc.mjs b/packages/cli/assets/templates/pages/table-comparison/template.doc.mjsindex ac1f5c4c02..ca6aa56cfe 100644--- a/packages/cli/assets/templates/pages/table-comparison/template.doc.mjs+++ b/packages/cli/assets/templates/pages/table-comparison/template.doc.mjs@@ -9,4 +9,16 @@ export const doc = {'Transposed matrix that puts candidates in the columns and criteria in grouped rows, with a pinned label column that survives horizontal scroll, columns you can swap or add, and best-in-row marks you can toggle. Compare, comparison, matrix, spec sheet, feature grid, pricing table, benchmark, frozen column, sticky column, or side-by-side.',isReady: true,category: 'Table - Comparison',+ icons: {+ AudioLines: 'audio',+ Box: 'package',+ CircleCheck: 'success',+ CircleX: 'error',+ FileText: 'document',+ Image: 'image',+ Plus: 'add',+ Sparkles: 'sparkles',+ Video: 'video',+ Zap: 'bolt',+ },};diff --git a/packages/cli/assets/templates/pages/table-filter/template.doc.mjs b/packages/cli/assets/templates/pages/table-filter/template.doc.mjsindex 6ee2022887..f1229b0f9f 100644--- a/packages/cli/assets/templates/pages/table-filter/template.doc.mjs+++ b/packages/cli/assets/templates/pages/table-filter/template.doc.mjs@@ -28,4 +28,23 @@ export const doc = {],isReady: true,category: 'Table - Filtering',+ icons: {+ Bookmark: 'bookmark',+ BookmarkPlus: 'bookmark',+ Calendar: 'calendar',+ ChevronDown: 'chevronDown',+ CircleX: 'error',+ Columns3: 'viewColumns',+ GripVertical: 'drag',+ Image: 'image',+ Pencil: 'edit',+ Pin: 'pin',+ Plus: 'add',+ Search: 'search',+ SlidersHorizontal: 'adjustments',+ Table: 'table',+ Table2: 'table',+ UserPlus: 'userAdd',+ X: 'close',+ },};diff --git a/packages/cli/assets/templates/pages/table-grouped/template.doc.mjs b/packages/cli/assets/templates/pages/table-grouped/template.doc.mjsindex 4564e9ce8b..c5bf57939b 100644--- a/packages/cli/assets/templates/pages/table-grouped/template.doc.mjs+++ b/packages/cli/assets/templates/pages/table-grouped/template.doc.mjs@@ -22,4 +22,17 @@ export const doc = {],isReady: true,category: 'Table - Grouped',+ icons: {+ ArrowRightIcon: 'arrowRight',+ ChartBarIcon: 'chart',+ ChevronDownIcon: 'chevronDown',+ ChevronRightIcon: 'chevronRight',+ DocumentDuplicateIcon: 'copy',+ EllipsisHorizontalIcon: 'moreHorizontal',+ PencilIcon: 'edit',+ TagIcon: 'tag',+ TrashIcon: 'delete',+ UserIcon: 'user',+ XMarkIcon: 'close',+ },};diff --git a/packages/cli/assets/templates/pages/table-inbox/template.doc.mjs b/packages/cli/assets/templates/pages/table-inbox/template.doc.mjsindex c5e3eb1030..a7081a4a84 100644--- a/packages/cli/assets/templates/pages/table-inbox/template.doc.mjs+++ b/packages/cli/assets/templates/pages/table-inbox/template.doc.mjs@@ -26,4 +26,21 @@ export const doc = {],isReady: true,category: 'Table - Split Pane',+ icons: {+ ArchiveBoxIcon: 'archive',+ ArrowLeftIcon: 'arrowLeft',+ ArrowPathIcon: 'refresh',+ ArrowUturnLeftIcon: 'undo',+ FaceSmileIcon: 'emoji',+ FolderArrowDownIcon: 'folder',+ InboxIcon: 'inbox',+ LinkIcon: 'link',+ PaperAirplaneIcon: 'send',+ PaperClipIcon: 'attach',+ PencilSquareIcon: 'compose',+ PhotoIcon: 'image',+ TrashIcon: 'delete',+ UsersIcon: 'users',+ XMarkIcon: 'close',+ },};diff --git a/packages/cli/assets/templates/pages/table-page/template.doc.mjs b/packages/cli/assets/templates/pages/table-page/template.doc.mjsindex 5f077a8a6a..589f98c20b 100644--- a/packages/cli/assets/templates/pages/table-page/template.doc.mjs+++ b/packages/cli/assets/templates/pages/table-page/template.doc.mjs@@ -28,4 +28,5 @@ export const doc = {],isReady: true,category: 'Table - Basic',+ icons: {ArrowDownTrayIcon: 'download', MagnifyingGlassIcon: 'search'},};diff --git a/packages/cli/assets/templates/pages/table-tree/template.doc.mjs b/packages/cli/assets/templates/pages/table-tree/template.doc.mjsindex 62e3cd18c6..62a4a9c77d 100644--- a/packages/cli/assets/templates/pages/table-tree/template.doc.mjs+++ b/packages/cli/assets/templates/pages/table-tree/template.doc.mjs@@ -22,4 +22,16 @@ export const doc = {],isReady: true,category: 'Table - Tree/Hierarchical List',+ icons: {+ BookOpen: 'book',+ ChartColumn: 'chart',+ Code: 'code',+ Eye: 'eye',+ File: 'file',+ Folder: 'folder',+ Search: 'search',+ ShieldCheck: 'shield',+ Star: 'star',+ Tag: 'tag',+ },};diff --git a/packages/cli/assets/templates/pages/theme-showcase/template.doc.mjs b/packages/cli/assets/templates/pages/theme-showcase/template.doc.mjsindex 90a799befb..6aebb5c904 100644--- a/packages/cli/assets/templates/pages/theme-showcase/template.doc.mjs+++ b/packages/cli/assets/templates/pages/theme-showcase/template.doc.mjs@@ -21,4 +21,23 @@ export const doc = {// No `category` — it's hidden from the overview gallery (the only consumer// of `category`), and 'Showcase' isn't part of the TemplateCategory taxonomy.isHiddenFromOverview: true,+ icons: {+ Banknote: 'money',+ CreditCard: 'creditCard',+ Download: 'download',+ Folder: 'folder',+ LayoutGrid: 'apps',+ List: 'list',+ Lock: 'lock',+ MapPin: 'location',+ Mic: 'microphone',+ Plus: 'add',+ Search: 'search',+ ShoppingBag: 'shoppingBag',+ Smartphone: 'mobile',+ Tag: 'tag',+ User: 'user',+ Wallet: 'money',+ X: 'close',+ },};diff --git a/packages/cli/assets/templates/pages/work-item-detail/template.doc.mjs b/packages/cli/assets/templates/pages/work-item-detail/template.doc.mjsindex c86cb50975..5aecef2f3f 100644--- a/packages/cli/assets/templates/pages/work-item-detail/template.doc.mjs+++ b/packages/cli/assets/templates/pages/work-item-detail/template.doc.mjs@@ -19,4 +19,17 @@ export const doc = {],isReady: true,category: 'Content - Work Item Detail',+ icons: {+ ArrowLeftIcon: 'arrowLeft',+ BellIcon: 'notification',+ DocumentTextIcon: 'document',+ EyeIcon: 'eye',+ InformationCircleIcon: 'info',+ LinkIcon: 'link',+ PencilIcon: 'edit',+ PhotoIcon: 'image',+ ShareIcon: 'share',+ TrashIcon: 'delete',+ ViewColumnsIcon: 'viewColumns',+ },};diff --git a/packages/cli/authoring/config/config.doc.mjs b/packages/cli/authoring/config/config.doc.mjsindex e7bce3a084..c8714e801a 100644--- a/packages/cli/authoring/config/config.doc.mjs+++ b/packages/cli/authoring/config/config.doc.mjs@@ -75,6 +75,14 @@ export const doc = {type: '{ xle?: { components?: Record<string, XleComponent> } }',description: 'Unstable features; may change without a breaking bump.',fields: [+ {+ name: 'experimental.iconSet',+ type: 'string',+ stability: 'experimental',+ description:+ "Experimental: may change or be removed in a patch release. The project's icon set, by set name or as `<package>/<set>`. It is the opt-in: copied templates use its icons, and `astryx discover` and `astryx doctor` report icon sets, only when it is set. `astryx experimental icon` ranks its icons first; without it, the only installed set is the project's there. `astryx search` never returns icons.",+ example: "'@acme/outline-icons/outline'",+ },{name: 'experimental.xle.components',type: 'Record<string, XleComponent>',diff --git a/packages/cli/authoring/config/parse.mjs b/packages/cli/authoring/config/parse.mjsindex f247f74aad..80145807bb 100644--- a/packages/cli/authoring/config/parse.mjs+++ b/packages/cli/authoring/config/parse.mjs@@ -103,6 +103,7 @@ const configSchema = z}).strict().optional(),+ iconSet: z.string().min(1).optional(),}).strict().optional(),diff --git a/packages/cli/authoring/config/type.ts b/packages/cli/authoring/config/type.tsindex bf718185b5..8558651a8c 100644--- a/packages/cli/authoring/config/type.ts+++ b/packages/cli/authoring/config/type.ts@@ -122,5 +122,13 @@ export interface AstryxConfig {*/components?: Record<string, XleComponent>;};+ /**+ * Experimental icon sets (spec:AST-084): the project's icon set, a set+ * name (`"outline"`) or `"<package>/<set>"`, and the opt-in. Copied+ * templates use its icons, and discover and Doctor report icon sets, only+ * when it is set.+ * @experimental May change or be removed in a patch release.+ */+ iconSet?: string;};}diff --git a/packages/cli/authoring/discover/parse.mjs b/packages/cli/authoring/discover/parse.mjsindex c51af0bbf9..75aac8f49b 100644--- a/packages/cli/authoring/discover/parse.mjs+++ b/packages/cli/authoring/discover/parse.mjs@@ -21,6 +21,7 @@ export const DISCOVER_KINDS = /** @type {const} */ (['theme','codemod','agent-doc',+ 'icon-set',]);const text = (/** @type {number} */ max) => z.string().min(1).max(max);@@ -31,6 +32,8 @@ const contributionSchema = z.object({title: z.string().max(512).optional(),summary: z.string().max(4096).optional(),keywords: z.array(z.string().max(128)).max(64).optional(),+ iconCount: z.number().int().min(0).optional(),+ definitions: z.array(z.string().max(128)).max(2048).optional(),});const versionSchema = z.object({@@ -74,16 +77,62 @@ function newestFirst(a, b) {return b.version.localeCompare(a.version, 'en', {numeric: true});}+/** Item fields read only for the experimental `icon-set` kind. */+const ICON_SET_FIELDS = /** @type {const} */ (['iconCount', 'definitions']);++/**+ * The catalog with every icon-set-only field taken off its items, so a project+ * that has not opted into icon sets checks a catalog exactly as a CLI without+ * them does: those fields are unknown, so dropped unread. Anything not shaped+ * like a catalog is returned as is, for the schema to report.+ * @param {unknown} value+ * @returns {unknown}+ */+function withoutIconSetFields(value) {+ if (value == null || typeof value !== 'object') return value;+ const catalog = /** @type {{packages?: unknown}} */ (value);+ if (!Array.isArray(catalog.packages)) return value;+ return {+ ...catalog,+ packages: catalog.packages.map(pkg => {+ if (pkg == null || typeof pkg !== 'object') return pkg;+ const {contributions} = /** @type {{contributions?: unknown}} */ (pkg);+ if (!Array.isArray(contributions)) return pkg;+ return {+ ...pkg,+ contributions: contributions.map(item => {+ if (item == null || typeof item !== 'object') return item;+ const copy = {...item};+ for (const field of ICON_SET_FIELDS) delete copy[field];+ return copy;+ }),+ };+ }),+ };+}+/*** Check a catalog a discover source returned. Throws an Error naming the first- * problem. Items of a kind this CLI does not know are dropped, and versions are+ * problem. Items of a kind this CLI does not read are dropped, and versions are* put newest first whatever order the source used.*+ * The experimental `icon-set` kind and its item fields (`iconCount`,+ * `definitions`) are read only with `iconSets` (spec:AST-084). Without it they+ * are unknown: the fields are taken off before the check and the items are+ * dropped after it, exactly as for any kind or field this CLI does not know+ * (spec:AST-051 FR7).+ ** @param {unknown} value* @param {string} [label]+ * @param {{iconSets?: boolean}} [options] `iconSets`: the project opts into+ * icon sets (`experimental.iconSet`)* @returns {import('./type.js').DiscoverCatalog}*/-export function parseDiscoverCatalog(value, label = 'discover source') {+export function parseDiscoverCatalog(+ value,+ label = 'discover source',+ {iconSets = false} = {},+) {const version =value != null && typeof value === 'object'? /** @type {{schemaVersion?: unknown}} */ (value).schemaVersion@@ -93,7 +142,9 @@ export function parseDiscoverCatalog(value, label = 'discover source') {`${label} returned schemaVersion ${String(version)}; this CLI reads schemaVersion 1`,);}- const parsed = catalogSchema.safeParse(value);+ const parsed = catalogSchema.safeParse(+ iconSets ? value : withoutIconSetFields(value),+ );if (!parsed.success) {const issue = parsed.error.issues[0];const where = issue?.path.length ? ` at ${issue.path.join('.')}` : '';@@ -101,7 +152,9 @@ export function parseDiscoverCatalog(value, label = 'discover source') {`${label} returned an invalid catalog${where}: ${issue?.message}`,);}- const known = /** @type {readonly string[]} */ (DISCOVER_KINDS);+ const known = /** @type {readonly string[]} */ (DISCOVER_KINDS).filter(+ kind => iconSets || kind !== 'icon-set',+ );return /** @type {import('./type.js').DiscoverCatalog} */ ({...parsed.data,packages: parsed.data.packages.map(pkg => ({diff --git a/packages/cli/authoring/discover/parse.test.mjs b/packages/cli/authoring/discover/parse.test.mjsindex f30578a3eb..16b9f9113b 100644--- a/packages/cli/authoring/discover/parse.test.mjs+++ b/packages/cli/authoring/discover/parse.test.mjs@@ -50,6 +50,39 @@ describe('parseDiscoverCatalog', () => {expect(parsed).not.toHaveProperty('cursor');});+ it('keeps an icon-set entry with its icon count and definitions when the project opts in', () => {+ const value = catalog();+ const set = {+ kind: 'icon-set',+ name: 'outline',+ title: 'Outline',+ iconCount: 120,+ definitions: ['close', 'search'],+ };+ value.packages[0].contributions.push(/** @type {any} */ (set));+ expect(+ parseDiscoverCatalog(value, 'source', {iconSets: true}).packages[0]+ .contributions[1],+ ).toEqual(set);+ expect(DISCOVER_KINDS).toContain('icon-set');+ const bad = catalog();+ bad.packages[0].contributions.push(+ /** @type {any} */ ({kind: 'icon-set', name: 'x', iconCount: -1}),+ );+ expect(() => parseDiscoverCatalog(bad, 'source', {iconSets: true})).toThrow(+ /iconCount/,+ );+ });++ it('without the opt-in, ignores icon-set entries and fields as unknown, even malformed ones', () => {+ const value = catalog();+ value.packages[0].contributions.push(+ /** @type {any} */ ({kind: 'icon-set', name: 'x', iconCount: -1}),+ );+ /** @type {any} */ (value.packages[0].contributions[0]).definitions = [7];+ expect(parseDiscoverCatalog(value)).toEqual(catalog());+ });+it('drops items of a kind it does not know', () => {const value = catalog();value.packages[0].contributions.push({kind: 'widget', name: 'Spinner'});@@ -106,6 +139,7 @@ describe('parseDiscoverCatalog', () => {'theme','codemod','agent-doc',+ 'icon-set',]);});});diff --git a/packages/cli/authoring/discover/type.ts b/packages/cli/authoring/discover/type.tsindex 352ffe30b6..04ddcdcf62 100644--- a/packages/cli/authoring/discover/type.ts+++ b/packages/cli/authoring/discover/type.ts@@ -13,19 +13,39 @@/** Kinds of item a package can add. */export type DiscoverKind =- 'component' | 'template' | 'doc' | 'theme' | 'codemod' | 'agent-doc';+ | 'component'+ | 'template'+ | 'doc'+ | 'theme'+ | 'codemod'+ | 'agent-doc'+ /**+ * An icon set, read only in a project that sets `experimental.iconSet`.+ * @experimental May change or be removed in a patch release.+ */+ | 'icon-set';/** One item a package version adds. */export interface DiscoverContribution {kind: DiscoverKind;/*** The name the CLI uses for it: a component name, template id, doc topic,- * theme slug, or codemod id.+ * theme slug, codemod id, or icon set name.*/name: string;title?: string;summary?: string;keywords?: string[];+ /**+ * For an icon set: how many icons it has.+ * @experimental May change or be removed in a patch release.+ */+ iconCount?: number;+ /**+ * For an icon set: the icon definitions its `map` covers.+ * @experimental May change or be removed in a patch release.+ */+ definitions?: string[];}/** One published version of a package. */diff --git a/packages/cli/authoring/doctypes/_schema.mjs b/packages/cli/authoring/doctypes/_schema.mjsindex 1a17ce4b53..e66fc698a8 100644--- a/packages/cli/authoring/doctypes/_schema.mjs+++ b/packages/cli/authoring/doctypes/_schema.mjs@@ -39,6 +39,7 @@ export const AuthoredDocKindSchema = z.enum(['command','enum','namespace',+ 'icon-definition',]);/**@@ -59,6 +60,7 @@ export const AuthoredDocGraphFields = {.optional(),aliases: z.array(nonEmptyString).optional(),audience: z.enum(['public', 'internal']).optional(),+ stability: z.literal('experimental').optional(),};const _AuthoredDocGraphSchema = z.object(AuthoredDocGraphFields).strict();@@ -486,6 +488,7 @@ const SchemaFieldSchema =default: z.string().optional(),example: z.string().optional(),deprecated: z.string().optional(),+ stability: z.literal('experimental').optional(),fields: z.array(SchemaFieldSchema).optional(),}).passthrough(),@@ -608,6 +611,7 @@ export const EnumDocKindSchema = zvalue: z.string().min(1, 'member value is required'),description: z.string(),deprecated: z.string().optional(),+ stability: z.literal('experimental').optional(),}).passthrough(),),@@ -657,6 +661,7 @@ export const NamespaceDocKindSchema = z.object({group: nonEmptyString,kinds: z.array(AuthoredDocKindSchema).min(1).optional(),+ packages: z.literal('all').optional(),}).strict(),into: nonEmptyString,diff --git a/packages/cli/authoring/doctypes/base/graph-fields.doc.mjs b/packages/cli/authoring/doctypes/base/graph-fields.doc.mjsindex 6de73a717c..0942b9184f 100644--- a/packages/cli/authoring/doctypes/base/graph-fields.doc.mjs+++ b/packages/cli/authoring/doctypes/base/graph-fields.doc.mjs@@ -12,7 +12,7 @@ export const doc = {displayName: 'Authored doc graph fields',namespace: 'authoring',description:- "Fields every authored doc kind can declare for the docs tree: `placement`, plus two reserved fields, `aliases` and `audience`. The docs tree reads `placement` for every guide and namespace doc, the CLI's and each integration's. Nothing reads `aliases` or `audience` today: a reference topic that sets one fails to load, placed in the docs tree or not, and other doc kinds accept them and ignore them.",+ "Fields every authored doc kind can declare for the docs tree: `placement`, `stability`, and two reserved fields, `aliases` and `audience`. The docs tree reads `placement` for every guide and namespace doc, the CLI's and each integration's. Nothing reads `aliases` or `audience` today: a reference topic that sets one fails to load, placed in the docs tree or not, and other doc kinds accept them and ignore them.",appliesTo:"Every authored doc kind's .doc.mjs object. Theme descriptors take none of these fields.",fields: [@@ -56,6 +56,12 @@ export const doc = {"Reserved: which docs bundle includes this doc ('public' when omitted). Nothing reads it today, and a topic that sets it fails to load.",default: "'public'",},+ {+ name: 'stability',+ type: "'experimental'",+ description:+ "Marks the doc of an experimental surface: one whose shape can still change, or disappear, in any patch release. A command's help shows it as `[experimental]`. The doc's own text still says so. Omit it for a stable surface.",+ },],notes: [{diff --git a/packages/cli/authoring/doctypes/base/type.ts b/packages/cli/authoring/doctypes/base/type.tsindex d215962555..1e0d210c28 100644--- a/packages/cli/authoring/doctypes/base/type.ts+++ b/packages/cli/authoring/doctypes/base/type.ts@@ -14,7 +14,12 @@ export type AuthoredDocKind =| 'schema'| 'command'| 'enum'- | 'namespace';+ | 'namespace'+ /**+ * An icon definition (spec:AST-084 FR4).+ * @experimental May change or be removed in a patch release.+ */+ | 'icon-definition';/** Visibility of an authored doc in a compiled audience-specific bundle. */export type DocAudience = 'public' | 'internal';@@ -45,6 +50,10 @@ export interface AuthoredDocGraphFields {/** Reserved: docs bundle audience; omit for public docs. Nothing reads it* yet. */audience?: DocAudience;+ /** Set on the doc of an experimental surface (spec:AST-017 FR21, FR27),+ * whose text then says it may change or be removed in a patch release. A+ * command's help shows it as `[experimental]`. Omit for stable surfaces. */+ stability?: 'experimental';}/**diff --git a/packages/cli/authoring/doctypes/doc-stability-types.test.mjs b/packages/cli/authoring/doctypes/doc-stability-types.test.mjsnew file mode 100644index 0000000000..f3ff626d86--- /dev/null+++ b/packages/cli/authoring/doctypes/doc-stability-types.test.mjs@@ -0,0 +1,91 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Which public doc types accept `stability: 'experimental'`+ * (spec:AST-084 FR18): every one the authoring entry exports except `ThemeDoc`+ * and `IconSetDoc`, plus the schema field and enum member types. Read from+ * the published declarations with the TypeScript checker, so a new doc type+ * fails here until it carries the field or joins the exceptions.+ *+ * @input packages/cli/authoring/index.d.ts and the doc-type declarations+ * @output assertions only+ * @position authoring/doctypes — beside the types it reads+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import ts from 'typescript';+import {describe, expect, it} from 'vitest';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const ENTRY = path.resolve(HERE, '..', 'index.d.ts');+/** Doc types FR18 excepts; the data file is not a doc. */+const EXCEPT = new Set(['ThemeDoc', 'IconSetDoc', 'IconSetData']);+/** Types FR18 names beside the docs: a schema field and an enum value. */+const MEMBER_TYPES = ['SchemaFieldDoc', 'EnumMemberDoc'];++describe('stability on the public doc types', () => {+ it('every doc type the authoring entry exports accepts it, except ThemeDoc and IconSetDoc', () => {+ const program = ts.createProgram([ENTRY], {+ noEmit: true,+ allowJs: true,+ skipLibCheck: true,+ module: ts.ModuleKind.NodeNext,+ moduleResolution: ts.ModuleResolutionKind.NodeNext,+ target: ts.ScriptTarget.ES2022,+ });+ const checker = program.getTypeChecker();+ const entry = /** @type {ts.SourceFile} */ (program.getSourceFile(ENTRY));+ const module = /** @type {ts.Symbol} */ (+ checker.getSymbolAtLocation(entry)+ );+ /** @type {Map<string, ts.Type>} */+ const exported = new Map();+ for (const symbol of checker.getExportsOfModule(module)) {+ const target =+ symbol.flags & ts.SymbolFlags.Alias+ ? checker.getAliasedSymbol(symbol)+ : symbol;+ if (+ target.flags &+ (ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias)+ ) {+ exported.set(symbol.getName(), checker.getDeclaredTypeOfSymbol(target));+ }+ }+ /** @param {ts.Type} type */+ const accepts = type => {+ const members = type.isUnion() ? type.types : [type];+ return members.every(member => {+ const property = checker.getPropertyOfType(member, 'stability');+ return (+ property != null &&+ checker.typeToString(checker.getTypeOfSymbol(property)) ===+ '"experimental" | undefined'+ );+ });+ };+ // The doc file types: each the entry exports on its own line from the+ // doc-type barrel, one per kind of doc file.+ const docTypes = [+ ...fs+ .readFileSync(ENTRY, 'utf8')+ .matchAll(/^export type \{(\w+)\} from '\.\/doctypes\/types\.js';/gmu),+ ].map(([, name]) => name);+ expect(docTypes.length).toBeGreaterThan(10);+ /** @type {Record<string, boolean>} */+ const result = {};+ for (const name of [...docTypes, ...MEMBER_TYPES]) {+ const type = exported.get(name);+ expect(type, `${name} is exported`).toBeDefined();+ result[name] = accepts(/** @type {ts.Type} */ (type));+ }+ /** @type {Record<string, boolean>} */+ const expected = {};+ for (const name of [...docTypes, ...MEMBER_TYPES]) {+ expected[name] = !EXCEPT.has(name);+ }+ expect(result).toEqual(expected);+ }, 120_000);+});diff --git a/packages/cli/authoring/doctypes/enum/type.ts b/packages/cli/authoring/doctypes/enum/type.tsindex 67d5bccd11..ce5babae7a 100644--- a/packages/cli/authoring/doctypes/enum/type.ts+++ b/packages/cli/authoring/doctypes/enum/type.ts@@ -15,6 +15,10 @@ export interface EnumMemberDoc {description: string;/** Deprecation reason, if deprecated. */deprecated?: string;+ /** Set on a value of an experimental surface (spec:AST-017 FR27). The+ * enum's own section leaves it out; the experimental feature's docs,+ * under `astryx docs cli/experimental`, document it. */+ stability?: 'experimental';}/**diff --git a/packages/cli/authoring/doctypes/icon-definition/icon-definition.doc.mjs b/packages/cli/authoring/doctypes/icon-definition/icon-definition.doc.mjsnew file mode 100644index 0000000000..978b9bd6bb--- /dev/null+++ b/packages/cli/authoring/doctypes/icon-definition/icon-definition.doc.mjs@@ -0,0 +1,89 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SchemaDoc for the IconDefinitionDoc authoring type (AST-084).+ * @position packages/cli/authoring/doctypes/icon-definition — doc-type documentation+ */++/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */+export const doc = {+ type: 'schema',+ name: 'icon-definition-doc',+ displayName: 'IconDefinitionDoc',+ namespace: 'authoring',+ stability: 'experimental',+ description:+ "Experimental: may change or be removed in a patch release. One thing an icon can stand for, such as `close` or `delete`. Astryx ships one file per definition; an icon set adds its own in the same format. A set's data file `map` registers which of its icons draws each definition.",+ appliesTo: '<iconSetsRoot>/<set>/definitions/<name>.doc.mjs',+ fields: [+ {+ name: 'type',+ type: "'icon-definition'",+ description: 'Doc-kind discriminant.',+ required: true,+ },+ {+ name: 'name',+ type: 'string',+ description:+ "camelCase identity: the key a data file's `map` uses. Must match the file name.",+ required: true,+ example: "'delete'",+ },+ {+ name: 'description',+ type: 'string',+ description: 'One sentence: what an icon with this definition is for.',+ required: true,+ example: "'Delete something permanently.'",+ },+ {+ name: 'words',+ type: 'string[]',+ description: 'Lower-case terms a person might search for; at least one.',+ required: true,+ example: "['trash', 'bin', 'discard']",+ },+ {+ name: 'builtIn',+ type: 'true',+ description:+ "Only on Astryx's own definitions: the definition is a shared icon name Core renders, so every icon set maps it.",+ required: false,+ },+ {+ name: 'stability',+ type: "'experimental'",+ description:+ 'Marks the definition as experimental: the icon-definitions listing shows it as `[experimental]`. Omit it for a definition you mean to keep.',+ required: false,+ },+ ],+ examples: [+ {+ label:+ "A set's own definition at icon-sets/outline/definitions/rotate.doc.mjs",+ code: `/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {+ type: 'icon-definition',+ name: 'rotate',+ description: 'Rotate an image or shape.',+ words: ['turn', 'spin'],+};`,+ },+ ],+ notes: [+ {+ type: 'prose',+ text: "A set's own definitions sit in a `definitions` folder in the set's directory, one file per definition. Its `map` registers icons for them like for Astryx's. `astryx docs cli/experimental/icon-definitions` lists every definition: Astryx's, and, in a project that sets `experimental.iconSet`, those of each installed set. A definition file refuses a field it does not know.",+ },+ {+ type: 'prose',+ text: "IconDefinitionDoc is static metadata: one default-exported object of literal fields directly under a `/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */` comment. Discovery reads it without executing it.",+ },+ {+ type: 'prose',+ text: "To share a definition with every set, copy its file into Astryx's definitions folder in a pull request.",+ },+ ],+};diff --git a/packages/cli/authoring/doctypes/icon-definition/parse.mjs b/packages/cli/authoring/doctypes/icon-definition/parse.mjsnew file mode 100644index 0000000000..b34c064a3b--- /dev/null+++ b/packages/cli/authoring/doctypes/icon-definition/parse.mjs@@ -0,0 +1,89 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Icon definition parser (AST-084). Zod is sealed here; definition discovery+ * calls `parseIconDefinition` on each statically read `<name>.doc.mjs`.+ *+ * @input an unknown definition value+ * @output a validated IconDefinitionDoc, or a readable schema error+ * @position packages/cli/authoring/doctypes/icon-definition — load boundary+ */++import {z} from 'zod';+import {formatZodError} from '../../_shared/errors.mjs';++/** @typedef {import('./type.js').IconDefinitionDoc} IconDefinitionDoc */++/** A definition name: camelCase, starting with a lower-case letter. */+export const ICON_DEFINITION_NAME_RE = /^[a-z][a-zA-Z0-9]*$/u;++/** @param {string} field */+const nonBlank = field =>+ z.string().refine(value => value.trim() !== '', {+ message: `${field} must not be blank`,+ abort: true,+ });++const iconDefinitionSchema = z+ .object({+ type: z.literal('icon-definition'),+ name: nonBlank('name').regex(+ ICON_DEFINITION_NAME_RE,+ 'name must be camelCase starting with a lower-case letter',+ ),+ description: nonBlank('description'),+ words: z+ .array(+ nonBlank('word').refine(+ word => word === word.toLowerCase() && word === word.trim(),+ {message: 'words must be lower-case and trimmed'},+ ),+ )+ .min(1, 'a definition must have at least one word'),+ builtIn: z.literal(true).optional(),+ stability: z.literal('experimental').optional(),+ })+ .strict();++/** Zod skips `__proto__` when it looks for unknown keys. */+const PROTO_KEY_ISSUE = {+ code: /** @type {const} */ ('unrecognized_keys'),+ keys: ['__proto__'],+ path: [],+ message: 'Unrecognized key: "__proto__"',+};++/**+ * Compile-time drift lock: the sealed schema must infer IconDefinitionDoc.+ *+ * @typedef {import('../../_shared/contract.js').Expect<+ * import('../../_shared/contract.js').MutuallyAssignable<+ * z.infer<typeof iconDefinitionSchema>,+ * IconDefinitionDoc+ * >+ * >} _IconDefinitionDocDriftLock+ */++/**+ * Validate an unknown value as an icon definition, or throw.+ *+ * @param {unknown} input+ * @param {string} [label]+ * @returns {IconDefinitionDoc}+ * @experimental May change or be removed in a patch release.+ */+export function parseIconDefinition(input, label = 'icon definition') {+ const result = iconDefinitionSchema.safeParse(input);+ const protoKey =+ input !== null &&+ typeof input === 'object' &&+ Object.hasOwn(input, '__proto__');+ if (result.success && !protoKey) {+ return /** @type {IconDefinitionDoc} */ (result.data);+ }+ const issues = [+ ...(result.error?.issues ?? []),+ ...(protoKey ? [PROTO_KEY_ISSUE] : []),+ ];+ throw new Error(formatZodError(label, new z.ZodError(issues)));+}diff --git a/packages/cli/authoring/doctypes/icon-definition/parse.test.mjs b/packages/cli/authoring/doctypes/icon-definition/parse.test.mjsnew file mode 100644index 0000000000..b57f4c3828--- /dev/null+++ b/packages/cli/authoring/doctypes/icon-definition/parse.test.mjs@@ -0,0 +1,78 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The icon definition parser, and Astryx's own definitions: each one reads,+ * and the built-in ones are exactly Core's shared icon names.+ */++import {describe, expect, it} from 'vitest';+import {parseIconDefinition} from './parse.mjs';+import {parseDoc} from '../parse.mjs';+import {ICON_NAMES} from '../icon-set/icon-names.mjs';+import {astryxIconDefinitions} from '../../../foundation/discovery/icon-definition-discovery.mjs';++const DOC = {+ type: 'icon-definition',+ name: 'delete',+ description: 'Delete something permanently.',+ words: ['trash', 'bin'],+};++describe('parseIconDefinition', () => {+ it('accepts a definition, also through parseDoc', () => {+ expect(parseIconDefinition(DOC)).toEqual(DOC);+ expect(parseDoc(DOC)).toEqual(DOC);+ expect(parseIconDefinition({...DOC, builtIn: true}).builtIn).toBe(true);+ expect(+ parseIconDefinition({...DOC, stability: 'experimental'}).stability,+ ).toBe('experimental');+ expect(() => parseIconDefinition({...DOC, stability: 'stable'})).toThrow();+ });++ it('rejects a name that is not camelCase, a blank description, no words, and an unknown field', () => {+ expect(() => parseIconDefinition({...DOC, name: 'Delete'})).toThrow(+ /camelCase/,+ );+ expect(() => parseIconDefinition({...DOC, name: 'de-lete'})).toThrow(+ /camelCase/,+ );+ expect(() => parseIconDefinition({...DOC, description: ' '})).toThrow(+ /blank/,+ );+ expect(() => parseIconDefinition({...DOC, words: []})).toThrow(/word/);+ expect(() => parseIconDefinition({...DOC, words: ['Trash']})).toThrow(+ /lower-case/,+ );+ expect(() => parseIconDefinition({...DOC, builtIn: false})).toThrow();+ expect(() => parseIconDefinition({...DOC, icons: []})).toThrow(+ /Unrecognized key/,+ );+ expect(() =>+ parseIconDefinition({...DOC, examples: {lib: 'Delete'}}),+ ).toThrow(/Unrecognized key/);+ });+});++describe("Astryx's definitions", () => {+ const {definitions, errors} = astryxIconDefinitions();+ const docs = definitions.map(m => m.doc);++ it('every file reads, with a unique camelCase name, a description, and words', () => {+ expect(errors).toEqual([]);+ expect(docs.length).toBeGreaterThan(ICON_NAMES.length);+ expect(new Set(docs.map(d => d.name)).size).toBe(docs.length);+ for (const doc of docs) {+ expect(doc.description.trim(), doc.name).not.toBe('');+ expect(doc.words.length, doc.name).toBeGreaterThan(0);+ }+ });++ it("the built-in definitions are exactly Core's shared icon names", () => {+ expect(+ docs+ .filter(d => d.builtIn)+ .map(d => d.name)+ .sort(),+ ).toEqual([...ICON_NAMES].sort());+ });+});diff --git a/packages/cli/authoring/doctypes/icon-definition/type.ts b/packages/cli/authoring/doctypes/icon-definition/type.tsnew file mode 100644index 0000000000..71431a240c--- /dev/null+++ b/packages/cli/authoring/doctypes/icon-definition/type.ts@@ -0,0 +1,55 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Icon definition doc type (AST-084).+ *+ * An icon definition is one thing an icon can stand for, such as `close` or+ * `delete`. Astryx ships one `<name>.doc.mjs` per definition in the CLI; an icon+ * set can add its own in `<iconSetsRoot>/<set>/definitions/<name>.doc.mjs`, in+ * the same format. A set's data file `map` registers which of its icons+ * draws each definition, so a template written against definitions swaps+ * sets by lookup.+ *+ * @input metadata authored for one definition+ * @output the public IconDefinitionDoc contract+ * @position packages/cli/authoring/doctypes/icon-definition — definition vocabulary+ */++/**+ * One icon definition.+ *+ * @example+ * ```+ * /** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} *\/+ * export default {+ * type: 'icon-definition',+ * name: 'delete',+ * description: 'Delete something permanently.',+ * words: ['trash', 'bin', 'discard'],+ * };+ * ```+ *+ * @experimental Icon definitions may change or be removed in a patch release+ * (spec:AST-017 FR27).+ */+export interface IconDefinitionDoc {+ /** Doc-kind discriminant. */+ type: 'icon-definition';+ /** camelCase identity, the key a data file's `map` uses. Must match the file name. */+ name: string;+ /** One sentence: what an icon with this definition is for. */+ description: string;+ /** Lower-case terms a person might search for; at least one. */+ words: string[];+ /**+ * Only on Astryx's own definitions: the definition is a shared icon name Core+ * renders (`IconName`), so every icon set maps it.+ */+ builtIn?: true;+ /**+ * Marks the definition as experimental (spec:AST-017 FR27): the+ * `icon-definitions` listing shows it as `[experimental]`. Every icon+ * definition already belongs to the experimental icon-set feature.+ */+ stability?: 'experimental';+}diff --git a/packages/cli/authoring/doctypes/icon-set/icon-names.mjs b/packages/cli/authoring/doctypes/icon-set/icon-names.mjsnew file mode 100644index 0000000000..5bc762c4c0--- /dev/null+++ b/packages/cli/authoring/doctypes/icon-set/icon-names.mjs@@ -0,0 +1,44 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The shared semantic icon names (`IconName`) Core renders: the+ * built-in icon definitions every icon set maps (AST-084 FR3, FR12).+ *+ * SYNC: packages/core/src/Icon/globalIconRegistry.tsx (the `IconName` union).+ * `icon-names.test.mjs` fails when the two lists differ.+ *+ * @position packages/cli/authoring/doctypes/icon-set — data-file vocabulary+ */++/** Every `IconName`, in the order Core declares them. */+export const ICON_NAMES = Object.freeze([+ 'close',+ 'chevronDown',+ 'chevronLeft',+ 'chevronRight',+ 'chevronsLeft',+ 'chevronsRight',+ 'check',+ 'success',+ 'error',+ 'warning',+ 'info',+ 'calendar',+ 'clock',+ 'externalLink',+ 'menu',+ 'moreHorizontal',+ 'search',+ 'upload',+ 'arrowUp',+ 'arrowDown',+ 'arrowsUpDown',+ 'funnel',+ 'eyeSlash',+ 'viewColumns',+ 'copy',+ 'checkDouble',+ 'wrench',+ 'stop',+ 'microphone',+]);diff --git a/packages/cli/authoring/doctypes/icon-set/icon-names.test.mjs b/packages/cli/authoring/doctypes/icon-set/icon-names.test.mjsnew file mode 100644index 0000000000..c9dc053e01--- /dev/null+++ b/packages/cli/authoring/doctypes/icon-set/icon-names.test.mjs@@ -0,0 +1,26 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The CLI's IconName list matches Core's `IconName` union.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {describe, it, expect} from 'vitest';+import {ICON_NAMES} from './icon-names.mjs';++const REGISTRY = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../../../core/src/Icon/globalIconRegistry.tsx',+);++describe('ICON_NAMES', () => {+ it("lists exactly Core's IconName union, in order", () => {+ const source = fs.readFileSync(REGISTRY, 'utf-8');+ const union = /export type IconName =([^;]*);/u.exec(source)?.[1] ?? '';+ const names = [...union.matchAll(/'([^']+)'/gu)].map(match => match[1]);+ expect(names.length).toBeGreaterThan(0);+ expect([...ICON_NAMES]).toEqual(names);+ });+});diff --git a/packages/cli/authoring/doctypes/icon-set/icon-set-data.doc.mjs b/packages/cli/authoring/doctypes/icon-set/icon-set-data.doc.mjsnew file mode 100644index 0000000000..cb0e2bda46--- /dev/null+++ b/packages/cli/authoring/doctypes/icon-set/icon-set-data.doc.mjs@@ -0,0 +1,169 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SchemaDoc for an icon set's `<name>.icons.json` data file+ * (AST-084 FR3).+ * @position packages/cli/authoring/doctypes/icon-set — data-file documentation+ */++/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */+export const doc = {+ type: 'schema',+ name: 'icon-set-data',+ displayName: 'IconSetData',+ namespace: 'authoring',+ stability: 'experimental',+ description:+ "Experimental: may change or be removed in a patch release. An icon set's data file: which icons exist, the export that draws each one, the words a person might search for, and which icon draws each icon definition (`map`). `astryx experimental icon`, template icon mapping, and the checks read this file and nothing else.",+ appliesTo: '<iconSetsRoot>/<name>/<name>.icons.json',+ fields: [+ {+ name: 'schemaVersion',+ type: '1',+ description: 'Data-file format version.',+ required: true,+ },+ {+ name: 'module',+ type: 'string',+ description:+ "The import specifier every `export` is read from: the set's own package name, or one of its package.json `exports` subpaths. Never a file path.",+ required: true,+ example: "'@acme/outline-icons'",+ },+ {+ name: 'source',+ type: '{package: string, version: string}',+ description:+ 'The upstream library and version the file was generated from. Omit it for a set with no upstream.',+ },+ {+ name: 'generated',+ type: 'string',+ description:+ "The module `astryx experimental icon add` writes, as a `./` path from the package root: one export per icon, a re-export of a library component or the adapter applied to a library export, and `themeIcons`, the theme map, from the built-in entries of `map`. The CLI writes its declaration file beside it. The package's entry re-exports it.",+ example: "'./icon-sets/outline/outline.generated.js'",+ },+ {+ name: 'adapter',+ type: '{module: string, export: string}',+ description:+ 'A function in the package, `(source) => Component`, that turns a library export that is not a component (icon data, an SVG string or URL) into one. `module` is a `./` path from the package root.',+ example: "{module: './src/adapt.js', export: 'adapt'}",+ },+ {+ name: 'variants',+ type: 'string[]',+ description:+ 'The named looks the set offers, in lower-kebab case, such as `outline` and `solid`. Icon size is never a variant: CSS sets it. Omit it when the set has one look.',+ example: "['outline', 'solid']",+ },+ {+ name: 'default',+ type: '{variant?: string}',+ description:+ "The variant each icon's own `export` draws; one of `variants`.",+ example: "{variant: 'outline'}",+ },+ {+ name: 'themeMap',+ type: 'string',+ description:+ 'The export that maps each built-in icon definition to its artwork, keyed by exactly the built-in definitions in `map`.',+ example: "'themeIcons'",+ },+ {+ name: 'map',+ type: 'Record<string, string>',+ description:+ "Which of this set's icons draws each icon definition: definition name to icon `id`. Keys are Astryx's definitions (`astryx docs cli/experimental/icon-definitions`) or ones the set declares in its `definitions` folder, one file per definition. One icon may draw several definitions; each definition maps to one icon. Every built-in definition must be mapped.",+ example: '{"close": "x", "delete": "trash", "remove": "trash"}',+ },+ {+ name: 'icons',+ type: 'IconSetIcon[]',+ description: 'Every icon in the set.',+ required: true,+ fields: [+ {+ name: 'icons[].id',+ type: 'string',+ description: 'Lower-kebab identity, unique in the set.',+ required: true,+ example: "'trash'",+ },+ {+ name: 'icons[].export',+ type: 'string',+ description:+ "The named export that draws the icon's default variant, named `<Name>Icon`: a React component that takes SVG props and draws with `currentColor`.",+ required: true,+ example: "'TrashIcon'",+ },+ {+ name: 'icons[].module',+ type: 'string',+ description:+ "The import specifier, when it differs from the set's `module`.",+ },+ {+ name: 'icons[].words',+ type: 'string[]',+ description:+ "Lower-case terms a person might search for, the words of the icon's own name included; at least one. Do not copy the words of the definitions `map` names the icon for: search already matches the icon by them.",+ required: true,+ example: "['trash', 'delete', 'remove', 'bin']",+ },+ {+ name: 'icons[].variants',+ type: '{variant, export, module?}[]',+ description:+ 'Other variants of the icon: each names one of `variants`, never the default, and the export that draws it. At most one export per variant.',+ },+ {+ name: 'icons[].matches',+ type: "{set, export, variant?, confidence: 'exact' | 'strong' | 'likely'}[]",+ description:+ "Reviewed equivalents of this icon in other icon sets or libraries, such as `{set: 'lines', export: 'CrossIcon', variant: 'solid', confidence: 'exact'}`. When a copied template imports a matched icon from that installed set, `exact` and `strong` matches are used before any other rule; a `likely` match is only suggested. A match never names this set itself.",+ },+ ],+ },+ ],+ examples: [+ {+ label: 'A data file at icons/outline/outline.icons.json',+ code: `{+ "schemaVersion": 1,+ "module": "@acme/outline-icons",+ "generated": "./icon-sets/outline/outline.generated.js",+ "variants": ["outline", "solid"],+ "default": {"variant": "outline"},+ "themeMap": "themeIcons",+ "map": {"close": "x", "delete": "trash"},+ "icons": [+ {"id": "x", "export": "XIcon", "words": ["close", "cancel", "dismiss"]},+ {+ "id": "trash",+ "export": "TrashIcon",+ "words": ["trash", "delete", "remove", "bin"],+ "variants": [{"variant": "solid", "export": "TrashSolidIcon"}]+ }+ ]+}`,+ },+ ],+ notes: [+ {+ type: 'prose',+ text: 'A file that fails this schema, repeats an id, gives an icon no words, has a `map` key that is not camelCase or a `map` value that is not an icon id in the file, or names a variant `variants` does not declare is invalid, and its set is withdrawn from every surface until it is fixed. `astryx doctor` names the reason.',+ },+ {+ type: 'prose',+ text: "A template declares the icon definition each icon it imports draws. With a project icon set, each declared icon maps to the icon whose `matches` name it with `exact` or `strong` confidence (for an icon another installed set ships), else to the icon this file's `map` names for its definition. Nothing is guessed from names or words.",+ },+ {+ type: 'prose',+ text: 'Write it with the CLI: `astryx experimental icon add` registers one icon and its `map` entry, `astryx experimental icon map` changes an entry, and `astryx experimental icon new-set --from` wraps a whole library.',+ },+ ],+};diff --git a/packages/cli/authoring/doctypes/icon-set/icon-set.doc.mjs b/packages/cli/authoring/doctypes/icon-set/icon-set.doc.mjsnew file mode 100644index 0000000000..86cc2c2222--- /dev/null+++ b/packages/cli/authoring/doctypes/icon-set/icon-set.doc.mjs@@ -0,0 +1,90 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SchemaDoc for the IconSetDoc authoring type (AST-084 FR2).+ * @position packages/cli/authoring/doctypes/icon-set — doc-type documentation+ */++/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */+export const doc = {+ type: 'schema',+ name: 'icon-set-doc',+ displayName: 'IconSetDoc',+ namespace: 'authoring',+ stability: 'experimental',+ description:+ "Experimental: may change or be removed in a patch release. The strongly typed descriptor for one icon set an integration ships: what a person writes about the set. The set's icons, and what each one means, live in the `<name>.icons.json` data file beside it.",+ appliesTo: '<iconSetsRoot>/<name>/<name>.doc.mjs',+ fields: [+ {+ name: 'type',+ type: "'icon-set'",+ description: 'Doc-kind discriminant.',+ required: true,+ },+ {+ name: 'name',+ type: 'string',+ description:+ 'Lower-kebab icon-set identity. Must match the descriptor parent directory.',+ required: true,+ example: "'outline'",+ },+ {+ name: 'displayName',+ type: 'string',+ description:+ 'Human-readable name shown by `astryx experimental icon --list`.',+ required: true,+ example: "'Acme Outline'",+ },+ {+ name: 'description',+ type: 'string',+ description:+ 'One-line summary shown by `astryx experimental icon --list`.',+ required: true,+ },+ {+ name: 'maintained',+ type: 'boolean',+ description: 'Whether the owning package actively maintains this set.',+ required: true,+ },+ {+ name: 'license',+ type: 'string',+ description: 'SPDX license expression for the artwork.',+ required: true,+ example: "'MIT'",+ },+ ],+ examples: [+ {+ label: 'An icon-set descriptor at icons/outline/outline.doc.mjs',+ code: `/** @type {import('@astryxdesign/cli/authoring').IconSetDoc} */+export default {+ type: 'icon-set',+ name: 'outline',+ displayName: 'Acme Outline',+ description: 'Outline icons with rounded strokes.',+ maintained: true,+ license: 'MIT',+};`,+ },+ ],+ notes: [+ {+ type: 'prose',+ text: "Point the manifest's `experimental.iconSets` field at the folder that holds your sets. Each lower-kebab folder under it is one set, named by the folder, and holds `<name>.doc.mjs`, `<name>.icons.json`, and any license notice files. The manifest never lists sets or icons.",+ },+ {+ type: 'prose',+ text: "Write the descriptor as one default-exported object of literal strings and booleans under a `/** @type {import('@astryxdesign/cli/authoring').IconSetDoc} */` comment, with nothing else in the file. Discovery reads it, and the data file, without executing them or the icon module.",+ },+ {+ type: 'prose',+ text: 'The data file is described by {@link schema:icon-set-data}. Run `astryx integration check` to prove every export it names exists in the module and that the theme map agrees with the built-in entries of `map`.',+ },+ ],+};diff --git a/packages/cli/authoring/doctypes/icon-set/parse.mjs b/packages/cli/authoring/doctypes/icon-set/parse.mjsnew file mode 100644index 0000000000..4a108ac58a--- /dev/null+++ b/packages/cli/authoring/doctypes/icon-set/parse.mjs@@ -0,0 +1,322 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Icon-set descriptor and data-file parsers (AST-084 FR2, FR3). Zod is+ * sealed here; icon-set discovery calls `parseIconSet` on the statically read+ * descriptor and `parseIconSetData` on the parsed `<name>.icons.json`.+ *+ * The data parser checks the whole file, not only its shape: a duplicate id,+ * an icon with no words, a `map` key that is not a camelCase definition name+ * or a value that is not an icon id in the file, and a variant or default+ * naming a variant the set's `variants` do not declare all make the file+ * invalid,+ * and an invalid file withdraws its set from every surface (FR3). Whether each+ * `map` key is Astryx's definition or one the set declares is checked by+ * icon-set discovery, which reads the definition files.+ *+ * @input an unknown descriptor value, or an unknown parsed data file+ * @output a validated IconSetDoc / IconSetData, or a readable schema error+ * @position packages/cli/authoring/doctypes/icon-set — load boundary+ */++import {z} from 'zod';+import {formatZodError} from '../../_shared/errors.mjs';+import {ICON_DEFINITION_NAME_RE} from '../icon-definition/parse.mjs';++/** @typedef {import('./type.js').IconSetDoc} IconSetDoc */+/** @typedef {import('./type.js').IconSetData} IconSetData */++/**+ * The confidences a reviewed match may carry: template mapping applies the+ * first two and suggests the last.+ */+export const MATCH_CONFIDENCES = /** @type {const} */ ([+ 'exact',+ 'strong',+ 'likely',+]);++const KEBAB_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;+const ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;+const EXPORT_RE = /^[$A-Z_a-z][$\w]*$/u;+// A bare package specifier, optionally with a subpath: never relative or+// absolute, so no path in the data file can leave the package (FR5).+// A path inside the set's package, from its root: `./src/icons.js`.+const PACKAGE_PATH_RE = /^\.\/(?:[A-Za-z0-9._~@-]+\/)*[A-Za-z0-9._~@-]+$/u;+const packagePathSchema = z+ .string()+ .regex(PACKAGE_PATH_RE, 'must be a ./ path inside the package')+ .refine(+ value =>+ !value+ .split('/')+ .slice(1)+ .some(part => part === '..' || part === '.'),+ {message: 'must not contain "." or ".." segments'},+ );+const MODULE_RE =+ /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*(?:\/[A-Za-z0-9._~-]+)*$/u;++/** @param {string} field */+const nonBlank = field =>+ z.string().refine(value => value.trim() !== '', {+ message: `${field} must not be blank`,+ abort: true,+ });++const iconSetDocSchema = z+ .object({+ type: z.literal('icon-set'),+ name: nonBlank('name').regex(+ KEBAB_RE,+ 'name must be lowercase kebab-case starting with a letter',+ ),+ displayName: nonBlank('displayName'),+ description: z.string(),+ maintained: z.boolean(),+ license: nonBlank('license'),+ })+ .strict();++const moduleSchema = z+ .string()+ .regex(+ MODULE_RE,+ 'module must be a package import specifier, never a relative or absolute path',+ )+ .refine(+ value => !value.split('/').some(part => part === '..' || part === '.'),+ {+ message: 'module must not contain "." or ".." segments',+ },+ );+const exportSchema = z+ .string()+ .regex(EXPORT_RE, 'export must be a JavaScript identifier');+const variantNameSchema = z+ .string()+ .regex(KEBAB_RE, 'a variant must be lowercase kebab-case');++const variantSchema = z+ .object({+ variant: variantNameSchema,+ export: exportSchema,+ module: moduleSchema.optional(),+ })+ .strict();++const matchSchema = z+ .object({+ set: z.string().regex(KEBAB_RE, 'set must be a lower-kebab set name'),+ export: exportSchema,+ variant: nonBlank('variant').optional(),+ confidence: z.enum(MATCH_CONFIDENCES),+ })+ .strict();++const iconSchema = z+ .object({+ id: z+ .string()+ .regex(ID_RE, 'id must be lowercase kebab-case letters and digits'),+ export: exportSchema,+ module: moduleSchema.optional(),+ words: z+ .array(+ nonBlank('word').refine(+ word => word === word.toLowerCase() && word === word.trim(),+ {message: 'words must be lower-case and trimmed'},+ ),+ )+ .min(1, 'an icon must have at least one word'),+ variants: z.array(variantSchema).optional(),+ matches: z.array(matchSchema).optional(),+ })+ .strict();++const dataSchema = z+ .object({+ schemaVersion: z.literal(1),+ module: moduleSchema,+ source: z+ .object({+ package: nonBlank('source.package'),+ version: nonBlank('source.version'),+ })+ .strict()+ .optional(),+ variants: z.array(variantNameSchema).min(1).optional(),+ default: z+ .object({variant: variantNameSchema.optional()})+ .strict()+ .optional(),+ themeMap: exportSchema.optional(),+ map: z.record(z.string(), z.string()).optional(),+ generated: packagePathSchema+ .refine(value => /\.(?:[cm]?js|jsx|tsx?|mts)$/u.test(value), {+ message: 'generated must be a JavaScript or TypeScript module file',+ })+ .optional(),+ adapter: z+ .object({module: packagePathSchema, export: exportSchema})+ .strict()+ .optional(),+ icons: z.array(iconSchema),+ })+ .strict()+ .superRefine((data, ctx) => {+ const declared = data.variants ?? [];+ /**+ * Whether a named variant is one the set declares.+ * @param {string | undefined} variant+ * @param {(string|number)[]} at+ */+ const checkVariant = (variant, at) => {+ if (variant != null && !declared.includes(variant)) {+ ctx.addIssue({+ code: 'custom',+ path: [...at, 'variant'],+ message: `variant "${variant}" is not in variants`,+ });+ }+ };++ declared.forEach((variant, at) => {+ if (declared.indexOf(variant) !== at) {+ ctx.addIssue({+ code: 'custom',+ path: ['variants', at],+ message: `variant "${variant}" is listed twice`,+ });+ }+ });+ if (data.default) checkVariant(data.default.variant, ['default']);+ const defaultVariant = data.default?.variant;++ /** @type {Map<string, number>} */+ const ids = new Map();+ data.icons.forEach((icon, index) => {+ const first = ids.get(icon.id);+ if (first != null) {+ ctx.addIssue({+ code: 'custom',+ path: ['icons', index, 'id'],+ message: `duplicate id "${icon.id}" (also icons.${first})`,+ });+ } else {+ ids.set(icon.id, index);+ }+ /** @type {Set<string>} */+ const named = new Set();+ (icon.matches ?? []).forEach((match, at) => {+ const key = `${match.set}\0${match.variant ?? ''}\0${match.export}`;+ if (named.has(key)) {+ ctx.addIssue({+ code: 'custom',+ path: ['icons', index, 'matches', at],+ message: `the match ${match.set}${match.variant ? ` ${match.variant}` : ''} "${match.export}" is listed twice`,+ });+ }+ named.add(key);+ });+ /** @type {Set<string>} */+ const drawn = new Set();+ (icon.variants ?? []).forEach((entry, at) => {+ const where = ['icons', index, 'variants', at];+ checkVariant(entry.variant, where);+ if (entry.variant === defaultVariant) {+ ctx.addIssue({+ code: 'custom',+ path: [...where, 'variant'],+ message: `variant "${entry.variant}" is the default: the icon's own export draws it`,+ });+ } else if (drawn.has(entry.variant)) {+ ctx.addIssue({+ code: 'custom',+ path: [...where, 'variant'],+ message: `variant "${entry.variant}" is listed twice`,+ });+ }+ drawn.add(entry.variant);+ });+ });++ for (const [name, id] of Object.entries(data.map ?? {})) {+ if (!ICON_DEFINITION_NAME_RE.test(name)) {+ ctx.addIssue({+ code: 'custom',+ path: ['map', name],+ message: `"${name}" is not an icon definition name: definitions are camelCase`,+ });+ }+ if (!ids.has(id)) {+ ctx.addIssue({+ code: 'custom',+ path: ['map', name],+ message: `"${id}" is not the id of an icon in this file`,+ });+ }+ }+ });++/** Zod skips `__proto__` when it looks for unknown keys. */+const PROTO_KEY_ISSUE = {+ code: /** @type {const} */ ('unrecognized_keys'),+ keys: ['__proto__'],+ path: [],+ message: 'Unrecognized key: "__proto__"',+};++/**+ * Compile-time drift locks: the sealed schemas must infer the public types.+ *+ * @typedef {import('../../_shared/contract.js').Expect<+ * import('../../_shared/contract.js').Equal<+ * z.infer<typeof iconSetDocSchema>,+ * IconSetDoc+ * >+ * >} _IconSetDocDriftLock+ * @typedef {import('../../_shared/contract.js').Expect<+ * import('../../_shared/contract.js').MutuallyAssignable<+ * z.infer<typeof dataSchema>,+ * IconSetData+ * >+ * >} _IconSetDataDriftLock+ */++/**+ * Validate an unknown value as an icon-set descriptor, or throw.+ *+ * @param {unknown} input+ * @param {string} [label]+ * @returns {IconSetDoc}+ * @experimental May change or be removed in a patch release.+ */+export function parseIconSet(input, label = 'icon set') {+ const result = iconSetDocSchema.safeParse(input);+ const protoKey =+ input !== null &&+ typeof input === 'object' &&+ Object.hasOwn(input, '__proto__');+ if (result.success && !protoKey) return result.data;+ const issues = [+ ...(result.error?.issues ?? []),+ ...(protoKey ? [PROTO_KEY_ISSUE] : []),+ ];+ throw new Error(formatZodError(label, new z.ZodError(issues)));+}++/**+ * Validate an unknown value as an icon-set data file (`<name>.icons.json`),+ * shape and consistency both, or throw.+ *+ * @param {unknown} input+ * @param {string} [label]+ * @returns {IconSetData}+ * @experimental May change or be removed in a patch release.+ */+export function parseIconSetData(input, label = 'icon set data') {+ const result = dataSchema.safeParse(input);+ if (result.success) return /** @type {IconSetData} */ (result.data);+ throw new Error(formatZodError(label, result.error));+}diff --git a/packages/cli/authoring/doctypes/icon-set/parse.test.mjs b/packages/cli/authoring/doctypes/icon-set/parse.test.mjsnew file mode 100644index 0000000000..1a6b33ab27--- /dev/null+++ b/packages/cli/authoring/doctypes/icon-set/parse.test.mjs@@ -0,0 +1,179 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The icon-set descriptor and data-file parsers (AST-084 FR2, FR3).+ */++import {describe, it, expect} from 'vitest';+import {parseIconSet, parseIconSetData} from './parse.mjs';+import {parseDoc} from '../parse.mjs';+import {glyphsData} from '../../../test-utils/icon-set-fixture.mjs';++const DOC = {+ type: 'icon-set',+ name: 'outline',+ displayName: 'Acme Outline',+ description: 'Outline icons.',+ maintained: true,+ license: 'MIT',+};++/** @param {(data: any) => void} change */+function dataWith(change) {+ const data = /** @type {any} */ (glyphsData());+ change(data);+ return data;+}++describe('parseIconSet', () => {+ it('accepts a complete descriptor, also through parseDoc', () => {+ expect(parseIconSet(DOC)).toEqual(DOC);+ expect(parseDoc(DOC)).toEqual(DOC);+ });++ it('rejects an unknown field, a missing license, and a non-kebab name', () => {+ expect(() => parseIconSet({...DOC, icons: []})).toThrow(/Unrecognized key/);+ const {license: _license, ...noLicense} = DOC;+ expect(() => parseIconSet(noLicense)).toThrow(/license/);+ expect(() => parseIconSet({...DOC, name: 'Outline'})).toThrow(/kebab/);+ });+});++describe('parseIconSetData', () => {+ it('accepts the fixture data file', () => {+ expect(parseIconSetData(glyphsData()).icons).toHaveLength(4);+ // One icon may draw several definitions.+ const data = /** @type {any} */ (glyphsData());+ data.map = {...data.map, delete: 'trash', remove: 'trash'};+ expect(parseIconSetData(data).map).toMatchObject({+ delete: 'trash',+ remove: 'trash',+ });+ });++ it.each([+ ['schemaVersion 2', d => (d.schemaVersion = 2), /schemaVersion/],+ ['an unknown field', d => (d.extra = true), /Unrecognized key/],+ ['a relative module', d => (d.module = './icons'), /module/],+ ['a duplicate id', d => (d.icons[1].id = 'x'), /duplicate id "x"/],+ [+ 'an icon with no words',+ d => (d.icons[0].words = []),+ /at least one word/,+ ],+ ['an upper-case word', d => (d.icons[0].words = ['Close']), /lower-case/],+ [+ 'a map key that is not a definition name',+ d => (d.map['big-house'] = 'home'),+ /"big-house" is not an icon definition name/,+ ],+ [+ 'a map value that is not an icon id',+ d => (d.map.delete = 'bin'),+ /"bin" is not the id of an icon in this file/,+ ],+ [+ 'icons that still carry fills',+ d => (d.icons[0].fills = ['close']),+ /Unrecognized key/,+ ],+ [+ 'an undeclared variant',+ d => (d.icons[2].variants[0].variant = 'duotone'),+ /"duotone" is not in variants/,+ ],+ [+ 'a variant entry that names no variant',+ d => (d.icons[2].variants = [{export: 'TrashAltIcon'}]),+ /variant/,+ ],+ [+ 'a variant entry for the default variant',+ d => (d.icons[2].variants[0].variant = 'outline'),+ /"outline" is the default/,+ ],+ [+ 'two exports for one variant',+ d =>+ d.icons[2].variants.push({variant: 'solid', export: 'TrashFillIcon'}),+ /"solid" is listed twice/,+ ],+ [+ 'a variant declared twice',+ d => (d.variants = ['outline', 'solid', 'solid']),+ /"solid" is listed twice/,+ ],+ [+ 'a variant name that is not kebab-case',+ d => (d.variants = ['outline', 'Solid']),+ /kebab-case/,+ ],+ [+ 'an undeclared default',+ d => (d.default.variant = 'duotone'),+ /"duotone" is not in variants/,+ ],+ ['a size axis', d => (d.sizes = [24]), /Unrecognized key/],+ ['the retired axes field', d => (d.axes = {}), /Unrecognized key/],+ [+ 'a match with an unknown confidence',+ d =>+ (d.icons[0].matches = [+ {set: 'other-set', export: 'XMarkIcon', confidence: 'maybe'},+ ]),+ /confidence/,+ ],+ [+ 'a match listed twice',+ d =>+ (d.icons[0].matches = [+ {set: 'other-set', export: 'X', confidence: 'exact'},+ {set: 'other-set', export: 'X', confidence: 'likely'},+ ]),+ /listed twice/,+ ],+ [+ 'a match with an unknown field',+ d =>+ (d.icons[0].matches = [+ {set: 'other-set', export: 'X', confidence: 'exact', note: 'x'},+ ]),+ /Unrecognized key/,+ ],+ ])('rejects %s', (_label, change, message) => {+ expect(() => parseIconSetData(dataWith(change))).toThrow(message);+ });++ it('accepts reviewed matches with and without a variant', () => {+ const data = dataWith(d => {+ d.icons[0].matches = [+ {+ set: 'other-set',+ export: 'XMarkIcon',+ variant: 'outline',+ confidence: 'exact',+ },+ {set: 'other-set', export: 'X', confidence: 'likely'},+ ];+ });+ expect(parseIconSetData(data).icons[0].matches).toHaveLength(2);+ });++ it('accepts the declared variants and a default among them', () => {+ const data = parseIconSetData(glyphsData());+ expect(data.variants).toEqual(['outline', 'solid']);+ expect(data.default).toEqual({variant: 'outline'});+ expect(data.icons[2].variants).toEqual([+ {variant: 'solid', export: 'TrashSolidIcon'},+ ]);+ });++ it('accepts a set with one look: no variants and no default', () => {+ const data = dataWith(d => {+ delete d.variants;+ delete d.default;+ delete d.icons[2].variants;+ });+ expect(parseIconSetData(data).variants).toBeUndefined();+ });+});diff --git a/packages/cli/authoring/doctypes/icon-set/type.ts b/packages/cli/authoring/doctypes/icon-set/type.tsnew file mode 100644index 0000000000..94feb8cd83--- /dev/null+++ b/packages/cli/authoring/doctypes/icon-set/type.ts@@ -0,0 +1,182 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Icon-set contribution descriptor and data-file types (AST-084).+ *+ * An icon set is one integration item: a lower-kebab directory under the+ * manifest's `experimental.iconSets` root holding a strongly typed `<name>.doc.mjs`+ * descriptor and one `<name>.icons.json` data file. The descriptor holds what+ * a person writes about the set; the data file says what every icon means.+ * Every icon surface (`astryx experimental icon`, template icon mapping, the theme+ * map check, Doctor) reads the data file and nothing else.+ *+ * @input metadata authored beside one icon set+ * @output the public IconSetDoc and IconSetData contracts+ * @position packages/cli/authoring/doctypes/icon-set — icon-set vocabulary+ */++/**+ * The descriptor for one icon set an integration contributes.+ *+ * @example+ * ```+ * /** @type {import('@astryxdesign/cli/authoring').IconSetDoc} *\/+ * export default {+ * type: 'icon-set',+ * name: 'outline',+ * displayName: 'Acme Outline',+ * description: 'Outline icons with rounded strokes.',+ * maintained: true,+ * license: 'MIT',+ * };+ * ```+ *+ * @experimental Icon sets may change or be removed in a patch release+ * (spec:AST-017 FR27).+ */+export interface IconSetDoc {+ /** Doc-kind discriminant. */+ type: 'icon-set';+ /** Stable CLI identity. Must be lower-kebab and match the parent directory. */+ name: string;+ /** Human-readable name shown by icon-set listings. */+ displayName: string;+ /** One-line summary shown by icon-set listings. */+ description: string;+ /** Whether the owning package actively maintains this set. */+ maintained: boolean;+ /** SPDX license expression for the artwork. */+ license: string;+}++/**+ * The variant an icon's own `export` draws, when the set declares variants.+ * A variant is a named look the set supplies (for example outline or solid);+ * size comes from CSS.+ * @experimental May change or be removed in a patch release.+ */+export interface IconSetDefault {+ /** One of the set's declared `variants`. */+ variant?: string;+}++/**+ * Another variant of one icon, drawn by its own export.+ * @experimental May change or be removed in a patch release.+ */+export interface IconSetVariant {+ /** One of the set's declared `variants`. */+ variant: string;+ /** The named export that draws this variant. */+ export: string;+ /** The import specifier, when it differs from the icon's module. */+ module?: string;+}++/**+ * How sure a reviewed cross-set match is.+ * @experimental May change or be removed in a patch release.+ */+export type IconSetMatchConfidence = 'exact' | 'strong' | 'likely';++/**+ * A reviewed equivalent of an icon in another icon set or icon library.+ * Template icon mapping applies `exact` and `strong` matches and only+ * suggests `likely` ones.+ * @experimental May change or be removed in a patch release.+ */+export interface IconSetMatch {+ /** The other set's name, such as `lines`; never this set's own name. */+ set: string;+ /** The export that draws the equivalent icon in that set. */+ export: string;+ /** Which of that set's variants, such as `solid`, when it has several. */+ variant?: string;+ /** How sure the match is. */+ confidence: IconSetMatchConfidence;+}++/**+ * One icon of a set.+ * @experimental May change or be removed in a patch release.+ */+export interface IconSetIcon {+ /** Lower-kebab identity, unique in the set. */+ id: string;+ /** The named export that draws the icon's default variant. */+ export: string;+ /** The import specifier, when it differs from the set's module. */+ module?: string;+ /** Lower-case terms a person might search for; at least one. */+ words: string[];+ /** Other variants, each naming a declared variant and its own export. */+ variants?: IconSetVariant[];+ /** Reviewed equivalents of this icon in other sets. */+ matches?: IconSetMatch[];+}++/**+ * The upstream library and version the data file was generated from.+ * @experimental May change or be removed in a patch release.+ */+export interface IconSetSource {+ package: string;+ version: string;+}++/**+ * The function that turns a library export into an icon component.+ * @experimental May change or be removed in a patch release.+ */+export interface IconSetAdapter {+ /** A path from the package root, such as `./src/adapt.js`. */+ module: string;+ /** Its named export. */+ export: string;+}++/**+ * The `<name>.icons.json` data file of one icon set.+ * @experimental May change or be removed in a patch release.+ */+export interface IconSetData {+ /** Data-file format version. */+ schemaVersion: 1;+ /** The import specifier every `export` is read from. */+ module: string;+ /** The upstream library, absent for a set with no upstream. */+ source?: IconSetSource;+ /**+ * The variants the set supplies, lower-kebab names such as `outline` and+ * `solid`; absent when it has one look. A variant is a named look the set+ * supplies; size comes from CSS.+ */+ variants?: string[];+ /** The variant an icon's own `export` draws. */+ default?: IconSetDefault;+ /** The export that maps each built-in definition in `map` to its artwork. */+ themeMap?: string;+ /**+ * Which of this set's icons draws each icon definition, by definition name:+ * Astryx's (`astryx docs cli/experimental/icon-definitions`) or one the set declares in its+ * `definitions` folder. One icon may draw several definitions; each+ * definition maps to one icon.+ */+ map?: Record<string, string>;+ /**+ * The module `astryx experimental icon add` writes, from the package root, such as+ * `./src/icons.generated.js`: one export per registered icon, a re-export+ * of a library component or an adapted export. The set's `module` exports+ * it, so every icon entry reads from the set's own module.+ */+ generated?: string;+ /**+ * A function in the set's package, `(source) => Component`, that turns a+ * library export that is not a component (an icon data object, an SVG+ * string or URL, a glyph name) into one. `module` is a path from the+ * package root.+ */+ adapter?: IconSetAdapter;+ /** Every icon in the set. */+ icons: IconSetIcon[];+}diff --git a/packages/cli/authoring/doctypes/load-contract.test.mjs b/packages/cli/authoring/doctypes/load-contract.test.mjsindex 3a4a8e3acc..d3b4ac73e9 100644--- a/packages/cli/authoring/doctypes/load-contract.test.mjs+++ b/packages/cli/authoring/doctypes/load-contract.test.mjs@@ -16,6 +16,7 @@ import {describe, expect, it} from 'vitest';import {parseDoc} from './parse.mjs';import {AuthoredDocKindSchema} from './_schema.mjs';import {doc as graphFieldsDoc} from './base/graph-fields.doc.mjs';+import {doc as iconDefinitionDoc} from './icon-definition/icon-definition.doc.mjs';import {problemsInTopic} from '../../foundation/discovery/docs-discovery.mjs';const HERE = path.dirname(fileURLToPath(import.meta.url));@@ -32,6 +33,7 @@ const LOCKS = {command: '_CommandDocDriftLock',enum: '_EnumDocDriftLock',namespace: '_NamespaceDocDriftLock',+ 'icon-definition': '_IconDefinitionDocDriftLock',};/** One valid example doc per kind, from the typed examples. */@@ -49,7 +51,12 @@ const EXAMPLES = Object.fromEntries(describe('load check vs published type', () => {it('locks every doc kind', () => {- const source = ['_schema.mjs', 'template/parse.mjs', 'theme/parse.mjs']+ const source = [+ '_schema.mjs',+ 'template/parse.mjs',+ 'theme/parse.mjs',+ 'icon-definition/parse.mjs',+ ].map(file => fs.readFileSync(path.join(HERE, file), 'utf8')).join('\n');expect(Object.keys(LOCKS).sort()).toEqual([...KINDS].sort());@@ -175,11 +182,17 @@ describe('unknown fields', () => {' docs accept',);const named = (/** @type {string} */ text) =>- [...text.matchAll(/`([a-z]+)`/g)].map(match => match[1]).sort();+ [...text.matchAll(/`([a-z][a-z-]*)`/g)].map(match => match[1]).sort();expect(named(kept)).toEqual([...keeps].sort());- expect(named(refused).filter(kind => KINDS.includes(kind))).toEqual(- KINDS.filter(kind => !keeps.includes(kind)).sort(),+ // The experimental icon-definition kind states its own policy in its+ // schema doc, on its experimental route (spec:AST-017 FR27).+ const stable = KINDS.filter(kind => kind !== 'icon-definition');+ expect(named(refused).filter(kind => stable.includes(kind))).toEqual(+ stable.filter(kind => !keeps.includes(kind)).sort(),);+ expect(keeps).not.toContain('icon-definition');+ const iconDefinitionNotes = JSON.stringify(iconDefinitionDoc.notes);+ expect(iconDefinitionNotes).toContain('refuses a field it does not know');});it("are refused inside a section's reference block, which a section takes", () => {diff --git a/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs b/packages/cli/authoring/doctypes/namespace/namespace.doc.mjsindex 1cffdb8c63..98a5ac890b 100644--- a/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs+++ b/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs@@ -77,6 +77,13 @@ export const doc = {description:'Provider-local rules that adopt otherwise-unplaced docs from a logical discovery group. They never scan a folder.',},+ {+ name: 'adopts[].source.packages',+ type: "'all'",+ stability: 'experimental',+ description:+ "Experimental: may change or be removed in a patch release. `'all'` adopts the group from every package, not only the namespace's own, and is read only on the CLI's own namespaces that are marked `stability: 'experimental'`.",+ },{name: 'blocks',type: '(ReferenceContentBlock | GraphContentBlock)[]',diff --git a/packages/cli/authoring/doctypes/namespace/type.ts b/packages/cli/authoring/doctypes/namespace/type.tsindex 3524c56958..809b5cbfed 100644--- a/packages/cli/authoring/doctypes/namespace/type.ts+++ b/packages/cli/authoring/doctypes/namespace/type.ts@@ -37,6 +37,13 @@ export interface NamespaceAdoptionSource {group: string;/** Optional subset of authored kinds from the group. */kinds?: AuthoredDocKind[];+ /**+ * Experimental: `all` adopts the group's docs from every package, not+ * only the namespace's own. Read only on the CLI's own namespaces marked+ * `stability: 'experimental'` (the icon definitions).+ * @experimental+ */+ packages?: 'all';}/**diff --git a/packages/cli/authoring/doctypes/parse.mjs b/packages/cli/authoring/doctypes/parse.mjsindex decc3a7cd4..2cf813ce6f 100644--- a/packages/cli/authoring/doctypes/parse.mjs+++ b/packages/cli/authoring/doctypes/parse.mjs@@ -5,7 +5,7 @@* into its typed shape (or throws a readable error), dispatching on the stamped* `type` and falling back to legacy shape-sniffing for unstamped docs. Its* acceptance set preserves the old permissive `ComponentDocSchema` while new- * stamped kinds, including `theme`, use their sealed parser.+ * stamped kinds, including `theme`, `icon-set`, and `icon-definition`, use their sealed parser.*/import {parseComponent} from './component/parse.mjs';@@ -17,6 +17,8 @@ import {parseCommand} from './command/parse.mjs';import {parseEnum} from './enum/parse.mjs';import {parseNamespace} from './namespace/parse.mjs';import {parseTheme} from './theme/parse.mjs';+import {parseIconSet} from './icon-set/parse.mjs';+import {parseIconDefinition} from './icon-definition/parse.mjs';import {parseLegacyDoc} from './legacy.mjs';/** @typedef {import('./types.js').ComponentDoc} ComponentDoc */@@ -29,6 +31,8 @@ import {parseLegacyDoc} from './legacy.mjs';/** @typedef {import('./types.js').EnumDoc} EnumDoc *//** @typedef {import('./types.js').NamespaceDoc} NamespaceDoc *//** @typedef {import('./types.js').ThemeDoc} ThemeDoc */+/** @typedef {import('./types.js').IconSetDoc} IconSetDoc */+/** @typedef {import('./types.js').IconDefinitionDoc} IconDefinitionDoc *//*** Validate an unknown loaded doc value into its typed shape, or throw.@@ -38,7 +42,7 @@ import {parseLegacyDoc} from './legacy.mjs';** @param {unknown} input* @param {string} [label]- * @returns {ComponentDoc | HookDoc | FunctionDoc | ReferenceDoc | TemplateDoc | SchemaDoc | CommandDoc | EnumDoc | NamespaceDoc | ThemeDoc}+ * @returns {ComponentDoc | HookDoc | FunctionDoc | ReferenceDoc | TemplateDoc | SchemaDoc | CommandDoc | EnumDoc | NamespaceDoc | ThemeDoc | IconSetDoc | IconDefinitionDoc}*/export function parseDoc(input, label = 'doc') {const type =@@ -66,6 +70,10 @@ export function parseDoc(input, label = 'doc') {return parseNamespace(input, label);case 'theme':return parseTheme(input, label);+ case 'icon-set':+ return parseIconSet(input, label);+ case 'icon-definition':+ return parseIconDefinition(input, label);case undefined:default:// 0.6.x shape-sniffed unknown stamps. Keep accepting them through thediff --git a/packages/cli/authoring/doctypes/schema/type.ts b/packages/cli/authoring/doctypes/schema/type.tsindex 3d6c2f1f90..8164b46a99 100644--- a/packages/cli/authoring/doctypes/schema/type.ts+++ b/packages/cli/authoring/doctypes/schema/type.ts@@ -28,6 +28,10 @@ export interface SchemaFieldDoc {example?: string;/** Deprecation reason, if the field is deprecated. */deprecated?: string;+ /** Set on a field of an experimental surface (spec:AST-017 FR27). The+ * schema's own section leaves it out; the experimental feature's docs,+ * under `astryx docs cli/experimental`, document it. */+ stability?: 'experimental';/** Nested object fields, for object-typed fields. */fields?: SchemaFieldDoc[];}diff --git a/packages/cli/authoring/doctypes/template/parse.mjs b/packages/cli/authoring/doctypes/template/parse.mjsindex 3208d80a26..dfc50355f4 100644--- a/packages/cli/authoring/doctypes/template/parse.mjs+++ b/packages/cli/authoring/doctypes/template/parse.mjs@@ -49,6 +49,17 @@ const baseTemplateFields = {componentsUsed: z.array(z.string()).optional(),preview: previewSchema.optional(),isReady: z.boolean().optional(),+ icons: z+ .record(+ z.string().regex(/^[$A-Z_a-z][$\w]*$/u, 'icons keys are imported names'),+ z+ .string()+ .regex(+ /^[a-z][a-zA-Z0-9]*$/u,+ 'icons values are icon definition names',+ ),+ )+ .optional(),scaffold: z.boolean().optional(),isHiddenFromOverview: z.boolean().optional(),registry: registryIdentitySchema.optional(),diff --git a/packages/cli/authoring/doctypes/template/template.doc.mjs b/packages/cli/authoring/doctypes/template/template.doc.mjsindex acc49b3ae7..99ac547ec2 100644--- a/packages/cli/authoring/doctypes/template/template.doc.mjs+++ b/packages/cli/authoring/doctypes/template/template.doc.mjs@@ -64,6 +64,13 @@ export const doc = {description:"Integration templates only: the exact id of the Core template this one replaces for unqualified lookup. Find it with `astryx --json template --list --package @astryxdesign/core`; the Core original stays selectable with `--package @astryxdesign/core`. A page replaces only a Core page and a block only a Core block. Needs @astryxdesign/cli 0.6.4 or later: earlier CLIs reject the field, drop that template, and hide the package's doc topics.",},+ {+ name: 'icons',+ type: 'Record<string, string>',+ stability: 'experimental',+ description:+ "The icon definition each icon the source imports draws, such as `{TrashIcon: 'delete'}`: a named import is keyed by the name it imports (`{Trash as TrashIcon}` is `Trash`), a default import by its local name (`import DeleteIcon from …` is `DeleteIcon`). When the project sets `experimental.iconSet`, `astryx template` (shown or copied) replaces each declared icon with the set's icon for that definition (`astryx docs cli/experimental/icon-definitions`) and reports every key as mapped or kept; an undeclared import is left alone.",+ },{name: 'isReady',type: 'boolean',diff --git a/packages/cli/authoring/doctypes/template/type.ts b/packages/cli/authoring/doctypes/template/type.tsindex 710f48cb27..a984db0228 100644--- a/packages/cli/authoring/doctypes/template/type.ts+++ b/packages/cli/authoring/doctypes/template/type.ts@@ -51,6 +51,16 @@ export interface BaseTemplateDoc extends AuthoredDocGraphFields {* isReady: false show as "(WIP)" in the gallery and CLI. */isReady?: boolean;+ /** The icon definition each icon the source imports draws+ * (`{TrashIcon: 'delete'}`), keyed by the name a named import reads+ * (`{Trash as TrashIcon}` is `Trash`) or a default import's local name+ * (`import DeleteIcon from …` is `DeleteIcon`). When the project has an+ * icon set, each declared icon is replaced by the set's icon for that+ * definition (`astryx docs cli/experimental/icon-definitions`), and every+ * key is reported as mapped or kept.+ * @experimental May change or be removed in a patch release. */+ icons?: Record<string, string>;+/** Whether this template is a scaffolding tool only (e.g. blank page).* Scaffold templates are available via the CLI but hidden from* browsable template galleries like the craft browser. */diff --git a/packages/cli/authoring/doctypes/types.ts b/packages/cli/authoring/doctypes/types.tsindex 6165f4cdd9..fee7d651bc 100644--- a/packages/cli/authoring/doctypes/types.ts+++ b/packages/cli/authoring/doctypes/types.ts@@ -3,7 +3,7 @@/*** @file Doc-type vocabulary barrel. Each kind's types live in one `type.ts`* under its folder (`base/` shared leaves, then `component/`, `hook/`,- * `reference/`, `template/`, `theme/`); this re-exports them as the full doc vocabulary+ * `reference/`, `template/`, `theme/`, `icon-set/`, `icon-definition/`); this re-exports them as the full doc vocabulary* behind `@astryxdesign/cli/authoring`.*/@@ -18,3 +18,5 @@ export type * from './schema/type.js';export type * from './command/type.js';export type * from './enum/type.js';export type * from './theme/type.js';+export type * from './icon-set/type.js';+export type * from './icon-definition/type.js';diff --git a/packages/cli/authoring/identity/type.ts b/packages/cli/authoring/identity/type.tsindex 8fa73bfce4..1f4d55df52 100644--- a/packages/cli/authoring/identity/type.ts+++ b/packages/cli/authoring/identity/type.ts@@ -14,6 +14,7 @@ import type {ComponentDoc} from '../doctypes/component/type.js';import type {EnumDoc} from '../doctypes/enum/type.js';import type {FunctionDoc} from '../doctypes/function/type.js';import type {HookDoc} from '../doctypes/hook/type.js';+import type {IconDefinitionDoc} from '../doctypes/icon-definition/type.js';import type {NamespaceDoc} from '../doctypes/namespace/type.js';import type {ReferenceDoc} from '../doctypes/reference/type.js';import type {SchemaDoc} from '../doctypes/schema/type.js';@@ -42,7 +43,11 @@ export type ProviderInstanceId = string & {/** Lowercase `sha256:<64 hex characters>` digest. */export type ContentDigest = string & {readonly [contentDigestBrand]: true};-/** Every stable artifact kind owned by a provider. */+/**+ * Every artifact kind owned by a provider, each with a stable identity. The+ * `icon-definition` kind is experimental (spec:AST-084): it may change or be+ * removed in a patch release.+ */export type ContributionKind =AuthoredDocKind | 'theme' | 'codemod' | 'agent-doc';@@ -73,7 +78,8 @@ export type AuthoredDoc =| SchemaDoc| CommandDoc| EnumDoc- | NamespaceDoc;+ | NamespaceDoc+ | IconDefinitionDoc;/** Provenance attached by discovery before compilation. */export interface AuthoredDocSource {@@ -103,7 +109,9 @@ export type AuthoredDocKindOf<TDoc extends AuthoredDoc> =? 'enum': TDoc extends NamespaceDoc? 'namespace'- : never;+ : TDoc extends IconDefinitionDoc+ ? 'icon-definition'+ : never;type DeepReadonly<Value> = Value extends (...args: never[]) => unknown? Valuediff --git a/packages/cli/authoring/index.d.ts b/packages/cli/authoring/index.d.tsindex c7d6759e51..9dda79baff 100644--- a/packages/cli/authoring/index.d.ts+++ b/packages/cli/authoring/index.d.ts@@ -34,6 +34,9 @@ export type {CommandDoc} from './doctypes/types.js'; // search.doc.mjs (CLIexport type {EnumDoc} from './doctypes/types.js'; // error-codes.doc.mjs (vocabulary)export type {NamespaceDoc} from './doctypes/types.js'; // cli.doc.mjs (hierarchy)export type {ThemeDoc} from './doctypes/types.js'; // oceanTheme.doc.mjs+export type {IconSetDoc} from './doctypes/types.js'; // outline.doc.mjs+export type {IconSetData} from './doctypes/types.js'; // outline.icons.json+export type {IconDefinitionDoc} from './doctypes/types.js'; // delete.doc.mjsexport type {AstryxConfig} from './config/type.js'; // astryx.config.{ts,mjs}export type {DebugEvent} from './debug/type.js'; // one recorded CLI runexport type {AstryxIntegration} from './integration/type.js'; // astryx.integration.{ts,mjs}@@ -70,6 +73,10 @@ export {parseCommand} from './doctypes/command/parse.mjs';export {parseEnum} from './doctypes/enum/parse.mjs';export {parseNamespace} from './doctypes/namespace/parse.mjs';export {parseTheme} from './doctypes/theme/parse.mjs';+/** @experimental Icon sets may change or be removed in a patch release. */+export {parseIconSet, parseIconSetData} from './doctypes/icon-set/parse.mjs';+/** @experimental Icon definitions may change or be removed in a patch release. */+export {parseIconDefinition} from './doctypes/icon-definition/parse.mjs';export {parseLegacyDoc} from './doctypes/legacy.mjs';export {parseConfig} from './config/parse.mjs';export {parseIntegration} from './integration/parse.mjs';@@ -166,6 +173,14 @@ export type {CommandOutsideProject,// enumEnumMemberDoc,+ // icon set+ IconSetDefault,+ IconSetIcon,+ IconSetMatch,+ IconSetMatchConfidence,+ IconSetSource,+ IconSetVariant,+ IconSetAdapter,} from './doctypes/types.js';export type {PostCodemodHook, DebugConfig} from './config/type.js';export type {diff --git a/packages/cli/authoring/index.mjs b/packages/cli/authoring/index.mjsindex 5698c0ca7e..cf36da7d48 100644--- a/packages/cli/authoring/index.mjs+++ b/packages/cli/authoring/index.mjs@@ -11,7 +11,7 @@* `type` directly.** Types (config, integration, codemod, and the doc vocabulary —- * component/hook/reference/template/theme) are re-exported via `./index.ts`.+ * component/hook/reference/template/theme/icon-set/icon-definition) are re-exported via `./index.ts`.*/export {parseConfig} from './config/parse.mjs';@@ -34,4 +34,8 @@ export {parseCommand} from './doctypes/command/parse.mjs';export {parseEnum} from './doctypes/enum/parse.mjs';export {parseNamespace} from './doctypes/namespace/parse.mjs';export {parseTheme} from './doctypes/theme/parse.mjs';+/** @experimental Icon sets may change or be removed in a patch release. */+export {parseIconSet, parseIconSetData} from './doctypes/icon-set/parse.mjs';+/** @experimental Icon definitions may change or be removed in a patch release. */+export {parseIconDefinition} from './doctypes/icon-definition/parse.mjs';export {parseLegacyDoc} from './doctypes/legacy.mjs';diff --git a/packages/cli/authoring/integration/integration.doc.mjs b/packages/cli/authoring/integration/integration.doc.mjsindex 9cb9ef6aef..d756f68d15 100644--- a/packages/cli/authoring/integration/integration.doc.mjs+++ b/packages/cli/authoring/integration/integration.doc.mjs@@ -61,6 +61,23 @@ export const doc = {'The folder that holds your themes, relative to package.json, with one folder per theme. Each theme folder has the theme source and a matching .doc.mjs file with the same name. Installed themes show up in `{@command theme list}`; `theme add` imports their built package exports, and `theme eject` creates an editable local fork.',example: "'./themes'",},+ {+ name: 'experimental',+ type: '{ iconSets?: string }',+ stability: 'experimental',+ description:+ 'Experimental contribution roots: they may change or be removed in a patch release.',+ fields: [+ {+ name: 'experimental.iconSets',+ type: 'string',+ stability: 'experimental',+ description:+ "Experimental: may change or be removed in a patch release. The folder that holds your icon sets, relative to package.json, with one folder per set. Each set folder has a matching `<name>.doc.mjs` IconSetDoc and a `<name>.icons.json` data file. Installed sets answer `astryx experimental icon`; a project that sets `experimental.iconSet` gets copied templates in that set's icons.",+ example: "'./icon-sets'",+ },+ ],+ },{name: 'agentDocs',type: '{ append?: readonly string[] }',diff --git a/packages/cli/authoring/integration/schema.mjs b/packages/cli/authoring/integration/schema.mjsindex 768d2bde52..71c423bb1a 100644--- a/packages/cli/authoring/integration/schema.mjs+++ b/packages/cli/authoring/integration/schema.mjs@@ -93,6 +93,10 @@ export const integrationBaseSchema = z.object({codemods: z.string().optional(),docs: z.string().optional(),themes: z.string().optional(),+ // Experimental roots (spec:AST-017 FR27). An unknown key inside is+ // stripped, as unknown top-level keys are, so a newer CLI's experiment+ // never fails an older CLI's parse.+ experimental: z.object({iconSets: z.string().optional()}).optional(),issuesUrl: z.string().url().optional(),docsiteUrl: z.string().url().optional(),});diff --git a/packages/cli/authoring/integration/type.ts b/packages/cli/authoring/integration/type.tsindex 2740c09a97..bc65f7c6eb 100644--- a/packages/cli/authoring/integration/type.ts+++ b/packages/cli/authoring/integration/type.ts@@ -38,6 +38,14 @@ export interface AstryxIntegration {* lower-kebab theme directory contains a source module and mandatory* same-stem, strongly typed `.doc.mjs` descriptor. */themes?: string;+ /** Experimental contribution roots (spec:AST-017 FR27).+ * @experimental Their shape may change or be removed in a patch release. */+ experimental?: {+ /** Relative path to the icon-set root (spec:AST-084). Each lower-kebab+ * directory under it is one icon set holding a strongly typed+ * `<name>.doc.mjs` IconSetDoc and its `<name>.icons.json` data file. */+ iconSets?: string;+ };/** Static package guidance appended to the CLI-owned managed agent block. */agentDocs?: {append?: readonly string[];diff --git a/packages/cli/clients/cli/commands/discover.icon-sets.test.mjs b/packages/cli/clients/cli/commands/discover.icon-sets.test.mjsnew file mode 100644index 0000000000..cf25a124e4--- /dev/null+++ b/packages/cli/clients/cli/commands/discover.icon-sets.test.mjs@@ -0,0 +1,133 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx discover` lists icon sets as their own kind (spec:AST-084+ * FR16, spec:AST-051 FR1, FR3, FR5): the package list, `--type icon-set`, a+ * search, and the item page, over the synthetic icon-set fixture.+ */++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 {runCli} from '../../../test-utils/run-cli.mjs';+import {+ glyphsData,+ writeIconSetProject,+} from '../../../test-utils/icon-set-fixture.mjs';++/** @type {string} */+let tmp;+/** @type {string} */+let cwd;+beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-discover-icons-'));+ cwd = writeIconSetProject(tmp, {+ config: {+ integrations: ['@acme/glyphs'],+ experimental: {iconSet: 'glyphs'},+ },+ });+});+afterEach(() => {+ fs.rmSync(tmp, {recursive: true, force: true});+});++/** @param {string[]} args */+async function json(args) {+ const res = await runCli([...args, '--json'], cwd);+ expect(res.code, res.stderr).toBe(0);+ return JSON.parse(res.stdout);+}++describe('discover icon sets', () => {+ it('lists a package’s icon sets under iconSets, and --type icon-set keeps them', async () => {+ const all = await json(['discover']);+ expect(all.data).toEqual([+ expect.objectContaining({name: '@acme/glyphs', iconSets: ['glyphs']}),+ ]);+ const only = await json(['discover', '--type', 'icon-set']);+ expect(only.data.map((/** @type {any} */ e) => e.name)).toEqual([+ '@acme/glyphs',+ ]);+ const none = await json(['discover', '--type', 'theme']);+ expect(none.data).toEqual([]);+ });++ it('shows the item page with description, license, count, default, definitions, and the icon command', async () => {+ const page = await json(['discover', '@acme/glyphs/glyphs']);+ expect(page).toMatchObject({+ type: 'discover.item',+ // The envelope names the package the answer comes from.+ package: '@acme/glyphs',+ data: {+ package: '@acme/glyphs',+ kind: 'icon-set',+ name: 'glyphs',+ license: expect.any(String),+ iconCount: glyphsData().icons.length,+ default: {variant: 'outline'},+ definitions: ['close', 'search'],+ command: 'astryx experimental icon <words> --set @acme/glyphs/glyphs',+ installed: true,+ },+ });+ expect(typeof page.data.summary).toBe('string');++ const text = await runCli(['discover', '@acme/glyphs/glyphs'], cwd);+ expect(text.code).toBe(0);+ expect(text.stdout).toMatch(/kind: +icon-set/);+ expect(text.stdout).toContain(+ 'astryx experimental icon <words> --set @acme/glyphs/glyphs',+ );+ });++ it('finds the set by name in a search, and individual icons are not discover items', async () => {+ const found = await json(['discover', 'glyphs', '--type', 'icon-set']);+ expect(found.data.matches).toEqual([+ expect.objectContaining({+ package: '@acme/glyphs',+ component: 'glyphs',+ kind: 'icon-set',+ }),+ ]);+ const icon = await runCli(+ ['discover', 'trash', '--type', 'icon-set', '--json'],+ cwd,+ );+ expect(icon.code).not.toBe(0);+ });++ it('refuses an unknown --type and names icon-set among the kinds', async () => {+ const res = await runCli(['discover', '--type', 'icons', '--json'], cwd);+ expect(res.code).not.toBe(0);+ expect(res.stdout + res.stderr).toContain('icon-set');+ });+});++describe('discover and a withdrawn icon set', () => {+ it('lists no withdrawn set, and its item page says withdrawn and why', async () => {+ const dir = writeIconSetProject(path.join(tmp, 'withdrawn'), {+ packages: [{data: '{nope'}],+ config: {+ integrations: ['@acme/glyphs'],+ experimental: {iconSet: 'glyphs'},+ },+ });+ const all = await runCli(['discover', '--json'], dir);+ const [entry] = JSON.parse(all.stdout).data;+ expect(entry.name).toBe('@acme/glyphs');+ expect(entry.iconSets ?? []).toEqual([]);+ expect(all.stdout).not.toContain('withdrawnIconSets');+ const page = await runCli(+ ['discover', '@acme/glyphs/glyphs', '--json'],+ dir,+ );+ expect(page.code).toBe(1);+ const body = JSON.parse(page.stdout);+ expect(body.code).toBe('ERR_UNKNOWN_COMPONENT');+ expect(body.error).toMatch(+ /Icon set "glyphs" in @acme\/glyphs is installed but withdrawn: .*not valid JSON/,+ );+ });+});diff --git a/packages/cli/clients/cli/commands/discover.mjs b/packages/cli/clients/cli/commands/discover.mjsindex c53c9606cb..565f1669ee 100644--- a/packages/cli/clients/cli/commands/discover.mjs+++ b/packages/cli/clients/cli/commands/discover.mjs@@ -52,6 +52,7 @@ const KIND_PLURALS = {theme: 'themes',codemod: 'codemods','agent-doc': 'agent docs',+ 'icon-set': 'icon sets',};// The list fields that hold item names, summarized in the package list.@@ -62,6 +63,7 @@ const ITEM_FIELDS = ['themes','codemods','agentDocs',+ 'iconSets',];/**@@ -81,6 +83,7 @@ const RESULT_KINDS = {theme: 'theme',codemod: 'migration','agent-doc': 'doc',+ 'icon-set': 'mixed',};/**diff --git a/packages/cli/clients/cli/commands/docs.mjs b/packages/cli/clients/cli/commands/docs.mjsindex bdaae5f6da..6669e014ce 100644--- a/packages/cli/clients/cli/commands/docs.mjs+++ b/packages/cli/clients/cli/commands/docs.mjs@@ -500,7 +500,7 @@ function emitIndex(index, owner, run) {* name (`assert-response assertResponse()`).* @param {import('../../../api/docs/docs.type.mjs').DocsNodeChild} child* @param {string} owner the package that owns the namespace- * @returns {{name: string, summary: string}}+ * @returns {{name: string, summary: string, experimental: boolean}}*/function childRow(child, owner) {const titleAddsIdentity =@@ -510,10 +510,18 @@ function childRow(child, owner) {return {// A child another package owns says which one.name: child.package === owner ? child.name : `${child.name} (${child.package})`,+ // An experimental child is marked as help marks an experimental command,+ // unless its own summary already opens by saying so.summary: prefixCliCommands(- titleAddsIdentity ? `${child.title}: ${child.summary}` : child.summary,+ `${+ child.stability === 'experimental' &&+ !/^experimental\b/iu.test(child.summary)+ ? '[experimental] '+ : ''+ }${titleAddsIdentity ? `${child.title}: ${child.summary}` : child.summary}`,getCliInvocation(),),+ experimental: child.stability === 'experimental',};}@@ -551,10 +559,19 @@ function emitNode(node, detail, run) {...(node.slots.length === 1 && slot.title === node.title? []: [section(slot.title)]),- records(slot.children.map(child => childRow(child, node.package)), {- fields: ['name', 'summary'],- layout: 'inline',- }),+ records(+ slot.children.map(child => childRow(child, node.package)),+ {+ fields: ['name', 'summary'],+ layout: 'inline',+ // Stable rows set the column, so an experimental entry changes no+ // stable line (spec:AST-017 FR27); a long experimental name+ // overhangs. A slot of experimental entries only sizes from them.+ sizesColumn: row =>+ !row.experimental ||+ slot.children.every(child => child.stability === 'experimental'),+ },+ ),]),text([diff --git a/packages/cli/clients/cli/commands/doctor-integration.test.mjs b/packages/cli/clients/cli/commands/doctor-integration.test.mjsindex eaa33fb554..b74e8e3652 100644--- a/packages/cli/clients/cli/commands/doctor-integration.test.mjs+++ b/packages/cli/clients/cli/commands/doctor-integration.test.mjs@@ -290,6 +290,44 @@ describe('doctor integration — command', () => {expect(process.exitCode).toBeUndefined();});+ it('validate type-checks each icon set descriptor against IconSetDoc', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: '@acme/icons', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ "export default {experimental: {iconSets: './icon-sets'}};\n",+ );+ const dir = path.join(tmpDir, 'icon-sets', 'outline');+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'outline.doc.mjs'),+ "export default {type: 'icon-set', name: 'outline', displayName: 'Outline', description: 'D', maintained: true, license: 'MIT'};\n",+ );+ fs.writeFileSync(+ path.join(dir, 'outline.icons.json'),+ JSON.stringify({schemaVersion: 1, module: '@acme/icons', icons: []}),+ );+ process.chdir(tmpDir);++ await createProgram().parseAsync([+ 'node',+ 'astryx',+ 'doctor',+ 'integration',+ 'validate',+ '--json',+ ]);++ const result = JSON.parse(logCalls.join('\n'));+ expect(result.data.docTypes).toMatchObject({+ status: 'checked',+ docs: 1,+ findings: [],+ });+ });+it('validate says there is no doc to type-check, rather than asking for TypeScript', async () => {const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-no-docs-'));try {diff --git a/packages/cli/clients/cli/commands/doctor.mjs b/packages/cli/clients/cli/commands/doctor.mjsindex d473e38577..9e46e02888 100644--- a/packages/cli/clients/cli/commands/doctor.mjs+++ b/packages/cli/clients/cli/commands/doctor.mjs@@ -22,7 +22,14 @@ import {validateIntegration,} from '../../../api/integration/validate-integration.mjs';import {jsonOut} from '../../../foundation/response/json.mjs';-import {emit, section, record, records, text} from '../formatters/index.mjs';+import {+ emit,+ list,+ section,+ record,+ records,+ text,+} from '../formatters/index.mjs';import {defineCommand} from '../lib/define-command.mjs';import {doc as doctorCommand} from './doctor.doc.mjs';import {doc as doctorIntegrationGroup} from './doctor-integration.doc.mjs';@@ -87,16 +94,56 @@ function printHuman(report) {/*** @param {Array<{code: string, severity: string, message: string}>} issues+ * @param {Set<string>} [seen] issues an earlier check printed* @returns {import('../formatters/index.mjs').Block[]}*/-function issueBlocks(issues) {- if (issues.length === 0) return [];+function issueBlocks(issues, seen) {+ const fresh = unseen(issues, seen);+ if (fresh.length === 0) return alsoApply(issues, fresh);return [section('Integration issues'),- records(issues, {+ records(fresh, {fields: ['severity', 'code', 'message', 'fix', 'file', 'line'],format: {severity: statusToken},}),+ ...alsoApply(issues, fresh),+ ];+}++/**+ * The issues not printed yet, recording them as printed. `integration+ * check` runs several checks that each report an experimental icon set's+ * package-wide issues; each is printed once, under the first check. Every+ * other issue prints under each check that reports it, as it always has.+ * @template {{code: string, message: string}} T+ * @param {T[]} issues+ * @param {Set<string> | undefined} seen+ * @returns {T[]}+ */+function unseen(issues, seen) {+ if (!seen) return issues;+ const once = (/** @type {T} */ issue) => /icon/u.test(issue.code);+ const fresh = issues.filter(+ issue => !once(issue) || !seen.has(`${issue.code}\0${issue.message}`),+ );+ for (const issue of issues) {+ if (once(issue)) seen.add(`${issue.code}\0${issue.message}`);+ }+ return fresh;+}++/**+ * One line naming the issues an earlier check already printed.+ * @param {unknown[]} issues+ * @param {unknown[]} fresh+ */+function alsoApply(issues, fresh) {+ const repeated = issues.length - fresh.length;+ if (repeated === 0) return [];+ return [+ text(+ `${repeated} package-wide issue${repeated === 1 ? '' : 's'} listed above also appl${repeated === 1 ? 'ies' : 'y'} here.`,+ ),];}@@ -209,8 +256,9 @@ function blockComponentsBlocks(report) {/*** @param {import('../../../api/integration/validate-integration.type.mjs').ValidateIntegrationResponse['data']} data+ * @param {Set<string>} [seen] issues an earlier check printed, printed once*/-function printIntegrationValidation(data) {+function printIntegrationValidation(data, seen) {const {warnings, errors} = summarizeIssues(data.issues);emit(section(@@ -218,7 +266,7 @@ function printIntegrationValidation(data) {),...(data.issues.length > 0? [- records(data.issues, {+ records(unseen(data.issues, seen), {fields: ['severity', 'code', 'message', 'fix', 'file', 'line'],format: {severity: statusToken},}),@@ -235,6 +283,8 @@ function printIntegrationValidation(data) {...docTypesBlocks(data.docTypes, errors > 0),...docNamesBlocks(data.docNames),...blockComponentsBlocks(data.blockComponents),+ ...iconSetCoverageBlocks(data.iconSets),+ ...olderCliNoteBlocks(data.olderCliNotes),...(data.exampleAssets && data.exampleAssets.unchecked.length > 0? [text(@@ -258,15 +308,100 @@ function printIntegrationValidation(data) {);}+/**+ * The optional icon definitions each icon set leaves unmapped, and the icons+ * that fit (spec:AST-084 FR15). Listed, never counted: nothing here fails.+ * @param {import('../../../api/integration/validate-integration.type.mjs').IconSetCoverage[] | undefined} sets+ * @returns {import('../formatters/index.mjs').Block[]}+ */+function iconSetCoverageBlocks(sets) {+ const listed = (sets ?? []).filter(+ each => each.unmappedDefinitions.length > 0 || each.suggestions.length > 0,+ );+ const unchecked = (sets ?? []).flatMap(each =>+ (each.unchecked ?? []).map(item => ({+ set: each.set,+ item: item.icon+ ? `icon ${item.icon}`+ : item.adapter+ ? `adapter ${item.adapter}`+ : `theme map ${item.entry}`,+ reason: item.reason,+ })),+ );+ return [+ ...(unchecked.length > 0+ ? [+ section('Not checked'),+ records(unchecked, {fields: ['set', 'item', 'reason']}),+ text(+ 'The icon-set checks could not judge these; they are never counted and never fail a check.',+ ),+ ]+ : []),+ ...unmappedBlocks(listed),+ ];+}++/**+ * @param {import('../../../api/integration/validate-integration.type.mjs').IconSetCoverage[]} listed+ * @returns {import('../formatters/index.mjs').Block[]}+ */+function unmappedBlocks(listed) {+ if (listed.length === 0) return [];+ return [+ section('Unmapped icon definitions (optional)'),+ records(+ listed.map(each => ({+ set: each.set,+ unmapped: each.unmappedDefinitions.length,+ definitions: each.unmappedDefinitions+ .map(definition => definition.name)+ .join(', '),+ })),+ {fields: ['set', 'unmapped', 'definitions']},+ ),+ ...listed.flatMap(each =>+ each.suggestions.length > 0+ ? [+ list(+ each.suggestions.map(+ ({definition, icon}) =>+ `astryx experimental icon map ${definition} ${icon}${listed.length === 1 ? '' : ` --set ${each.set}`}`,+ ),+ ),+ ]+ : [],+ ),+ text(+ 'Mapping these is optional and never fails a check. --json lists each with its description and words.',+ ),+ ];+}++/**+ * Descriptors an older CLI drops: listed, never counted.+ * @param {import('../../../api/integration/validate-integration.type.mjs').OlderCliNote[] | undefined} notes+ * @returns {import('../formatters/index.mjs').Block[]}+ */+function olderCliNoteBlocks(notes) {+ if (!notes || notes.length === 0) return [];+ return [+ section('Notes for older CLIs'),+ records(notes, {fields: ['file', 'kind', 'message']}),+ ];+}+/*** @param {import('../../../api/integration/authoring-checks.type.mjs').IntegrationTemplateConflictResponse['data']} data+ * @param {Set<string>} [seen] issues an earlier check printed, printed once*/-function printTemplateConflicts(data) {+function printTemplateConflicts(data, seen) {const output = [section(`Checking integration templates: ${integrationLabel(data) ?? '(local package)'}`,),- ...issueBlocks(data.issues),+ ...issueBlocks(data.issues, seen),];if (data.conflicts.length === 0 && data.issues.length === 0) {output.push(text('[ok] No template ids conflict with Core.'));@@ -406,13 +541,14 @@ function propDriftBlocks(report, failed) {/*** @param {import('../../../api/integration/authoring-checks.type.mjs').IntegrationComponentConflictResponse['data']} data+ * @param {Set<string>} [seen] issues an earlier check printed, printed once*/-function printComponentConflicts(data) {+function printComponentConflicts(data, seen) {const output = [section(`Checking integration components: ${integrationLabel(data) ?? '(local package)'}`,),- ...issueBlocks(data.issues),+ ...issueBlocks(data.issues, seen),];// An [ok] after a failed check reads as a pass: say nothing it could not check.const failed = data.issues.some(issue => issue.severity === 'error');@@ -443,8 +579,9 @@ function printComponentConflicts(data) {/*** @param {import('../../../api/integration/authoring-checks.type.mjs').IntegrationDocConflictResponse['data']} data+ * @param {Set<string>} [seen] issues an earlier check printed, printed once*/-function printDocConflicts(data) {+function printDocConflicts(data, seen) {const output = [section(`Checking integration docs: ${integrationLabel(data) ?? '(local package)'}`,@@ -458,6 +595,7 @@ function printDocConflicts(data) {issue.code !== 'doc_fluff' &&issue.code !== 'stray_doc_pointer',),+ seen,),];if (@@ -561,16 +699,17 @@ function printDocConflicts(data) {* Print one `doctor integration` check's result as its own subcommand prints* it. `astryx integration check` prints each check it runs through this.* @param {import('../../../api/integration/integration-check.type.mjs').IntegrationCheckResponse} response+ * @param {Set<string>} [seen] issues an earlier check printed, printed once*/-export function printIntegrationCheckResponse(response) {+export function printIntegrationCheckResponse(response, seen) {if (response.type === 'integration.validate') {- printIntegrationValidation(response.data);+ printIntegrationValidation(response.data, seen);} else if (response.type === 'integration.component-conflicts') {- printComponentConflicts(response.data);+ printComponentConflicts(response.data, seen);} else if (response.type === 'integration.template-conflicts') {- printTemplateConflicts(response.data);+ printTemplateConflicts(response.data, seen);} else {- printDocConflicts(response.data);+ printDocConflicts(response.data, seen);}}diff --git a/packages/cli/clients/cli/commands/experimental-icon-add.doc.mjs b/packages/cli/clients/cli/commands/experimental-icon-add.doc.mjsnew file mode 100644index 0000000000..600bfe19b5--- /dev/null+++ b/packages/cli/clients/cli/commands/experimental-icon-add.doc.mjs@@ -0,0 +1,105 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file CommandDoc for `astryx experimental icon add`. */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'experimental icon add',+ displayName: 'astryx experimental icon add',+ namespace: 'cli/commands',+ stability: 'experimental',+ summary: 'Register one icon you chose from a library in your icon set',+ description:+ "Run inside an icon-set package. You pick the export; the CLI proves it is a component of --from, read without running it, and never searches the library. Without a definition it lists the icon definitions that fit and the command for each. With --definition it adds the icon and maps the definition to it; --new-definition first adds your set's own definition. Experimental: it may change or be removed in a patch release.",+ fn: 'iconAdd',+ args: [{name: 'export', param: 'exportName', required: true}],+ options: [+ {+ flag: '--from <module>',+ param: 'options.from',+ description:+ 'The module the icon is exported from: a package, a subpath, or a relative path this package exports',+ },+ {+ flag: '--definition <name>',+ param: 'options.definition',+ description: 'Map the icon to this icon definition',+ },+ {+ flag: '--new-definition <name>',+ param: 'options.newDefinition',+ description:+ "Add your set's own definition, then map the icon to it; needs --description and --words",+ },+ {+ flag: '--description <text>',+ param: 'options.description',+ description: 'With --new-definition: what the icon is for',+ },+ {+ flag: '--words <list>',+ param: 'options.words',+ description:+ 'With --new-definition: comma-separated words people search for',+ },+ {+ flag: '--default',+ param: 'options.useDefault',+ description:+ "The module's default export is the icon; your set's module must re-export it under <export>",+ },+ {+ flag: '--variant <name>',+ param: 'options.variant',+ description:+ "Add the export as this variant of an existing icon: one of the set's declared variants, such as solid",+ },+ {+ flag: '--id <id>',+ param: 'options.id',+ description: "The icon's id, instead of the one its name gives",+ },+ {+ flag: '--set <name>',+ param: 'options.set',+ description: 'The set to edit, when the package ships several',+ },+ ],+ examples: [+ {+ label: 'Which definitions fit',+ cli: 'astryx experimental icon add Bin --from @acme/glyph-library',+ },+ {+ label: 'Add and map',+ cli: 'astryx experimental icon add Bin --from @acme/glyph-library --definition delete',+ },+ {+ label: 'Add your own definition',+ cli: "astryx experimental icon add RotateCw --from @acme/glyph-library --new-definition rotate --description 'Rotate an image or shape.' --words turn,spin",+ },+ {+ label: 'Add a solid variant',+ cli: 'astryx experimental icon add Bin --from @acme/glyph-library/solid --id bin --variant solid',+ },+ ],+ outsideProject: 'refuse',+ exitCodes: [+ {+ code: 0,+ when: 'the icon is added, already present, or the matching definitions are listed',+ },+ {+ code: 1,+ when: 'the export is missing or is data, the definition is unknown, the id is taken, or the variant is not one the set declares',+ },+ ],+ related: ['experimental icon map', 'integration add', 'integration check'],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a project, with no package.json in the folder or above it, experimental icon add writes nothing and stops with `ERR_PROJECT_REQUIRED`; run it in the icon-set package. In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:problems}.",+ },+ ],+};diff --git a/packages/cli/clients/cli/commands/experimental-icon-map.doc.mjs b/packages/cli/clients/cli/commands/experimental-icon-map.doc.mjsnew file mode 100644index 0000000000..04d316d63b--- /dev/null+++ b/packages/cli/clients/cli/commands/experimental-icon-map.doc.mjs@@ -0,0 +1,57 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file CommandDoc for `astryx experimental icon map`. */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'experimental icon map',+ displayName: 'astryx experimental icon map',+ namespace: 'cli/commands',+ stability: 'experimental',+ summary: 'Register which icon of your set draws an icon definition',+ description:+ "Run inside an icon-set package. Sets `map[<definition>] = <icon>` in the set's data file; `integration check` prints these commands for definitions your set already has a fitting icon for. Experimental: it may change or be removed in a patch release.",+ fn: 'iconMap',+ args: [+ {name: 'definition', param: 'definition', required: true},+ {name: 'icon', param: 'icon', required: false},+ ],+ options: [+ {+ flag: '--set <name>',+ param: 'options.set',+ description: 'The set to edit, when the package ships several',+ },+ {+ flag: '--remove',+ param: 'options.remove',+ description: "Remove the definition's entry; takes no icon",+ },+ ],+ examples: [+ {+ label: 'Map a definition',+ cli: 'astryx experimental icon map delete trash',+ },+ {+ label: 'Remove an entry',+ cli: 'astryx experimental icon map delete --remove',+ },+ ],+ outsideProject: 'refuse',+ exitCodes: [+ {code: 0, when: 'the entry is written, removed, or already as asked'},+ {+ code: 1,+ when: 'the definition is unknown, the set has no such icon, or no set is found',+ },+ ],+ related: ['experimental icon add', 'integration add', 'integration check'],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a project, with no package.json in the folder or above it, experimental icon map writes nothing and stops with `ERR_PROJECT_REQUIRED`; run it in the icon-set package. In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:problems}.",+ },+ ],+};diff --git a/packages/cli/clients/cli/commands/experimental-icon-new-definition.doc.mjs b/packages/cli/clients/cli/commands/experimental-icon-new-definition.doc.mjsnew file mode 100644index 0000000000..c6ce95991e--- /dev/null+++ b/packages/cli/clients/cli/commands/experimental-icon-new-definition.doc.mjs@@ -0,0 +1,72 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file CommandDoc for `astryx experimental icon new-definition`. */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'experimental icon new-definition',+ displayName: 'astryx experimental icon new-definition',+ namespace: 'cli/commands',+ stability: 'experimental',+ summary: "Add your icon set's own icon definition",+ description:+ "Run inside an icon-set package. Writes one icon definition file for a meaning Astryx's definitions do not cover, and with --icon maps it to an icon of the set. Experimental: it may change or be removed in a patch release.",+ fn: 'iconNewDefinition',+ args: [+ {+ name: 'name',+ param: 'name',+ required: true,+ description: 'The definition name, in camelCase (rocketLaunch)',+ },+ ],+ options: [+ {+ flag: '--dry-run',+ param: 'options.dryRun',+ description: 'Validate and show planned writes without changing files',+ },+ {+ flag: '--set <name>',+ param: 'options.set',+ description: 'The icon set to add it to, when the package ships several',+ },+ {+ flag: '--description <text>',+ param: 'options.description',+ description: 'One sentence on what an icon with this definition is for',+ },+ {+ flag: '--words <list>',+ param: 'options.words',+ description: 'Comma-separated words people search for',+ },+ {+ flag: '--icon <id>',+ param: 'options.icon',+ description: 'Also map it to this icon of the set (its `map` entry)',+ },+ ],+ examples: [+ {+ label: "Add a set's own icon definition",+ cli: "astryx experimental icon new-definition rotate --description 'Rotate an image or shape.' --words turn,spin --icon rotate-cw",+ },+ ],+ outsideProject: 'refuse',+ exitCodes: [+ {code: 0, when: 'the definition is written or the dry run succeeds'},+ {+ code: 1,+ when: 'the name is invalid or taken, the description or words are missing, or the set or icon is not found',+ },+ ],+ related: ['experimental icon map', 'experimental icon add'],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a project, with no package.json in the folder or above it, experimental icon new-definition writes nothing and stops with `ERR_PROJECT_REQUIRED`; run it in the icon-set package. In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:problems}.",+ },+ ],+};diff --git a/packages/cli/clients/cli/commands/experimental-icon-new-set.doc.mjs b/packages/cli/clients/cli/commands/experimental-icon-new-set.doc.mjsnew file mode 100644index 0000000000..199fdb01a1--- /dev/null+++ b/packages/cli/clients/cli/commands/experimental-icon-new-set.doc.mjs@@ -0,0 +1,76 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file CommandDoc for `astryx experimental icon new-set`. */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'experimental icon new-set',+ displayName: 'astryx experimental icon new-set',+ namespace: 'cli/commands',+ stability: 'experimental',+ summary: 'Start an icon set in your integration package',+ description:+ "Run inside an integration package. Writes the set's folder with its descriptor, its data file, and its generated module, and declares the manifest's `experimental.iconSets` root on first use. With --from it wraps every icon component of a library; run it again to refresh. Experimental: it may change or be removed in a patch release.",+ fn: 'iconNewSet',+ args: [+ {+ name: 'name',+ param: 'name',+ required: true,+ description: 'The set name, in lowercase kebab-case (outline)',+ },+ ],+ options: [+ {+ flag: '--dry-run',+ param: 'options.dryRun',+ description: 'Validate and show planned writes without changing files',+ },+ {+ flag: '--from <module>',+ param: 'options.from',+ description:+ 'A module whose every icon component the set wraps (a package, a subpath, or a ./ path); run again to refresh',+ },+ {+ flag: '--exclude <names>',+ param: 'options.exclude',+ description:+ 'With --from: comma-separated export names of the library that are not icons',+ },+ ],+ examples: [+ {+ label: 'Start an icon set',+ cli: 'astryx experimental icon new-set outline',+ },+ {+ label: 'Wrap a whole icon library',+ cli: 'astryx experimental icon new-set outline --from @acme/glyph-library',+ },+ {+ label: 'Preview the files',+ cli: 'astryx experimental icon new-set outline --dry-run --json',+ },+ ],+ outsideProject: 'refuse',+ exitCodes: [+ {code: 0, when: 'the set is written or the dry run succeeds'},+ {+ code: 1,+ when: 'the name, options, package, or target files are invalid or conflict',+ },+ ],+ related: [+ 'experimental icon add',+ 'experimental icon new-definition',+ 'integration check',+ ],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a project, with no package.json in the folder or above it, experimental icon new-set writes nothing and stops with `ERR_PROJECT_REQUIRED`; run it in the integration package. In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:problems}.",+ },+ ],+};diff --git a/packages/cli/clients/cli/commands/experimental-icon-use.doc.mjs b/packages/cli/clients/cli/commands/experimental-icon-use.doc.mjsnew file mode 100644index 0000000000..c7c0ae547a--- /dev/null+++ b/packages/cli/clients/cli/commands/experimental-icon-use.doc.mjs@@ -0,0 +1,42 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file CommandDoc for `astryx experimental icon use`. */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'experimental icon use',+ displayName: 'astryx experimental icon use',+ namespace: 'cli/commands',+ stability: 'experimental',+ summary: "Choose the project's icon set",+ description:+ "Writes `experimental.iconSet` in astryx.config, so copied templates and blocks use that set's icons. The set must be installed. Experimental: it may change or be removed in a patch release.",+ fn: 'iconUse',+ args: [{name: 'set', param: 'set', required: true}],+ examples: [+ {label: 'Use a set', cli: 'astryx experimental icon use outline'},+ {+ label: 'Name its package',+ cli: 'astryx experimental icon use @acme/icons/outline',+ },+ ],+ outsideProject: 'refuse',+ exitCodes: [+ {+ code: 0,+ when: 'experimental.iconSet is written, or already names the set',+ },+ {+ code: 1,+ when: 'the set is not installed, two packages ship it, the config cannot be updated (not a static object literal, or it spreads another object, which you then edit by hand), or the config is protected (a symbolic link, or marked generated, vendored, or ignored: `ERR_CODEMOD_PROTECTED`, naming the declaration)',+ },+ ],+ related: ['experimental icon', 'template'],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a project, with no package.json in the folder or above it, experimental icon use writes nothing and stops with `ERR_PROJECT_REQUIRED`; run it in the app project. In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:problems}.",+ },+ ],+};diff --git a/packages/cli/clients/cli/commands/experimental-icon.doc.mjs b/packages/cli/clients/cli/commands/experimental-icon.doc.mjsnew file mode 100644index 0000000000..ae2d74798a--- /dev/null+++ b/packages/cli/clients/cli/commands/experimental-icon.doc.mjs@@ -0,0 +1,68 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CommandDoc for `astryx experimental icon` (AST-084 FR6, FR7). The terminal binding+ * of the `icon()` function (referenced via `fn`).+ * @position packages/cli/clients/cli/commands — command documentation+ */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'experimental icon',+ displayName: 'astryx experimental icon',+ namespace: 'cli/commands',+ stability: 'experimental',+ summary:+ 'Find an icon by meaning in the installed icon sets, with its import line',+ description:+ "Terminal front-end to icon(): searches every installed icon set's data file by meaning and prints each match's import line. `<set>/<id>` reads one icon with every variant's import line; --list lists the installed sets and how many icon definitions each one maps. The subcommands author a set: `new-set` starts one in an integration package, `new-definition` adds the set's own icon definition, `add` registers an icon from a library, `map` points an icon definition at an icon, and `use` makes a set the project's. Experimental: it may change or be removed in a patch release.",+ fn: 'icon',+ // `new-set` and `new-definition` start a set and its own definitions,+ // `add` registers an icon, `map` edits a map entry, and `use` picks the+ // project's icon set.+ subcommands: ['new-set', 'new-definition', 'add', 'map', 'use'],+ // Every word after `icon` is the query: `astryx experimental icon arrow up`+ // searches for+ // "arrow up", with no quotes needed.+ args: [{name: 'query', param: 'query', required: false, variadic: true}],+ options: [+ {+ flag: '--list',+ param: 'options.list',+ description:+ 'List the installed icon sets and do nothing else; a query is refused',+ },+ {+ flag: '--set <name>',+ param: 'options.set',+ description: 'Search one set, by name or <package>/<set>',+ },+ {+ flag: '--limit <n>',+ param: 'options.limit',+ description: 'Max number of matches, a positive integer (default 10)',+ },+ ],+ examples: [+ {label: 'Find by meaning', cli: 'astryx experimental icon delete'},+ {+ label: 'One icon and its variants',+ cli: 'astryx experimental icon outline/trash',+ },+ {label: 'Installed sets', cli: 'astryx experimental icon --list --json'},+ {+ label: 'One set, top 3',+ cli: 'astryx experimental icon arrow --set outline --limit 3',+ },+ ],+ outsideProject: 'same',+ exitCodes: [+ {code: 0, when: 'success (including zero matches)'},+ {+ code: 1,+ when: 'no query and no --list, a query with --list, a --limit that is not a positive integer, or a set or icon that is not installed',+ },+ ],+ related: ['search', 'template'],+};diff --git a/packages/cli/clients/cli/commands/experimental.doc.mjs b/packages/cli/clients/cli/commands/experimental.doc.mjsnew file mode 100644index 0000000000..8df791dde3--- /dev/null+++ b/packages/cli/clients/cli/commands/experimental.doc.mjs@@ -0,0 +1,28 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CommandDoc for the `astryx experimental` command group: the one+ * namespace for experimental CLI commands (spec:AST-017 FR27). Each+ * experiment is a subcommand of it; none is added to a stable command.+ */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'experimental',+ displayName: 'astryx experimental',+ namespace: 'cli/commands',+ stability: 'experimental',+ summary: 'Try features that may change or be removed in a patch release',+ description:+ 'The experimental command group. Every command under it is experimental: its arguments, options, output, and JSON may change or be removed in any patch release, with no deprecation period. A feature leaves this group when it becomes stable. Nothing here changes what any other command does unless you use it.',+ subcommands: ['icon'],+ examples: [+ {label: 'List the experiments', cli: 'astryx experimental'},+ {label: 'Find an icon by meaning', cli: 'astryx experimental icon delete'},+ ],+ exitCodes: [+ {code: 0, when: 'help is shown or a subcommand succeeds'},+ {code: 1, when: 'an unknown subcommand or a subcommand failure'},+ ],+};diff --git a/packages/cli/clients/cli/commands/experimental/icon.mjs b/packages/cli/clients/cli/commands/experimental/icon.mjsnew file mode 100644index 0000000000..3ccfbe214e--- /dev/null+++ b/packages/cli/clients/cli/commands/experimental/icon.mjs@@ -0,0 +1,462 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx experimental icon` — find an icon by meaning in the installed+ * icon sets, and author a set (AST-084 FR6, FR7). Experimental (spec:AST-017+ * FR27): it is registered only under the `experimental` group.+ *+ * The command surface comes from the colocated `icon.doc.mjs` CommandDoc via+ * `defineCommand`; this file parses flags, calls `icon()`, and renders.+ *+ * Usage:+ * astryx experimental icon delete Ranked matches with import lines+ * astryx experimental icon outline/trash One icon and every variant's import+ * astryx experimental icon --list Installed sets and the names they fill+ * astryx experimental icon arrow --set outline --limit 3+ */++import {+ formatCliCommand,+ getCliInvocation,+} from '../../../../foundation/env/package-manager.mjs';+import {jsonOut} from '../../../../foundation/response/json.mjs';+import {resultSet} from '../../../../foundation/debug/index.mjs';+import {+ emit,+ section,+ text,+ record,+ records,+ list,+} from '../../formatters/index.mjs';+import {cliError} from '../../lib/cli-error.mjs';+import {defineCommand} from '../../lib/define-command.mjs';+import {icon as iconApi} from '../../../../api/icon/icon.mjs';+import {iconAdd} from '../../../../api/icon/add/add.mjs';+import {iconMap} from '../../../../api/icon/map/map.mjs';+import {iconUse} from '../../../../api/icon/use/use.mjs';+import {iconNewSet} from '../../../../api/icon/new-set/new-set.mjs';+import {iconNewDefinition} from '../../../../api/icon/new-definition/new-definition.mjs';+import {doc as iconCommand} from '../experimental-icon.doc.mjs';+import {doc as iconUseCommand} from '../experimental-icon-use.doc.mjs';+import {doc as iconMapCommand} from '../experimental-icon-map.doc.mjs';+import {doc as iconAddCommand} from '../experimental-icon-add.doc.mjs';+import {doc as iconNewSetCommand} from '../experimental-icon-new-set.doc.mjs';+import {doc as iconNewDefinitionCommand} from '../experimental-icon-new-definition.doc.mjs';+import {doc as iconFn} from '../../../../api/icon/icon.doc.mjs';+import {doc as iconUseFn} from '../../../../api/icon/iconUse.doc.mjs';+import {doc as iconMapFn} from '../../../../api/icon/iconMap.doc.mjs';+import {doc as iconAddFn} from '../../../../api/icon/iconAdd.doc.mjs';+import {doc as iconNewSetFn} from '../../../../api/icon/iconNewSet.doc.mjs';+import {doc as iconNewDefinitionFn} from '../../../../api/icon/iconNewDefinition.doc.mjs';+import {NO_RESULT_SET} from '../../../../foundation/debug/index.mjs';++/** @param {unknown} value */+const defaultVariantText = value =>+ /** @type {{variant?: string} | null} */ (value)?.variant ?? '';++/** @param {unknown} value */+const variantsText = value => (Array.isArray(value) ? value.join('/') : '');++/**+ * Register `icon` and its subcommands under the `experimental` group.+ * @param {import('commander').Command} group the `experimental` command+ * @param {import('commander').Command} program the root program+ */+export function registerExperimentalIcon(group, program) {+ const iconCli = defineCommand(group, iconCommand, {+ fn: iconFn,+ action: async (+ /** @type {string[] | string | undefined} */ words,+ /** @type {{list?: boolean, set?: string, limit?: string}} */ options,+ ) => {+ const json = program.opts().json || false;+ const query = Array.isArray(words) ? words.join(' ') : words;+ // Number(), not parseInt(): the API refuses `1.5` and `5abc`.+ const limit = options.limit != null ? Number(options.limit) : undefined;++ /** @type {Awaited<ReturnType<typeof iconApi>>} */+ let result;+ try {+ result = await iconApi(query, {+ cwd: process.cwd(),+ list: options.list ?? false,+ set: options.set,+ limit,+ });+ } catch (e) {+ const err =+ /** @type {import('../../../../api/error.mjs').AstryxError} */ (e);+ return cliError(err.message, {+ suggestions: err.suggestions,+ code: err.code,+ });+ }++ const answered =+ result.type === 'icon.search'+ ? resultSet({+ count: result.data.matchCount,+ resultKind: 'mixed',+ empty: result.data.matchCount === 0,+ })+ : result.type === 'icon.list'+ ? resultSet({+ count: result.data.sets.length,+ resultKind: 'mixed',+ empty: result.data.sets.length === 0,+ })+ : resultSet({count: 1, resultKind: 'mixed', directMatch: true});++ if (json) {+ jsonOut(result);+ return answered;+ }++ const run = getCliInvocation();+ if (result.type === 'icon.search') {+ const {query: q, matchCount, matches} = result.data;+ if (matches.length === 0) {+ emit(+ text(`No icons match "${q}".`),+ text(`See the installed sets: ${run} experimental icon --list`),+ );+ return answered;+ }+ emit(+ section(+ matchCount > matches.length+ ? `Icons for "${q}" (${matches.length} of ${matchCount})`+ : `Icons for "${q}" (${matches.length})`,+ ),+ // A match's variants are read with `icon <set>/<id>`; each match+ // with any says how many.+ records(+ matches.map(({variants, ...match}) => ({+ ...match,+ ...(variants.length > 0+ ? {variant: variants.map(each => each.variant).join(', ')}+ : {}),+ })),+ {+ fields: [+ 'set',+ 'id',+ 'package',+ 'import',+ 'words',+ 'definitions',+ 'variant',+ 'reason',+ ],+ },+ ),+ text(+ `Read one with its variants: ${run} experimental icon <set>/<id>`,+ ),+ );+ return answered;+ }++ if (result.type === 'icon.detail') {+ const {variants, ...rest} = result.data;+ emit(+ record(rest, {+ fields: [+ 'set',+ 'id',+ 'package',+ 'module',+ 'export',+ 'import',+ 'words',+ 'definitions',+ ],+ }),+ ...(variants.length > 0+ ? [+ section('Variants'),+ records(variants, {+ fields: ['variant', 'module', 'export', 'import'],+ }),+ ]+ : []),+ text(+ `More icons: ${formatCliCommand(`astryx experimental icon ${rest.words[0]}`)}`,+ ),+ );+ return answered;+ }++ const {status, projectSet, reason, sets, withdrawn} = result.data;+ emit(+ section('Icon sets'),+ record({status, projectSet, reason}),+ ...(sets.length > 0+ ? [+ records(+ sets.map(({coverage, ...set}) => ({+ ...set,+ builtIn: `${coverage.builtIn.mapped}/${coverage.builtIn.total}`,+ definitions: `${coverage.astryx.mapped}/${coverage.astryx.total}`,+ own: coverage.own,+ missing: coverage.builtIn.missing,+ })),+ {+ fields: [+ 'name',+ 'displayName',+ 'package',+ 'license',+ 'iconCount',+ 'default',+ 'variants',+ 'builtIn',+ 'definitions',+ 'own',+ 'missing',+ 'project',+ 'description',+ ],+ format: {default: defaultVariantText, variants: variantsText},+ },+ ),+ ]+ : []),+ ...(withdrawn.length > 0+ ? [+ section('Withdrawn'),+ list(+ withdrawn.map(+ each => `${each.package}/${each.name}: ${each.reason}`,+ ),+ ),+ ]+ : []),+ text(`Find one: ${run} experimental icon <words>`),+ );+ return answered;+ },+ });++ /**+ * Run one authoring call and print its receipt, or its error.+ * @param {() => Promise<any>} call+ * @param {(result: any) => void} print+ */+ const run = async (call, print) => {+ let result;+ try {+ result = await call();+ } catch (e) {+ const err =+ /** @type {import('../../../../api/error.mjs').AstryxError} */ (e);+ return cliError(err.message, {+ suggestions: err.suggestions ?? [],+ code: err.code,+ });+ }+ if (program.opts().json) jsonOut(result);+ else print(result);+ return NO_RESULT_SET;+ };++ defineCommand(iconCli, iconUseCommand, {+ fn: iconUseFn,+ action: (/** @type {string} */ set) =>+ run(+ () => iconUse(set, {cwd: process.cwd()}),+ ({data}) =>+ emit(+ text(+ data.changed+ ? `[ok] experimental.iconSet is now "${data.iconSet}" (${data.set}) in ${data.config}${data.created ? ', created' : ''}.`+ : `[ok] experimental.iconSet already names "${data.iconSet}" in ${data.config}.`,+ ),+ ...(data.previous && data.changed+ ? [text(`It was "${data.previous}".`)]+ : []),+ ...(data.warning ? [text(`[warn] ${data.warning}`)] : []),+ ),+ ),+ });++ defineCommand(iconCli, iconMapCommand, {+ fn: iconMapFn,+ action: (+ /** @type {string} */ definition,+ /** @type {string | undefined} */ iconId,+ /** @type {{set?: string, remove?: boolean}} */ options,+ ) =>+ run(+ () =>+ iconMap(definition, iconId, {+ cwd: process.cwd(),+ set: options.set,+ remove: options.remove ?? false,+ }),+ ({data}) =>+ emit(+ text(+ data.icon == null+ ? data.changed+ ? `[ok] Removed map.${data.definition} (was "${data.previous}") from ${data.file}.`+ : `[ok] ${data.file} has no map.${data.definition}.`+ : data.changed+ ? `[ok] map.${data.definition} = "${data.icon}" in ${data.file}${data.previous ? ` (was "${data.previous}")` : ''}.`+ : `[ok] map.${data.definition} is already "${data.icon}".`,+ ),+ ),+ ),+ });++ defineCommand(iconCli, iconAddCommand, {+ fn: iconAddFn,+ action: (+ /** @type {string} */ exportName,+ /** @type {Record<string, string | boolean | undefined>} */ options,+ ) =>+ run(+ () =>+ iconAdd(exportName, {+ cwd: process.cwd(),+ from: /** @type {string} */ (options.from),+ set: /** @type {string | undefined} */ (options.set),+ definition: /** @type {string | undefined} */ (options.definition),+ newDefinition: /** @type {string | undefined} */ (+ options.newDefinition+ ),+ description: /** @type {string | undefined} */ (+ options.description+ ),+ words:+ typeof options.words === 'string'+ ? options.words.split(',')+ : undefined,+ useDefault: options.default === true,+ variant: /** @type {string | undefined} */ (options.variant),+ id: /** @type {string | undefined} */ (options.id),+ }),+ result => {+ const cli = getCliInvocation();+ if (result.type === 'icon.definitionMatches') {+ const {matches, newDefinition} = result.data;+ emit(+ section(+ `Icon definitions for ${result.data.export} (${matches.length})`,+ ),+ ...(matches.length > 0+ ? [+ records(matches, {+ fields: [+ 'name',+ 'source',+ 'score',+ 'reason',+ 'description',+ 'command',+ ],+ format: {+ command: (/** @type {string} */ value) =>+ formatCliCommand(value),+ },+ }),+ ]+ : [text('No icon definition fits it.')]),+ ...(newDefinition+ ? [+ text(+ `None fits well? Add your own: ${formatCliCommand(newDefinition)}`,+ ),+ ]+ : []),+ text(+ `All icon definitions: ${cli} docs cli/experimental/icon-definitions`,+ ),+ );+ return;+ }+ const {data} = result;+ emit(+ text(+ data.changed+ ? `[ok] Added ${data.icon.export} as "${data.icon.id}"${data.variant ? ` (variant ${data.variant})` : ''}${data.definition ? `, map.${data.definition} = "${data.icon.id}"` : ''}.`+ : `[ok] ${data.icon.export} is already "${data.icon.id}"${data.definition ? ` and map.${data.definition} names it` : ''}.`,+ ),+ ...(data.files.length > 0 ? [list(data.files)] : []),+ ...(data.note ? [text(`[next] ${data.note}`)] : []),+ );+ },+ ),+ });++ /**+ * Print a new-set or new-definition receipt: what it wrote and where.+ * @param {string} what `icon set` or `icon definition`+ */+ const printNew =+ (/** @type {string} */ what) =>+ (+ /** @type {import('../../../../api/icon/icon.type.mjs').IconNewResponse} */ {+ data,+ },+ ) => {+ const {root, manifest, files, written, dryRun} = data;+ const state = dryRun ? 'plan' : written ? 'ok' : 'unchanged';+ emit(+ section(+ dryRun+ ? `New ${what} plan`+ : written+ ? `New ${what} added`+ : `New ${what} unchanged`,+ ),+ text(`[${state}] ${data.name}`),+ text(+ root != null+ ? `${root.created ? 'Declare' : 'Use'} experimental.iconSets root ${root.path} in ${manifest}.`+ : `Update ${manifest}.`,+ ),+ ...(files.length > 0 ? [list(files)] : []),+ ...(data.notes ?? []).map(note => text(`[next] ${note}`)),+ );+ };++ defineCommand(iconCli, iconNewSetCommand, {+ fn: iconNewSetFn,+ action: (+ /** @type {string} */ name,+ /** @type {{dryRun?: boolean, from?: string, exclude?: string}} */ options,+ ) =>+ run(+ () =>+ iconNewSet(name, {+ cwd: process.cwd(),+ dryRun: options.dryRun,+ from: options.from,+ exclude: options.exclude,+ }),+ printNew('icon set'),+ ),+ }).allowExcessArguments(false);++ defineCommand(iconCli, iconNewDefinitionCommand, {+ fn: iconNewDefinitionFn,+ action: (+ /** @type {string} */ name,+ /** @type {{dryRun?: boolean, set?: string, description?: string, words?: string, icon?: string}} */ options,+ ) =>+ run(+ () =>+ iconNewDefinition(name, {+ cwd: process.cwd(),+ dryRun: options.dryRun,+ set: options.set,+ description: options.description,+ words: options.words,+ icon: options.icon,+ }),+ printNew('icon definition'),+ ),+ }).allowExcessArguments(false);+}diff --git a/packages/cli/clients/cli/commands/experimental/index.mjs b/packages/cli/clients/cli/commands/experimental/index.mjsnew file mode 100644index 0000000000..6780ce39ef--- /dev/null+++ b/packages/cli/clients/cli/commands/experimental/index.mjs@@ -0,0 +1,43 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx experimental` — the command group every experimental CLI+ * command lives under (spec:AST-017 FR27). It has no behavior of its own:+ * bare, it prints its help; an unknown word is an unknown subcommand. Each+ * experiment registers its own subcommand here.+ */++import {NO_RESULT_SET} from '../../../../foundation/debug/index.mjs';+import {ERROR_CODES} from '../../../../foundation/response/error-codes.mjs';+import {cliError} from '../../lib/cli-error.mjs';+import {defineCommand} from '../../lib/define-command.mjs';+import {doc as experimentalGroup} from '../experimental.doc.mjs';+import {registerExperimentalIcon} from './icon.mjs';++/** @param {import('commander').Command} program */+export function registerExperimental(program) {+ /** @type {import('commander').Command} */+ const experimental = defineCommand(program, experimentalGroup, {+ action: (+ /** @type {unknown} */ options,+ /** @type {import('commander').Command} */ cmd,+ ) => {+ const extras = cmd?.args ?? [];+ if (extras.length > 0) {+ return cliError(+ `unknown subcommand 'experimental ${String(extras[0])}'`,+ {+ suggestions: (experimental.commands ?? []).map(command => ({+ name: command.name(),+ reason: 'available subcommand',+ })),+ code: ERROR_CODES.ERR_UNKNOWN_SUBCOMMAND,+ },+ );+ }+ experimental.help();+ return NO_RESULT_SET;+ },+ });+ registerExperimentalIcon(experimental, program);+}diff --git a/packages/cli/clients/cli/commands/icon-authoring.test.mjs b/packages/cli/clients/cli/commands/icon-authoring.test.mjsnew file mode 100644index 0000000000..86ba4a0aae--- /dev/null+++ b/packages/cli/clients/cli/commands/icon-authoring.test.mjs@@ -0,0 +1,1035 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Icon-set authoring commands end to end (AST-084): `experimental icon+ * new-set --from`, `experimental icon new-definition`, `experimental icon add`, `icon+ * map`, and `experimental icon use`, driving the real program over an icon-set package+ * that wraps a small component library and an app that installs it.+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {createRequire} from 'node:module';+import {pathToFileURL} from 'node:url';+import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import {runCli} from '../../../test-utils/run-cli.mjs';+import {writeIconSetProject} from '../../../test-utils/icon-set-fixture.mjs';++/** @type {string} */+let tmp;+/** @type {string} */+let pkg;++/**+ * A component library under node_modules: two components (one also exported+ * under an `…Icon` alias), a data export, and a default-export file.+ * @param {string} dir+ */+function writeLibrary(dir) {+ const lib = path.join(dir, 'node_modules', '@acme', 'glyph-library');+ fs.mkdirSync(path.join(lib, 'icons'), {recursive: true});+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ name: '@acme/glyph-library',+ version: '2.0.0',+ type: 'module',+ exports: {'.': './index.js', './rocket': './icons/rocket.js'},+ }),+ );+ fs.writeFileSync(+ path.join(lib, 'index.js'),+ [+ "export {Bin, Bin as BinIcon} from './icons/bin.js';",+ "export {Cross} from './icons/cross.js';",+ "export const glyphData = {path: 'M0 0'};",+ "export const version = '2.0.0';",+ '',+ ].join('\n'),+ );+ fs.writeFileSync(+ path.join(lib, 'icons', 'bin.js'),+ 'export function Bin(props) { return null; }\n',+ );+ fs.writeFileSync(+ path.join(lib, 'icons', 'cross.js'),+ 'export const Cross = props => null;\n',+ );+ fs.writeFileSync(+ path.join(lib, 'icons', 'rocket.js'),+ 'export default function Rocket(props) { return null; }\n',+ );+}++beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-icon-authoring-'));+ pkg = path.join(tmp, 'icons');+ fs.mkdirSync(pkg, {recursive: true});+ fs.writeFileSync(+ path.join(pkg, 'package.json'),+ JSON.stringify(+ {+ name: '@acme/icons',+ version: '1.0.0',+ license: 'MIT',+ type: 'module',+ exports: {'.': './index.js'},+ dependencies: {'@acme/glyph-library': '^2.0.0'},+ },+ null,+ 2,+ ),+ );+ fs.writeFileSync(path.join(pkg, 'index.js'), 'export {};\n');+ writeLibrary(pkg);+});+afterEach(() => {+ fs.rmSync(tmp, {recursive: true, force: true});+});++/** @param {string[]} args @param {string} [cwd] */+async function json(args, cwd = pkg) {+ const res = await runCli([...args, '--json'], cwd);+ return {code: res.code, body: JSON.parse(res.stdout)};+}++/** @param {string} set */+const dataOf = set =>+ JSON.parse(+ fs.readFileSync(+ path.join(pkg, 'icon-sets', set, `${set}.icons.json`),+ 'utf-8',+ ),+ );++describe('experimental icon new-set --from', () => {+ it('wraps every component of a library once, names each <Name>Icon, pre-fills exact map hits, and says what to export', async () => {+ const {code, body} = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ]);+ expect(code).toBe(0);+ expect(body.data).toMatchObject({kind: 'icon-set', icons: 2});+ expect(body.data.notes[0]).toContain(+ "export * from './icon-sets/outline/outline.generated.js'",+ );+ const data = dataOf('outline');+ expect(data.generated).toBe('./icon-sets/outline/outline.generated.js');+ expect(data.icons).toEqual([+ {id: 'bin', export: 'BinIcon', words: ['bin']},+ {id: 'cross', export: 'CrossIcon', words: ['cross']},+ ]);+ // `delete` has the word bin; nothing is guessed beyond exact hits.+ expect(data.map).toMatchObject({delete: 'bin'});+ const generated = fs.readFileSync(+ path.join(pkg, 'icon-sets', 'outline', 'outline.generated.js'),+ 'utf-8',+ );+ expect(generated).toContain("export {BinIcon} from '@acme/glyph-library';");+ expect(generated).toContain(+ "export {Cross as CrossIcon} from '@acme/glyph-library';",+ );+ expect(generated).not.toContain('glyphData');++ // Running it again refreshes in place and keeps the map.+ const again = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ]);+ expect(again.code).toBe(0);+ expect(dataOf('outline').map).toMatchObject({delete: 'bin'});+ });++ it('the theme map reads each re-exported icon through an import, so the generated module loads', async () => {+ await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ]);+ // `close` is built in, so it lands in the theme map.+ expect(+ (await json(['experimental', 'icon', 'map', 'close', 'cross'])).code,+ ).toBe(0);+ const file = path.join(pkg, 'icon-sets', 'outline', 'outline.generated.js');+ const text = fs.readFileSync(file, 'utf-8');+ // A re-export binds no local name: the theme map's import does.+ expect(text).toContain(+ "import {Cross as CrossIcon} from '@acme/glyph-library';",+ );+ expect(text).toContain(+ "export {Cross as CrossIcon} from '@acme/glyph-library';",+ );+ expect(text).toContain('close: createElement(CrossIcon,');+ const check = JSON.stringify(+ JSON.parse(+ (await runCli(['integration', 'check', '--json'], pkg)).stdout,+ ),+ );+ expect(check).not.toContain('icon_theme_map_mismatch');+ expect(check).not.toContain('icon_module_invalid');++ // The module loads and the theme map draws the exported component.+ const react = path.dirname(+ createRequire(import.meta.url).resolve('react/package.json'),+ );+ fs.symlinkSync(react, path.join(pkg, 'node_modules', 'react'), 'dir');+ const mod = await import(pathToFileURL(file).href);+ expect(mod.themeIcons.close.type).toBe(mod.CrossIcon);++ // Remapping drops the import the theme map no longer reads.+ await json(['experimental', 'icon', 'map', 'close', 'bin']);+ const remapped = fs.readFileSync(file, 'utf-8');+ expect(remapped).not.toContain('import {Cross as CrossIcon}');+ expect(remapped).toContain("import {BinIcon} from '@acme/glyph-library';");+ }, 60_000);+});++describe('icon add', () => {+ beforeEach(async () => {+ await runCli(['experimental', 'icon', 'new-set', 'outline'], pkg);+ });++ it('lists the definitions that fit an export, and writes nothing', async () => {+ const {code, body} = await json([+ 'experimental',+ 'icon',+ 'add',+ 'Bin',+ '--from',+ '@acme/glyph-library',+ ]);+ expect(code).toBe(0);+ expect(body.type).toBe('icon.definitionMatches');+ expect(body.data.matches[0]).toMatchObject({+ name: 'delete',+ source: 'astryx',+ command:+ 'astryx experimental icon add Bin --from @acme/glyph-library --definition delete',+ });+ expect(dataOf('outline').icons).toEqual([]);+ });++ it('adds the icon as <Name>Icon through the generated module, maps it, and is idempotent', async () => {+ const args = [+ 'experimental',+ 'icon',+ 'add',+ 'Bin',+ '--from',+ '@acme/glyph-library',+ '--definition',+ 'delete',+ ];+ const first = await json(args);+ expect(first.code).toBe(0);+ expect(first.body.data).toMatchObject({+ icon: {id: 'bin', export: 'BinIcon', module: '@acme/icons'},+ definition: 'delete',+ changed: true,+ });+ expect(first.body.data.note).toContain('export * from');+ const data = dataOf('outline');+ expect(data.map).toEqual({delete: 'bin'});+ expect(data.icons[0]).toMatchObject({id: 'bin', export: 'BinIcon'});+ // Only its own words: the definition's words are matched, not copied.+ expect(data.icons[0].words).toEqual(['bin']);+ expect(data.icons[0]).not.toHaveProperty('module');+ const again = await json(args);+ expect(again.body.data.changed).toBe(false);+ });++ it('adds a declared variant of an existing icon with --variant, refusing one the set does not declare', async () => {+ await json([+ 'experimental',+ 'icon',+ 'add',+ 'Bin',+ '--from',+ '@acme/glyph-library',+ '--definition',+ 'delete',+ ]);+ const args = [+ 'experimental',+ 'icon',+ 'add',+ 'Cross',+ '--from',+ '@acme/glyph-library',+ '--id',+ 'bin',+ '--variant',+ 'solid',+ ];+ const before = dataOf('outline');+ const refused = await json(args);+ expect(refused.code).toBe(1);+ expect(refused.body.code).toBe('ERR_INVALID_ARGUMENT');+ expect(refused.body.error).toContain('variant "solid" is not in variants');+ expect(refused.body.error).toContain('Declare it in "variants"');+ expect(dataOf('outline')).toEqual(before);++ const dataPath = path.join(+ pkg,+ 'icon-sets',+ 'outline',+ 'outline.icons.json',+ );+ fs.writeFileSync(+ dataPath,+ JSON.stringify({+ ...before,+ variants: ['outline', 'solid'],+ default: {variant: 'outline'},+ }),+ );+ const added = await json(args);+ expect(added.code).toBe(0);+ expect(added.body.data).toMatchObject({+ icon: {id: 'bin', export: 'BinSolidIcon'},+ variant: 'solid',+ changed: true,+ });+ const data = dataOf('outline');+ expect(Object.keys(data)).toContain('variants');+ expect(data.icons[0].variants).toEqual([+ {variant: 'solid', export: 'BinSolidIcon'},+ ]);+ expect(+ fs.readFileSync(+ path.join(pkg, 'icon-sets', 'outline', 'outline.generated.js'),+ 'utf-8',+ ),+ ).toContain("export {Cross as BinSolidIcon} from '@acme/glyph-library';");+ });++ it("adds the set's own definition with --new-definition, refusing one Astryx has", async () => {+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ 'Cross',+ '--from',+ '@acme/glyph-library',+ '--new-definition',+ 'crossOut',+ '--description',+ 'Cross something out.',+ '--words',+ 'strike,cross',+ ]);+ expect(added.code).toBe(0);+ expect(+ fs.existsSync(+ path.join(+ pkg,+ 'icon-sets',+ 'outline',+ 'definitions',+ 'crossOut.doc.mjs',+ ),+ ),+ ).toBe(true);+ expect(dataOf('outline').map).toEqual({crossOut: 'cross'});+ expect(+ fs.readFileSync(+ path.join(+ pkg,+ 'icon-sets',+ 'outline',+ 'definitions',+ 'crossOut.doc.mjs',+ ),+ 'utf-8',+ ),+ ).toContain("words: ['strike', 'cross']");+ const refused = await json([+ 'experimental',+ 'icon',+ 'add',+ 'Cross',+ '--from',+ '@acme/glyph-library',+ '--new-definition',+ 'close',+ '--description',+ 'x',+ '--words',+ 'x',+ ]);+ expect(refused.code).toBe(1);+ expect(refused.body.suggestions).toContainEqual(+ expect.objectContaining({name: '--definition close'}),+ );+ });++ it('--new-definition that cannot write its definition leaves the generated module, its types, and the set data unchanged', async () => {+ const set = path.join(pkg, 'icon-sets', 'outline');+ const first = await json([+ 'experimental',+ 'icon',+ 'add',+ 'Bin',+ '--from',+ '@acme/glyph-library',+ '--definition',+ 'delete',+ ]);+ expect(first.code).toBe(0);+ const files = ['outline.generated.js', 'outline.generated.d.ts'].map(name =>+ path.join(set, name),+ );+ files.push(path.join(set, 'outline.icons.json'));+ const before = files.map(file => fs.readFileSync(file, 'utf-8'));+ // A file where the definitions folder belongs: the definition write fails.+ fs.rmSync(path.join(set, 'definitions'), {recursive: true, force: true});+ fs.writeFileSync(path.join(set, 'definitions'), 'not a folder\n');+ const failed = await json([+ 'experimental',+ 'icon',+ 'add',+ 'Cross',+ '--from',+ '@acme/glyph-library',+ '--new-definition',+ 'crossOut',+ '--description',+ 'Cross something out.',+ '--words',+ 'strike,cross',+ ]);+ expect(failed.code).toBe(1);+ expect(files.map(file => fs.readFileSync(file, 'utf-8'))).toEqual(before);+ expect(fs.readFileSync(path.join(set, 'definitions'), 'utf-8')).toBe(+ 'not a folder\n',+ );+ });++ it('refuses an export the module lacks, with close names, and an unknown definition', async () => {+ const missing = await json([+ 'experimental',+ 'icon',+ 'add',+ 'Bim',+ '--from',+ '@acme/glyph-library',+ '--definition',+ 'delete',+ ]);+ expect(missing.code).toBe(1);+ expect(+ missing.body.suggestions.map((/** @type {any} */ s) => s.name),+ ).toContain('Bin');+ const unknown = await json([+ 'experimental',+ 'icon',+ 'add',+ 'Bin',+ '--from',+ '@acme/glyph-library',+ '--definition',+ 'trashCan',+ ]);+ expect(unknown.code).toBe(1);+ });++ it('a default export, or a value through the declared adapter', async () => {+ const rocket = await json([+ 'experimental',+ 'icon',+ 'add',+ 'Rocket',+ '--from',+ '@acme/glyph-library/rocket',+ '--default',+ '--definition',+ 'rocket',+ ]);+ expect(rocket.code).toBe(0);+ const refused = await json([+ 'experimental',+ 'icon',+ 'add',+ 'glyphData',+ '--from',+ '@acme/glyph-library',+ '--definition',+ 'activity',+ ]);+ expect(refused.code).toBe(1);+ expect(refused.body.error).toContain('adapter');++ const dataFile = path.join(+ pkg,+ 'icon-sets',+ 'outline',+ 'outline.icons.json',+ );+ const data = JSON.parse(fs.readFileSync(dataFile, 'utf-8'));+ data.adapter = {module: './src/adapt.js', export: 'adapt'};+ fs.writeFileSync(dataFile, JSON.stringify(data, null, 2));+ fs.mkdirSync(path.join(pkg, 'src'));+ fs.writeFileSync(+ path.join(pkg, 'src', 'adapt.js'),+ 'export function adapt(data) { return () => null; }\n',+ );+ const adapted = await json([+ 'experimental',+ 'icon',+ 'add',+ 'glyphData',+ '--from',+ '@acme/glyph-library',+ '--definition',+ 'activity',+ ]);+ expect(adapted.code).toBe(0);+ expect(adapted.body.data.icon.export).toBe('GlyphDataIcon');+ const generated = fs.readFileSync(+ path.join(pkg, 'icon-sets', 'outline', 'outline.generated.js'),+ 'utf-8',+ );+ expect(generated).toContain(+ "import {adapt as adaptIcon} from '../../src/adapt.js';",+ );+ expect(generated).toContain(+ 'export const GlyphDataIcon = adaptIcon(GlyphDataIconSource);',+ );+ expect(generated).toContain(+ "export {default as RocketIcon} from '@acme/glyph-library/rocket';",+ );+ });+});++describe('experimental icon map and new-definition', () => {+ beforeEach(async () => {+ await runCli(+ [+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ],+ pkg,+ );+ });++ it('maps, remaps, and removes an entry; refuses an unknown definition or icon', async () => {+ const mapped = await json([+ 'experimental',+ 'icon',+ 'map',+ 'close',+ 'cross',+ ]);+ expect(mapped.body.data).toMatchObject({+ definition: 'close',+ icon: 'cross',+ changed: true,+ });+ expect(dataOf('outline').map.close).toBe('cross');+ const removed = await json([+ 'experimental',+ 'icon',+ 'map',+ 'close',+ '--remove',+ ]);+ expect(removed.body.data).toMatchObject({icon: null, previous: 'cross'});+ expect(dataOf('outline').map).not.toHaveProperty('close');+ const unknown = await json([+ 'experimental',+ 'icon',+ 'map',+ 'rotate',+ 'cross',+ ]);+ expect(unknown.code).toBe(1);+ expect(unknown.body.suggestions).toContainEqual(+ expect.objectContaining({+ name: 'astryx experimental icon new-definition rotate --set outline',+ }),+ );+ const noIcon = await json([+ 'experimental',+ 'icon',+ 'map',+ 'close',+ 'crosss',+ ]);+ expect(noIcon.code).toBe(1);+ expect(noIcon.body.suggestions).toContainEqual(+ expect.objectContaining({name: 'cross'}),+ );+ });++ it("adds the set's own definition, mapped with --icon", async () => {+ const {code, body} = await json([+ 'experimental',+ 'icon',+ 'new-definition',+ 'crossOut',+ '--description',+ 'Cross something out.',+ '--words',+ 'strike,cross',+ '--icon',+ 'cross',+ ]);+ expect(code).toBe(0);+ expect(body.data).toMatchObject({+ kind: 'icon-definition',+ name: 'crossOut',+ });+ expect(dataOf('outline').map.crossOut).toBe('cross');+ const again = await json([+ 'experimental',+ 'icon',+ 'new-definition',+ 'crossOut',+ '--description',+ 'x',+ '--words',+ 'x',+ ]);+ expect(again.code).toBe(1);+ expect(again.body.code).toBe('ERR_FILE_EXISTS');+ });+});++describe('experimental icon use', () => {+ it("writes the project's experimental.iconSet, creating astryx.config.mjs, and refuses a set that is not installed", async () => {+ const app = writeIconSetProject(tmp);+ const used = await json(['experimental', 'icon', 'use', 'glyphs'], app);+ expect(used.code).toBe(0);+ expect(used.body.data).toMatchObject({+ iconSet: 'glyphs',+ set: '@acme/glyphs/glyphs',+ created: true,+ changed: true,+ });+ expect(+ fs.readFileSync(path.join(app, 'astryx.config.mjs'), 'utf-8'),+ ).toMatch(/experimental: \{\s*iconSet: 'glyphs',?\s*\}/);+ const again = await json(+ ['experimental', 'icon', 'use', '@acme/glyphs/glyphs'],+ app,+ );+ expect(again.body.data).toMatchObject({+ previous: 'glyphs',+ changed: true,+ created: false,+ });+ const missing = await json(['experimental', 'icon', 'use', 'glyps'], app);+ expect(missing.code).toBe(1);+ expect(missing.body.suggestions).toContainEqual(+ expect.objectContaining({name: 'glyphs'}),+ );+ });++ it('warns in the receipt when the project may run a CLI that refuses experimental.iconSet', async () => {+ const app = writeIconSetProject(tmp);+ const pkgFile = path.join(app, 'package.json');+ const pkgJson = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));+ // No CLI range declared: nothing says which CLI it runs.+ const none = await json(['experimental', 'icon', 'use', 'glyphs'], app);+ expect(none.body.data).not.toHaveProperty('warning');+ pkgJson.devDependencies = {'@astryxdesign/cli': '^0.7.0'};+ fs.writeFileSync(pkgFile, JSON.stringify(pkgJson));+ const old = await json(['experimental', 'icon', 'use', 'glyphs'], app);+ expect(old.code).toBe(0);+ expect(old.body.data.warning).toContain(+ 'range "^0.7.0" (devDependencies) admits a release before 0.7.4',+ );+ expect(old.body.data.warning).toContain('"Unrecognized key"');+ expect(old.body.data.warning).toContain(+ 'commands that load the project configuration, such as `doctor` and `discover`, fail there',+ );+ expect(old.body.data.warning).not.toContain('every command');+ const text = await runCli(['experimental', 'icon', 'use', 'glyphs'], app);+ expect(text.stdout).toContain(+ "[warn] The project's @astryxdesign/cli range",+ );+ // Published 0.7.3 still refuses the key.+ pkgJson.devDependencies = {'@astryxdesign/cli': '^0.7.3'};+ fs.writeFileSync(pkgFile, JSON.stringify(pkgJson));+ const previous = await json(['experimental', 'icon', 'use', 'glyphs'], app);+ expect(previous.body.data.warning).toContain(+ 'range "^0.7.3" (devDependencies) admits a release before 0.7.4',+ );+ pkgJson.devDependencies = {'@astryxdesign/cli': '^0.7.4'};+ fs.writeFileSync(pkgFile, JSON.stringify(pkgJson));+ const current = await json(['experimental', 'icon', 'use', 'glyphs'], app);+ expect(current.body.data).not.toHaveProperty('warning');+ });++ it('writes a plain existing config, keeping its other fields', async () => {+ const app = writeIconSetProject(tmp);+ const config = path.join(app, 'astryx.config.mjs');+ fs.writeFileSync(config, 'export default {\n integrations: [],\n};\n');+ const used = await json(['experimental', 'icon', 'use', 'glyphs'], app);+ expect(used.code).toBe(0);+ expect(used.body.data).toMatchObject({created: false, changed: true});+ const written = fs.readFileSync(config, 'utf-8');+ expect(written).toContain('integrations: []');+ expect(written).toMatch(/iconSet: 'glyphs'/);+ });++ it('refuses a config reached through a symbolic link, leaving its target untouched', async () => {+ const app = writeIconSetProject(tmp);+ const target = path.join(tmp, 'shared.config.mjs');+ const before = 'export default {\n integrations: [],\n};\n';+ fs.writeFileSync(target, before);+ fs.symlinkSync(target, path.join(app, 'astryx.config.mjs'));+ const refused = await json(['experimental', 'icon', 'use', 'glyphs'], app);+ expect(refused.code).toBe(1);+ expect(refused.body.code).toBe('ERR_CODEMOD_PROTECTED');+ expect(refused.body.error).toContain('symbolic link at astryx.config.mjs');+ expect(fs.readFileSync(target, 'utf-8')).toBe(before);+ expect(+ fs.lstatSync(path.join(app, 'astryx.config.mjs')).isSymbolicLink(),+ ).toBe(true);+ });++ it('refuses a generated config, naming the marker that protects it', async () => {+ const app = writeIconSetProject(tmp);+ const config = path.join(app, 'astryx.config.mjs');+ const before = '// @generated\nexport default {\n integrations: [],\n};\n';+ fs.writeFileSync(config, before);+ const refused = await json(['experimental', 'icon', 'use', 'glyphs'], app);+ expect(refused.code).toBe(1);+ expect(refused.body.code).toBe('ERR_CODEMOD_PROTECTED');+ expect(refused.body.error).toContain(+ '@generated in the leading comment block',+ );+ expect(fs.readFileSync(config, 'utf-8')).toBe(before);+ });+});++describe('a library of icon data, through the adapter', () => {+ beforeEach(() => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-data');+ fs.mkdirSync(lib, {recursive: true});+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ name: '@acme/glyph-data',+ version: '1.0.0',+ type: 'module',+ exports: {'.': './index.js'},+ }),+ );+ fs.writeFileSync(+ path.join(lib, 'index.js'),+ [+ "export const glyphEye = {path: 'M1 1'};",+ "export const glyphEyeOff = {path: 'M1 2'};",+ "export const glyphTrash = {path: 'M2 2'};",+ "export const glyphX = {path: 'M3 3'};",+ '',+ ].join('\n'),+ );+ fs.mkdirSync(path.join(pkg, 'src'));+ fs.writeFileSync(+ path.join(pkg, 'src', 'adapt.js'),+ 'export function adapt(data) { return () => null; }\n',+ );+ fs.writeFileSync(+ path.join(pkg, 'index.js'),+ "export * from './icon-sets/outline/outline.generated.js';\n",+ );+ });++ /** Declare the adapter in the set's data file. */+ const declareAdapter = () => {+ const file = path.join(pkg, 'icon-sets', 'outline', 'outline.icons.json');+ const data = JSON.parse(fs.readFileSync(file, 'utf-8'));+ data.adapter = {module: './src/adapt.js', export: 'adapt'};+ fs.writeFileSync(file, JSON.stringify(data, null, 2));+ };+ const generated = () =>+ fs.readFileSync(+ path.join(pkg, 'icon-sets', 'outline', 'outline.generated.js'),+ 'utf-8',+ );++ it('the bulk wrap finds nothing until the adapter is declared, then wraps every data export without the shared prefix', async () => {+ const before = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-data',+ ]);+ expect(before.code).toBe(1);+ expect(before.body.error).toContain('adapter');+ await runCli(['experimental', 'icon', 'new-set', 'outline'], pkg);+ declareAdapter();+ const wrapped = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-data',+ ]);+ expect(wrapped.code).toBe(0);+ expect(+ dataOf('outline').icons.map((/** @type {any} */ i) => [i.id, i.export]),+ ).toEqual([+ ['eye', 'EyeIcon'],+ ['eye-off', 'EyeOffIcon'],+ ['trash', 'TrashIcon'],+ ['x', 'XIcon'],+ ]);+ expect(generated()).toContain(+ 'export const EyeIcon = adaptIcon(EyeIconSource);',+ );+ expect(generated()).toContain(+ "import {glyphEye as EyeIconSource} from '@acme/glyph-data';",+ );+ });++ it('icon add appended twice writes the adapter import once, and the module still parses', async () => {+ await runCli(['experimental', 'icon', 'new-set', 'outline'], pkg);+ declareAdapter();+ for (const [name, definition] of [+ ['glyphTrash', 'delete'],+ ['glyphEye', 'view'],+ ['glyphX', 'close'],+ ]) {+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ name,+ '--from',+ '@acme/glyph-data',+ ...(definition === 'view'+ ? [+ '--new-definition',+ 'peek',+ '--description',+ 'Peek.',+ '--words',+ 'peek',+ ]+ : ['--definition', definition]),+ ]);+ expect(added.code, name).toBe(0);+ }+ const text = generated();+ expect(text.match(/as adaptIcon/gu)).toHaveLength(1);+ // The library prefix is left out of the id and the export name.+ expect(dataOf('outline').map).toMatchObject({delete: 'trash', close: 'x'});+ expect(text).toContain(+ 'export const TrashIcon = adaptIcon(TrashIconSource);',+ );+ // A built-in mapping lands in the theme map, and the types follow.+ expect(text).toContain(+ "close: createElement(XIcon, {'aria-hidden': true, 'width': '1em', 'height': '1em'}),",+ );+ const types = fs.readFileSync(+ path.join(pkg, 'icon-sets', 'outline', 'outline.generated.d.ts'),+ 'utf-8',+ );+ expect(types).toContain(+ 'export declare const TrashIcon: ComponentType<SVGProps<SVGSVGElement>>;',+ );+ expect(types).toContain(+ 'export declare const themeIcons: {readonly close: ReactElement};',+ );+ // icon map rewrites the theme map.+ await json(['experimental', 'icon', 'map', 'close', 'trash']);+ expect(generated()).toContain('close: createElement(TrashIcon,');+ // Integration check reads it all: no parse error, no missing export, no+ // theme-map or types mismatch.+ const check = await runCli(['integration', 'check', '--json'], pkg);+ const codes = JSON.stringify(JSON.parse(check.stdout));+ for (const code of [+ 'icon_module_invalid',+ 'icon_export_missing',+ 'icon_theme_map_mismatch',+ 'icon_generated_types_mismatch',+ ]) {+ expect(codes, code).not.toContain(code);+ }+ // The optional definitions left unmapped are listed, never issues.+ expect(codes).not.toContain('"severity":"info"');+ const printed = await runCli(['integration', 'check'], pkg);+ expect(printed.stdout).toContain('Unmapped icon definitions (optional)');+ expect(printed.stdout).toContain(+ 'Mapping these is optional and never fails',+ );+ }, 60_000);+});++describe('the library prefix ignores constants', () => {+ beforeEach(() => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-data');+ fs.mkdirSync(lib, {recursive: true});+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ name: '@acme/glyph-data',+ version: '1.0.0',+ type: 'module',+ exports: {'.': './index.js'},+ }),+ );+ fs.writeFileSync(+ path.join(lib, 'index.js'),+ [+ "export const glyphEye = {path: 'M1 1'};",+ "export const glyphTrash = {path: 'M2 2'};",+ "export const glyphX = {path: 'M3 3'};",+ "export const README = 'See the docs.';",+ "export const notes = 'Some notes.';",+ 'export const count = 5;',+ "export const meta = {kind: 'meta'};",+ '',+ ].join('\n'),+ );+ fs.mkdirSync(path.join(pkg, 'src'));+ fs.writeFileSync(+ path.join(pkg, 'src', 'adapt.js'),+ 'export function adapt(data) { return () => null; }\n',+ );+ });++ /** Create the set with an adapter. */+ const setUp = async () => {+ await runCli(['experimental', 'icon', 'new-set', 'outline'], pkg);+ const file = path.join(pkg, 'icon-sets', 'outline', 'outline.icons.json');+ const data = JSON.parse(fs.readFileSync(file, 'utf-8'));+ data.adapter = {module: './src/adapt.js', export: 'adapt'};+ fs.writeFileSync(file, JSON.stringify(data, null, 2));+ };+ const exportsOf = () =>+ dataOf('outline').icons.map((/** @type {any} */ i) => i.export);+ const wrap = (/** @type {string[]} */ extra = []) =>+ json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-data',+ ...extra,+ ]);++ it('skips SCREAMING_CASE names, numbers, and stray strings; --exclude drops a non-icon object, and the refresh prunes the old exports', async () => {+ await setUp();+ // meta is shaped like an icon, so it keeps the prefix off.+ expect((await wrap()).code).toBe(0);+ expect(exportsOf()).toEqual([+ 'GlyphEyeIcon',+ 'GlyphTrashIcon',+ 'GlyphXIcon',+ 'MetaIcon',+ ]);+ expect((await wrap(['--exclude', 'meta'])).code).toBe(0);+ expect(exportsOf()).toEqual(['EyeIcon', 'TrashIcon', 'XIcon']);+ const generated = fs.readFileSync(+ path.join(pkg, 'icon-sets', 'outline', 'outline.generated.js'),+ 'utf-8',+ );+ expect(generated).not.toContain('Glyph');+ expect(generated).not.toContain('README');+ expect(generated).not.toContain('notes');+ // icon add reuses the icon the wrap already made for an export, even+ // though meta keeps its own prefix off.+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ 'glyphTrash',+ '--from',+ '@acme/glyph-data',+ '--definition',+ 'delete',+ ]);+ expect(added.code).toBe(0);+ expect(added.body.data.icon).toMatchObject({+ id: 'trash',+ export: 'TrashIcon',+ });+ expect(exportsOf()).toEqual(['EyeIcon', 'TrashIcon', 'XIcon']);+ });++ it('--exclude needs --from', async () => {+ const res = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--exclude',+ 'README',+ ]);+ expect(res.code).toBe(1);+ expect(res.body.error).toContain('--from');+ });++ it('a library of SVG strings keeps its strings as icons', async () => {+ fs.writeFileSync(+ path.join(pkg, 'node_modules', '@acme', 'glyph-data', 'index.js'),+ [+ "export const glyphEye = '<svg/>';",+ "export const glyphSun = '<svg/>';",+ "export const VERSION = '1.0.0';",+ '',+ ].join('\n'),+ );+ await setUp();+ expect((await wrap()).code).toBe(0);+ expect(exportsOf()).toEqual(['EyeIcon', 'SunIcon']);+ });+});++describe('module resolution', () => {+ it('resolves the library from a set package nested deeper than six folders below node_modules', async () => {+ const deep = path.join(tmp, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'icons');+ fs.mkdirSync(path.dirname(deep), {recursive: true});+ fs.renameSync(pkg, deep);+ // The library is installed at the top, as a hoisting package manager does.+ fs.mkdirSync(path.join(tmp, 'node_modules', '@acme'), {recursive: true});+ fs.renameSync(+ path.join(deep, 'node_modules', '@acme', 'glyph-library'),+ path.join(tmp, 'node_modules', '@acme', 'glyph-library'),+ );+ pkg = deep;+ await runCli(['experimental', 'icon', 'new-set', 'outline'], pkg);+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ 'Bin',+ '--from',+ '@acme/glyph-library',+ '--definition',+ 'delete',+ ]);+ expect(added.code).toBe(0);+ fs.writeFileSync(+ path.join(pkg, 'index.js'),+ "export * from './icon-sets/outline/outline.generated.js';\n",+ );+ const check = await runCli(['integration', 'check', '--json'], pkg);+ expect(check.stdout).not.toContain('icon_export_missing');+ }, 60_000);+});diff --git a/packages/cli/clients/cli/commands/icon-sets-guide.test.mjs b/packages/cli/clients/cli/commands/icon-sets-guide.test.mjsnew file mode 100644index 0000000000..ab1c690f7e--- /dev/null+++ b/packages/cli/clients/cli/commands/icon-sets-guide.test.mjs@@ -0,0 +1,186 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The icon-set guide reads on its experimental route, each section on+ * its own, and `astryx search` never returns it or any experimental doc+ * (spec:AST-017 FR27, spec:AST-084 FR11).+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {afterAll, beforeAll, describe, expect, it} from 'vitest';+import {runCli} from '../../../test-utils/run-cli.mjs';+import {formatCliCommand} from '../../../foundation/env/package-manager.mjs';+import {writeIconSetProject} from '../../../test-utils/icon-set-fixture.mjs';++const GUIDE = 'cli/experimental/icon-sets';++/** @type {string} */+let tmp;+/** @type {string} */+let withSet;+/** @type {string} */+let withoutSet;++beforeAll(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-icon-guide-'));+ withSet = writeIconSetProject(path.join(tmp, 'with'), {+ config: {experimental: {iconSet: 'glyphs'}},+ });+ withoutSet = writeIconSetProject(path.join(tmp, 'without'), {packages: []});+});++afterAll(() => {+ fs.rmSync(tmp, {recursive: true, force: true});+});++/** @param {string} query @param {string} cwd */+async function topDoc(query, cwd) {+ const {status, stdout} = await runCli(+ ['search', ...query.split(' '), '--type', 'doc', '--json'],+ cwd,+ );+ expect(status).toBe(0);+ return JSON.parse(stdout).data.results;+}++describe('icon-set guide', () => {+ it('search leaves every experimental doc out, with or without an icon set', async () => {+ // Icon sets join `astryx search` only at promotion (spec:AST-084 FR11);+ // the guide is read on its experimental route.+ for (const query of ['icon set', 'add icons', 'close']) {+ for (const result of [+ ...(await topDoc(query, withoutSet)),+ ...(await topDoc(query, withSet)),+ ]) {+ expect(result.name).not.toMatch(/experimental|icon-definitions/);+ expect(result.command).not.toMatch(/experimental|icon-definitions/);+ expect(result.section ?? '').not.toMatch(/^icon-(set|definition)/);+ }+ }+ });++ it('covers adding a set, adding icons, the export contract, library shapes, checks, and how apps use it', async () => {+ const {status, stdout} = await runCli(['docs', GUIDE, '--full']);+ expect(status).toBe(0);+ for (const phrase of [+ 'Icon sets are experimental',+ 'patch release',+ formatCliCommand('experimental icon new-set outline'),+ formatCliCommand(+ 'experimental icon add Bin --from @acme/glyph-library --definition delete',+ ),+ '--new-definition',+ formatCliCommand('docs cli/experimental/icon-definitions'),+ 'icon_builtin_definition_missing',+ 'Unmapped icon definitions (optional)',+ 'unmappedDefinitions',+ 'icon_module_not_public',+ 'icon_not_component',+ 'Not checked',+ 'icon_module_invalid',+ 'icon_generated_types_mismatch',+ 'themeIcons',+ "defineTheme({name: 'brand', icons: themeIcons})",+ 'prepublishOnly',+ 'optional peer',+ 'never fail a check',+ 'adapter',+ '`experimental.iconSet`',+ '`experimental.iconSets`',+ '`icon.newSet`',+ ]) {+ expect(stdout).toContain(phrase);+ }+ });++ it('tells authors no version range promises icon sets, and what a CLI without them says', async () => {+ const {stdout} = await runCli(['docs', GUIDE, 'publish']);+ expect(stdout).toContain('no version range promises them');+ expect(stdout).not.toContain('>=0.8.0');+ expect(stdout).toContain('published against a newer Astryx CLI');+ const versioning = await runCli([+ 'docs',+ 'cli/integrations/ship/versioning',+ '--full',+ ]);+ expect(versioning.stdout).not.toMatch(/icon/i);+ });++ it('every icon-set doc says it is experimental and carries the marker', async () => {+ for (const route of [+ 'cli/experimental',+ GUIDE,+ 'cli/experimental/icon-definitions',+ 'cli/commands/experimental-icon',+ 'cli/commands/experimental-icon-new-set',+ ]) {+ const {status, stdout} = await runCli(['docs', route, '--json']);+ expect(status, route).toBe(0);+ expect(stdout, route).toMatch(/[Ee]xperimental/);+ }+ });++ // The guide's list of JSON types is every `icon.*` response type: a new one+ // fails here until the guide names it.+ it("names every icon response type in 'Where icon sets show up'", async () => {+ const {doc} =+ await import('../../../foundation/response/response-types.doc.mjs');+ const types = doc.members+ .map((/** @type {{value: string}} */ member) => member.value)+ .filter((/** @type {string} */ value) => value.startsWith('icon.'))+ .sort();+ expect(types.length).toBeGreaterThan(5);+ const {stdout} = await runCli(['docs', GUIDE, '--json']);+ const section = JSON.parse(stdout).data.sections.find(+ (/** @type {any} */ each) => each.title === 'Where icon sets show up',+ );+ const row = section.content+ .find((/** @type {any} */ block) => block.type === 'table')+ .rows.find((/** @type {string[]} */ each) => each[0] === 'JSON types');+ expect(+ [...row[1].matchAll(/`(icon\.\w+)`/gu)].map(([, t]) => t).sort(),+ ).toEqual(types);+ });++ // A set's own definitions join the namespace only in a project that opts+ // in, as FR4 says; Astryx's are always there.+ it("lists a set's own icon definitions only with experimental.iconSet", async () => {+ const definition = `/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export default {type: 'icon-definition', name: 'rocketLaunch', description: 'Launch something.', words: ['launch', 'liftoff']};+`;+ /** @param {string} name @param {Record<string, unknown>} config */+ const project = (name, config) => {+ const dir = writeIconSetProject(path.join(tmp, name), {+ packages: [{definitions: {rocketLaunch: definition}}],+ config,+ });+ return dir;+ };+ const optedIn = project('own-defs-opted-in', {+ integrations: ['@acme/glyphs'],+ experimental: {iconSet: 'glyphs'},+ });+ const notOptedIn = project('own-defs-no-opt-in', {+ integrations: ['@acme/glyphs'],+ });+ /** @param {string} cwd */+ const routes = async cwd => {+ const {status, stdout} = await runCli(+ ['docs', 'cli/experimental/icon-definitions', '--json'],+ cwd,+ );+ expect(status).toBe(0);+ return JSON.parse(stdout).data.slots.flatMap((/** @type {any} */ slot) =>+ slot.children.map((/** @type {any} */ child) => child.name),+ );+ };+ const withOptIn = await routes(optedIn);+ const without = await routes(notOptedIn);+ expect(withOptIn).toContain('rocket-launch');+ expect(without).not.toContain('rocket-launch');+ expect(without).toContain('close');+ expect(withOptIn.filter(name => name !== 'rocket-launch')).toEqual(without);+ });+});diff --git a/packages/cli/clients/cli/commands/icon.test.mjs b/packages/cli/clients/cli/commands/icon.test.mjsnew file mode 100644index 0000000000..b5b78e5d87--- /dev/null+++ b/packages/cli/clients/cli/commands/icon.test.mjs@@ -0,0 +1,96 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx experimental icon` end to end (AST-084 FR6, FR7): text and JSON, exit+ * codes, and the envelope package, driving the real program in-process.+ */++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 {runCli} from '../../../test-utils/run-cli.mjs';+import {writeIconSetProject} from '../../../test-utils/icon-set-fixture.mjs';++/** @type {string} */+let tmp;+/** @type {string} */+let cwd;+beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-icon-cli-'));+ cwd = writeIconSetProject(tmp);+});+afterEach(() => {+ fs.rmSync(tmp, {recursive: true, force: true});+});++describe('astryx experimental icon', () => {+ it('prints ranked matches with import lines; every word is the query', async () => {+ const res = await runCli(['experimental', 'icon', 'delete'], cwd);+ expect(res.code).toBe(0);+ expect(res.stdout).toContain('Icons for "delete" (1)');+ expect(res.stdout).toMatch(+ /import: +import \{TrashIcon\} from '@acme\/glyphs';/,+ );+ expect(res.stdout).toMatch(/package: +@acme\/glyphs/);+ expect(res.stdout).toMatch(/variant: +solid/);+ const many = await runCli(+ ['experimental', 'icon', 'magni', 'fier', '--json'],+ cwd,+ );+ expect(JSON.parse(many.stdout).data.query).toBe('magni fier');+ });++ it('answers icon.search, icon.detail, and icon.list as JSON', async () => {+ const search = JSON.parse(+ (await runCli(['experimental', 'icon', 'close', '--json'], cwd)).stdout,+ );+ expect(search).toMatchObject({type: 'icon.search', data: {matchCount: 1}});+ const detail = JSON.parse(+ (await runCli(['experimental', 'icon', 'glyphs/x', '--json'], cwd))+ .stdout,+ );+ expect(Object.keys(detail).slice(0, 3)).toEqual([+ 'apiVersion',+ 'type',+ 'package',+ ]);+ expect(detail).toMatchObject({+ type: 'icon.detail',+ package: '@acme/glyphs',+ });+ const list = JSON.parse(+ (await runCli(['experimental', 'icon', '--list', '--json'], cwd)).stdout,+ );+ expect(list).toMatchObject({type: 'icon.list', data: {status: 'selected'}});+ });++ it('exits 1 with ERR_NOT_FOUND for an unknown icon, the same way in text and JSON', async () => {+ const text = await runCli(['experimental', 'icon', 'glyphs/nope'], cwd);+ const json = await runCli(+ ['experimental', 'icon', 'glyphs/nope', '--json'],+ cwd,+ );+ expect(text.code).toBe(1);+ expect(json.code).toBe(1);+ expect(JSON.parse(json.stdout).code).toBe('ERR_NOT_FOUND');+ });++ it('no match exits 0 and points at the set list', async () => {+ const res = await runCli(['experimental', 'icon', 'zebra'], cwd);+ expect(res.code).toBe(0);+ expect(res.stdout).toContain('No icons match "zebra".');+ expect(res.stdout).toContain('icon --list');+ });++ it('lists the sets in text, with the withdrawn ones', async () => {+ const broken = writeIconSetProject(path.join(tmp, 'b'), {+ packages: [{}, {name: '@acme/lines', data: '{nope'}],+ });+ const res = await runCli(['experimental', 'icon', '--list'], broken);+ expect(res.code).toBe(0);+ expect(res.stdout).toContain('name: glyphs');+ expect(res.stdout).toContain('Withdrawn');+ expect(res.stdout).toContain('@acme/lines/lines');+ });+});diff --git a/packages/cli/clients/cli/commands/integration.mjs b/packages/cli/clients/cli/commands/integration.mjsindex f7270798a8..8fbc72fb55 100644--- a/packages/cli/clients/cli/commands/integration.mjs+++ b/packages/cli/clients/cli/commands/integration.mjs@@ -77,6 +77,24 @@ async function verifyPackage(program) {),);}+ // Only a package that ships an experimental icon set gets this line;+ // every other package's output is unchanged.+ const local = result.data.contributions?.local;+ if (local && (local.iconSets ?? []).length > 0) {+ const counts = [+ ['component', local.components.length],+ ['template', local.templates.length],+ ['theme', local.themes.length],+ ['doc topic', local.docs.length],+ ['codemod', local.codemods.length],+ ['icon set', (local.iconSets ?? []).length],+ ]+ .filter(([, count]) => Number(count) > 0)+ .map(([word, count]) => `${count} ${word}${count === 1 ? '' : 's'}`);+ if (counts.length > 0) {+ blocks.push(text(`Contributes ${counts.join(', ')}.`));+ }+ }if (issues.length > 0) {blocks.push(list(@@ -132,10 +150,14 @@ async function checkPackage(program, options) {),);} else {+ // A package-wide issue every check reports is printed once, under the+ // first check; the counts below are unchanged.+ /** @type {Set<string>} */+ const seen = new Set();data.checks.forEach((check, index) => {// A blank line keeps each check's output apart from the next.if (index > 0) emit(text(''));- printIntegrationCheckResponse(check.response);+ printIntegrationCheckResponse(check.response, seen);});}const plural = (/** @type {number} */ n, /** @type {string} */ word) =>diff --git a/packages/cli/clients/cli/commands/template.icons.test.mjs b/packages/cli/clients/cli/commands/template.icons.test.mjsnew file mode 100644index 0000000000..1380b8258a--- /dev/null+++ b/packages/cli/clients/cli/commands/template.icons.test.mjs@@ -0,0 +1,132 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Copied and printed templates follow the project's icon set+ * (AST-084 FR9, FR10): the JSON and the copy receipt report every icon,+ * and printed source keeps stdout to the source with the report on stderr.+ */++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 {runCli} from '../../../test-utils/run-cli.mjs';+import {writeIconSetProject} from '../../../test-utils/icon-set-fixture.mjs';++/** @type {string} */+let tmp;+beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-template-icons-'));+});+afterEach(() => {+ fs.rmSync(tmp, {recursive: true, force: true});+});++// ai-chat imports XMarkIcon (the close definition) and icons the fixture set lacks.+const TEMPLATE = 'ai-chat';++describe('template icon mapping', () => {+ it('printed source maps icons; the report goes to stderr', async () => {+ const cwd = writeIconSetProject(tmp, {+ config: {experimental: {iconSet: 'glyphs'}},+ });+ const res = await runCli(['template', TEMPLATE], cwd);+ expect(res.code).toBe(0);+ expect(res.stdout).toContain("import {XIcon} from '@acme/glyphs';");+ expect(res.stdout).not.toMatch(/\bXMarkIcon\b/);+ expect(res.stdout).not.toContain('icons: ');+ expect(res.stderr).toContain(+ 'icons: mapped XMarkIcon (@heroicons/react/24/outline) -> XIcon (@acme/glyphs) by definition',+ );+ expect(res.stderr).toMatch(+ /icons: kept \w+ \(@heroicons\/react\/24\/outline\)/,+ );+ });++ it('the JSON and the copy receipt report mapped and kept icons; kept libraries stay needed', async () => {+ const cwd = writeIconSetProject(tmp, {+ config: {experimental: {iconSet: 'glyphs'}},+ });+ const shown = JSON.parse(+ (await runCli(['template', TEMPLATE, '--json'], cwd)).stdout,+ );+ expect(shown.data.icons).toMatchObject({+ status: 'selected',+ set: '@acme/glyphs/glyphs',+ });+ const copied = JSON.parse(+ (await runCli(['template', TEMPLATE, './out', '--json'], cwd)).stdout,+ );+ expect(copied.data.icons).toEqual(shown.data.icons);+ expect(copied.data.icons.mapped[0]).toMatchObject({+ source: {module: '@heroicons/react/24/outline', export: 'XMarkIcon'},+ target: {set: 'glyphs', id: 'x', export: 'XIcon'},+ by: 'definition',+ });+ expect(copied.data.icons.kept.length).toBeGreaterThan(0);+ expect(copied.data.missingPackages).toContain('@heroicons/react');+ const written = fs.readFileSync(path.join(cwd, 'out', 'page.tsx'), 'utf-8');+ expect(written).toBe(shown.data.source);+ });++ it('experimental.iconSet that two packages ship: source unchanged, status ambiguous', async () => {+ // A name both packages ship names no set.+ const cwd = writeIconSetProject(tmp, {+ packages: [{}, {name: '@acme/lines', set: 'glyphs'}],+ config: {experimental: {iconSet: 'glyphs'}},+ });+ const res = await runCli(['template', TEMPLATE, '--json'], cwd);+ const data = JSON.parse(res.stdout).data;+ expect(data.icons).toMatchObject({+ status: 'ambiguous',+ mapped: [],+ kept: [],+ });+ expect(data.source).toMatch(/\bXMarkIcon\b/);+ const text = await runCli(['template', TEMPLATE], cwd);+ expect(text.stderr).toContain('icons: unchanged (ambiguous)');+ });++ it('a set installed but experimental.iconSet not set: no report, and the output it always had', async () => {+ // Icon sets are experimental (spec:AST-017 FR27): nothing changes+ // until the project opts in.+ const cwd = writeIconSetProject(path.join(tmp, 'none'));+ const res = await runCli(['template', TEMPLATE, '--json'], cwd);+ const data = JSON.parse(res.stdout).data;+ expect(data).not.toHaveProperty('icons');+ expect(data.source).toMatch(/\bXMarkIcon\b/);+ const text = await runCli(['template', TEMPLATE], cwd);+ expect(text.stderr).not.toContain('icons:');+ const copied = await runCli(['template', TEMPLATE, 'out', '--json'], cwd);+ expect(JSON.parse(copied.stdout).data).not.toHaveProperty('icons');+ const copiedText = await runCli(['template', TEMPLATE, 'out2'], cwd);+ expect(`${copiedText.stdout}${copiedText.stderr}`).not.toContain('icons:');+ });++ it('a configured set that is installed but withdrawn says so, with why, and maps nothing', async () => {+ const cwd = writeIconSetProject(path.join(tmp, 'withdrawn'), {+ packages: [{data: '{nope'}],+ config: {experimental: {iconSet: 'glyphs'}},+ });+ const res = await runCli(['template', TEMPLATE, '--json'], cwd);+ const icons = JSON.parse(res.stdout).data.icons;+ expect(icons).toMatchObject({status: 'withdrawn', set: null, mapped: []});+ expect(icons.reason).toMatch(+ /names "glyphs", which is installed but withdrawn: .*not valid JSON/,+ );+ const text = await runCli(['template', TEMPLATE], cwd);+ expect(text.stderr).toContain('icons: unchanged (withdrawn):');+ });++ it('a configured set that is not installed reports why nothing was mapped', async () => {+ const cwd = writeIconSetProject(path.join(tmp, 'missing'), {+ packages: [],+ config: {experimental: {iconSet: 'nope'}},+ });+ const res = await runCli(['template', TEMPLATE, '--json'], cwd);+ expect(JSON.parse(res.stdout).data.icons).toMatchObject({+ status: 'missing',+ mapped: [],+ });+ });+});diff --git a/packages/cli/clients/cli/commands/template.mjs b/packages/cli/clients/cli/commands/template.mjsindex fc2cc4bdc3..c27deb66a1 100644--- a/packages/cli/clients/cli/commands/template.mjs+++ b/packages/cli/clients/cli/commands/template.mjs@@ -32,6 +32,35 @@ export {discoverTemplates, listTemplates} from '../../../api/template/template.m* )} TemplateResponse*/+/**+ * The icon report as text lines (AST-084 FR10): one line per mapped or kept+ * icon, or one line saying why nothing was mapped. Nothing when the project+ * has no icon set at all (no report: icon sets are experimental).+ * @param {import('../../../api/template/template.type.mjs').TemplateIconsReport | undefined} icons+ * @returns {string[]}+ */+function iconLines(icons) {+ if (icons == null) return [];+ if (icons.status !== 'selected') {+ return icons.status === 'none'+ ? []+ : [`icons: unchanged (${icons.status}): ${icons.reason}`];+ }+ return [+ ...icons.mapped.map(+ each =>+ `icons: mapped ${each.source.export} (${each.source.module}) -> ${each.target.export} (${each.target.module}) by ${each.by}`,+ ),+ ...icons.kept.map(+ each =>+ `icons: kept ${each.export}${each.module == null ? '' : ` (${each.module})`}: ${each.reason}` ++ (each.suggestion+ ? `; likely match: ${each.suggestion.export} (${each.suggestion.module})`+ : ''),+ ),+ ];+}+/*** What the run answered with. Listing and printing a template are lookups;* scaffolding one into a project (or writing the CDN starter) is a file@@ -213,7 +242,7 @@ export function registerTemplate(program) {// from (cli-surface INV28) and the note about replaced demo media go// to stderr, the note in the copy receipt's words. (Text mode only:// --json returned above with both in the envelope.)- const {source, demoMediaReplaced} = result.data;+ const {source, demoMediaReplaced, icons} = result.data;console.error(`package: ${result.package}`);emit(code(source));if (demoMediaReplaced > 0) {@@ -222,12 +251,16 @@ export function registerTemplate(program) {'images now show a neutral placeholder and videos have an empty source. Supply your own media there.',);}+ // The icon report goes to stderr too, so stdout stays the source.+ for (const line of iconLines(icons)) console.error(line);break;}case 'template.copy': {- const {outputDir, fileName, demoMediaReplaced, notes} = result.data;+ const {outputDir, fileName, demoMediaReplaced, notes, icons} =+ result.data;const file = `${outputDir}/${fileName}`;+ const iconText = iconLines(icons);emit(text(`Copied template to ${file}`),record({package: result.package}),@@ -237,6 +270,7 @@ export function registerTemplate(program) {'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)),+ iconText.length > 0 && text(iconText.join('\n')),);break;}diff --git a/packages/cli/clients/cli/commands/text-json-parity.test.mjs b/packages/cli/clients/cli/commands/text-json-parity.test.mjsindex 453d01b396..f990a30aad 100644--- a/packages/cli/clients/cli/commands/text-json-parity.test.mjs+++ b/packages/cli/clients/cli/commands/text-json-parity.test.mjs@@ -31,6 +31,7 @@ import * as path from 'node:path';import * as os from 'node:os';import {fileURLToPath} from 'node:url';import {runCli} from '../../../test-utils/run-cli.mjs';+import {writeIconPackage} from '../../../test-utils/icon-set-fixture.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));const REPO_ROOT = path.resolve(__dirname, '../../../../..');@@ -399,6 +400,26 @@ const CASES = [args: ['integration', 'pack', '--check'],skipFieldChecks: true,},+ {+ name: 'experimental icon',+ args: ['experimental', 'icon', 'remove'],+ cwd: '__TMP__',+ // A project with the synthetic icon set installed.+ setup: dir => {+ writeIconPackage(path.join(dir, 'node_modules', '@acme', 'glyphs'));+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name: 'app', dependencies: {'@acme/glyphs': '1.0.0'}}),+ );+ },+ jsonFieldAllowlist: [+ 'matchCount — stated in section heading "Icons for ... (N)"',+ 'query — stated in section heading',+ 'module — part of the import line',+ 'export — part of the import line',+ 'score — the reason states the tier',+ ],+ },{name: 'manifest',args: ['manifest'],@@ -443,6 +464,36 @@ const CASES = [errorExpected: true,skipFieldChecks: true,},+ {+ name: 'experimental icon use',+ args: ['experimental', 'icon', 'use', 'does-not-exist'],+ errorExpected: true,+ skipFieldChecks: true,+ },+ {+ name: 'experimental icon map',+ args: ['experimental', 'icon', 'map', 'close', 'x'],+ errorExpected: true,+ skipFieldChecks: true,+ },+ {+ name: 'experimental icon new-set',+ args: ['experimental', 'icon', 'new-set', 'Not-Kebab'],+ errorExpected: true,+ skipFieldChecks: true,+ },+ {+ name: 'experimental icon new-definition',+ args: ['experimental', 'icon', 'new-definition', 'not-camel'],+ errorExpected: true,+ skipFieldChecks: true,+ },+ {+ name: 'experimental icon add',+ args: ['experimental', 'icon', 'add', 'XIcon', '--from', 'does-not-exist'],+ errorExpected: true,+ skipFieldChecks: true,+ },{name: 'theme use',args: ['theme', 'use', 'does-not-exist'],diff --git a/packages/cli/clients/cli/formatters/index.mjs b/packages/cli/clients/cli/formatters/index.mjsindex 161e62a731..dcc8f17334 100644--- a/packages/cli/clients/cli/formatters/index.mjs+++ b/packages/cli/clients/cli/formatters/index.mjs@@ -119,6 +119,9 @@ export class Block {* @property {'wrap' | 'truncate'} [overflow] - What an inline record longer* than {@link WRAP_WIDTH} does: `wrap` (the default) continues under the* first column; `truncate` cuts it to one line.+ * @property {(item: any) => boolean} [sizesColumn] - Which inline records the+ * first column is sized from (default: all). A record left out keeps its+ * place and overhangs a narrower column, so adding it changes no other line.*//** @param {unknown} v @returns {boolean} */@@ -318,8 +321,12 @@ function inlineRecords(items, options) {return fmt ? fmt(o[k]) : renderValue(o[k]);};const leads = items.map(o => (isEmpty(o[lead]) ? '' : value(o, lead)));+ const sizes = options.sizesColumn ?? (() => true);const column = Math.min(- Math.max(0, ...leads.map(l => displayWidth(l))),+ Math.max(+ 0,+ ...leads.filter((_, i) => sizes(items[i])).map(l => displayWidth(l)),+ ),INLINE_LEAD_MAX,);const indent = ' '.repeat(column + 2);diff --git a/packages/cli/clients/cli/formatters/index.test.mjs b/packages/cli/clients/cli/formatters/index.test.mjsindex 57b43c8c02..afdd989b5b 100644--- a/packages/cli/clients/cli/formatters/index.test.mjs+++ b/packages/cli/clients/cli/formatters/index.test.mjs@@ -186,6 +186,21 @@ describe('records inline layout', () => {).toBe('a Alpha - First.\nbbb Beta');});+ it('sizes the first column from the records sizesColumn keeps; another overhangs it', () => {+ const rows = [+ {id: 'a', summary: 'First.'},+ {id: 'a-much-longer-name', summary: 'Extra.', extra: true},+ {id: 'bbb', summary: 'Third.'},+ ];+ expect(+ records(rows, {+ fields: ['id', 'summary'],+ layout: 'inline',+ sizesColumn: row => !row.extra,+ }).toString(),+ ).toBe('a First.\na-much-longer-name Extra.\nbbb Third.');+ });+it('wraps a long record under the first column', () => {const out = records([{id: 'a', text: 'word '.repeat(40).trim()}], {layout: 'inline',diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjsindex dfa3edc4cb..817517d55c 100644--- a/packages/cli/clients/cli/index.mjs+++ b/packages/cli/clients/cli/index.mjs@@ -93,6 +93,12 @@ export const JSON_SUPPORTED = new Set(['blog','discover','search',+ 'experimental icon',+ 'experimental icon add',+ 'experimental icon map',+ 'experimental icon use',+ 'experimental icon new-set',+ 'experimental icon new-definition','build','swizzle','gap-report',@@ -309,6 +315,13 @@ const commands = [{name: 'search', path: './commands/search.mjs', register: 'registerSearch'},{name: 'build', path: './commands/build.mjs', register: 'registerBuild'},{name: 'doctor', path: './commands/doctor.mjs', register: 'registerDoctor'},+ // Experimental commands (spec:AST-017 FR27): last, so every stable command+ // keeps its place in help.+ {+ name: 'experimental',+ path: './commands/experimental/index.mjs',+ register: 'registerExperimental',+ },// Registered after every other command: the manifest lists the commands in// registration order.{name: 'manifest', path: './commands/manifest.mjs', register: 'registerManifest'},diff --git a/packages/cli/clients/cli/lib/define-command.mjs b/packages/cli/clients/cli/lib/define-command.mjsindex a4131ed435..ba25f7f466 100644--- a/packages/cli/clients/cli/lib/define-command.mjs+++ b/packages/cli/clients/cli/lib/define-command.mjs@@ -129,6 +129,10 @@ export function defineCommand(parent, doc, {fn, action, hidden} = {}) {Object.defineProperty(cmd, COMMAND_DOCS, {value: {doc, fn}, configurable: true});// Help shows doc tokens as commands, the way `astryx docs` does.if (doc.summary) cmd.description(renderTokens(doc.summary));+ // An experimental command says so wherever its name is listed in help.+ if (doc.stability === 'experimental') {+ cmd.description(`[experimental] ${cmd.description() || ''}`.trimEnd());+ }if (doc.deprecated) {const base = cmd.description() || '';cmd.description(`${base} [DEPRECATED: ${doc.deprecated}]`);diff --git a/packages/cli/foundation/config/config-writer.mjs b/packages/cli/foundation/config/config-writer.mjsnew file mode 100644index 0000000000..a70d8cc5c3--- /dev/null+++ b/packages/cli/foundation/config/config-writer.mjs@@ -0,0 +1,202 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Write one string field of a project's astryx.config.+ *+ * The field is a top-level key or a dotted path into nested object literals+ * (`experimental.iconSet`); a missing object on the path is created.+ *+ * Edits the default-exported object literal in place (comments and other+ * fields kept), or creates `astryx.config.mjs` when the project has no+ * config. A config whose default export is not a static object literal, or+ * whose object on the path spreads another (`{...base}`), is refused rather+ * than rewritten: a key written beside a spread could replace what it sets.+ *+ * Before any write the target is classified like every other consumer-file+ * writer (spec:AST-040 FR2, FR8): a config reached through a symbolic link,+ * marked generated or vendored, ignored, or otherwise protected is refused with+ * `ERR_CODEMOD_PROTECTED` naming the protecting declaration, and an unreadable+ * protection source fails with `ERR_CODEMOD_PROTECTION_SOURCE`.+ *+ * @input A project directory, a field name, and its string value+ * @output The config file written and the value it replaced+ * @position packages/cli/foundation/config — read by `astryx experimental icon use`+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {randomUUID} from 'node:crypto';+import jscodeshift from 'jscodeshift';+import {+ findManifestObject,+ unwrapManifestExpression,+} from '../integrations/manifest-writer.mjs';+import {createFileProtectionResolver} from '../fs/file-protection.mjs';+import {CONFIG_BASENAMES} from './project.mjs';++/** A protected astryx.config the writer refused to touch. */+export class ConfigProtectedError extends Error {+ /**+ * @param {string} file+ * @param {import('../fs/file-protection.mjs').FileProtection[]} protections+ */+ constructor(file, protections) {+ const declarations = protections.map(item => item.declaration).join('; ');+ super(+ `Could not update ${path.basename(file)}: it is protected by ${declarations}. Set the value at its source yourself.`,+ );+ this.name = 'ConfigProtectedError';+ this.code = 'ERR_CODEMOD_PROTECTED';+ this.file = file;+ this.protections = protections;+ }+}++/**+ * Refuse to write `file` when the project protects it (spec:AST-040 FR2).+ * @param {string} projectDir+ * @param {string} file+ */+function assertWritable(projectDir, file) {+ const protections = createFileProtectionResolver(projectDir).classify(file);+ if (protections.length > 0) throw new ConfigProtectedError(file, protections);+}++/** @param {any} property a member of an object literal */+function isSpread(property) {+ return [+ 'SpreadElement',+ 'SpreadProperty',+ 'ExperimentalSpreadProperty',+ ].includes(property?.type);+}++/** @param {any} property @param {string} name */+function propertyNamed(property, name) {+ if (+ !property ||+ !['ObjectProperty', 'Property'].includes(property.type) ||+ property.computed+ ) {+ return false;+ }+ return (+ (property.key?.type === 'Identifier' && property.key.name === name) ||+ (['Literal', 'StringLiteral'].includes(property.key?.type) &&+ property.key.value === name)+ );+}++/**+ * Set `key` to `value` in the project's astryx.config.+ * @param {string} projectDir+ * @param {string} key a top-level key, or a dotted path (`experimental.iconSet`)+ * @param {string} value+ * @returns {{file: string, created: boolean, previous: string | null, changed: boolean}}+ */+export function setConfigString(projectDir, key, value) {+ const keys = key.split('.');+ const leaf = /** @type {string} */ (keys[keys.length - 1]);+ const existing = CONFIG_BASENAMES.map(name =>+ path.join(projectDir, name),+ ).find(file => fs.existsSync(file));+ if (!existing) {+ const file = path.join(projectDir, 'astryx.config.mjs');+ assertWritable(projectDir, file);+ const quoted = `'${value.replace(/\\/gu, '\\\\').replace(/'/gu, "\\'")}'`;+ // Each key on the path opens one nested object: `experimental: {`.+ const open = keys+ .slice(0, -1)+ .map((each, depth) => `${' '.repeat(depth + 1)}${each}: {\n`)+ .join('');+ const close = keys+ .slice(0, -1)+ .map((_, depth) => `${' '.repeat(depth + 1)}},\n`)+ .reverse()+ .join('');+ writeAtomically(+ file,+ `export default {\n${open}${' '.repeat(keys.length)}${leaf}: ${quoted},\n${close}};\n`,+ );+ return {file, created: true, previous: null, changed: true};+ }+ assertWritable(projectDir, existing);+ const source = fs.readFileSync(existing, 'utf-8');+ const j = jscodeshift.withParser('tsx');+ const ast = j(source);+ let object = findManifestObject(j, ast);+ const refuse = () =>+ new Error(+ `Could not update ${path.basename(existing)} safely: its default export is not a static object literal. Set "${key}: '${value}'" in it yourself.`,+ );+ if (!object) throw refuse();+ // A spread on the path can hold the same keys: a key added beside it would+ // shadow the spread's whole object and drop what it sets, so nothing is+ // written there (`{...base}` may set `experimental.xle`).+ /** @param {any} holder @param {string} where */+ const assertNoSpread = (holder, where) => {+ if (holder.properties.some((/** @type {any} */ each) => isSpread(each))) {+ throw new Error(+ `Could not update ${path.basename(existing)} safely: ${where} spreads another object (\`...\`), whose keys a written "${key}" could replace. Set "${key}: '${value}'" in it yourself.`,+ );+ }+ };+ assertNoSpread(object, 'its default export');+ for (const each of keys.slice(0, -1)) {+ const holder = object.properties.find((/** @type {any} */ property) =>+ propertyNamed(property, each),+ );+ if (!holder) {+ const created = j.objectExpression([]);+ object.properties.push(j.objectProperty(j.identifier(each), created));+ object = created;+ continue;+ }+ const nested = unwrapManifestExpression(holder.value);+ if (!j.ObjectExpression.check(nested)) throw refuse();+ assertNoSpread(nested, `its "${each}" object`);+ object = nested;+ }+ const property = object.properties.find((/** @type {any} */ each) =>+ propertyNamed(each, leaf),+ );+ /** @type {string | null} */+ let previous = null;+ if (property) {+ const current = property.value;+ previous =+ current?.type === 'StringLiteral' || current?.type === 'Literal'+ ? String(current.value)+ : null;+ if (previous === value) {+ return {file: existing, created: false, previous, changed: false};+ }+ property.value = j.stringLiteral(value);+ } else {+ object.properties.push(+ j.objectProperty(j.identifier(leaf), j.stringLiteral(value)),+ );+ }+ let next = ast.toSource({quote: 'single', reuseWhitespace: true});+ if (source.endsWith('\n') && !next.endsWith('\n')) next += '\n';+ writeAtomically(existing, next);+ return {file: existing, created: false, previous, changed: true};+}++/**+ * @param {string} file+ * @param {string} text+ */+function writeAtomically(file, text) {+ const temporary = path.join(+ path.dirname(file),+ `.${path.basename(file)}.tmp-${randomUUID()}`,+ );+ try {+ fs.writeFileSync(temporary, text, 'utf-8');+ fs.renameSync(temporary, file);+ } catch (error) {+ fs.rmSync(temporary, {force: true});+ throw error;+ }+}diff --git a/packages/cli/foundation/config/config-writer.test.mjs b/packages/cli/foundation/config/config-writer.test.mjsnew file mode 100644index 0000000000..89471122a5--- /dev/null+++ b/packages/cli/foundation/config/config-writer.test.mjs@@ -0,0 +1,84 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `setConfigString` (the writer behind `astryx experimental icon use`):+ * a key written beside a spread could replace what the spread sets, so a+ * config whose object on the path spreads another is refused and left as it+ * was; a plain literal is written, and an existing literal object keeps its+ * other keys.+ */++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 {setConfigString} from './config-writer.mjs';++/** @type {string} */+let dir;+beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-config-writer-'));+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"app"}\n');+});+afterEach(() => {+ fs.rmSync(dir, {recursive: true, force: true});+});++/** @param {string} text */+const writeConfig = text =>+ fs.writeFileSync(path.join(dir, 'astryx.config.mjs'), text);+const readConfig = () =>+ fs.readFileSync(path.join(dir, 'astryx.config.mjs'), 'utf-8');++describe('setConfigString beside a spread', () => {+ it('refuses a default export that spreads another object, and leaves it as it was', () => {+ const before = `import base from './base.mjs';++export default {+ ...base,+ integrations: [],+};+`;+ writeConfig(before);+ expect(() =>+ setConfigString(dir, 'experimental.iconSet', 'glyphs'),+ ).toThrow(+ /its default export spreads another object \(`\.\.\.`\).*Set "experimental\.iconSet: 'glyphs'" in it yourself/u,+ );+ expect(readConfig()).toBe(before);+ });++ it('refuses an experimental object that spreads another, and leaves it as it was', () => {+ const before = `const shared = {xle: {components: ['./xle']}};++export default {+ experimental: {...shared},+};+`;+ writeConfig(before);+ expect(() =>+ setConfigString(dir, 'experimental.iconSet', 'glyphs'),+ ).toThrow(/its "experimental" object spreads another object/u);+ expect(readConfig()).toBe(before);+ });++ it('writes a plain literal', () => {+ writeConfig('export default {\n integrations: [],\n};\n');+ const result = setConfigString(dir, 'experimental.iconSet', 'glyphs');+ expect(result).toMatchObject({created: false, changed: true});+ const text = readConfig();+ expect(text).toContain('integrations: []');+ expect(text).toMatch(/experimental: \{\s*iconSet: 'glyphs'/u);+ });++ it('adds iconSet inside an existing literal experimental object, keeping its other keys', () => {+ writeConfig(+ "export default {\n experimental: {\n xle: {components: ['./xle']},\n },\n};\n",+ );+ setConfigString(dir, 'experimental.iconSet', 'glyphs');+ const text = readConfig();+ expect(text).toContain("xle: {components: ['./xle']}");+ expect(text).toContain("iconSet: 'glyphs'");+ expect(text.match(/experimental:/gu)).toHaveLength(1);+ });+});diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjsindex 5c49ffde61..ddc8efe72e 100644--- a/packages/cli/foundation/config/project.mjs+++ b/packages/cli/foundation/config/project.mjs@@ -6,7 +6,7 @@* `Project` is the one entry point a command uses to read everything it needs* about a consumer's project: the validated config surface, the configured* integrations, and the resolved discovery sets (components, templates,- * codemods, docs, themes) — plus issue routing (issuesUrl) and the accumulated+ * codemods, docs, themes, icon sets) — plus issue routing (issuesUrl) and the accumulated* integration issues. It replaces the old `loadConfig(cwd)` plain-object loader* and the per-command fan-out into the various discovery helpers.*@@ -18,7 +18,7 @@* package being authored when it carries a manifest. Provider identity is* resolved once over all three (see integrations/provider-resolution), and* the ledger is kept for {@link providerLedgerOf}. Discovery is LAZY.- * - Discovery methods (components/templates/codemods/docs/themes) are MEMOIZED per+ * - Discovery methods (components/templates/codemods/docs/themes/iconSets) are MEMOIZED per* instance (via the pluggable cache) and orchestrate the EXISTING discovery* functions — Project never reimplements discovery.* - SKIP + WARN policy: discovery records each integration issue. Other valid@@ -82,6 +82,12 @@ import {discoverIntegrationThemes,discoverLocalThemes,} from '../discovery/theme-discovery.mjs';+import {+ chooseProjectIconSet,+ discoverIntegrationIconSets,+ orderIconSets,+} from '../discovery/icon-set-discovery.mjs';+import {iconDefinitionTreeInput} from '../doc-compiler/tree.mjs';import {getTransformsBetween} from '../../assets/codemods/registry.mjs';import {discoverIntegrationCodemods,@@ -743,7 +749,13 @@ export class Project {return;}try {- const found = await validateLoadedIntegration(integration);+ // An experimental root is checked only in a project that opts in+ // (spec:AST-017 FR27); the package's own checks read it either way.+ const found = await validateLoadedIntegration(+ this.#config.experimental?.iconSet+ ? integration+ : {...integration, iconSets: undefined},+ );for (const issue of found ?? []) this.#pushIssue(pkg, issue);} catch (err) {this.#pushIssue(pkg, {@@ -954,6 +966,75 @@ export class Project {});}+ /**+ * Installed icon sets, the sets withdrawn and why, and the project's icon+ * set (AST-084 FR7, FR8). Sets come from each loaded integration's+ * `iconSets` root in load order; `sets` puts the project's set first, the+ * tie order every icon surface uses. A set whose descriptor or data file is+ * invalid is withdrawn and reported as an `invalid_icon_set` issue; a set+ * whose module does not resolve from the project is withdrawn without one.+ *+ * Icon sets are experimental (spec:AST-017 FR27): every surface but+ * `astryx experimental icon` reads them only in a project that sets+ * `experimental.iconSet`. Without it this answers no sets and records no+ * issue, unless `experimental` asks for the installed sets anyway.+ *+ * @param {{experimental?: boolean}} [options] `experimental`: read the+ * installed sets without the opt-in, for `astryx experimental icon`+ * @returns {Promise<{sets: import('../discovery/icon-set-discovery.mjs').DiscoveredIconSet[], withdrawn: import('../discovery/icon-set-discovery.mjs').WithdrawnIconSet[], choice: import('../discovery/icon-set-discovery.mjs').IconSetChoice}>}+ */+ async iconSets({experimental = false} = {}) {+ if (!experimental && !this.#config.experimental?.iconSet) {+ return {+ sets: [],+ withdrawn: [],+ choice: {+ status: /** @type {const} */ ('none'),+ reason: 'astryx.config sets no experimental.iconSet.',+ },+ };+ }+ return this.#memo('iconSets', async () => {+ const projectDir = findPackageRoot(this.#cwd) ?? this.#cwd;+ /** @type {import('../discovery/icon-set-discovery.mjs').DiscoveredIconSet[]} */+ const sets = [];+ /** @type {import('../discovery/icon-set-discovery.mjs').WithdrawnIconSet[]} */+ const withdrawn = [];+ for (const integration of this.#loadedIntegrations) {+ if (!integration?.iconSets || integration.__loadError) continue;+ if (integration.__providerConflict) continue;+ await this.#collectIssues(integration);+ const pkg = this.#pkgLabel(integration);+ try {+ const found = discoverIntegrationIconSets(integration, {projectDir});+ sets.push(...found.sets);+ for (const each of found.withdrawn) {+ withdrawn.push(each);+ if (each.kind === 'invalid') {+ this.#pushIssue(pkg, {+ code: 'invalid_icon_set',+ severity: 'error',+ message: each.reason,+ });+ }+ }+ } catch (err) {+ this.#pushIssue(pkg, {+ code: 'invalid_icon_set',+ severity: 'error',+ message: errorMessage(err),+ });+ }+ }+ const choice = chooseProjectIconSet(+ sets,+ this.#config.experimental?.iconSet,+ withdrawn,+ );+ return {sets: orderIconSets(sets, choice), withdrawn, choice};+ });+ }+/*** The components and templates this project reads, as links name them: by* owner provider id, kind, and name (a template by its id).@@ -1099,6 +1180,27 @@ export class Project {}}+ // With the opt-in (`iconSets()` reads no set without it), each installed+ // icon set's own icon definitions join Astryx's under the+ // `icon-definitions` namespace, marked with their package.+ const {sets} = await this.iconSets();+ for (const set of sets) {+ if (set.definitions.length === 0) continue;+ const at = this.#loadedIntegrations.findIndex(+ each => each?.name === set.package,+ );+ const integration = this.#loadedIntegrations[at];+ const providerId = integration?.providerId ?? set.package;+ catalog.addTreeInputs({+ namespaces: [],+ guides: set.definitions.map(({doc, file}) => ({+ ...iconDefinitionTreeInput(doc, file, set.package, providerId),+ summary: `${doc.description} (from ${set.package}, icon set "${set.name}")`,+ rank: at + 1,+ })),+ });+ }+return catalog;});}diff --git a/packages/cli/foundation/discovery/authoring-self-docs.mjs b/packages/cli/foundation/discovery/authoring-self-docs.mjsindex 28a0aaf73e..203919e43f 100644--- a/packages/cli/foundation/discovery/authoring-self-docs.mjs+++ b/packages/cli/foundation/discovery/authoring-self-docs.mjs@@ -57,6 +57,9 @@ export const AUTHORING_SELF_DOCS = ['doctypes/template/template.doc.mjs','doctypes/template/integration-template.doc.mjs','doctypes/theme/theme.doc.mjs',+ 'doctypes/icon-set/icon-set.doc.mjs',+ 'doctypes/icon-set/icon-set-data.doc.mjs',+ 'doctypes/icon-definition/icon-definition.doc.mjs',];/** Blocks a self-doc note may carry that a topic section can render. */@@ -127,21 +130,27 @@ export async function loadAuthoringSelfDocs(* @returns {string[][]}*/function fieldRows(fields) {- return fields.flatMap(field => [- [- String(field.name),- String(field.type ?? ''),- field.required ? 'yes' : 'no',- [- field.description,- field.default != null ? `Default: ${field.default}.` : null,- field.example != null ? `Example: ${field.example}.` : null,- ]- .filter(Boolean)- .join(' '),- ],- ...fieldRows(field.fields ?? []),- ]);+ // An experimental field is documented on its feature's experimental route,+ // never in the stable schema's table (spec:AST-017 FR27).+ return fields.flatMap(field =>+ field.stability === 'experimental'+ ? []+ : [+ [+ String(field.name),+ String(field.type ?? ''),+ field.required ? 'yes' : 'no',+ [+ field.description,+ field.default != null ? `Default: ${field.default}.` : null,+ field.example != null ? `Example: ${field.example}.` : null,+ ]+ .filter(Boolean)+ .join(' '),+ ],+ ...fieldRows(field.fields ?? []),+ ],+ );}/**@@ -192,7 +201,24 @@ export function selfDocSection(doc) {}/**- * The `authoring` topic: one section per self-doc, in the order given.+ * Whether a self-doc documents an experimental surface (spec:AST-017 FR27).+ * @param {any} doc+ */+export function isExperimentalSelfDoc(doc) {+ return doc?.stability === 'experimental';+}++/**+ * The route that serves the experimental self-docs, one section each:+ * stable `astryx docs authoring/field-reference` never lists them+ * (spec:AST-084 FR0).+ */+export const EXPERIMENTAL_AUTHORING_ROUTE = 'cli/experimental/icon-set-files';++/**+ * The `authoring` topic: one section per stable self-doc, in the order+ * given. An experimental self-doc is a section of+ * {@link EXPERIMENTAL_AUTHORING_ROUTE} instead.* @param {any[]} docs* @returns {import('../../authoring/doctypes/reference/type').ReferenceDoc}*/@@ -206,10 +232,25 @@ export function buildAuthoringReferenceDoc(docs) {keywords: ['authoring reference', 'field reference', 'every field'],description:'Every file an integration author writes, field by field: the integration manifest, astryx.config, codemods, identity, and each doc type. The guides that use them are the rest of {@link namespace:authoring}.',- sections: docs.map(selfDocSection),+ sections: docs+ .filter(doc => !isExperimentalSelfDoc(doc))+ .map(selfDocSection),});}+/**+ * The sections of {@link EXPERIMENTAL_AUTHORING_ROUTE}: one per experimental+ * self-doc that loads, in reading order.+ * @returns {Promise<any[]>}+ */+export async function buildExperimentalAuthoringSections() {+ const {loaded} = await loadAuthoringSelfDocs();+ return loaded+ .map(entry => entry.doc)+ .filter(isExperimentalSelfDoc)+ .map(selfDocSection);+}+/*** The `authoring` topic from every self-doc that loads. One that fails is left* out here and reported by {@link auditAuthoringSelfDocs}.@@ -225,6 +266,7 @@ export async function buildAuthoringTopic() {* @param {{root?: string, sources?: string[], budget?: number}} [options]* @returns {Promise<{* sections: number,+ * experimental: number,* unreachable: string[],* failed: {source: string, error: string}[],* oversized: {key: string, title: string, bytes: number}[],@@ -240,11 +282,19 @@ export async function auditAuthoringSelfDocs({source => !listed.has(source),);const {loaded, failed} = await loadAuthoringSelfDocs(sources, root);- const topic = buildAuthoringReferenceDoc(loaded.map(entry => entry.doc));+ const docs = loaded.map(entry => entry.doc);+ const topic = buildAuthoringReferenceDoc(docs);+ const experimental = docs.filter(isExperimentalSelfDoc).map(selfDocSection);return {sections: topic.sections.length,+ // Experimental schemas (spec:AST-017 FR27), counted apart: they are+ // sections of the experimental route, not of `astryx docs authoring`.+ experimental: experimental.length,unreachable,failed,- oversized: oversizedDocSections(topic.sections, budget),+ oversized: oversizedDocSections(+ [...topic.sections, ...experimental],+ budget,+ ),};}diff --git a/packages/cli/foundation/discovery/authoring-self-docs.test.mjs b/packages/cli/foundation/discovery/authoring-self-docs.test.mjsindex 173109b454..1f770f7eb9 100644--- a/packages/cli/foundation/discovery/authoring-self-docs.test.mjs+++ b/packages/cli/foundation/discovery/authoring-self-docs.test.mjs@@ -6,7 +6,9 @@ import * as path from 'node:path';import {AUTHORING_SELF_DOCS,auditAuthoringSelfDocs,+ EXPERIMENTAL_AUTHORING_ROUTE,buildAuthoringTopic,+ buildExperimentalAuthoringSections,discoverAuthoringSelfDocSources,} from './authoring-self-docs.mjs';import {@@ -30,23 +32,37 @@ describe('authoring self-docs', () => {});it('audits clean: every self-doc loads, is reachable, and fits one read', async () => {+ // The three experimental schemas are sections of their own route, not of+ // `astryx docs authoring` (spec:AST-084 FR0).expect(await auditAuthoringSelfDocs()).toEqual({- sections: AUTHORING_SELF_DOCS.length,+ sections: AUTHORING_SELF_DOCS.length - 3,+ experimental: 3,unreachable: [],failed: [],oversized: [],});});- it('builds a valid guide with one section per self-doc, placed under authoring', async () => {+ it('builds a valid guide with one section per stable self-doc, placed under authoring, and serves the experimental ones on their own route', async () => {const {placement, ...topic} = await buildAuthoringTopic();expect(problemsInTopic(topic)).toEqual([]);- expect(topic.sections).toHaveLength(AUTHORING_SELF_DOCS.length);+ expect(topic.sections).toHaveLength(AUTHORING_SELF_DOCS.length - 3);expect(placement).toEqual({parent: 'namespace:authoring',slot: 'reference',order: 10,});+ const experimental = await buildExperimentalAuthoringSections();+ expect(experimental.map(section => section.id)).toEqual([+ 'icon-set-doc',+ 'icon-set-data',+ 'icon-definition-doc',+ ]);+ expect(topic.sections.map(section => section.id)).not.toContain(+ 'icon-set-doc',+ );+ const read = await docs(EXPERIMENTAL_AUTHORING_ROUTE, 'icon-set-data');+ expect(read.data.title).toBe('IconSetData');});it(diff --git a/packages/cli/foundation/discovery/authoring-surface.mjs b/packages/cli/foundation/discovery/authoring-surface.mjsindex c191c2ed34..b0210ce3eb 100644--- a/packages/cli/foundation/discovery/authoring-surface.mjs+++ b/packages/cli/foundation/discovery/authoring-surface.mjs@@ -25,7 +25,8 @@ import jscodeshift from 'jscodeshift';import {AUTHORING_ROOT,AUTHORING_SELF_DOCS,- buildAuthoringReferenceDoc,+ isExperimentalSelfDoc,+ selfDocSection,discoverAuthoringSelfDocSources,loadAuthoringSelfDocs,} from './authoring-self-docs.mjs';@@ -451,12 +452,16 @@ export async function auditAuthoringSurface({const registered = new Set(sources);const {loaded, failed} = await loadAuthoringSelfDocs(sources, root);const failedSources = new Set(failed.map(entry => entry.source));- const sections = buildAuthoringReferenceDoc(- loaded.map(entry => entry.doc),- ).sections;/** @type {Map<string, string>} */const keyOf = new Map(- loaded.map((entry, i) => [entry.source, sectionKey(sections[i])]),+ loaded.map(entry => [entry.source, sectionKey(selfDocSection(entry.doc))]),+ );+ // An experimental self-doc is a section of the experimental route, never+ // of `astryx docs authoring`, so the topic index is not asked for it.+ const experimental = new Set(+ loaded+ .filter(entry => isExperimentalSelfDoc(entry.doc))+ .map(entry => entry.source),);/**@@ -467,7 +472,9 @@ export async function auditAuthoringSurface({if (!registered.has(source)) return 'unregistered';if (failedSources.has(source) || !keyOf.has(source)) return 'failed';const key = /** @type {string} */ (keyOf.get(source));- return topicKeys != null && !topicKeys.has(key) ? 'missing-section' : null;+ return topicKeys != null && !experimental.has(source) && !topicKeys.has(key)+ ? 'missing-section'+ : null;};/** @type {Map<string, string[]>} declaring module -> its public types */diff --git a/packages/cli/foundation/discovery/cli-self-docs.mjs b/packages/cli/foundation/discovery/cli-self-docs.mjsindex 4e72bb9e46..523d6f8454 100644--- a/packages/cli/foundation/discovery/cli-self-docs.mjs+++ b/packages/cli/foundation/discovery/cli-self-docs.mjs@@ -409,17 +409,56 @@ function enumSection(doc) {{type: 'table',headers: ['Value', 'Meaning'],- rows: (doc.members ?? []).map((/** @type {any} */ m) => [- `\`${m.value}\``,- m.deprecated- ? `${m.description} Deprecated: ${m.deprecated}`- : m.description,- ]),+ // An experimental value is documented on its feature's experimental+ // route, never in the stable enum's table (spec:AST-017 FR27).+ rows: (doc.members ?? [])+ .filter((/** @type {any} */ m) => m.stability !== 'experimental')+ .map((/** @type {any} */ m) => [+ `\`${m.value}\``,+ m.deprecated+ ? `${m.description} Deprecated: ${m.deprecated}`+ : m.description,+ ]),},],};}+/**+ * What `astryx docs <route>` prints for one icon definition: its description,+ * its words, whether it is built in, and the command+ * that finds the icon each installed set draws for it.+ * @param {any} doc+ */+function iconDefinitionSection(doc) {+ /** @type {string[][]} */+ const rows = [+ [+ 'Words',+ doc.words.map((/** @type {string} */ w) => `\`${w}\``).join(', '),+ ],+ ];+ if (doc.builtIn) {+ rows.push([+ 'Built in',+ 'Yes: every icon set maps it, and Core renders it.',+ ]);+ }+ const content = [+ {type: 'prose', text: doc.description},+ {type: 'table', headers: ['Field', 'Value'], rows},+ {+ type: 'prose',+ text: `An icon set registers the icon that draws this definition in its data file: \`"map": {"${doc.name}": "<icon id>"}\`. Find it in each installed set: \`astryx experimental icon ${doc.name}\`.`,+ },+ {+ type: 'prose',+ text: 'Icon definitions are experimental: they may change or be removed in a patch release.',+ },+ ];+ return {id: routeSegment(doc.name), title: doc.name, content};+}+/*** What `astryx docs <route>` prints for one CLI typed doc: its title and the* blocks of its content, with cross-links to the routes the tree gave.@@ -429,6 +468,7 @@ function enumSection(doc) {*/export function cliDocSection(doc, index) {if (doc.type === 'command') return commandSection(doc, index);+ if (doc.type === 'icon-definition') return iconDefinitionSection(doc);if (doc.type === 'function') return functionSection(doc, index);if (doc.type === 'enum') return enumSection(doc);if (doc.type === 'namespace')@@ -450,6 +490,7 @@ export function cliDocSection(doc, index) {* docs: number,* tree: number,* authoring: number,+ * experimental: {docs: number, tree: number, authoring: number},* missing: string[],* unknown: {source: string, namespace: string}[],* misfiled: {source: string, message: string}[],@@ -506,10 +547,21 @@ export async function auditCliSelfDocs({}}const index = cliDocIndex(loaded.map(entry => entry.doc));+ // Experimental docs (spec:AST-017 FR27) are audited like every other, and+ // counted apart, so the stable counts stay what they were.+ const experimental = (/** @type {any} */ doc) =>+ doc?.stability === 'experimental';return {docs: loaded.length,tree: treeDocs.length,authoring,+ experimental: {+ docs: loaded.filter(entry => experimental(entry.doc)).length,+ tree: treeDocs.filter(experimental).length,+ authoring: loaded.filter(+ entry => listed.has(entry.source) && experimental(entry.doc),+ ).length,+ },missing,unknown,misfiled,diff --git a/packages/cli/foundation/discovery/component-discovery.export-names.test.mjs b/packages/cli/foundation/discovery/component-discovery.export-names.test.mjsindex cc424b31d0..8bee2c2b2a 100644--- a/packages/cli/foundation/discovery/component-discovery.export-names.test.mjs+++ b/packages/cli/foundation/discovery/component-discovery.export-names.test.mjs@@ -558,6 +558,37 @@ describe('integration components a family doc lists in components', () => {expect(namesIn(loaded)).toEqual(['AcmeList']);});+ it('lists no member the import only re-exports from another package', () => {+ // Discovery follows relative re-exports alone; a package another package+ // re-exports is not this integration's member.+ const loaded = writePackage(+ {main: './src/index.ts'},+ {+ 'src/list/AcmeList.doc.mjs': family(+ 'AcmeList',+ "{name: 'AcmeListRow', description: 'x'}, {name: 'AcmeListCell', description: 'x'}",+ ).replace('usage:', "import: '@acme/widgets', usage:"),+ 'src/list/AcmeList.tsx':+ 'export function AcmeList() { return null; }\n',+ 'src/index.ts':+ "export {AcmeList} from './list/AcmeList';\nexport {AcmeListRow} from '@acme/rows';\nexport * from '@acme/cells';\n",+ 'node_modules/@acme/rows/package.json': JSON.stringify({+ name: '@acme/rows',+ main: 'index.js',+ }),+ 'node_modules/@acme/rows/index.js':+ 'export function AcmeListRow() { return null; }\n',+ 'node_modules/@acme/cells/package.json': JSON.stringify({+ name: '@acme/cells',+ exports: {'.': './index.js'},+ }),+ 'node_modules/@acme/cells/index.js':+ 'export function AcmeListCell() { return null; }\n',+ },+ );+ expect(namesIn(loaded)).toEqual(['AcmeList']);+ });+it("takes a member's source from the family's folder, never a bundle or the package root", () => {const loaded = writePackage({exports: {'.': {import: './dist/index.mjs'}}},diff --git a/packages/cli/foundation/discovery/doc-stability.mjs b/packages/cli/foundation/discovery/doc-stability.mjsnew file mode 100644index 0000000000..a2464e81c7--- /dev/null+++ b/packages/cli/foundation/discovery/doc-stability.mjs@@ -0,0 +1,100 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Integration descriptors an older CLI drops (spec:AST-017 FR21, FR27;+ * spec:AST-084 FR16).+ *+ * Published CLIs before 0.7.4 refuse an unknown field on a page or block+ * template, which they drop, and on a namespace doc, which hides every doc+ * topic the package ships. Component docs and guides keep loading there and+ * ignore it. So each template or namespace doc that sets `stability`, and+ * each template that declares `icons`, gets a note, unless the package's+ * `@astryxdesign/cli` peer range admits only CLIs that read the field.+ *+ * @input A loaded integration and its package.json.+ * @output One note per descriptor. A note is not an issue: it is never an+ * error or a warning, and never fails a check, even under `--strict`.+ * @position foundation/discovery; read by `doctor integration validate`+ * (and so `integration check`) for the package being authored.+ */++import * as path from 'node:path';+import {discoverIntegrationDocs, loadTopicModule} from './docs-discovery.mjs';+import {discoverIntegrationTemplatesForOne} from './template-adapter.mjs';+import {+ STABILITY_CLI,+ TEMPLATE_ICONS_CLI,+ stabilityCliProblem,+ templateIconsCliProblem,+} from '../integrations/cli-requirement.mjs';++/**+ * @typedef {object} OlderCliNote+ * @property {string} file the descriptor, relative to the package+ * @property {'template' | 'namespace'} kind+ * @property {'stability' | 'icons'} field the field an older CLI refuses+ * @property {string} message what an older CLI does with it, and the fix+ */++/**+ * @param {any} loaded a loaded integration (absolute roots)+ * @param {any} pkg its package.json+ * @param {string} packageDir+ * @returns {Promise<OlderCliNote[]>}+ */+export async function olderCliNotes(loaded, pkg, packageDir) {+ const stability = stabilityCliProblem(pkg) != null;+ const icons = templateIconsCliProblem(pkg) != null;+ if (!stability && !icons) return [];+ /** @type {Array<{file: string, kind: 'template' | 'namespace', field: 'stability' | 'icons'}>} */+ const found = [];+ if (stability && loaded.docs) {+ const {namespaces} = await discoverIntegrationDocs(loaded).catch(() => ({+ namespaces: [],+ }));+ for (const namespace of namespaces) {+ if (/** @type {any} */ (namespace.doc)?.stability != null) {+ // A namespace's source is `<package>/<path in the docs root>`.+ const inRoot = String(namespace.source).slice(+ String(loaded.name).length + 1,+ );+ found.push({+ file: path.join(loaded.docs, inRoot),+ kind: 'namespace',+ field: 'stability',+ });+ }+ }+ }+ if (loaded.templates) {+ const {templates} = await discoverIntegrationTemplatesForOne(loaded).catch(+ () => ({templates: []}),+ );+ for (const template of templates) {+ if (!template.docPath) continue;+ const doc = /** @type {any} */ (+ await loadTopicModule(template.docPath).catch(() => null)+ );+ if (stability && doc?.stability != null) {+ found.push({+ file: template.docPath,+ kind: 'template',+ field: 'stability',+ });+ }+ if (icons && doc?.icons != null) {+ found.push({file: template.docPath, kind: 'template', field: 'icons'});+ }+ }+ }+ return found.map(({file, kind, field}) => {+ const relative = path.relative(packageDir, file).split(path.sep).join('/');+ const floor = field === 'icons' ? TEMPLATE_ICONS_CLI : STABILITY_CLI;+ return {+ file: relative,+ kind,+ field,+ message: `${relative} ${field === 'icons' ? 'declares `icons`' : 'sets `stability`'}: CLIs before ${floor} drop this descriptor${kind === 'namespace' ? " and hide the package's doc topics" : ''}, and the package's @astryxdesign/cli peer range admits them. Declare "@astryxdesign/cli": ">=${floor}" in peerDependencies (optional in peerDependenciesMeta), or remove \`${field}\`.`,+ };+ });+}diff --git a/packages/cli/foundation/discovery/doc-types.mjs b/packages/cli/foundation/discovery/doc-types.mjsindex e379332c9b..74ac4c712e 100644--- a/packages/cli/foundation/discovery/doc-types.mjs+++ b/packages/cli/foundation/discovery/doc-types.mjs@@ -26,7 +26,8 @@* - docs root: the type the doc's `type` names (`ReferenceDoc` when it names* none), and a `<topic>.doc.<lang>.mjs` overlay against* `ReferenceTranslationDoc`;- * - themes root: `ThemeDoc`.+ * - themes root: `ThemeDoc`;+ * - iconSets root: `IconSetDoc`.* Every finding is a warning, names the field, and says how to fix it.** @input Doc files with the root each was found in, the package root, and the@@ -46,7 +47,7 @@ import {} from './project-typescript.mjs';/**- * @typedef {'components' | 'hooks' | 'templates' | 'docs' | 'docs-overlay' | 'themes'} DocRoot+ * @typedef {'components' | 'hooks' | 'templates' | 'docs' | 'docs-overlay' | 'themes' | 'icon-sets'} DocRoot*//**@@ -113,6 +114,7 @@ const MAIN_EXPORTS = {docs: ['docs', 'default'],'docs-overlay': [],themes: ['default', 'doc', 'docs'],+ 'icon-sets': ['default'],};/** The type a docs-root doc's `type` stamp names. */@@ -308,6 +310,9 @@ function expectedType(ts, root, exportName, node, core = false) {if (root === 'themes') {return {typeExpr: authoring('ThemeDoc'), typeName: 'ThemeDoc'};}+ if (root === 'icon-sets') {+ return {typeExpr: authoring('IconSetDoc'), typeName: 'IconSetDoc'};+ }if (translation) {return {typeExpr: authoring('ReferenceTranslationDoc'),@@ -421,7 +426,7 @@ function targetsOf(ts, sf, root, core = false) {const names = [];const main = MAIN_EXPORTS[root].find(name => exported.has(name));if (main) names.push(main);- if (root !== 'templates' && root !== 'themes') {+ if (root !== 'templates' && root !== 'themes' && root !== 'icon-sets') {for (const name of TRANSLATIONS) if (exported.has(name)) names.push(name);}/** @type {Target[]} */diff --git a/packages/cli/foundation/discovery/doc-types.test.mjs b/packages/cli/foundation/discovery/doc-types.test.mjsindex ca3f7ad51c..cef65c821d 100644--- a/packages/cli/foundation/discovery/doc-types.test.mjs+++ b/packages/cli/foundation/discovery/doc-types.test.mjs@@ -686,6 +686,36 @@ describe('checkDocTypes', () => {);});+ it('checks an icon set descriptor against IconSetDoc', async () => {+ withTypeScript();+ write(+ 'icon-sets/outline/outline.doc.mjs',+ "/** @type {import('@astryxdesign/cli/authoring').IconSetDoc} */\nexport default {type: 'icon-set', name: 'outline', displayName: 'Outline', description: 'D', maintained: true, license: 1, icons: []};\n",+ );+ write(+ 'icon-sets/solid/solid.doc.mjs',+ "export default {type: 'icon-set', name: 'solid', displayName: 'Solid', description: 'D', maintained: true};\n",+ );+ write(+ 'icon-sets/ok/ok.doc.mjs',+ "export default {type: 'icon-set', name: 'ok', displayName: 'Ok', description: 'D', maintained: true, license: 'MIT'};\n",+ );+ const report = await check([+ ['icon-sets/outline/outline.doc.mjs', 'icon-sets'],+ ['icon-sets/solid/solid.doc.mjs', 'icon-sets'],+ ['icon-sets/ok/ok.doc.mjs', 'icon-sets'],+ ]);+ expect(report.docs).toBe(3);+ expect(summary(report)).toEqual([+ 'icon-sets/outline/outline.doc.mjs default icons unknown_field',+ 'icon-sets/outline/outline.doc.mjs default license wrong_type',+ 'icon-sets/solid/solid.doc.mjs default license missing_field',+ ]);+ expect(new Set(report.findings.map(f => f.type))).toEqual(+ new Set(['IconSetDoc']),+ );+ });+it('checks nothing with a TypeScript older than 4.9, even when every doc is TypeScript', async () => {const fake = path.join(pkg, 'node_modules', 'typescript');fs.mkdirSync(fake, {recursive: true});diff --git a/packages/cli/foundation/discovery/icon-definition-discovery.mjs b/packages/cli/foundation/discovery/icon-definition-discovery.mjsnew file mode 100644index 0000000000..e6d3eb26e4--- /dev/null+++ b/packages/cli/foundation/discovery/icon-definition-discovery.mjs@@ -0,0 +1,117 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Icon definition discovery (AST-084): every definition file in a definitions+ * folder, read statically and checked as an IconDefinitionDoc.+ *+ * Astryx's own definitions are the files in the CLI's `assets/icons/definitions`+ * folder. An icon set adds its own in `<set>/definitions`. There is no index+ * file and no list: discovery reads every `<name>.doc.mjs` in the folder,+ * and the file name must equal the definition's `name`.+ *+ * @input A definitions folder and the package that ships it+ * @output The definitions, and the files that did not read+ * @position packages/cli/foundation/discovery — the definition seam every icon+ * surface reads+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {parseIconDefinition} from '../../authoring/doctypes/icon-definition/parse.mjs';+import {CLI_ROOT} from '../fs/paths.mjs';+import {readStaticDescriptorValue} from './theme-discovery.mjs';++/** @typedef {import('../../authoring/doctypes/icon-definition/type').IconDefinitionDoc} IconDefinitionDoc */++/** The folder Astryx's own definitions live in. */+export const ASTRYX_DEFINITIONS_DIR = path.join(+ CLI_ROOT,+ 'assets',+ 'icons',+ 'definitions',+);++/** The package that ships Astryx's definitions. */+export const ASTRYX_DEFINITIONS_PACKAGE = '@astryxdesign/cli';++/**+ * One definition, with the file and package it came from.+ * @typedef {object} DiscoveredIconDefinition+ * @property {IconDefinitionDoc} doc+ * @property {string} file absolute path+ * @property {string} package the package that ships it+ */++/**+ * Read every definition file in one folder, without executing any.+ * @param {string} dir+ * @param {string} owner the package that ships the folder+ * @returns {{definitions: DiscoveredIconDefinition[], errors: Array<{file: string, message: string}>}}+ */+export function readDefinitionsDir(dir, owner) {+ /** @type {DiscoveredIconDefinition[]} */+ const definitions = [];+ /** @type {Array<{file: string, message: string}>} */+ const errors = [];+ /** @type {fs.Dirent[]} */+ let entries;+ try {+ entries = fs.readdirSync(dir, {withFileTypes: true});+ } catch {+ return {definitions, errors};+ }+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {+ if (!entry.name.endsWith('.doc.mjs')) continue;+ const file = path.join(dir, entry.name);+ const label = `Icon definition ${entry.name} in ${owner}`;+ try {+ if (!entry.isFile()) {+ throw new Error(`${label} must be a regular file.`);+ }+ const doc = parseIconDefinition(+ readStaticDescriptorValue(file, label, 'IconDefinitionDoc', {+ data: true,+ }),+ label,+ );+ const stem = entry.name.slice(0, -'.doc.mjs'.length);+ if (doc.name !== stem) {+ throw new Error(+ `${label} names "${doc.name}"; a definition file is named after its definition (${doc.name}.doc.mjs).`,+ );+ }+ definitions.push({doc, file, package: owner});+ } catch (error) {+ errors.push({+ file,+ message: error instanceof Error ? error.message : String(error),+ });+ }+ }+ return {definitions, errors};+}++/** @type {{definitions: DiscoveredIconDefinition[], errors: Array<{file: string, message: string}>} | undefined} */+let astryx;++/**+ * Astryx's own definitions, read once per process.+ * @returns {{definitions: DiscoveredIconDefinition[], errors: Array<{file: string, message: string}>}}+ */+export function astryxIconDefinitions() {+ astryx ??= readDefinitionsDir(+ ASTRYX_DEFINITIONS_DIR,+ ASTRYX_DEFINITIONS_PACKAGE,+ );+ return astryx;+}++/**+ * Astryx's definitions by name.+ * @returns {Map<string, IconDefinitionDoc>}+ */+export function astryxDefinitionsByName() {+ return new Map(+ astryxIconDefinitions().definitions.map(m => [m.doc.name, m.doc]),+ );+}diff --git a/packages/cli/foundation/discovery/icon-ranking.mjs b/packages/cli/foundation/discovery/icon-ranking.mjsnew file mode 100644index 0000000000..3921157e89--- /dev/null+++ b/packages/cli/foundation/discovery/icon-ranking.mjs@@ -0,0 +1,305 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Pure icon records and ranking (AST-084 FR6), shared by the `icon`+ * leaves and the icon-set checks' suggestions. No environment access.+ *+ * Ranking tiers, highest first:+ * 100 the query is an icon definition the set's `map` names the icon for+ * 90 an exact match in the reading the searched sets favor (below)+ * 80 an exact match in the other reading+ * 60 one of its words starts with the query+ * 40 a partial match: the id or a word contains the query, or every+ * word of the query starts one of the icon's words or id parts+ *+ * An exact match is a NAME match when the query is the icon's id, or one of+ * its words that is also a part of its id (`trash` for `trash-2`); it is a+ * MEANING match when the query is one of its other words, its tags. An id+ * names the artwork; the tags say what it is for. Lucide's `delete` draws the+ * Delete key, so `delete` names it, while `trash` is tagged `delete`: the+ * query asks for the meaning. Which reading leads is decided by the searched+ * sets themselves: when at least as many icons carry the query as a tag as+ * carry it as a name, meaning matches score 90 and name-only matches 80;+ * otherwise name matches score 90 and meaning-only matches 80 (`user` names+ * many icons, so the `user` icon stays ahead of `contact`, which is only+ * tagged `user`).+ *+ * Equal scores keep the set order first (the project's set, then load+ * order), so the project's set always leads at a score. Within one set, a+ * name match on the whole id comes before one on a part of it, and a meaning+ * match whose query sits earlier among the icon's tags comes first (sets list+ * an icon's most telling tags first). Remaining ties keep id order, so the+ * same installation always answers the same way.+ *+ * @position foundation/discovery — read by api/icon and icon-set-checks+ */++import {definitionsByIcon} from './icon-set-discovery.mjs';+import {astryxDefinitionsByName} from './icon-definition-discovery.mjs';++/** @typedef {import('./icon-set-discovery.mjs').DiscoveredIconSet} DiscoveredIconSet */+/** @typedef {import('../../authoring/doctypes/icon-set/type').IconSetIcon} IconSetIcon */+/** @typedef {import('../../api/icon/icon.type.mjs').IconRecord} IconRecord */+/** @typedef {import('../../api/icon/icon.type.mjs').IconMatchEntry} IconMatchEntry */++/**+ * The import line for one export.+ * @param {string} exportName+ * @param {string} module+ */+export function importLine(exportName, module) {+ return `import {${exportName}} from '${module}';`;+}++/**+ * One icon as every icon read names it.+ * @param {DiscoveredIconSet} set+ * @param {IconSetIcon} icon+ * @param {string[]} [definitions] the definitions the set's `map` names it+ * for; read from the set when not given+ * @returns {IconRecord}+ */+export function iconRecord(set, icon, definitions) {+ const module = icon.module ?? set.data.module;+ return {+ set: set.name,+ id: icon.id,+ package: set.package,+ module,+ export: icon.export,+ import: importLine(icon.export, module),+ words: [...icon.words],+ definitions: [+ ...(definitions ?? definitionsByIcon(set.data).get(icon.id) ?? []),+ ],+ variants: (icon.variants ?? []).map(variant => ({+ variant: variant.variant,+ module: variant.module ?? module,+ export: variant.export,+ })),+ };+}++/** @param {string} value */+const squash = value => value.toLowerCase().replace(/[\s_-]+/g, '');++/**+ * How one icon matches a query, before the searched sets decide which exact+ * reading leads: the tier, whether an exact match is a name or a meaning+ * match, and the keys that order matches within a tier.+ * @typedef {object} IconMatch+ * @property {'definition' | 'exact' | 'prefix' | 'partial'} tier+ * @property {boolean} name the query is the id, or a word that is an id part+ * @property {boolean} meaning the query is one of the icon's tags (never+ * both: a tag is a word that is not the id or one of its parts)+ * @property {number} rank within-tier key, lower first: for a name match 0+ * (whole id) or 1 (an id part); for a meaning match the tag's position+ * @property {string} reason+ */++/**+ * How one icon matches a query, or null when it does not.+ * @param {string} query lower-case, trimmed+ * @param {IconSetIcon} icon+ * @param {string[]} [definitions] the icon definitions the set maps it to+ * @returns {IconMatch | null}+ */+export function matchIcon(query, icon, definitions = []) {+ const joined = squash(query);+ const definition = definitions.find(name => name.toLowerCase() === joined);+ if (definition) {+ return {+ tier: 'definition',+ name: false,+ meaning: false,+ rank: 0,+ reason: `definition "${definition}"`,+ };+ }+ const id = query.replace(/\s+/g, '-');+ const parts = new Set(icon.id.split('-'));+ const tags = icon.words.filter(word => word !== icon.id && !parts.has(word));+ const tagAt = tags.indexOf(query);+ const wholeId = icon.id === id;+ const partWord = !wholeId && parts.has(query) && icon.words.includes(query);+ if (wholeId || partWord || tagAt >= 0) {+ return {+ tier: 'exact',+ name: wholeId || partWord,+ meaning: !wholeId && !partWord,+ rank: wholeId ? 0 : partWord ? 1 : tagAt,+ reason: wholeId ? `id "${icon.id}"` : `word "${query}"`,+ };+ }+ const prefix = icon.words.find(word => word.startsWith(query));+ if (prefix) {+ return {+ tier: 'prefix',+ name: false,+ meaning: false,+ rank: 0,+ reason: `word "${prefix}" starts with "${query}"`,+ };+ }+ const contains = [icon.id, ...icon.words].find(text => text.includes(query));+ if (contains) {+ return {+ tier: 'partial',+ name: false,+ meaning: false,+ rank: 0,+ reason: `partial "${contains}"`,+ };+ }+ const tokens = query.split(/\s+/).filter(Boolean);+ if (tokens.length > 1) {+ const all = [+ ...icon.id.split('-'),+ ...icon.words.flatMap(w => w.split(/\s+/)),+ ];+ if (tokens.every(token => all.some(part => part.startsWith(token)))) {+ return {+ tier: 'partial',+ name: false,+ meaning: false,+ rank: 0,+ reason: `partial "${tokens.join(' ')}"`,+ };+ }+ }+ return null;+}++/**+ * The score of one match, given which exact reading leads.+ * @param {IconMatch} match+ * @param {'name' | 'meaning'} leading+ * @returns {number}+ */+function scoreOf(match, leading) {+ switch (match.tier) {+ case 'definition':+ return 100;+ case 'exact':+ return match[leading] ? 90 : 80;+ case 'prefix':+ return 60;+ default:+ return 40;+ }+}++/**+ * Which exact reading leads for a set of matches: meaning, unless more icons+ * carry the query as a name than as a tag.+ * @param {Array<IconMatch | null>} matches+ * @returns {'name' | 'meaning'}+ */+export function leadingReading(matches) {+ let names = 0;+ let meanings = 0;+ for (const match of matches) {+ if (match?.tier !== 'exact') continue;+ if (match.name) names++;+ if (match.meaning) meanings++;+ }+ return names > meanings ? 'name' : 'meaning';+}++/**+ * How well one icon answers a query on its own, or null when it does not.+ * An exact match is scored as if `leading` were the reading the searched+ * sets favor (meaning, unless told otherwise).+ * @param {string} query lower-case, trimmed+ * @param {IconSetIcon} icon+ * @param {'name' | 'meaning'} [leading]+ * @param {string[]} [definitions] the icon definitions the set maps it to+ * @returns {{score: number, reason: string} | null}+ */+export function scoreIcon(query, icon, leading = 'meaning', definitions = []) {+ const match = matchIcon(query, icon, definitions);+ return match ? {score: scoreOf(match, leading), reason: match.reason} : null;+}++/**+ * The icon with the words it matches by: its own words, then the name (read+ * as words) and words of every definition the set's `map` names it for, so+ * `bin` finds the icon mapped to `delete` without the data file repeating+ * the definition's words. The icon's own words keep their places, so its+ * own tags still rank first.+ * @param {IconSetIcon} icon+ * @param {string[]} definitions+ * @param {(name: string) => {name: string, words: string[]} | undefined} lookup+ * @returns {IconSetIcon}+ */+export function withDefinitionWords(icon, definitions, lookup) {+ if (definitions.length === 0) return icon;+ const words = [...icon.words];+ for (const name of definitions) {+ const doc = lookup(name);+ const humanized = name+ .replace(/([a-z0-9])([A-Z])/gu, '$1 $2')+ .toLowerCase();+ for (const word of [humanized, ...(doc?.words ?? [])]) {+ const lower = word.toLowerCase();+ if (!words.includes(lower)) words.push(lower);+ }+ }+ return {...icon, words};+}++/**+ * Every icon in `sets` that answers the query, ranked (FR6).+ * @param {DiscoveredIconSet[]} sets in tie order+ * @param {string} query+ * @returns {IconMatchEntry[]}+ */+export function rankIcons(sets, query) {+ const term = query.trim().toLowerCase();+ const astryx = astryxDefinitionsByName();+ /** @type {Array<{set: DiscoveredIconSet, icon: IconSetIcon, definitions: string[], match: IconMatch, setIndex: number}>} */+ const hits = [];+ sets.forEach((set, setIndex) => {+ const byIcon = definitionsByIcon(set.data);+ const own = new Map(+ (set.definitions ?? []).map(each => [each.doc.name, each.doc]),+ );+ for (const icon of set.data.icons) {+ const definitions = byIcon.get(icon.id) ?? [];+ const match = matchIcon(+ term,+ withDefinitionWords(+ icon,+ definitions,+ name => astryx.get(name) ?? own.get(name),+ ),+ definitions,+ );+ if (match) hits.push({set, icon, definitions, match, setIndex});+ }+ });+ const leading = leadingReading(hits.map(hit => hit.match));+ const found = hits.map(({set, icon, definitions, match, setIndex}) => {+ const score = scoreOf(match, leading);+ return {+ entry: {+ ...iconRecord(set, icon, definitions),+ reason: match.reason,+ score,+ },+ // Within an exact score and one set: a name match keeps whole id+ // before id part, a meaning match its tag position.+ rank: match.tier === 'exact' ? match.rank : 0,+ setIndex,+ };+ });+ found.sort(+ (a, b) =>+ // Equal scores keep set order, so the project's set leads (FR6, FR8).+ b.entry.score - a.entry.score ||+ a.setIndex - b.setIndex ||+ a.rank - b.rank ||+ (a.entry.id < b.entry.id ? -1 : a.entry.id > b.entry.id ? 1 : 0),+ );+ return found.map(({entry}) => entry);+}diff --git a/packages/cli/foundation/discovery/icon-set-checks.mjs b/packages/cli/foundation/discovery/icon-set-checks.mjsnew file mode 100644index 0000000000..600ac2956b--- /dev/null+++ b/packages/cli/foundation/discovery/icon-set-checks.mjs@@ -0,0 +1,742 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The icon-set checks of `astryx integration check` and+ * `astryx doctor integration validate` (AST-084 FR12, FR15).+ *+ * For each set under a package's `iconSets` root it proves, without executing+ * anything, that the data file matches the package. The codes below are+ * exactly FR15's table:+ * errors `invalid_icon_set` (an invalid descriptor, data file, or+ * definition file: a duplicate id, an icon with no words, a `map`+ * key that is neither an Astryx icon definition nor one the set+ * declares, a `map` value that is not an icon id, or a variant or+ * default naming a variant the set does not declare);+ * `icon_builtin_definition_missing`; `icon_module_not_public`;+ * `icon_not_component`; `icon_export_missing` (an export, the+ * generated module, or the adapter its module does not have, read+ * statically with re-exports followed); `icon_module_invalid`;+ * `icon_generated_types_mismatch`; `icon_theme_map_mismatch` (a+ * theme map whose keys or values disagree with the built-in+ * entries of `map`);+ * warnings `icon_export_name` (an export not named `<Name>Icon`);+ * `icon_definition_unused` and `icon_definition_shadowed` (a+ * definition the set declares that `map` leaves out, or that has+ * an Astryx definition's name); `icon_source_version_drift`;+ * `icon_license_notice_missing`.+ * An optional (not built-in) Astryx definition the set leaves unmapped is no+ * issue: {@link iconSetCoverage} lists it, never counted, never failing.+ * Only what the static reader proves absent fails. What it cannot judge it+ * lists as not checked, never as an issue (`architecture:cli-surface` INV35,+ * DEC-7): an export whose module is a package `exports` target not built+ * yet; an icon or adapter export it cannot prove either way (behind a+ * re-export it cannot follow, bound to a default or namespace import, or+ * imported from a package that does not resolve); and a theme map or+ * theme-map entry it cannot read.+ *+ * @input A package directory and its loaded integration roots+ * @output Issues in the integration issue format, and the items not checked+ * @position packages/cli/foundation/discovery — read by validate-integration+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {findInstalledPackage} from '../fs/paths.mjs';+import {satisfiesRange} from '../env/semver.mjs';+import {+ NOTICE_FILE_RE,+ discoverIconSetDirectory,+ resolveIconModule,+ splitSpecifier,+} from './icon-set-discovery.mjs';+import {inspectPackageExport} from './package-exports.mjs';+import {+ generatedTypesPath,+ generatedTypesText,+ readGeneratedStatements,+} from './icon-set-writer.mjs';+import {+ exportValueKind,+ aliasedOrigin,+ exportOriginVerdict,+ moduleParseFailure,+ staticExportBindings,+} from './module-exports.mjs';+import {astryxIconDefinitions} from './icon-definition-discovery.mjs';+import {+ issueError,+ issueWarning,+} from '../integrations/validate-contributions.mjs';++/** @typedef {import('../integrations/issue').AstryxIntegrationIssue} Issue */+/** @typedef {import('./icon-set-discovery.mjs').DiscoveredIconSet} DiscoveredIconSet */++/** An invalid descriptor or data file. */+export const INVALID_ICON_SET = 'invalid_icon_set';+/** An `export` (or module) the package does not provide at runtime. */+export const ICON_EXPORT_MISSING = 'icon_export_missing';+/** A theme map whose keys or values disagree with the built-in `map` entries. */+export const ICON_THEME_MAP_MISMATCH = 'icon_theme_map_mismatch';+/** A built-in definition missing from the set's `map`. */+export const ICON_BUILTIN_DEFINITION_MISSING =+ 'icon_builtin_definition_missing';+/** A generated module's declaration file that is missing or out of date. */+export const ICON_GENERATED_TYPES_MISMATCH = 'icon_generated_types_mismatch';+/** A module of the set's package that does not parse. */+export const ICON_MODULE_INVALID = 'icon_module_invalid';+/** An icon read from a module other than the set's package public entry. */+export const ICON_MODULE_NOT_PUBLIC = 'icon_module_not_public';+/** An icon export not named `<Name>Icon`. */+export const ICON_EXPORT_NAME = 'icon_export_name';+/** An icon export that is a literal, not a component. */+export const ICON_NOT_COMPONENT = 'icon_not_component';+/** A definition the set declares whose name is an Astryx definition. */+export const ICON_DEFINITION_SHADOWED = 'icon_definition_shadowed';+/** A definition the set declares that is missing from its `map`. */+export const ICON_DEFINITION_UNUSED = 'icon_definition_unused';+/** Data generated from another upstream version than the package uses. */+export const ICON_SOURCE_VERSION_DRIFT = 'icon_source_version_drift';+/** A set with an upstream and no license notice. */+export const ICON_LICENSE_NOTICE_MISSING = 'icon_license_notice_missing';++/**+ * @param {string} file+ * @returns {Record<string, any> | null}+ */+function readJson(file) {+ try {+ return JSON.parse(fs.readFileSync(file, 'utf-8'));+ } catch {+ return null;+ }+}++/**+ * One item a check could not judge: listed, never counted, never failing.+ * @typedef {object} IconSetUnchecked+ * @property {string} [icon] the icon whose export was not checked+ * @property {string} [entry] the theme-map entry that was not checked+ * @property {string} [adapter] the adapter export that was not checked+ * @property {string} reason why, and what would let the check judge it+ */++/**+ * Every icon-set issue of one integration package.+ * @param {string} packageDir+ * @param {{name: string, iconSets?: string}} loaded+ * @param {Map<string, IconSetUnchecked[]>} [unchecked] filled, by set name,+ * with what the checks could not judge+ * @returns {Issue[]}+ */+export function iconSetIssues(packageDir, loaded, unchecked = new Map()) {+ if (!loaded.iconSets) return [];+ /** @type {Issue[]} */+ const issues = [];+ const found = discoverIconSetDirectory(loaded.iconSets, loaded.name);+ for (const each of found.errors) {+ issues.push(issueError(INVALID_ICON_SET, each.message));+ }+ const pkg = readJson(path.join(packageDir, 'package.json')) ?? {};+ for (const set of found.sets) {+ /** @type {IconSetUnchecked[]} */+ const notChecked = [];+ issues.push(+ ...checkContract({...set, packageDir}, loaded.name, pkg, notChecked),+ );+ issues.push(...checkDefinitions(set));+ // A module that does not parse hides every export behind it: report it+ // once instead of one missing export per icon.+ const broken = unparsedModule(set, packageDir, loaded.name);+ if (broken) issues.push(broken);+ else issues.push(...checkExports(set, packageDir, loaded.name, notChecked));+ if (notChecked.length > 0) unchecked.set(set.name, notChecked);+ issues.push(...checkUpstream(set, packageDir, pkg));+ }+ return issues;+}++/**+ * The set's module, its relative re-exports, or its generated module, when+ * one does not parse: one error naming the file and the parser's message.+ * @param {DiscoveredIconSet} set+ * @param {string} packageDir+ * @param {string} packageName+ * @returns {Issue | null}+ */+function unparsedModule(set, packageDir, packageName) {+ const entry = resolveIconModule(set.data.module, packageDir, {+ name: packageName,+ dir: packageDir,+ });+ const files = [+ ...(entry ? [entry] : []),+ ...(set.data.generated+ ? [path.join(packageDir, set.data.generated)].filter(file =>+ fs.existsSync(file),+ )+ : []),+ ];+ for (const file of files) {+ const failure = moduleParseFailure(file);+ if (failure) {+ return issueError(+ ICON_MODULE_INVALID,+ `Icon set "${set.name}": ${path.relative(packageDir, failure.file).split(path.sep).join('/')} does not parse (${failure.message}), so its exports cannot be read. Fix the file; for the generated icons module, delete the broken lines and run \`astryx experimental icon add\` again.`,+ );+ }+ }+ return null;+}++/**+ * The icon export contract of one set: every icon and variant is read from+ * the package's public entry (its name, or one of its `exports` subpaths),+ * and named `<Name>Icon`; a declared generated module and adapter exist.+ * @param {DiscoveredIconSet} set+ * @param {string} packageName+ * @param {Record<string, any>} pkg+ * @param {IconSetUnchecked[]} unchecked filled with what it cannot judge+ * @returns {Issue[]}+ */+function checkContract(set, packageName, pkg, unchecked) {+ /** @type {Issue[]} */+ const issues = [];+ const label = `Icon set "${set.name}"`;+ const packageDir = /** @type {string} */ (set.packageDir);+ /**+ * Is `module` the package itself, or a subpath its `exports` map exposes+ * (pattern keys such as `./*` included)? With no `exports`, only the+ * package name is public.+ * @param {string} module+ */+ const isPublic = module => {+ if (module === packageName) return true;+ const {name, subpath} = splitSpecifier(module);+ if (name !== packageName || pkg.exports === undefined) return false;+ return inspectPackageExport(pkg, packageDir, subpath).exported;+ };+ /** @param {string} module @param {string} what */+ const checkModule = (module, what) => {+ if (!isPublic(module)) {+ issues.push(+ issueError(+ ICON_MODULE_NOT_PUBLIC,+ `${label}: ${what} is read from "${module}", which is not ${packageName} or one of its package.json "exports" subpaths. Every icon is a named export of the set's own package; re-export it there (\`astryx experimental icon add\` does this).`,+ ),+ );+ }+ };+ /** @param {string} name @param {string} what */+ const checkName = (name, what) => {+ if (!/^[A-Z][A-Za-z0-9]*Icon$/u.test(name)) {+ issues.push(+ issueWarning(+ ICON_EXPORT_NAME,+ `${label}: ${what} is exported as "${name}"; icon exports are named <Name>Icon, such as TrashIcon.`,+ ),+ );+ }+ };+ checkModule(set.data.module, 'the set');+ for (const icon of set.data.icons) {+ if (icon.module && icon.module !== set.data.module) {+ checkModule(icon.module, `icon "${icon.id}"`);+ }+ checkName(icon.export, `icon "${icon.id}"`);+ for (const variant of icon.variants ?? []) {+ if (+ variant.module &&+ variant.module !== (icon.module ?? set.data.module)+ ) {+ checkModule(variant.module, `a variant of icon "${icon.id}"`);+ }+ checkName(variant.export, `a variant of icon "${icon.id}"`);+ }+ }+ if (set.data.generated) {+ const file = path.join(packageDir, set.data.generated);+ const typesRel = generatedTypesPath(set.data.generated);+ if (fs.existsSync(file) && typesRel) {+ const typesFile = path.join(packageDir, typesRel);+ let expected = null;+ try {+ expected = generatedTypesText(+ readGeneratedStatements(+ fs.readFileSync(file, 'utf-8'),+ set.data.generated,+ ),+ );+ } catch {+ // A module that does not parse is reported on its own.+ }+ const actual = fs.existsSync(typesFile)+ ? fs.readFileSync(typesFile, 'utf-8')+ : null;+ if (expected != null && actual !== expected) {+ issues.push(+ issueError(+ ICON_GENERATED_TYPES_MISMATCH,+ `${label}: ${typesRel} ${actual == null ? 'is missing' : 'does not match its generated module'}. Run \`astryx experimental icon map\` or \`astryx experimental icon add\` to rewrite it, or restore it from the generated module's exports.`,+ ),+ );+ }+ }+ if (!fs.existsSync(file)) {+ issues.push(+ issueError(+ ICON_EXPORT_MISSING,+ `${label}: its generated icons module "${set.data.generated}" does not exist. Run \`astryx experimental icon add\` for each icon, or remove "generated".`,+ ),+ );+ }+ }+ if (set.data.adapter) {+ const {module, export: name} = set.data.adapter;+ const file = resolveFile(path.join(packageDir, module));+ const found = file ? exportOriginVerdict(file, name) : null;+ if (found?.verdict === 'unknown') {+ // The reader cannot prove it either way: listed, never failed.+ unchecked.push({adapter: name, reason: found.reason});+ } else if (!found || found.verdict === 'lacks') {+ issues.push(+ issueError(+ ICON_EXPORT_MISSING,+ `${label}: its adapter "${name}" from "${module}" does not exist. Export the function there, or fix "adapter".`,+ ),+ );+ }+ }+ return issues;+}++/** @param {string} base */+function resolveFile(base) {+ for (const candidate of [+ base,+ ...['.mjs', '.js', '.cjs', '.ts', '.tsx', '.jsx', '.mts'].map(+ extension => `${base}${extension}`,+ ),+ ]) {+ try {+ if (fs.statSync(candidate).isFile()) return candidate;+ } catch {+ // Try the next.+ }+ }+ return null;+}++/**+ * The definition checks of one set's `map`: every built-in definition mapped+ * (error), and each definition the set declares mapped and not already an+ * Astryx definition (warnings). Another unmapped Astryx definition is not an+ * issue: a library need not draw every definition, so it is listed in+ * {@link iconSetCoverage} instead and never fails a check.+ * @param {DiscoveredIconSet} set+ * @returns {Issue[]}+ */+function checkDefinitions(set) {+ /** @type {Issue[]} */+ const issues = [];+ const label = `Icon set "${set.name}"`;+ const mapped = new Set(Object.keys(set.data.map ?? {}));+ const astryx = astryxIconDefinitions().definitions.map(each => each.doc);+ for (const doc of astryx) {+ if (mapped.has(doc.name) || !doc.builtIn) continue;+ const suggestion = suggestIcon(set, doc);+ const hint = suggestion+ ? ` Suggested: astryx experimental icon map ${doc.name} ${suggestion.icon}.`+ : '';+ issues.push(+ issueError(+ ICON_BUILTIN_DEFINITION_MISSING,+ `${label} maps no icon to the built-in icon definition "${doc.name}" (${doc.description} Words: ${doc.words.join(', ')}.). Every set maps every built-in definition: add it to "map" in ${set.name}.icons.json with the id of the icon that draws it.${hint}`,+ ),+ );+ }+ const names = new Set(astryx.map(doc => doc.name));+ for (const {doc} of set.definitions) {+ if (names.has(doc.name)) {+ issues.push(+ issueWarning(+ ICON_DEFINITION_SHADOWED,+ `${label} declares the icon definition "${doc.name}", which Astryx now has. Map your icon to Astryx's definition and remove definitions/${doc.name}.doc.mjs; Astryx's is the one templates use.`,+ ),+ );+ } else if (!mapped.has(doc.name)) {+ const suggestion = suggestIcon(set, doc);+ issues.push(+ issueWarning(+ ICON_DEFINITION_UNUSED,+ `${label} declares the icon definition "${doc.name}", but "map" names no icon for it. Add it to "map" with the id of the icon that draws it, or remove definitions/${doc.name}.doc.mjs.${suggestion ? ` Suggested: astryx experimental icon map ${doc.name} ${suggestion.icon}.` : ''}`,+ ),+ );+ }+ }+ return issues;+}++/**+ * @typedef {object} IconSetCoverage+ * @property {string} set the set's name+ * @property {Array<{name: string, description: string, words: string[]}>} unmappedDefinitions+ * Astryx's optional (not built-in) definitions the set's `map` does not+ * name. Mapping them is optional, so they never fail a check.+ * @property {Array<{definition: string, icon: string}>} suggestions for every+ * unmapped definition, built-in, optional, or the set's own, the icon whose+ * whole id is the definition's name or one of its words; nothing is guessed+ * beyond that+ * @property {IconSetUnchecked[]} unchecked what the checks could not judge:+ * never counted, never failing, even under `--strict`+ */++/**+ * Which icon definitions each valid set under a package's+ * `experimental.iconSets` root leaves unmapped, and the icons that fit them.+ * Reported beside the issues, never as one (spec:AST-084 FR15).+ * @param {{name: string, iconSets?: string}} loaded+ * @param {Map<string, IconSetUnchecked[]>} [unchecked] what+ * {@link iconSetIssues} could not judge, by set name+ * @returns {IconSetCoverage[]}+ */+export function iconSetCoverage(loaded, unchecked = new Map()) {+ if (!loaded.iconSets) return [];+ const found = discoverIconSetDirectory(loaded.iconSets, loaded.name);+ const astryx = astryxIconDefinitions().definitions.map(each => each.doc);+ const names = new Set(astryx.map(doc => doc.name));+ return found.sets.map(set => {+ const mapped = new Set(Object.keys(set.data.map ?? {}));+ const unmapped = [+ ...astryx,+ ...set.definitions+ .map(each => each.doc)+ .filter(doc => !names.has(doc.name)),+ ].filter(doc => !mapped.has(doc.name));+ return {+ set: set.name,+ unmappedDefinitions: unmapped+ .filter(doc => names.has(doc.name) && !doc.builtIn)+ .map(doc => ({+ name: doc.name,+ description: doc.description,+ words: [...doc.words],+ })),+ suggestions: unmapped.flatMap(doc => {+ const suggestion = suggestIcon(set, doc);+ return suggestion+ ? [{definition: doc.name, icon: suggestion.icon}]+ : [];+ }),+ unchecked: unchecked.get(set.name) ?? [],+ };+ });+}++/**+ * The set's icon whose whole id is the definition's name (`chevronDown` is+ * `chevron-down`) or, in order, one of its words (spaces read as `-`). Null+ * when none is: a suggestion is never a guess from parts of words.+ * @param {DiscoveredIconSet} set+ * @param {import('../../authoring/doctypes/icon-definition/type').IconDefinitionDoc} doc+ * @returns {{map: string, icon: string} | null}+ */+export function suggestIcon(set, doc) {+ const kebab = doc.name.replace(/([a-z0-9])([A-Z])/gu, '$1-$2').toLowerCase();+ // No guessing: only an icon whose whole id is the definition's name or one+ // of its words.+ for (const candidate of [+ kebab,+ ...doc.words.map(word => word.trim().toLowerCase().replace(/\s+/gu, '-')),+ ]) {+ const icon = set.data.icons.find(each => each.id === candidate);+ if (icon) return {map: doc.name, icon: icon.id};+ }+ return null;+}++/**+ * The export and theme-map checks of one set.+ * @param {DiscoveredIconSet} set+ * @param {string} packageDir+ * @param {string} packageName+ * @param {IconSetUnchecked[]} unchecked filled with what it cannot judge+ * @returns {Issue[]}+ */+function checkExports(set, packageDir, packageName, unchecked) {+ /** @type {Issue[]} */+ const issues = [];+ const label = `Icon set "${set.name}"`;+ /** @type {Map<string, string | null>} */+ const files = new Map();+ /** @param {string} specifier */+ const fileOf = specifier => {+ if (!files.has(specifier)) {+ files.set(+ specifier,+ resolveIconModule(specifier, packageDir, {+ name: packageName,+ dir: packageDir,+ }),+ );+ }+ return /** @type {string | null} */ (files.get(specifier));+ };+ /**+ * The `exports` target a specifier of this package declares when its file+ * is not there yet, as before a build; null otherwise.+ * @param {string} specifier+ */+ const unbuiltTarget = specifier => {+ const {name, subpath} = splitSpecifier(specifier);+ if (name !== packageName) return null;+ const pkg = readJson(path.join(packageDir, 'package.json'));+ if (!pkg || pkg.exports === undefined) return null;+ const found = inspectPackageExport(pkg, packageDir, subpath);+ return found.exported && found.authoredTarget && !found.target+ ? found.authoredTarget+ : null;+ };+ /** @type {Map<string, {file: string, name: string} | null>} */+ const origins = new Map();+ /**+ * The origin of one export, or an issue when its module lacks it. What it+ * cannot judge it lists as not checked.+ * @param {string} specifier+ * @param {string} name+ * @param {string} what+ * @param {Omit<IconSetUnchecked, 'reason'>} subject+ * @param {boolean} [component] whether the export must be a component+ */+ const originOf = (specifier, name, what, subject, component = true) => {+ const key = `${specifier}\0${name}`;+ if (origins.has(key)) return origins.get(key) ?? null;+ const file = fileOf(specifier);+ const found = file ? exportOriginVerdict(file, name) : null;+ const origin = found?.verdict === 'exports' ? found.origin : null;+ origins.set(key, origin);+ const unbuilt = file ? null : unbuiltTarget(specifier);+ if (unbuilt) {+ unchecked.push({+ ...subject,+ reason: `${what} is read from "${specifier}", whose exports target ${unbuilt} is not there yet; build the package and run the check again.`,+ });+ } else if (!file) {+ issues.push(+ issueError(+ ICON_EXPORT_MISSING,+ `${label}: ${what} is read from "${specifier}", which does not resolve from the package. Fix "module" in ${set.name}.icons.json, or add the subpath to package.json "exports".`,+ ),+ );+ } else if (found?.verdict === 'unknown') {+ // Only an export the reader proves absent fails; anything it cannot+ // prove is listed (architecture:cli-surface INV35, DEC-7).+ unchecked.push({+ ...subject,+ reason: `${what} names export "${name}" of "${specifier}", which this check could not prove: ${found.reason}`,+ });+ } else if (!origin) {+ issues.push(+ issueError(+ ICON_EXPORT_MISSING,+ `${label}: ${what} names export "${name}", which "${specifier}" does not export at runtime. Export it, or fix the name in ${set.name}.icons.json.`,+ ),+ );+ } else if (component && exportValueKind(file, name) === 'data') {+ issues.push(+ issueError(+ ICON_NOT_COMPONENT,+ `${label}: ${what} names export "${name}", which is a value, not a component. Export a React component, or add it with \`astryx experimental icon add\` and declare an "adapter" that turns it into one.`,+ ),+ );+ }+ return origin;+ };++ // The theme map is keyed by the built-in definitions in `map`: the shared+ // names Core renders.+ const builtIn = new Set(+ astryxIconDefinitions()+ .definitions.filter(definition => definition.doc.builtIn)+ .map(definition => definition.doc.name),+ );+ /** @type {Map<string, {file: string, name: string} | null>} */+ const iconOrigins = new Map();+ for (const icon of set.data.icons) {+ const module = icon.module ?? set.data.module;+ iconOrigins.set(+ icon.id,+ originOf(module, icon.export, `icon "${icon.id}"`, {icon: icon.id}),+ );+ for (const variant of icon.variants ?? []) {+ originOf(+ variant.module ?? module,+ variant.export,+ `a variant of icon "${icon.id}"`,+ {icon: icon.id},+ );+ }+ }++ /** @type {Map<string, {id: string, origin: {file: string, name: string} | null}>} */+ const fillers = new Map();+ for (const [name, id] of Object.entries(set.data.map ?? {})) {+ if (builtIn.has(name)) {+ fillers.set(name, {id, origin: iconOrigins.get(id) ?? null});+ }+ }+ const themeMap = set.data.themeMap;+ if (fillers.size === 0) return issues;+ if (!themeMap) {+ issues.push(+ issueError(+ ICON_THEME_MAP_MISMATCH,+ `${label} maps the built-in icon definitions ${[...fillers.keys()].join(', ')} but names no "themeMap". Export an object keyed by exactly those names and name it in ${set.name}.icons.json.`,+ ),+ );+ return issues;+ }+ const mapOrigin = originOf(+ set.data.module,+ themeMap,+ `the theme map`,+ {entry: themeMap},+ false,+ );+ const file = fileOf(set.data.module);+ if (!mapOrigin || !file) return issues;+ const bindings = staticExportBindings(file, themeMap);+ // A theme map built at runtime cannot be read, so it is not checked.+ if (!bindings) {+ unchecked.push({+ entry: themeMap,+ reason: `Theme map "${themeMap}" is not one object literal the static reader can read, so none of its entries were checked. Export it as \`export const ${themeMap} = {...}\` to have it checked.`,+ });+ return issues;+ }+ for (const key of bindings.keys()) {+ if (!fillers.has(key)) {+ issues.push(+ issueError(+ ICON_THEME_MAP_MISMATCH,+ `${label}: theme map "${themeMap}" has "${key}", which "map" does not map. Remove it, or add "${key}" to "map" with the id of the icon that draws it.`,+ ),+ );+ }+ }+ for (const [name, filler] of fillers) {+ if (!bindings.has(name)) {+ issues.push(+ issueError(+ ICON_THEME_MAP_MISMATCH,+ `${label}: theme map "${themeMap}" has no "${name}", which "map" maps to icon "${filler.id}". Add it.`,+ ),+ );+ continue;+ }+ const value = bindings.get(name);+ if (!value) {+ unchecked.push({+ entry: name,+ reason: `Theme map "${themeMap}" has an entry for "${name}" the static reader cannot read. Write it as the icon's binding (${name}: TrashIcon), an element (<TrashIcon />), or createElement(TrashIcon) to have it checked.`,+ });+ continue;+ }+ if (!filler.origin) continue;+ // Compare the bindings each finally names: \`const XIcon = X\` is X. A+ // mismatch is reported only when both are followed to their declarations.+ const mapped = aliasedOrigin(value);+ const drawn = aliasedOrigin(filler.origin);+ if (!mapped || !drawn) {+ unchecked.push({+ entry: name,+ reason: `Theme map "${themeMap}" maps "${name}" through an alias the static reader cannot follow to its declaration, so it was not compared with icon "${filler.id}". Point it at the icon's export, or alias a binding declared in this package.`,+ });+ continue;+ }+ if (mapped.file !== drawn.file || mapped.name !== drawn.name) {+ issues.push(+ issueError(+ ICON_THEME_MAP_MISMATCH,+ `${label}: theme map "${themeMap}" maps "${name}" to other artwork than icon "${filler.id}", which "map" names for it. Point it at the icon's export.`,+ ),+ );+ }+ }+ return issues;+}++/**+ * The upstream checks of one set: version drift and license notices.+ * @param {DiscoveredIconSet} set+ * @param {string} packageDir+ * @param {Record<string, any>} pkg+ * @returns {Issue[]}+ */+function checkUpstream(set, packageDir, pkg) {+ const source = set.data.source;+ if (!source) return [];+ /** @type {Issue[]} */+ const issues = [];+ const label = `Icon set "${set.name}"`;+ const range = ['dependencies', 'peerDependencies', 'optionalDependencies']+ .map(field => pkg[field]?.[source.package])+ .find(value => typeof value === 'string');+ const installedDir = findInstalledPackage(+ packageDir,+ source.package,+ Infinity,+ );+ const installed = installedDir+ ? readJson(path.join(installedDir, 'package.json'))?.version+ : undefined;+ if (typeof installed === 'string' && installed !== source.version) {+ issues.push(+ issueWarning(+ ICON_SOURCE_VERSION_DRIFT,+ `${label} was generated from ${source.package}@${source.version}, but the package resolves ${source.package}@${installed}. Regenerate ${set.name}.icons.json.`,+ ),+ );+ } else if (+ installed == null &&+ range != null &&+ !safeSatisfies(source.version, range)+ ) {+ issues.push(+ issueWarning(+ ICON_SOURCE_VERSION_DRIFT,+ `${label} was generated from ${source.package}@${source.version}, but the package depends on ${source.package}@${range}. Regenerate ${set.name}.icons.json.`,+ ),+ );+ }+ const rootNotices = safeList(packageDir).filter(name =>+ NOTICE_FILE_RE.test(name),+ );+ if (set.notices.length === 0 && rootNotices.length === 0) {+ issues.push(+ issueWarning(+ ICON_LICENSE_NOTICE_MISSING,+ `${label} is generated from ${source.package} but ships no license notice. Copy the library's LICENSE (and NOTICE, if any) into the set directory or the package root.`,+ ),+ );+ }+ return issues;+}++/** @param {string} version @param {string} range */+function safeSatisfies(version, range) {+ try {+ return satisfiesRange(version, range);+ } catch {+ // A range this reader cannot judge is not reported.+ return true;+ }+}++/** @param {string} dir */+function safeList(dir) {+ try {+ return fs.readdirSync(dir);+ } catch {+ return [];+ }+}diff --git a/packages/cli/foundation/discovery/icon-set-checks.test.mjs b/packages/cli/foundation/discovery/icon-set-checks.test.mjsnew file mode 100644index 0000000000..97b5e6ddf5--- /dev/null+++ b/packages/cli/foundation/discovery/icon-set-checks.test.mjs@@ -0,0 +1,905 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The icon-set checks of `integration check` (AST-084 FR12, FR15):+ * every error and warning FR15 lists, read statically, and how `--strict`+ * treats the warnings.+ */++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 {iconSetCoverage, iconSetIssues} from './icon-set-checks.mjs';+import {moduleExportOrigin} from './module-exports.mjs';+import {generatedTypesText} from './icon-set-writer.mjs';+import {integrationCheck} from '../../api/integration/check/check.mjs';+import {+ completeGlyphs,+ definitionSource,+ glyphsData,+ glyphsModules,+ writeIconPackage,+} from '../../test-utils/icon-set-fixture.mjs';+import {ICON_NAMES} from '../../authoring/doctypes/icon-set/icon-names.mjs';++/** @type {string} */+let tmp;+/** @type {string} */+let dir;+beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-icon-checks-'));+ dir = path.join(tmp, 'glyphs');+});+afterEach(() => {+ fs.rmSync(tmp, {recursive: true, force: true});+});++/** The findings about which icon definitions `map` covers. */+const COVERAGE = new Set(['icon_builtin_definition_missing']);++/**+ * What the checks could not judge in the last {@link issuesOf} call, by set.+ * @type {Map<string, import('./icon-set-checks.mjs').IconSetUnchecked[]>}+ */+let notChecked = new Map();++/**+ * The set's issues, leaving out the definition-coverage findings that the+ * small fixture set always has; `coverage: true` keeps them.+ * @param {import('../../test-utils/icon-set-fixture.mjs').IconPackageSpec} [spec]+ * @param {{coverage?: boolean}} [options]+ */+function issuesOf(spec = {}, {coverage = false} = {}) {+ writeIconPackage(dir, spec);+ notChecked = new Map();+ const issues = iconSetIssues(+ dir,+ {+ name: spec.name ?? '@acme/glyphs',+ iconSets: path.join(dir, 'icon-sets'),+ },+ notChecked,+ );+ return coverage ? issues : issues.filter(issue => !COVERAGE.has(issue.code));+}++/** @param {(data: any) => void} change */+function data(change) {+ const value = /** @type {any} */ ({...glyphsData(), module: '@acme/glyphs'});+ change(value);+ return value;+}++/** @param {Record<string, string>} changes */+function modules(changes) {+ return {...glyphsModules(), ...changes};+}++describe('iconSetIssues', () => {+ it('a set that matches its package has no issues', () => {+ expect(issuesOf()).toEqual([]);+ });++ it('follows re-exports, renames, and export * to the declaring file', () => {+ writeIconPackage(dir);+ expect(+ moduleExportOrigin(path.join(dir, 'index.js'), 'TrashSolidIcon'),+ ).toEqual({+ file: path.join(dir, 'icons', 'trash.js'),+ name: 'TrashSolidIcon',+ });+ });++ it('an invalid data file is an error', () => {+ const issues = issuesOf({data: data(d => (d.icons[1].id = 'x'))});+ expect(issues).toEqual([+ expect.objectContaining({code: 'invalid_icon_set', severity: 'error'}),+ ]);+ expect(issues[0].message).toMatch(/duplicate id "x"/);+ });++ it('an export or variant export the module lacks is an error', () => {+ const issues = issuesOf({+ data: data(d => {+ d.icons[3].export = 'HouseIcon';+ d.icons[2].variants[0].export = 'TrashFilledIcon';+ }),+ });+ expect(issues.map(issue => issue.code)).toEqual([+ 'icon_export_missing',+ 'icon_export_missing',+ ]);+ const messages = issues.map(issue => issue.message).join('\n');+ expect(messages).toContain('HouseIcon');+ expect(messages).toContain('TrashFilledIcon');+ });++ it('a type-only export is not a runtime export', () => {+ const issues = issuesOf({+ modules: modules({+ 'icons/home.js': '',+ 'index.js': glyphsModules()['index.js'].replace(+ "export {HomeIcon} from './icons/home.js';",+ 'export type HomeIcon = unknown;',+ ),+ }),+ });+ expect(issues).toEqual([+ expect.objectContaining({code: 'icon_export_missing'}),+ ]);+ });++ it('a match with an unknown confidence or naming the set itself is an error', () => {+ const unknown = issuesOf({+ data: data(+ d =>+ (d.icons[0].matches = [+ {set: 'heroicons', export: 'XMarkIcon', confidence: 'maybe'},+ ]),+ ),+ });+ expect(unknown).toEqual([+ expect.objectContaining({code: 'invalid_icon_set', severity: 'error'}),+ ]);+ expect(unknown[0].message).toMatch(/confidence/);+ fs.rmSync(dir, {recursive: true});+ const self = issuesOf({+ data: data(+ d =>+ (d.icons[0].matches = [+ {set: 'glyphs', export: 'XIcon', confidence: 'exact'},+ ]),+ ),+ });+ expect(self).toEqual([+ expect.objectContaining({code: 'invalid_icon_set', severity: 'error'}),+ ]);+ expect(self[0].message).toMatch(/names this set itself/);+ fs.rmSync(dir, {recursive: true});+ const valid = issuesOf({+ data: data(+ d =>+ (d.icons[0].matches = [+ {+ set: 'heroicons',+ export: 'XMarkIcon',+ variant: 'outline',+ confidence: 'exact',+ },+ ]),+ ),+ });+ expect(valid).toEqual([]);+ });++ it('a module that does not resolve from the package is an error', () => {+ const issues = issuesOf({+ data: data(d => (d.icons[0].module = '@acme/glyphs/solid')),+ });+ // It is not a public entry of the package either.+ expect(issues.map(issue => issue.code).sort()).toEqual([+ 'icon_export_missing',+ 'icon_module_not_public',+ ]);+ expect(+ issues.find(issue => issue.code === 'icon_export_missing')?.message,+ ).toMatch(/does not resolve/);+ });++ describe('the icon export contract', () => {+ it('an icon read from a module other than the package or its exports subpaths is an error', () => {+ const issues = issuesOf({+ data: data(d => (d.icons[0].module = 'upstream-icons')),+ });+ expect(issues).toContainEqual(+ expect.objectContaining({+ code: 'icon_module_not_public',+ severity: 'error',+ }),+ );+ });++ it('a module public only through a pattern subpath is public; a subpath no key matches is not', () => {+ /** @param {Record<string, string>} exports @param {string} module */+ const contractIssues = (exports, module) => {+ writeIconPackage(dir, {+ data: data(d => (d.icons[0].module = module)),+ modules: modules({+ 'dist/outline.js': "export {XIcon} from '../icons/x.js';\n",+ }),+ });+ const pkgFile = path.join(dir, 'package.json');+ const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));+ pkg.exports = exports;+ fs.writeFileSync(pkgFile, JSON.stringify(pkg));+ return iconSetIssues(dir, {+ name: '@acme/glyphs',+ iconSets: path.join(dir, 'icon-sets'),+ }).filter(issue => issue.code === 'icon_module_not_public');+ };+ expect(+ contractIssues(+ {'.': './index.js', './*': './dist/*.js'},+ '@acme/glyphs/outline',+ ),+ ).toEqual([]);+ expect(+ contractIssues(+ {'.': './index.js', './icons/*': './dist/*.js'},+ '@acme/glyphs/outline',+ ),+ ).toEqual([+ expect.objectContaining({+ code: 'icon_module_not_public',+ severity: 'error',+ }),+ ]);+ });++ it('an export not named <Name>Icon warns', () => {+ const issues = issuesOf({+ data: data(d => (d.icons[3].export = 'House')),+ modules: modules({+ 'icons/home.js': 'export function House() { return null; }\n',+ 'index.js': glyphsModules()['index.js'].replace(+ "export {HomeIcon} from './icons/home.js';",+ "export {House} from './icons/home.js';",+ ),+ }),+ });+ expect(issues).toEqual([+ expect.objectContaining({+ code: 'icon_export_name',+ severity: 'warning',+ }),+ ]);+ });++ it('an export that is a value, not a component, is an error', () => {+ const issues = issuesOf({+ modules: modules({+ 'icons/home.js': "export const HomeIcon = {path: 'M3 11'};\n",+ }),+ });+ expect(issues).toEqual([+ expect.objectContaining({+ code: 'icon_not_component',+ severity: 'error',+ }),+ ]);+ });++ it('follows `export *` from an installed package, and lists an export behind a re-export it cannot follow as not checked', () => {+ const upstream = path.join(dir, 'node_modules', 'upstream-icons');+ fs.mkdirSync(upstream, {recursive: true});+ fs.writeFileSync(+ path.join(upstream, 'package.json'),+ JSON.stringify({+ name: 'upstream-icons',+ version: '1.0.0',+ exports: {'.': './index.js'},+ }),+ );+ fs.writeFileSync(+ path.join(upstream, 'index.js'),+ 'export function HomeIcon() { return null; }\n',+ );+ const followed = issuesOf({+ modules: modules({+ 'index.js': glyphsModules()['index.js'].replace(+ "export {HomeIcon} from './icons/home.js';",+ "export * from 'upstream-icons';",+ ),+ }),+ });+ expect(followed).toEqual([]);+ const missing = issuesOf({+ modules: modules({+ 'index.js': glyphsModules()['index.js'].replace(+ "export {HomeIcon} from './icons/home.js';",+ "export * from 'not-installed';",+ ),+ }),+ });+ // The reader cannot judge it, so it is not checked, never an issue.+ expect(missing).toEqual([]);+ expect(notChecked.get('glyphs')).toEqual([+ {+ icon: 'home',+ reason: expect.stringContaining(+ 're-exports everything from "not-installed"',+ ),+ },+ ]);+ });++ it('lists an export whose module is an exports target not built yet as not checked, and still fails an export the built file lacks', () => {+ const unbuilt = issuesOf({+ name: '@acme/glyphs',+ data: data(d => {+ d.icons[0].module = '@acme/glyphs/extra';+ }),+ });+ const pkgFile = path.join(dir, 'package.json');+ const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));+ pkg.exports = {...pkg.exports, './extra': './dist/extra.js'};+ fs.writeFileSync(pkgFile, JSON.stringify(pkg));+ notChecked = new Map();+ const before = iconSetIssues(+ dir,+ {name: '@acme/glyphs', iconSets: path.join(dir, 'icon-sets')},+ notChecked,+ ).filter(issue => !COVERAGE.has(issue.code));+ expect(unbuilt.some(issue => issue.code === 'icon_export_missing')).toBe(+ true,+ );+ expect(+ before.filter(issue => issue.code === 'icon_export_missing'),+ ).toEqual([]);+ expect(notChecked.get('glyphs')).toEqual([+ {+ icon: 'x',+ reason: expect.stringContaining(+ 'exports target ./dist/extra.js is not there yet',+ ),+ },+ ]);+ // Built without the export: a real miss, an error.+ fs.mkdirSync(path.join(dir, 'dist'), {recursive: true});+ fs.writeFileSync(path.join(dir, 'dist', 'extra.js'), 'export {};\n');+ notChecked = new Map();+ const built = iconSetIssues(+ dir,+ {name: '@acme/glyphs', iconSets: path.join(dir, 'icon-sets')},+ notChecked,+ );+ expect(built).toContainEqual(+ expect.objectContaining({+ code: 'icon_export_missing',+ severity: 'error',+ }),+ );+ expect(notChecked.get('glyphs')).toBeUndefined();+ });++ it('fails only an export the reader proves absent; an export it cannot follow is not checked', () => {+ // Bound to a default import: present, but not followed to its declaration.+ const viaDefault = issuesOf({+ modules: modules({+ 'icons/trash-default.js':+ 'export default function Trash(props) { return null; }\n',+ 'icons/trash.js':+ "import Trash from './trash-default.js';\nexport {Trash as TrashIcon};\nexport function TrashSolidIcon(props) { return null; }\n",+ }),+ });+ expect(viaDefault).toEqual([]);+ expect(notChecked.get('glyphs')).toEqual([+ {+ icon: 'trash',+ reason: expect.stringContaining(+ 'from a default import of "./trash-default.js"',+ ),+ },+ ]);+ // Imported from a package that does not resolve.+ const viaMissing = issuesOf({+ modules: modules({+ 'icons/trash.js':+ "import {TrashIcon} from 'not-installed';\nexport {TrashIcon};\nexport function TrashSolidIcon(props) { return null; }\n",+ }),+ });+ expect(viaMissing).toEqual([]);+ expect(notChecked.get('glyphs')).toEqual([+ {+ icon: 'trash',+ reason: expect.stringContaining(+ 'imported from "not-installed", which does not resolve from the package',+ ),+ },+ ]);+ // A built file that truly lacks the export: an error.+ const lacking = issuesOf({+ modules: modules({+ 'icons/trash.js':+ 'export function TrashSolidIcon(props) { return null; }\n',+ }),+ });+ expect(lacking).toEqual([+ expect.objectContaining({+ code: 'icon_export_missing',+ severity: 'error',+ }),+ ]);+ expect(notChecked.get('glyphs')).toBeUndefined();+ });++ it('an adapter behind a re-export the reader cannot follow is not checked; one proved absent is an error', () => {+ const adapter = {module: './src/adapt.js', export: 'adapt'};+ const unfollowed = issuesOf({+ data: data(d => {+ d.adapter = adapter;+ }),+ modules: modules({+ 'src/adapt.js': "export * from 'not-installed';\n",+ }),+ });+ expect(unfollowed).toEqual([]);+ expect(notChecked.get('glyphs')).toEqual([+ {+ adapter: 'adapt',+ reason: expect.stringContaining('"not-installed"'),+ },+ ]);+ const absent = issuesOf({+ data: data(d => {+ d.adapter = adapter;+ }),+ modules: modules({'src/adapt.js': 'export function other() {}\n'}),+ });+ expect(absent).toEqual([+ expect.objectContaining({+ code: 'icon_export_missing',+ message: expect.stringContaining('its adapter "adapt"'),+ }),+ ]);+ });++ it('a generated module or adapter the data names must exist', () => {+ const issues = issuesOf({+ data: data(d => {+ d.generated = './icon-sets/glyphs/glyphs.generated.js';+ d.adapter = {module: './src/adapt.js', export: 'adapt'};+ }),+ });+ expect(issues.map(issue => issue.code)).toEqual([+ 'icon_export_missing',+ 'icon_export_missing',+ ]);+ });+ });++ describe('theme map (FR12)', () => {+ it('an extra key is an error', () => {+ const issues = issuesOf({+ modules: modules({+ 'theme.js': glyphsModules()['theme.js'].replace(+ '};',+ ' menu: XIcon,\n};',+ ),+ }),+ });+ expect(issues).toEqual([+ expect.objectContaining({code: 'icon_theme_map_mismatch'}),+ ]);+ expect(issues[0].message).toMatch(/has "menu", which "map" does not map/);+ });++ it('a missing key is an error', () => {+ const issues = issuesOf({+ modules: modules({+ 'theme.js':+ "import {XIcon} from './icons/x.js';\nexport const themeIcons = {close: XIcon};\n",+ }),+ });+ expect(issues).toEqual([+ expect.objectContaining({code: 'icon_theme_map_mismatch'}),+ ]);+ expect(issues[0].message).toMatch(/has no "search"/);+ });++ it('wrong artwork is an error, an aliased import of the right artwork is not', () => {+ const issues = issuesOf({+ modules: modules({+ 'theme.js':+ "import {XIcon} from './icons/x.js';\nimport {HomeIcon} from './icons/home.js';\nexport const themeIcons = {close: XIcon, search: HomeIcon};\n",+ }),+ });+ expect(issues).toEqual([+ expect.objectContaining({code: 'icon_theme_map_mismatch'}),+ ]);+ expect(issues[0].message).toMatch(/maps "search" to other artwork/);+ });++ it('reads JSX elements as the artwork they render', () => {+ const issues = issuesOf({+ modules: modules({+ 'theme.js':+ "import {XIcon} from './icons/x.js';\nimport {SearchIcon} from './icons/search.js';\nexport const themeIcons = {close: <XIcon />, search: <SearchIcon />};\n",+ }),+ });+ expect(issues).toEqual([]);+ });++ it('reads createElement and jsx calls as the artwork they render, and lists an entry it cannot read as not checked', () => {+ const read = issuesOf({+ modules: modules({+ 'theme.js':+ "import {createElement} from 'react';\nimport {jsx as _jsx} from 'react/jsx-runtime';\nimport {XIcon} from './icons/x.js';\nimport {SearchIcon} from './icons/search.js';\nexport const themeIcons = {close: createElement(XIcon, {}), search: _jsx(SearchIcon, {})};\n",+ }),+ });+ expect(read).toEqual([]);+ const unread = issuesOf({+ modules: modules({+ 'theme.js':+ "import {XIcon} from './icons/x.js';\nconst pick = icon => icon;\nexport const themeIcons = {close: XIcon, search: pick(XIcon)};\n",+ }),+ });+ expect(unread).toEqual([]);+ expect(notChecked.get('glyphs')).toEqual([+ {+ entry: 'search',+ reason: expect.stringContaining('the static reader cannot read'),+ },+ ]);+ });++ it('follows a const alias of an icon before comparing; one it cannot follow is not checked', () => {+ const aliased = issuesOf({+ modules: modules({+ 'icons/x.js':+ "import {XMark} from './x-mark.js';\nexport const XIcon = XMark;\n",+ 'icons/x-mark.js': 'export function XMark(props) { return null; }\n',+ 'theme.js':+ "import {XMark} from './icons/x-mark.js';\nimport {SearchIcon as Magnifier} from './icons/search.js';\nexport const themeIcons = {close: XMark, search: Magnifier};\n",+ }),+ });+ expect(aliased).toEqual([]);+ expect(notChecked.get('glyphs')).toBeUndefined();+ // An alias of another component is still a proven mismatch.+ const other = issuesOf({+ modules: modules({+ 'icons/x.js':+ "import {XMark} from './x-mark.js';\nexport const XIcon = XMark;\n",+ 'icons/x-mark.js':+ 'export function XMark(props) { return null; }\nexport function Other(props) { return null; }\n',+ 'theme.js':+ "import {Other} from './icons/x-mark.js';\nimport {SearchIcon as Magnifier} from './icons/search.js';\nexport const themeIcons = {close: Other, search: Magnifier};\n",+ }),+ });+ expect(other).toEqual([+ expect.objectContaining({code: 'icon_theme_map_mismatch'}),+ ]);+ // An alias of a member the reader cannot follow: not checked.+ const member = issuesOf({+ modules: modules({+ 'icons/x.js':+ "import * as all from './x-mark.js';\nexport const XIcon = all.XMark;\n",+ 'icons/x-mark.js': 'export function XMark(props) { return null; }\n',+ 'theme.js':+ "import {XMark} from './icons/x-mark.js';\nimport {SearchIcon as Magnifier} from './icons/search.js';\nexport const themeIcons = {close: XMark, search: Magnifier};\n",+ }),+ });+ expect(member).toEqual([]);+ expect(notChecked.get('glyphs')).toEqual([+ {entry: 'close', reason: expect.stringContaining('alias')},+ ]);+ });++ it('a set that maps built-in definitions but has no themeMap is an error', () => {+ const issues = issuesOf({data: data(d => delete d.themeMap)});+ expect(issues).toEqual([+ expect.objectContaining({code: 'icon_theme_map_mismatch'}),+ ]);+ });++ it('a map built at runtime is left unchecked, not reported', () => {+ const issues = issuesOf({+ modules: modules({+ 'theme.js': 'export const themeIcons = Object.fromEntries([]);\n',+ }),+ });+ expect(issues).toEqual([]);+ });+ });++ describe('upstream (warnings)', () => {+ /** @param {string} installed */+ const withUpstream = (installed, notice = true) => {+ const upstream = path.join(dir, 'node_modules', 'upstream-icons');+ fs.mkdirSync(upstream, {recursive: true});+ fs.writeFileSync(+ path.join(upstream, 'package.json'),+ JSON.stringify({name: 'upstream-icons', version: installed}),+ );+ return issuesOf({+ notice,+ dependencies: {'upstream-icons': '^1.0.0'},+ data: data(+ d => (d.source = {package: 'upstream-icons', version: '1.2.0'}),+ ),+ });+ };++ it('data generated from another upstream version warns', () => {+ expect(withUpstream('1.3.0')).toEqual([+ expect.objectContaining({+ code: 'icon_source_version_drift',+ severity: 'warning',+ }),+ ]);+ expect(withUpstream('1.2.0')).toEqual([]);+ });++ it('no license notice for a set with an upstream warns', () => {+ expect(withUpstream('1.2.0', false)).toEqual([+ expect.objectContaining({+ code: 'icon_license_notice_missing',+ severity: 'warning',+ }),+ ]);+ });+ });+});++describe('icon definitions (map)', () => {+ it('every built-in definition missing from map is an error; the optional ones are listed, never issues, with a suggestion only when an icon id is its name or a word', () => {+ const issues = issuesOf({}, {coverage: true});+ const builtIn = issues.filter(+ issue => issue.code === 'icon_builtin_definition_missing',+ );+ // close and search are mapped; every other built-in is not.+ expect(builtIn).toHaveLength(ICON_NAMES.length - 2);+ expect(builtIn.every(issue => issue.severity === 'error')).toBe(true);+ // An issue is only ever an error or a warning.+ expect(+ issues.every(issue => ['error', 'warning'].includes(issue.severity)),+ ).toBe(true);+ expect(issues.some(issue => /"delete"|"home"/.test(issue.message))).toBe(+ false,+ );+ const [coverage] = iconSetCoverage({+ name: '@acme/glyphs',+ iconSets: path.join(dir, 'icon-sets'),+ });+ expect(coverage.set).toBe('glyphs');+ const names = coverage.unmappedDefinitions.map(each => each.name);+ expect(names).toContain('delete');+ expect(names).toContain('home');+ // Built-in definitions are issues, not listed here.+ expect(names).not.toContain('calendar');+ expect(+ coverage.unmappedDefinitions.find(each => each.name === 'delete'),+ ).toMatchObject({+ description: expect.any(String),+ words: expect.any(Array),+ });+ // `delete` names no icon, but one of its words is the trash icon's id.+ expect(coverage.suggestions).toContainEqual({+ definition: 'delete',+ icon: 'trash',+ });+ expect(coverage.suggestions).toContainEqual({+ definition: 'home',+ icon: 'home',+ });+ // Nothing in the set draws a calendar: no suggestion.+ expect(+ coverage.suggestions.some(each => each.definition === 'calendar'),+ ).toBe(false);+ expect(+ builtIn.find(issue => issue.message.includes('"calendar"')),+ ).toBeDefined();+ });++ it('a set mapping every built-in definition has no error', () => {+ const {data: complete, modules: completeModules} = completeGlyphs();+ const issues = issuesOf(+ {data: {...complete, module: '@acme/glyphs'}, modules: completeModules},+ {coverage: true},+ );+ expect(issues.filter(issue => issue.severity === 'error')).toEqual([]);+ });++ it("a map key that is neither Astryx's definition nor the set's own is an error", () => {+ const issues = issuesOf({data: data(d => (d.map.rotate = 'home'))});+ expect(issues).toEqual([+ expect.objectContaining({code: 'invalid_icon_set', severity: 'error'}),+ ]);+ expect(issues[0].message).toMatch(+ /map "rotate" \(icon "home"\) is not an icon definition\. Declare it in definitions\/rotate\.doc\.mjs/,+ );+ });++ it("the set's own definitions: mapped is fine, unmapped warns with a suggestion, and one Astryx has warns", () => {+ const issues = issuesOf({+ data: data(d => (d.map.rotate = 'home')),+ definitions: {+ rotate: definitionSource('rotate'),+ garbage: definitionSource('garbage', {words: ['bin', 'trash']}),+ // The trash icon is tagged garbage, and `tra` starts its id: neither+ // is a suggestion. No guessing.+ rubbish: definitionSource('rubbish', {words: ['garbage', 'tra']}),+ delete: definitionSource('delete'),+ },+ });+ expect(issues.map(issue => issue.code).sort()).toEqual([+ 'icon_definition_shadowed',+ 'icon_definition_unused',+ 'icon_definition_unused',+ ]);+ const unused = issues.filter(+ issue => issue.code === 'icon_definition_unused',+ );+ const garbage = unused.find(issue => issue.message.includes('"garbage"'));+ expect(garbage?.message).toContain(+ 'astryx experimental icon map garbage trash',+ );+ const rubbish = unused.find(issue => issue.message.includes('"rubbish"'));+ expect(rubbish?.message).not.toContain('Suggested');+ const [coverage] = iconSetCoverage({+ name: '@acme/glyphs',+ iconSets: path.join(dir, 'icon-sets'),+ });+ expect(coverage.suggestions).toContainEqual({+ definition: 'garbage',+ icon: 'trash',+ });+ expect(+ coverage.suggestions.some(each => each.definition === 'rubbish'),+ ).toBe(false);+ expect(+ issues.find(issue => issue.code === 'icon_definition_shadowed')?.message,+ ).toContain('Astryx now has');+ });++ it('a definition file that does not read makes the set invalid', () => {+ const issues = issuesOf({+ definitions: {rotate: definitionSource('Rotate')},+ });+ expect(issues).toEqual([+ expect.objectContaining({code: 'invalid_icon_set'}),+ ]);+ });+});++describe('integration check over an icon set', () => {+ it('an error fails the run; a warning fails only under --strict', async () => {+ const complete = completeGlyphs();+ writeIconPackage(dir, {+ notice: false,+ modules: complete.modules,+ data: {+ ...complete.data,+ module: '@acme/glyphs',+ source: {package: 'upstream-icons', version: '1.2.0'},+ },+ });+ const loose = await integrationCheck({cwd: dir});+ const strict = await integrationCheck({cwd: dir, strict: true});+ expect(loose.data.failed).toBe(false);+ expect(strict.data.failed).toBe(true);+ expect(JSON.stringify(strict.data)).toContain(+ 'icon_license_notice_missing',+ );++ fs.rmSync(dir, {recursive: true});+ writeIconPackage(dir, {data: data(d => (d.icons[0].export = 'Nope'))});+ const broken = await integrationCheck({cwd: dir});+ expect(broken.data.failed).toBe(true);+ expect(JSON.stringify(broken.data)).toContain('icon_export_missing');+ }, 60_000);++ it('a set that maps every built-in definition passes --strict: other unmapped Astryx definitions are listed, not issues', async () => {+ const complete = completeGlyphs();+ writeIconPackage(dir, {+ modules: complete.modules,+ data: {...complete.data, module: '@acme/glyphs'},+ });+ const strict = await integrationCheck({cwd: dir, strict: true});+ // The fixture has no TypeScript, so only that skipped work remains.+ expect(+ strict.data.failures.filter(each => each.code !== 'doc_types_skipped'),+ ).toEqual([]);+ expect(strict.data.warnings).toBe(0);+ const validate = strict.data.checks.find(each => each.check === 'validate');+ const listed = /** @type {any} */ (validate).response.data.iconSets;+ expect(listed[0].unmappedDefinitions.length).toBeGreaterThan(0);+ expect(JSON.stringify(strict.data)).not.toContain('"severity":"info"');+ // `--next` counts only notes marked `next`; the icon-set lists are not+ // notes, so it fails no more than `--strict` does.+ const ahead = await integrationCheck({cwd: dir, strict: true, next: true});+ expect(+ ahead.data.failures.filter(each => each.code !== 'doc_types_skipped'),+ ).toEqual([]);+ }, 60_000);+});++describe('modules that do not parse, and generated types', () => {+ it('a module that does not parse is one error, not a missing export per icon', () => {+ const issues = issuesOf({+ modules: modules({+ 'index.js': "export {XIcon} from './icons/x.js';\nexport {SearchIcon\n",+ }),+ });+ expect(issues).toEqual([+ expect.objectContaining({code: 'icon_module_invalid', severity: 'error'}),+ ]);+ expect(issues[0].message).toContain('index.js does not parse');+ });++ it("a generated module's declaration file that is missing or stale is an error", () => {+ const generated = './icon-sets/glyphs/glyphs.generated.js';+ const withGenerated = data(d => (d.generated = generated));+ const setup = (/** @type {string | null} */ types) => {+ fs.rmSync(dir, {recursive: true, force: true});+ writeIconPackage(dir, {data: withGenerated});+ const file = path.join(dir, generated);+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, "export {XIcon} from '../../icons/x.js';\n");+ if (types != null) {+ fs.writeFileSync(file.replace(/\.js$/u, '.d.ts'), types);+ }+ return iconSetIssues(dir, {+ name: '@acme/glyphs',+ iconSets: path.join(dir, 'icon-sets'),+ });+ };+ const codes = (/** @type {any[]} */ issues) =>+ issues+ .map(issue => issue.code)+ .filter(code => code === 'icon_generated_types_mismatch');+ expect(codes(setup(null))).toEqual(['icon_generated_types_mismatch']);+ expect(codes(setup('export {};\n'))).toEqual([+ 'icon_generated_types_mismatch',+ ]);+ expect(+ codes(+ setup(generatedTypesText(["export {XIcon} from '../../icons/x.js';"])),+ ),+ ).toEqual([]);+ });+});++// FR15's table is the whole list: a code the checks add, drop, or move to+// another severity fails here until the table says so.+describe('the codes and severities FR15 lists', () => {+ it('are exactly the codes this module raises, at the same severity', async () => {+ const checks = await import('./icon-set-checks.mjs');+ const source = fs.readFileSync(+ new URL('./icon-set-checks.mjs', import.meta.url),+ 'utf8',+ );+ /** @type {Record<string, string>} */+ const constants = Object.fromEntries(+ Object.entries(checks).filter(+ ([name, value]) =>+ /^(?:ICON_|INVALID_ICON_SET$)/u.test(name) &&+ typeof value === 'string' &&+ /^(?:icon_|invalid_icon_set$)/u.test(value),+ ),+ );+ /** @type {Record<string, string>} */+ const raised = {};+ for (const [, kind, name] of source.matchAll(+ /issue(Error|Warning)\(\s*([A-Z_]+)\b/gu,+ )) {+ const code = constants[name];+ expect(code, `${name} is a code constant`).toBeTypeOf('string');+ const severity = kind.toLowerCase();+ expect(raised[code] ?? severity, `${code} has one severity`).toBe(+ severity,+ );+ raised[code] = severity;+ }+ expect(Object.keys(constants).length).toBeGreaterThan(10);+ expect(Object.keys(raised).sort()).toEqual(Object.values(constants).sort());++ const spec = fs.readFileSync(+ new URL(+ '../../../../docs/specs/AST-084-icon-sets/spec.md',+ import.meta.url,+ ),+ 'utf8',+ );+ const fr15 = spec.slice(spec.indexOf('**FR15 '), spec.indexOf('**FR16 '));+ /** @type {Record<string, string>} */+ const listed = {};+ for (const [, code, severity] of fr15.matchAll(+ /^\s*\| `([a-z_]+)`\s*\| (error|warning)\s*\|/gmu,+ )) {+ listed[code] = severity;+ }+ expect(listed).toEqual(raised);+ });+});diff --git a/packages/cli/foundation/discovery/icon-set-discovery.mjs b/packages/cli/foundation/discovery/icon-set-discovery.mjsnew file mode 100644index 0000000000..876474d6f0--- /dev/null+++ b/packages/cli/foundation/discovery/icon-set-discovery.mjs@@ -0,0 +1,464 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Icon-set discovery (AST-084 FR1–FR5, FR8, FR17): the one seam+ * every icon surface reads installed icon sets through.+ *+ * An integration's `experimental.iconSets` root holds one lower-kebab directory per set.+ * Each set has a statically read `<name>.doc.mjs` IconSetDoc and a+ * `<name>.icons.json` data file. Discovery never executes the descriptor, the+ * data file, or the icon module. A set whose descriptor or data is invalid,+ * or whose `module` does not resolve from the project, is withdrawn: it+ * answers nothing, and its reason is kept for Doctor.+ *+ * @input Loaded integrations and the project directory+ * @output Discovered icon sets, withdrawn sets with reasons, and the+ * project's icon-set choice+ * @position packages/cli/foundation/discovery — icon-set discovery seam+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ parseIconSet,+ parseIconSetData,+} from '../../authoring/doctypes/icon-set/parse.mjs';+import {assertWithin} from '../fs/path-safety.mjs';+import {findInstalledPackage} from '../fs/paths.mjs';+import {inspectPackageExport} from './package-exports.mjs';+import {+ astryxDefinitionsByName,+ readDefinitionsDir,+} from './icon-definition-discovery.mjs';+import {+ isIgnoredThemeEntry,+ readStaticDescriptorValue,+} from './theme-discovery.mjs';++/** @typedef {import('../../authoring/doctypes/icon-set/type').IconSetData} IconSetData */+/** @typedef {import('../../authoring/doctypes/icon-set/type').IconSetIcon} IconSetIcon */++const SET_NAME_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;++/** A license or notice file a set ships beside its data (FR15). */+export const NOTICE_FILE_RE = /^(?:licen[cs]e|notice|copying)(?:[.-].*)?$/iu;++/**+ * One installed icon set: its descriptor, its data, and where it came from.+ * @typedef {object} DiscoveredIconSet+ * @property {string} name set name, the directory name+ * @property {string} displayName+ * @property {string} description+ * @property {boolean} maintained+ * @property {string} license SPDX expression for the artwork+ * @property {string} package the integration package that ships the set+ * @property {string} [packageDir] absolute directory of that package+ * @property {string} dir absolute set directory+ * @property {string} docPath absolute descriptor path+ * @property {string} dataPath absolute data-file path+ * @property {IconSetData} data the validated data file+ * @property {string[]} notices license and notice files in the set directory+ * @property {import('./icon-definition-discovery.mjs').DiscoveredIconDefinition[]} definitions+ * the set's own definitions, from its `definitions` folder+ * @property {string | null} [moduleFile] the file `data.module` resolves to+ * from the project, when it resolves+ */++/**+ * A set that was found but answers nothing, and why.+ * @typedef {object} WithdrawnIconSet+ * @property {string} name+ * @property {string} package+ * @property {'invalid' | 'unresolved'} kind `invalid`: the descriptor or data+ * file is invalid; `unresolved`: its module does not resolve from the project+ * @property {string} reason+ */++/**+ * The project's icon set (FR8).+ * @typedef {object} IconSetChoice+ * @property {'selected' | 'none' | 'ambiguous' | 'missing' | 'withdrawn'} status+ * `selected`: one set is the project's; `none`: no set is installed;+ * `ambiguous`: two or more are installed and `experimental.iconSet` names none of them+ * uniquely; `missing`: `experimental.iconSet` names a set that is not installed;+ * `withdrawn`: it names a set that is installed but withdrawn (invalid, or+ * its module does not resolve), and `reason` says why+ * @property {DiscoveredIconSet} [set] the project's set, when selected+ * @property {string} [configured] the `experimental.iconSet` config value, when set+ * @property {string} reason one sentence saying why+ */++/**+ * Read every set under one `iconSets` root, without executing anything.+ * @param {string} root absolute `iconSets` root+ * @param {string} owner the package that ships the root+ * @returns {{sets: DiscoveredIconSet[], errors: Array<{name: string, message: string}>}}+ */+export function discoverIconSetDirectory(root, owner) {+ /** @type {DiscoveredIconSet[]} */+ const sets = [];+ /** @type {Array<{name: string, message: string}>} */+ const errors = [];+ let entries;+ try {+ entries = fs.readdirSync(root, {withFileTypes: true});+ } catch {+ return {sets, errors};+ }+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {+ if (isIgnoredThemeEntry(entry.name) || !entry.isDirectory()) continue;+ // Only a lower-kebab directory is a set (FR1).+ if (!SET_NAME_RE.test(entry.name)) continue;+ try {+ sets.push(readIconSet(root, entry.name, owner));+ } catch (error) {+ errors.push({+ name: entry.name,+ message: error instanceof Error ? error.message : String(error),+ });+ }+ }+ return {sets, errors};+}++/**+ * Read one set directory: its descriptor, its data file, and its notices.+ * @param {string} root+ * @param {string} name+ * @param {string} owner+ * @returns {DiscoveredIconSet}+ */+function readIconSet(root, name, owner) {+ const dir = assertWithin(name, root, {label: 'icon set directory'});+ const docPath = path.join(dir, `${name}.doc.mjs`);+ const dataPath = path.join(dir, `${name}.icons.json`);+ const label = `Icon set "${name}" in ${owner}`;+ for (const [file, what] of [+ [docPath, 'descriptor'],+ [dataPath, 'data file'],+ ]) {+ let stat;+ try {+ stat = fs.lstatSync(file);+ } catch {+ throw new Error(+ `${label} has no ${what}: add ${path.basename(file)} to its directory.`,+ );+ }+ if (!stat.isFile()) {+ throw new Error(+ `${label}: ${path.basename(file)} must be a regular file inside the set directory.`,+ );+ }+ }++ const doc = parseIconSet(+ readStaticDescriptorValue(docPath, `${label} descriptor`, 'IconSetDoc'),+ `${label} descriptor`,+ );+ if (doc.name !== name) {+ throw new Error(+ `${label}: the descriptor names "${doc.name}", but a set's name must equal its directory name.`,+ );+ }++ /** @type {unknown} */+ let raw;+ try {+ raw = JSON.parse(fs.readFileSync(dataPath, 'utf-8'));+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new Error(+ `${label}: ${name}.icons.json is not valid JSON: ${message}`,+ {+ cause: error,+ },+ );+ }+ const data = parseIconSetData(raw, `${label} data file`);+ // A reviewed match names an icon in another set (AST-084 FR3).+ for (const icon of data.icons) {+ for (const match of icon.matches ?? []) {+ if (match.set === name) {+ throw new Error(+ `${label} data file is invalid: icon "${icon.id}" has a match that names this set itself; a match names an icon in another set.`,+ );+ }+ }+ }++ // The set's own definitions, one file each in its `definitions` folder. A file+ // that does not read makes the set invalid, like its descriptor.+ const own = readDefinitionsDir(path.join(dir, 'definitions'), owner);+ if (own.errors.length > 0) {+ throw new Error(+ `${label}: ${own.errors.map(error => error.message).join(' ')}`,+ );+ }+ // Every key of `map` is Astryx's definition or one the set declares.+ const astryx = astryxDefinitionsByName();+ const declared = new Set(+ own.definitions.map(definition => definition.doc.name),+ );+ for (const [name, id] of Object.entries(data.map ?? {})) {+ if (astryx.has(name) || declared.has(name)) continue;+ throw new Error(+ `${label} data file is invalid: map "${name}" (icon "${id}") is not an icon definition. Declare it in definitions/${name}.doc.mjs, or use an Astryx icon definition (astryx docs cli/experimental/icon-definitions).`,+ );+ }++ const notices = fs+ .readdirSync(dir, {withFileTypes: true})+ .filter(file => file.isFile() && NOTICE_FILE_RE.test(file.name))+ .map(file => file.name)+ .sort();++ return {+ name,+ displayName: doc.displayName,+ description: doc.description,+ maintained: doc.maintained,+ license: doc.license,+ package: owner,+ dir,+ docPath,+ dataPath,+ data,+ notices,+ definitions: own.definitions,+ };+}++/**+ * The definitions each icon draws, by icon id, from the set's `map`.+ * @param {IconSetData} data+ * @returns {Map<string, string[]>}+ */+export function definitionsByIcon(data) {+ /** @type {Map<string, string[]>} */+ const byIcon = new Map();+ for (const [name, id] of Object.entries(data.map ?? {})) {+ const list = byIcon.get(id) ?? [];+ list.push(name);+ byIcon.set(id, list);+ }+ return byIcon;+}++/**+ * Split an import specifier into its package name and subpath.+ * @param {string} specifier+ * @returns {{name: string, subpath: string}}+ */+export function splitSpecifier(specifier) {+ const parts = specifier.split('/');+ const count = specifier.startsWith('@') ? 2 : 1;+ const name = parts.slice(0, count).join('/');+ const rest = parts.slice(count).join('/');+ return {name, subpath: rest ? `./${rest}` : '.'};+}++/**+ * The file a package's root resolves to when it has no `exports` map.+ * @param {string} packageDir+ * @param {Record<string, unknown>} pkg+ * @returns {string | null}+ */+function legacyRootEntry(packageDir, pkg) {+ const candidates = [+ ...[pkg.module, pkg.main].filter(+ (/** @type {unknown} */ value) => typeof value === 'string',+ ),+ 'index.js',+ 'index.mjs',+ 'index.ts',+ ];+ for (const candidate of /** @type {string[]} */ (candidates)) {+ for (const file of [candidate, `${candidate}.js`, `${candidate}.mjs`]) {+ try {+ const resolved = assertWithin(file, packageDir, {+ label: 'package entry',+ });+ if (fs.statSync(resolved).isFile()) return resolved;+ } catch {+ // Try the next candidate.+ }+ }+ }+ return null;+}++/**+ * Resolve an icon module specifier from a directory, the way the project+ * would import it, without executing anything: the package is found through+ * node_modules (or the package being authored, when it is that package), and+ * the subpath through its `exports` map.+ * @param {string} specifier+ * @param {string} fromDir+ * @param {{name?: string, dir?: string}} [self] the package being read, which+ * resolves its own name even when it does not install itself+ * @returns {string | null} the module file, or null when it does not resolve+ */+export function resolveIconModule(specifier, fromDir, self = {}) {+ const {name, subpath} = splitSpecifier(specifier);+ const packageDir =+ self.name === name && self.dir+ ? self.dir+ : // Node's own resolution: every ancestor's node_modules, no depth cap.+ findInstalledPackage(fromDir, name, Infinity);+ if (!packageDir) return null;+ /** @type {Record<string, unknown>} */+ let pkg;+ try {+ pkg = JSON.parse(+ fs.readFileSync(path.join(packageDir, 'package.json'), 'utf-8'),+ );+ } catch {+ return null;+ }+ if (pkg.exports === undefined && subpath === '.') {+ return legacyRootEntry(packageDir, pkg);+ }+ return inspectPackageExport(pkg, packageDir, subpath).target;+}++/**+ * Discover one loaded integration's icon sets, and withdraw each one that is+ * invalid or whose module does not resolve from the project (FR3, FR17).+ * @param {import('../integrations/integrations.mjs').LoadedIntegration} integration+ * @param {{projectDir: string}} options+ * @returns {{sets: DiscoveredIconSet[], withdrawn: WithdrawnIconSet[]}}+ */+export function discoverIntegrationIconSets(integration, {projectDir}) {+ /** @type {DiscoveredIconSet[]} */+ const sets = [];+ /** @type {WithdrawnIconSet[]} */+ const withdrawn = [];+ if (!integration.iconSets) return {sets, withdrawn};+ const found = discoverIconSetDirectory(+ integration.iconSets,+ integration.name,+ );+ for (const error of found.errors) {+ withdrawn.push({+ name: error.name,+ package: integration.name,+ kind: 'invalid',+ reason: error.message,+ });+ }+ for (const set of found.sets) {+ const moduleFile = resolveIconModule(set.data.module, projectDir, {+ name: integration.name,+ dir: integration.__packageDir,+ });+ if (!moduleFile) {+ withdrawn.push({+ name: set.name,+ package: integration.name,+ kind: 'unresolved',+ reason: `Icon set "${set.name}" in ${integration.name}: its module "${set.data.module}" does not resolve from the project. Install it, or fix "module" in ${set.name}.icons.json.`,+ });+ continue;+ }+ sets.push({...set, packageDir: integration.__packageDir, moduleFile});+ }+ return {sets, withdrawn};+}++/**+ * The withdrawn sets a selector names, as `"<set>"` or `"<package>/<set>"`.+ * @param {WithdrawnIconSet[]} withdrawn+ * @param {string} selector+ * @returns {WithdrawnIconSet[]}+ */+export function withdrawnNamed(withdrawn, selector) {+ const exact = withdrawn.filter(+ each => `${each.package}/${each.name}` === selector,+ );+ return exact.length > 0+ ? exact+ : withdrawn.filter(each => each.name === selector);+}++/**+ * Pick the project's icon set (FR8, FR17): the set `experimental.iconSet`+ * names, as `"<set>"` or `"<package>/<set>"`; otherwise the only installed+ * set; otherwise none. A configured name that matches no valid set but an+ * installed set that was withdrawn says so, with why.+ * @param {DiscoveredIconSet[]} sets installed sets, in integration load order+ * @param {string | undefined} configured the `experimental.iconSet` config value+ * @param {WithdrawnIconSet[]} [withdrawn] installed sets that were withdrawn+ * @returns {IconSetChoice}+ */+export function chooseProjectIconSet(sets, configured, withdrawn = []) {+ if (configured) {+ const exact = sets.filter(+ set => `${set.package}/${set.name}` === configured,+ );+ const byName =+ exact.length > 0 ? exact : sets.filter(set => set.name === configured);+ if (byName.length === 1) {+ return {+ status: 'selected',+ set: byName[0],+ configured,+ reason: `experimental.iconSet names "${configured}".`,+ };+ }+ if (byName.length > 1) {+ return {+ status: 'ambiguous',+ configured,+ reason: `experimental.iconSet "${configured}" names a set in ${byName.map(set => set.package).join(' and ')}; write it as "<package>/<set>".`,+ };+ }+ const gone = withdrawnNamed(withdrawn, configured);+ if (gone.length > 0) {+ return {+ status: 'withdrawn',+ configured,+ reason: `experimental.iconSet names "${configured}", which is installed but withdrawn: ${gone.map(each => each.reason).join(' ')}`,+ };+ }+ return {+ status: 'missing',+ configured,+ reason: `experimental.iconSet names "${configured}", but no installed set has that name${sets.length > 0 ? ` (installed: ${sets.map(iconSetKey).join(', ')})` : ''}.`,+ };+ }+ if (sets.length === 1) {+ return {+ status: 'selected',+ set: sets[0],+ reason: `"${iconSetKey(sets[0])}" is the only installed icon set.`,+ };+ }+ if (sets.length === 0) {+ return {status: 'none', reason: 'No icon set is installed.'};+ }+ return {+ status: 'ambiguous',+ reason: `${sets.length} icon sets are installed (${sets.map(iconSetKey).join(', ')}) and astryx.config sets no experimental.iconSet.`,+ };+}++/**+ * A set's full name, `<package>/<set>`.+ * @param {{package: string, name: string}} set+ */+export function iconSetKey(set) {+ return `${set.package}/${set.name}`;+}++/**+ * Sets in tie order (FR6, FR8): the project's set first, then load order.+ * @param {DiscoveredIconSet[]} sets+ * @param {IconSetChoice} choice+ * @returns {DiscoveredIconSet[]}+ */+export function orderIconSets(sets, choice) {+ const first = choice.set;+ if (!first) return [...sets];+ return [first, ...sets.filter(set => set !== first)];+}diff --git a/packages/cli/foundation/discovery/icon-set-discovery.test.mjs b/packages/cli/foundation/discovery/icon-set-discovery.test.mjsnew file mode 100644index 0000000000..c86b70e7d2--- /dev/null+++ b/packages/cli/foundation/discovery/icon-set-discovery.test.mjs@@ -0,0 +1,320 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Icon-set discovery and the project's icon-set choice (AST-084 FR1–FR5,+ * FR8, FR17), over the synthetic fixture package.+ */++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 {Project} from '../config/project.mjs';+import {+ chooseProjectIconSet,+ discoverIconSetDirectory,+ resolveIconModule,+ splitSpecifier,+} from './icon-set-discovery.mjs';+import {+ definitionSource,+ glyphsData,+ writeIconPackage,+ writeIconSetProject,+} from '../../test-utils/icon-set-fixture.mjs';++/** @type {string} */+let tmp;+beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-icon-sets-'));+});+afterEach(() => {+ fs.rmSync(tmp, {recursive: true, force: true});+});++/** @param {Parameters<typeof writeIconSetProject>[1]} [options] */+async function iconSetsOf(options) {+ const project = await Project.load(writeIconSetProject(tmp, options), {+ fresh: true,+ });+ return {+ state: await project.iconSets({experimental: true}),+ issues: await project.issues(),+ };+}++describe('discoverIconSetDirectory', () => {+ it('reads one valid set: descriptor, data, and notices', () => {+ const dir = path.join(tmp, 'pkg');+ writeIconPackage(dir);+ const {sets, errors} = discoverIconSetDirectory(+ path.join(dir, 'icon-sets'),+ '@acme/glyphs',+ );+ expect(errors).toEqual([]);+ expect(sets).toHaveLength(1);+ expect(sets[0]).toMatchObject({+ name: 'glyphs',+ license: 'MIT',+ package: '@acme/glyphs',+ notices: ['LICENSE'],+ });+ expect(sets[0].data.icons.map(icon => icon.id)).toEqual([+ 'x',+ 'search',+ 'trash',+ 'home',+ ]);+ });++ it("keeps a set valid whose own definition is marked stability: 'experimental'", () => {+ const dir = path.join(tmp, 'pkg');+ writeIconPackage(dir, {+ definitions: {+ rotate: definitionSource('rotate').replace(+ '"type": "icon-definition",',+ '"type": "icon-definition",\n "stability": "experimental",',+ ),+ },+ data: {+ ...glyphsData(),+ module: '@acme/glyphs',+ map: {...glyphsData().map, rotate: 'x'},+ },+ });+ const {sets, errors} = discoverIconSetDirectory(+ path.join(dir, 'icon-sets'),+ '@acme/glyphs',+ );+ expect(errors).toEqual([]);+ expect(sets.map(set => set.name)).toEqual(['glyphs']);+ expect(sets[0].definitions?.map(each => each.doc ?? each)).toContainEqual(+ expect.objectContaining({name: 'rotate', stability: 'experimental'}),+ );+ });++ it.each([+ ['no descriptor', {docSource: null}, /has no descriptor/],+ ['no data file', {data: null}, /has no data file/],+ [+ 'a misnamed descriptor',+ {doc: {name: 'other'}},+ /must equal its directory name/,+ ],+ [+ 'a descriptor that runs code',+ {docSource: "import fs from 'node:fs';\nexport default {};\n"},+ /must contain only/,+ ],+ [+ 'an untyped descriptor',+ {docSource: 'export default {type: "icon-set"};\n'},+ /must declare its public IconSetDoc type/,+ ],+ ['data that is not JSON', {data: '{nope'}, /not valid JSON/],+ [+ 'data with schemaVersion 2',+ {data: {...glyphsData(), schemaVersion: 2}},+ /schemaVersion/,+ ],+ ])(+ 'reports a set with %s, without hiding siblings',+ (_label, spec, message) => {+ const dir = path.join(tmp, 'pkg');+ writeIconPackage(dir, /** @type {any} */ (spec));+ // A second, valid set beside the broken one.+ const sibling = path.join(dir, 'icon-sets', 'extra');+ fs.mkdirSync(sibling, {recursive: true});+ fs.writeFileSync(+ path.join(sibling, 'extra.doc.mjs'),+ "/** @type {import('@astryxdesign/cli/authoring').IconSetDoc} */\nexport default {type: 'icon-set', name: 'extra', displayName: 'Extra', description: '', maintained: true, license: 'MIT'};\n",+ );+ fs.writeFileSync(+ path.join(sibling, 'extra.icons.json'),+ JSON.stringify({...glyphsData(), module: '@acme/glyphs'}),+ );+ const {sets, errors} = discoverIconSetDirectory(+ path.join(dir, 'icon-sets'),+ '@acme/glyphs',+ );+ expect(sets.map(set => set.name)).toEqual(['extra']);+ expect(errors).toHaveLength(1);+ expect(errors[0].message).toMatch(message);+ },+ );++ it('never executes the icon module', () => {+ const dir = path.join(tmp, 'pkg');+ writeIconPackage(dir, {+ modules: {+ 'index.js': "throw new Error('executed');\nexport const XIcon = 1;\n",+ },+ });+ const {sets} = discoverIconSetDirectory(+ path.join(dir, 'icon-sets'),+ '@acme/glyphs',+ );+ expect(sets).toHaveLength(1);+ });++ it('ignores dot folders and non-kebab folders', () => {+ const dir = path.join(tmp, 'pkg');+ writeIconPackage(dir);+ fs.mkdirSync(path.join(dir, 'icon-sets', '.cache'));+ fs.mkdirSync(path.join(dir, 'icon-sets', 'Draft'));+ const {sets, errors} = discoverIconSetDirectory(+ path.join(dir, 'icon-sets'),+ '@acme/glyphs',+ );+ expect(sets.map(set => set.name)).toEqual(['glyphs']);+ expect(errors).toEqual([]);+ });+});++describe('resolveIconModule', () => {+ it('splits scoped and unscoped specifiers', () => {+ expect(splitSpecifier('@acme/glyphs/solid')).toEqual({+ name: '@acme/glyphs',+ subpath: './solid',+ });+ expect(splitSpecifier('glyphs')).toEqual({name: 'glyphs', subpath: '.'});+ });++ it('resolves through node_modules and the exports map, and refuses an unexported subpath', () => {+ const project = writeIconSetProject(tmp);+ expect(resolveIconModule('@acme/glyphs', project)).toBe(+ path.join(project, 'node_modules', '@acme', 'glyphs', 'index.js'),+ );+ expect(resolveIconModule('@acme/glyphs/icons/x.js', project)).toBeNull();+ expect(resolveIconModule('@acme/missing', project)).toBeNull();+ });+});++describe('Project.iconSets', () => {+ it('reads no set, and records no issue, without experimental.iconSet unless asked', async () => {+ const project = await Project.load(+ writeIconSetProject(tmp, {packages: [{data: '{nope'}]}),+ {fresh: true},+ );+ expect((await project.iconSets()).sets).toEqual([]);+ expect(await project.issues()).toEqual([]);+ });++ it('answers one installed set as the project set', async () => {+ const {state, issues} = await iconSetsOf();+ expect(state.sets.map(set => set.name)).toEqual(['glyphs']);+ expect(state.choice.status).toBe('selected');+ expect(state.withdrawn).toEqual([]);+ expect(issues).toEqual([]);+ });++ it('withdraws a set whose data is invalid, and reports it', async () => {+ const {state, issues} = await iconSetsOf({+ packages: [+ {+ data: {+ ...glyphsData(),+ module: '@acme/glyphs',+ icons: [{id: 'x', export: 'XIcon', words: []}],+ },+ },+ ],+ });+ expect(state.sets).toEqual([]);+ expect(state.withdrawn).toEqual([+ expect.objectContaining({name: 'glyphs', kind: 'invalid'}),+ ]);+ expect(issues).toEqual([+ expect.objectContaining({+ code: 'invalid_icon_set',+ package: '@acme/glyphs',+ }),+ ]);+ expect(state.choice.status).toBe('none');+ });++ it('withdraws a set whose module does not resolve from the project', async () => {+ const {state} = await iconSetsOf({+ packages: [{data: {...glyphsData(), module: '@acme/not-installed'}}],+ });+ expect(state.sets).toEqual([]);+ expect(state.withdrawn[0]).toMatchObject({kind: 'unresolved'});+ expect(state.withdrawn[0].reason).toMatch(+ /does not resolve from the project/,+ );+ });++ it('two sets and no iconSet: ambiguous, never one picked silently', async () => {+ const {state} = await iconSetsOf({+ packages: [{}, {name: '@acme/lines'}],+ });+ expect(state.sets.map(set => set.name)).toEqual(['glyphs', 'lines']);+ expect(state.choice.status).toBe('ambiguous');+ expect(state.choice.set).toBeUndefined();+ });++ it('two sets with iconSet: that set first, by name or <package>/<set>', async () => {+ for (const iconSet of ['lines', '@acme/lines/lines']) {+ fs.rmSync(tmp, {recursive: true, force: true});+ fs.mkdirSync(tmp);+ const {state} = await iconSetsOf({+ packages: [{}, {name: '@acme/lines'}],+ config: {experimental: {iconSet}},+ });+ expect(state.choice.status).toBe('selected');+ expect(state.sets.map(set => set.name)).toEqual(['lines', 'glyphs']);+ }+ });++ it('iconSet naming an installed set that was withdrawn is withdrawn, with why', async () => {+ const {state} = await iconSetsOf({+ packages: [{data: {...glyphsData(), module: '@acme/not-installed'}}],+ config: {experimental: {iconSet: 'glyphs'}},+ });+ expect(state.choice.status).toBe('withdrawn');+ expect(state.choice.reason).toMatch(+ /names "glyphs", which is installed but withdrawn: .*does not resolve/,+ );+ });++ it('iconSet naming a set that is not installed is missing', async () => {+ const {state} = await iconSetsOf({+ config: {experimental: {iconSet: 'nope'}},+ });+ expect(state.choice.status).toBe('missing');+ expect(state.choice.reason).toMatch(/no installed set has that name/);+ });+});++describe('chooseProjectIconSet', () => {+ it('no sets: none', () => {+ expect(chooseProjectIconSet([], undefined).status).toBe('none');+ });++ it('a set name two packages share is ambiguous', () => {+ const a = /** @type {any} */ ({name: 'outline', package: '@acme/a'});+ const b = /** @type {any} */ ({name: 'outline', package: '@acme/b'});+ expect(chooseProjectIconSet([a, b], 'outline').status).toBe('ambiguous');+ expect(chooseProjectIconSet([a, b], '@acme/b/outline').set).toBe(b);+ });++ it('a configured name only a withdrawn set has is withdrawn; a valid set wins over it', () => {+ const gone = /** @type {any} */ ({+ name: 'outline',+ package: '@acme/a',+ kind: 'invalid',+ reason: 'its data is not valid JSON.',+ });+ const valid = /** @type {any} */ ({name: 'outline', package: '@acme/b'});+ expect(chooseProjectIconSet([], 'outline', [gone])).toMatchObject({+ status: 'withdrawn',+ reason:+ 'experimental.iconSet names "outline", which is installed but withdrawn: its data is not valid JSON.',+ });+ expect(chooseProjectIconSet([], '@acme/a/outline', [gone]).status).toBe(+ 'withdrawn',+ );+ expect(chooseProjectIconSet([], 'other', [gone]).status).toBe('missing');+ expect(chooseProjectIconSet([valid], 'outline', [gone]).set).toBe(valid);+ });+});diff --git a/packages/cli/foundation/discovery/icon-set-writer.mjs b/packages/cli/foundation/discovery/icon-set-writer.mjsnew file mode 100644index 0000000000..de38e94e8a--- /dev/null+++ b/packages/cli/foundation/discovery/icon-set-writer.mjs@@ -0,0 +1,1181 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Icon-set authoring (AST-084): find the icon set being authored, read+ * a source module's exports statically, and rewrite the set's data file.+ *+ * Shared by `astryx experimental icon map`, `astryx experimental icon add`, and the icon-set kinds of+ * `astryx integration add`. Nothing here executes package code: exports are+ * read with the static module reader. A rewritten data file is checked the+ * way discovery checks it (the data parser, then every `map` key against+ * Astryx's definitions and the set's own) before it replaces the old one, and+ * it is written in one fixed shape, so the same edits give the same bytes.+ *+ * Errors carry a `code` (an ERR_* code) and `suggestions`, which the api+ * leaves turn into typed CLI errors.+ *+ * @input The directory the command runs in, and a set name when the package+ * ships more than one+ * @output The set, its source module's icons, and data-file writes+ * @position packages/cli/foundation/discovery — read by api/icon and+ * api/integration+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {randomUUID} from 'node:crypto';+import {parse} from '@babel/parser';+import {parseIconSetData} from '../../authoring/doctypes/icon-set/parse.mjs';+import {ICON_NAMES} from '../../authoring/doctypes/icon-set/icon-names.mjs';+import {assertWithin} from '../fs/path-safety.mjs';+import {findLocalIntegrationManifestOrNull} from '../integrations/manifest-writer.mjs';+import {loadManifestObject} from '../integrations/integrations.mjs';+import {levenshteinDistance} from '../text/string-utils.mjs';+import {astryxDefinitionsByName} from './icon-definition-discovery.mjs';+import {+ discoverIconSetDirectory,+ resolveIconModule,+} from './icon-set-discovery.mjs';+import {+ exportScalarType,+ exportValueKind,+ followedExportNames,+ moduleExportOrigin,+} from './module-exports.mjs';++/** @typedef {import('./icon-set-discovery.mjs').DiscoveredIconSet} DiscoveredIconSet */+/** @typedef {import('../../authoring/doctypes/icon-set/type').IconSetData} IconSetData */++/**+ * An authoring error with an ERR_* code and suggestions.+ */+export class IconSetAuthoringError extends Error {+ /**+ * @param {string} message+ * @param {string} code+ * @param {Array<{name: string, reason: string}>} [suggestions]+ */+ constructor(message, code, suggestions = []) {+ super(message);+ this.code = code;+ this.suggestions = suggestions;+ }+}++/**+ * `XMarkIcon` → `x-mark`; `Trash2` → `trash-2`; `ArrowUpDown` →+ * `arrow-up-down`: an icon id from an export name.+ * @param {string} name+ */+export function iconIdOf(name) {+ return name+ .replace(/Icon$/u, '')+ .replace(/([a-z])([A-Z0-9])/gu, '$1-$2')+ .replace(/([0-9])([A-Z])/gu, '$1-$2')+ .replace(/([A-Z])([A-Z][a-z])/gu, '$1-$2')+ .toLowerCase();+}++/**+ * The name an icon set exports an icon as: PascalCase ending in `Icon`+ * (`Trash2` → `Trash2Icon`; `TrashIcon` stays).+ * @param {string} name+ */+export function iconExportName(name) {+ const pascal = name[0].toUpperCase() + name.slice(1);+ return pascal.endsWith('Icon') ? pascal : `${pascal}Icon`;+}++/**+ * The name an icon set exports a variant as: the icon's name, then the+ * variant's name, then `Icon` (`TrashIcon` solid → `TrashSolidIcon`).+ * @param {string} iconName the icon's own export+ * @param {string} variant one of the set's declared variants+ */+export function variantExportName(iconName, variant) {+ const base = iconName.replace(/Icon$/u, '');+ const name = variant+ .split('-')+ .map(part => (part ? part[0].toUpperCase() + part.slice(1) : ''))+ .join('');+ return `${base}${name}Icon`;+}++/**+ * The nearest directory at or above `cwd` with a package.json.+ * @param {string} cwd+ */+function packageDirOf(cwd) {+ let dir = path.resolve(cwd);+ for (let depth = 0; depth < 50; depth++) {+ if (fs.existsSync(path.join(dir, 'package.json'))) return dir;+ const parent = path.dirname(dir);+ if (parent === dir) break;+ dir = parent;+ }+ throw new IconSetAuthoringError(+ 'No package.json found. Run this command inside the icon-set package.',+ 'ERR_FILE_NOT_FOUND',+ );+}++/**+ * The icon-set package the command runs in, and the set it edits: the one+ * `selector` names, else the only set.+ * @param {string} cwd+ * @param {string} [selector] a set name+ * @returns {Promise<{packageDir: string, pkg: Record<string, any>, root: string, set: DiscoveredIconSet, sets: DiscoveredIconSet[]}>}+ */+export async function findLocalIconSet(cwd, selector) {+ const packageDir = packageDirOf(cwd);+ /** @type {Record<string, any>} */+ let pkg;+ try {+ pkg = JSON.parse(+ fs.readFileSync(path.join(packageDir, 'package.json'), 'utf-8'),+ );+ } catch (error) {+ throw new IconSetAuthoringError(+ `Cannot read package.json: ${error instanceof Error ? error.message : String(error)}`,+ 'ERR_INVALID_ARGUMENT',+ );+ }+ const manifestFile = findLocalIntegrationManifestOrNull(packageDir);+ const manifest = manifestFile+ ? await loadManifestObject(manifestFile, 'Integration manifest', {+ fresh: true,+ })+ : {};+ const declared = manifest.experimental?.iconSets;+ if (!declared) {+ throw new IconSetAuthoringError(+ 'This package ships no icon set. Add one first.',+ 'ERR_NOT_FOUND',+ [+ {+ name: 'astryx experimental icon new-set <name>',+ reason: 'add an icon set',+ },+ ],+ );+ }+ const root = assertWithin(declared, packageDir, {+ label: 'experimental.iconSets root',+ });+ const owner = typeof pkg.name === 'string' ? pkg.name : '(local integration)';+ const found = discoverIconSetDirectory(root, owner);+ const named = selector+ ? found.sets.filter(set => set.name === selector)+ : found.sets;+ if (named.length === 1) {+ return {+ packageDir,+ pkg,+ root,+ set: {...named[0], packageDir},+ sets: found.sets,+ };+ }+ const broken = selector+ ? found.errors.find(error => error.name === selector)+ : null;+ if (broken) {+ throw new IconSetAuthoringError(broken.message, 'ERR_INVALID_ARGUMENT');+ }+ const names = found.sets.map(set => set.name);+ if (named.length === 0 && selector) {+ throw new IconSetAuthoringError(+ `This package has no icon set "${selector}".`,+ 'ERR_NOT_FOUND',+ names.map(name => ({name, reason: 'an icon set in this package'})),+ );+ }+ throw new IconSetAuthoringError(+ names.length === 0+ ? `This package has no valid icon set${found.errors.length > 0 ? `: ${found.errors[0].message}` : '.'}`+ : `This package has ${names.length} icon sets; name one with --set.`,+ names.length === 0 ? 'ERR_NOT_FOUND' : 'ERR_INVALID_ARGUMENT',+ names.map(name => ({+ name: `--set ${name}`,+ reason: 'an icon set in this package',+ })),+ );+}++/** The data file's fields, in the order the file is written. */+const DATA_KEYS = [+ 'schemaVersion',+ 'module',+ 'source',+ 'generated',+ 'adapter',+ 'variants',+ 'default',+ 'themeMap',+ 'map',+ 'icons',+];++/**+ * A data file's text, in one fixed shape: fields in schema order, `map` keys+ * sorted, two-space JSON, a final newline.+ * @param {IconSetData} data+ */+export function iconSetDataText(data) {+ /** @type {Record<string, unknown>} */+ const ordered = {};+ for (const key of DATA_KEYS) {+ const value = /** @type {Record<string, unknown>} */ (+ /** @type {unknown} */ (data)+ )[key];+ if (value === undefined) continue;+ ordered[key] =+ key === 'map'+ ? Object.fromEntries(+ Object.entries(/** @type {Record<string, string>} */ (value)).sort(+ ([a], [b]) => (a < b ? -1 : a > b ? 1 : 0),+ ),+ )+ : value;+ }+ for (const [key, value] of Object.entries(data)) {+ if (!DATA_KEYS.includes(key)) ordered[key] = value;+ }+ return `${JSON.stringify(ordered, null, 2)}\n`;+}++/**+ * The icon definitions a set may map: Astryx's and its own, by name.+ * @param {DiscoveredIconSet} set+ * @param {string[]} [extra] definition names about to be added+ */+export function mappableDefinitions(set, extra = []) {+ return new Set([+ ...astryxDefinitionsByName().keys(),+ ...set.definitions.map(each => each.doc.name),+ ...extra,+ ]);+}++/**+ * Check a set's next data the way discovery will, then write it in place.+ * Returns a function that puts the old file back.+ * @param {DiscoveredIconSet} set+ * @param {IconSetData} next+ * @param {{extraDefinitions?: string[]}} [options] definitions written in+ * the same command, which count as declared+ * @returns {() => void}+ */+export function writeIconSetData(set, next, {extraDefinitions = []} = {}) {+ const label = `Icon set "${set.name}"`;+ let parsed;+ try {+ parsed = parseIconSetData(next, `${label} data file`);+ } catch (error) {+ throw new IconSetAuthoringError(+ error instanceof Error ? error.message : String(error),+ 'ERR_INVALID_ARGUMENT',+ );+ }+ const known = mappableDefinitions(set, extraDefinitions);+ for (const name of Object.keys(parsed.map ?? {})) {+ if (!known.has(name)) {+ throw new IconSetAuthoringError(+ `"${name}" is not an icon definition. Use an Astryx icon definition (astryx docs cli/experimental/icon-definitions), or add your own.`,+ 'ERR_INVALID_ARGUMENT',+ [+ ...closestNames(name, [...known]).map(each => ({+ name: each,+ reason: 'a known icon definition',+ })),+ {+ name: `astryx experimental icon new-definition ${name} --set ${set.name}`,+ reason: 'add it as your own definition',+ },+ ],+ );+ }+ }+ const text = iconSetDataText(next);+ const before = fs.readFileSync(set.dataPath);+ replaceText(set.dataPath, text);+ return () => {+ if (fs.readFileSync(set.dataPath, 'utf-8') === text) {+ replaceText(set.dataPath, before.toString('utf-8'));+ }+ };+}++/**+ * Replace a file's text atomically.+ * @param {string} file+ * @param {string} text+ */+function replaceText(file, text) {+ const temporary = path.join(+ path.dirname(file),+ `.${path.basename(file)}.tmp-${randomUUID()}`,+ );+ try {+ fs.writeFileSync(temporary, text, 'utf-8');+ fs.renameSync(temporary, file);+ } catch (error) {+ fs.rmSync(temporary, {force: true});+ throw new IconSetAuthoringError(+ `Could not write ${path.basename(file)}: ${error instanceof Error ? error.message : String(error)}`,+ 'ERR_WRITE_FAILED',+ );+ }+}++/**+ * The names closest to one that matched nothing.+ * @param {string} wanted+ * @param {string[]} candidates+ * @param {number} [max]+ */+export function closestNames(wanted, candidates, max = 5) {+ const lower = wanted.toLowerCase();+ return [...new Set(candidates)]+ .map(name => ({+ name,+ distance: levenshteinDistance(lower, name.toLowerCase()),+ }))+ .filter(each => each.distance <= Math.max(2, Math.ceil(lower.length / 3)))+ .sort((a, b) => a.distance - b.distance || (a.name < b.name ? -1 : 1))+ .slice(0, max)+ .map(each => each.name);+}++/**+ * A source module an icon is read from: the file it resolves to, and the+ * specifier to import it by. A package or a package subpath resolves from the+ * set's package (its `exports` map honored) and is imported by that+ * specifier. A relative path inside the set's package is imported by its+ * path (`module` is then the path from the package root).+ * @param {string} from+ * @param {{packageDir: string, pkg: Record<string, any>}} where+ * @returns {{file: string, module: string}}+ */+export function resolveIconSource(from, {packageDir, pkg}) {+ const name = typeof pkg.name === 'string' ? pkg.name : '';+ if (from.startsWith('.') || path.isAbsolute(from)) {+ const target = assertWithin(from, packageDir, {+ label: 'icon source',+ allowAbsolute: true,+ });+ const file = resolveFile(target);+ if (!file) {+ throw new IconSetAuthoringError(+ `"${from}" does not resolve to a module file in this package.`,+ 'ERR_FILE_NOT_FOUND',+ );+ }+ return {+ file,+ module: `./${path.relative(packageDir, file).split(path.sep).join('/')}`,+ };+ }+ const file = resolveIconModule(from, packageDir, {name, dir: packageDir});+ if (!file) {+ throw new IconSetAuthoringError(+ `"${from}" does not resolve from ${name || 'this package'}. Install it as a dependency, or check the specifier.`,+ 'ERR_NOT_FOUND',+ );+ }+ return {file, module: from};+}++/** @param {string} base */+function resolveFile(base) {+ const extensions = ['', '.mjs', '.js', '.cjs', '.ts', '.tsx', '.jsx', '.mts'];+ for (const candidate of [+ ...extensions.map(extension => `${base}${extension}`),+ ...extensions+ .slice(1)+ .map(extension => path.join(base, `index${extension}`)),+ ]) {+ try {+ if (fs.statSync(candidate).isFile()) return candidate;+ } catch {+ // Try the next candidate.+ }+ }+ return null;+}++/**+ * Prove a source module has one export, without running it. `default` reads+ * the module's default export.+ * @param {string} file+ * @param {string} module the specifier, for messages+ * @param {string} exportName+ */+export function assertIconExport(file, module, exportName) {+ if (!moduleExportOrigin(file, exportName)) {+ const names = followedExportNames(file);+ throw new IconSetAuthoringError(+ exportName === 'default'+ ? `"${module}" has no default export.`+ : `"${module}" does not export "${exportName}".`,+ 'ERR_NOT_FOUND',+ closestNames(exportName, names).map(name => ({+ name,+ reason: `an export of ${module}`,+ })),+ );+ }+}++/** A SCREAMING_CASE name: two or more capitals, digits, or underscores. */+const SCREAMING_CASE_RE = /^[A-Z][A-Z0-9_]+$/u;++/**+ * The library exports that can be icons: PascalCase components and, when the+ * set declares an adapter, also data exports, camelCase included: objects,+ * and plain strings only in a library whose candidates are all strings.+ * Left out: `default`, `Icon`, SCREAMING_CASE constants, number and boolean+ * exports, and `exclude`.+ * @param {string} file+ * @param {{adapter?: boolean, exclude?: string[]}} [options] `exclude`: export+ * names that are not icons+ * @returns {Array<{name: string, adapt: boolean, scalar: string | null}>}+ */+function iconCandidates(file, {adapter = false, exclude = []} = {}) {+ const skipped = new Set(exclude);+ /** @type {Array<{name: string, adapt: boolean, scalar: string | null}>} */+ const out = [];+ for (const name of followedExportNames(file)) {+ if (name === 'default' || name === 'Icon' || skipped.has(name)) continue;+ // SCREAMING_CASE names are constants (`README`, `VERSION`), not icons.+ if (SCREAMING_CASE_RE.test(name)) continue;+ const kind = exportValueKind(file, name);+ if (kind === 'component' && /^[A-Z][A-Za-z0-9]*$/u.test(name)) {+ out.push({name, adapt: false, scalar: null});+ } else if (+ adapter &&+ kind === 'data' &&+ /^[A-Za-z][A-Za-z0-9]*$/u.test(name)+ ) {+ const scalar = exportScalarType(file, name);+ // A number or a boolean draws nothing; a string may be SVG markup.+ if (scalar === 'number' || scalar === 'boolean') continue;+ out.push({name, adapt: true, scalar});+ }+ }+ // A plain string is an icon only in a library of strings (SVG markup); next+ // to components or icon objects it is a stray constant.+ return out.some(each => each.scalar == null)+ ? out.filter(each => each.scalar == null)+ : out;+}++/**+ * The names the library prefix is computed over: the icon-like candidates+ * (stray constants are already left out by {@link iconCandidates}).+ * @param {Array<{name: string, scalar: string | null}>} candidates+ * @returns {string[]}+ */+function prefixNames(candidates) {+ return candidates.map(each => each.name);+}++/**+ * The leading words every icon export of a library shares, such as+ * `feather` in `featherEye` and `featherSun`: a library prefix that ids and+ * the set's export names leave out. Empty when fewer than two exports share+ * one, or when it would leave an export with no name.+ * @param {string[]} names+ * @returns {string[]}+ */+export function libraryPrefix(names) {+ if (names.length < 2) return [];+ const split = names.map(name => iconIdOf(name).split('-'));+ /** @type {string[]} */+ const prefix = [];+ for (let index = 0; ; index++) {+ const word = split[0][index];+ if (+ word == null ||+ !split.every(words => words[index] === word && words.length > index + 1)+ ) {+ break;+ }+ prefix.push(word);+ }+ return prefix;+}++/**+ * An export's id and the name the set exports it as, with the library prefix+ * left out: `featherEye` with prefix `feather` is id `eye`, `EyeIcon`.+ * @param {string} name+ * @param {string[]} prefix+ * @returns {{id: string, name: string}}+ */+export function iconNaming(name, prefix) {+ const all = iconIdOf(name).split('-');+ // Only a name that starts with the prefix, and has more after it, loses it.+ const strip =+ all.length > prefix.length &&+ prefix.every((word, index) => all[index] === word);+ if (!strip) prefix = [];+ const words = all.slice(prefix.length);+ const id = words.join('-');+ const pascal = words+ .map(word => word[0].toUpperCase() + word.slice(1))+ .join('');+ return {+ id,+ name: prefix.length > 0 ? iconExportName(pascal) : iconExportName(name),+ };+}++/**+ * The library prefix of the module an icon is read from+ * ({@link libraryPrefix} over its icon exports).+ * @param {string} file+ * @param {{adapter?: boolean, exclude?: string[]}} [options]+ */+export function modulePrefix(file, options) {+ return libraryPrefix(prefixNames(iconCandidates(file, options)));+}++/**+ * Every icon a whole library exports, for wrapping it at once: one entry per+ * component (and, with an adapter, per data export), read by its `…Icon`+ * export when it has one (an alias of the same value is recorded once), with+ * its id and the name the set exports it as from the name, the library+ * prefix left out ({@link libraryPrefix}).+ * @param {string} file+ * @param {{adapter?: boolean, exclude?: string[]}} [options] `adapter`:+ * whether the set declares one; `exclude`: export names that are not icons+ * @returns {Array<{export: string, id: string, name: string, adapt: boolean}>}+ */+export function libraryIcons(file, options = {}) {+ const candidates = iconCandidates(file, options);+ /** @type {Map<string, {names: string[], adapt: boolean, scalar: string | null}>} */+ const byOrigin = new Map();+ for (const {name, adapt, scalar} of candidates) {+ const origin = moduleExportOrigin(file, name);+ if (!origin) continue;+ const key = `${origin.file}\0${origin.name}`;+ const entry = byOrigin.get(key) ?? {names: [], adapt, scalar};+ entry.names.push(name);+ byOrigin.set(key, entry);+ }+ /** @type {Array<[string, string, boolean, string | null]>} */+ const chosen = [];+ for (const [key, {names, adapt, scalar}] of byOrigin) {+ const local = key.split('\0')[1];+ const withIcon = names.filter(name => name.endsWith('Icon'));+ const preferred =+ withIcon.find(name => name === `${local}Icon`) ??+ names.find(name => name === local) ??+ [...(withIcon.length > 0 ? withIcon : names)].sort(+ (a, b) => a.length - b.length || (a < b ? -1 : 1),+ )[0];+ chosen.push([key, preferred, adapt, scalar]);+ }+ const prefix = libraryPrefix(+ prefixNames(chosen.map(([, name, , scalar]) => ({name, scalar}))),+ );+ /** @type {Map<string, {export: string, id: string, name: string, adapt: boolean}>} */+ const byId = new Map();+ for (const [, preferred, adapt] of chosen) {+ const naming = iconNaming(preferred, prefix);+ if (!naming.id || byId.has(naming.id)) continue;+ byId.set(naming.id, {export: preferred, ...naming, adapt});+ }+ return [...byId.values()].sort((a, b) =>+ a.id < b.id ? -1 : a.id > b.id ? 1 : 0,+ );+}++/** @param {string} value a single-quoted JavaScript string literal */+function quote(value) {+ return `'${value.replace(/\\/gu, '\\\\').replace(/'/gu, "\\'").replace(/\n/gu, '\\n')}'`;+}++/**+ * The source of one icon definition file, typed IconDefinitionDoc.+ * @param {{name: string, description: string, words: string[]}} doc+ */+export function iconDefinitionSource(doc) {+ return [+ "/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */",+ 'export default {',+ " type: 'icon-definition',",+ ` name: ${quote(doc.name)},`,+ ` description: ${quote(doc.description)},`,+ ` words: [${doc.words.map(quote).join(', ')}],`,+ '};',+ '',+ ].join('\n');+}++/**+ * Check a new icon definition for a set: a camelCase name no Astryx+ * definition has, a description, and at least one lower-case word.+ * @param {DiscoveredIconSet} set+ * @param {{name: string, description?: string, words?: string[]}} doc+ * @returns {{name: string, description: string, words: string[]}}+ */+export function checkNewDefinition(set, doc) {+ if (!/^[a-z][a-zA-Z0-9]*$/u.test(doc.name)) {+ throw new IconSetAuthoringError(+ `Invalid icon definition name "${doc.name}": use camelCase starting with a lower-case letter.`,+ 'ERR_INVALID_ARGUMENT',+ );+ }+ if (astryxDefinitionsByName().has(doc.name)) {+ throw new IconSetAuthoringError(+ `Astryx already has the icon definition "${doc.name}"; map to it instead of adding your own.`,+ 'ERR_INVALID_ARGUMENT',+ [{name: `--definition ${doc.name}`, reason: "use Astryx's definition"}],+ );+ }+ const description = (doc.description ?? '').trim();+ const words = [+ ...new Set(+ (doc.words ?? []).map(word => word.trim().toLowerCase()).filter(Boolean),+ ),+ ];+ if (!description || words.length === 0) {+ throw new IconSetAuthoringError(+ `A new icon definition needs --description and --words: one sentence on what the icon is for, and the words people search for.`,+ 'ERR_MISSING_ARGUMENT',+ );+ }+ return {name: doc.name, description, words};+}++/**+ * The set's definition file for `name`, and whether it exists.+ * @param {DiscoveredIconSet} set+ * @param {string} name+ */+export function definitionFile(set, name) {+ return assertWithin(`definitions/${name}.doc.mjs`, set.dir, {+ label: 'icon definition file',+ });+}++/**+ * Write one new definition file into the set, refusing to overwrite one.+ * Returns a function that removes it again.+ * @param {DiscoveredIconSet} set+ * @param {{name: string, description: string, words: string[]}} doc+ * @returns {() => void}+ */+export function writeDefinitionFile(set, doc) {+ const file = definitionFile(set, doc.name);+ if (fs.existsSync(file)) {+ throw new IconSetAuthoringError(+ `Refusing to overwrite existing file definitions/${doc.name}.doc.mjs.`,+ 'ERR_FILE_EXISTS',+ );+ }+ const text = iconDefinitionSource(doc);+ fs.mkdirSync(path.dirname(file), {recursive: true});+ try {+ fs.writeFileSync(file, text, {encoding: 'utf-8', flag: 'wx'});+ } catch (error) {+ throw new IconSetAuthoringError(+ `Could not write definitions/${doc.name}.doc.mjs: ${error instanceof Error ? error.message : String(error)}`,+ 'ERR_WRITE_FAILED',+ );+ }+ return () => {+ if (fs.existsSync(file) && fs.readFileSync(file, 'utf-8') === text) {+ fs.rmSync(file);+ }+ };+}++/** The comment the generated icons module opens with. */+const GENERATED_HEADER = [+ '// Generated by `astryx experimental icon add`: one export per icon of this set.',+ '// Edit with `astryx experimental icon add`; a statement added by hand is kept.',+];++/**+ * The top-level statements of a generated module, one normalized line each,+ * however the file was formatted: whitespace collapsed, no padding inside+ * braces, no trailing comma. Comments are dropped.+ * @param {string} text+ * @param {string} label the module's path, for the error+ * @returns {string[]}+ */+function generatedStatements(text, label) {+ let ast;+ try {+ ast = parse(text, {sourceType: 'module', plugins: ['jsx', 'typescript']});+ } catch (error) {+ throw new IconSetAuthoringError(+ `The generated icons module ${label} does not parse (${error instanceof Error ? error.message : String(error)}). Fix or delete it, then run the command again.`,+ 'ERR_INVALID_ARGUMENT',+ );+ }+ return ast.program.body.map(node =>+ text+ .slice(+ /** @type {number} */ (node.start),+ /** @type {number} */ (node.end),+ )+ .replace(/\s+/gu, ' ')+ .replace(/\{ /gu, '{')+ .replace(/,? \}/gu, '}')+ .replace(/,\}/gu, '}'),+ );+}++/** The local name the generated module gives the set's adapter. */+const ADAPTER_LOCAL = 'adaptIcon';++/** The theme map the generated module writes. */+export const THEME_MAP_NAME = 'themeIcons';++/** How the generated module imports React for its theme map. */+const REACT_IMPORT = "import {createElement} from 'react';";++/** The built-in icon definitions: the shared names a theme map covers. */+const BUILT_IN = new Set(ICON_NAMES);++/**+ * The generated icons module of a set, from the package root: `generated`+ * in its data file, else `<set directory>/<set>.generated.js`.+ * @param {DiscoveredIconSet} set+ * @param {string} packageDir+ */+export function generatedModulePath(set, packageDir) {+ return (+ set.data.generated ??+ `./${path+ .relative(packageDir, path.join(set.dir, `${set.name}.generated.js`))+ .split(path.sep)+ .join('/')}`+ );+}++/**+ * One icon export of the generated module.+ * @typedef {object} GeneratedIcon+ * @property {string} name the export the set exposes+ * @property {string} from the source module: a specifier, or a ./ path from+ * the package root+ * @property {string} source the source export, or `default`+ * @property {boolean} adapt whether the set's adapter turns it into a+ * component+ */++/** The props every theme-map element gets: sized to its box, hidden from assistive tech. */+const THEME_ELEMENT_PROPS =+ "{'aria-hidden': true, 'width': '1em', 'height': '1em'}";++/**+ * The declaration file beside a generated module (`x.generated.js` →+ * `x.generated.d.ts`, `.mjs` → `.d.mts`); null for a TypeScript module.+ * @param {string} generated+ * @returns {string | null}+ */+export function generatedTypesPath(generated) {+ if (/\.m?tsx?$/u.test(generated)) return null;+ if (generated.endsWith('.mjs')) return generated.replace(/\.mjs$/u, '.d.mts');+ if (generated.endsWith('.cjs')) return generated.replace(/\.cjs$/u, '.d.cts');+ return generated.replace(/\.jsx?$/u, '.d.ts');+}++/**+ * The declaration file's text for a generated module's statements: each+ * re-export as written, so a component keeps its library's types; each+ * adapted icon as a component that takes SVG props; and the theme map.+ * @param {string[]} statements the module's normalized statements+ * @returns {string}+ */+export function generatedTypesText(statements) {+ /** @type {string[]} */+ const lines = [];+ const react = new Set();+ for (const statement of statements) {+ if (statement.startsWith('import ')) continue;+ if (/^export (?:\*|\{[^}]*\}) from /u.test(statement)) {+ lines.push(statement);+ continue;+ }+ const adapted = new RegExp(+ `^export const (\\w+) = ${ADAPTER_LOCAL}\\(`,+ 'u',+ ).exec(statement);+ if (adapted) {+ react.add('ComponentType').add('SVGProps');+ lines.push(+ `export declare const ${adapted[1]}: ComponentType<SVGProps<SVGSVGElement>>;`,+ );+ continue;+ }+ const theme = /^export const (\w+) = \{(.*)\};$/u.exec(statement);+ if (+ theme &&+ (theme[1] === THEME_MAP_NAME || statement.includes('createElement('))+ ) {+ react.add('ReactElement');+ const keys = [...theme[2].matchAll(/(\w+): createElement\(/gu)].map(+ match => match[1],+ );+ lines.push(+ `export declare const ${theme[1]}: {${keys.map(key => `readonly ${key}: ReactElement`).join('; ')}};`,+ );+ }+ }+ return [+ ...GENERATED_HEADER,+ ...(react.size > 0+ ? [`import type {${[...react].sort().join(', ')}} from 'react';`]+ : []),+ ...lines,+ '',+ ].join('\n');+}++/**+ * The generated module's statements, normalized, from its text.+ * @param {string} text+ * @param {string} label+ */+export function readGeneratedStatements(text, label) {+ return generatedStatements(text, label);+}++/**+ * The generated module and its declaration file after adding icons: every+ * statement it already has is kept; each new icon is a re-export of a+ * component or the adapter applied to anything else; the adapter is imported+ * once when an export needs it; and, when the data names `themeIcons` as its+ * theme map, `themeIcons` is rewritten from the built-in entries of `map`.+ * An export the module already has with another source is refused.+ * @param {string} packageDir+ * @param {string} generated the module's ./ path from the package root+ * @param {string | null} before the module's current text+ * @param {import('../../authoring/doctypes/icon-set/type').IconSetData} data+ * the data file as it will be written+ * @param {GeneratedIcon[]} icons+ * @param {string[]} [remove] export names to drop, with the import an+ * adapted one reads: the icons a refreshed library no longer has+ * @returns {{js: string, dts: string | null}}+ */+export function generatedModuleText(+ packageDir,+ generated,+ before,+ data,+ icons,+ remove = [],+) {+ const file = path.join(packageDir, generated);+ const fileDir = path.dirname(file);+ /** @param {string} from */+ const specifierOf = from => {+ if (!from.startsWith('./')) return from;+ const relative = path+ .relative(fileDir, path.join(packageDir, from))+ .split(path.sep)+ .join('/');+ return relative.startsWith('.') ? relative : `./${relative}`;+ };+ const themeName = data.themeMap === THEME_MAP_NAME ? THEME_MAP_NAME : null;+ const lines = before == null ? [] : generatedStatements(before, generated);+ // Written once, below: the adapter's import, React's createElement, and+ // the theme map.+ const adapterImport = new RegExp(`\\bas ${ADAPTER_LOCAL}\\b`, 'u');+ const dropped = [...new Set(remove)].map(+ name =>+ new RegExp(+ `(?:\\bas ${name}(?:Source)?\\}|^export const ${name} = |^export \\{${name}\\} |^import ${name}Source )`,+ 'u',+ ),+ );+ // A re-export binds no local name, so the theme map reads each re-exported+ // icon through an import that mirrors its re-export. Those imports are+ // rewritten with the theme map.+ const themeImport = (/** @type {string} */ line) =>+ themeName != null &&+ line.startsWith('import {') &&+ lines.includes(`export${line.slice('import'.length)}`);+ const managed = (/** @type {string} */ line) =>+ dropped.some(pattern => pattern.test(line)) ||+ adapterImport.test(line) ||+ line === REACT_IMPORT ||+ themeImport(line) ||+ (themeName != null && line.startsWith(`export const ${themeName} = `));+ const imports = new Set(+ lines.filter(line => line.startsWith('import ') && !managed(line)),+ );+ const exports = new Set(+ lines.filter(line => !line.startsWith('import ') && !managed(line)),+ );+ /** @param {string} name */+ const existing = name =>+ [...exports].find(line =>+ new RegExp(+ `(?:\\b(?:as\\s+|export\\s+\\{\\s*|export const\\s+))${name}\\b`,+ 'u',+ ).test(line),+ );+ for (const icon of icons) {+ const specifier = specifierOf(icon.from);+ /** @type {string[]} */+ const want = [];+ /** @type {string[]} */+ const wantImports = [];+ if (icon.adapt) {+ const local = `${icon.name}Source`;+ wantImports.push(+ icon.source === 'default'+ ? `import ${local} from '${specifier}';`+ : `import {${icon.source === local ? local : `${icon.source} as ${local}`}} from '${specifier}';`,+ );+ want.push(`export const ${icon.name} = ${ADAPTER_LOCAL}(${local});`);+ } else {+ want.push(+ icon.source === icon.name+ ? `export {${icon.name}} from '${specifier}';`+ : `export {${icon.source} as ${icon.name}} from '${specifier}';`,+ );+ }+ const prior = existing(icon.name);+ if (prior) {+ if (prior !== want[0]) {+ throw new IconSetAuthoringError(+ `The generated icons module already exports ${icon.name} as \`${prior}\`. Pass another name, or edit ${generated}.`,+ 'ERR_FILE_EXISTS',+ );+ }+ continue;+ }+ for (const line of wantImports) imports.add(line);+ for (const line of want) exports.add(line);+ }+ const needsAdapter = [...exports].some(line =>+ line.includes(`= ${ADAPTER_LOCAL}(`),+ );+ if (needsAdapter && !data.adapter) {+ throw new IconSetAuthoringError(+ 'An icon here is not a component, so the set needs an adapter. Declare "adapter": {"module": "./src/adapt.js", "export": "adapt"} in the data file: a function in your package that turns the library export into a component (astryx docs cli/experimental/icon-sets library-shapes).',+ 'ERR_INVALID_ARGUMENT',+ );+ }+ /** @type {string[]} */+ const theme = [];+ /** @type {Set<string>} */+ const themeImports = new Set();+ if (themeName) {+ const byId = new Map(data.icons.map(icon => [icon.id, icon.export]));+ for (const name of Object.keys(data.map ?? {}).sort()) {+ const exportName = byId.get(/** @type {string} */ (data.map?.[name]));+ if (BUILT_IN.has(name) && exportName) {+ theme.push(+ ` ${name}: createElement(${exportName}, ${THEME_ELEMENT_PROPS}),`,+ );+ const reexport = [...exports].find(line =>+ new RegExp(+ `^export \\{(?:\\w+ as )?${exportName}\\} from `,+ 'u',+ ).test(line),+ );+ if (reexport) {+ themeImports.add(`import${reexport.slice('export'.length)}`);+ }+ }+ }+ }+ const adapterLine =+ needsAdapter && data.adapter+ ? [+ `import {${data.adapter.export} as ${ADAPTER_LOCAL}} from '${specifierOf(data.adapter.module)}';`,+ ]+ : [];+ const js = [+ ...GENERATED_HEADER,+ ...(themeName ? [REACT_IMPORT] : []),+ ...adapterLine,+ ...[...imports, ...themeImports].sort(),+ ...[...exports].sort(),+ ...(themeName+ ? theme.length > 0+ ? [`export const ${themeName} = {`, ...theme, '};']+ : [`export const ${themeName} = {};`]+ : []),+ '',+ ].join('\n');+ const typesPath = generatedTypesPath(generated);+ return {+ js,+ dts: typesPath+ ? generatedTypesText(generatedStatements(js, generated))+ : null,+ };+}++/**+ * Every name the generated module already exports one library export as: `export {featherSun as SunIcon} from '…'` or the import an adapted+ * icon reads (`import {featherSun as SunIconSource} from '…'`). Adding the+ * same library export again then reuses that icon instead of naming a new+ * one.+ * @param {string} packageDir+ * @param {string} generated+ * @param {string} from the source module: a specifier, or a ./ path+ * @param {string} source the source export, or `default`+ * @returns {string[]}+ */+export function generatedNamesOf(packageDir, generated, from, source) {+ /** @type {string[]} */+ const names = [];+ const file = path.join(packageDir, generated);+ if (!fs.existsSync(file)) return names;+ let statements;+ try {+ statements = generatedStatements(fs.readFileSync(file, 'utf-8'), generated);+ } catch {+ return names;+ }+ let specifier = from;+ if (from.startsWith('./')) {+ specifier = path+ .relative(path.dirname(file), path.join(packageDir, from))+ .split(path.sep)+ .join('/');+ if (!specifier.startsWith('.')) specifier = `./${specifier}`;+ }+ const tail = ` from '${specifier}';`;+ for (const statement of statements) {+ if (!statement.endsWith(tail)) continue;+ const head = statement.slice(0, -tail.length);+ if (source === 'default') {+ const plain = /^import (\w+)Source$/u.exec(head);+ if (plain) names.push(plain[1]);+ const named = /^export \{default as (\w+)\}$/u.exec(head);+ if (named) names.push(named[1]);+ continue;+ }+ if (head === `export {${source}}`) names.push(source);+ const reexport = new RegExp(`^export \\{${source} as (\\w+)\\}$`, 'u').exec(+ head,+ );+ if (reexport) names.push(reexport[1]);+ const adapted = new RegExp(+ `^import \\{${source} as (\\w+)Source\\}$`,+ 'u',+ ).exec(head);+ if (adapted) names.push(adapted[1]);+ if (head === `import {${source}}` && source.endsWith('Source')) {+ names.push(source.slice(0, -'Source'.length));+ }+ }+ return names;+}++/**+ * Write the set's generated module and its declaration file+ * ({@link generatedModuleText}). Returns whether either changed, and a+ * function that puts both back.+ * @param {string} packageDir+ * @param {string} generated+ * @param {import('../../authoring/doctypes/icon-set/type').IconSetData} data+ * @param {GeneratedIcon[]} icons+ * @param {string[]} [remove] export names to drop ({@link generatedModuleText})+ * @returns {{changed: boolean, files: string[], undo: () => void}}+ */+export function writeGeneratedIcons(+ packageDir,+ generated,+ data,+ icons,+ remove = [],+) {+ const file = assertWithin(generated, packageDir, {+ label: 'generated icons module',+ });+ const before = fs.existsSync(file) ? fs.readFileSync(file, 'utf-8') : null;+ const {js, dts} = generatedModuleText(+ packageDir,+ generated,+ before,+ data,+ icons,+ remove,+ );+ const typesRel = generatedTypesPath(generated);+ const typesFile = typesRel ? path.join(packageDir, typesRel) : null;+ const typesBefore =+ typesFile && fs.existsSync(typesFile)+ ? fs.readFileSync(typesFile, 'utf-8')+ : null;+ /** @type {string[]} */+ const files = [];+ /** @type {Array<() => void>} */+ const undos = [];+ /**+ * @param {string} target+ * @param {string} text+ * @param {string | null} prior+ * @param {string} rel+ */+ const put = (target, text, prior, rel) => {+ if (prior === text) return;+ fs.mkdirSync(path.dirname(target), {recursive: true});+ replaceText(target, text);+ files.push(rel.replace(/^\.\//u, ''));+ undos.push(() => {+ if (!fs.existsSync(target) || fs.readFileSync(target, 'utf-8') !== text) {+ return;+ }+ if (prior == null) fs.rmSync(target);+ else replaceText(target, prior);+ });+ };+ const undo = () => {+ for (const each of [...undos].reverse()) each();+ };+ try {+ put(file, js, before, generated);+ if (typesFile && dts != null && typesRel)+ put(typesFile, dts, typesBefore, typesRel);+ } catch (error) {+ // A failed types write leaves the module as it was too.+ undo();+ throw error;+ }+ return {+ changed: files.length > 0,+ files,+ undo,+ };+}++/**+ * Whether the set's own module exports `name`, read without running it, and+ * the line its entry needs when it does not.+ * @param {DiscoveredIconSet} set+ * @param {{packageDir: string, pkg: Record<string, any>}} where+ * @param {string} generated the generated module's ./ path from the package root+ * @param {string} name+ * @returns {string | null} a note for the author, or null when nothing is needed+ */+export function setModuleNote(set, where, generated, name) {+ const entry = resolveIconModule(set.data.module, where.packageDir, {+ name: where.pkg.name,+ dir: where.packageDir,+ });+ if (entry && moduleExportOrigin(entry, name)) return null;+ const target = path.join(where.packageDir, generated);+ if (!entry) {+ return `"${set.data.module}" does not resolve yet: point its package.json "exports" at a file that has \`export * from '${generated.replace(/\.[cm]?[jt]sx?$/u, '.js')}';\`.`;+ }+ let relative = path+ .relative(path.dirname(entry), target)+ .split(path.sep)+ .join('/');+ if (!relative.startsWith('.')) relative = `./${relative}`;+ return `Add \`export * from '${relative}';\` to ${path.relative(where.packageDir, entry).split(path.sep).join('/')}, so the icons import from ${set.data.module}.`;+}diff --git a/packages/cli/foundation/discovery/integration-doc-files.mjs b/packages/cli/foundation/discovery/integration-doc-files.mjsindex 16550b6fce..1852e14ac7 100644--- a/packages/cli/foundation/discovery/integration-doc-files.mjs+++ b/packages/cli/foundation/discovery/integration-doc-files.mjs@@ -13,7 +13,10 @@* read applies;* - themes: each theme's descriptor, as theme discovery resolves it. A themes* root that discovery cannot read serves no theme, and is listed with the- * reason.+ * reason;+ * - iconSets: each icon set's descriptor that icon-set discovery reads. A+ * set whose descriptor or data file does not parse still ships its+ * descriptor, which is checked as a doc no reader serves.* A doc no reader serves still ships: a `hidden` one, a second doc for one* name, an overlay without its topic. It goes to its root's kind. A test* fixture does not ship as a doc, and is only counted: a doc under@@ -35,6 +38,7 @@ import {discoverIntegrationComponents} from './component-discovery.mjs';import {discoverIntegrationDocs} from './docs-discovery.mjs';import {discoverIntegrationTemplatesForOne} from './template-adapter.mjs';import {discoverThemeDirectory} from './theme-discovery.mjs';+import {discoverIconSetDirectory} from './icon-set-discovery.mjs';import {rootProblem} from '../integrations/validate-contributions.mjs';/** @typedef {import('./doc-types.mjs').DocFile} DocFile */@@ -48,7 +52,7 @@ import {rootProblem} from '../integrations/validate-contributions.mjs';* @returns {Promise<{files: DocFile[], unread: Array<{path: string, reason: string}>, fixtures: number}>}*/export async function integrationDocFiles(integration) {- const {components, templates, docs, themes} = integration ?? {};+ const {components, templates, docs, themes, iconSets} = integration ?? {};/** @type {Array<[DocRoot, string, string[]]>} */const read = [];/** @type {Array<{path: string, reason: string}>} */@@ -121,6 +125,15 @@ export async function integrationDocFiles(integration) {).map(theme => theme.docPath),],]);+ await take(iconSets, 'iconSets', async () => [+ [+ 'icon-sets',+ discoverIconSetDirectory(+ /** @type {string} */ (iconSets),+ integration?.name ?? 'the package',+ ).sets.map(set => set.docPath),+ ],+ ]);/** @type {Map<string, {root: DocRoot, dir: string}>} */const owners = new Map();/** @type {(table: Map<string, {root: DocRoot, dir: string}>, root: DocRoot, dir: string, file: string) => void} */@@ -143,6 +156,7 @@ export async function integrationDocFiles(integration) {['templates', templates],['docs', docs],['themes', themes],+ ['icon-sets', iconSets],])) {if (!dir || !readable.has(dir)) continue;for (const file of docFilesUnder(dir)) {@@ -179,6 +193,7 @@ function isFixture(file, root) {return (root !== 'templates' &&root !== 'themes' &&+ root !== 'icon-sets' &&file.split(path.sep).includes('__tests__'));}diff --git a/packages/cli/foundation/discovery/integration-doc-files.test.mjs b/packages/cli/foundation/discovery/integration-doc-files.test.mjsindex a3312d74b6..3e6030b2f6 100644--- a/packages/cli/foundation/discovery/integration-doc-files.test.mjs+++ b/packages/cli/foundation/discovery/integration-doc-files.test.mjs@@ -186,6 +186,35 @@ describe('integrationDocFiles', () => {]);});+ it('takes each icon set descriptor, and the descriptor of a set that does not parse', async () => {+ const data = JSON.stringify({+ schemaVersion: 1,+ module: '@acme/icons',+ icons: [],+ });+ write(+ 'icon-sets/outline/outline.doc.mjs',+ "export default {type: 'icon-set', name: 'outline', displayName: 'Outline', description: 'D', maintained: true, license: 'MIT'};\n",+ );+ write('icon-sets/outline/outline.icons.json', data);+ // A descriptor with a wrongly typed field: discovery withdraws the set,+ // but the file still ships and is still checked.+ write(+ 'icon-sets/solid/solid.doc.mjs',+ "export default {type: 'icon-set', name: 'solid', displayName: 'Solid', description: 'D', maintained: 'yes', license: 'MIT'};\n",+ );+ write('icon-sets/solid/solid.icons.json', data);+ const {files, unread} = await integrationDocFiles({+ name: '@acme/icons',+ iconSets: path.join(pkg, 'icon-sets'),+ });+ expect(listed(files)).toEqual([+ ['icon-sets/outline/outline.doc.mjs', 'icon-sets'],+ ['icon-sets/solid/solid.doc.mjs', 'icon-sets'],+ ]);+ expect(unread).toEqual([]);+ });+it("takes a scoped package's namespace docs and placed guides where they are, with each guide's overlays", async () => {write('docs/guides/guides.doc.mjs',diff --git a/packages/cli/foundation/discovery/module-exports.mjs b/packages/cli/foundation/discovery/module-exports.mjsindex a3d2dd1a21..0760f95dae 100644--- a/packages/cli/foundation/discovery/module-exports.mjs+++ b/packages/cli/foundation/discovery/module-exports.mjs@@ -4,18 +4,24 @@* @file Static JavaScript module export inspection.** Proves a runtime export without executing package code. Local ESM re-exports- * are followed recursively; unresolved or unparsable modules fail closed.+ * are followed recursively; unresolved or unparsable modules fail closed. A+ * check that must fail only what it proves asks for a verdict: an export is+ * present (followed to its declaration, `const` aliases included), proved+ * absent, or unknown with the reason.** @input A module path and runtime export name, or a module path and the* exports to try- * @output Whether that export can be proved statically and the file that- * declares it, or the exported object literal as plain data+ * @output Whether that export can be proved statically, the file and binding+ * that declare it, a present / absent / unknown verdict with its reason, or+ * the exported object literal as plain data* @position packages/cli/foundation/discovery — shared package inspection*/import * as fs from 'node:fs';import * as path from 'node:path';import {parse} from '@babel/parser';+import {findInstalledPackage} from '../fs/paths.mjs';+import {inspectPackageExport} from './package-exports.mjs';const MODULE_EXTENSIONS = ['.mjs',@@ -172,13 +178,144 @@ function resolveLocalModule(specifier, fromFile) {...MODULE_EXTENSIONS.map(extension => `${base}${extension}`),...MODULE_EXTENSIONS.map(extension => path.join(base, `index${extension}`)),];- return candidates.find(candidate => {+ return (+ candidates.find(candidate => {+ try {+ return fs.statSync(candidate).isFile();+ } catch {+ return false;+ }+ }) ?? null+ );+}++/**+ * The file a re-export's specifier names, from the file that writes it: a+ * relative path, or an installed package (its `exports` map honored, else+ * its `module` or `main`), found through node_modules from that file. Only+ * the icon-set readers follow packages; every other reader in this module+ * uses {@link resolveLocalModule}, which follows relative paths alone.+ * @param {unknown} specifier+ * @param {string} fromFile+ */+function resolveModuleOrPackage(specifier, fromFile) {+ if (typeof specifier !== 'string') return null;+ if (!specifier.startsWith('.'))+ return resolvePackageModule(specifier, fromFile);+ return resolveLocalModule(specifier, fromFile);+}++/**+ * @param {string} specifier a bare package specifier, with an optional subpath+ * @param {string} fromFile+ * @returns {string | null}+ */+function resolvePackageModule(specifier, fromFile) {+ if (specifier.startsWith('node:') || specifier.startsWith('/')) return null;+ const parts = specifier.split('/');+ const count = specifier.startsWith('@') ? 2 : 1;+ const name = parts.slice(0, count).join('/');+ const rest = parts.slice(count).join('/');+ // Node's own resolution: every ancestor's node_modules, no depth cap.+ const packageDir = findInstalledPackage(+ path.dirname(fromFile),+ name,+ Infinity,+ );+ if (!packageDir) return null;+ /** @type {Record<string, any>} */+ let pkg;+ try {+ pkg = JSON.parse(+ fs.readFileSync(path.join(packageDir, 'package.json'), 'utf-8'),+ );+ } catch {+ return null;+ }+ if (pkg.exports !== undefined) {+ return inspectPackageExport(pkg, packageDir, rest ? `./${rest}` : '.')+ .target;+ }+ const entry = rest || pkg.module || pkg.main || 'index';+ const base = path.join(packageDir, entry);+ return (+ [+ base,+ ...MODULE_EXTENSIONS.map(extension => `${base}${extension}`),+ ...MODULE_EXTENSIONS.map(extension =>+ path.join(base, `index${extension}`),+ ),+ ].find(candidate => {+ try {+ return fs.statSync(candidate).isFile();+ } catch {+ return false;+ }+ }) ?? null+ );+}++/**+ * The first module, from `file` through its relative re-exports, that does+ * not parse, with the parser's message; null when every one parses.+ * @param {string} file+ * @returns {{file: string, message: string} | null}+ */+export function moduleParseFailure(file) {+ /** @type {Set<string>} */+ const seen = new Set();+ /** @type {string[]} */+ const queue = [file];+ while (queue.length > 0) {+ const next = /** @type {string} */ (queue.shift());+ if (seen.has(next)) continue;+ seen.add(next);+ let ast;try {- return fs.statSync(candidate).isFile();- } catch {- return false;+ ast = parseModule(next);+ } catch (error) {+ return {+ file: next,+ message: error instanceof Error ? error.message : String(error),+ };}- }) ?? null;+ for (const type of ['ExportNamedDeclaration', 'ExportAllDeclaration']) {+ for (const node of nodesOfType(ast.program, type)) {+ const specifier = node.source?.value;+ if (typeof specifier !== 'string' || !specifier.startsWith('.')) {+ continue;+ }+ const target = resolveLocalModule(specifier, next);+ if (target) queue.push(target);+ }+ }+ }+ return null;+}++/**+ * The re-exports of a module whose source the reader could not follow:+ * each `export ... from '<specifier>'` that resolves to no file.+ * @param {string} file+ * @returns {string[]}+ */+export function unfollowedReexports(file) {+ let ast;+ try {+ ast = parseModule(file);+ } catch {+ return [];+ }+ /** @type {Set<string>} */+ const missing = new Set();+ for (const type of ['ExportNamedDeclaration', 'ExportAllDeclaration']) {+ for (const node of nodesOfType(ast.program, type)) {+ const specifier = node.source?.value;+ if (typeof specifier !== 'string' || node.exportKind === 'type') continue;+ if (!resolveModuleOrPackage(specifier, file)) missing.add(specifier);+ }+ }+ return [...missing].sort();}/** @param {any} declaration @param {string} exportName */@@ -294,7 +431,11 @@ export function moduleExportSource(file, exportName, seen = new Set()) {if (exportName === 'default') {const defaults = nodesOfType(ast.program, 'ExportDefaultDeclaration');- if (defaults.some((/** @type {any} */ node) => runtimeDefault(node.declaration))) {+ if (+ defaults.some((/** @type {any} */ node) =>+ runtimeDefault(node.declaration),+ )+ ) {return file;}}@@ -309,6 +450,28 @@ export function moduleExportSource(file, exportName, seen = new Set()) {return found;}+/** The calls that make a React element: createElement, jsx, jsxs, jsxDEV. */+const ELEMENT_CALLS = new Set([+ 'createElement',+ 'jsx',+ 'jsxs',+ 'jsxDEV',+ '_jsx',+ '_jsxs',+ '_jsxDEV',+]);++/** @param {any} callee */+function isElementCall(callee) {+ if (callee?.type === 'Identifier') return ELEMENT_CALLS.has(callee.name);+ return (+ callee?.type === 'MemberExpression' &&+ !callee.computed &&+ callee.property?.type === 'Identifier' &&+ ELEMENT_CALLS.has(callee.property.name)+ );+}+/*** The module's own top-level statements of one type: an `export` inside a* TypeScript namespace names a member of that namespace, not of the module.@@ -427,7 +590,9 @@ export function moduleExportVerdict(file, exportName, seen = new Set()) {);}if (topLevel(ast.program, 'TSExportAssignment').length > 0) {- unknown.push(`${shown} uses \`export =\`, whose names this check does not read.`);+ unknown.push(+ `${shown} uses \`export =\`, whose names this check does not read.`,+ );}/*** Follow a re-export of `imported` from `specifier`.@@ -513,7 +678,9 @@ export function moduleExportVerdict(file, exportName, seen = new Set()) {return {verdict: 'exports'};}if (specifier.type !== 'ExportSpecifier') {- unknown.push(`${shown} re-exports ${exportName} in a form this check does not read.`);+ unknown.push(+ `${shown} re-exports ${exportName} in a form this check does not read.`,+ );continue;}const imported =@@ -722,3 +889,507 @@ export function staticExportObject(file, exportNames) {}return null;}++/**+ * Where a module's runtime export is declared, as the file and the name it+ * has there, without executing anything: local re-exports, renames, and+ * imported bindings a module exports again are followed. Two exports are the+ * same value when their origins are equal. Null when it cannot be proved.+ * @param {string} file+ * @param {string} exportName+ * @param {Set<string>} [seen]+ * @returns {{file: string, name: string} | null}+ */+export function moduleExportOrigin(file, exportName, seen = new Set()) {+ const identity = `${file}\0${exportName}`;+ if (seen.has(identity)) return null;+ seen.add(identity);+ let ast;+ try {+ if (!fs.statSync(file).isFile()) return null;+ ast = parseModule(file);+ } catch {+ return null;+ }+ for (const node of nodesOfType(ast.program, 'ExportNamedDeclaration')) {+ if (node.exportKind === 'type') continue;+ if (declarationExports(node.declaration, exportName)) {+ return {file, name: exportName};+ }+ for (const specifier of node.specifiers ?? []) {+ if (+ specifier.type !== 'ExportSpecifier' ||+ specifier.exportKind === 'type'+ ) {+ continue;+ }+ const exported = specifier.exported?.name ?? specifier.exported?.value;+ if (exported !== exportName) continue;+ const local =+ specifier.local?.name ?? specifier.local?.value ?? exportName;+ if (node.source) {+ const target = resolveModuleOrPackage(node.source.value, file);+ const origin = target ? moduleExportOrigin(target, local, seen) : null;+ if (origin) return origin;+ continue;+ }+ return bindingOrigin(ast, file, local, seen);+ }+ }+ if (exportName === 'default') {+ for (const node of nodesOfType(ast.program, 'ExportDefaultDeclaration')) {+ const declaration = node.declaration;+ if (!runtimeDefault(declaration)) continue;+ if (declaration.type === 'Identifier') {+ return bindingOrigin(ast, file, declaration.name, seen);+ }+ return {file, name: 'default'};+ }+ }+ for (const node of nodesOfType(ast.program, 'ExportAllDeclaration')) {+ if (node.exportKind === 'type' || node.exported) continue;+ const target = resolveModuleOrPackage(node.source?.value, file);+ const origin = target ? moduleExportOrigin(target, exportName, seen) : null;+ if (origin) return origin;+ }+ return null;+}++/**+ * @typedef {{verdict: 'exports', origin: {file: string, name: string}} | {verdict: 'lacks'} | {verdict: 'unknown', reason: string}} ExportOriginVerdict+ */++/**+ * Whether a module exports `exportName`, and where it is declared, for a+ * check that must fail only what it proves: `exports` with the origin when+ * {@link moduleExportOrigin} follows it to its declaration (through local+ * files and installed packages); `lacks` only when+ * {@link moduleExportVerdict} proves no export binds it; `unknown`, with the+ * reason, for anything else, including an export bound to a default or+ * namespace import, or to an import from a package that does not resolve.+ * @param {string} file+ * @param {string} exportName+ * @returns {ExportOriginVerdict}+ */+export function exportOriginVerdict(file, exportName) {+ const origin = moduleExportOrigin(file, exportName);+ if (origin) return {verdict: 'exports', origin};+ const verdict = moduleExportVerdict(file, exportName);+ if (verdict.verdict === 'lacks') return {verdict: 'lacks'};+ if (verdict.verdict === 'unknown') return verdict;+ return {verdict: 'unknown', reason: originGapReason(file, exportName)};+}++/**+ * Why an export a module binds could not be followed to its declaration:+ * re-exports are followed to the module that binds it.+ * @param {string} file+ * @param {string} exportName+ * @param {Set<string>} [seen]+ * @returns {string}+ */+function originGapReason(file, exportName, seen = new Set()) {+ const shown = path.basename(file);+ const identity = `${file}\0${exportName}`;+ if (seen.has(identity)) {+ return `${shown} exports ${exportName}, but this check could not follow it to the declaration.`;+ }+ seen.add(identity);+ const generic = `${shown} exports ${exportName}, but this check could not follow it to the declaration.`;+ let ast;+ try {+ ast = parseModule(file);+ } catch {+ return generic;+ }+ /** @type {string | null} */+ let local = null;+ for (const node of nodesOfType(ast.program, 'ExportNamedDeclaration')) {+ for (const specifier of node.specifiers ?? []) {+ const exported = specifier.exported?.name ?? specifier.exported?.value;+ if (exported !== exportName) continue;+ const name = specifier.local?.name ?? specifier.local?.value;+ if (node.source) {+ const source = String(node.source.value);+ const target = resolveModuleOrPackage(source, file);+ if (!target) {+ return `${shown} re-exports ${exportName} from "${source}", which does not resolve from the package.`;+ }+ return originGapReason(+ target,+ typeof name === 'string' ? name : exportName,+ seen,+ );+ }+ local = typeof name === 'string' ? name : null;+ }+ }+ if (exportName === 'default') {+ for (const node of nodesOfType(ast.program, 'ExportDefaultDeclaration')) {+ if (node.declaration?.type === 'Identifier') {+ local = node.declaration.name;+ }+ }+ }+ if (!local) {+ // Bound behind `export *`: the module it comes from says why.+ for (const node of nodesOfType(ast.program, 'ExportAllDeclaration')) {+ if (node.exportKind === 'type' || node.exported) continue;+ const target = resolveModuleOrPackage(node.source?.value, file);+ if (+ target &&+ moduleExportVerdict(target, exportName).verdict === 'exports'+ ) {+ return originGapReason(target, exportName, seen);+ }+ }+ return generic;+ }+ for (const node of ast.program.body) {+ if (node.type !== 'ImportDeclaration' || node.importKind === 'type') {+ continue;+ }+ const source = String(node.source.value);+ for (const specifier of node.specifiers ?? []) {+ if (specifier.local?.name !== local) continue;+ if (specifier.type === 'ImportDefaultSpecifier') {+ return `${shown} exports ${exportName} from a default import of "${source}", which this check does not follow.`;+ }+ if (specifier.type === 'ImportNamespaceSpecifier') {+ return `${shown} exports ${exportName} from a namespace import of "${source}", which this check does not follow.`;+ }+ return resolveModuleOrPackage(source, file)+ ? `${shown} exports ${exportName} imported from "${source}", which this check could not follow to the declaration.`+ : `${shown} exports ${exportName} imported from "${source}", which does not resolve from the package.`;+ }+ }+ return generic;+}++/**+ * Every runtime export name of a module, read without running it: its own+ * named exports and, through `export *` from local files and installed+ * packages, theirs. Unlike {@link moduleExportNames}, it never gives up on an+ * `export *`: what it cannot read is left out. Type-only+ * exports and `default` are left out. Sorted.+ * @param {string} file+ * @param {Set<string>} [seen]+ * @returns {string[]}+ */+export function followedExportNames(file, seen = new Set()) {+ if (seen.has(file)) return [];+ seen.add(file);+ let ast;+ try {+ if (!fs.statSync(file).isFile()) return [];+ ast = parseModule(file);+ } catch {+ return [];+ }+ /** @type {Set<string>} */+ const names = new Set();+ for (const node of nodesOfType(ast.program, 'ExportNamedDeclaration')) {+ if (node.exportKind === 'type') continue;+ const declaration = node.declaration;+ if (declaration && declaration.declare !== true) {+ if (+ ['FunctionDeclaration', 'ClassDeclaration'].includes(declaration.type)+ ) {+ if (declaration.id?.name) names.add(declaration.id.name);+ } else if (declaration.type === 'VariableDeclaration') {+ for (const item of declaration.declarations) {+ if (item.id?.type === 'Identifier') names.add(item.id.name);+ }+ }+ }+ for (const specifier of node.specifiers ?? []) {+ if (+ specifier.type !== 'ExportSpecifier' ||+ specifier.exportKind === 'type'+ ) {+ continue;+ }+ const exported = specifier.exported?.name ?? specifier.exported?.value;+ if (typeof exported === 'string' && exported !== 'default') {+ names.add(exported);+ }+ }+ }+ for (const node of nodesOfType(ast.program, 'ExportAllDeclaration')) {+ if (node.exportKind === 'type' || node.exported) continue;+ const target = resolveModuleOrPackage(node.source?.value, file);+ if (target) {+ for (const name of followedExportNames(target, seen)) names.add(name);+ }+ }+ return [...names].sort();+}++/**+ * What a module's runtime export is, read without running it: `component`+ * for a function, a class, or a value a call returns (`forwardRef(...)`);+ * `data` for an object, array, or other literal; `unknown` when it cannot be+ * read.+ * @param {string} file+ * @param {string} exportName+ * @returns {'component' | 'data' | 'unknown'}+ */+export function exportValueKind(file, exportName) {+ const origin = moduleExportOrigin(file, exportName);+ if (!origin) return 'unknown';+ let ast;+ try {+ ast = parseModule(origin.file);+ } catch {+ return 'unknown';+ }+ /** @param {any} node @returns {'component' | 'data' | 'unknown'} */+ const kindOf = node => {+ const value = withoutTypeWrappers(node);+ if (!value) return 'unknown';+ if (+ [+ 'FunctionDeclaration',+ 'FunctionExpression',+ 'ArrowFunctionExpression',+ 'ClassDeclaration',+ 'ClassExpression',+ 'CallExpression',+ ].includes(value.type)+ ) {+ return 'component';+ }+ if (+ [+ 'ObjectExpression',+ 'ArrayExpression',+ 'StringLiteral',+ 'NumericLiteral',+ 'BooleanLiteral',+ 'TemplateLiteral',+ 'NullLiteral',+ ].includes(value.type)+ ) {+ return 'data';+ }+ return 'unknown';+ };+ if (origin.name === 'default') {+ const [node] = nodesOfType(ast.program, 'ExportDefaultDeclaration');+ return node ? kindOf(node.declaration) : 'unknown';+ }+ for (const statement of ast.program.body) {+ const declaration =+ statement.type === 'ExportNamedDeclaration'+ ? statement.declaration+ : statement;+ if (!declaration) continue;+ if (+ ['FunctionDeclaration', 'ClassDeclaration'].includes(declaration.type) &&+ declaration.id?.name === origin.name+ ) {+ return 'component';+ }+ if (declaration.type !== 'VariableDeclaration') continue;+ for (const declarator of declaration.declarations) {+ if (+ declarator.id?.type === 'Identifier' &&+ declarator.id.name === origin.name+ ) {+ return kindOf(declarator.init);+ }+ }+ }+ return 'unknown';+}++/**+ * The scalar type of an export's static value: `string` for a string or a+ * template literal with no expressions, `number` or `boolean` for those+ * literals; null for anything else, or when the value cannot be read.+ * @param {string} file+ * @param {string} exportName+ * @returns {'string' | 'number' | 'boolean' | null}+ */+export function exportScalarType(file, exportName) {+ const origin = moduleExportOrigin(file, exportName);+ if (!origin) return null;+ let ast;+ try {+ ast = parseModule(origin.file);+ } catch {+ return null;+ }+ /** @param {any} node */+ const typeOf = node => {+ const value = withoutTypeWrappers(node);+ if (value?.type === 'StringLiteral') return 'string';+ if (value?.type === 'TemplateLiteral' && value.expressions.length === 0) {+ return 'string';+ }+ if (value?.type === 'NumericLiteral') return 'number';+ if (value?.type === 'BooleanLiteral') return 'boolean';+ return null;+ };+ if (origin.name === 'default') {+ const [node] = nodesOfType(ast.program, 'ExportDefaultDeclaration');+ return node ? typeOf(node.declaration) : null;+ }+ for (const statement of ast.program.body) {+ const declaration =+ statement.type === 'ExportNamedDeclaration'+ ? statement.declaration+ : statement;+ if (declaration?.type !== 'VariableDeclaration') continue;+ for (const declarator of declaration.declarations) {+ if (+ declarator.id?.type === 'Identifier' &&+ declarator.id.name === origin.name+ ) {+ return typeOf(declarator.init);+ }+ }+ }+ return null;+}++/**+ * The binding an origin finally names: a top-level `const X = Y` (under `as`+ * or `satisfies` too) is followed to where `Y` is declared, through imports,+ * until a declaration that is not such an alias. Two aliases of one component+ * then have the same final origin. Null when an alias cannot be followed (to+ * a default or namespace import, a member such as `Icons.X`, or an import+ * that does not resolve), so a caller leaves the comparison unchecked.+ * @param {{file: string, name: string}} origin+ * @param {Set<string>} [seen]+ * @returns {{file: string, name: string} | null}+ */+export function aliasedOrigin(origin, seen = new Set()) {+ const identity = `${origin.file}\0${origin.name}`;+ if (seen.has(identity)) return null;+ seen.add(identity);+ let ast;+ try {+ ast = parseModule(origin.file);+ } catch {+ return null;+ }+ for (const statement of ast.program.body) {+ const declaration =+ statement.type === 'ExportNamedDeclaration'+ ? statement.declaration+ : statement;+ if (declaration?.type !== 'VariableDeclaration') continue;+ for (const declarator of declaration.declarations) {+ if (+ declarator.id?.type !== 'Identifier' ||+ declarator.id.name !== origin.name+ ) {+ continue;+ }+ const init = withoutTypeWrappers(declarator.init);+ if (init?.type === 'MemberExpression') return null;+ if (init?.type !== 'Identifier') return origin;+ const next = bindingOrigin(ast, origin.file, init.name, new Set());+ return next ? aliasedOrigin(next, seen) : null;+ }+ }+ return origin;+}++/**+ * Where a top-level binding of a parsed module comes from: an import from a+ * local module is followed to its origin; anything else is declared here.+ * @param {any} ast+ * @param {string} file+ * @param {string} local+ * @param {Set<string>} seen+ * @returns {{file: string, name: string} | null}+ */+function bindingOrigin(ast, file, local, seen) {+ for (const node of ast.program.body) {+ if (node.type !== 'ImportDeclaration' || node.importKind === 'type') {+ continue;+ }+ for (const specifier of node.specifiers ?? []) {+ if (specifier.local?.name !== local) continue;+ if (specifier.type !== 'ImportSpecifier') return null;+ const imported =+ specifier.imported?.name ?? specifier.imported?.value ?? local;+ const target = resolveModuleOrPackage(node.source.value, file);+ return target ? moduleExportOrigin(target, imported, seen) : null;+ }+ }+ return {file, name: local};+}++/**+ * The object a module exports under `exportName`, read without running it:+ * each property's key and the binding its value names (an identifier, or the+ * element name of `<Name />`), followed to where that binding is declared.+ * The export itself is followed through re-exports first. A property whose+ * value is anything else maps to null, so a caller can leave it unchecked.+ * Null when the export is not one static object literal.+ * @param {string} file+ * @param {string} exportName+ * @returns {Map<string, {file: string, name: string} | null> | null}+ */+export function staticExportBindings(file, exportName) {+ const origin = moduleExportOrigin(file, exportName);+ if (!origin) return null;+ let ast;+ try {+ ast = parseModule(origin.file);+ } catch {+ return null;+ }+ /** @type {any} */+ let init = null;+ for (const statement of ast.program.body) {+ const declaration =+ statement.type === 'ExportNamedDeclaration'+ ? statement.declaration+ : statement;+ if (declaration?.type !== 'VariableDeclaration') continue;+ for (const declarator of declaration.declarations) {+ if (+ declarator.id?.type === 'Identifier' &&+ declarator.id.name === origin.name+ ) {+ init = declarator.init;+ }+ }+ }+ const object = withoutTypeWrappers(init);+ if (object?.type !== 'ObjectExpression') return null;+ /** @type {Map<string, {file: string, name: string} | null>} */+ const bindings = new Map();+ for (const property of object.properties) {+ if (property.type !== 'ObjectProperty' || property.computed) return null;+ const key = property.key?.name ?? property.key?.value;+ if (typeof key !== 'string') return null;+ let value = withoutTypeWrappers(property.value);+ if (value?.type === 'JSXElement') {+ const name = value.openingElement?.name;+ value =+ name?.type === 'JSXIdentifier'+ ? {type: 'Identifier', name: name.name}+ : null;+ } else if (+ value?.type === 'CallExpression' &&+ isElementCall(value.callee)+ ) {+ // createElement(X, ...), React.createElement(X, ...), jsx(X, ...),+ // _jsx(X, ...): the element of component X.+ const first = withoutTypeWrappers(value.arguments?.[0]);+ value = first?.type === 'Identifier' ? first : null;+ }+ bindings.set(+ key,+ value?.type === 'Identifier'+ ? bindingOrigin(ast, origin.file, value.name, new Set())+ : null,+ );+ }+ return bindings;+}diff --git a/packages/cli/foundation/discovery/runner-commands.test.mjs b/packages/cli/foundation/discovery/runner-commands.test.mjsindex be6d1e14c9..f0e02de3b5 100644--- a/packages/cli/foundation/discovery/runner-commands.test.mjs+++ b/packages/cli/foundation/discovery/runner-commands.test.mjs@@ -120,7 +120,10 @@ describe('CLI_COMMANDS', () => {.readdirSync(COMMAND_DOCS).filter(file => file.endsWith('.doc.mjs')).map(file => file.slice(0, -'.doc.mjs'.length))- .filter(name => !name.includes('-') || name === 'gap-report');+ .filter(name => !name.includes('-') || name === 'gap-report')+ // The experimental group is no stable command, so a runner note never+ // names it (spec:AST-084 FR0).+ .filter(name => name !== 'experimental');expect([...CLI_COMMANDS].sort()).toEqual([...new Set([...documented, 'help'])].sort(),);diff --git a/packages/cli/foundation/discovery/template-adapter.mjs b/packages/cli/foundation/discovery/template-adapter.mjsindex f99fd4c5f3..e6aa658592 100644--- a/packages/cli/foundation/discovery/template-adapter.mjs+++ b/packages/cli/foundation/discovery/template-adapter.mjs@@ -112,6 +112,8 @@ export function effectiveTemplateDiscovery(templates) {* @property {string[]} [alsoExampleFor]* @property {string[]} [alsoShowcaseFor]* @property {string[]} [componentsUsed]+ * @property {Record<string, string>} [icons] the icon definition each+ * imported icon draws, by its imported name* @property {boolean} [isShowcase]* @property {string} filePath* @property {string} docPath@@ -665,6 +667,7 @@ async function discoverPages() {keywords: doc?.keywords ?? [],isReady: doc?.isReady ?? true,scaffold: doc?.scaffold ?? false,+ ...(doc?.icons ? {icons: doc.icons} : {}),filePath: path.join(dirPath, 'page.tsx'),docPath,});@@ -695,6 +698,7 @@ async function discoverBlocks() {isReady: doc?.isReady ?? true,aspectRatio: doc?.aspectRatio ?? 1,componentsUsed: doc?.componentsUsed ?? [],+ ...(doc?.icons ? {icons: doc.icons} : {}),isShowcase: doc?.isShowcase ?? false,...(typeof doc?.exampleFor === 'string'? {exampleFor: doc.exampleFor}@@ -740,6 +744,7 @@ async function discoverExternalBlocks(cwd = process.cwd()) {isReady: doc?.isReady ?? true,aspectRatio: doc?.aspectRatio ?? 1,componentsUsed: doc?.componentsUsed ?? [],+ ...(doc?.icons ? {icons: doc.icons} : {}),isShowcase: doc?.isShowcase ?? false,...(typeof doc?.exampleFor === 'string'? {exampleFor: doc.exampleFor}@@ -1341,6 +1346,7 @@ export async function discoverIntegrationTemplatesForOne(integration) {// so read it off the envelope shape here.componentsUsed:/** @type {{componentsUsed?: string[]}} */ (doc).componentsUsed ?? [],+ ...(doc?.icons ? {icons: doc.icons} : {}),filePath: sourcePath,docPath,package: pkgLabel,diff --git a/packages/cli/foundation/discovery/template-icon-notes.mjs b/packages/cli/foundation/discovery/template-icon-notes.mjsnew file mode 100644index 0000000000..70c644c401--- /dev/null+++ b/packages/cli/foundation/discovery/template-icon-notes.mjs@@ -0,0 +1,66 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Template `icons` keys a template's source never imports (spec:AST-084+ * FR10).+ *+ * A template's `icons` names each icon it imports, by the name it imports or,+ * for a default import, its local name. A key that no import or re-export in+ * the template's source binds can never map to a project's icon set, so each+ * one gets a note with its fix.+ *+ * @input A loaded integration (absolute roots) and its package directory.+ * @output One `template_icon_not_imported` note per such key. A note is not an+ * issue: it is never an error or a warning, and never fails a check, even+ * under `--strict` (architecture:cli-surface INV35).+ * @position foundation/discovery; read by `doctor integration validate` (and+ * so `integration check`) for the package being authored.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {loadTopicModule} from './docs-discovery.mjs';+import {discoverIntegrationTemplatesForOne} from './template-adapter.mjs';+import {iconsNotImported} from './template-icons.mjs';++/** A template `icons` key its source never imports. */+export const TEMPLATE_ICON_NOT_IMPORTED = 'template_icon_not_imported';++/**+ * One note per template `icons` key the template's source never imports.+ * @param {any} loaded a loaded integration (absolute roots)+ * @param {string} packageDir+ * @returns {Promise<Array<{code: string, message: string}>>}+ */+export async function templateIconNotes(loaded, packageDir) {+ if (!loaded.templates) return [];+ const {templates} = await discoverIntegrationTemplatesForOne(loaded).catch(+ () => ({templates: []}),+ );+ /** @type {Array<{code: string, message: string}>} */+ const notes = [];+ /** @param {string} file */+ const shown = file =>+ path.relative(packageDir, file).split(path.sep).join('/');+ for (const template of templates) {+ if (!template.docPath || !template.filePath) continue;+ const doc = /** @type {any} */ (+ await loadTopicModule(template.docPath).catch(() => null)+ );+ const declared = doc?.icons;+ if (declared == null || typeof declared !== 'object') continue;+ let source;+ try {+ source = fs.readFileSync(template.filePath, 'utf-8');+ } catch {+ continue;+ }+ for (const key of iconsNotImported(source, declared) ?? []) {+ notes.push({+ code: TEMPLATE_ICON_NOT_IMPORTED,+ message: `${shown(template.docPath)} declares icon "${key}" in \`icons\`, which ${shown(template.filePath)} does not import, so it never maps to a project's icon set. Name a named import by the name it imports and a default import by its local name, or remove "${key}" from \`icons\`.`,+ });+ }+ }+ return notes;+}diff --git a/packages/cli/foundation/discovery/template-icons.mjs b/packages/cli/foundation/discovery/template-icons.mjsnew file mode 100644index 0000000000..7dca5dd06c--- /dev/null+++ b/packages/cli/foundation/discovery/template-icons.mjs@@ -0,0 +1,712 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Template icon mapping (AST-084 FR9, FR10): rewrite a template's icon+ * imports to the project's icon set, by icon definition.+ *+ * Source text, the template's declared icons, and icon-set data in; source+ * text and a report out. The CLI knows no icon library: a template says, in+ * its own descriptor's `icons`, which icon definition each icon it imports+ * draws (`{TrashIcon: 'delete'}`), and an icon an installed set ships draws+ * the definitions that set's `map` names it for. Each such icon maps to the+ * project set's icon that:+ * 1. names it in a reviewed `matches` entry with `exact` or `strong`+ * confidence (for an icon an installed set ships);+ * 2. otherwise is the icon the project set's `map` names for the Astryx+ * icon definition the source icon draws.+ * Nothing is guessed from names or words. A `likely` reviewed match is never+ * applied: a kept icon names it as a suggestion.+ * A declared key names a named import by the name it imports+ * (`{Trash as TrashIcon}` is `Trash`) and a default import by its local name+ * (`import DeleteIcon from …` is `DeleteIcon`). A mapped named import and+ * every reference to it use the mapped export, under an alias when that name+ * would collide with another binding in the file; a mapped default import+ * becomes the set's named import aliased to its local name. An icon from an+ * installed set that draws a variant (such as solid) maps to the target's+ * variant of that name, else its default. With a project icon set, every+ * declared key ends up mapped or kept (FR10): an icon with no match keeps its+ * original import, and a key bound only by a namespace import, a type-only+ * import, a re-export, an import from an Astryx package or from the project's+ * own set, or by no import at all, is kept with the reason. A side-effect+ * import binds nothing. Without a project icon set the source is unchanged+ * and the report says why.+ *+ * @input Template source, its declared icons, the installed sets, and the+ * project's choice+ * @output The rewritten source and the `icons` report+ * @position packages/cli/foundation/discovery — read by template show/copy+ */++import {parse} from '@babel/parser';+import {definitionsByIcon} from './icon-set-discovery.mjs';+import {astryxDefinitionsByName} from './icon-definition-discovery.mjs';++/** @typedef {import('./icon-set-discovery.mjs').DiscoveredIconSet} DiscoveredIconSet */+/** @typedef {import('./icon-set-discovery.mjs').IconSetChoice} IconSetChoice */+/** @typedef {import('../../authoring/doctypes/icon-set/type').IconSetIcon} IconSetIcon */++/**+ * A source icon: what an imported icon means.+ * @typedef {object} SourceIcon+ * @property {string | null} setName the installed set it comes from, as a+ * reviewed match names it; null for an icon only the template declares+ * @property {string} export the export the template imports+ * @property {string} [variant] which of its set's declared variants the+ * export draws, as a reviewed match names it+ * @property {string} id+ * @property {string[]} definitions the Astryx definitions it draws+ * @property {DiscoveredIconSet} [set] the set it came from, when installed+ */++/**+ * One mapped icon.+ * @typedef {object} MappedIcon+ * @property {{module: string, export: string}} source+ * @property {{set: string, package: string, id: string, module: string, export: string}} target+ * @property {'match' | 'definition'} by `match`: a reviewed+ * `exact` or `strong` match in the project set's data names the source+ * icon; `definition`: the target's `map` names it for the Astryx icon+ * definition the source draws+ */++/**+ * One icon kept as the template wrote it.+ * @typedef {object} KeptIcon+ * @property {string | null} module the module it is imported or re-exported+ * from; null when the template does not import it+ * @property {string} export the name it is imported by: `default` for a+ * default import, `*` for a namespace import+ * @property {string} reason+ * @property {{set: string, id: string, module: string, export: string, confidence: 'likely'}} [suggestion]+ * a `likely` reviewed match, suggested and never applied+ */++/**+ * What template icon mapping did.+ * @typedef {object} TemplateIconsReport+ * @property {'selected' | 'none' | 'ambiguous' | 'missing' | 'withdrawn'} status the+ * project's icon-set state; only `selected` maps anything+ * @property {string | null} set the project set as `<package>/<set>`+ * @property {string} reason+ * @property {MappedIcon[]} mapped+ * @property {KeptIcon[]} kept+ */++/**+ * Index every installed set's exports: `<module>\0<export>` → the icon it+ * draws and the variant that export draws.+ * @param {DiscoveredIconSet[]} sets+ * @returns {Map<string, SourceIcon>}+ */+function indexSets(sets) {+ /** @type {Map<string, SourceIcon>} */+ const index = new Map();+ const astryx = astryxDefinitionsByName();+ for (const set of sets) {+ const byIcon = definitionsByIcon(set.data);+ for (const icon of set.data.icons) {+ const module = icon.module ?? set.data.module;+ const base = {+ setName: set.name,+ id: icon.id,+ // Only Astryx's definitions map between sets: a set's own definition is+ // its own vocabulary, and Astryx's wins a shared name.+ definitions: (byIcon.get(icon.id) ?? []).filter(name =>+ astryx.has(name),+ ),+ set,+ };+ const key = `${module}\0${icon.export}`;+ if (!index.has(key)) {+ const variant = set.data.default?.variant;+ index.set(key, {+ ...base,+ export: icon.export,+ ...(variant ? {variant} : {}),+ });+ }+ for (const entry of icon.variants ?? []) {+ const variantKey = `${entry.module ?? module}\0${entry.export}`;+ if (!index.has(variantKey)) {+ index.set(variantKey, {+ ...base,+ export: entry.export,+ variant: entry.variant,+ });+ }+ }+ }+ }+ return index;+}++/**+ * The target-set icon whose reviewed `matches` name the source icon with one+ * of `confidences`, ties broken by the order the confidences are given and+ * then by id. A match with a `variant` names only that variant of its set; a+ * match without one names every variant.+ * @param {SourceIcon} source+ * @param {DiscoveredIconSet} target+ * @param {readonly string[]} confidences+ * @returns {IconSetIcon | null}+ */+export function reviewedMatch(source, target, confidences) {+ /** @type {{icon: IconSetIcon, rank: number} | null} */+ let best = null;+ for (const icon of target.data.icons) {+ for (const match of icon.matches ?? []) {+ const rank = confidences.indexOf(match.confidence);+ if (+ rank === -1 ||+ match.set !== source.setName ||+ match.export !== source.export ||+ (match.variant != null && match.variant !== source.variant)+ ) {+ continue;+ }+ if (+ !best ||+ rank < best.rank ||+ (rank === best.rank && icon.id < best.icon.id)+ ) {+ best = {icon, rank};+ }+ }+ }+ return best?.icon ?? null;+}++/**+ * The project-set icon a source icon maps to (FR9), or null: a reviewed+ * `exact` or `strong` match, then the icon the project set's `map` names for+ * an Astryx definition the source draws.+ * @param {SourceIcon} source+ * @param {DiscoveredIconSet} target+ * @returns {{icon: IconSetIcon, by: 'match' | 'definition'} | null}+ */+export function matchIcon(source, target) {+ const reviewed = source.setName+ ? reviewedMatch(source, target, ['exact', 'strong'])+ : null;+ if (reviewed) return {icon: reviewed, by: 'match'};+ const icons = target.data.icons;+ for (const name of source.definitions) {+ const id = target.data.map?.[name];+ const icon = id == null ? undefined : icons.find(each => each.id === id);+ if (icon) return {icon, by: 'definition'};+ }+ return null;+}++/**+ * The export a mapped icon uses: the target's variant of the source's+ * variant name when it has one, else the default.+ * @param {IconSetIcon} icon+ * @param {DiscoveredIconSet} set+ * @param {string | undefined} variant+ */+function targetExport(icon, set, variant) {+ const module = icon.module ?? set.data.module;+ if (variant && variant !== set.data.default?.variant) {+ const entry = (icon.variants ?? []).find(each => each.variant === variant);+ if (entry) {+ return {module: entry.module ?? module, export: entry.export};+ }+ }+ return {module, export: icon.export};+}++/** @param {string} source */+function parseSource(source) {+ return parse(source, {+ sourceType: 'module',+ plugins: ['jsx', 'typescript'],+ errorRecovery: false,+ });+}++/**+ * Every node in the tree, with its parent and the key it sits under.+ * @param {any} node+ * @param {(node: any, parent: any, key: string) => void} visit+ * @param {any} [parent]+ * @param {string} [key]+ */+function walk(node, visit, parent = null, key = '') {+ if (Array.isArray(node)) {+ for (const child of node) walk(child, visit, parent, key);+ return;+ }+ if (+ node == null ||+ typeof node !== 'object' ||+ typeof node.type !== 'string'+ ) {+ return;+ }+ visit(node, parent, key);+ for (const childKey of Object.keys(node)) {+ if (+ childKey === 'loc' ||+ childKey === 'extra' ||+ childKey.endsWith('Comments') ||+ childKey === 'comments' ||+ childKey === 'tokens'+ ) {+ continue;+ }+ const child = node[childKey];+ if (child != null && typeof child === 'object') {+ walk(child, visit, node, childKey);+ }+ }+}++/**+ * Whether an identifier node is a reference to a binding, not a property+ * name or a JSX attribute name.+ * @param {any} node+ * @param {any} parent+ * @param {string} key+ */+function isReference(node, parent, key) {+ if (!parent) return true;+ switch (parent.type) {+ case 'ImportSpecifier':+ case 'ImportDefaultSpecifier':+ case 'ImportNamespaceSpecifier':+ return false;+ case 'MemberExpression':+ case 'OptionalMemberExpression':+ return key !== 'property' || parent.computed;+ case 'ObjectProperty':+ return key === 'value' || parent.computed;+ case 'ObjectMethod':+ case 'ClassMethod':+ case 'ClassProperty':+ return key !== 'key' || parent.computed;+ case 'JSXAttribute':+ return false;+ case 'JSXMemberExpression':+ return key === 'object';+ case 'TSPropertySignature':+ return key !== 'key';+ default:+ return true;+ }+}++/**+ * Whether a module is one of Astryx's own packages (`@astryxdesign/core`,+ * its subpaths, and every other `@astryxdesign/` package).+ * @param {string} module+ */+function isAstryxModule(module) {+ return module.startsWith('@astryxdesign/');+}++/**+ * The name an import specifier reads from its module: `default` for a+ * default import, `*` for a namespace import.+ * @param {any} specifier+ */+function importedName(specifier) {+ if (specifier.type === 'ImportDefaultSpecifier') return 'default';+ if (specifier.type === 'ImportNamespaceSpecifier') return '*';+ return specifier.imported.name ?? specifier.imported.value;+}++/**+ * The key a template's `icons` uses for one import specifier: the name a+ * named import reads, or the local name of a default or namespace import.+ * @param {any} specifier+ */+function declaredKey(specifier) {+ return specifier.type === 'ImportSpecifier'+ ? importedName(specifier)+ : specifier.local.name;+}++/**+ * Every binding in a parsed module that a declared key can name: each import+ * specifier (with whether it is type-only) and each named re-export.+ * @param {any} ast+ * @returns {Array<{key: string, module: string, export: string, form: 'named' | 'default' | 'namespace' | 'type' | 're-export'}>}+ */+function iconBindings(ast) {+ /** @type {Array<{key: string, module: string, export: string, form: 'named' | 'default' | 'namespace' | 'type' | 're-export'}>} */+ const found = [];+ for (const node of ast.program.body) {+ if (node.type === 'ImportDeclaration') {+ const module = String(node.source.value);+ for (const specifier of node.specifiers ?? []) {+ const typeOnly =+ node.importKind === 'type' || specifier.importKind === 'type';+ found.push({+ key: declaredKey(specifier),+ module,+ export: importedName(specifier),+ form: typeOnly+ ? 'type'+ : specifier.type === 'ImportDefaultSpecifier'+ ? 'default'+ : specifier.type === 'ImportNamespaceSpecifier'+ ? 'namespace'+ : 'named',+ });+ }+ } else if (node.type === 'ExportNamedDeclaration' && node.source) {+ const module = String(node.source.value);+ for (const specifier of node.specifiers ?? []) {+ const local = specifier.local?.name ?? specifier.local?.value;+ const exported = specifier.exported?.name ?? specifier.exported?.value;+ for (const key of new Set([local, exported])) {+ if (typeof key === 'string') {+ found.push({key, module, export: key, form: 're-export'});+ }+ }+ }+ }+ }+ return found;+}++/**+ * The keys of a template's `icons` that its source binds by no import or+ * re-export at all, so they can never map (`integration check` lists them).+ * Null when the source does not parse.+ * @param {string} source+ * @param {Record<string, string>} declared+ * @returns {string[] | null}+ */+export function iconsNotImported(source, declared) {+ let ast;+ try {+ ast = parseSource(source);+ } catch {+ return null;+ }+ const keys = new Set(iconBindings(ast).map(binding => binding.key));+ return Object.keys(declared).filter(key => !keys.has(key));+}++/** What a template reads with no icon-set state given: nothing is mapped. */+export const NO_ICON_SETS = Object.freeze({+ sets: [],+ choice: /** @type {IconSetChoice} */ ({+ status: 'none',+ reason: 'No icon set is installed.',+ }),+});++/**+ * Rewrite a template's icon imports to the project's icon set (FR9, FR10).+ * @param {string} source+ * @param {{sets: DiscoveredIconSet[], choice: IconSetChoice}} iconSets+ * @param {Record<string, string>} [declared] the template's `icons`: the+ * icon definition each imported icon draws, by its imported name+ * @returns {{source: string, icons: TemplateIconsReport | undefined}} `icons`+ * is undefined, and the source unchanged, when no set is given and none is+ * configured, as for every project without the opt-in, whose state carries+ * no sets: icon sets are experimental (spec:AST-017 FR27), so a+ * project that does not use them gets exactly the output it always has.+ */+export function mapTemplateIcons(source, {sets, choice}, declared = {}) {+ if (sets.length === 0 && choice.configured == null) {+ return {source, icons: undefined};+ }+ const target = choice.set ?? null;+ /** @type {TemplateIconsReport} */+ const icons = {+ status: choice.status,+ set: target ? `${target.package}/${target.name}` : null,+ reason: choice.reason,+ mapped: [],+ kept: [],+ };+ if (!target) return {source, icons};++ /** @type {any} */+ let ast;+ try {+ ast = parseSource(source);+ } catch {+ return {source, icons};+ }+ const index = indexSets(sets);+ const targetModules = new Set(+ target.data.icons.flatMap(icon => [+ icon.module ?? target.data.module,+ ...(icon.variants ?? []).map(+ variant => variant.module ?? icon.module ?? target.data.module,+ ),+ ]),+ );++ /** Every name the file writes, to keep aliases collision-free. */+ const written = new Set();+ walk(ast.program, (node, parent, key) => {+ // The name an import specifier reads from its module binds nothing here.+ if (parent?.type === 'ImportSpecifier' && key === 'imported') return;+ if (node.type === 'Identifier' || node.type === 'JSXIdentifier') {+ written.add(node.name);+ }+ });++ /** @type {Array<{start: number, end: number, text: string}>} */+ const edits = [];+ /** @type {Map<string, string>} old local name → new local name */+ const renames = new Map();+ /** @type {Map<string, {module: string, imported: string, local: string}>} */+ const added = new Map();+ /**+ * Every local name whose import maps away, found first, so a mapped name+ * may reuse a name another mapped import frees.+ * @type {Set<string>}+ */+ const freed = new Set();+ /**+ * The source record and the match of each mapped import specifier.+ * @type {Map<any, {record: SourceIcon, match: ReturnType<typeof matchIcon>}>}+ */+ const planned = new Map();+ for (const node of ast.program.body) {+ if (node.type !== 'ImportDeclaration' || node.importKind === 'type')+ continue;+ const module = node.source.value;+ if (targetModules.has(module)) continue;+ for (const specifier of node.specifiers) {+ if (+ specifier.type === 'ImportNamespaceSpecifier' ||+ specifier.importKind === 'type'+ ) {+ continue;+ }+ const imported = importedName(specifier);+ const key = declaredKey(specifier);+ const fromSet = index.get(`${module}\0${imported}`);+ // A declared name is the export a template imports from an icon+ // library. Astryx's own packages ship components, not icons, so a+ // declaration never matches an import from one (Core's `Table` is not+ // the icon a template imports as `Table as TableIcon`); an installed+ // set's icons are matched through the set instead.+ const meant =+ !isAstryxModule(module) && Object.hasOwn(declared, key)+ ? declared[key]+ : null;+ /** @type {SourceIcon | null} */+ const record = fromSet+ ? {+ ...fromSet,+ definitions: [+ ...new Set([...(meant ? [meant] : []), ...fromSet.definitions]),+ ],+ }+ : meant+ ? {+ setName: null,+ export: imported,+ id: key,+ definitions: [meant],+ }+ : null;+ if (!record || record.set === target) continue;+ const match = matchIcon(record, target);+ planned.set(specifier, {record, match});+ if (match) freed.add(specifier.local.name);+ }+ }+ /** Where the mapped imports go: where the first rewritten import was. */+ let insertAt = -1;+ /** The declared keys reported as mapped or kept so far. */+ const accounted = new Set();++ for (const node of ast.program.body) {+ if (node.type !== 'ImportDeclaration') continue;+ if (node.importKind === 'type') continue;+ const module = node.source.value;+ if (targetModules.has(module)) continue;+ if (!node.specifiers.some((/** @type {any} */ each) => planned.has(each))) {+ continue;+ }++ /** @type {any[]} */+ const keep = [];+ for (const specifier of node.specifiers) {+ const plan = planned.get(specifier);+ if (!plan) {+ keep.push(specifier);+ continue;+ }+ const imported = importedName(specifier);+ const local = specifier.local.name;+ const {record, match} = plan;+ accounted.add(declaredKey(specifier));+ if (!match) {+ keep.push(specifier);+ const likely = reviewedMatch(record, target, ['likely']);+ icons.kept.push({+ module,+ export: imported,+ reason:+ record.definitions.length > 0+ ? `${icons.set} maps no icon to the icon definition "${record.definitions.join('", "')}"${record.setName ? ', and none is a reviewed match for it' : ''}`+ : `no icon in ${icons.set} is a reviewed match for it`,+ ...(likely+ ? {+ suggestion: {+ set: target.name,+ id: likely.id,+ ...targetExport(likely, target, record.variant),+ confidence: /** @type {const} */ ('likely'),+ },+ }+ : {}),+ });+ continue;+ }+ const chosen = targetExport(match.icon, target, record.variant);+ const key = `${chosen.module}\0${chosen.export}`;+ let entry = added.get(key);+ if (!entry) {+ // A default import keeps its local name: it becomes the set's named+ // import under that alias.+ let name =+ specifier.type === 'ImportDefaultSpecifier' ? local : chosen.export;+ const base = name;+ const taken = (/** @type {string} */ candidate) =>+ (written.has(candidate) && !freed.has(candidate)) ||+ [...added.values()].some(each => each.local === candidate);+ for (let n = 2; taken(name); n++) name = `${base}${n}`;+ entry = {module: chosen.module, imported: chosen.export, local: name};+ added.set(key, entry);+ }+ if (local !== entry.local) renames.set(local, entry.local);+ icons.mapped.push({+ source: {module, export: imported},+ target: {+ set: target.name,+ package: target.package,+ id: match.icon.id,+ module: chosen.module,+ export: chosen.export,+ },+ by: match.by,+ });+ }++ if (keep.length === node.specifiers.length) continue;+ if (insertAt === -1) insertAt = node.start;+ if (keep.length === 0) {+ let end = node.end;+ if (source[end] === '\n') end += 1;+ edits.push({start: node.start, end, text: ''});+ } else {+ const defaults = keep.filter(each => each.type !== 'ImportSpecifier');+ const named = keep.filter(each => each.type === 'ImportSpecifier');+ const parts = [+ ...defaults.map(each => source.slice(each.start, each.end)),+ ...(named.length > 0+ ? [+ `{${named.map(each => source.slice(each.start, each.end)).join(', ')}}`,+ ]+ : []),+ ];+ edits.push({+ start: node.start,+ end: node.end,+ text: `import ${parts.join(', ')} from ${source.slice(node.source.start, node.source.end)};`,+ });+ }+ }++ // Every other declared key is kept, with why it was not mapped (FR10).+ const bindings = iconBindings(ast);+ for (const key of Object.keys(declared)) {+ if (accounted.has(key)) continue;+ const forms = bindings.filter(binding => binding.key === key);+ const pick = (+ /** @type {(each: (typeof forms)[number]) => boolean} */ test,+ ) => forms.find(test);+ const fromTarget = pick(each => targetModules.has(each.module));+ const fromAstryx = pick(each => isAstryxModule(each.module));+ const namespace = pick(each => each.form === 'namespace');+ const typeOnly = pick(each => each.form === 'type');+ const reExport = pick(each => each.form === 're-export');+ const [binding, reason] = fromTarget+ ? [fromTarget, `it is already imported from ${icons.set}`]+ : namespace+ ? [+ namespace,+ 'it is a namespace import, which is not mapped: import the icon by name',+ ]+ : reExport+ ? [+ reExport,+ 'the template re-exports it rather than importing it, so it is not mapped',+ ]+ : typeOnly+ ? [typeOnly, 'it is a type-only import, which draws no icon']+ : fromAstryx+ ? [+ fromAstryx,+ 'it is imported from an Astryx package, which ships components, not icons',+ ]+ : [null, 'the template does not import it'];+ icons.kept.push({+ module: binding ? binding.module : null,+ export: binding ? binding.export : key,+ reason,+ });+ }++ if (added.size === 0) return {source, icons};++ // Every reference to a renamed binding uses the mapped name.+ walk(ast.program, (node, parent, key) => {+ if (node.type === 'Identifier' || node.type === 'JSXIdentifier') {+ const next = renames.get(node.name);+ if (!next || !isReference(node, parent, key)) return;+ if (parent?.type === 'ObjectProperty' && parent.shorthand) {+ edits.push({+ start: node.start,+ end: node.end,+ text: `${node.name}: ${next}`,+ });+ return;+ }+ edits.push({start: node.start, end: node.end, text: next});+ }+ });+ // A shorthand property is visited as both key and value; keep one edit.+ const unique = new Map();+ for (const edit of edits) {+ const at = `${edit.start}:${edit.end}`;+ const prior = unique.get(at);+ if (!prior || edit.text.length > prior.text.length) unique.set(at, edit);+ }++ /** @type {Map<string, string[]>} */+ const byModule = new Map();+ for (const entry of added.values()) {+ const list = byModule.get(entry.module) ?? [];+ list.push(+ entry.local === entry.imported+ ? entry.imported+ : `${entry.imported} as ${entry.local}`,+ );+ byModule.set(entry.module, list);+ }+ const lines = [...byModule.entries()]+ .map(([module, names]) => `import {${names.join(', ')}} from '${module}';`)+ .join('\n');+ unique.set('insert', {start: insertAt, end: insertAt, text: `${lines}\n`});++ let out = source;+ for (const edit of [...unique.values()].sort(+ (a, b) => b.start - a.start || b.end - a.end,+ )) {+ out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);+ }+ return {source: out, icons};+}diff --git a/packages/cli/foundation/discovery/template-icons.test.mjs b/packages/cli/foundation/discovery/template-icons.test.mjsnew file mode 100644index 0000000000..ac41f87533--- /dev/null+++ b/packages/cli/foundation/discovery/template-icons.test.mjs@@ -0,0 +1,457 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Template icon mapping (AST-084 FR9, FR10): a template's declared+ * icon definitions, an installed set's icons and reviewed matches, a kept+ * icon, a variant, a name collision, and no set. Nothing is guessed from+ * names or words.+ */++import {describe, expect, it} from 'vitest';+import {+ iconsNotImported,+ mapTemplateIcons,+ matchIcon,+} from './template-icons.mjs';+import {glyphsData} from '../../test-utils/icon-set-fixture.mjs';++const SET = /** @type {any} */ ({+ name: 'glyphs',+ package: '@acme/glyphs',+ data: {+ ...glyphsData(),+ module: '@acme/glyphs',+ map: {close: 'x', search: 'search', delete: 'trash', home: 'home'},+ },+});++/** @type {any} */+const SELECTED = {status: 'selected', set: SET, reason: 'only set'};++/**+ * @param {string} source+ * @param {Record<string, string>} [declared]+ * @param {any} [choice]+ * @param {any[]} [sets]+ */+const map = (source, declared = {}, choice = SELECTED, sets = [SET]) =>+ mapTemplateIcons(source, {sets, choice}, declared);++describe('matchIcon', () => {+ it("maps by the project set's map for the declared definition, and never by name", () => {+ expect(+ matchIcon(+ {+ setName: null,+ export: 'BinIcon',+ id: 'BinIcon',+ definitions: ['delete'],+ },+ SET,+ ),+ ).toMatchObject({by: 'definition', icon: {id: 'trash'}});+ // Same id as a set icon, but no definition: not mapped.+ expect(+ matchIcon(+ {setName: null, export: 'HomeIcon', id: 'home', definitions: []},+ SET,+ ),+ ).toBeNull();+ // A definition the set does not map: not mapped.+ expect(+ matchIcon(+ {+ setName: null,+ export: 'PencilIcon',+ id: 'PencilIcon',+ definitions: ['edit'],+ },+ SET,+ ),+ ).toBeNull();+ });+});++describe('mapTemplateIcons', () => {+ const SOURCE = [+ "import React from 'react';",+ "import {CloseGlyph, PencilGlyph, HomeGlyph as House} from '@acme/library';",+ "import {BinGlyph} from '@acme/library/solid';",+ '',+ 'export default function Page() {',+ ' const icons = {CloseGlyph};',+ ' return <div><CloseGlyph className="x" /><PencilGlyph /><House /><BinGlyph />{icons.CloseGlyph}</div>;',+ '}',+ '',+ ].join('\n');+ const DECLARED = {+ CloseGlyph: 'close',+ PencilGlyph: 'edit',+ HomeGlyph: 'home',+ BinGlyph: 'delete',+ };++ it('rewrites each declared icon the set maps, every reference too, and keeps the rest', () => {+ const {source, icons} = map(SOURCE, DECLARED);+ expect(source).toContain(+ "import {XIcon, HomeIcon, TrashIcon} from '@acme/glyphs';",+ );+ expect(source).toContain("import {PencilGlyph} from '@acme/library';");+ expect(source).not.toContain('@acme/library/solid');+ expect(source).toContain('<XIcon className="x" />');+ expect(source).toContain('<HomeIcon />');+ expect(source).toContain('<PencilGlyph />');+ // A property name keeps its text; a shorthand property keeps its key.+ expect(source).toContain('const icons = {CloseGlyph: XIcon};');+ expect(source).toContain('{icons.CloseGlyph}');+ expect(icons.status).toBe('selected');+ expect(+ icons.mapped.map(each => [+ each.source.export,+ each.target.export,+ each.by,+ ]),+ ).toEqual([+ ['CloseGlyph', 'XIcon', 'definition'],+ ['HomeGlyph', 'HomeIcon', 'definition'],+ ['BinGlyph', 'TrashIcon', 'definition'],+ ]);+ expect(icons.kept).toEqual([+ expect.objectContaining({+ module: '@acme/library',+ export: 'PencilGlyph',+ reason: expect.stringContaining('"edit"'),+ }),+ ]);+ });++ it('an undeclared import is not an icon: it is left alone and not reported', () => {+ const source =+ "import {CloseGlyph} from '@acme/library';\nexport const A = () => <CloseGlyph />;\n";+ expect(map(source)).toEqual({+ source,+ icons: expect.objectContaining({mapped: [], kept: []}),+ });+ });++ it("a declaration never matches an import from an Astryx package: Core's Table stays", () => {+ const source = [+ "import {Table} from '@astryxdesign/core/Table';",+ "import {Table as TableIcon, CloseGlyph} from '@acme/library';",+ 'export const A = () => <Table icon={TableIcon} close={CloseGlyph} />;',+ '',+ ].join('\n');+ const declared = {Table: 'search', CloseGlyph: 'close'};+ const {source: out, icons} = map(source, declared);+ expect(out).toContain("import {Table} from '@astryxdesign/core/Table';");+ expect(out).toContain("import {SearchIcon, XIcon} from '@acme/glyphs';");+ expect(out).not.toContain('@acme/library');+ expect(out).toContain('<Table icon={SearchIcon} close={XIcon} />');+ expect(+ icons.mapped.map(each => [each.source.module, each.source.export]),+ ).toEqual([+ ['@acme/library', 'Table'],+ ['@acme/library', 'CloseGlyph'],+ ]);+ });++ it('imports under an alias when the mapped name is taken', () => {+ const {source} = map(+ "import {CloseGlyph} from '@acme/library';\nconst XIcon = 1;\nexport const A = () => <CloseGlyph />;\n",+ {CloseGlyph: 'close'},+ );+ expect(source).toContain("import {XIcon as XIcon2} from '@acme/glyphs';");+ expect(source).toContain('<XIcon2 />');+ expect(source).toContain('const XIcon = 1;');+ });++ it('without a project icon set the source is unchanged and the report says why', () => {+ for (const status of ['none', 'ambiguous']) {+ const {source, icons} = map(SOURCE, DECLARED, {status, reason: 'why'});+ expect(source).toBe(SOURCE);+ expect(icons).toEqual({+ status,+ set: null,+ reason: 'why',+ mapped: [],+ kept: [],+ });+ }+ });++ it('leaves imports from the project set alone, and reports them as kept', () => {+ const source =+ "import {XIcon} from '@acme/glyphs';\nexport const A = () => <XIcon />;\n";+ expect(map(source, {XIcon: 'close'})).toEqual({+ source,+ icons: expect.objectContaining({+ mapped: [],+ kept: [+ {+ module: '@acme/glyphs',+ export: 'XIcon',+ reason: 'it is already imported from @acme/glyphs/glyphs',+ },+ ],+ }),+ });+ });+});++describe('every binding form a declared key can name (FR10)', () => {+ it('a named import maps by the name it imports', () => {+ const {source, icons} = map(+ "import {BinGlyph} from '@acme/library';\nexport const A = () => <BinGlyph />;\n",+ {BinGlyph: 'delete'},+ );+ expect(source).toContain("import {TrashIcon} from '@acme/glyphs';");+ expect(source).toContain('<TrashIcon />');+ expect(icons?.mapped).toHaveLength(1);+ expect(icons?.kept).toEqual([]);+ });++ it('an aliased named import maps by the name it imports, not its local name', () => {+ const {source, icons} = map(+ "import {BinGlyph as Bin} from '@acme/library';\nexport const A = () => <Bin />;\n",+ {BinGlyph: 'delete'},+ );+ expect(source).toContain("import {TrashIcon} from '@acme/glyphs';");+ expect(source).toContain('<TrashIcon />');+ expect(icons?.mapped[0].source).toEqual({+ module: '@acme/library',+ export: 'BinGlyph',+ });+ // Its local name is not a key.+ expect(+ map(+ "import {BinGlyph as Bin} from '@acme/library';\nexport const A = () => <Bin />;\n",+ {Bin: 'delete'},+ ).icons?.kept,+ ).toEqual([+ {module: null, export: 'Bin', reason: 'the template does not import it'},+ ]);+ });++ it("a default import maps by its local name, to the set's named import under that name", () => {+ const {source, icons} = map(+ "import DeleteIcon from '@mui/icons-material/Delete';\nexport const A = () => <DeleteIcon />;\n",+ {DeleteIcon: 'delete'},+ );+ expect(source).toBe(+ "import {TrashIcon as DeleteIcon} from '@acme/glyphs';\nexport const A = () => <DeleteIcon />;\n",+ );+ expect(icons?.mapped).toEqual([+ expect.objectContaining({+ source: {module: '@mui/icons-material/Delete', export: 'default'},+ target: expect.objectContaining({export: 'TrashIcon'}),+ by: 'definition',+ }),+ ]);+ expect(icons?.kept).toEqual([]);+ });++ it('a default import beside named ones keeps the rest of its import', () => {+ const {source} = map(+ "import DeleteIcon, {useThing} from '@acme/library';\nexport const A = () => <DeleteIcon />;\n",+ {DeleteIcon: 'delete'},+ );+ expect(source).toContain(+ "import {TrashIcon as DeleteIcon} from '@acme/glyphs';",+ );+ expect(source).toContain("import {useThing} from '@acme/library';");+ });++ it('a default import the set cannot map is kept', () => {+ expect(+ map(+ "import PencilIcon from '@acme/library/pencil';\nexport const A = () => <PencilIcon />;\n",+ {PencilIcon: 'edit'},+ ).icons?.kept,+ ).toEqual([+ expect.objectContaining({+ module: '@acme/library/pencil',+ export: 'default',+ reason: expect.stringContaining('"edit"'),+ }),+ ]);+ });++ it('a namespace import is kept, with why', () => {+ const source =+ "import * as Icons from '@acme/library';\nexport const A = () => <Icons.BinGlyph />;\n";+ const result = map(source, {Icons: 'delete'});+ expect(result.source).toBe(source);+ expect(result.icons?.kept).toEqual([+ {+ module: '@acme/library',+ export: '*',+ reason:+ 'it is a namespace import, which is not mapped: import the icon by name',+ },+ ]);+ });++ it('a side-effect import binds nothing: the key is not imported', () => {+ const source =+ "import '@acme/library/styles.css';\nexport const A = () => null;\n";+ const result = map(source, {BinGlyph: 'delete'});+ expect(result.source).toBe(source);+ expect(result.icons?.kept).toEqual([+ {+ module: null,+ export: 'BinGlyph',+ reason: 'the template does not import it',+ },+ ]);+ });++ it('a re-export is kept, with why', () => {+ const source =+ "export {BinGlyph} from '@acme/library';\nexport const A = () => null;\n";+ const result = map(source, {BinGlyph: 'delete'});+ expect(result.source).toBe(source);+ expect(result.icons?.kept).toEqual([+ {+ module: '@acme/library',+ export: 'BinGlyph',+ reason:+ 'the template re-exports it rather than importing it, so it is not mapped',+ },+ ]);+ });++ it('a type-only import is kept, with why', () => {+ for (const line of [+ "import type {BinGlyph} from '@acme/library';",+ "import {type BinGlyph} from '@acme/library';",+ ]) {+ const source = `${line}\nexport const A = (p: BinGlyph) => null;\n`;+ const result = map(source, {BinGlyph: 'delete'});+ expect(result.source).toBe(source);+ expect(result.icons?.kept).toEqual([+ {+ module: '@acme/library',+ export: 'BinGlyph',+ reason: 'it is a type-only import, which draws no icon',+ },+ ]);+ }+ });++ it('an import from an Astryx package only is kept, with why', () => {+ const source =+ "import {Table} from '@astryxdesign/core/Table';\nexport const A = () => <Table />;\n";+ expect(map(source, {Table: 'table'}).icons?.kept).toEqual([+ {+ module: '@astryxdesign/core/Table',+ export: 'Table',+ reason:+ 'it is imported from an Astryx package, which ships components, not icons',+ },+ ]);+ });++ it('iconsNotImported lists the keys no import or re-export binds', () => {+ const source = [+ "import '@acme/side-effect';",+ "import Def from 'a';",+ "import * as Ns from 'b';",+ "import {Named as Local} from 'c';",+ "import type {Typed} from 'd';",+ "export {Again} from 'e';",+ 'export const A = () => null;',+ '',+ ].join('\n');+ expect(+ iconsNotImported(source, {+ Def: 'a',+ Ns: 'b',+ Named: 'c',+ Local: 'c',+ Typed: 'd',+ Again: 'e',+ Missing: 'f',+ }),+ ).toEqual(['Local', 'Missing']);+ expect(iconsNotImported('not ( valid', {X: 'y'})).toBeNull();+ });+});++describe('icons another installed set ships', () => {+ const OTHER = /** @type {any} */ ({+ name: 'lines',+ package: '@acme/lines',+ data: {+ schemaVersion: 1,+ module: '@acme/lines',+ variants: ['outline', 'solid'],+ default: {variant: 'outline'},+ map: {close: 'cross'},+ icons: [+ {+ id: 'cross',+ export: 'CrossIcon',+ words: ['cross'],+ variants: [{variant: 'solid', export: 'CrossSolidIcon'}],+ },+ {id: 'bin', export: 'BinIcon', words: ['bin']},+ ],+ },+ });++ it("maps by the source set's map, with no declaration, and keeps the variant", () => {+ const {source, icons} = map(+ "import {CrossIcon, CrossSolidIcon, BinIcon} from '@acme/lines';\nexport const A = () => <><CrossIcon /><CrossSolidIcon /><BinIcon /></>;\n",+ {},+ SELECTED,+ [SET, OTHER],+ );+ expect(+ icons.mapped.map(each => [each.source.export, each.target.export]),+ ).toEqual([+ ['CrossIcon', 'XIcon'],+ ['CrossSolidIcon', 'XIcon'],+ ]);+ // bin draws no definition the lines set maps: kept.+ expect(icons.kept.map(each => each.export)).toEqual(['BinIcon']);+ expect(source).toContain("import {BinIcon} from '@acme/lines';");+ });++ it('a reviewed exact match beats the definition, and a likely one is only suggested', () => {+ const REVIEWED = /** @type {any} */ ({+ ...SET,+ data: {+ ...SET.data,+ icons: SET.data.icons.map((/** @type {any} */ icon) =>+ icon.id === 'home'+ ? {+ ...icon,+ matches: [+ {set: 'lines', export: 'CrossIcon', confidence: 'exact'},+ {set: 'lines', export: 'BinIcon', confidence: 'likely'},+ ],+ }+ : icon,+ ),+ },+ });+ const {icons} = map(+ "import {CrossIcon, BinIcon} from '@acme/lines';\nexport const A = () => <><CrossIcon /><BinIcon /></>;\n",+ {},+ {status: 'selected', set: REVIEWED, reason: 'only set'},+ [REVIEWED, OTHER],+ );+ expect(icons.mapped).toEqual([+ expect.objectContaining({+ target: expect.objectContaining({id: 'home'}),+ by: 'match',+ }),+ ]);+ expect(icons.kept).toEqual([+ expect.objectContaining({+ export: 'BinIcon',+ suggestion: expect.objectContaining({id: 'home', confidence: 'likely'}),+ }),+ ]);+ });+});diff --git a/packages/cli/foundation/discovery/theme-discovery.mjs b/packages/cli/foundation/discovery/theme-discovery.mjsindex 24afc0cd65..e12118d763 100644--- a/packages/cli/foundation/discovery/theme-discovery.mjs+++ b/packages/cli/foundation/discovery/theme-discovery.mjs@@ -547,6 +547,67 @@ function staticThemeValue(node, label) {);}+/**+ * Convert one static literal of a data descriptor (an icon definition): a+ * string, a boolean, or an array or plain object of those.+ * @param {any} node+ * @param {string} label+ * @returns {unknown}+ */+function staticDataValue(node, label) {+ if (node?.type === 'StringLiteral' || node?.type === 'BooleanLiteral') {+ return node.value;+ }+ if (node?.type === 'ArrayExpression') {+ return node.elements.map((/** @type {any} */ element) =>+ staticDataValue(unparenthesized(element), label),+ );+ }+ if (node?.type === 'ObjectExpression') {+ return staticObject(node, label, staticDataValue);+ }+ throw new Error(+ `${label} must use static strings, booleans, arrays, and objects in its default export.`,+ );+}++/**+ * A static object literal, every value converted by `convert`.+ * @param {any} object+ * @param {string} label+ * @param {(node: any, label: string) => unknown} convert+ * @returns {Record<string, any>}+ */+function staticObject(object, label, convert) {+ /** @type {Record<string, any>} */+ const value = {};+ for (const property of object.properties) {+ if (property.type !== 'ObjectProperty' || property.computed) {+ throw new Error(`${label} must contain only static object properties.`);+ }+ const key =+ property.key.type === 'Identifier'+ ? property.key.name+ : property.key.type === 'StringLiteral'+ ? property.key.value+ : null;+ if (key === null) {+ throw new Error(`${label} has an invalid property name.`);+ }+ if (Object.hasOwn(value, key)) {+ throw new Error(`${label} declares "${key}" more than once.`);+ }+ // Defined, not assigned, so `__proto__` stays a key the parser rejects.+ Object.defineProperty(value, key, {+ value: convert(unparenthesized(property.value), label),+ enumerable: true,+ writable: true,+ configurable: true,+ });+ }+ return value;+}+/*** How messages about a theme descriptor name it.* @param {string} docPath@@ -583,7 +644,7 @@ function readThemeDoc(docPath, owner) {/*** Descriptor reads in this process, by path and label, reused while the file* keeps its size and mtime.- * @type {Map<string, {size: number, mtimeMs: number, read: {value: Record<string, string | boolean>} | {error: unknown}}>}+ * @type {Map<string, {size: number, mtimeMs: number, read: {value: Record<string, any>} | {error: unknown}}>}*/const descriptorReads = new Map();@@ -596,15 +657,41 @@ const descriptorReads = new Map();* @returns {Record<string, string | boolean>}*/export function readThemeDescriptorValue(docPath, label) {+ return readStaticDescriptorValue(docPath, label, 'ThemeDoc');+}++/**+ * The static value a typed descriptor default-exports, read from its source+ * without executing it. Throws when the file is not one static object typed+ * with `typeName` from `@astryxdesign/cli/authoring`. Theme and icon-set+ * descriptors share this reader.+ * @param {string} docPath+ * @param {string} label+ * @param {string} typeName the public authoring type, such as `ThemeDoc`+ * @param {{data?: boolean}} [options] `data`: also accept arrays and plain+ * objects of static values (icon definitions)+ * @returns {Record<string, any>}+ */+export function readStaticDescriptorValue(+ docPath,+ label,+ typeName,+ {data = false} = {},+) {const {size, mtimeMs} = fs.statSync(docPath);- const key = `${docPath}\0${label}`;+ const key = `${docPath}\0${label}\0${typeName}\0${data}`;let cached = descriptorReads.get(key);if (!cached || cached.size !== size || cached.mtimeMs !== mtimeMs) {- /** @type {{value: Record<string, string | boolean>} | {error: unknown}} */+ /** @type {{value: Record<string, any>} | {error: unknown}} */let read;try {read = {- value: readDescriptorSource(fs.readFileSync(docPath, 'utf-8'), label),+ value: readDescriptorSource(+ fs.readFileSync(docPath, 'utf-8'),+ label,+ typeName,+ data,+ ),};} catch (error) {read = {error};@@ -613,15 +700,17 @@ export function readThemeDescriptorValue(docPath, label) {descriptorReads.set(key, cached);}if ('error' in cached.read) throw cached.read.error;- return {...cached.read.value};+ return data ? structuredClone(cached.read.value) : {...cached.read.value};}/*** @param {string} source* @param {string} label- * @returns {Record<string, string | boolean>}+ * @param {string} typeName+ * @param {boolean} [data]+ * @returns {Record<string, any>}*/-function readDescriptorSource(source, label) {+function readDescriptorSource(source, label, typeName, data = false) {/** @type {any} */let ast;try {@@ -647,52 +736,34 @@ function readDescriptorSource(source, label) {);if (unsupported.length > 0 || ast.program.directives.length > 0) {throw new Error(- `${label} must contain only its static default-exported ThemeDoc object.`,+ `${label} must contain only its static default-exported ${typeName} object.`,);}const object =defaults.length === 1 && unparenthesized(defaults[0].declaration);if (object?.type !== 'ObjectExpression') {- throw new Error(`${label} must default-export one static ThemeDoc object.`);+ throw new Error(+ `${label} must default-export one static ${typeName} object.`,+ );}- if (!declaresThemeDoc(ast, defaults[0])) {+ if (!declaresDocType(ast, defaults[0], typeName)) {throw new Error(- `${label} must declare its public ThemeDoc type from @astryxdesign/cli/authoring.`,+ `${label} must declare its public ${typeName} type from @astryxdesign/cli/authoring.`,);}- /** @type {Record<string, string | boolean>} */- const value = {};- for (const property of object.properties) {- if (property.type !== 'ObjectProperty' || property.computed) {- throw new Error(`${label} must contain only static object properties.`);- }- const key =- property.key.type === 'Identifier'- ? property.key.name- : property.key.type === 'StringLiteral'- ? property.key.value- : null;- if (key === null) {- throw new Error(`${label} has an invalid property name.`);- }- if (Object.hasOwn(value, key)) {- throw new Error(`${label} declares "${key}" more than once.`);- }- // Defined, not assigned, so `__proto__` stays a key the parser rejects.- Object.defineProperty(value, key, {- value: staticThemeValue(unparenthesized(property.value), label),- enumerable: true,- writable: true,- configurable: true,- });- }- return value;+ return staticObject(object, label, data ? staticDataValue : staticThemeValue);}-/** `import('@astryxdesign/cli/authoring').ThemeDoc`, without whitespace. */-const THEME_DOC_TYPE =- /^import\((['"])@astryxdesign\/cli\/authoring\1\)\.ThemeDoc$/u;+/**+ * `import('@astryxdesign/cli/authoring').<typeName>`, without whitespace.+ * @param {string} typeName+ */+const authoringTypeRe = typeName =>+ new RegExp(+ String.raw`^import\((['"])@astryxdesign\/cli\/authoring\1\)\.${typeName}$`,+ 'u',+ );/** @param {any} comment */function isJsdoc(comment) {@@ -835,15 +906,16 @@ function wrappedInParens(type) {/*** Whether a JSDoc type, whitespace removed, checks an object literal exactly- * as ThemeDoc does: ThemeDoc or one of its aliases, optionally parenthesized,- * marked `!`, `?` or `=`, joined with `null` or `undefined`, or intersected- * with `{}`.+ * as `typeName` does: the type or one of its aliases, optionally+ * parenthesized, marked `!`, `?` or `=`, joined with `null` or `undefined`, or+ * intersected with `{}`.* @param {string} type* @param {Map<string, string>} aliases alias name to the type it names+ * @param {string} typeName* @param {Set<string>} [seen]* @returns {boolean}*/-function isThemeDocType(type, aliases, seen = new Set()) {+function isDocType(type, aliases, typeName, seen = new Set()) {let current = type;for (;;) {if (/^[!?]/u.test(current)) current = current.slice(1);@@ -855,15 +927,17 @@ function isThemeDocType(type, aliases, seen = new Set()) {member => member !== 'null' && member !== 'undefined',);if (members.length !== 1) return false;- if (members[0] !== current) return isThemeDocType(members[0], aliases, seen);+ if (members[0] !== current) {+ return isDocType(members[0], aliases, typeName, seen);+ }const parts = splitType(current, '&').filter(part => part !== '{}');if (parts.length !== 1) return false;- if (parts[0] !== current) return isThemeDocType(parts[0], aliases, seen);- if (THEME_DOC_TYPE.test(current)) return true;+ if (parts[0] !== current) return isDocType(parts[0], aliases, typeName, seen);+ if (authoringTypeRe(typeName).test(current)) return true;const named = aliases.get(current);if (named === undefined || seen.has(current)) return false;seen.add(current);- return isThemeDocType(named, aliases, seen);+ return isDocType(named, aliases, typeName, seen);}const AUTHORING = String.raw`(['"])@astryxdesign\/cli\/authoring\2`;@@ -872,12 +946,13 @@ const AUTHORING = String.raw`(['"])@astryxdesign\/cli\/authoring\2`;* The type names the file's JSDoc binds with `@typedef` or `@import`, from any* JSDoc comment in the module, as TypeScript reads them.* @param {any[]} comments+ * @param {string} typeName* @returns {Map<string, string>}*/-function jsdocAliases(comments) {+function jsdocAliases(comments, typeName) {/** @type {Map<string, string>} */const aliases = new Map();- const theme = "import('@astryxdesign/cli/authoring').ThemeDoc";+ const theme = `import('@astryxdesign/cli/authoring').${typeName}`;for (const comment of comments.filter(isJsdoc)) {for (const tag of jsdocTags(comment.value)) {if (tag.name === 'typedef') {@@ -890,17 +965,17 @@ function jsdocAliases(comments) {'u',).exec(tag.text);for (const specifier of named?.[1].split(',') ?? []) {- const match =- /^\s*(?:type\s+)?ThemeDoc(?:\s+as\s+([$A-Z_a-z][$\w]*))?\s*$/u.exec(- specifier,- );- if (match) aliases.set(match[1] ?? 'ThemeDoc', theme);+ const match = new RegExp(+ String.raw`^\s*(?:type\s+)?${typeName}(?:\s+as\s+([$A-Z_a-z][$\w]*))?\s*$`,+ 'u',+ ).exec(specifier);+ if (match) aliases.set(match[1] ?? typeName, theme);}const namespace = new RegExp(String.raw`^\s*\*\s*as\s+([$A-Z_a-z][$\w]*)\s+from\s*${AUTHORING}`,'u',).exec(tag.text)?.[1];- if (namespace) aliases.set(`${namespace}.ThemeDoc`, theme);+ if (namespace) aliases.set(`${namespace}.${typeName}`, theme);}}}@@ -909,14 +984,15 @@ function jsdocAliases(comments) {/*** Whether the JSDoc TypeScript reads for the default export types it as the- * public ThemeDoc: `@type` in the last JSDoc comment between the previous+ * public `typeName` (such as ThemeDoc): `@type` in the last JSDoc comment between the previous* token and `export`, or `@type` or `@satisfies` in the last one between the* previous token and the opening parenthesis of a JSDoc cast of the object.* Line comments, strings, code spans, and JSDoc anywhere else never type it.* @param {any} ast parsed with tokens and parenthesized expressions* @param {any} exportDefault+ * @param {string} typeName*/-function declaresThemeDoc(ast, exportDefault) {+function declaresDocType(ast, exportDefault, typeName) {const tokens = ast.tokens.filter((/** @type {any} */ token) => typeof token.type !== 'string',);@@ -947,14 +1023,14 @@ function declaresThemeDoc(ast, exportDefault) {tags: ['type', 'satisfies'],});}- const aliases = jsdocAliases(comments);+ const aliases = jsdocAliases(comments, typeName);return attached.some(({comment, tags}) => {if (!comment) return false;const found = jsdocTags(comment.value);return tags.some(name => {const tag = found.find(candidate => candidate.name === name);const typed = tag && bracedType(tag.text);- return typed != null && isThemeDocType(typed.type, aliases);+ return typed != null && isDocType(typed.type, aliases, typeName);});});}diff --git a/packages/cli/foundation/doc-compiler/bundle.mjs b/packages/cli/foundation/doc-compiler/bundle.mjsindex 21755e7813..69b45b5913 100644--- a/packages/cli/foundation/doc-compiler/bundle.mjs+++ b/packages/cli/foundation/doc-compiler/bundle.mjs@@ -14,7 +14,9 @@* Internal to the CLI.*/+import * as path from 'node:path';import {+ readStaticDescriptorValue,readThemeDescriptorValue,themeDescriptorLabel,} from '../discovery/theme-discovery.mjs';@@ -242,6 +244,18 @@ export async function compileDocs(project, {lang = null} = {}) {check: true,...(input.root === 'templates' ? {loader: 'template'} : {}),...(input.root === 'tree' ? {loader: 'native'} : {}),+ ...(input.root === 'icon-definitions'+ ? {+ label: `Icon definition ${path.basename(input.file)} in ${input.owner}`,+ readStatic: () =>+ readStaticDescriptorValue(+ input.file,+ `Icon definition ${path.basename(input.file)} in ${input.owner}`,+ 'IconDefinitionDoc',+ {data: true},+ ),+ }+ : {}),...(input.root === 'themes'? {label: themeDescriptorLabel(input.file, input.owner),diff --git a/packages/cli/foundation/doc-compiler/compile.mjs b/packages/cli/foundation/doc-compiler/compile.mjsindex abb8530b2c..ea94ced833 100644--- a/packages/cli/foundation/doc-compiler/compile.mjs+++ b/packages/cli/foundation/doc-compiler/compile.mjs@@ -23,6 +23,7 @@import {parseTemplate} from '../../authoring/doctypes/template/parse.mjs';import {parseTheme} from '../../authoring/doctypes/theme/parse.mjs';+import {parseIconDefinition} from '../../authoring/doctypes/icon-definition/parse.mjs';import {mergeTopic,problemsInTopic,@@ -68,6 +69,7 @@ export const COMPILED_DOC_KINDS = /** @type {const} */ (['enum','theme','namespace',+ 'icon-definition',]);/**@@ -80,6 +82,7 @@ export const ROOT_KINDS = Object.freeze({hooks: ['function'],templates: ['page', 'block'],themes: ['theme'],+ 'icon-definitions': ['icon-definition'],'self-docs': ['command', 'function', 'schema', 'enum'],tree: ['namespace', 'generic'],});@@ -393,6 +396,7 @@ function applyOverlay(docs, translation) {*/export function parserFor(root) {if (root === 'themes') return parseTheme;+ if (root === 'icon-definitions') return parseIconDefinition;if (root === 'templates') return parseTemplate;return parseReadableDoc;}@@ -492,10 +496,14 @@ export function lowerDoc(input, {check = true, node: wantNode = true} = {}) {const result = {node: null, diagnostics};let view = file.doc;// A theme descriptor is read statically; its parse result is the doc.- if (check || input.root === 'themes') {+ // A theme descriptor and an icon definition are read statically; the parse+ // result is the doc.+ const staticRoot =+ input.root === 'themes' || input.root === 'icon-definitions';+ if (check || staticRoot) {try {const parsed = parserFor(input.root)(file.doc, input.label ?? file.file);- if (input.useParsed || input.root === 'themes') view = parsed;+ if (input.useParsed || staticRoot) view = parsed;} catch (error) {result.failed = true;result.failure = error;diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjsindex dab9b50a2b..2066da3b5f 100644--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs@@ -102,6 +102,27 @@ const RUNNERS = {runs: SELF_DOCS,sites: ['import ../../../api/blog/blog.doc.mjs', 'import ./blog.doc.mjs'],},+ 'clients/cli/commands/experimental/icon.mjs': {+ runs: SELF_DOCS,+ sites: [+ 'import ../../../../api/icon/icon.doc.mjs',+ 'import ../../../../api/icon/iconAdd.doc.mjs',+ 'import ../../../../api/icon/iconMap.doc.mjs',+ 'import ../../../../api/icon/iconNewDefinition.doc.mjs',+ 'import ../../../../api/icon/iconNewSet.doc.mjs',+ 'import ../../../../api/icon/iconUse.doc.mjs',+ 'import ../experimental-icon-add.doc.mjs',+ 'import ../experimental-icon-map.doc.mjs',+ 'import ../experimental-icon-new-definition.doc.mjs',+ 'import ../experimental-icon-new-set.doc.mjs',+ 'import ../experimental-icon-use.doc.mjs',+ 'import ../experimental-icon.doc.mjs',+ ],+ },+ 'clients/cli/commands/experimental/index.mjs': {+ runs: SELF_DOCS,+ sites: ['import ../experimental.doc.mjs'],+ },'clients/cli/commands/manifest.mjs': {runs: SELF_DOCS,sites: ['import ./manifest.doc.mjs'],@@ -276,6 +297,14 @@ const RUNNERS = {runs: "a package's component docs and topics, to read the props, overlays, sections, and replaces/extends they declare",sites: ['importDocModule ×2'],},+ 'foundation/discovery/doc-stability.mjs': {+ runs: "an integration's template docs, to see which set `stability`",+ sites: ['loadTopicModule'],+ },+ 'foundation/discovery/template-icon-notes.mjs': {+ runs: "an integration's template docs, to read the icons each declares",+ sites: ['loadTopicModule'],+ },'foundation/discovery/doc-fluff.mjs': {runs: "the CLI's own guides, to measure the median share of content words a topic's density is compared with",sites: ['builtinGuideFiles'],diff --git a/packages/cli/foundation/doc-compiler/inputs.mjs b/packages/cli/foundation/doc-compiler/inputs.mjsindex 6040460d33..8c883bb2e6 100644--- a/packages/cli/foundation/doc-compiler/inputs.mjs+++ b/packages/cli/foundation/doc-compiler/inputs.mjs@@ -23,6 +23,7 @@ import {} from '../discovery/component-discovery.mjs';import {discoverHooks, findHookDoc} from '../discovery/hook-discovery.mjs';import {themeImportPackage} from '../discovery/theme-discovery.mjs';+import {astryxIconDefinitions} from '../discovery/icon-definition-discovery.mjs';import {CLI_ROOT, findCoreDir} from '../fs/paths.mjs';import {packageSource} from './source.mjs';import {treeDocFiles} from './tree.mjs';@@ -44,7 +45,7 @@ const NON_DESCRIPTOR_DIRS = new Set([]);/**- * @typedef {'components' | 'hooks' | 'templates' | 'themes' | 'docs' | 'self-docs' | 'tree'} DocRoot+ * @typedef {'components' | 'hooks' | 'templates' | 'themes' | 'icon-definitions' | 'docs' | 'self-docs' | 'tree'} DocRoot*//**@@ -140,6 +141,21 @@ export async function collectDocInputs(project) {list.add('themes', theme.slug, themeImportPackage(theme), theme.docPath);}+ // Icon definitions: Astryx's, then each installed set's own.+ for (const {doc, file} of astryxIconDefinitions().definitions) {+ list.add('icon-definitions', doc.name, CLI_PACKAGE, file);+ }+ for (const set of (await project.iconSets()).sets) {+ for (const {doc, file} of set.definitions) {+ list.add(+ 'icon-definitions',+ `${set.name}/${doc.name}`,+ set.package,+ file,+ );+ }+ }+for (const topic of (await project.docs()).entries()) {list.add('docs', topic.name, topic.package, topic.path, 'base');for (const extension of topic.extensions) {diff --git a/packages/cli/foundation/doc-compiler/inputs.test.mjs b/packages/cli/foundation/doc-compiler/inputs.test.mjsindex 2fde9abc42..f690a79b2f 100644--- a/packages/cli/foundation/doc-compiler/inputs.test.mjs+++ b/packages/cli/foundation/doc-compiler/inputs.test.mjs@@ -225,6 +225,7 @@ describe('collectDocInputs problems', () => {components: async () => [],templates: async () => [],themes: async () => [],+ iconSets: async () => ({sets: []}),docs: async () => ({entries: () => []}),...overrides,});diff --git a/packages/cli/foundation/doc-compiler/lower-doc.test.mjs b/packages/cli/foundation/doc-compiler/lower-doc.test.mjsindex 5e3e25529d..c72c1d3ba1 100644--- a/packages/cli/foundation/doc-compiler/lower-doc.test.mjs+++ b/packages/cli/foundation/doc-compiler/lower-doc.test.mjs@@ -386,7 +386,7 @@ describe('parseCompiledDocNode and parseCompiledDocsBundle', () => {it('accepts a node of every kind and a bundle, as given', () => {const value = bundle();expect(parseCompiledDocsBundle(value)).toBe(value);- expect(COMPILED_DOC_KINDS).toHaveLength(10);+ expect(COMPILED_DOC_KINDS).toHaveLength(11);// A namespace doc, which the docs tree reads, lowers to a node too.const namespace = {...node(), kind: 'namespace'};expect(parseCompiledDocNode(namespace)).toBe(namespace);diff --git a/packages/cli/foundation/doc-compiler/read.mjs b/packages/cli/foundation/doc-compiler/read.mjsindex bbeba72275..525feac318 100644--- a/packages/cli/foundation/doc-compiler/read.mjs+++ b/packages/cli/foundation/doc-compiler/read.mjs@@ -61,7 +61,7 @@ const LOADERS = Object.freeze({/*** @typedef {object} ReadOptions- * @property {'components' | 'hooks' | 'templates' | 'themes' | 'self-docs' | 'tree'} root+ * @property {'components' | 'hooks' | 'templates' | 'themes' | 'icon-definitions' | 'self-docs' | 'tree'} root* @property {string | null} [lang] overlay language; null reads the authored* text* @property {string} [label] how a parse error names the file (default: its@@ -74,7 +74,7 @@ const LOADERS = Object.freeze({* @property {readonly string[]} [exports] which exports name the doc, in* precedence order, for a reader that has always read a narrower set than its* root's default ({@link DOC_EXPORTS})- * @property {() => unknown} [readStatic] for themes: the descriptor value, read+ * @property {() => unknown} [readStatic] for themes and icon definitions: the descriptor value, read* without executing the file* @property {'authored' | 'parsed'} [value] which value the view carries: the* authored export (default) or its parser's result, for a reader that has@@ -250,10 +250,10 @@ async function missingDocProblem(file, options, exported) {*/async function loadAuthored(file, options, lang) {const name = path.basename(file);- if (options.root === 'themes') {+ if (options.root === 'themes' || options.root === 'icon-definitions') {if (!options.readStatic) {throw new Error(- 'A theme descriptor is read statically; pass readStatic.',+ 'A theme descriptor or an icon definition is read statically; pass readStatic.',);}try {diff --git a/packages/cli/foundation/doc-compiler/tree.mjs b/packages/cli/foundation/doc-compiler/tree.mjsindex 68c2dcfa55..a1149d0942 100644--- a/packages/cli/foundation/doc-compiler/tree.mjs+++ b/packages/cli/foundation/doc-compiler/tree.mjs@@ -21,6 +21,7 @@ import * as fs from 'node:fs';import * as path from 'node:path';import {CLI_ROOT} from '../fs/paths.mjs';import {loadCliSelfDocs} from '../discovery/cli-self-docs.mjs';+import {astryxIconDefinitions} from '../discovery/icon-definition-discovery.mjs';import {routeSegment} from '../discovery/docs-section-key.mjs';import {diagnostic, sortDiagnostics} from './diagnostics.mjs';import {readDocView} from './read.mjs';@@ -771,8 +772,9 @@ function checkPlacement(placement, kind, at, declared) {}/**- * Every adoption rule in the doc's own package that matches its group and- * kind, from namespaces that have a route.+ * Every adoption rule that matches the doc's group and kind, from namespaces+ * that have a route: its own package's, and an experimental CLI namespace's+ * rule that adopts its group from every package (`source.packages: 'all'`).* @param {TreeDocInput} doc* @param {Map<string, TreeNamespaceInput>} declared* @param {Map<string, string | null>} routeOf@@ -781,10 +783,16 @@ function adoptionsFor(doc, declared, routeOf) {/** @type {Array<{key: string, namespace: TreeNamespaceInput, rule: NonNullable<NamespaceDoc['adopts']>[number]}>} */const matches = [];for (const [key, namespace] of declared) {- if (namespace.provider !== doc.provider || routeOf.get(key) == null)- continue;+ if (routeOf.get(key) == null) continue;for (const rule of namespace.doc.adopts ?? []) {if (rule.source.group !== doc.group) continue;+ // Adopting from every package is experimental (spec:AST-017 FR27): only+ // a CLI namespace marked experimental may (the icon definitions).+ const shared =+ rule.source.packages === 'all' &&+ namespace.provider === CLI_PROVIDER &&+ /** @type {any} */ (namespace.doc).stability === 'experimental';+ if (namespace.provider !== doc.provider && !shared) continue;if (rule.source.kinds &&!rule.source.kinds.includes(/** @type {any} */ (doc.kind))@@ -922,6 +930,23 @@ export async function loadTreeInputs({}}if (selfDocs) {+ // Astryx's icon definitions, adopted by the `icon-definitions` namespace with+ // every installed set's own.+ const definitions = astryxIconDefinitions();+ for (const {file, message} of definitions.errors) {+ diagnostics.push(+ diagnostic('invalid_doc', {+ provider: CLI_PROVIDER,+ source: packageSource(file),+ message,+ }),+ );+ }+ for (const {doc, file} of definitions.definitions) {+ docs.push(+ iconDefinitionTreeInput(doc, file, CLI_PROVIDER, CLI_PROVIDER_ID),+ );+ }const {loaded} = await loadCliSelfDocs();for (const {source, doc} of loaded) {docs.push({@@ -941,6 +966,33 @@ export async function loadTreeInputs({return {namespaces, docs, diagnostics};}+/** The discovery group every icon definition doc belongs to. */+export const ICON_DEFINITIONS_GROUP = 'icon-definitions';++/**+ * One icon definition as a docs-tree input: grouped for the CLI's+ * `icon-definitions` namespace, which adopts them from every package.+ * @param {import('../../authoring/doctypes/icon-definition/type').IconDefinitionDoc} doc+ * @param {string} file+ * @param {string} provider+ * @param {string} providerId+ * @returns {TreeDocInput}+ */+export function iconDefinitionTreeInput(doc, file, provider, providerId) {+ return {+ provider,+ providerId,+ source: packageSource(file),+ kind: 'icon-definition',+ name: doc.name,+ title: doc.name,+ summary: doc.description,+ group: ICON_DEFINITIONS_GROUP,+ placement: undefined,+ ref: {selfDoc: doc},+ };+}+/** @type {Map<string, Promise<DocsTree>>} */const built = new Map();@@ -973,3 +1025,18 @@ export function loadDocsTree({selfDocs = true, fresh = false} = {}) {}return tree;}++/**+ * Is this node an experimental surface's doc (spec:AST-017 FR27): marked+ * `stability: 'experimental'` itself, or under a namespace that is? Every+ * reader that marks or counts experimental docs asks this one question.+ * @param {DocsTree} tree+ * @param {TreeNode} node+ * @returns {boolean}+ */+export function isExperimentalTreeNode(tree, node) {+ return [...tree.ancestors(node), node].some(+ (/** @type {any} */ each) =>+ each.ref?.selfDoc?.stability === 'experimental',+ );+}diff --git a/packages/cli/foundation/doc-compiler/tree.test.mjs b/packages/cli/foundation/doc-compiler/tree.test.mjsindex 7bb11b1353..309d35fba2 100644--- a/packages/cli/foundation/doc-compiler/tree.test.mjs+++ b/packages/cli/foundation/doc-compiler/tree.test.mjs@@ -289,6 +289,40 @@ describe('buildDocsTree', () => {]);});+ it('adopts from every package only on an experimental CLI namespace', () => {+ const CLI = '@astryxdesign/cli';+ /** @param {object} extra */+ const shared = extra => ({+ ...ns('words', {+ slots: {all: {title: 'All', accepts: {kinds: ['generic']}}},+ adopts: [+ {+ source: {group: 'words', kinds: ['generic'], packages: 'all'},+ into: 'all',+ },+ ],+ ...extra,+ }),+ provider: CLI,+ providerId: CLI,+ source: `${CLI}/tree/words.doc.mjs`,+ });+ const docs = [+ guide('mine', {group: 'words', provider: CLI, providerId: CLI}),+ guide('theirs', {group: 'words'}),+ ];+ const stable = buildDocsTree({namespaces: [shared({})], docs});+ expect(stable.get('words')?.slots[0].children).toEqual(['words/mine']);+ const experimental = buildDocsTree({+ namespaces: [shared({stability: 'experimental'})],+ docs,+ });+ expect(experimental.get('words')?.slots[0].children).toEqual([+ 'words/mine',+ 'words/theirs',+ ]);+ });+it('prefers explicit placement over adoption, and never falls back', () => {const namespaces = [ns('guides'),diff --git a/packages/cli/foundation/fs/paths.mjs b/packages/cli/foundation/fs/paths.mjsindex 14ca5a4fc8..98b96004aa 100644--- a/packages/cli/foundation/fs/paths.mjs+++ b/packages/cli/foundation/fs/paths.mjs@@ -687,10 +687,16 @@ export function findNodeModulesPackage(startDir, name) {** @param {string} startDir* @param {string} name+ * @param {number} [maxDepth] how many folders to walk up; `Infinity` walks+ * every ancestor, as Node's own resolution does* @returns {string|null} the package directory, or null when not installed*/-export function findInstalledPackage(startDir, name) {- for (const dir of readFolders(startDir, INSTALLED_REACH)) {+export function findInstalledPackage(+ startDir,+ name,+ maxDepth = INSTALLED_REACH,+) {+ for (const dir of readFolders(startDir, maxDepth)) {const packageDir = installedIn(dir, name);if (packageDir) return packageDir;}diff --git a/packages/cli/foundation/identity/provider-identity.mjs b/packages/cli/foundation/identity/provider-identity.mjsindex 2ec142764f..0df43e3974 100644--- a/packages/cli/foundation/identity/provider-identity.mjs+++ b/packages/cli/foundation/identity/provider-identity.mjs@@ -37,6 +37,7 @@ const CONTRIBUTION_KINDS = new Set(['command','enum','namespace',+ 'icon-definition','theme','codemod','agent-doc',@@ -53,6 +54,7 @@ const DOC_KINDS = new Set(['command','enum','namespace',+ 'icon-definition',]);/** RFC 3986 path-segment encoding with uppercase escapes. */diff --git a/packages/cli/foundation/integrations/cli-requirement.mjs b/packages/cli/foundation/integrations/cli-requirement.mjsindex 2b0ed25e17..7017b6b187 100644--- a/packages/cli/foundation/integrations/cli-requirement.mjs+++ b/packages/cli/foundation/integrations/cli-requirement.mjs@@ -71,6 +71,27 @@ export const THEMES_CLI = '0.6.4';*/export const SECTION_IDS_CLI = '0.6.4';+/**+ * The first stable CLI release that reads `stability` on a doc+ * (spec:AST-017 FR21, FR27). Published 0.7.3 refuses the field on a page or+ * block template, which it drops, and on a namespace doc, which hides every+ * doc topic the package ships; component docs and guides keep loading and+ * ignore it.+ *+ * Tied to the next patch slot: it must equal the first stable release that+ * reads the field.+ */+export const STABILITY_CLI = '0.7.4';++/**+ * The first stable CLI release that reads a template's `icons` declaration+ * (spec:AST-084 FR16). Published 0.7.3 refuses the field and drops that+ * template.+ *+ * Tied to the next patch slot, with {@link STABILITY_CLI}.+ */+export const TEMPLATE_ICONS_CLI = '0.7.4';+/*** The first CLI release that reads a doc section's `before` and `after`.* Earlier releases reject the fields and hide every doc topic the package@@ -85,7 +106,8 @@ export const SECTION_POSITION_CLI = '0.7.4';*/export const DOC_TOKENS_CLI = '0.7.4';-const VERSION_RE = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;+const VERSION_RE =+ /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;/*** A version or partial version as MAJOR.MINOR.PATCH, a wildcard part as 0.@@ -339,3 +361,72 @@ export function withCliPeer(pkg, floor) {export function withDocsTreeCli(pkg) {return withCliPeer(pkg, NAMESPACE_DOCS_CLI);}++/**+ * Why a package whose template or namespace doc sets `stability` would lose+ * it on an older CLI, or null when its declared CLI range admits only CLIs+ * that read the field.+ * @param {any} pkg package.json+ * @returns {string | null}+ */+export function stabilityCliProblem(pkg) {+ return cliRangeProblem(+ pkg,+ 'has a template or namespace doc that sets `stability`',+ "rejects the field and drops that descriptor, and for a namespace doc hides the package's doc topics",+ STABILITY_CLI,+ );+}++/**+ * Why a package with a template that declares `icons` would lose that+ * template on an older CLI, or null when its declared CLI range admits only+ * CLIs that read the field.+ * @param {any} pkg package.json+ * @returns {string | null}+ */+export function templateIconsCliProblem(pkg) {+ return cliRangeProblem(+ pkg,+ 'has a template that declares `icons`',+ 'rejects the field and drops that template',+ TEMPLATE_ICONS_CLI,+ );+}++/**+ * The first stable CLI release that reads `experimental.iconSet` in a+ * project's astryx.config (spec:AST-084 FR16). Published 0.7.3 refuses the+ * config ("Unrecognized key"), so commands that load the project+ * configuration, such as `doctor` and `discover`, fail in that project.+ *+ * Tied to the next patch slot, with {@link STABILITY_CLI}.+ */+export const CONFIG_ICON_SET_CLI = '0.7.4';++/**+ * Why an app project whose astryx.config sets `experimental.iconSet` would be+ * refused by a CLI it may run, or null when the `@astryxdesign/cli` range it+ * declares (in dependencies, devDependencies, optionalDependencies, or+ * peerDependencies) admits only CLIs that read the key. A project that+ * declares no range, or one that is not a version range (`workspace:`,+ * `file:`, `link:`), gets null: nothing says which CLI it runs.+ * @param {any} pkg the project's package.json+ * @returns {string | null}+ */+export function projectIconSetCliWarning(pkg) {+ const field = [+ 'dependencies',+ 'devDependencies',+ 'optionalDependencies',+ 'peerDependencies',+ ].find(name => typeof pkg?.[name]?.[CLI_PACKAGE] === 'string');+ if (!field) return null;+ const range = pkg[field][CLI_PACKAGE];+ if (range.includes(':')) return null;+ const lowest = lowestAdmitted(range);+ if (lowest != null && semverCompare(lowest, CONFIG_ICON_SET_CLI) >= 0) {+ return null;+ }+ return `The project's ${CLI_PACKAGE} range "${range}" (${field}) admits a release before ${CONFIG_ICON_SET_CLI}, which refuses an astryx.config that sets \`experimental.iconSet\` ("Unrecognized key"), so commands that load the project configuration, such as \`doctor\` and \`discover\`, fail there. Require "${CLI_PACKAGE}": ">=${CONFIG_ICON_SET_CLI}".`;+}diff --git a/packages/cli/foundation/integrations/cli-requirement.test.mjs b/packages/cli/foundation/integrations/cli-requirement.test.mjsindex 793860596a..cbf6636818 100644--- a/packages/cli/foundation/integrations/cli-requirement.test.mjs+++ b/packages/cli/foundation/integrations/cli-requirement.test.mjs@@ -10,6 +10,8 @@ import {NAMESPACE_DOCS_CLI,SECTION_IDS_CLI,DOC_TOKENS_CLI,+ STABILITY_CLI,+ TEMPLATE_ICONS_CLI,TEMPLATE_REPLACES_CLI,cliRangeProblem,componentReplacesCliProblem,@@ -340,6 +342,8 @@ describe('every feature check names its CLI floor', () => {sectionIdsCliProblem: '0.6.4',sectionPositionCliProblem: '0.7.4',themesCliProblem: '0.6.4',+ stabilityCliProblem: STABILITY_CLI,+ templateIconsCliProblem: TEMPLATE_ICONS_CLI,// The release doc tokens ship in.docTokensCliProblem: '0.7.4',};@@ -369,6 +373,11 @@ describe('every feature check names its CLI floor', () => {// `replaces`, and 0.6.6 reads its `keywords`.replacesCliProblem: '0.6.4',keywordsCliProblem: '0.6.6',+ // Tied to the next patch slot: published 0.7.3 refuses `stability` on+ // a template or namespace doc.+ stabilityCliProblem: '0.7.4',+ // Published 0.7.3 refuses a template's `icons`.+ templateIconsCliProblem: '0.7.4',});});});diff --git a/packages/cli/foundation/integrations/contribution-inventory.mjs b/packages/cli/foundation/integrations/contribution-inventory.mjsindex 7a949e51e0..9a3d102bd3 100644--- a/packages/cli/foundation/integrations/contribution-inventory.mjs+++ b/packages/cli/foundation/integrations/contribution-inventory.mjs@@ -24,6 +24,8 @@ import {loadComponentDoc} from '../discovery/component-loader.mjs';import {discoverIntegrationTemplatesForOne} from '../discovery/template-adapter.mjs';import {discoverIntegrationCodemods} from '../../assets/codemods/integration-discovery.mjs';import {discoverIntegrationDocs} from '../discovery/docs-discovery.mjs';+import {discoverIconSetDirectory} from '../discovery/icon-set-discovery.mjs';+import {generatedTypesPath} from '../discovery/icon-set-writer.mjs';// ── File-walk helpers (no module imports, no execution) ──────────@@ -121,8 +123,34 @@ function enumerateDocFiles(root, pkgDir) {return walkDir(root, n => DOC_RE.test(n)).map(f => rel(pkgDir, f));}+/**+ * Every file an icon set ships: its descriptor, data file, own definitions,+ * and license notices, and its generated icons module.+ * @param {string} root+ * @param {string} pkgDir+ */+function enumerateIconSetFiles(root, pkgDir) {+ /** @type {string[]} */+ const files = [];+ for (const set of discoverIconSetDirectory(root, '(local)').sets) {+ files.push(set.docPath, set.dataPath);+ for (const definition of set.definitions) files.push(definition.file);+ for (const notice of set.notices) files.push(path.join(set.dir, notice));+ if (set.data.generated) {+ const generated = path.join(pkgDir, set.data.generated);+ if (fs.existsSync(generated)) files.push(generated);+ const types = generatedTypesPath(set.data.generated);+ if (types && fs.existsSync(path.join(pkgDir, types))) {+ files.push(path.join(pkgDir, types));+ }+ }+ }+ return [...new Set(files)].sort().map(file => rel(pkgDir, file));+}+/** @type {Record<FileInventoryRoot['kind'], (root: string, pkgDir: string) => string[]>} */const ENUMERATORS = {+ iconSets: enumerateIconSetFiles,themes: enumerateThemeFiles,components: enumerateComponentFiles,templates: enumerateTemplateFiles,@@ -135,13 +163,14 @@ const ROOT_KINDS = /** @type {const} */ (['templates','codemods','docs',+ 'iconSets',]);/*** The contribution files readers read under each declared root that is a* readable folder, package-relative, without importing anything. A folder* inside a root that cannot be listed is skipped.- * @param {{components?: string, templates?: string, codemods?: string, docs?: string, themes?: string}} loaded+ * @param {{components?: string, templates?: string, codemods?: string, docs?: string, themes?: string, iconSets?: string}} loaded* @param {string} pkgDir* @returns {string[]}*/@@ -164,7 +193,7 @@ export function contributionFiles(loaded, pkgDir) {/*** @typedef {object} FileInventoryRoot- * @property {'themes'|'components'|'templates'|'codemods'|'docs'} kind+ * @property {'themes'|'components'|'templates'|'codemods'|'docs'|'iconSets'} kind* @property {string} path — project-relative root path* @property {string[]} files — project-relative required file paths*/@@ -216,6 +245,8 @@ export function computeRequiredFiles(loaded) {* @property {{version: string, id: string}[]} codemods* @property {string[]} docs* @property {string[]} agentDocsAppend+ * @property {string[]} [iconSets] icon set names; present only when the+ * package declares `experimental.iconSets` (experimental)*//**@@ -228,6 +259,7 @@ export function computeRequiredFiles(loaded) {* @property {string} [codemods]* @property {string} [docs]* @property {{append?: readonly string[]}} [agentDocs]+ * @property {string} [iconSets]*//**@@ -261,9 +293,19 @@ export async function collectIdentities(loaded) {agentDocsAppend: loaded.agentDocs?.append? [...loaded.agentDocs.append]: [],+ // Experimental: only a package that declares `experimental.iconSets`+ // gains the field, so every other package's inventory is unchanged.+ ...(loaded.iconSets ? {iconSets: []} : {}),};/** @type {Array<{kind: string, message: string}>} */const errors = [];+ if (loaded.iconSets && fs.existsSync(loaded.iconSets)) {+ const found = discoverIconSetDirectory(loaded.iconSets, loaded.name);+ identities.iconSets = found.sets.map(set => set.name).sort();+ for (const error of found.errors) {+ errors.push({kind: 'iconSets', message: error.message});+ }+ }if (loaded.themes && isFolder(loaded.themes)) {try {@@ -379,7 +421,7 @@ export async function collectIdentities(loaded) {* handler, not a second set of per-writer rules.** @param {IdentitySource} loaded- * @param {'theme'|'component'|'template'|'codemod'|'doc'|'agent-doc'} kind+ * @param {'theme'|'component'|'template'|'codemod'|'doc'|'agent-doc'|'icon-set'} kind* @param {string} name* @param {{version?: string}} [options]* @returns {Promise<void>}@@ -390,6 +432,21 @@ export async function assertContributionVisible(name,{version} = {},) {+ if (kind === 'icon-set') {+ // An icon set is read by its own discovery seam (spec:AST-084 FR1–FR3):+ // the descriptor and data file must both parse, and the set must be found.+ const {sets, errors} = loaded.iconSets+ ? discoverIconSetDirectory(loaded.iconSets, loaded.name)+ : {sets: [], errors: []};+ const error = errors.find(entry => entry.name === name);+ if (error) throw new Error(error.message);+ if (!sets.some(set => set.name === name)) {+ throw new Error(+ `icon-set contribution "${name}" was not visible after writing.`,+ );+ }+ return;+ }const {identities, errors} = await collectIdentities(loaded);const errorKind =kind === 'theme'@@ -497,6 +554,12 @@ export function compareIdentities(local, packed) {item => `${item.version}/${item.id}`,);compareKind('Doc topic', local.docs, packed.docs, item => item);+ compareKind(+ 'Icon set',+ local.iconSets ?? [],+ packed.iconSets ?? [],+ item => item,+ );if (JSON.stringify(local.agentDocsAppend) !==diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjsindex 4adac5411e..9908f3d942 100644--- a/packages/cli/foundation/integrations/integrations.mjs+++ b/packages/cli/foundation/integrations/integrations.mjs@@ -6,8 +6,9 @@* Integrations are PACKAGE NAMES listed in astryx.config.{ts,mjs,js}. Each* package declares a single conventional root manifest sibling to its* package.json — astryx.integration.{ts,mjs,js} — which contributes- * components/templates/codemods/docs/themes roots, an optional issuesUrl, and- * an optional cliCommand.+ * components/templates/codemods/docs/themes roots (and the experimental+ * `experimental.iconSets` root), an optional issuesUrl, and an optional+ * cliCommand.* Stable provider identity and package metadata come from package.json, not the* manifest.*@@ -52,6 +53,7 @@ import {resolveProviders} from './provider-resolution.mjs';* @property {string} [codemods]* @property {string} [docs]* @property {string} [themes]+ * @property {string} [iconSets] the manifest's `experimental.iconSets` root* @property {string} [issuesUrl]* @property {{append?: readonly string[]}} [agentDocs]* @property {string} [cliCommand] the command this package's users run the@@ -510,6 +512,7 @@ export async function loadLocalIntegration(packageDir, {fresh = false} = {}) {codemods: resolveRoot(manifest.codemods),docs: resolveRoot(manifest.docs),themes: resolveRoot(manifest.themes),+ iconSets: resolveRoot(manifest.experimental?.iconSets),issuesUrl: manifest.issuesUrl,agentDocs: manifest.agentDocs,cliCommand: manifest.cliCommand,@@ -637,6 +640,7 @@ export async function loadIntegrations(codemods: resolveRoot(manifest.codemods),docs: resolveRoot(manifest.docs),themes: resolveRoot(manifest.themes),+ iconSets: resolveRoot(manifest.experimental?.iconSets),issuesUrl: manifest.issuesUrl,agentDocs: manifest.agentDocs,cliCommand: manifest.cliCommand,diff --git a/packages/cli/foundation/integrations/manifest-writer.mjs b/packages/cli/foundation/integrations/manifest-writer.mjsindex 474c9b721e..8d0aa469c1 100644--- a/packages/cli/foundation/integrations/manifest-writer.mjs+++ b/packages/cli/foundation/integrations/manifest-writer.mjs@@ -214,6 +214,9 @@ function removeFileIfUnchanged(file, expectedContents) {* Add a contribution root to an integration manifest, creating the manifest* when requested and none exists.*+ * `kind` is a root key, or a dotted path into a nested object literal+ * (`experimental.iconSets`), which is created when missing.+ ** If the key already has `rootPath`, this is an idempotent no-op. A different* author-owned value is a typed refusal. `dryRun` performs every read and* source-shape check but writes nothing. `createIfMissing` creates a minimal@@ -231,9 +234,11 @@ export async function patchIntegrationRoot(rootPath,{dryRun = false, verify, createIfMissing = false} = {},) {- if (!/^[A-Za-z_$][\w$]*$/u.test(kind)) {+ const keys = kind.split('.');+ if (!keys.every(key => /^[A-Za-z_$][\w$]*$/u.test(key))) {throw new Error(`Invalid integration root key "${kind}".`);}+ const leaf = /** @type {string} */ (keys[keys.length - 1]);assertWithin(rootPath, packageDir, {label: `${kind} root`});const existingManifest = findLocalIntegrationManifestOrNull(packageDir);@@ -266,7 +271,14 @@ export async function patchIntegrationRoot());}- const current = manifest[kind];+ /** @type {unknown} */+ let current = manifest;+ for (const key of keys) {+ current =+ current != null && typeof current === 'object'+ ? /** @type {Record<string, unknown>} */ (current)[key]+ : undefined;+ }if (current !== undefined) {if (current !== rootPath) {throw new IntegrationRootConflictError(kind, String(current), rootPath);@@ -289,16 +301,50 @@ export async function patchIntegrationRoot({cause: error},);}- const object = findManifestObject(j, ast);+ let object = findManifestObject(j, ast);if (!object) {throw new Error(`Could not update ${path.basename(manifestFile)} safely: its default export is not a static object literal.`,);}+ // Walk to the object that holds the leaf key, creating each missing one.+ for (const key of keys.slice(0, -1)) {+ const holder = object.properties.find((/** @type {any} */ property) =>+ propertyNamed(property, key),+ );+ if (!holder) {+ // A spread here may set this key: an object added beside it would+ // replace the spread's whole object and drop what it sets.+ if (+ object.properties.some((/** @type {any} */ property) =>+ [+ 'SpreadElement',+ 'SpreadProperty',+ 'ExperimentalSpreadProperty',+ ].includes(property?.type),+ )+ ) {+ throw new Error(+ `Could not update ${path.basename(manifestFile)} safely: it spreads another object (\`...\`) where "${key}" would go, so a written "${key}" could replace what the spread sets. Set "${kind}: '${rootPath}'" in it yourself.`,+ );+ }+ const created = j.objectExpression([]);+ object.properties.push(j.objectProperty(j.identifier(key), created));+ object = created;+ continue;+ }+ const value = unwrapManifestExpression(holder.value);+ if (!j.ObjectExpression.check(value)) {+ throw new Error(+ `Could not update ${path.basename(manifestFile)} safely: its \`${key}\` field is not a static object literal. Set "${kind}: '${rootPath}'" in it yourself.`,+ );+ }+ object = value;+ }if (object.properties.some((/** @type {any} */ property) =>- propertyNamed(property, kind),+ propertyNamed(property, leaf),)) {throw new Error(@@ -307,7 +353,7 @@ export async function patchIntegrationRoot(}object.properties.push(- j.objectProperty(j.identifier(kind), j.stringLiteral(rootPath)),+ j.objectProperty(j.identifier(leaf), j.stringLiteral(rootPath)),);let next = ast.toSource({quote: 'single', reuseWhitespace: true});if (source.endsWith('\n') && !next.endsWith('\n')) next += '\n';diff --git a/packages/cli/foundation/integrations/manifest-writer.test.mjs b/packages/cli/foundation/integrations/manifest-writer.test.mjsindex 6e9844ff6c..0735b97614 100644--- a/packages/cli/foundation/integrations/manifest-writer.test.mjs+++ b/packages/cli/foundation/integrations/manifest-writer.test.mjs@@ -227,3 +227,45 @@ describe('patchIntegrationRoot', () => {);});});++describe('patchIntegrationRoot with a nested key beside a spread', () => {+ it('refuses to add the object a spread may set, and leaves the manifest as it was', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'shared.mjs'),+ "export default {experimental: {other: './other'}};\n",+ );+ const before =+ "import shared from './shared.mjs';\n\nexport default {\n ...shared,\n docs: './docs',\n};\n";+ const file = manifest(before);+ await expect(+ patchIntegrationRoot(tmpDir, 'experimental.iconSets', './icon-sets'),+ ).rejects.toThrow(+ /spreads another object \(`\.\.\.`\) where "experimental" would go.*Set "experimental\.iconSets: '\.\/icon-sets'" in it yourself/u,+ );+ expect(fs.readFileSync(file, 'utf8')).toBe(before);+ });++ it('adds the key inside an existing literal object, keeping its other keys', async () => {+ const file = manifest(+ "export default {\n experimental: {\n other: './other',\n },\n};\n",+ );+ await patchIntegrationRoot(tmpDir, 'experimental.iconSets', './icon-sets');+ const text = fs.readFileSync(file, 'utf8');+ expect(text).toContain("other: './other'");+ expect(text).toContain("iconSets: './icon-sets'");+ expect(text.match(/experimental:/gu)).toHaveLength(1);+ });++ it('a top-level key beside a spread is still added: the loaded manifest shows whether the spread sets it', async () => {+ const file = manifest(+ "const shared = {docs: './docs'};\n\nexport default {\n ...shared,\n};\n",+ );+ await patchIntegrationRoot(tmpDir, 'themes', './themes');+ expect(fs.readFileSync(file, 'utf8')).toContain("themes: './themes'");+ // The spread already sets `docs`: the same value is a no-op, another a+ // conflict, so the spread's value is never shadowed.+ await expect(+ patchIntegrationRoot(tmpDir, 'docs', './elsewhere'),+ ).rejects.toBeInstanceOf(IntegrationRootConflictError);+ });+});diff --git a/packages/cli/foundation/integrations/validate-contributions.mjs b/packages/cli/foundation/integrations/validate-contributions.mjsindex 7727d82898..e2f9c0b09e 100644--- a/packages/cli/foundation/integrations/validate-contributions.mjs+++ b/packages/cli/foundation/integrations/validate-contributions.mjs@@ -259,7 +259,7 @@ export function rootProblem(root) {* `unreadable_root` error. The contribution checks skip all three.* A readable root reached through a symlinked folder is a `symlinked_root`* warning: npm pack does not follow it, so the published package loses it.- * @param {{components?: string, templates?: string, codemods?: string, docs?: string, themes?: string, __manifestFile?: string}} resolved+ * @param {{components?: string, templates?: string, codemods?: string, docs?: string, themes?: string, iconSets?: string, __manifestFile?: string}} resolved* absolute resolved roots (undefined when not declared)* @param {Issue[]} issues* @param {string} [packageDir] the package the roots belong to@@ -271,6 +271,7 @@ function checkRoots(resolved, issues, packageDir) {'codemods','docs','themes',+ 'iconSets',]);for (const kind of kinds) {const root = resolved[kind];@@ -2438,6 +2439,7 @@ async function allLoadedIntegrationIssues(loaded) {codemods: loaded.codemods,docs: loaded.docs,themes: loaded.themes,+ iconSets: loaded.iconSets,__manifestFile: loaded.__manifestFile,},issues,diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex cd36ce869e..0feb96f746 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -113,6 +113,63 @@ export const doc = {"One post's metadata plus the feed URL and the post's full plaintext body.",},+ // experimental icon (installed icon sets, AST-084): experimental values,+ // documented under `astryx docs cli/experimental`, not in this table.+ {+ value: 'icon.search',+ stability: 'experimental',+ description:+ 'The echoed query, `matchCount` (every match, before `limit`), and matches: icons from the installed icon sets ranked by meaning, each {set, id, package, module, export, import, words, definitions, variants, reason, score}.',+ },+ {+ value: 'icon.detail',+ stability: 'experimental',+ description:+ "One icon's fields, as a match names them, with every variant's import line. The envelope names the set's package.",+ },+ {+ value: 'icon.list',+ stability: 'experimental',+ description:+ "The project's icon-set state (status, projectSet, reason), each installed set with its package, license, icon count, default variant, declared variants, and the icon definitions its `map` covers (built-in, all of Astryx's, and its own), and each withdrawn set with its reason.",+ },+ {+ value: 'icon.use',+ stability: 'experimental',+ description:+ 'The `experimental.iconSet` written to astryx.config, the set it names as `<package>/<set>`, the config file, whether it was created, the value it replaced, and whether anything changed.',+ },+ {+ value: 'icon.map',+ stability: 'experimental',+ description:+ 'One `map` entry of the icon set being authored: the set, its package, the data file, the definition, the icon id now mapped (null after --remove), the id it replaced, and whether the file changed.',+ },+ {+ value: 'icon.add',+ stability: 'experimental',+ description:+ "One icon registered in the icon set being authored: the set, its package, the icon {id, export, module}, the variant when it was added as one, the definition mapped to it, the definition file written when it added the set's own, the files written, and whether anything changed.",+ },+ {+ value: 'icon.definitionMatches',+ stability: 'experimental',+ description:+ "The icon definitions that fit an export, before it is added: the export, its source module, the id it would get, at most 10 matches {name, description, source (astryx or set), score, reason, command}, and the command that adds the set's own definition when none fits.",+ },+ {+ value: 'icon.newSet',+ stability: 'experimental',+ description:+ "An icon set started in the integration package: the set's name, the manifest's `experimental.iconSets` root (and whether it was declared now), the manifest file, the files written, whether they were written or only planned, and with --from how many icons it wrapped and what to do next.",+ },+ {+ value: 'icon.newDefinition',+ stability: 'experimental',+ description:+ "An icon set's own icon definition: its name, the manifest file, the files written (the definition and, with --icon, the data file), and whether they were written or only planned.",+ },+// discover (external / integration packages){value: 'discover.list',@@ -338,7 +395,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. 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.',+ '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. For the package being authored, olderCliNotes ({file, kind: template | namespace, field, message}) lists each descriptor field a CLI before 0.7.4 refuses, such as stability on a template or namespace doc; it is present only when it has entries, and is never counted or fails a check.',},{value: 'integration.template-conflicts',diff --git a/packages/cli/scripts/generate-cli-readme.mjs b/packages/cli/scripts/generate-cli-readme.mjsindex 638b8c4bb4..bee04dc6a1 100644--- a/packages/cli/scripts/generate-cli-readme.mjs+++ b/packages/cli/scripts/generate-cli-readme.mjs@@ -104,8 +104,14 @@ async function build() {const errorCodes = await loadDoc('foundation/response/error-codes.doc.mjs');const errorRows = errorCodes.members.map((/** @type {any} */ m) => [`\`${m.value}\``, m.description]);- const responseTypes = await loadDoc('foundation/response/response-types.doc.mjs');- const rtRows = responseTypes.members.map((/** @type {any} */ m) => [`\`${m.value}\``, m.description]);+ const responseTypes = await loadDoc(+ 'foundation/response/response-types.doc.mjs',+ );+ // Experimental response types are documented under `astryx docs+ // cli/experimental`, not in the stable table (spec:AST-017 FR27).+ const rtRows = responseTypes.members+ .filter((/** @type {any} */ m) => m.stability !== 'experimental')+ .map((/** @type {any} */ m) => [`\`${m.value}\``, m.description]);let content = fs.readFileSync(README, 'utf8');content = replaceBlock(diff --git a/packages/cli/test-utils/icon-set-fixture.mjs b/packages/cli/test-utils/icon-set-fixture.mjsnew file mode 100644index 0000000000..01cd3a82e3--- /dev/null+++ b/packages/cli/test-utils/icon-set-fixture.mjs@@ -0,0 +1,280 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file A tiny synthetic icon-set integration, laid out on disk for tests+ * (AST-084).+ *+ * `writeIconSetProject` writes a consuming project that declares one or more+ * icon packages, each installed under node_modules with an integration+ * manifest whose `experimental.iconSets` root holds one set. The default package,+ * `@acme/glyphs`, ships four hand-made SVG components (x, search, trash,+ * home) re-exported from per-icon files, a solid trash variant, a theme map,+ * and a license notice. Every part can be overridden to build a broken case.+ *+ * @input A temp directory and per-package overrides+ * @output The project directory+ * @position test-utils — shared by the icon-set discovery, command, search,+ * check, Doctor, and template-mapping tests+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {ICON_NAMES} from '../authoring/doctypes/icon-set/icon-names.mjs';++/** @typedef {import('../authoring/doctypes/icon-set/type').IconSetData} IconSetData */++/** The default set's data file. */+export function glyphsData() {+ return /** @type {IconSetData} */ ({+ schemaVersion: 1,+ module: '@acme/glyphs',+ variants: ['outline', 'solid'],+ default: {variant: 'outline'},+ themeMap: 'themeIcons',+ map: {close: 'x', search: 'search'},+ icons: [+ {+ id: 'x',+ export: 'XIcon',+ words: ['close', 'cancel', 'dismiss', 'remove', 'times'],+ },+ {+ id: 'search',+ export: 'SearchIcon',+ words: ['find', 'magnifier', 'lookup', 'search'],+ },+ {+ id: 'trash',+ export: 'TrashIcon',+ words: ['delete', 'remove', 'bin', 'garbage'],+ variants: [{variant: 'solid', export: 'TrashSolidIcon'}],+ },+ {+ id: 'home',+ export: 'HomeIcon',+ words: ['house', 'start', 'main'],+ },+ ],+ });+}++/** @param {string} name @param {string} d */+const svgComponent = (name, d) => `export function ${name}(props) {+ return {+ type: 'svg',+ props: {viewBox: '0 0 24 24', 'aria-hidden': true, ...props, children: [{type: 'path', props: {d: '${d}'}}]},+ };+}+`;++/** The default package's module files, by path. */+export function glyphsModules() {+ return {+ 'index.js': [+ "export {XIcon} from './icons/x.js';",+ "export {SearchIcon} from './icons/search.js';",+ "export * from './icons/trash.js';",+ "export {HomeIcon} from './icons/home.js';",+ "export {themeIcons} from './theme.js';",+ '',+ ].join('\n'),+ 'icons/x.js': svgComponent('XIcon', 'M6 6l12 12M6 18L18 6'),+ 'icons/search.js': svgComponent(+ 'SearchIcon',+ 'M11 4a7 7 0 100 14 7 7 0 000-14zM20 20l-4-4',+ ),+ 'icons/trash.js':+ svgComponent('TrashIcon', 'M5 7h14M9 7V4h6v3M7 7l1 13h8l1-13') ++ svgComponent('TrashSolidIcon', 'M5 7h14v13H5z'),+ 'icons/home.js': svgComponent('HomeIcon', 'M3 11l9-8 9 8v10H3z'),+ 'theme.js': [+ "import {XIcon} from './icons/x.js';",+ "import {SearchIcon as Magnifier} from './icons/search.js';",+ '',+ 'export const themeIcons = {',+ ' close: XIcon,',+ ' search: Magnifier,',+ '};',+ '',+ ].join('\n'),+ };+}++/**+ * The default set with every built-in icon definition mapped: `close` and+ * `search` to their icons, every other built-in to `home`, and a theme map+ * keyed by exactly those definitions. `integration check` then reports no+ * error for it.+ * @returns {{data: IconSetData, modules: Record<string, string>}}+ */+export function completeGlyphs() {+ const others = ICON_NAMES.filter(+ name => name !== 'close' && name !== 'search',+ );+ const data = glyphsData();+ data.map = {+ ...data.map,+ ...Object.fromEntries(others.map(name => [name, 'home'])),+ };+ const modules = glyphsModules();+ modules['theme.js'] = [+ "import {XIcon} from './icons/x.js';",+ "import {SearchIcon as Magnifier} from './icons/search.js';",+ "import {HomeIcon} from './icons/home.js';",+ '',+ 'export const themeIcons = {',+ ' close: XIcon,',+ ' search: Magnifier,',+ ...others.map(name => ` ${name}: HomeIcon,`),+ '};',+ '',+ ].join('\n');+ return {data, modules};+}++/**+ * @typedef {object} IconPackageSpec+ * @property {string} [name] package name (default `@acme/glyphs`)+ * @property {string} [version]+ * @property {string} [set] set directory name (default the package's last+ * segment)+ * @property {Record<string, unknown>} [doc] descriptor fields (merged over+ * the defaults)+ * @property {string | null} [docSource] the whole descriptor source, or null+ * to leave it out+ * @property {unknown} [data] the data file value (default glyphsData with+ * `module` set to the package name), or null to leave it out+ * @property {Record<string, string>} [modules] module files (default+ * glyphsModules)+ * @property {boolean} [notice] write a LICENSE in the set directory (default+ * true)+ * @property {Record<string, string>} [dependencies] the package's own+ * dependencies+ * @property {boolean} [install] install it in node_modules (default true)+ * @property {Record<string, string>} [definitions] the set's own icon+ * definition files, by name: each value is the file's source+ */++/**+ * Write one icon package into a directory.+ * @param {string} dir+ * @param {IconPackageSpec} spec+ */+export function writeIconPackage(dir, spec = {}) {+ const name = spec.name ?? '@acme/glyphs';+ const set = spec.set ?? name.split('/').pop();+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify(+ {+ name,+ version: spec.version ?? '1.0.0',+ type: 'module',+ sideEffects: false,+ exports: {'.': './index.js'},+ ...(spec.dependencies ? {dependencies: spec.dependencies} : {}),+ },+ null,+ 2,+ ),+ );+ fs.writeFileSync(+ path.join(dir, 'astryx.integration.mjs'),+ "export default {experimental: {iconSets: './icon-sets'}};\n",+ );+ for (const [file, text] of Object.entries(spec.modules ?? glyphsModules())) {+ fs.mkdirSync(path.dirname(path.join(dir, file)), {recursive: true});+ fs.writeFileSync(path.join(dir, file), text);+ }+ const setDir = path.join(dir, 'icon-sets', /** @type {string} */ (set));+ fs.mkdirSync(setDir, {recursive: true});+ const doc = {+ type: 'icon-set',+ name: set,+ displayName: `Acme ${set}`,+ description: 'Hand-drawn test icons.',+ maintained: true,+ license: 'MIT',+ ...(spec.doc ?? {}),+ };+ if (spec.docSource !== null) {+ fs.writeFileSync(+ path.join(setDir, `${set}.doc.mjs`),+ spec.docSource ??+ `/** @type {import('@astryxdesign/cli/authoring').IconSetDoc} */\nexport default ${JSON.stringify(doc, null, 2)};\n`,+ );+ }+ const data =+ spec.data === undefined ? {...glyphsData(), module: name} : spec.data;+ if (data !== null) {+ fs.writeFileSync(+ path.join(setDir, `${set}.icons.json`),+ typeof data === 'string' ? data : JSON.stringify(data, null, 2),+ );+ }+ if (spec.notice !== false) {+ fs.writeFileSync(path.join(setDir, 'LICENSE'), 'MIT License\n');+ }+ for (const [definition, source] of Object.entries(spec.definitions ?? {})) {+ const definitionsDir = path.join(setDir, 'definitions');+ fs.mkdirSync(definitionsDir, {recursive: true});+ fs.writeFileSync(+ path.join(definitionsDir, `${definition}.doc.mjs`),+ source,+ );+ }+}++/**+ * The source of one icon definition file.+ * @param {string} name+ * @param {{description?: string, words?: string[]}} [fields]+ */+export function definitionSource(name, fields = {}) {+ return `/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */\nexport default ${JSON.stringify(+ {+ type: 'icon-definition',+ name,+ description: fields.description ?? `The ${name} icon.`,+ words: fields.words ?? [name.toLowerCase()],+ },+ null,+ 2,+ )};\n`;+}++/**+ * Write a consuming project that declares (and installs) icon packages.+ * @param {string} root+ * @param {{packages?: IconPackageSpec[], config?: Record<string, unknown> | null}} [options]+ * `config`: astryx.config.mjs contents; null for none+ * @returns {string} the project directory+ */+export function writeIconSetProject(root, options = {}) {+ const packages = options.packages ?? [{}];+ const project = path.join(root, 'app');+ fs.mkdirSync(project, {recursive: true});+ /** @type {Record<string, string>} */+ const dependencies = {};+ for (const spec of packages) {+ const name = spec.name ?? '@acme/glyphs';+ dependencies[name] = spec.version ?? '1.0.0';+ if (spec.install === false) continue;+ writeIconPackage(+ path.join(project, 'node_modules', ...name.split('/')),+ spec,+ );+ }+ fs.writeFileSync(+ path.join(project, 'package.json'),+ JSON.stringify({name: 'app', private: true, dependencies}, null, 2),+ );+ if (options.config) {+ fs.writeFileSync(+ path.join(project, 'astryx.config.mjs'),+ `export default ${JSON.stringify(options.config)};\n`,+ );+ }+ return project;+}diff --git a/packages/cli/test/__golden__/no-icon-set/discover-malformed-icon-set-source.json b/packages/cli/test/__golden__/no-icon-set/discover-malformed-icon-set-source.jsonnew file mode 100644index 0000000000..e696bf73cb--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/discover-malformed-icon-set-source.json@@ -0,0 +1,139 @@+{+ "apiVersion": 1,+ "type": "discover.list",+ "data": [],+ "meta": {+ "configured": false,+ "available": [+ {+ "name": "@astryxdesign/richtext",+ "package": "@astryxdesign/richtext",+ "components": [+ "RichTextEditor"+ ],+ "version": "<version>",+ "description": "Astryx rich text — a Lexical-based rich text editor and viewer, styled with Astryx design tokens.",+ "templates": [+ "RichTextEditorShowcase"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/richtext@<version>"+ },+ {+ "name": "@astryxdesign/theme-butter",+ "package": "@astryxdesign/theme-butter",+ "components": [],+ "version": "<version>",+ "description": "Warm, creamy yellows with a friendly blue accent. Playful enough for consumer surfaces, soft enough to stay readable.",+ "themes": [+ "butter"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/theme-butter@<version>"+ },+ {+ "name": "@astryxdesign/theme-chocolate",+ "package": "@astryxdesign/theme-chocolate",+ "components": [],+ "version": "<version>",+ "description": "Warm chocolate theme for Astryx — rich brown palette with Fraunces headings, Albert Sans body, and Lucide icons",+ "themes": [+ "chocolate"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/theme-chocolate@<version>"+ },+ {+ "name": "@astryxdesign/theme-gothic",+ "package": "@astryxdesign/theme-gothic",+ "components": [],+ "version": "<version>",+ "description": "Deep blue-grays and a signature display serif. Dramatic and editorial, for surfaces that want to be remembered.",+ "themes": [+ "gothic"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/theme-gothic@<version>"+ },+ {+ "name": "@astryxdesign/theme-matcha",+ "package": "@astryxdesign/theme-matcha",+ "components": [],+ "version": "<version>",+ "description": "Earthy greens with a calm, organic feel. Naturalistic and grounded, great for wellness or content-first apps.",+ "themes": [+ "matcha"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/theme-matcha@<version>"+ },+ {+ "name": "@astryxdesign/theme-neutral",+ "package": "@astryxdesign/theme-neutral",+ "components": [],+ "version": "<version>",+ "description": "Restrained warm grays. Minimal and quiet, so the content stays the focus.",+ "themes": [+ "neutral"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/theme-neutral@<version>"+ },+ {+ "name": "@astryxdesign/theme-stone",+ "package": "@astryxdesign/theme-stone",+ "components": [],+ "version": "<version>",+ "description": "Warm stone and slate, earthy and understated, with just enough character to feel handcrafted.",+ "themes": [+ "stone"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/theme-stone@<version>"+ },+ {+ "name": "@astryxdesign/theme-y2k",+ "package": "@astryxdesign/theme-y2k",+ "components": [],+ "version": "<version>",+ "description": "Hot pinks, lime greens, and Poppins. Bubbly, playful, and unmistakably retro.",+ "themes": [+ "y2k"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/theme-y2k@<version>"+ },+ {+ "name": "@acme/glyphs",+ "package": "@acme/glyphs",+ "components": [],+ "version": "1.0.0",+ "themes": [+ "glyph-theme"+ ],+ "source": "acme",+ "install": "pnpm add @acme/glyphs"+ }+ ],+ "sources": [+ {+ "name": "acme",+ "from": "astryx.config",+ "status": "fresh",+ "generatedAt": "2026-01-01T00:00:00.000Z",+ "complete": true+ },+ {+ "name": "Astryx",+ "from": "@astryxdesign/cli",+ "status": "fresh",+ "complete": true+ }+ ],+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "project"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/discover-type-bogus.json b/packages/cli/test/__golden__/no-icon-set/discover-type-bogus.jsonnew file mode 100644index 0000000000..57f31d89ed--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/discover-type-bogus.json@@ -0,0 +1,31 @@+{+ "apiVersion": 1,+ "error": "Unknown --type \"bogus\"",+ "code": "ERR_INVALID_OPTION",+ "suggestions": [+ {+ "name": "component",+ "reason": "item kind"+ },+ {+ "name": "template",+ "reason": "item kind"+ },+ {+ "name": "doc",+ "reason": "item kind"+ },+ {+ "name": "theme",+ "reason": "item kind"+ },+ {+ "name": "codemod",+ "reason": "item kind"+ },+ {+ "name": "agent-doc",+ "reason": "item kind"+ }+ ]+}diff --git a/packages/cli/test/__golden__/no-icon-set/discover-type-icon-set.json b/packages/cli/test/__golden__/no-icon-set/discover-type-icon-set.jsonnew file mode 100644index 0000000000..bf5602920c--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/discover-type-icon-set.json@@ -0,0 +1,31 @@+{+ "apiVersion": 1,+ "error": "Unknown --type \"icon-set\"",+ "code": "ERR_INVALID_OPTION",+ "suggestions": [+ {+ "name": "component",+ "reason": "item kind"+ },+ {+ "name": "template",+ "reason": "item kind"+ },+ {+ "name": "doc",+ "reason": "item kind"+ },+ {+ "name": "theme",+ "reason": "item kind"+ },+ {+ "name": "codemod",+ "reason": "item kind"+ },+ {+ "name": "agent-doc",+ "reason": "item kind"+ }+ ]+}diff --git a/packages/cli/test/__golden__/no-icon-set/discover.json b/packages/cli/test/__golden__/no-icon-set/discover.jsonnew file mode 100644index 0000000000..41efd10cc5--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/discover.json@@ -0,0 +1,128 @@+{+ "apiVersion": 1,+ "type": "discover.list",+ "data": [+ {+ "name": "@acme/glyphs",+ "package": "@acme/glyphs",+ "category": "@acme/glyphs",+ "components": [],+ "version": "1.0.0"+ }+ ],+ "meta": {+ "available": [+ {+ "name": "@astryxdesign/richtext",+ "package": "@astryxdesign/richtext",+ "components": [+ "RichTextEditor"+ ],+ "version": "<version>",+ "description": "Astryx rich text — a Lexical-based rich text editor and viewer, styled with Astryx design tokens.",+ "templates": [+ "RichTextEditorShowcase"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/richtext@<version>"+ },+ {+ "name": "@astryxdesign/theme-butter",+ "package": "@astryxdesign/theme-butter",+ "components": [],+ "version": "<version>",+ "description": "Warm, creamy yellows with a friendly blue accent. Playful enough for consumer surfaces, soft enough to stay readable.",+ "themes": [+ "butter"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/theme-butter@<version>"+ },+ {+ "name": "@astryxdesign/theme-chocolate",+ "package": "@astryxdesign/theme-chocolate",+ "components": [],+ "version": "<version>",+ "description": "Warm chocolate theme for Astryx — rich brown palette with Fraunces headings, Albert Sans body, and Lucide icons",+ "themes": [+ "chocolate"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/theme-chocolate@<version>"+ },+ {+ "name": "@astryxdesign/theme-gothic",+ "package": "@astryxdesign/theme-gothic",+ "components": [],+ "version": "<version>",+ "description": "Deep blue-grays and a signature display serif. Dramatic and editorial, for surfaces that want to be remembered.",+ "themes": [+ "gothic"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/theme-gothic@<version>"+ },+ {+ "name": "@astryxdesign/theme-matcha",+ "package": "@astryxdesign/theme-matcha",+ "components": [],+ "version": "<version>",+ "description": "Earthy greens with a calm, organic feel. Naturalistic and grounded, great for wellness or content-first apps.",+ "themes": [+ "matcha"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/theme-matcha@<version>"+ },+ {+ "name": "@astryxdesign/theme-neutral",+ "package": "@astryxdesign/theme-neutral",+ "components": [],+ "version": "<version>",+ "description": "Restrained warm grays. Minimal and quiet, so the content stays the focus.",+ "themes": [+ "neutral"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/theme-neutral@<version>"+ },+ {+ "name": "@astryxdesign/theme-stone",+ "package": "@astryxdesign/theme-stone",+ "components": [],+ "version": "<version>",+ "description": "Warm stone and slate, earthy and understated, with just enough character to feel handcrafted.",+ "themes": [+ "stone"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/theme-stone@<version>"+ },+ {+ "name": "@astryxdesign/theme-y2k",+ "package": "@astryxdesign/theme-y2k",+ "components": [],+ "version": "<version>",+ "description": "Hot pinks, lime greens, and Poppins. Bubbly, playful, and unmistakably retro.",+ "themes": [+ "y2k"+ ],+ "source": "Astryx",+ "install": "pnpm add @astryxdesign/theme-y2k@<version>"+ }+ ],+ "sources": [+ {+ "name": "Astryx",+ "from": "@astryxdesign/cli",+ "status": "fresh",+ "complete": true+ }+ ],+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "project"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/docs-cli-api-functions.json b/packages/cli/test/__golden__/no-icon-set/docs-cli-api-functions.jsonnew file mode 100644index 0000000000..0a347847f2--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/docs-cli-api-functions.json@@ -0,0 +1,380 @@+{+ "apiVersion": 1,+ "type": "docs.node",+ "package": "@astryxdesign/cli",+ "data": {+ "id": null,+ "route": "cli/api/functions",+ "kind": "namespace",+ "package": "@astryxdesign/cli",+ "title": "<text>",+ "summary": "<text>",+ "breadcrumb": [+ {+ "route": "cli",+ "title": "<text>"+ },+ {+ "route": "cli/api",+ "title": "<text>"+ }+ ],+ "slots": [+ {+ "name": "items",+ "title": "<text>",+ "children": [+ {+ "route": "cli/api/functions/assert-response",+ "name": "assert-response",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/blog",+ "name": "blog",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/build",+ "name": "build",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/component",+ "name": "component",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/discover",+ "name": "discover",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/docs",+ "name": "docs",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/doctor",+ "name": "doctor",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/gap-report",+ "name": "gap-report",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/generate-tonal-palette",+ "name": "generate-tonal-palette",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/hook",+ "name": "hook",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/init",+ "name": "init",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/integration-add",+ "name": "integration-add",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/integration-add-agent-doc",+ "name": "integration-add-agent-doc",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/integration-add-codemod",+ "name": "integration-add-codemod",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/integration-add-component",+ "name": "integration-add-component",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/integration-add-doc",+ "name": "integration-add-doc",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/integration-add-template",+ "name": "integration-add-template",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/integration-add-theme",+ "name": "integration-add-theme",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/integration-check",+ "name": "integration-check",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/integration-component-conflicts",+ "name": "integration-component-conflicts",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/integration-doc-conflicts",+ "name": "integration-doc-conflicts",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/integration-pack-check",+ "name": "integration-pack-check",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/integration-template-conflicts",+ "name": "integration-template-conflicts",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/is-error",+ "name": "is-error",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/list-themes",+ "name": "list-themes",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/parse-response",+ "name": "parse-response",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/search",+ "name": "search",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/summarize-issues",+ "name": "summarize-issues",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/swizzle",+ "name": "swizzle",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/template",+ "name": "template",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/theme-add",+ "name": "theme-add",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/theme-build",+ "name": "theme-build",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/theme-eject",+ "name": "theme-eject",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/theme-list",+ "name": "theme-list",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/theme-list-available",+ "name": "theme-list-available",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/theme-list-copy-sources",+ "name": "theme-list-copy-sources",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/theme-palette-generate",+ "name": "theme-palette-generate",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/theme-remove",+ "name": "theme-remove",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/theme-targets",+ "name": "theme-targets",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/theme-template",+ "name": "theme-template",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/theme-use",+ "name": "theme-use",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/upgrade",+ "name": "upgrade",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api/functions/validate-integration",+ "name": "validate-integration",+ "package": "@astryxdesign/cli",+ "kind": "function",+ "title": "<text>",+ "summary": "<text>"+ }+ ]+ }+ ],+ "content": [],+ "links": {+ "up": "<text>",+ "next": "<text>"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/docs-cli-api-functions.txt b/packages/cli/test/__golden__/no-icon-set/docs-cli-api-functions.txtnew file mode 100644index 0000000000..4ea4cb7094--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/docs-cli-api-functions.txt@@ -0,0 +1,49 @@+<text>++package: @astryxdesign/cli++assert-response <text>+blog <text>+build <text>+component <text>+discover <text>+docs <text>+doctor <text>+gap-report <text>+generate-tonal-palette <text>+hook <text>+init <text>+integration-add <text>+integration-add-agent-doc <text>+integration-add-codemod <text>+integration-add-component <text>+integration-add-doc <text>+integration-add-template <text>+integration-add-theme <text>+integration-check <text>+integration-component-conflicts <text>+integration-doc-conflicts <text>+integration-pack-check <text>+integration-template-conflicts <text>+is-error <text>+list-themes <text>+parse-response <text>+search <text>+summarize-issues <text>+swizzle <text>+template <text>+theme-add <text>+theme-build <text>+theme-eject <text>+theme-list <text>+theme-list-available <text>+theme-list-copy-sources <text>+theme-palette-generate <text>+theme-remove <text>+theme-targets <text>+theme-template <text>+theme-use <text>+upgrade <text>+validate-integration <text>++<text>diff --git a/packages/cli/test/__golden__/no-icon-set/docs-cli-commands.json b/packages/cli/test/__golden__/no-icon-set/docs-cli-commands.jsonnew file mode 100644index 0000000000..ae52383d5d--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/docs-cli-commands.json@@ -0,0 +1,325 @@+{+ "apiVersion": 1,+ "type": "docs.node",+ "package": "@astryxdesign/cli",+ "data": {+ "id": "astryx:artifact:v1/%40astryxdesign%2Fcli/namespace/commands",+ "route": "cli/commands",+ "kind": "namespace",+ "package": "@astryxdesign/cli",+ "title": "<text>",+ "summary": "<text>",+ "breadcrumb": [+ {+ "route": "cli",+ "title": "<text>"+ }+ ],+ "slots": [+ {+ "name": "commands",+ "title": "<text>",+ "children": [+ {+ "route": "cli/commands/blog",+ "name": "blog",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/build",+ "name": "build",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/component",+ "name": "component",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/discover",+ "name": "discover",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/docs",+ "name": "docs",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/doctor",+ "name": "doctor",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/doctor-integration",+ "name": "doctor-integration",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/doctor-integration-components",+ "name": "doctor-integration-components",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/doctor-integration-docs",+ "name": "doctor-integration-docs",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/doctor-integration-templates",+ "name": "doctor-integration-templates",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/doctor-integration-validate",+ "name": "doctor-integration-validate",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/gap-report",+ "name": "gap-report",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/hook",+ "name": "hook",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/init",+ "name": "init",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/integration",+ "name": "integration",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/integration-add",+ "name": "integration-add",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/integration-check",+ "name": "integration-check",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/integration-pack",+ "name": "integration-pack",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/integration-verify",+ "name": "integration-verify",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/manifest",+ "name": "manifest",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/postinstall",+ "name": "postinstall",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/search",+ "name": "search",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/swizzle",+ "name": "swizzle",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/template",+ "name": "template",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/theme",+ "name": "theme",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/theme-add",+ "name": "theme-add",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/theme-build",+ "name": "theme-build",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/theme-eject",+ "name": "theme-eject",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/theme-list",+ "name": "theme-list",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/theme-palette",+ "name": "theme-palette",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/theme-palette-generate",+ "name": "theme-palette-generate",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/theme-remove",+ "name": "theme-remove",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/theme-targets",+ "name": "theme-targets",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/theme-template",+ "name": "theme-template",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/theme-use",+ "name": "theme-use",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/commands/upgrade",+ "name": "upgrade",+ "package": "@astryxdesign/cli",+ "kind": "command",+ "title": "<text>",+ "summary": "<text>"+ }+ ]+ }+ ],+ "content": [+ {+ "type": "prose",+ "text": "<text>"+ }+ ],+ "links": {+ "up": "<text>",+ "next": "<text>"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/docs-cli-commands.txt b/packages/cli/test/__golden__/no-icon-set/docs-cli-commands.txtnew file mode 100644index 0000000000..e401372173--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/docs-cli-commands.txt@@ -0,0 +1,44 @@+<text>++package: @astryxdesign/cli++<text>++blog <text>+build <text>+component <text>+discover <text>+docs <text>+doctor <text>+doctor-integration <text>+doctor-integration-components <text>+doctor-integration-docs <text>+doctor-integration-templates <text>+doctor-integration-validate <text>+gap-report <text>+hook <text>+init <text>+integration <text>+integration-add <text>+integration-check <text>+integration-pack <text>+integration-verify <text>+manifest <text>+postinstall <text>+search <text>+swizzle <text>+template <text>+theme <text>+theme-add <text>+theme-build <text>+theme-eject <text>+theme-list <text>+theme-palette <text>+theme-palette-generate <text>+theme-remove <text>+theme-targets <text>+theme-template <text>+theme-use <text>+upgrade <text>++<text>diff --git a/packages/cli/test/__golden__/no-icon-set/docs-cli-mentions.json b/packages/cli/test/__golden__/no-icon-set/docs-cli-mentions.jsonnew file mode 100644index 0000000000..0967ef424b--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/docs-cli-mentions.json@@ -0,0 +1 @@+{}diff --git a/packages/cli/test/__golden__/no-icon-set/docs-cli.json b/packages/cli/test/__golden__/no-icon-set/docs-cli.jsonnew file mode 100644index 0000000000..acbf971c60--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/docs-cli.json@@ -0,0 +1,69 @@+{+ "apiVersion": 1,+ "type": "docs.node",+ "package": "@astryxdesign/cli",+ "data": {+ "id": "astryx:artifact:v1/%40astryxdesign%2Fcli/namespace/cli",+ "route": "cli",+ "kind": "namespace",+ "package": "@astryxdesign/cli",+ "title": "<text>",+ "summary": "<text>",+ "breadcrumb": [],+ "slots": [+ {+ "name": "guides",+ "title": "<text>",+ "children": [+ {+ "route": "cli/component-lookups",+ "name": "component-lookups",+ "package": "@astryxdesign/cli",+ "kind": "generic",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/host-entry",+ "name": "host-entry",+ "package": "@astryxdesign/cli",+ "kind": "generic",+ "title": "<text>",+ "summary": "<text>"+ }+ ]+ },+ {+ "name": "reference",+ "title": "<text>",+ "children": [+ {+ "route": "cli/commands",+ "name": "commands",+ "package": "@astryxdesign/cli",+ "kind": "namespace",+ "title": "<text>",+ "summary": "<text>"+ },+ {+ "route": "cli/api",+ "name": "api",+ "package": "@astryxdesign/cli",+ "kind": "namespace",+ "title": "<text>",+ "summary": "<text>"+ }+ ]+ }+ ],+ "content": [+ {+ "type": "prose",+ "text": "<text>"+ }+ ],+ "links": {+ "up": "<text>"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/docs-cli.txt b/packages/cli/test/__golden__/no-icon-set/docs-cli.txtnew file mode 100644index 0000000000..0a683acf85--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/docs-cli.txt@@ -0,0 +1,17 @@+<text>++package: @astryxdesign/cli++<text>++<text>++component-lookups <text>+host-entry <text>++<text>++commands <text>+api <text>++<text>diff --git a/packages/cli/test/__golden__/no-icon-set/docs-topics.json b/packages/cli/test/__golden__/no-icon-set/docs-topics.jsonnew file mode 100644index 0000000000..f19b3f7b33--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/docs-topics.json@@ -0,0 +1,300 @@+{+ "list": [+ {+ "topic": "author-a-theme",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "browser-support",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "color",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "elevation",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "getting-started",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "icons",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "illustrations",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "is-my-code-good",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "motion",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "principles",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "shape",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "spacing",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "styling-overview",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "theme",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "use-a-theme",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "use-integrations",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ },+ {+ "topic": "working-with-ai",+ "description": "<text>",+ "package": "@astryxdesign/cli"+ }+ ],+ "topics": {+ "author-a-theme": {+ "sections": [+ "creating-a-custom-theme",+ "palette",+ "definetheme",+ "extending-a-theme",+ "component-style-overrides",+ "custom-variants",+ "theme-adaptations",+ "adaptation-rules",+ "building-themes-for-production",+ "icon-registry",+ "building-a-theme-family",+ "token-utilities",+ "usetheme-hook"+ ],+ "skeleton": "4e494f1ed2599a4a3ba54c3f722ae1ff9808fe80843e9ed0c6ab2e8b9f0bb19e",+ "mentions": []+ },+ "browser-support": {+ "sections": [+ "overview",+ "support-tiers",+ "which-features-set-the-floor",+ "which-components-are-affected",+ "what-astryx-guarantees",+ "supporting-older-browsers",+ "how-these-tiers-move-over-time"+ ],+ "skeleton": "98bdd1d0e1db35f5ad03896962be51d2f21679c3f3cd25cf724045778a959b5e",+ "mentions": []+ },+ "color": {+ "sections": [+ "overview",+ "surface-colors",+ "usage",+ "best-practices"+ ],+ "skeleton": "940c5a29904f209dfe36a4c7f19ba5a11e333eabb1f8ea0e66127b7b29337a0a",+ "mentions": []+ },+ "elevation": {+ "sections": [+ "overview",+ "elevation-scale",+ "choosing-a-level",+ "the-elevation-prop",+ "usage",+ "best-practices"+ ],+ "skeleton": "7a448412efe0ab7d7c8fd7e89966e74494ec3fcff734ec7e30ec353a3542b874",+ "mentions": []+ },+ "getting-started": {+ "sections": [+ "quick-start-with-ai",+ "install",+ "install-once",+ "add-base-css-and-a-theme",+ "add-your-first-component",+ "customize-with-stylex",+ "example-apps",+ "explore-the-cli"+ ],+ "skeleton": "6564c786e0e708b5ffb9a1811db06328dc9eb1f833c9722f7a4c417c46cc6eee",+ "mentions": []+ },+ "icons": {+ "sections": [+ "available-names",+ "custom-icons",+ "theme-overrides",+ "component-and-library-icons"+ ],+ "skeleton": "e64c5b38eb3c598a4e2d35f4301fe72a59497fee2f48a32e1faf270fc5fd41f1",+ "mentions": [+ "This lets you swap the icon set (e.g."+ ]+ },+ "illustrations": {+ "sections": [+ "when-to-use",+ "guidelines",+ "placement"+ ],+ "skeleton": "1bbcbbda636d363c3605412a29da2005832b14bea6d99a94a38e91ccdafbdeca",+ "mentions": []+ },+ "is-my-code-good": {+ "sections": [+ "understand-the-app",+ "choose-the-review",+ "apply-the-rubric",+ "collect-the-evidence",+ "ask-an-agent",+ "verify-and-repeat"+ ],+ "skeleton": "57ad5ac61d3b02e08bad08cd26a048b4096c260c40d733ac2c2cbea7e6467117",+ "mentions": []+ },+ "motion": {+ "sections": [+ "overview",+ "duration",+ "easing",+ "where-motion-helps",+ "where-motion-hurts",+ "movement-principles",+ "respecting-user-preferences",+ "usage",+ "best-practices"+ ],+ "skeleton": "e648d618f9141bbd7f15bf970ba9e0d41b59ff9ae89e0cbbb2042e98bd5f0109",+ "mentions": []+ },+ "principles": {+ "sections": [+ "design-philosophy",+ "rules",+ "styling-approach",+ "anti-patterns",+ "design-tokens"+ ],+ "skeleton": "137859678ce5cc2df84192ca7065e7a4ecb46225c5a4437fe7a7393af7f8c87e",+ "mentions": []+ },+ "shape": {+ "sections": [+ "overview",+ "radius-scale",+ "concentric-radius",+ "best-practices"+ ],+ "skeleton": "f656eee5271a84e4b83cc3bbd7b09fdc47f3f308131882865f594b59581318fc",+ "mentions": []+ },+ "spacing": {+ "sections": [+ "overview",+ "scale",+ "usage",+ "best-practices"+ ],+ "skeleton": "bf2132b4acd9e8734709007ab1ae8bf40d89fb92d3281607d6ef19e4f2c7557e",+ "mentions": []+ },+ "styling-overview": {+ "sections": [+ "pick-a-path",+ "plain",+ "tailwind",+ "stylex-own-code",+ "other-packages",+ "what-each-file-does",+ "further-reading"+ ],+ "skeleton": "2bb79103d25e7b1f1a0cb160776a00d871056f95a6b8a728bb5c4c487475a25f",+ "mentions": []+ },+ "theme": {+ "sections": [+ "quick-start",+ "creating-a-custom-theme",+ "light-dark-mode",+ "integration-themes"+ ],+ "skeleton": "4af0a08dbcf2008c2ad6c12e61a1451130f10109fdb666a08933a7ce69ce18bd",+ "mentions": []+ },+ "use-a-theme": {+ "sections": [+ "quick-start",+ "migrating-earlier-theme-copies",+ "available-themes",+ "theme-props",+ "integration-themes",+ "light-dark-mode",+ "nesting-themes",+ "runtime-vs-built-themes"+ ],+ "skeleton": "eeb293ed4c43f4ff72bb3d44ae5a36e3fdae16d01717f8db75370add6dc928d4",+ "mentions": []+ },+ "use-integrations": {+ "sections": [+ "discover-integrations",+ "install-an-integration",+ "use-what-it-adds",+ "check-for-problems"+ ],+ "skeleton": "906555b962d65e80281e888eabf678729956d8c13b8bc65f6fb892e6917d66f0",+ "mentions": []+ },+ "working-with-ai": {+ "sections": [+ "overview",+ "quick-start",+ "what-gets-generated",+ "cursor-setup",+ "checking-your-setup",+ "the-astryx-pattern",+ "the-dense-flag",+ "mcp-server",+ "global-mode"+ ],+ "skeleton": "032b8da5c5f97f350157c8f4b270f1c954ba32da04cbb5e846f42ed7fc9e31bb",+ "mentions": []+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/docs-tree.json b/packages/cli/test/__golden__/no-icon-set/docs-tree.jsonnew file mode 100644index 0000000000..d25cb9ca7f--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/docs-tree.json@@ -0,0 +1,1436 @@+{+ "author-a-theme": {+ "type": "docs.detail",+ "sections": [+ "creating-a-custom-theme",+ "palette",+ "definetheme",+ "extending-a-theme",+ "component-style-overrides",+ "custom-variants",+ "theme-adaptations",+ "adaptation-rules",+ "building-themes-for-production",+ "icon-registry",+ "building-a-theme-family",+ "token-utilities",+ "usetheme-hook"+ ],+ "mentions": []+ },+ "authoring": {+ "type": "docs.node",+ "children": [+ "authoring/quick-start",+ "authoring/building-blocks",+ "authoring/global-integrations",+ "authoring/ship",+ "authoring/help",+ "authoring/field-reference"+ ],+ "mentions": []+ },+ "authoring/building-blocks": {+ "type": "docs.node",+ "children": [+ "authoring/building-blocks/components",+ "authoring/building-blocks/templates",+ "authoring/building-blocks/themes",+ "authoring/building-blocks/docs",+ "authoring/building-blocks/codemods",+ "authoring/building-blocks/configuration"+ ],+ "mentions": []+ },+ "authoring/building-blocks/codemods": {+ "type": "docs.detail",+ "sections": [+ "add-a-codemod",+ "write-the-transform",+ "which-codemods-run",+ "run-codemods-in-an-app",+ "global-mode"+ ],+ "mentions": []+ },+ "authoring/building-blocks/components": {+ "type": "docs.node",+ "children": [+ "authoring/building-blocks/components/add-a-component",+ "authoring/building-blocks/components/describe-the-component",+ "authoring/building-blocks/components/component-imports",+ "authoring/building-blocks/components/see-it-in-an-app",+ "authoring/building-blocks/components/replace-a-core-component"+ ],+ "mentions": []+ },+ "authoring/building-blocks/components/add-a-component": {+ "type": "docs.detail",+ "sections": [+ "pick-a-component-name",+ "run-the-add-command",+ "document-an-existing-component",+ "global-mode"+ ],+ "mentions": []+ },+ "authoring/building-blocks/components/component-imports": {+ "type": "docs.detail",+ "sections": [+ "export-the-component",+ "verify-the-packed-import",+ "global-mode"+ ],+ "mentions": []+ },+ "authoring/building-blocks/components/describe-the-component": {+ "type": "docs.node",+ "children": [+ "authoring/building-blocks/components/describe-the-component/single-component",+ "authoring/building-blocks/components/describe-the-component/component-family",+ "authoring/building-blocks/components/describe-the-component/subcomponent",+ "authoring/building-blocks/components/describe-the-component/check-the-props"+ ],+ "mentions": []+ },+ "authoring/building-blocks/components/describe-the-component/check-the-props": {+ "type": "docs.detail",+ "sections": [+ "run-the-props-check",+ "fix-each-finding",+ "write-types-the-check-can-judge",+ "when-a-component-is-not-compared"+ ],+ "mentions": []+ },+ "authoring/building-blocks/components/describe-the-component/component-family": {+ "type": "docs.detail",+ "sections": [+ "choose-the-family-shape",+ "document-the-family-inline",+ "give-a-member-its-own-file"+ ],+ "mentions": []+ },+ "authoring/building-blocks/components/describe-the-component/single-component": {+ "type": "docs.detail",+ "sections": [+ "start-from-the-generated-doc",+ "explain-when-to-use-it",+ "document-every-public-prop",+ "add-focused-examples",+ "read-the-result"+ ],+ "mentions": []+ },+ "authoring/building-blocks/components/describe-the-component/subcomponent": {+ "type": "docs.detail",+ "sections": [+ "choose-a-separate-doc",+ "reference-it-from-the-parent",+ "write-the-subcomponent-doc"+ ],+ "mentions": []+ },+ "authoring/building-blocks/components/replace-a-core-component": {+ "type": "docs.detail",+ "sections": [+ "decide-whether-to-replace",+ "set-the-replacement",+ "check-replacement-resolution",+ "global-mode"+ ],+ "mentions": []+ },+ "authoring/building-blocks/components/see-it-in-an-app": {+ "type": "docs.detail",+ "sections": [+ "read-the-installed-component",+ "test-the-packed-package",+ "global-mode"+ ],+ "mentions": []+ },+ "authoring/building-blocks/configuration": {+ "type": "docs.node",+ "children": [+ "authoring/building-blocks/configuration/agent-guidance",+ "authoring/building-blocks/configuration/cli-command",+ "authoring/building-blocks/configuration/debug-and-gap-reports"+ ],+ "mentions": []+ },+ "authoring/building-blocks/configuration/agent-guidance": {+ "type": "docs.detail",+ "sections": [+ "add-a-guidance-line",+ "keep-within-the-limits",+ "see-what-agents-read",+ "refresh-the-block",+ "global-mode"+ ],+ "mentions": []+ },+ "authoring/building-blocks/configuration/cli-command": {+ "type": "docs.detail",+ "sections": [+ "when-to-set-it",+ "set-it",+ "how-the-cli-picks",+ "when-two-packages-disagree",+ "check-it",+ "global-mode"+ ],+ "mentions": []+ },+ "authoring/building-blocks/configuration/debug-and-gap-reports": {+ "type": "docs.detail",+ "sections": [+ "record-runs-with-debug",+ "turn-off-debug-in-an-app",+ "handle-gap-reports",+ "ask-before-filing-in-public",+ "fall-back-to-issues-url",+ "choose-a-destination",+ "global-mode"+ ],+ "mentions": []+ },+ "authoring/building-blocks/docs": {+ "type": "docs.node",+ "children": [+ "authoring/building-blocks/docs/add-a-topic",+ "authoring/building-blocks/docs/doc-syntax",+ "authoring/building-blocks/docs/sections-and-placement",+ "authoring/building-blocks/docs/links",+ "authoring/building-blocks/docs/extend-or-replace",+ "authoring/building-blocks/docs/short-and-findable",+ "authoring/building-blocks/docs/check-your-docs"+ ],+ "mentions": []+ },+ "authoring/building-blocks/docs/add-a-topic": {+ "type": "docs.detail",+ "sections": [+ "add-a-topic-with-the-cli",+ "write-the-sections",+ "write-commands-without-a-runner",+ "pick-the-doc-kind",+ "keep-topics-in-the-docs-root",+ "global-mode"+ ],+ "mentions": []+ },+ "authoring/building-blocks/docs/check-your-docs": {+ "type": "docs.detail",+ "sections": [+ "run-the-docs-check",+ "know-what-fails-the-check",+ "check-each-doc-against-its-type",+ "check-read-size",+ "check-the-cli-peer"+ ],+ "mentions": []+ },+ "authoring/building-blocks/docs/doc-syntax": {+ "type": "docs.detail",+ "sections": [+ "the-tokens",+ "package-manager-steps",+ "one-package-manager",+ "what-doctor-checks"+ ],+ "mentions": []+ },+ "authoring/building-blocks/docs/extend-or-replace": {+ "type": "docs.detail",+ "sections": [+ "replace-a-topic",+ "extend-a-topic",+ "replace-or-extend-a-cli-guide",+ "check-overlaps-with-core-topics",+ "global-mode"+ ],+ "mentions": []+ },+ "authoring/building-blocks/docs/links": {+ "type": "docs.detail",+ "sections": [+ "link-another-doc",+ "link-another-packages-docs",+ "fix-a-link-that-names-no-doc"+ ],+ "mentions": []+ },+ "authoring/building-blocks/docs/sections-and-placement": {+ "type": "docs.detail",+ "sections": [+ "add-a-docs-section",+ "place-a-doc",+ "fix-a-failed-placement"+ ],+ "mentions": []+ },+ "authoring/building-blocks/docs/short-and-findable": {+ "type": "docs.detail",+ "sections": [+ "keep-each-read-short",+ "lead-with-the-summary",+ "make-docs-findable",+ "test-with-search"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates": {+ "type": "docs.node",+ "children": [+ "authoring/building-blocks/templates/start-a-template",+ "authoring/building-blocks/templates/document-the-template",+ "authoring/building-blocks/templates/build-the-template",+ "authoring/building-blocks/templates/write-good-templates"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/build-the-template": {+ "type": "docs.node",+ "children": [+ "authoring/building-blocks/templates/build-the-template/write-the-template-file",+ "authoring/building-blocks/templates/build-the-template/template-assets",+ "authoring/building-blocks/templates/build-the-template/package-and-test"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/build-the-template/package-and-test": {+ "type": "docs.node",+ "children": [+ "authoring/building-blocks/templates/build-the-template/package-and-test/export-template-assets",+ "authoring/building-blocks/templates/build-the-template/package-and-test/verify-packed-template",+ "authoring/building-blocks/templates/build-the-template/package-and-test/test-template-in-app"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/build-the-template/package-and-test/export-template-assets": {+ "type": "docs.detail",+ "sections": [+ "keep-the-generated-template-export",+ "export-package-owned-support-files",+ "include-every-file",+ "declare-what-the-copied-file-imports"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/build-the-template/package-and-test/test-template-in-app": {+ "type": "docs.detail",+ "sections": [+ "install-the-packed-package",+ "copy-the-template",+ "build-every-supported-app",+ "render-the-behavior-matrix",+ "grade-the-result"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/build-the-template/package-and-test/verify-packed-template": {+ "type": "docs.detail",+ "sections": [+ "run-the-package-check",+ "know-what-it-does-not-prove"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/build-the-template/template-assets": {+ "type": "docs.node",+ "children": [+ "authoring/building-blocks/templates/build-the-template/template-assets/template-styles",+ "authoring/building-blocks/templates/build-the-template/template-assets/template-fonts",+ "authoring/building-blocks/templates/build-the-template/template-assets/template-icons",+ "authoring/building-blocks/templates/build-the-template/template-assets/template-images-media"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/build-the-template/template-assets/template-fonts": {+ "type": "docs.detail",+ "sections": [+ "prefer-host-typography",+ "package-a-required-font",+ "check-fonts-in-the-app"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/build-the-template/template-assets/template-icons": {+ "type": "docs.detail",+ "sections": [+ "use-astryx-icon",+ "ship-a-custom-icon",+ "check-icons-in-the-app"+ ],+ "mentions": [+ "Do not paste raw `svg` and `path` markup when an existing icon definition fits.",+ "Export a compatible icon definition from a public package path, then import that path from the template.",+ "For a component icon prop, pass what that prop accepts: most, such as `Button` and `IconButton`, take an element like `<Icon icon={BellIcon} />`, and some menu and navigation items also accept the icon definition itself.",+ "Use one supported icon set consistently inside a template."+ ]+ },+ "authoring/building-blocks/templates/build-the-template/template-assets/template-images-media": {+ "type": "docs.detail",+ "sections": [+ "do-not-copy-relative-media",+ "understand-template-assets",+ "design-a-useful-placeholder",+ "check-media-in-the-app"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/build-the-template/template-assets/template-styles": {+ "type": "docs.detail",+ "sections": [+ "start-with-astryx",+ "keep-editable-styles-with-the-source",+ "publish-shared-css"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/build-the-template/write-the-template-file": {+ "type": "docs.detail",+ "sections": [+ "know-what-gets-copied",+ "keep-edited-code-in-one-file",+ "use-imports-that-work",+ "export-one-component"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/document-the-template": {+ "type": "docs.node",+ "children": [+ "authoring/building-blocks/templates/document-the-template/template-doc-overview",+ "authoring/building-blocks/templates/document-the-template/page-template",+ "authoring/building-blocks/templates/document-the-template/block-template",+ "authoring/building-blocks/templates/document-the-template/replace-a-core-template"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/document-the-template/block-template": {+ "type": "docs.detail",+ "sections": [+ "start-with-a-standalone-block",+ "choose-the-component-relationship",+ "choose-a-useful-preview"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/document-the-template/page-template": {+ "type": "docs.detail",+ "sections": [+ "start-from-the-generated-page-doc",+ "help-people-find-the-page"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/document-the-template/replace-a-core-template": {+ "type": "docs.detail",+ "sections": [+ "replace-only-on-purpose",+ "declare-the-replacement",+ "require-a-compatible-cli",+ "what-apps-receive",+ "check-the-replacement"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/document-the-template/template-doc-overview": {+ "type": "docs.detail",+ "sections": [+ "understand-the-two-files",+ "document-the-shared-fields",+ "check-how-astryx-lists-it"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/start-a-template": {+ "type": "docs.detail",+ "sections": [+ "what-a-template-is",+ "why-share-one",+ "choose-page-or-block",+ "pick-a-template-id",+ "run-the-add-command",+ "global-mode"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/write-good-templates": {+ "type": "docs.node",+ "children": [+ "authoring/building-blocks/templates/write-good-templates/template-grading-rubric",+ "authoring/building-blocks/templates/write-good-templates/grade-template-with-agent"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/write-good-templates/grade-template-with-agent": {+ "type": "docs.detail",+ "sections": [+ "give-the-agent-the-rubric",+ "require-a-scorecard",+ "improve-and-regrade"+ ],+ "mentions": []+ },+ "authoring/building-blocks/templates/write-good-templates/template-grading-rubric": {+ "type": "docs.detail",+ "sections": [+ "understand-the-score",+ "component-purity",+ "icon-purity",+ "custom-css",+ "layout-and-structure",+ "doc-metadata",+ "image-handling",+ "code-quality"+ ],+ "mentions": []+ },+ "authoring/building-blocks/themes": {+ "type": "docs.node",+ "children": [+ "authoring/building-blocks/themes/add-a-theme",+ "authoring/building-blocks/themes/generate-a-palette",+ "authoring/building-blocks/themes/define-the-theme",+ "authoring/building-blocks/themes/fonts-and-assets",+ "authoring/building-blocks/themes/use-a-theme-in-an-app",+ "authoring/building-blocks/themes/document-the-theme"+ ],+ "mentions": []+ },+ "authoring/building-blocks/themes/add-a-theme": {+ "type": "docs.detail",+ "sections": [+ "add-a-theme",+ "start-from-an-existing-theme",+ "ship-several-themes",+ "global-mode"+ ],+ "mentions": []+ },+ "authoring/building-blocks/themes/define-the-theme": {+ "type": "docs.detail",+ "sections": [+ "map-the-palette-to-tokens",+ "build-on-another-theme",+ "keep-light-dark-to-colors",+ "avoid-core-internals",+ "declare-the-peers"+ ],+ "mentions": []+ },+ "authoring/building-blocks/themes/document-the-theme": {+ "type": "docs.detail",+ "sections": [+ "extend-the-theme-topic",+ "not-agent-guidance"+ ],+ "mentions": []+ },+ "authoring/building-blocks/themes/fonts-and-assets": {+ "type": "docs.detail",+ "sections": [+ "name-the-font",+ "ship-the-font-loader",+ "verify-in-an-app"+ ],+ "mentions": []+ },+ "authoring/building-blocks/themes/generate-a-palette": {+ "type": "docs.detail",+ "sections": [+ "generate-a-palette"+ ],+ "mentions": []+ },+ "authoring/building-blocks/themes/use-a-theme-in-an-app": {+ "type": "docs.detail",+ "sections": [+ "apply-the-theme",+ "extend-the-theme",+ "global-mode"+ ],+ "mentions": []+ },+ "authoring/field-reference": {+ "type": "docs.detail",+ "sections": [+ "integration",+ "config",+ "debug-event",+ "gap-report-handler",+ "discover-source",+ "codemod",+ "provider-identity",+ "authored-doc-graph-fields",+ "component-doc",+ "hook-doc",+ "function-doc",+ "command-doc",+ "enum-doc",+ "namespace-doc",+ "reference-doc",+ "schema-doc",+ "template-doc",+ "integration-template-doc",+ "theme-doc"+ ]+ },+ "authoring/global-integrations": {+ "type": "docs.detail",+ "sections": [+ "peer-range",+ "where-it-works",+ "checklist",+ "try-it",+ "more"+ ],+ "mentions": []+ },+ "authoring/help": {+ "type": "docs.node",+ "children": [+ "authoring/help/troubleshooting"+ ],+ "mentions": []+ },+ "authoring/help/troubleshooting": {+ "type": "docs.detail",+ "sections": [+ "fix-setup-errors",+ "fix-verify-failures",+ "fix-problems-in-an-app"+ ],+ "mentions": []+ },+ "authoring/quick-start": {+ "type": "docs.detail",+ "sections": [+ "quick-start",+ "fill-in-package-json",+ "the-integration-file",+ "global-mode"+ ],+ "mentions": []+ },+ "authoring/ship": {+ "type": "docs.node",+ "children": [+ "authoring/ship/test-in-an-app",+ "authoring/ship/checks",+ "authoring/ship/versioning",+ "authoring/ship/publishing",+ "authoring/ship/upgrading"+ ],+ "mentions": []+ },+ "authoring/ship/checks": {+ "type": "docs.detail",+ "sections": [+ "pick-a-check",+ "run-every-check-in-ci",+ "what-integration-verify-does"+ ],+ "mentions": []+ },+ "authoring/ship/publishing": {+ "type": "docs.detail",+ "sections": [+ "check-before-you-publish",+ "keep-private-files-out",+ "publish-to-npm",+ "check-the-published-package"+ ],+ "mentions": []+ },+ "authoring/ship/test-in-an-app": {+ "type": "docs.detail",+ "sections": [+ "install-the-packed-package",+ "check-what-the-app-sees",+ "run-doctor-in-the-app"+ ],+ "mentions": []+ },+ "authoring/ship/upgrading": {+ "type": "docs.detail",+ "sections": [+ "update-for-a-new-astryx-release",+ "upgrade-an-app",+ "know-which-files-upgrades-skip"+ ],+ "mentions": []+ },+ "authoring/ship/versioning": {+ "type": "docs.detail",+ "sections": [+ "pick-a-version",+ "know-what-breaks-apps",+ "declare-peer-ranges",+ "support-older-clis",+ "codemods-and-versions"+ ],+ "mentions": []+ },+ "browser-support": {+ "type": "docs.detail",+ "sections": [+ "overview",+ "support-tiers",+ "which-features-set-the-floor",+ "which-components-are-affected",+ "what-astryx-guarantees",+ "supporting-older-browsers",+ "how-these-tiers-move-over-time"+ ],+ "mentions": []+ },+ "color": {+ "type": "docs.detail",+ "sections": [+ "overview",+ "surface-colors",+ "usage",+ "best-practices"+ ],+ "mentions": []+ },+ "elevation": {+ "type": "docs.detail",+ "sections": [+ "overview",+ "elevation-scale",+ "choosing-a-level",+ "the-elevation-prop",+ "usage",+ "best-practices"+ ],+ "mentions": []+ },+ "foundations": {+ "type": "docs.node",+ "children": [+ "color",+ "elevation",+ "icons",+ "illustrations",+ "motion",+ "shape",+ "spacing"+ ],+ "mentions": []+ },+ "getting-started": {+ "type": "docs.detail",+ "sections": [+ "quick-start-with-ai",+ "install",+ "install-once",+ "add-base-css-and-a-theme",+ "add-your-first-component",+ "customize-with-stylex",+ "example-apps",+ "explore-the-cli"+ ],+ "mentions": []+ },+ "global": {+ "type": "docs.node",+ "children": [+ "global/project-global-or-both",+ "global/install-once",+ "global/who-answers",+ "global/updates",+ "global/computer-agent-guide",+ "global/computer-integrations",+ "global/monorepos",+ "global/ci-and-containers",+ "global/problems",+ "global/uninstall",+ "global/reference"+ ],+ "mentions": []+ },+ "global/ci-and-containers": {+ "type": "docs.detail",+ "sections": [+ "in-ci",+ "cache",+ "read-only",+ "short-lived",+ "more"+ ],+ "mentions": []+ },+ "global/computer-agent-guide": {+ "type": "docs.detail",+ "sections": [+ "what",+ "where",+ "cloud-and-apps",+ "other-agents",+ "choose",+ "more"+ ],+ "mentions": []+ },+ "global/computer-integrations": {+ "type": "docs.detail",+ "sections": [+ "install",+ "outside",+ "inside",+ "check",+ "more"+ ],+ "mentions": []+ },+ "global/install-once": {+ "type": "docs.detail",+ "sections": [+ "install",+ "eacces",+ "versions-for-projects",+ "offline",+ "more"+ ],+ "mentions": []+ },+ "global/monorepos": {+ "type": "docs.detail",+ "sections": [+ "find",+ "workspaces",+ "nested",+ "more"+ ],+ "mentions": []+ },+ "global/problems": {+ "type": "docs.detail",+ "sections": [+ "answered-by",+ "installing",+ "notices",+ "old-astryx",+ "fallback",+ "not-global",+ "core-offline",+ "unavailable",+ "needs-a-project",+ "install-problems",+ "more"+ ],+ "mentions": []+ },+ "global/project-global-or-both": {+ "type": "docs.detail",+ "sections": [+ "both",+ "compare",+ "set-up",+ "what-happens",+ "more"+ ],+ "mentions": []+ },+ "global/reference": {+ "type": "docs.detail",+ "sections": [+ "paths",+ "env",+ "json",+ "errors",+ "changes",+ "glossary",+ "more"+ ],+ "mentions": []+ },+ "global/uninstall": {+ "type": "docs.detail",+ "sections": [+ "agent-guide",+ "uninstall",+ "reset",+ "more"+ ],+ "mentions": []+ },+ "global/updates": {+ "type": "docs.detail",+ "sections": [+ "notice",+ "project-notice",+ "turn-off",+ "more"+ ],+ "mentions": []+ },+ "global/who-answers": {+ "type": "docs.detail",+ "sections": [+ "in-a-project",+ "outside",+ "see-it",+ "printed-commands",+ "more"+ ],+ "mentions": []+ },+ "guides": {+ "type": "docs.node",+ "children": [+ "author-a-theme",+ "browser-support",+ "getting-started",+ "is-my-code-good",+ "principles",+ "styling-overview",+ "theme",+ "use-a-theme",+ "use-integrations",+ "working-with-ai"+ ],+ "mentions": []+ },+ "icons": {+ "type": "docs.detail",+ "sections": [+ "available-names",+ "custom-icons",+ "theme-overrides",+ "component-and-library-icons"+ ],+ "mentions": [+ "This lets you swap the icon set (e.g."+ ]+ },+ "illustrations": {+ "type": "docs.detail",+ "sections": [+ "when-to-use",+ "guidelines",+ "placement"+ ],+ "mentions": []+ },+ "internationalization": {+ "type": "docs.node",+ "children": [+ "internationalization/i18n-quick-start",+ "internationalization/i18n-library-integration",+ "internationalization/i18n-rtl-and-testing"+ ],+ "mentions": []+ },+ "internationalization/i18n-library-integration": {+ "type": "docs.detail",+ "sections": [+ "overriding-astryx-s-default-text",+ "using-astryx-with-your-own-i18n-library",+ "using-astryx-as-your-i18n-library"+ ],+ "mentions": []+ },+ "internationalization/i18n-quick-start": {+ "type": "docs.detail",+ "sections": [+ "quick-start",+ "runtime-language-swap"+ ],+ "mentions": []+ },+ "internationalization/i18n-rtl-and-testing": {+ "type": "docs.detail",+ "sections": [+ "text-direction-rtl",+ "testing-your-translations",+ "for-contributors"+ ],+ "mentions": []+ },+ "is-my-code-good": {+ "type": "docs.detail",+ "sections": [+ "understand-the-app",+ "choose-the-review",+ "apply-the-rubric",+ "collect-the-evidence",+ "ask-an-agent",+ "verify-and-repeat"+ ],+ "mentions": []+ },+ "layout": {+ "type": "docs.node",+ "children": [+ "layout/scaffold",+ "layout/structure",+ "layout/headers-and-footers",+ "layout/side-panels",+ "layout/layout-spacing",+ "layout/responsive"+ ],+ "mentions": []+ },+ "layout/headers-and-footers": {+ "type": "docs.detail",+ "sections": [+ "headers-and-footers"+ ],+ "mentions": []+ },+ "layout/layout-spacing": {+ "type": "docs.detail",+ "sections": [+ "spacing",+ "alignment",+ "rhythm",+ "density"+ ],+ "mentions": []+ },+ "layout/responsive": {+ "type": "docs.detail",+ "sections": [+ "breakpoints",+ "responsive-contract",+ "columns-that-reflow"+ ],+ "mentions": []+ },+ "layout/scaffold": {+ "type": "docs.detail",+ "sections": [+ "scaffold",+ "shell",+ "navigation"+ ],+ "mentions": []+ },+ "layout/side-panels": {+ "type": "docs.detail",+ "sections": [+ "side-panels"+ ],+ "mentions": []+ },+ "layout/structure": {+ "type": "docs.detail",+ "sections": [+ "structure",+ "type-hierarchy",+ "containers"+ ],+ "mentions": []+ },+ "migration": {+ "type": "docs.node",+ "children": [+ "migration/migration-setup",+ "migration/component-migration",+ "migration/migration-verification"+ ],+ "mentions": []+ },+ "migration/component-migration": {+ "type": "docs.detail",+ "sections": [+ "move-the-app-frame-first",+ "map-shadcn-and-radix-primitives",+ "command-palette"+ ],+ "mentions": []+ },+ "migration/migration-setup": {+ "type": "docs.detail",+ "sections": [+ "overview",+ "recommended-order",+ "cli-workflow",+ "theme-and-css-setup",+ "cascade-layer-safety",+ "layer-audit",+ "foundation-smoke-test"+ ],+ "mentions": []+ },+ "migration/migration-verification": {+ "type": "docs.detail",+ "sections": [+ "verification-checklist",+ "ai-migration-prompt"+ ],+ "mentions": []+ },+ "motion": {+ "type": "docs.detail",+ "sections": [+ "overview",+ "duration",+ "easing",+ "where-motion-helps",+ "where-motion-hurts",+ "movement-principles",+ "respecting-user-preferences",+ "usage",+ "best-practices"+ ],+ "mentions": []+ },+ "principles": {+ "type": "docs.detail",+ "sections": [+ "design-philosophy",+ "rules",+ "styling-approach",+ "anti-patterns",+ "design-tokens"+ ],+ "mentions": []+ },+ "shape": {+ "type": "docs.detail",+ "sections": [+ "overview",+ "radius-scale",+ "concentric-radius",+ "best-practices"+ ],+ "mentions": []+ },+ "spacing": {+ "type": "docs.detail",+ "sections": [+ "overview",+ "scale",+ "usage",+ "best-practices"+ ],+ "mentions": []+ },+ "styling": {+ "type": "docs.node",+ "children": [+ "styling/styling-basics",+ "styling/styling-advanced",+ "styling/tokens-and-setup"+ ],+ "mentions": []+ },+ "styling-libraries": {+ "type": "docs.node",+ "children": [+ "styling-libraries/css-and-stylex",+ "styling-libraries/tailwind",+ "styling-libraries/other-libraries",+ "styling-libraries/non-css-processing"+ ],+ "mentions": []+ },+ "styling-libraries/css-and-stylex": {+ "type": "docs.detail",+ "sections": [+ "core-principle",+ "choose-an-integration-path",+ "best-practices",+ "plain-css-and-css-modules",+ "stylex"+ ],+ "mentions": []+ },+ "styling-libraries/non-css-processing": {+ "type": "docs.detail",+ "sections": [+ "non-css-processing",+ "non-css-best-practices"+ ],+ "mentions": []+ },+ "styling-libraries/other-libraries": {+ "type": "docs.detail",+ "sections": [+ "semantic-token-systems",+ "mui-and-palette-based-themes",+ "css-in-js",+ "unocss",+ "interop-checklist"+ ],+ "mentions": []+ },+ "styling-libraries/tailwind": {+ "type": "docs.detail",+ "sections": [+ "tailwind"+ ],+ "mentions": []+ },+ "styling-overview": {+ "type": "docs.detail",+ "sections": [+ "pick-a-path",+ "plain",+ "tailwind",+ "stylex-own-code",+ "other-packages",+ "what-each-file-does",+ "further-reading"+ ],+ "mentions": []+ },+ "styling/styling-advanced": {+ "type": "docs.detail",+ "sections": [+ "compound-components",+ "preferred-selector-surface-data-attributes",+ "deprecated-classes",+ "what-not-to-do"+ ],+ "mentions": []+ },+ "styling/styling-basics": {+ "type": "docs.detail",+ "sections": [+ "overview",+ "xstyle-prop",+ "tailwind-integration",+ "classname-and-style-props",+ "rest-props-prop-drilling"+ ],+ "mentions": []+ },+ "styling/tokens-and-setup": {+ "type": "docs.detail",+ "sections": [+ "design-tokens",+ "stylex-setup"+ ],+ "mentions": []+ },+ "theme": {+ "type": "docs.detail",+ "sections": [+ "quick-start",+ "creating-a-custom-theme",+ "light-dark-mode",+ "integration-themes"+ ],+ "mentions": []+ },+ "tokens": {+ "type": "docs.node",+ "children": [+ "tokens/tokens-color",+ "tokens/tokens-data",+ "tokens/tokens-syntax",+ "tokens/tokens-spacing",+ "tokens/tokens-size",+ "tokens/tokens-border",+ "tokens/tokens-focus",+ "tokens/tokens-radius",+ "tokens/tokens-shadow",+ "tokens/tokens-duration",+ "tokens/tokens-ease",+ "tokens/tokens-typography",+ "tokens/tokens-text-size",+ "tokens/tokens-font-weight",+ "tokens/tokens-type-scale",+ "tokens/tokens-usage"+ ],+ "mentions": []+ },+ "tokens/tokens-border": {+ "type": "docs.detail",+ "sections": [+ "border-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-color": {+ "type": "docs.detail",+ "sections": [+ "color-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-data": {+ "type": "docs.detail",+ "sections": [+ "data-visualization-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-duration": {+ "type": "docs.detail",+ "sections": [+ "duration-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-ease": {+ "type": "docs.detail",+ "sections": [+ "easing-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-focus": {+ "type": "docs.detail",+ "sections": [+ "focus-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-font-weight": {+ "type": "docs.detail",+ "sections": [+ "font-weight-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-radius": {+ "type": "docs.detail",+ "sections": [+ "radius-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-shadow": {+ "type": "docs.detail",+ "sections": [+ "shadow-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-size": {+ "type": "docs.detail",+ "sections": [+ "size-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-spacing": {+ "type": "docs.detail",+ "sections": [+ "spacing-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-syntax": {+ "type": "docs.detail",+ "sections": [+ "syntax-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-text-size": {+ "type": "docs.detail",+ "sections": [+ "font-size-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-type-scale": {+ "type": "docs.detail",+ "sections": [+ "type-scale-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-typography": {+ "type": "docs.detail",+ "sections": [+ "font-family-tokens"+ ],+ "mentions": []+ },+ "tokens/tokens-usage": {+ "type": "docs.detail",+ "sections": [+ "usage-in-stylex"+ ],+ "mentions": []+ },+ "typography": {+ "type": "docs.node",+ "children": [+ "typography/font-setup",+ "typography/type-scale",+ "typography/typography-best-practices"+ ],+ "mentions": []+ },+ "typography/font-setup": {+ "type": "docs.detail",+ "sections": [+ "overview",+ "font-families",+ "loading-custom-fonts",+ "font-sizes",+ "font-weights"+ ],+ "mentions": []+ },+ "typography/type-scale": {+ "type": "docs.detail",+ "sections": [+ "line-height",+ "type-scale",+ "display-text",+ "usage",+ "custom-type-scale"+ ],+ "mentions": []+ },+ "typography/typography-best-practices": {+ "type": "docs.detail",+ "sections": [+ "best-practices"+ ],+ "mentions": []+ },+ "use-a-theme": {+ "type": "docs.detail",+ "sections": [+ "quick-start",+ "migrating-earlier-theme-copies",+ "available-themes",+ "theme-props",+ "integration-themes",+ "light-dark-mode",+ "nesting-themes",+ "runtime-vs-built-themes"+ ],+ "mentions": []+ },+ "use-integrations": {+ "type": "docs.detail",+ "sections": [+ "discover-integrations",+ "install-an-integration",+ "use-what-it-adds",+ "check-for-problems"+ ],+ "mentions": []+ },+ "working-with-ai": {+ "type": "docs.detail",+ "sections": [+ "overview",+ "quick-start",+ "what-gets-generated",+ "cursor-setup",+ "checking-your-setup",+ "the-astryx-pattern",+ "the-dense-flag",+ "mcp-server",+ "global-mode"+ ],+ "mentions": []+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/doctor-doc-counts.txt b/packages/cli/test/__golden__/no-icon-set/doctor-doc-counts.txtnew file mode 100644index 0000000000..e3054c5150--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/doctor-doc-counts.txt@@ -0,0 +1,4 @@+authoring-docs: <text> 19+cli-docs: <text> 101 82 19+docs-tree: <text> 199 31 12+docs-progressive-disclosure: <text> 117 32diff --git a/packages/cli/test/__golden__/no-icon-set/doctor-installed-set.json b/packages/cli/test/__golden__/no-icon-set/doctor-installed-set.jsonnew file mode 100644index 0000000000..716479f1b3--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/doctor-installed-set.json@@ -0,0 +1,142 @@+{+ "apiVersion": 1,+ "type": "doctor",+ "data": {+ "checks": [+ {+ "id": "node-version",+ "label": "<text>",+ "status": "pass",+ "message": "<text> 22.13.0"+ },+ {+ "id": "core-installed",+ "label": "<text>",+ "status": "pass",+ "message": "<text>"+ },+ {+ "id": "version-alignment",+ "label": "<text>",+ "status": "pass",+ "message": "<text>"+ },+ {+ "id": "themes",+ "label": "<text>",+ "status": "warn",+ "message": "<text>",+ "fix": "<text>"+ },+ {+ "id": "theme-management",+ "label": "<text>",+ "status": "info",+ "message": "<text>",+ "fix": "<text>"+ },+ {+ "id": "config",+ "label": "<text>",+ "status": "pass",+ "message": "<text>"+ },+ {+ "id": "implicit-integrations",+ "label": "<text>",+ "status": "info",+ "message": "<text>"+ },+ {+ "id": "configured-integrations",+ "label": "<text>",+ "status": "pass",+ "message": "<text> 1"+ },+ {+ "id": "provider-identity",+ "label": "<text>",+ "status": "pass",+ "message": "<text> 1"+ },+ {+ "id": "integration-issues",+ "label": "<text>",+ "status": "pass",+ "message": "<text> 1"+ },+ {+ "id": "agent-docs",+ "label": "<text>",+ "status": "info",+ "message": "<text>",+ "fix": "<text>"+ },+ {+ "id": "peer-deps",+ "label": "<text>",+ "status": "warn",+ "message": "<text> 0.19.0",+ "fix": "<text>"+ },+ {+ "id": "package-manager",+ "label": "<text>",+ "status": "info",+ "message": "<text>"+ },+ {+ "id": "cli-command",+ "label": "<text>",+ "status": "info",+ "message": "<text>"+ },+ {+ "id": "newest-release"+ },+ {+ "id": "cli-on-path"+ },+ {+ "id": "computer-integrations"+ },+ {+ "id": "authoring-docs",+ "label": "<text>",+ "status": "pass",+ "message": "<text> 19"+ },+ {+ "id": "cli-docs",+ "label": "<text>",+ "status": "pass",+ "message": "<text> 101 82 19"+ },+ {+ "id": "docs-tree",+ "label": "<text>",+ "status": "pass",+ "message": "<text> 199 31 12"+ },+ {+ "id": "docs-progressive-disclosure",+ "label": "<text>",+ "status": "pass",+ "message": "<text> 117 32"+ }+ ],+ "summary": {+ "pass": 11,+ "warn": 2,+ "fail": 0,+ "info": 5+ }+ },+ "meta": {+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "project"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/help.txt b/packages/cli/test/__golden__/no-icon-set/help.txtnew file mode 100644index 0000000000..3ee0a85c17--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/help.txt@@ -0,0 +1,47 @@+Usage: astryx [options] [command]++<text>++Options:+ -V, --version <text>+ --zh <text>+ --dense <text>+ --lang <locale> <text>+ --detail <level> <text>+ --json <text>+ -h, --help <text>++Commands:+ init [options] <text>+ component [options] [names...] <text>+ docs [options] [topic] [section] <text>+ blog [slug] <text>+ swizzle [options] [component] <text>+ gap-report [options] [component] <text>+ template [options] [name] [path] <text>+ upgrade [options] <text>+ theme <text>+ integration <text>+ hook [options] [name] <text>+ discover [options] [query] <text>+ search [options] <query...> <text>+ build [options] [query] <text>+ doctor [options] <text>+ manifest <text>+ help <text>++<text>++<text>++<text>++<text>++<text>++<text>++Grep a field across records, e.g. <text>++<text>diff --git a/packages/cli/test/__golden__/no-icon-set/installed-set-stderr.txt b/packages/cli/test/__golden__/no-icon-set/installed-set-stderr.txtnew file mode 100644index 0000000000..6a3c0e35f0--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/installed-set-stderr.txt@@ -0,0 +1,21 @@+$ astryx component Button++$ astryx discover++$ astryx search close++$ astryx template settings-dialog+package: @astryxdesign/core++$ astryx theme list++$ astryx theme eject stone++$ astryx theme add stone++$ astryx theme use stone++$ astryx theme remove matcha++$ astryx upgrade --from 0.7.0+<text>diff --git a/packages/cli/test/__golden__/no-icon-set/integration-verify.json b/packages/cli/test/__golden__/no-icon-set/integration-verify.jsonnew file mode 100644index 0000000000..98726e78ab--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/integration-verify.json@@ -0,0 +1,59 @@+{+ "apiVersion": 1,+ "type": "integration.pack-check",+ "data": {+ "name": "@acme/widgets",+ "version": "1.0.0",+ "packable": true,+ "tarball": {+ "filename": "acme-widgets-1.0.0.tgz",+ "fileCount": 3,+ "size": "<gzip>",+ "unpackedSize": 492+ },+ "inventory": {+ "manifest": "astryx.integration.mjs",+ "roots": [+ {+ "kind": "docs",+ "path": "docs",+ "expectedFiles": 1,+ "missingFiles": [],+ "complete": true+ }+ ],+ "expectedFiles": 2,+ "packedFiles": 2+ },+ "contributions": {+ "local": {+ "themes": [],+ "components": [],+ "templates": [],+ "codemods": [],+ "docs": [+ "local-guide"+ ],+ "agentDocsAppend": []+ },+ "packed": {+ "themes": [],+ "components": [],+ "templates": [],+ "codemods": [],+ "docs": [+ "local-guide"+ ],+ "agentDocsAppend": []+ }+ },+ "issues": []+ },+ "meta": {+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "carried"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/manifest.json b/packages/cli/test/__golden__/no-icon-set/manifest.jsonnew file mode 100644index 0000000000..0907332f90--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/manifest.json@@ -0,0 +1,1813 @@+{+ "apiVersion": 1,+ "type": "manifest",+ "data": {+ "name": "astryx",+ "version": "<version>",+ "apiVersion": 1,+ "description": "<text>",+ "globalOptions": [+ {+ "flag": "-V, --version",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--zh",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--dense",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--lang <locale>",+ "description": "<text>",+ "type": "enum",+ "choices": [+ "en",+ "zh",+ "dense"+ ]+ },+ {+ "flag": "--detail <level>",+ "description": "<text>",+ "type": "enum",+ "choices": [+ "full",+ "compact",+ "brief"+ ],+ "default": "<text>"+ },+ {+ "flag": "--json",+ "description": "<text>",+ "type": "boolean"+ }+ ],+ "commands": [+ {+ "name": "blog",+ "description": "<text>",+ "arguments": [+ {+ "name": "slug",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [],+ "json": true,+ "responseTypes": [+ "<text>",+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "build",+ "description": "<text>",+ "arguments": [+ {+ "name": "query",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "--type <domain>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--limit <n>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--verbose",+ "description": "<text>",+ "type": "boolean"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>",+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "component",+ "description": "<text>",+ "arguments": [+ {+ "name": "names",+ "required": false,+ "variadic": true,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "--list",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--category <category>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--props",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--source",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--showcase",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--blocks",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--package <name>",+ "description": "<text>",+ "type": "string"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "discover",+ "description": "<text>",+ "arguments": [+ {+ "name": "query",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "--components",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--type <kind>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--installed",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--available",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--limit <n>",+ "description": "<text>",+ "type": "string"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "docs",+ "description": "<text>",+ "arguments": [+ {+ "name": "topic",+ "required": false,+ "variadic": false,+ "description": "<text>"+ },+ {+ "name": "section",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "--index",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--full",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--depth <levels>",+ "description": "<text>",+ "type": "string"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "doctor",+ "description": "<text>",+ "arguments": [],+ "options": [+ {+ "flag": "--built <path>",+ "description": "<text>",+ "type": "string"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>",+ "subcommands": [+ {+ "name": "doctor integration",+ "description": "<text>",+ "arguments": [],+ "options": [],+ "json": false,+ "examples": [+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "subcommands": [+ {+ "name": "doctor integration components",+ "description": "<text>",+ "arguments": [+ {+ "name": "package",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "doctor integration docs",+ "description": "<text>",+ "arguments": [+ {+ "name": "package",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "doctor integration templates",+ "description": "<text>",+ "arguments": [+ {+ "name": "package",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "doctor integration validate",+ "description": "<text>",+ "arguments": [+ {+ "name": "package",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ }+ ]+ }+ ]+ },+ {+ "name": "gap-report",+ "description": "<text>",+ "arguments": [+ {+ "name": "component",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "--category <category>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--reason <reason>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--additional-context <text>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--package <pkg>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--confirm-public",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--to <package>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--list-categories",+ "description": "<text>",+ "type": "boolean"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>",+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "hook",+ "description": "<text>",+ "arguments": [+ {+ "name": "name",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "--list",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--category <category>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--params",+ "description": "<text>",+ "type": "boolean"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>",+ "<text>",+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "init",+ "description": "<text>",+ "arguments": [],+ "options": [+ {+ "flag": "--features <list>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--all",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--remove-agents",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--user",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--agent <tool>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--agent-docs-path <path...>",+ "description": "<text>",+ "type": "string"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>",+ "<text>",+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "integration",+ "description": "<text>",+ "arguments": [],+ "options": [],+ "json": false,+ "examples": [+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "subcommands": [+ {+ "name": "integration add",+ "description": "<text>",+ "arguments": [+ {+ "name": "kind",+ "required": true,+ "variadic": false,+ "description": "<text>"+ },+ {+ "name": "name",+ "required": true,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "--dry-run",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--type <type>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--replaces <topic>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--extends <topic>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--parent <namespace>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--from <theme>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--to <version>",+ "description": "<text>",+ "type": "string"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "integration check",+ "description": "<text>",+ "arguments": [],+ "options": [+ {+ "flag": "--strict",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--next",+ "description": "<text>",+ "type": "boolean"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "integration pack",+ "description": "<text>",+ "arguments": [],+ "options": [+ {+ "flag": "--check",+ "description": "<text>",+ "type": "boolean"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "integration verify",+ "description": "<text>",+ "arguments": [],+ "options": [],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ }+ ]+ },+ {+ "name": "manifest",+ "description": "<text>",+ "arguments": [],+ "options": [],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "search",+ "description": "<text>",+ "arguments": [+ {+ "name": "query",+ "required": true,+ "variadic": true,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "--type <domain>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--limit <n>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--verbose",+ "description": "<text>",+ "type": "boolean"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "swizzle",+ "description": "<text>",+ "arguments": [+ {+ "name": "component",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "--output <dir>",+ "description": "<text>",+ "type": "string",+ "default": "<text>"+ },+ {+ "flag": "--package <pkg>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--list",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "-f, --overwrite",+ "description": "<text>",+ "type": "boolean"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>",+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "template",+ "description": "<text>",+ "arguments": [+ {+ "name": "name",+ "required": false,+ "variadic": false,+ "description": "<text>"+ },+ {+ "name": "path",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "--list",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--type <type>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--package <pkg>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--skeleton",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--cdn [path]",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "-f, --overwrite",+ "description": "<text>",+ "type": "boolean"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "theme",+ "description": "<text>",+ "arguments": [],+ "options": [],+ "json": false,+ "examples": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "subcommands": [+ {+ "name": "theme add",+ "description": "<text>",+ "arguments": [+ {+ "name": "slug",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "--list",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--import",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--package <package>",+ "description": "<text>",+ "type": "string"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>",+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "theme build",+ "description": "<text>",+ "arguments": [+ {+ "name": "files",+ "required": true,+ "variadic": true,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "--family",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--family-key <key>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "-o, --out <path>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--icons-specifier <specifier>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "-w, --watch",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "-c, --check",+ "description": "<text>",+ "type": "boolean"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>",+ "<text>",+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "theme eject",+ "description": "<text>",+ "arguments": [+ {+ "name": "slug",+ "required": true,+ "variadic": false,+ "description": "<text>"+ },+ {+ "name": "path",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "-f, --overwrite",+ "description": "<text>",+ "type": "boolean"+ },+ {+ "flag": "--package <package>",+ "description": "<text>",+ "type": "string"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "theme list",+ "description": "<text>",+ "arguments": [],+ "options": [+ {+ "flag": "--package <package>",+ "description": "<text>",+ "type": "string"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "theme palette",+ "description": "<text>",+ "arguments": [],+ "options": [],+ "json": false,+ "examples": [+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "subcommands": [+ {+ "name": "theme palette generate",+ "description": "<text>",+ "arguments": [+ {+ "name": "config",+ "required": true,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "-o, --out <path>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--preview <path>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "-f, --overwrite",+ "description": "<text>",+ "type": "boolean"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ }+ ]+ },+ {+ "name": "theme remove",+ "description": "<text>",+ "arguments": [+ {+ "name": "slug",+ "required": true,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "theme targets",+ "description": "<text>",+ "arguments": [+ {+ "name": "filter",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "theme template",+ "description": "<text>",+ "arguments": [+ {+ "name": "path",+ "required": false,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [+ {+ "flag": "-f, --overwrite",+ "description": "<text>",+ "type": "boolean"+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ },+ {+ "name": "theme use",+ "description": "<text>",+ "arguments": [+ {+ "name": "slug",+ "required": true,+ "variadic": false,+ "description": "<text>"+ }+ ],+ "options": [],+ "json": true,+ "responseTypes": [+ "<text>"+ ],+ "examples": [+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ }+ ]+ },+ {+ "name": "upgrade",+ "description": "<text>",+ "arguments": [],+ "options": [+ {+ "flag": "--from <version>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--apply",+ "description": "<text>",+ "type": "boolean",+ "default": false+ },+ {+ "flag": "--force",+ "description": "<text>",+ "type": "boolean",+ "default": false+ },+ {+ "flag": "--codemod <name>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--skip-codemod <name...>",+ "description": "<text>",+ "type": "string"+ },+ {+ "flag": "--integration <package>",+ "description": "<text>",+ "type": "string",+ "default": []+ },+ {+ "flag": "--path <dir>",+ "description": "<text>",+ "type": "string",+ "default": "<text>"+ },+ {+ "flag": "--install-deps",+ "description": "<text>",+ "type": "boolean",+ "default": false+ },+ {+ "flag": "--registry",+ "description": "<text>",+ "type": "boolean",+ "default": false+ },+ {+ "flag": "--list",+ "description": "<text>",+ "type": "boolean",+ "default": false+ }+ ],+ "json": true,+ "responseTypes": [+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "examples": [+ "<text>",+ "<text>",+ "<text>"+ ],+ "exitCodes": [+ {+ "code": 0,+ "when": "<text>"+ },+ {+ "code": 1,+ "when": "<text>"+ }+ ],+ "outsideProject": "<text>"+ }+ ],+ "jsonSupported": [+ "blog",+ "build",+ "component",+ "discover",+ "docs",+ "doctor",+ "doctor integration components",+ "doctor integration docs",+ "doctor integration templates",+ "doctor integration validate",+ "gap-report",+ "hook",+ "init",+ "integration add",+ "integration check",+ "integration pack",+ "integration verify",+ "manifest",+ "search",+ "swizzle",+ "template",+ "theme add",+ "theme build",+ "theme eject",+ "theme list",+ "theme palette generate",+ "theme remove",+ "theme targets",+ "theme template",+ "theme use",+ "upgrade"+ ],+ "globalMode": {+ "docs": "<text>",+ "summary": "<text>"+ },+ "responseTypes": {+ "blog": [+ "<text>",+ "<text>"+ ],+ "build": [+ "<text>",+ "<text>"+ ],+ "component": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "discover": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "docs": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "doctor": [+ "<text>"+ ],+ "doctor integration components": [+ "<text>"+ ],+ "doctor integration docs": [+ "<text>"+ ],+ "doctor integration templates": [+ "<text>"+ ],+ "doctor integration validate": [+ "<text>"+ ],+ "gap-report": [+ "<text>",+ "<text>"+ ],+ "hook": [+ "<text>",+ "<text>",+ "<text>"+ ],+ "init": [+ "<text>",+ "<text>",+ "<text>"+ ],+ "integration add": [+ "<text>"+ ],+ "integration check": [+ "<text>"+ ],+ "integration pack": [+ "<text>"+ ],+ "integration verify": [+ "<text>"+ ],+ "manifest": [+ "<text>"+ ],+ "search": [+ "<text>"+ ],+ "swizzle": [+ "<text>",+ "<text>"+ ],+ "template": [+ "<text>",+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ],+ "theme add": [+ "<text>",+ "<text>"+ ],+ "theme build": [+ "<text>",+ "<text>",+ "<text>"+ ],+ "theme eject": [+ "<text>"+ ],+ "theme list": [+ "<text>"+ ],+ "theme palette generate": [+ "<text>"+ ],+ "theme remove": [+ "<text>"+ ],+ "theme targets": [+ "<text>"+ ],+ "theme template": [+ "<text>"+ ],+ "theme use": [+ "<text>"+ ],+ "upgrade": [+ "<text>",+ "<text>",+ "<text>",+ "<text>"+ ]+ }+ },+ "meta": {+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "project"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/search-close.json b/packages/cli/test/__golden__/no-icon-set/search-close.jsonnew file mode 100644index 0000000000..b349cc7cc6--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/search-close.json@@ -0,0 +1,254 @@+{+ "apiVersion": 1,+ "type": "search",+ "data": {+ "query": "close",+ "matchCount": 43,+ "results": [+ {+ "domain": "component",+ "name": "AlertDialog",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/AlertDialog",+ "command": "astryx component AlertDialog",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "BottomSheetSwitcher",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/BottomSheet",+ "command": "astryx component BottomSheetSwitcher",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "DialogHeader",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/Dialog",+ "command": "astryx component DialogHeader",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "Drawer",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/Drawer",+ "command": "astryx component Drawer",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "DrawerHeader",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/Drawer",+ "command": "astryx component DrawerHeader",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "DropdownMenuSubMenu",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/DropdownMenu",+ "command": "astryx component DropdownMenuSubMenu",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "Toast",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/Toast",+ "command": "astryx component Toast",+ "mentions": []+ },+ {+ "domain": "hook",+ "name": "useImperativeAlertDialog",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/hooks",+ "command": "astryx hook useImperativeAlertDialog",+ "mentions": []+ },+ {+ "domain": "hook",+ "name": "useImperativeDialog",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/hooks",+ "command": "astryx hook useImperativeDialog",+ "mentions": []+ },+ {+ "domain": "hook",+ "name": "useListFocus",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/hooks",+ "command": "astryx hook useListFocus",+ "mentions": []+ },+ {+ "domain": "hook",+ "name": "usePopover",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/Popover",+ "command": "astryx hook usePopover",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "authoring/building-blocks/components/describe-the-component/subcomponent",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs authoring/building-blocks/components/describe-the-component/subcomponent write-the-subcomponent-doc",+ "parent": "astryx docs authoring/building-blocks/components/describe-the-component/subcomponent --index",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "authoring/field-reference",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs authoring/field-reference schema-doc",+ "parent": "astryx docs authoring/field-reference --index",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "browser-support",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs browser-support how-these-tiers-move-over-time",+ "parent": "astryx docs browser-support --index",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "cli/api/functions/build",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "title": "<text>",+ "command": "astryx docs cli/api/functions/build",+ "parent": "astryx docs cli/api/functions",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "icons",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs icons available-names",+ "parent": "astryx docs icons --index",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "icons",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs icons theme-overrides",+ "parent": "astryx docs icons --index",+ "mentions": [+ "This lets you swap the icon set (e.g."+ ]+ },+ {+ "domain": "doc",+ "name": "migration/component-migration",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs migration/component-migration move-the-app-frame-first",+ "parent": "astryx docs migration/component-migration --index",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "styling/styling-advanced",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs styling/styling-advanced compound-components",+ "parent": "astryx docs styling/styling-advanced --index",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "ComplexSelector",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/ComplexSelector",+ "command": "astryx component ComplexSelector",+ "mentions": []+ }+ ]+ },+ "meta": {+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "project"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/search-close.txt b/packages/cli/test/__golden__/no-icon-set/search-close.txtnew file mode 100644index 0000000000..0dc2095568--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/search-close.txt@@ -0,0 +1,108 @@+Results for "close" (20 of 43)+name: AlertDialog+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/AlertDialog+command: pnpm exec astryx component AlertDialog+name: BottomSheetSwitcher+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/BottomSheet+command: pnpm exec astryx component BottomSheetSwitcher+name: DialogHeader+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/Dialog+command: pnpm exec astryx component DialogHeader+name: Drawer+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/Drawer+command: pnpm exec astryx component Drawer+name: DrawerHeader+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/Drawer+command: pnpm exec astryx component DrawerHeader+name: DropdownMenuSubMenu+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/DropdownMenu+command: pnpm exec astryx component DropdownMenuSubMenu+name: Toast+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/Toast+command: pnpm exec astryx component Toast+name: useImperativeAlertDialog+domain: hook+package: @astryxdesign/core+import: @astryxdesign/core/hooks+command: pnpm exec astryx hook useImperativeAlertDialog+name: useImperativeDialog+domain: hook+package: @astryxdesign/core+import: @astryxdesign/core/hooks+command: pnpm exec astryx hook useImperativeDialog+name: useListFocus+domain: hook+package: @astryxdesign/core+import: @astryxdesign/core/hooks+command: pnpm exec astryx hook useListFocus+name: usePopover+domain: hook+package: @astryxdesign/core+import: @astryxdesign/core/Popover+command: pnpm exec astryx hook usePopover+name: authoring/building-blocks/components/describe-the-component/subcomponent+section: write-the-subcomponent-doc+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs authoring/building-blocks/components/describe-the-component/subcomponent write-the-subcomponent-doc+parent: pnpm exec astryx docs authoring/building-blocks/components/describe-the-component/subcomponent --index+name: authoring/field-reference+section: schema-doc+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs authoring/field-reference schema-doc+parent: pnpm exec astryx docs authoring/field-reference --index+name: browser-support+section: how-these-tiers-move-over-time+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs browser-support how-these-tiers-move-over-time+parent: pnpm exec astryx docs browser-support --index+name: cli/api/functions/build+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs cli/api/functions/build+parent: pnpm exec astryx docs cli/api/functions+name: icons+section: available-names+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs icons available-names+parent: pnpm exec astryx docs icons --index+name: icons+section: theme-overrides+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs icons theme-overrides+parent: pnpm exec astryx docs icons --index+name: migration/component-migration+section: move-the-app-frame-first+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs migration/component-migration move-the-app-frame-first+parent: pnpm exec astryx docs migration/component-migration --index+name: styling/styling-advanced+section: compound-components+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs styling/styling-advanced compound-components+parent: pnpm exec astryx docs styling/styling-advanced --index+name: ComplexSelector+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/ComplexSelector+command: pnpm exec astryx component ComplexSelector\ No newline at end of filediff --git a/packages/cli/test/__golden__/no-icon-set/search-delete.json b/packages/cli/test/__golden__/no-icon-set/search-delete.jsonnew file mode 100644index 0000000000..ca35134d43--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/search-delete.json@@ -0,0 +1,244 @@+{+ "apiVersion": 1,+ "type": "search",+ "data": {+ "query": "delete",+ "matchCount": 19,+ "results": [+ {+ "domain": "component",+ "name": "AlertDialog",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/AlertDialog",+ "command": "astryx component AlertDialog",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "global/uninstall",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "title": "<text>",+ "command": "astryx docs global/uninstall --index",+ "parent": "astryx docs global",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "Dialog",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/Dialog",+ "command": "astryx component Dialog",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "cli/api/functions/theme-template",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "title": "<text>",+ "command": "astryx docs cli/api/functions/theme-template",+ "parent": "astryx docs cli/api/functions",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "cli/commands/theme-template",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "title": "<text>",+ "command": "astryx docs cli/commands/theme-template",+ "parent": "astryx docs cli/commands",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "global/computer-agent-guide",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs global/computer-agent-guide choose",+ "parent": "astryx docs global/computer-agent-guide --index",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "global/uninstall",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs global/uninstall agent-guide",+ "parent": "astryx docs global/uninstall --index",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "global/uninstall",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs global/uninstall reset",+ "parent": "astryx docs global/uninstall --index",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "migration/migration-setup",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs migration/migration-setup foundation-smoke-test",+ "parent": "astryx docs migration/migration-setup --index",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "use-a-theme",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs use-a-theme migrating-earlier-theme-copies",+ "parent": "astryx docs use-a-theme --index",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "AlertDialogDeleteConfirmation",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template AlertDialogDeleteConfirmation --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ButtonWithIcon",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ButtonWithIcon --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "PopoverConfirmAction",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template PopoverConfirmAction --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ToastAction",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ToastAction --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "useContainerRevealHookUsage",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template useContainerRevealHookUsage --type block",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "Button",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/Button",+ "command": "astryx component Button",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "ButtonGroup",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/ButtonGroup",+ "command": "astryx component ButtonGroup",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "IconButton",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/IconButton",+ "command": "astryx component IconButton",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "ToggleButton",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/ToggleButton",+ "command": "astryx component ToggleButton",+ "mentions": []+ }+ ]+ },+ "meta": {+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "project"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/search-delete.txt b/packages/cli/test/__golden__/no-icon-set/search-delete.txtnew file mode 100644index 0000000000..33ad6800d6--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/search-delete.txt@@ -0,0 +1,96 @@+Results for "delete" (19)+name: AlertDialog+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/AlertDialog+command: pnpm exec astryx component AlertDialog+name: global/uninstall+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs global/uninstall --index+parent: pnpm exec astryx docs global+name: Dialog+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/Dialog+command: pnpm exec astryx component Dialog+name: cli/api/functions/theme-template+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs cli/api/functions/theme-template+parent: pnpm exec astryx docs cli/api/functions+name: cli/commands/theme-template+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs cli/commands/theme-template+parent: pnpm exec astryx docs cli/commands+name: global/computer-agent-guide+section: choose+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs global/computer-agent-guide choose+parent: pnpm exec astryx docs global/computer-agent-guide --index+name: global/uninstall+section: agent-guide+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs global/uninstall agent-guide+parent: pnpm exec astryx docs global/uninstall --index+name: global/uninstall+section: reset+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs global/uninstall reset+parent: pnpm exec astryx docs global/uninstall --index+name: migration/migration-setup+section: foundation-smoke-test+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs migration/migration-setup foundation-smoke-test+parent: pnpm exec astryx docs migration/migration-setup --index+name: use-a-theme+section: migrating-earlier-theme-copies+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs use-a-theme migrating-earlier-theme-copies+parent: pnpm exec astryx docs use-a-theme --index+name: AlertDialogDeleteConfirmation+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template AlertDialogDeleteConfirmation --type block+name: ButtonWithIcon+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ButtonWithIcon --type block+name: PopoverConfirmAction+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template PopoverConfirmAction --type block+name: ToastAction+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ToastAction --type block+name: useContainerRevealHookUsage+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template useContainerRevealHookUsage --type block+name: Button+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/Button+command: pnpm exec astryx component Button+name: ButtonGroup+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/ButtonGroup+command: pnpm exec astryx component ButtonGroup+name: IconButton+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/IconButton+command: pnpm exec astryx component IconButton+name: ToggleButton+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/ToggleButton+command: pnpm exec astryx component ToggleButton\ No newline at end of filediff --git a/packages/cli/test/__golden__/no-icon-set/search-experimental.json b/packages/cli/test/__golden__/no-icon-set/search-experimental.jsonnew file mode 100644index 0000000000..9c175f9957--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/search-experimental.json@@ -0,0 +1,63 @@+{+ "apiVersion": 1,+ "type": "search",+ "data": {+ "query": "experimental",+ "matchCount": 3,+ "results": [+ {+ "domain": "doc",+ "name": "authoring/field-reference",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs authoring/field-reference config",+ "parent": "astryx docs authoring/field-reference --index",+ "mentions": [+ "Declares which integrations to load, where to route issue links, post-codemod hooks, local debug-log and gap-report handlers, a discover source, and experimental layout components.…",+ "description mentions \"experimental\""+ ]+ },+ {+ "domain": "doc",+ "name": "authoring/field-reference",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs authoring/field-reference schema-doc",+ "parent": "astryx docs authoring/field-reference --index",+ "mentions": [+ "docs mention \"experimental\""+ ]+ },+ {+ "domain": "doc",+ "name": "authoring/field-reference",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs authoring/field-reference template-doc",+ "parent": "astryx docs authoring/field-reference --index",+ "mentions": [+ "docs mention \"experimental\""+ ]+ }+ ]+ },+ "meta": {+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "project"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/search-experimental.txt b/packages/cli/test/__golden__/no-icon-set/search-experimental.txtnew file mode 100644index 0000000000..718e7bde86--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/search-experimental.txt@@ -0,0 +1,19 @@+Results for "experimental" (3)+name: authoring/field-reference+section: config+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs authoring/field-reference config+parent: pnpm exec astryx docs authoring/field-reference --index+name: authoring/field-reference+section: schema-doc+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs authoring/field-reference schema-doc+parent: pnpm exec astryx docs authoring/field-reference --index+name: authoring/field-reference+section: template-doc+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs authoring/field-reference template-doc+parent: pnpm exec astryx docs authoring/field-reference --index\ No newline at end of filediff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json b/packages/cli/test/__golden__/no-icon-set/search-icon-set.jsonnew file mode 100644index 0000000000..c931a71b43--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json@@ -0,0 +1,257 @@+{+ "apiVersion": 1,+ "type": "search",+ "data": {+ "query": "icon set",+ "matchCount": 367,+ "results": [+ {+ "domain": "doc",+ "name": "authoring/building-blocks/templates/build-the-template/template-assets/template-icons",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs authoring/building-blocks/templates/build-the-template/template-assets/template-icons use-astryx-icon",+ "parent": "astryx docs authoring/building-blocks/templates/build-the-template/template-assets/template-icons --index",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ToolbarTableFilter",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ToolbarTableFilter --type block",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "icons",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs icons theme-overrides",+ "parent": "astryx docs icons --index",+ "mentions": [+ "This lets you swap the icon set (e.g."+ ]+ },+ {+ "domain": "component",+ "name": "Icon",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/Icon",+ "command": "astryx component Icon",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "icons",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "title": "<text>",+ "command": "astryx docs icons --index",+ "parent": "astryx docs foundations",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "IconButton",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/IconButton",+ "command": "astryx component IconButton",+ "mentions": []+ },+ {+ "domain": "hook",+ "name": "useInputContainer",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/hooks",+ "command": "astryx hook useInputContainer",+ "mentions": []+ },+ {+ "domain": "hook",+ "name": "useInputStatusIcon",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/hooks",+ "command": "astryx hook useInputStatusIcon",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "BaseTypeaheadCustomSearch",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template BaseTypeaheadCustomSearch --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "BottomSheetSnapPoints",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template BottomSheetSnapPoints --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "BreadcrumbsDeepHierarchy",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template BreadcrumbsDeepHierarchy --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "BreadcrumbsWithIcons",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template BreadcrumbsWithIcons --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ButtonFloating",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ButtonFloating --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ButtonGroupShowcase",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ButtonGroupShowcase --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ButtonWithIcon",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ButtonWithIcon --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "CenterHorizontal",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template CenterHorizontal --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "CenterInsideACard",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template CenterInsideACard --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ChatComposerDrawerShowcase",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ChatComposerDrawerShowcase --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ChatComposerDrawerWithProgress",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ChatComposerDrawerWithProgress --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ChatComposerFooterActions",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ChatComposerFooterActions --type block",+ "mentions": []+ }+ ]+ },+ "meta": {+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "project"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txtnew file mode 100644index 0000000000..6e222060b3--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt@@ -0,0 +1,90 @@+Results for "icon set" (20 of 367)+name: authoring/building-blocks/templates/build-the-template/template-assets/template-icons+section: use-astryx-icon+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs authoring/building-blocks/templates/build-the-template/template-assets/template-icons use-astryx-icon+parent: pnpm exec astryx docs authoring/building-blocks/templates/build-the-template/template-assets/template-icons --index+name: ToolbarTableFilter+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ToolbarTableFilter --type block+name: icons+section: theme-overrides+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs icons theme-overrides+parent: pnpm exec astryx docs icons --index+name: Icon+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/Icon+command: pnpm exec astryx component Icon+name: icons+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs icons --index+parent: pnpm exec astryx docs foundations+name: IconButton+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/IconButton+command: pnpm exec astryx component IconButton+name: useInputContainer+domain: hook+package: @astryxdesign/core+import: @astryxdesign/core/hooks+command: pnpm exec astryx hook useInputContainer+name: useInputStatusIcon+domain: hook+package: @astryxdesign/core+import: @astryxdesign/core/hooks+command: pnpm exec astryx hook useInputStatusIcon+name: BaseTypeaheadCustomSearch+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template BaseTypeaheadCustomSearch --type block+name: BottomSheetSnapPoints+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template BottomSheetSnapPoints --type block+name: BreadcrumbsDeepHierarchy+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template BreadcrumbsDeepHierarchy --type block+name: BreadcrumbsWithIcons+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template BreadcrumbsWithIcons --type block+name: ButtonFloating+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ButtonFloating --type block+name: ButtonGroupShowcase+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ButtonGroupShowcase --type block+name: ButtonWithIcon+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ButtonWithIcon --type block+name: CenterHorizontal+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template CenterHorizontal --type block+name: CenterInsideACard+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template CenterInsideACard --type block+name: ChatComposerDrawerShowcase+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ChatComposerDrawerShowcase --type block+name: ChatComposerDrawerWithProgress+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ChatComposerDrawerWithProgress --type block+name: ChatComposerFooterActions+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ChatComposerFooterActions --type block\ No newline at end of filediff --git a/packages/cli/test/__golden__/no-icon-set/search-icon.json b/packages/cli/test/__golden__/no-icon-set/search-icon.jsonnew file mode 100644index 0000000000..7505e0b6f4--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/search-icon.json@@ -0,0 +1,253 @@+{+ "apiVersion": 1,+ "type": "search",+ "data": {+ "query": "icon",+ "matchCount": 221,+ "results": [+ {+ "domain": "component",+ "name": "Icon",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/Icon",+ "command": "astryx component Icon",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "icons",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "title": "<text>",+ "command": "astryx docs icons --index",+ "parent": "astryx docs foundations",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "IconButton",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/IconButton",+ "command": "astryx component IconButton",+ "mentions": []+ },+ {+ "domain": "hook",+ "name": "useInputContainer",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/hooks",+ "command": "astryx hook useInputContainer",+ "mentions": []+ },+ {+ "domain": "hook",+ "name": "useInputStatusIcon",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/hooks",+ "command": "astryx hook useInputStatusIcon",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "BaseTypeaheadCustomSearch",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template BaseTypeaheadCustomSearch --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "BottomSheetSnapPoints",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template BottomSheetSnapPoints --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "BreadcrumbsDeepHierarchy",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template BreadcrumbsDeepHierarchy --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "BreadcrumbsWithIcons",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template BreadcrumbsWithIcons --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ButtonFloating",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ButtonFloating --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ButtonGroupShowcase",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ButtonGroupShowcase --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ButtonWithIcon",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ButtonWithIcon --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "CenterHorizontal",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template CenterHorizontal --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "CenterInsideACard",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template CenterInsideACard --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ChatComposerDrawerShowcase",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ChatComposerDrawerShowcase --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ChatComposerDrawerWithProgress",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ChatComposerDrawerWithProgress --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ChatComposerFooterActions",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ChatComposerFooterActions --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ChatComposerFullFeatured",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ChatComposerFullFeatured --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ChatMessageBubbleMetadata",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ChatMessageBubbleMetadata --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ChatMessageMetadataFooter",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ChatMessageMetadataFooter --type block",+ "mentions": []+ }+ ]+ },+ "meta": {+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "project"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon.txt b/packages/cli/test/__golden__/no-icon-set/search-icon.txtnew file mode 100644index 0000000000..a3b81501a3--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/search-icon.txt@@ -0,0 +1,86 @@+Results for "icon" (20 of 221)+name: Icon+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/Icon+command: pnpm exec astryx component Icon+name: icons+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs icons --index+parent: pnpm exec astryx docs foundations+name: IconButton+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/IconButton+command: pnpm exec astryx component IconButton+name: useInputContainer+domain: hook+package: @astryxdesign/core+import: @astryxdesign/core/hooks+command: pnpm exec astryx hook useInputContainer+name: useInputStatusIcon+domain: hook+package: @astryxdesign/core+import: @astryxdesign/core/hooks+command: pnpm exec astryx hook useInputStatusIcon+name: BaseTypeaheadCustomSearch+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template BaseTypeaheadCustomSearch --type block+name: BottomSheetSnapPoints+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template BottomSheetSnapPoints --type block+name: BreadcrumbsDeepHierarchy+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template BreadcrumbsDeepHierarchy --type block+name: BreadcrumbsWithIcons+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template BreadcrumbsWithIcons --type block+name: ButtonFloating+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ButtonFloating --type block+name: ButtonGroupShowcase+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ButtonGroupShowcase --type block+name: ButtonWithIcon+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ButtonWithIcon --type block+name: CenterHorizontal+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template CenterHorizontal --type block+name: CenterInsideACard+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template CenterInsideACard --type block+name: ChatComposerDrawerShowcase+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ChatComposerDrawerShowcase --type block+name: ChatComposerDrawerWithProgress+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ChatComposerDrawerWithProgress --type block+name: ChatComposerFooterActions+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ChatComposerFooterActions --type block+name: ChatComposerFullFeatured+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ChatComposerFullFeatured --type block+name: ChatMessageBubbleMetadata+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ChatMessageBubbleMetadata --type block+name: ChatMessageMetadataFooter+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ChatMessageMetadataFooter --type block\ No newline at end of filediff --git a/packages/cli/test/__golden__/no-icon-set/search-search.json b/packages/cli/test/__golden__/no-icon-set/search-search.jsonnew file mode 100644index 0000000000..6bc0a9281b--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/search-search.json@@ -0,0 +1,256 @@+{+ "apiVersion": 1,+ "type": "search",+ "data": {+ "query": "search",+ "matchCount": 112,+ "results": [+ {+ "domain": "doc",+ "name": "cli/api/functions/search",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "title": "<text>",+ "command": "astryx docs cli/api/functions/search",+ "parent": "astryx docs cli/api/functions",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "cli/commands/search",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "title": "<text>",+ "command": "astryx docs cli/commands/search",+ "parent": "astryx docs cli/commands",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "ChatToolCalls",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/Chat",+ "command": "astryx component ChatToolCalls",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "CommandPalette",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/CommandPalette",+ "command": "astryx component CommandPalette",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "PowerSearch",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/PowerSearch",+ "command": "astryx component PowerSearch",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "TextInput",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/TextInput",+ "command": "astryx component TextInput",+ "mentions": []+ },+ {+ "domain": "hook",+ "name": "useTypeahead",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/hooks",+ "command": "astryx hook useTypeahead",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "Typeahead",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/Typeahead",+ "command": "astryx component Typeahead",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "PowerSearchContentSearch",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template PowerSearchContentSearch --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "PowerSearchFullFeatured",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template PowerSearchFullFeatured --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "PowerSearchPresetFilters",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template PowerSearchPresetFilters --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "PowerSearchSearchWithTable",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template PowerSearchSearchWithTable --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "PowerSearchShowcase",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template PowerSearchShowcase --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "TableFilterableTable",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template TableFilterableTable --type block",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "TableInlineFilterTable",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template TableInlineFilterTable --type block",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "authoring/building-blocks/templates/document-the-template/template-doc-overview",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs authoring/building-blocks/templates/document-the-template/template-doc-overview document-the-shared-fields",+ "parent": "astryx docs authoring/building-blocks/templates/document-the-template/template-doc-overview --index",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "authoring/field-reference",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs authoring/field-reference config",+ "parent": "astryx docs authoring/field-reference --index",+ "mentions": [+ "Declares which integrations to load, where to route issue links, post-codemod hooks, local debug-log and gap-report handlers, a discover source, and experimental layout components.…"+ ]+ },+ {+ "domain": "doc",+ "name": "cli/api/enums/response-types",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "title": "<text>",+ "command": "astryx docs cli/api/enums/response-types",+ "parent": "astryx docs cli/api/enums",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "cli/api/functions/discover",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "title": "<text>",+ "command": "astryx docs cli/api/functions/discover",+ "parent": "astryx docs cli/api/functions",+ "mentions": []+ },+ {+ "domain": "doc",+ "name": "global/problems",+ "package": "@astryxdesign/cli",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "section": "<text>",+ "title": "<text>",+ "command": "astryx docs global/problems core-offline",+ "parent": "astryx docs global/problems --index",+ "mentions": []+ }+ ]+ },+ "meta": {+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "project"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/search-search.txt b/packages/cli/test/__golden__/no-icon-set/search-search.txtnew file mode 100644index 0000000000..2112617cef--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/search-search.txt@@ -0,0 +1,97 @@+Results for "search" (20 of 112)+name: cli/api/functions/search+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs cli/api/functions/search+parent: pnpm exec astryx docs cli/api/functions+name: cli/commands/search+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs cli/commands/search+parent: pnpm exec astryx docs cli/commands+name: ChatToolCalls+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/Chat+command: pnpm exec astryx component ChatToolCalls+name: CommandPalette+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/CommandPalette+command: pnpm exec astryx component CommandPalette+name: PowerSearch+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/PowerSearch+command: pnpm exec astryx component PowerSearch+name: TextInput+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/TextInput+command: pnpm exec astryx component TextInput+name: useTypeahead+domain: hook+package: @astryxdesign/core+import: @astryxdesign/core/hooks+command: pnpm exec astryx hook useTypeahead+name: Typeahead+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/Typeahead+command: pnpm exec astryx component Typeahead+name: PowerSearchContentSearch+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template PowerSearchContentSearch --type block+name: PowerSearchFullFeatured+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template PowerSearchFullFeatured --type block+name: PowerSearchPresetFilters+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template PowerSearchPresetFilters --type block+name: PowerSearchSearchWithTable+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template PowerSearchSearchWithTable --type block+name: PowerSearchShowcase+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template PowerSearchShowcase --type block+name: TableFilterableTable+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template TableFilterableTable --type block+name: TableInlineFilterTable+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template TableInlineFilterTable --type block+name: authoring/building-blocks/templates/document-the-template/template-doc-overview+section: document-the-shared-fields+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs authoring/building-blocks/templates/document-the-template/template-doc-overview document-the-shared-fields+parent: pnpm exec astryx docs authoring/building-blocks/templates/document-the-template/template-doc-overview --index+name: authoring/field-reference+section: config+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs authoring/field-reference config+parent: pnpm exec astryx docs authoring/field-reference --index+name: cli/api/enums/response-types+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs cli/api/enums/response-types+parent: pnpm exec astryx docs cli/api/enums+name: cli/api/functions/discover+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs cli/api/functions/discover+parent: pnpm exec astryx docs cli/api/functions+name: global/problems+section: core-offline+domain: doc+package: @astryxdesign/cli+command: pnpm exec astryx docs global/problems core-offline+parent: pnpm exec astryx docs global/problems --index\ No newline at end of filediff --git a/packages/cli/test/__golden__/no-icon-set/search-trash-can.json b/packages/cli/test/__golden__/no-icon-set/search-trash-can.jsonnew file mode 100644index 0000000000..bdfafe8912--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/search-trash-can.json@@ -0,0 +1,51 @@+{+ "apiVersion": 1,+ "type": "search",+ "data": {+ "query": "trash can",+ "matchCount": 3,+ "results": [+ {+ "domain": "component",+ "name": "Icon",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/Icon",+ "command": "astryx component Icon",+ "mentions": []+ },+ {+ "domain": "component",+ "name": "IconButton",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "import": "@astryxdesign/core/IconButton",+ "command": "astryx component IconButton",+ "mentions": []+ },+ {+ "domain": "template",+ "name": "ButtonWithIcon",+ "package": "@astryxdesign/core",+ "score": "<text>",+ "reason": "<text>",+ "description": "<text>",+ "displayName": "<text>",+ "kind": "block",+ "command": "astryx template ButtonWithIcon --type block",+ "mentions": []+ }+ ]+ },+ "meta": {+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "project"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/search-trash-can.txt b/packages/cli/test/__golden__/no-icon-set/search-trash-can.txtnew file mode 100644index 0000000000..f1a76e2ace--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/search-trash-can.txt@@ -0,0 +1,15 @@+Results for "trash can" (3)+name: Icon+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/Icon+command: pnpm exec astryx component Icon+name: IconButton+domain: component+package: @astryxdesign/core+import: @astryxdesign/core/IconButton+command: pnpm exec astryx component IconButton+name: ButtonWithIcon+domain: template+package: @astryxdesign/core+command: pnpm exec astryx template ButtonWithIcon --type block\ No newline at end of filediff --git a/packages/cli/test/__golden__/no-icon-set/template-copy.json b/packages/cli/test/__golden__/no-icon-set/template-copy.jsonnew file mode 100644index 0000000000..180331c77e--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/template-copy.json@@ -0,0 +1,27 @@+{+ "apiVersion": 1,+ "type": "template.copy",+ "package": "@astryxdesign/core",+ "data": {+ "template": "settings-dialog",+ "outputDir": "out/json",+ "fileName": "page.tsx",+ "filesCopied": 1,+ "demoMediaReplaced": 0,+ "notes": [+ "<text>",+ "<text>"+ ],+ "missingPackages": [+ "@heroicons/react"+ ],+ "installCommand": "pnpm add @heroicons/react@\"^2.2.0\""+ },+ "meta": {+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "project"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/template-copy.txt b/packages/cli/test/__golden__/no-icon-set/template-copy.txtnew file mode 100644index 0000000000..4f3b95332b--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/template-copy.txt@@ -0,0 +1,7 @@+Copied template to out/text/page.tsx++package: @astryxdesign/core++Install missing dependencies: pnpm add @heroicons/react@"^2.2.0"++<text>diff --git a/packages/cli/test/__golden__/no-icon-set/template-show.json b/packages/cli/test/__golden__/no-icon-set/template-show.jsonnew file mode 100644index 0000000000..07420d4704--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/template-show.json@@ -0,0 +1,40 @@+{+ "apiVersion": 1,+ "type": "template.show",+ "package": "@astryxdesign/core",+ "data": {+ "template": "settings-dialog",+ "description": "<text>",+ "type": "page",+ "components": [+ "AspectRatio",+ "Card",+ "Center",+ "Dialog",+ "Divider",+ "Grid",+ "IconButton",+ "Kbd",+ "Layout",+ "List",+ "SegmentedControl",+ "SelectableCard",+ "Selector",+ "SideNav",+ "Stack",+ "Switch",+ "TextInput",+ "Token",+ "Tooltip"+ ],+ "source": "<text>",+ "demoMediaReplaced": 0+ },+ "meta": {+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "project"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/validate-installed-set.json b/packages/cli/test/__golden__/no-icon-set/validate-installed-set.jsonnew file mode 100644index 0000000000..b5aba37f89--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/validate-installed-set.json@@ -0,0 +1,38 @@+{+ "apiVersion": 1,+ "type": "integration.validate",+ "data": {+ "validated": true,+ "name": "@acme/glyphs",+ "version": "1.0.0",+ "issues": [],+ "docTypes": {+ "status": "checked",+ "docs": 0,+ "findings": [],+ "unchecked": []+ },+ "docNames": {+ "status": "checked",+ "findings": [],+ "unchecked": []+ },+ "blockComponents": {+ "status": "checked",+ "findings": [],+ "unchecked": []+ },+ "publicImports": {+ "status": "checked",+ "findings": [],+ "unchecked": []+ }+ },+ "meta": {+ "answeredBy": {+ "cli": "<version>",+ "core": "<version>",+ "copy": "project"+ }+ }+}diff --git a/packages/cli/test/__golden__/no-icon-set/validate-installed-set.txt b/packages/cli/test/__golden__/no-icon-set/validate-installed-set.txtnew file mode 100644index 0000000000..69c12644b7--- /dev/null+++ b/packages/cli/test/__golden__/no-icon-set/validate-installed-set.txt@@ -0,0 +1,8 @@+exit 0+Validating integration: @acme/[email protected]++<text>++Summary: 0 errors, 0 warnings++<text>diff --git a/packages/cli/test/authoring-self-docs-match-types.test.mjs b/packages/cli/test/authoring-self-docs-match-types.test.mjsindex 5d2811e110..b7439d57cf 100644--- a/packages/cli/test/authoring-self-docs-match-types.test.mjs+++ b/packages/cli/test/authoring-self-docs-match-types.test.mjs@@ -23,7 +23,7 @@ const SUBPATHS = ['codemod','debug',];-const GRAPH_FIELDS = ['placement', 'aliases', 'audience'];+const GRAPH_FIELDS = ['placement', 'aliases', 'audience', 'stability'];/** Each self-doc and the published type (or union) it describes. */const SELF_DOCS = {diff --git a/packages/cli/test/authoring-types/all-kinds.doc.ts b/packages/cli/test/authoring-types/all-kinds.doc.tsindex 326b06d0b4..38807374c5 100644--- a/packages/cli/test/authoring-types/all-kinds.doc.ts+++ b/packages/cli/test/authoring-types/all-kinds.doc.ts@@ -12,6 +12,7 @@ import type {EnumDoc,FunctionDoc,HookDoc,+ IconDefinitionDoc,ReferenceDoc,SchemaDoc,TemplateDoc,@@ -107,6 +108,13 @@ export const theme = {maintained: true,} satisfies ThemeDoc;+export const iconDefinition = {+ type: 'icon-definition',+ name: 'delete',+ description: 'Delete something permanently.',+ words: ['trash', 'bin'],+} satisfies IconDefinitionDoc;+// A required field left out is a type error, not a runtime surprise.export const missingUsage = {type: 'component',diff --git a/packages/cli/test/authoring-types/icon-definition.doc.mjs b/packages/cli/test/authoring-types/icon-definition.doc.mjsnew file mode 100644index 0000000000..ee92012cad--- /dev/null+++ b/packages/cli/test/authoring-types/icon-definition.doc.mjs@@ -0,0 +1,9 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').IconDefinitionDoc} */+export const docs = {+ type: 'icon-definition',+ name: 'delete',+ description: 'Delete something permanently.',+ words: ['trash', 'bin'],+};diff --git a/packages/cli/test/docs-graph.test.mjs b/packages/cli/test/docs-graph.test.mjsindex b3d77093d9..03fedffa64 100644--- a/packages/cli/test/docs-graph.test.mjs+++ b/packages/cli/test/docs-graph.test.mjs@@ -32,6 +32,7 @@ import {loadCliSelfDocs,} from '../foundation/discovery/cli-self-docs.mjs';import {routeSegment} from '../foundation/discovery/docs-section-key.mjs';+import {EXPERIMENTAL_AUTHORING_ROUTE} from '../foundation/discovery/authoring-self-docs.mjs';import {generateCompressedIndex} from '../foundation/agent-docs/agent-docs.mjs';import {program, JSON_SUPPORTED} from '../clients/cli/index.mjs';import {buildManifest} from '../clients/cli/lib/manifest.mjs';@@ -406,25 +407,31 @@ describe('the docs graph', () => {// of the field reference, which `astryx docs authoring <name>` reads.const {loaded, failed} = await loadCliSelfDocs(discoverCliSelfDocSources(CLI), CLI);expect(failed).toEqual([]);- const authoring =- reads.get(`${TOP} authoring/field-reference --index`)?.data.sections ??- reads.get(`${TOP} authoring/field-reference`)?.data.sections ??- [];- expect(authoring.length).toBeGreaterThan(10);+ // An experimental schema is a section of its own experimental route+ // instead (spec:AST-084 FR0); that route is a tree node, and one read+ // returns all its sections.+ const sectionsOf = (/** @type {string} */ route) =>+ (reads.get(`${TOP} ${route} --index`) ?? reads.get(`${TOP} ${route}`))+ ?.data.sections ?? [];+ expect(sectionsOf('authoring/field-reference').length).toBeGreaterThan(10);for (const {source, doc} of loaded) {const leaf = [...tree.nodes.values()].find(node => node.kind === doc.type && node.name === doc.name,);- const section = authoring.find(+ const route =+ doc.stability === 'experimental'+ ? EXPERIMENTAL_AUTHORING_ROUTE+ : 'authoring/field-reference';+ const section = sectionsOf(route).find((/** @type {any} */ s) => s.id === routeSegment(doc.name) || s.title === doc.displayName,);const ok = leaf? reached(`${TOP} ${leaf.route}`): section? reached(`${TOP} authoring ${section.id}`) ||- reached(`${TOP} authoring/field-reference ${section.id}`) ||- // The walk opens the field reference whole, with every section.- reached(`${TOP} authoring/field-reference`)+ reached(`${TOP} ${route} ${section.id}`) ||+ // The walk opens the reference whole, with every section.+ reached(`${TOP} ${route}`): false;if (!ok) unreached.push(source);}diff --git a/packages/cli/test/experimental-isolation.test.mjs b/packages/cli/test/experimental-isolation.test.mjsnew file mode 100644index 0000000000..6f91f1fedd--- /dev/null+++ b/packages/cli/test/experimental-isolation.test.mjs@@ -0,0 +1,1300 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Experimental isolation (spec:AST-017 FR27, spec:AST-084 FR0): in a+ * project with no icon set installed and no `experimental.iconSet`, every+ * stable command answers exactly as it does without icon sets.+ *+ * The goldens under `__golden__/no-icon-set/` were written by the CLI+ * without the icon-set feature, so a result, field, section, count, or+ * `stability` that an experimental surface adds to search, the docs, a+ * template copy, doctor, or an integration's verify report fails here, as+ * does any sentence that names an experimental surface. They hold no prose+ * (titles, summaries, descriptions, snippets), so main's ordinary doc and+ * command wording edits rewrite none of them. Help, the+ * manifest, and the `astryx docs cli` listing gain only the experimental+ * group or namespace, the one marked entry point FR27 allows.+ *+ * Updating the goldens has two phases.+ *+ * While main lacks the icon-set feature (before the feature lands), the+ * goldens are main's own output: regenerate them from a checkout of main+ * with `GOLDEN_CLI_BIN=<main>/packages/cli/clients/cli/bin/astryx.mjs+ * GOLDEN_CLI_ROOT=<main>/packages/cli vitest run+ * packages/cli/test/experimental-isolation.test.mjs --update`, run from this+ * checkout. Name the file before `--update`: vitest 4 reads `-u <file>` as+ * the value of `-u` and updates every suite. That runs+ * main's CLI in test projects created inside main's checkout, so main's CLI+ * and Core answer: a project inside this checkout would hand the run over to+ * this checkout's CLI, and the goldens would record this branch's own output.+ * A run that hands over fails. Tests that need the feature are skipped while+ * regenerating, and every golden that this branch's CLI may add to (help,+ * the manifest, the `cli` docs listings) is compared with those additions+ * stripped.+ *+ * Once the feature is on main, a branch with an intended change to stable+ * output runs `vitest run packages/cli/test/experimental-isolation.test.mjs+ * --update` in the branch itself, then reviews+ * the diff of `__golden__/no-icon-set/`: a diff that names an icon set, an+ * icon definition, or `experimental` is the leak this test exists to catch.+ */++import {afterAll, beforeAll, describe, expect, it} from 'vitest';+import {spawnSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {createHash} from 'node:crypto';+import {pathToFileURL} from 'node:url';+import {CLI_ROOT} from '../foundation/fs/paths.mjs';+import {writeIconSetProject} from '../test-utils/icon-set-fixture.mjs';++const REPO_ROOT = path.resolve(CLI_ROOT, '..', '..');+// Goldens come from the CLI without the feature: point these at a checkout of+// main to rewrite them (`GOLDEN_CLI_BIN=<main>/packages/cli/clients/cli/bin/+// astryx.mjs GOLDEN_CLI_ROOT=<main>/packages/cli vitest run+// packages/cli/test/experimental-isolation.test.mjs --update`).+const CLI_BIN =+ process.env.GOLDEN_CLI_BIN ??+ path.join(CLI_ROOT, 'clients', 'cli', 'bin', 'astryx.mjs');+const GOLDEN_REPO = process.env.GOLDEN_CLI_ROOT+ ? path.resolve(process.env.GOLDEN_CLI_ROOT, '..', '..')+ : REPO_ROOT;+const GOLDEN = path.join(CLI_ROOT, 'test', '__golden__', 'no-icon-set');+/** Words an experimental surface's text uses; a stable doc that gains one leaks. */+const LEAK_WORDS =+ /\bexperimental\b|\bicon[- ]?sets?\b|\bicon[- ]definitions?\b/iu;+/** Writing the goldens from main's CLI, not checking this branch's. */+const REGENERATING = Boolean(process.env.GOLDEN_CLI_ROOT);+/**+ * The release of the CLI that answers, read from its package.json: each exact+ * mention becomes `<version>`, so a release bump rewrites no golden.+ */+const CLI_VERSION = JSON.parse(+ fs.readFileSync(+ path.join(process.env.GOLDEN_CLI_ROOT ?? CLI_ROOT, 'package.json'),+ 'utf8',+ ),+).version;+/**+ * The version alone, bare or after `v`: no letter, digit, dot, or hyphen+ * around it, so `0.7.40`, `10.7.4`, and a prerelease never match.+ */+const VERSION_PATTERN = new RegExp(+ `(?<![\\w.-])(v?)${CLI_VERSION.replaceAll('.', '\\.')}(?![\\w-]|\\.\\w)`,+ 'gu',+);+/**+ * Every command that prints the integration-issue nudge to stderr (spec:AST-084+ * FR0), with an invocation that reaches it: in text mode, after the command+ * succeeds. Run in this order, in one project (the theme writers build on one+ * another; `upgrade` is a dry run).+ */+const NUDGE_COMMANDS = [+ {name: 'component', args: ['component', 'Button']},+ {name: 'discover', args: ['discover']},+ {name: 'search', args: ['search', 'close']},+ {name: 'template', args: ['template', 'settings-dialog']},+ {name: 'theme list', args: ['theme', 'list']},+ {name: 'theme eject', args: ['theme', 'eject', 'stone']},+ {name: 'theme add', args: ['theme', 'add', 'stone']},+ {name: 'theme use', args: ['theme', 'use', 'stone']},+ {name: 'theme remove', args: ['theme', 'remove', 'matcha']},+ {name: 'upgrade', args: ['upgrade', '--from', '0.7.0']},+];+/** A call of the nudge or of a wrapper around it. */+const NUDGE_CALL =+ /(?<!function )\b(?:warnOnIntegrationIssues|warnOnThemeIntegrationIssues|warnIntegrationIssues)\(/gu;+/**+ * Where NUDGE_CALL appears, by file, and how often: the commands above and+ * the two wrappers (theme.mjs and upgrade's adapter each call the nudge once).+ */+const NUDGE_CALLERS = {+ // component+ 'clients/cli/commands/component.mjs': 1,+ // discover+ 'clients/cli/commands/discover.mjs': 1,+ // search+ 'clients/cli/commands/search.mjs': 1,+ // template+ 'clients/cli/commands/template.mjs': 1,+ // the wrapper, then theme list, add, remove, use, eject+ 'clients/cli/commands/theme.mjs': 6,+ // upgrade: the wrapper, and its one call+ 'api/upgrade/_adapter.mjs': 1,+ 'api/upgrade/run/run.mjs': 1,+};+/**+ * Every source file that reads an integration's icon-set root (`.iconSets`)+ * or runs icon-set discovery or checks, and why a project without+ * `experimental.iconSet` never sees what it reads (spec:AST-084 FR0, FR17).+ * A new reader fails the test below until it is listed with its gate.+ */+const ICON_SET_READERS = {+ // Readers that hold the gate.+ 'foundation/config/project.mjs':+ 'iconSets() reads no set without the opt-in; integration issues strip the root without it',+ 'api/integration/validate-integration.mjs':+ 'an installed package is checked only with the opt-in; the package being authored always',+ 'api/upgrade/run/run.mjs':+ 'passes the opt-in to the nudge, which strips the root without it',+ 'api/discover/_adapter.mjs':+ 'reads sets only with the opt-in, and strips the root before collecting identities',+ // Readers behind a gated reader.+ 'api/doctor/doctor.mjs': 'project.iconSets()',+ 'api/template/_adapter.mjs': 'project.iconSets()',+ 'foundation/doc-compiler/inputs.mjs': 'project.iconSets()',+ 'foundation/discovery/icon-set-discovery.mjs':+ 'discovery itself: called by the gated readers',+ 'foundation/discovery/icon-set-checks.mjs':+ 'the checks: called by validate-integration',+ 'foundation/discovery/integration-doc-files.mjs':+ 'the loaded root validate-integration resolved, so only with its gate',+ 'foundation/integrations/contribution-inventory.mjs':+ 'the package being authored (verify, pack-check, writers), or the root a gated caller passes',+ 'foundation/integrations/validate-contributions.mjs':+ 'the root of the integration a gated caller passes',+ 'foundation/integrations/integrations.mjs':+ 'resolves the root on the loaded integration; every reader of it is listed here',+ 'foundation/integrations/manifest-writer.mjs':+ 'writes the root of the package being authored',+ // The experimental commands and the authoring output.+ 'api/icon/_adapter.mjs': 'astryx experimental icon',+ 'api/icon/_authoring.mjs': 'astryx experimental icon new-set and friends',+ 'foundation/discovery/icon-set-writer.mjs':+ 'astryx experimental icon writers',+ 'clients/cli/commands/experimental/icon.mjs': 'astryx experimental icon',+ 'clients/cli/commands/integration.mjs':+ 'integration verify, for the package being authored',+ 'clients/cli/commands/doctor.mjs':+ "prints validate's iconSets, which validate fills only with its gate",+};+/** A read of an icon-set root, or a run of icon-set discovery or checks. */+const ICON_SET_READ =+ /\.iconSets\b|\b(?:discoverIntegrationIconSets|discoverIconSetDirectory|iconSetIssues|iconSetCoverage)\(/u;+/** Where test projects go: inside the checkout whose CLI answers. */+const PROJECTS_ROOT = REGENERATING ? GOLDEN_REPO : REPO_ROOT;++/** @type {string} */+let project;++/**+ * Run the CLI in the project; machine paths and the CLI's release version+ * become placeholders.+ * @param {string[]} args+ */+function astryx(args, cwd = project) {+ const result = spawnSync(process.execPath, [CLI_BIN, ...args], {+ cwd,+ encoding: 'utf8',+ env: {...process.env, NO_COLOR: '1', FORCE_COLOR: '0', COLUMNS: '100'},+ });+ // A golden is main's own answer, never one main handed to this checkout.+ if (REGENERATING && /handed over from CLI/u.test(result.stderr)) {+ throw new Error(+ `main's CLI handed \`astryx ${args.join(' ')}\` over to another CLI: ${result.stderr.trim()}`,+ );+ }+ /** @param {string} text */+ const clean = text =>+ text+ .split(cwd)+ .join('<project>')+ .split(REPO_ROOT)+ .join('<repo>')+ .split(GOLDEN_REPO)+ .join('<repo>')+ .replace(VERSION_PATTERN, '$1<version>');+ return {+ status: result.status,+ stdout: clean(result.stdout),+ stderr: clean(result.stderr),+ };+}++/** Doctor checks that read the computer, not the project. */+const COMPUTER_CHECKS = new Set([+ 'newest-release',+ 'cli-on-path',+ 'computer-integrations',+]);++/**+ * A doctor JSON report with the computer's checks reduced to their ids, and+ * the summary counting only the project's: those checks answer from this+ * machine's cache and search path, which no golden can hold.+ * @param {string} stdout+ */+function withoutComputerChecks(stdout) {+ const report = JSON.parse(stdout);+ const summary = {pass: 0, warn: 0, fail: 0, info: 0};+ report.data.checks = report.data.checks.map((/** @type {any} */ check) => {+ if (COMPUTER_CHECKS.has(check.id)) return {id: check.id};+ summary[/** @type {keyof typeof summary} */ (check.status)] += 1;+ // A message is prose; its counts are what icon sets could change. The+ // Node version is the machine's, not the project's.+ return {+ ...check,+ message: numbersIn(+ check.id === 'node-version'+ ? check.message.replace(/v\d+\.\d+\.\d+/u, 'v<node>')+ : check.message,+ ),+ };+ });+ report.data.summary = summary;+ const shaped = skeleton(report);+ report.data.checks.forEach(+ (/** @type {any} */ check, /** @type {number} */ at) => {+ if (check.message != null) shaped.data.checks[at].message = check.message;+ },+ );+ return asGolden(shaped);+}++/*+ * The goldens hold what icon sets could change, not main's prose: an edit to a+ * stable doc's title, summary, description, or snippet, or to a command's+ * description, rewrites no golden. Each golden keeps identities (ids, routes,+ * names, kinds, packages, commands), structure (which fields, sections,+ * children, and results there are, in order), counts, and the leak fields:+ * every `stability`, and every sentence that names `experimental`, an icon+ * set, or an icon definition.+ */++/** String fields kept as they are: identities, never prose. */+const IDENTITY_KEYS = new Set([+ 'apiVersion',+ 'type',+ 'package',+ 'id',+ 'key',+ 'route',+ 'name',+ 'topic',+ 'kind',+ 'domain',+ 'import',+ 'command',+ 'parent',+ 'stability',+ 'slot',+ 'template',+ 'outputDir',+ 'fileName',+ 'status',+ 'code',+ 'flag',+ 'version',+ 'query',+ 'cli',+ 'core',+ 'copy',+ 'severity',+ 'file',+ 'installCommand',+ 'lang',+]);+/** Fields whose strings are a list of identities. */+const IDENTITY_LIST_KEYS = new Set([+ 'components',+ 'missingPackages',+ 'jsonSupported',+ 'choices',+ 'iconSets',+]);+/** Numbers derived from prose (a match in a title scores higher). */+const PROSE_NUMBER_KEYS = new Set(['score']);+/** What a prose string becomes. */+const TEXT = '<text>';++/**+ * A JSON value with its prose replaced by {@link TEXT}: every string outside+ * {@link IDENTITY_KEYS} and {@link IDENTITY_LIST_KEYS}, and every number in+ * {@link PROSE_NUMBER_KEYS}. Keys, arrays, and their order stay.+ * @param {any} value+ * @param {string} [key]+ * @returns {any}+ */+function skeleton(value, key) {+ if (typeof value === 'string') {+ return key != null && IDENTITY_KEYS.has(key) ? value : TEXT;+ }+ if (typeof value === 'number') {+ return key != null && PROSE_NUMBER_KEYS.has(key) ? TEXT : value;+ }+ if (Array.isArray(value)) {+ return value.map(each =>+ typeof each === 'string' && key != null && IDENTITY_LIST_KEYS.has(key)+ ? each+ : skeleton(each, typeof each === 'string' ? undefined : key),+ );+ }+ if (value && typeof value === 'object') {+ return Object.fromEntries(+ Object.entries(value).map(([field, each]) => [+ field,+ skeleton(each, field),+ ]),+ );+ }+ return value;+}++/**+ * Every sentence in a value that names an experimental surface, sorted.+ * @param {any} value+ * @returns {string[]}+ */+function leakMentions(value) {+ /** @type {Set<string>} */+ const found = new Set();+ /** @param {any} each */+ const visit = each => {+ if (typeof each === 'string') {+ for (const sentence of each.split(/(?<=[.!?])\s+/u)) {+ if (LEAK_WORDS.test(sentence)) found.add(sentence.trim());+ }+ } else if (Array.isArray(each)) {+ each.forEach(visit);+ } else if (each && typeof each === 'object') {+ Object.values(each).forEach(visit);+ }+ };+ visit(value);+ return [...found].sort();+}++/** @param {any} value */+const asGolden = value => `${JSON.stringify(value, null, 2)}\n`;++/**+ * Text output with its prose dropped: a line matching one of `keep` stays;+ * a two-column row (`name description`) keeps its first column and the+ * column it sets; a line that wraps a row's description is dropped; any+ * other run of lines becomes one {@link TEXT}.+ * @param {string} text+ * @param {RegExp[]} [keep]+ */+function textShape(text, keep = []) {+ /** @type {string[]} */+ const out = [];+ for (const line of text.split('\n')) {+ if (line.trim() === '') {+ out.push('');+ } else if (keep.some(pattern => pattern.test(line))) {+ out.push(line);+ } else if (/^\s{8,}\S/u.test(line)) {+ continue;+ } else {+ const row = /^(\s*\S(?:.*?\S)?)( {2,})\S/u.exec(line);+ const shaped = row ? `${row[1]}${row[2]}${TEXT}` : TEXT;+ // A paragraph's lines are one prose run, however it wraps.+ if (shaped !== TEXT || out.at(-1) !== TEXT) out.push(shaped);+ }+ }+ return out.join('\n');+}++/**+ * `astryx search` as a golden: the count, and each result's identity and+ * order, with the sentences that name an experimental surface (the stable+ * icons topic names "the icon set" a theme swaps). No result is experimental,+ * an icon, or an icon definition.+ * @param {string} query+ * @param {string} cwd+ */+function searchGolden(query, cwd) {+ const json = astryx(['search', ...query.split(' '), '--json'], cwd);+ expect(json.status).toBe(0);+ const body = JSON.parse(json.stdout);+ // The one stable addition FR18 makes: the field reference's `stability`+ // field, named by its value. Main has no such field; nothing else may be+ // added.+ const added = body.data.results.filter(isStableAddition);+ body.data.results = body.data.results.filter(+ (/** @type {any} */ result) => !isStableAddition(result),+ );+ body.data.matchCount -= added.length;+ for (const result of body.data.results) {+ expect(result).not.toHaveProperty('stability');+ expect(['icon', 'icon-set', 'icon-definition']).not.toContain(+ result.domain,+ );+ expect(+ [result.name, result.command, result.route, result.parent].join(' '),+ ).not.toMatch(/experimental|icon-definitions|icon-sets?\b/u);+ }+ body.data.results = body.data.results.map((/** @type {any} */ result) => ({+ ...skeleton(result),+ mentions: leakMentions(result),+ }));+ const text = astryx(['search', ...query.split(' ')], cwd);+ // The same addition left out of the text: its block, and its count.+ const blocks = text.stdout+ .split('\n\n')+ .filter(+ block =>+ !(+ /^name: +authoring\/field-reference$/mu.test(block) &&+ /^section: +authored-doc-graph-fields$/mu.test(block)+ ),+ );+ return {+ json: asGolden(body),+ // Each result's identity lines and the count; descriptions are prose.+ text: blocks+ .join('\n\n')+ .replace(+ /^(Results for .*\()(\d+)((?: of (\d+))?\))$/mu,+ (_, head, shown, tail, total) =>+ total+ ? `${head}${Number(shown)}${tail.replace(total, String(Number(total) - added.length))}`+ : `${head}${Number(shown) - added.length}${tail}`,+ )+ .split('\n')+ .filter(line =>+ /^(?:Results for |(?:name|section|domain|package|import|command|parent|route):\s)/u.test(+ line,+ ),+ )+ .join('\n'),+ };+}++/**+ * Is this search result FR18's one stable addition: the field reference's+ * section on the authored doc graph fields, which gains `stability`?+ * @param {any} result+ */+function isStableAddition(result) {+ return (+ result.name === 'authoring/field-reference' &&+ result.section === 'authored-doc-graph-fields' &&+ !REGENERATING+ );+}++/**+ * The numbers a message states, in order, standing for the message: the+ * counts icon sets could change, without the prose around them.+ * @param {string} message+ */+function numbersIn(message) {+ return `${TEXT} ${(message.match(/\d+(?:\.\d+)*/gu) ?? []).join(' ')}`.trim();+}++beforeAll(() => {+ // Inside the checkout whose CLI answers, so it finds that checkout's Core.+ project = fs.mkdtempSync(path.join(PROJECTS_ROOT, '.astryx-no-icon-set-'));+ fs.writeFileSync(+ path.join(project, 'package.json'),+ JSON.stringify({name: 'no-icon-set', version: '1.0.0'}),+ );+ fs.mkdirSync(path.join(project, 'node_modules', '.bin'), {recursive: true});+ fs.writeFileSync(path.join(project, 'node_modules', '.bin', 'astryx'), '');+});++afterAll(() => {+ fs.rmSync(project, {recursive: true, force: true});+});++describe('with no icon set, stable output is unchanged', () => {+ // Every stable docs topic, against the CLI without the feature: the+ // listing, each topic's sections, a digest of each topic's JSON skeleton+ // (its fields, blocks, and identities, not its prose), and the leak fields.+ it('every stable docs topic: the listing, its sections, and its JSON', async () => {+ const list = JSON.parse(astryx(['docs', '--json']).stdout);+ /** @type {Record<string, any>} */+ const topics = {};+ for (const {topic} of list.data) {+ const doc = JSON.parse(astryx(['docs', topic, '--json']).stdout);+ topics[topic] = {+ sections: (doc.data.sections ?? []).map(+ (/** @type {any} */ section) => section.id ?? section.key,+ ),+ skeleton: createHash('sha256')+ .update(JSON.stringify(skeleton(doc)))+ .digest('hex'),+ ...(doc.data.stability ? {stability: doc.data.stability} : {}),+ mentions: leakMentions(doc),+ };+ }+ await expect(+ asGolden({list: skeleton(list.data), topics}),+ ).toMatchFileSnapshot(path.join(GOLDEN, 'docs-topics.json'));+ }, 120_000);++ // Every stable node of the docs tree outside `cli`, by structure and by+ // what could leak, so an unrelated doc edit rewrites no line here: each+ // namespace's children (routes) and each guide's sections (ids), every `stability` the node or a child carries, and every+ // sentence in the node that names `experimental`, an icon set, or an icon+ // definition. The field reference gains the stable `stability` field of+ // every doc kind, so it is compared by sections.+ it('every stable docs tree node: its children or sections, and its JSON', async () => {+ const root = process.env.GOLDEN_CLI_ROOT ?? CLI_ROOT;+ const {docs} = await import(+ pathToFileURL(path.join(root, 'api', 'docs', 'docs.mjs')).href+ );+ // The `cli` namespace is FR0's own case: its listing gains the+ // experimental group, and the experimental commands and API functions+ // document themselves on its routes, each marked experimental. Every+ // other namespace answers exactly as it does without the feature.+ const experimental = (/** @type {string} */ route) =>+ route === 'cli' || route.startsWith('cli/');+ /** @param {any} value */+ const clean = value =>+ JSON.stringify(value)+ .split(project)+ .join('<project>')+ .split(path.resolve(root, '..', '..'))+ .join('<repo>');+ /**+ * Every `stability` a read carries, on the node or a child, by where.+ * @param {any} res+ */+ const stabilities = res => {+ /** @type {string[]} */+ const marked = [];+ if (res.data?.stability) marked.push(`node: ${res.data.stability}`);+ for (const slot of res.data?.slots ?? []) {+ for (const child of slot.children ?? []) {+ if (child.stability) {+ marked.push(`${child.route}: ${child.stability}`);+ }+ }+ }+ return marked.length > 0 ? {stability: marked} : {};+ };+ /**+ * Every sentence in a read that names an experimental surface.+ * @param {any} value+ */+ const mentions = value => {+ /** @type {Set<string>} */+ const found = new Set();+ /** @param {any} each */+ const visit = each => {+ if (typeof each === 'string') {+ for (const sentence of each.split(/(?<=[.!?])\s+/u)) {+ if (LEAK_WORDS.test(sentence)) found.add(sentence);+ }+ } else if (Array.isArray(each)) {+ each.forEach(visit);+ } else if (each && typeof each === 'object') {+ Object.values(each).forEach(visit);+ }+ };+ visit(value);+ return [...found].sort();+ };+ const list = await docs(undefined, undefined, {cwd: project});+ const queue = (list.meta?.namespaces ?? []).map(+ (/** @type {any} */ entry) => entry.topic,+ );+ /** @type {Record<string, any>} */+ const nodes = {};+ while (queue.length > 0) {+ const route = queue.shift();+ if (route in nodes || experimental(route)) continue;+ const res = await docs(route, undefined, {cwd: project});+ if (res.type === 'docs.node') {+ for (const slot of res.data.slots) {+ slot.children = slot.children.filter(+ (/** @type {any} */ child) => !experimental(child.route),+ );+ for (const child of slot.children) queue.push(child.route);+ }+ }+ nodes[route] = {+ type: res.type,+ ...(res.type === 'docs.node'+ ? {+ children: res.data.slots.flatMap((/** @type {any} */ slot) =>+ slot.children.map((/** @type {any} */ c) => c.route),+ ),+ }+ : {+ sections: (res.data.sections ?? []).map(+ (/** @type {any} */ section) => section.id ?? section.key,+ ),+ }),+ ...stabilities(res),+ ...(route === 'authoring/field-reference'+ ? {}+ : {mentions: mentions(JSON.parse(clean(res)))}),+ };+ }+ const sorted = Object.fromEntries(+ Object.keys(nodes)+ .sort()+ .map(route => [route, nodes[route]]),+ );+ await expect(`${JSON.stringify(sorted, null, 2)}\n`).toMatchFileSnapshot(+ path.join(GOLDEN, 'docs-tree.json'),+ );+ }, 120_000);++ // Every stable node of the `cli` tree (the tree minus the nodes marked+ // experimental and what sits under them): every sentence, link, and+ // command in it that names `experimental`, an icon set, or an icon+ // definition, which must be main's own (spec:AST-084 FR0). A stable doc+ // that points at an experimental route, or a stable node whose previous or+ // next link is one, fails here.+ it('every stable cli docs node: no mention of an experimental surface main lacks', async () => {+ const root = process.env.GOLDEN_CLI_ROOT ?? CLI_ROOT;+ const {docs} = await import(+ pathToFileURL(path.join(root, 'api', 'docs', 'docs.mjs')).href+ );+ /** @type {Record<string, string[]>} */+ const mentions = {};+ const queue = ['cli'];+ /** @type {Set<string>} */+ const seen = new Set();+ while (queue.length > 0) {+ const route = /** @type {string} */ (queue.shift());+ if (seen.has(route)) continue;+ seen.add(route);+ const res = await docs(route, undefined, {cwd: project});+ if (res.data?.stability === 'experimental') continue;+ if (res.type === 'docs.node') {+ for (const slot of res.data.slots) {+ slot.children = slot.children.filter(+ (/** @type {any} */ child) => child.stability !== 'experimental',+ );+ for (const child of slot.children) queue.push(child.route);+ }+ }+ const found = leakMentions(res.data);+ if (found.length > 0) mentions[route] = found;+ }+ expect(seen.size).toBeGreaterThan(50);+ const sorted = Object.fromEntries(+ Object.keys(mentions)+ .sort()+ .map(route => [route, mentions[route]]),+ );+ await expect(asGolden(sorted)).toMatchFileSnapshot(+ path.join(GOLDEN, 'docs-cli-mentions.json'),+ );+ }, 120_000);++ // The `cli` listings are FR0's one docs exception: they gain the+ // experimental group, commands, and API functions, each marked as help marks+ // the command group. Every entry not marked experimental reads exactly as it+ // does without the feature, in JSON and in text: stable rows+ // set the name column, and an experimental row overhangs it.+ it.each(['cli', 'cli/commands', 'cli/api/functions'])(+ 'docs %s: every entry not marked experimental, text and JSON',+ async route => {+ const slug = route.replaceAll('/', '-');+ const json = JSON.parse(astryx(['docs', route, '--json']).stdout);+ for (const slot of json.data.slots) {+ slot.children = slot.children.filter(+ (/** @type {any} */ child) => child.stability !== 'experimental',+ );+ }+ delete json.meta;+ await expect(asGolden(skeleton(json))).toMatchFileSnapshot(+ path.join(GOLDEN, `docs-${slug}.json`),+ );+ // An experimental row and the lines it wraps onto are left out; every+ // other row is compared by its name and the name column it sets, so an+ // experimental name that widened the stable column would show.+ /** @type {string[]} */+ const lines = [];+ let inExperimental = false;+ for (const line of astryx(['docs', route]).stdout.split('\n')) {+ if (/^\S+ {2,}\[experimental\] /u.test(line)) {+ inExperimental = true;+ continue;+ }+ if (inExperimental && /^ {8,}\S/u.test(line)) continue;+ inExperimental = false;+ lines.push(line);+ }+ await expect(+ textShape(lines.join('\n'), [/^package: /u]),+ ).toMatchFileSnapshot(path.join(GOLDEN, `docs-${slug}.txt`));+ },+ );++ it.each([+ 'delete',+ 'close',+ 'icon',+ 'trash can',+ 'search',+ 'experimental',+ 'icon set',+ ])('search %s, text and JSON', async query => {+ const slug = query.replace(/\s+/g, '-');+ const {json, text} = searchGolden(query, project);+ await expect(json).toMatchFileSnapshot(+ path.join(GOLDEN, `search-${slug}.json`),+ );+ await expect(text).toMatchFileSnapshot(+ path.join(GOLDEN, `search-${slug}.txt`),+ );+ });++ it('search --type icon is an unknown type, offering only the stable domains', async () => {+ const res = astryx(['search', 'trash', '--type', 'icon', '--json']);+ expect(res.status).toBe(1);+ const body = JSON.parse(res.stdout);+ expect(body.code).toBe('ERR_INVALID_ARGUMENT');+ expect(body.suggestions.map((/** @type {any} */ s) => s.name)).toEqual([+ 'component',+ 'hook',+ 'doc',+ 'template',+ 'theme',+ ]);+ });++ it('a template that declares icons prints and copies as it always has', async () => {+ // The template's own source, from the checkout whose CLI answers: printed+ // and copied unchanged, icons included.+ const page = fs.readFileSync(+ path.join(+ process.env.GOLDEN_CLI_ROOT ?? CLI_ROOT,+ 'assets',+ 'templates',+ 'pages',+ 'settings-dialog',+ 'page.tsx',+ ),+ 'utf-8',+ );+ const shown = astryx(['template', 'settings-dialog', '--json']);+ expect(shown.status).toBe(0);+ const shownBody = JSON.parse(shown.stdout);+ expect(shownBody.data).not.toHaveProperty('icons');+ expect(shownBody.data.source).toBe(page);+ await expect(asGolden(skeleton(shownBody))).toMatchFileSnapshot(+ path.join(GOLDEN, 'template-show.json'),+ );++ const copied = astryx([+ 'template',+ 'settings-dialog',+ 'out/json',+ '--json',+ ]);+ expect(copied.status).toBe(0);+ const copiedBody = JSON.parse(copied.stdout);+ expect(copiedBody.data).not.toHaveProperty('icons');+ await expect(asGolden(skeleton(copiedBody))).toMatchFileSnapshot(+ path.join(GOLDEN, 'template-copy.json'),+ );++ const text = astryx(['template', 'settings-dialog', 'out/text']);+ expect(text.status).toBe(0);+ expect(`${text.stdout}${text.stderr}`).not.toContain('icons:');+ await expect(+ textShape(text.stdout, [+ /^Copied template to /u,+ /^package: /u,+ /^Install missing dependencies: /u,+ ]),+ ).toMatchFileSnapshot(path.join(GOLDEN, 'template-copy.txt'));+ // The written file is the template's source with its own icons.+ for (const out of ['out/json', 'out/text']) {+ expect(+ fs.readFileSync(path.join(project, out, 'page.tsx'), 'utf-8'),+ ).toBe(page);+ }+ });++ it('help gains only the experimental group', async () => {+ const help = astryx(['help']).stdout.split('\n');+ const added = help.filter(line => /experimental|\bicon\b/i.test(line));+ if (!REGENERATING) {+ expect(added).toHaveLength(1);+ expect(added[0]).toMatch(/^\s+experimental\s+\[experimental\] /);+ }+ // Every other line as main prints it, by command and option and the+ // column they set; descriptions are prose.+ await expect(+ textShape(help.filter(line => !added.includes(line)).join('\n'), [+ /^(?:Usage|Options|Commands|Exit codes|Examples):/u,+ ]),+ ).toMatchFileSnapshot(path.join(GOLDEN, 'help.txt'));+ });++ it('the manifest gains only the experimental group and its commands', async () => {+ const manifest = JSON.parse(astryx(['manifest', '--json']).stdout);+ const isExperimental = (/** @type {string} */ name) =>+ name === 'experimental' || name.startsWith('experimental ');+ const data = manifest.data;+ if (!REGENERATING) {+ expect(+ data.commands.filter((/** @type {any} */ c) => isExperimental(c.name)),+ ).toHaveLength(1);+ }+ data.commands = data.commands.filter(+ (/** @type {any} */ c) => !isExperimental(c.name),+ );+ data.jsonSupported = data.jsonSupported.filter(+ (/** @type {string} */ name) => !isExperimental(name),+ );+ data.responseTypes = Object.fromEntries(+ Object.entries(data.responseTypes).filter(+ ([name]) => !isExperimental(name),+ ),+ );+ await expect(asGolden(skeleton(manifest))).toMatchFileSnapshot(+ path.join(GOLDEN, 'manifest.json'),+ );+ });++ it('doctor has no icon-sets check, and its doc counts leave experimental docs out', async () => {+ const res = astryx(['doctor', '--json']);+ const checks = JSON.parse(res.stdout).data.checks;+ expect(+ checks.map((/** @type {{id: string}} */ check) => check.id),+ ).not.toContain('icon-sets');+ const counts = checks+ .filter((/** @type {{id: string}} */ check) =>+ [+ 'authoring-docs',+ 'cli-docs',+ 'docs-tree',+ 'docs-progressive-disclosure',+ ].includes(check.id),+ )+ .map(+ (/** @type {{id: string, message: string}} */ check) =>+ `${check.id}: ${numbersIn(check.message)}`,+ )+ .join('\n');+ await expect(`${counts}\n`).toMatchFileSnapshot(+ path.join(GOLDEN, 'doctor-doc-counts.txt'),+ );+ });++ it.skipIf(REGENERATING)(+ 'no stable command family gains an icon-set subcommand or kind',+ () => {+ const manifest = JSON.parse(astryx(['manifest', '--json']).stdout);+ /** @type {string[]} */+ const names = [];+ /** @param {any[]} commands */+ const walk = commands => {+ for (const command of commands ?? []) {+ names.push(command.name);+ walk(command.subcommands);+ }+ };+ walk(manifest.data?.commands ?? manifest.commands);+ const iconCommands = names.filter(name => /\bicon\b/.test(name));+ expect(iconCommands.length).toBeGreaterThan(0);+ for (const name of iconCommands) {+ expect(name.startsWith('experimental ')).toBe(true);+ }+ const res = astryx([+ 'integration',+ 'add',+ 'icon-set',+ 'outline',+ '--json',+ ]);+ expect(res.status).toBe(1);+ expect(JSON.parse(res.stdout).code).toBe('ERR_INVALID_ARGUMENT');+ },+ );+});++describe('an integration package without experimental.iconSets', () => {+ /** @type {string} */+ let pkg;+ beforeAll(() => {+ // Outside the repo, so this CLI answers, as the CLI without icon sets+ // that wrote the golden did.+ pkg = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-no-icon-sets-pkg-'));+ fs.writeFileSync(+ path.join(pkg, 'package.json'),+ `${JSON.stringify({+ name: '@acme/widgets',+ version: '1.0.0',+ files: ['astryx.integration.mjs', 'docs'],+ exports: {'./package.json': './package.json'},+ })}\n`,+ );+ fs.writeFileSync(+ path.join(pkg, 'astryx.integration.mjs'),+ "export default {\n docs: './docs'\n};\n",+ );+ fs.mkdirSync(path.join(pkg, 'docs'));+ fs.writeFileSync(+ path.join(pkg, 'docs', 'local-guide.doc.mjs'),+ `/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export default {+ type: 'generic',+ name: 'local-guide',+ title: 'Local Guide',+ description: 'Local Guide documentation.',+ sections: [+ {+ title: 'Overview',+ content: [{type: 'prose', text: 'Local Guide documentation.'}],+ },+ ],+};+`,+ );+ });+ afterAll(() => {+ fs.rmSync(pkg, {recursive: true, force: true});+ });++ // The golden was written by the CLI without icon sets; only the gzip size+ // of the tarball, which depends on the machine's zlib, is a placeholder.+ it('integration verify --json answers as it does without icon sets: no iconSets identities', async () => {+ const res = astryx(['integration', 'verify', '--json'], pkg);+ expect(res.status).toBe(0);+ const body = JSON.parse(res.stdout);+ expect(body.data.contributions.local).not.toHaveProperty('iconSets');+ expect(body.data.contributions.packed).not.toHaveProperty('iconSets');+ await expect(+ res.stdout.replace(/("size": )\d+/u, '$1"<gzip>"'),+ ).toMatchFileSnapshot(path.join(GOLDEN, 'integration-verify.json'));+ });+});++// Only while main lacks the feature: main's CLI refuses+// `experimental.iconSet`, so regenerating from main skips these, which+// compare with the goldens the project without icon sets wrote. Once the+// feature is on main, `vitest run+// packages/cli/test/experimental-isolation.test.mjs --update` in a branch+// runs them too.+describe.skipIf(REGENERATING)(+ 'with an icon set installed and configured, search is unchanged',+ () => {+ /** @type {string} */+ let root;+ /** @type {string} */+ let withSet;+ beforeAll(() => {+ root = fs.mkdtempSync(+ path.join(PROJECTS_ROOT, '.astryx-icon-set-search-'),+ );+ withSet = writeIconSetProject(root, {+ config: {experimental: {iconSet: 'glyphs'}},+ });+ fs.mkdirSync(path.join(withSet, 'node_modules', '.bin'), {+ recursive: true,+ });+ fs.writeFileSync(+ path.join(withSet, 'node_modules', '.bin', 'astryx'),+ '',+ );+ });+ afterAll(() => {+ fs.rmSync(root, {recursive: true, force: true});+ });++ it('the set is loaded', () => {+ const list = JSON.parse(+ astryx(['experimental', 'icon', '--list', '--json'], withSet).stdout,+ );+ expect(list.data.projectSet).toBe('@acme/glyphs/glyphs');+ });++ // Icon words: icon lookup by meaning is only `astryx experimental icon`;+ // `astryx search` joins it only at promotion (spec:AST-084 FR11).+ it.each(['delete', 'close', 'trash can', 'experimental', 'icon set'])(+ 'search %s equals the output without icon sets, text and JSON',+ async query => {+ const slug = query.replace(/\s+/g, '-');+ const {json, text} = searchGolden(query, withSet);+ await expect(json).toMatchFileSnapshot(+ path.join(GOLDEN, `search-${slug}.json`),+ );+ await expect(text).toMatchFileSnapshot(+ path.join(GOLDEN, `search-${slug}.txt`),+ );+ },+ );++ it('search --type icon stays an unknown type', () => {+ const res = astryx(+ ['search', 'trash', '--type', 'icon', '--json'],+ withSet,+ );+ expect(res.status).toBe(1);+ expect(JSON.parse(res.stdout).code).toBe('ERR_INVALID_ARGUMENT');+ });+ },+);++describe('with icon sets installed but no experimental.iconSet, stable output is unchanged', () => {+ /** @type {string} */+ let root;+ beforeAll(() => {+ root = fs.mkdtempSync(+ path.join(PROJECTS_ROOT, '.astryx-icon-set-no-opt-in-'),+ );+ });+ afterAll(() => {+ fs.rmSync(root, {recursive: true, force: true});+ });++ /**+ * A project that loads an icon-set package, its set valid or not.+ * @param {string} name+ * @param {unknown} [data] the set's data file; omit for a valid one+ */+ function installed(name, data) {+ const dir = writeIconSetProject(path.join(root, name), {+ packages: [data === undefined ? {} : {data}],+ config: {integrations: ['@acme/glyphs']},+ });+ fs.mkdirSync(path.join(dir, 'node_modules', '.bin'), {recursive: true});+ fs.writeFileSync(path.join(dir, 'node_modules', '.bin', 'astryx'), '');+ if (REGENERATING) {+ // Main's CLI warns about the manifest key it does not know.+ fs.writeFileSync(+ path.join(+ dir,+ 'node_modules',+ '@acme',+ 'glyphs',+ 'astryx.integration.mjs',+ ),+ 'export default {};\n',+ );+ }+ return dir;+ }++ // The goldens were written by the CLI without icon sets, in the same+ // project with the package's manifest emptied: that CLI warns about the+ // manifest key `experimental` it does not know, which is the one line no+ // CLI with this feature can print.+ it('discover lists no icon set, and --type icon-set is an unknown type', async () => {+ const cwd = installed('discover');+ await expect(+ astryx(['discover', '--json'], cwd).stdout,+ ).toMatchFileSnapshot(path.join(GOLDEN, 'discover.json'));+ const typed = astryx(['discover', '--type', 'icon-set', '--json'], cwd);+ expect(typed.status).toBe(1);+ await expect(typed.stdout).toMatchFileSnapshot(+ path.join(GOLDEN, 'discover-type-icon-set.json'),+ );+ const unknown = astryx(['discover', '--type', 'bogus', '--json'], cwd);+ await expect(unknown.stdout).toMatchFileSnapshot(+ path.join(GOLDEN, 'discover-type-bogus.json'),+ );+ });++ // A source that lists a malformed icon-set entry: without the opt-in its+ // fields are unknown and the entry is an unknown kind, so the source still+ // counts and discover answers as the CLI without icon sets does.+ it('a malformed icon-set entry in a source does not fail it', async () => {+ const cwd = writeIconSetProject(path.join(root, 'malformed-source'), {+ packages: [],+ });+ fs.writeFileSync(+ path.join(cwd, 'astryx.config.mjs'),+ `export default {+ discover: async () => ({+ schemaVersion: 1,+ source: {name: 'acme', generatedAt: '2026-01-01T00:00:00.000Z', complete: true},+ packages: [{+ package: '@acme/glyphs',+ integration: '@acme/glyphs',+ aliases: [],+ latest: '1.0.0',+ versions: [{version: '1.0.0', publishedAt: '2026-01-01T00:00:00.000Z', prerelease: false, status: 'published'}],+ contributions: [+ {kind: 'theme', name: 'glyph-theme', definitions: [7]},+ {kind: 'icon-set', name: 'outline', iconCount: -1, definitions: 'nope'},+ ],+ }],+ }),+};+`,+ );+ fs.mkdirSync(path.join(cwd, 'node_modules', '.bin'), {recursive: true});+ fs.writeFileSync(path.join(cwd, 'node_modules', '.bin', 'astryx'), '');+ const res = astryx(['discover', '--json'], cwd);+ expect(res.status).toBe(0);+ await expect(res.stdout).toMatchFileSnapshot(+ path.join(GOLDEN, 'discover-malformed-icon-set-source.json'),+ );+ });++ // The other difference FR0 names: every command that prints the+ // integration-issue nudge to stderr (NUDGE_COMMANDS) prints one for the+ // manifest key `experimental` in the CLI without icon sets; this CLI prints+ // none, so its stderr equals what that CLI prints for the package with the+ // key removed. The theme writers have no dry run and print the nudge only+ // after they succeed, so they run in this test's own project: two themes+ // are forked and their built files stubbed, then added, used, and removed.+ // `upgrade` runs without `--apply`, a dry run, against the repo's Core.+ it('every command that prints the integration-issue nudge prints none', async () => {+ const cwd = installed('nudge');+ const pkgFile = path.join(cwd, 'package.json');+ const pkgJson = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));+ pkgJson.dependencies['@astryxdesign/core'] = '*';+ fs.writeFileSync(pkgFile, JSON.stringify(pkgJson));+ fs.mkdirSync(path.join(cwd, 'src'));+ fs.mkdirSync(path.join(cwd, 'node_modules', '@astryxdesign'));+ fs.symlinkSync(+ path.join(PROJECTS_ROOT, 'packages', 'core'),+ path.join(cwd, 'node_modules', '@astryxdesign', 'core'),+ 'dir',+ );+ /** @type {Record<string, () => void>} */+ const setup = {+ 'theme add': () => {+ // `theme eject` above forked stone; matcha is the second theme.+ expect(astryx(['theme', 'eject', 'matcha', '--json'], cwd).status).toBe(+ 0,+ );+ for (const slug of ['stone', 'matcha']) {+ const dir = path.join(cwd, 'src', 'themes', slug);+ fs.writeFileSync(+ path.join(dir, `${slug}.js`),+ `export const ${slug}Theme = {};\n`,+ );+ fs.writeFileSync(path.join(dir, `${slug}.css`), '\n');+ }+ },+ 'theme use': () => {+ expect(astryx(['theme', 'add', 'matcha', '--json'], cwd).status).toBe(+ 0,+ );+ },+ };+ const stderr = NUDGE_COMMANDS.map(({name, args}) => {+ setup[name]?.();+ const res = astryx(args, cwd);+ expect(res.status, `astryx ${args.join(' ')}: ${res.stderr}`).toBe(0);+ if (!REGENERATING) {+ expect(res.stderr).not.toMatch(/integration issue/u);+ }+ return `$ astryx ${args.join(' ')}\n${textShape(res.stderr, [+ /^(?:Warning|Error):/u,+ /^package: /u,+ ])}`;+ }).join('\n');+ await expect(stderr).toMatchFileSnapshot(+ path.join(GOLDEN, 'installed-set-stderr.txt'),+ );+ });++ // The list is every caller of the nudge: a new caller fails here until it+ // joins NUDGE_COMMANDS, and FR0 names each command in the list.+ it('NUDGE_COMMANDS is every caller of the nudge, and FR0 names each one', () => {+ /** @type {Record<string, number>} */+ const callers = {};+ /** @param {string} dir */+ const walk = dir => {+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ const file = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (entry.name !== 'node_modules' && entry.name !== 'test') {+ walk(file);+ }+ } else if (+ entry.name.endsWith('.mjs') &&+ !entry.name.endsWith('.test.mjs')+ ) {+ const text = fs.readFileSync(file, 'utf8');+ const calls = text.match(NUDGE_CALL)?.length ?? 0;+ if (calls > 0) {+ callers[path.relative(CLI_ROOT, file).split(path.sep).join('/')] =+ calls;+ }+ }+ }+ };+ for (const dir of ['api', 'clients', 'foundation']) {+ walk(path.join(CLI_ROOT, dir));+ }+ expect(callers).toEqual(NUDGE_CALLERS);+ const spec = fs.readFileSync(+ path.join(REPO_ROOT, 'docs', 'specs', 'AST-084-icon-sets', 'spec.md'),+ 'utf8',+ );+ const fr0 = spec.slice(+ spec.indexOf('**FR0 '),+ spec.indexOf('### What a set declares'),+ );+ const text = fr0.replace(/\s+/gu, ' ');+ expect(text).toContain(+ 'every command that prints the integration-issue nudge',+ );+ for (const {name} of NUDGE_COMMANDS) {+ expect(text).toContain(`\`${name}\``);+ }+ });++ // `doctor integration validate <installed package>` checks the package's+ // icon sets only with the opt-in: here it reports what the CLI without+ // icon sets reports for the package with the manifest key removed.+ it('doctor integration validate of the installed package: text, JSON, and exit code', async () => {+ const cwd = installed('validate');+ const json = astryx(+ ['doctor', 'integration', 'validate', '@acme/glyphs', '--json'],+ cwd,+ );+ const text = astryx(+ ['doctor', 'integration', 'validate', '@acme/glyphs'],+ cwd,+ );+ if (!REGENERATING) {+ expect(JSON.parse(json.stdout).data).not.toHaveProperty('iconSets');+ expect(json.stdout).not.toMatch(/icon/iu);+ }+ // One exit code for both; the text golden holds it.+ expect(json.status).toBe(text.status);+ await expect(json.stdout).toMatchFileSnapshot(+ path.join(GOLDEN, 'validate-installed-set.json'),+ );+ await expect(+ `exit ${text.status}\n${textShape(`${text.stdout}${text.stderr}`, [+ /^Validating integration: /u,+ /^Summary: /u,+ /^severity:|^code:/u,+ ])}`,+ ).toMatchFileSnapshot(path.join(GOLDEN, 'validate-installed-set.txt'));+ });++ it('every reader of an icon-set root is listed with its gate', () => {+ /** @type {string[]} */+ const readers = [];+ /** @param {string} dir */+ const walk = dir => {+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ const file = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (!['node_modules', 'test', '__tests__'].includes(entry.name)) {+ walk(file);+ }+ } else if (+ entry.name.endsWith('.mjs') &&+ !/\.(?:test|doc|type)\.mjs$/u.test(entry.name) &&+ ICON_SET_READ.test(fs.readFileSync(file, 'utf8'))+ ) {+ readers.push(path.relative(CLI_ROOT, file).split(path.sep).join('/'));+ }+ }+ };+ for (const dir of ['api', 'clients', 'foundation']) {+ walk(path.join(CLI_ROOT, dir));+ }+ expect(readers.sort()).toEqual(Object.keys(ICON_SET_READERS).sort());+ });++ it('doctor reports nothing about an invalid installed set', async () => {+ const cwd = installed('doctor', '{nope');+ const res = astryx(['doctor', '--json'], cwd);+ expect(res.stdout).not.toMatch(/icon/i);+ await expect(withoutComputerChecks(res.stdout)).toMatchFileSnapshot(+ path.join(GOLDEN, 'doctor-installed-set.json'),+ );+ });+});diff --git a/packages/cli/test/icon-set-doc-pointers.test.mjs b/packages/cli/test/icon-set-doc-pointers.test.mjsnew file mode 100644index 0000000000..adb5abbc25--- /dev/null+++ b/packages/cli/test/icon-set-doc-pointers.test.mjs@@ -0,0 +1,61 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Every `astryx docs <route> [section]` an icon-set error, hint, or+ * receipt names resolves (spec:AST-084): the icon-set commands, discovery,+ * checks, writer, and template mapping point at docs that exist, so a moved+ * guide cannot leave a dead pointer in a message.+ */++import {spawnSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {describe, expect, it} from 'vitest';+import {CLI_ROOT} from '../foundation/fs/paths.mjs';++const CLI_BIN = path.join(CLI_ROOT, 'clients', 'cli', 'bin', 'astryx.mjs');++/** The icon-set sources whose text names docs routes. */+const SOURCES = [+ 'api/icon',+ 'clients/cli/commands/experimental',+ 'foundation/discovery/icon-set-discovery.mjs',+ 'foundation/discovery/icon-set-writer.mjs',+ 'foundation/discovery/icon-set-checks.mjs',+ 'foundation/discovery/icon-definition-discovery.mjs',+ 'foundation/discovery/template-icons.mjs',+];++/** @param {string} entry @returns {string[]} */+function files(entry) {+ const full = path.join(CLI_ROOT, entry);+ if (!fs.statSync(full).isDirectory()) return [full];+ return fs+ .readdirSync(full, {recursive: true, encoding: 'utf8'})+ .filter(name => name.endsWith('.mjs') && !name.includes('.test.'))+ .map(name => path.join(full, name));+}++describe('icon-set docs pointers', () => {+ it('every `astryx docs` route and section an icon-set message names resolves', () => {+ /** @type {Set<string>} */+ const pointers = new Set();+ for (const file of SOURCES.flatMap(files)) {+ const text = fs.readFileSync(file, 'utf-8');+ for (const match of text.matchAll(+ /astryx docs ([a-z][\w/-]*)(?: ([a-z][\w-]*)(?=[)`'.]))?/gu,+ )) {+ pointers.add(match[2] ? `${match[1]} ${match[2]}` : match[1]);+ }+ }+ expect(pointers.size).toBeGreaterThan(0);+ for (const pointer of pointers) {+ const run = spawnSync(+ process.execPath,+ [CLI_BIN, 'docs', ...pointer.split(' '), '--json'],+ {cwd: CLI_ROOT, encoding: 'utf8'},+ );+ expect(run.status, `astryx docs ${pointer}: ${run.stderr}`).toBe(0);+ }+ }, 60_000);+});diff --git a/packages/cli/test/integration-check-failures.json b/packages/cli/test/integration-check-failures.jsonindex 788c6efe4e..0564dc2a67 100644--- a/packages/cli/test/integration-check-failures.json+++ b/packages/cli/test/integration-check-failures.json@@ -38,6 +38,18 @@"duplicate_provider","duplicate_section_key","empty_section",+ "icon_builtin_definition_missing",+ "icon_definition_shadowed",+ "icon_definition_unused",+ "icon_export_missing",+ "icon_export_name",+ "icon_generated_types_mismatch",+ "icon_license_notice_missing",+ "icon_module_invalid",+ "icon_module_not_public",+ "icon_not_component",+ "icon_source_version_drift",+ "icon_theme_map_mismatch","inactive_component_replacement","integration_error","invalid_agent_docs",@@ -49,6 +61,7 @@"invalid_doc","invalid_doc_graph","invalid_doc_reference",+ "invalid_icon_set","invalid_manifest","invalid_package_json","invalid_package_spec",diff --git a/packages/cli/test/template-icon-declarations.test.mjs b/packages/cli/test/template-icon-declarations.test.mjsnew file mode 100644index 0000000000..b4aeeee4dc--- /dev/null+++ b/packages/cli/test/template-icon-declarations.test.mjs@@ -0,0 +1,132 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Every icon a bundled template or block imports is declared in its+ * descriptor's `icons` with the icon definition it draws, so a project's icon+ * set replaces it (AST-084 FR9). The CLI knows no icon library; only this+ * test names the libraries the bundled templates happen to import, to find+ * their icon imports.+ */++import * as fs from 'node:fs';+import {describe, expect, it} from 'vitest';+import {discoverCoreTemplates} from '../foundation/discovery/template-adapter.mjs';+import {astryxDefinitionsByName} from '../foundation/discovery/icon-definition-discovery.mjs';++/** The icon libraries the bundled templates import. */+const ICON_MODULE_RE =+ /^(?:@heroicons\/react\/(?:16|20|24)\/(?:outline|solid)|lucide-react)$/u;++/**+ * Icons no Astryx icon definition fits yet. A template keeps these as it+ * wrote them. The list only shrinks: add a definition, declare the icon, and+ * remove it here.+ */+const NO_DEFINITION_YET = new Set([+ 'Aperture',+ 'ArrowDownToLine',+ 'ArrowUpToLine',+ 'ArrowsRightLeftIcon',+ 'Bars3BottomLeftIcon',+ 'Baseline',+ 'CaseLower',+ 'CaseSensitive',+ 'CaseUpper',+ 'CloudIcon',+ 'Contrast',+ 'Cpu',+ 'CpuChipIcon',+ 'DeviceTabletIcon',+ 'FingerPrintIcon',+ 'FireIcon',+ 'FlipHorizontal2',+ 'FlipVertical2',+ 'FoldVertical',+ 'Frame',+ 'GiftIcon',+ 'GitBranch',+ 'GitFork',+ 'Group',+ 'PaintBrushIcon',+ 'PanelBottom',+ 'PanelLeft',+ 'PanelLeftRightDashed',+ 'PanelRight',+ 'PanelTopBottomDashed',+ 'PuzzlePieceIcon',+ 'RectangleStackIcon',+ 'RotateCcw',+ 'RotateCw',+ 'Scale',+ 'Scan',+ 'ScissorsIcon',+ 'SquareRoundCorner',+ 'SquareSquare',+ 'TextAlignCenter',+ 'TextAlignEnd',+ 'TextAlignJustify',+ 'TextAlignStart',+ 'TriangleRight',+ 'Type',+ 'UserMinusIcon',+]);++/** @param {string} source @returns {string[]} imported icon names */+function iconImports(source) {+ /** @type {string[]} */+ const names = [];+ for (const match of source.matchAll(+ /import\s*\{([^}]*)\}\s*from\s*'([^']+)'/gu,+ )) {+ if (!ICON_MODULE_RE.test(match[2])) continue;+ for (const part of match[1].replace(/\/\/[^\n]*/gu, '').split(',')) {+ const name = part+ .trim()+ .split(/\s+as\s+/u)[0]+ .trim();+ if (name && !name.startsWith('type ')) names.push(name);+ }+ }+ return names;+}++describe('bundled template icon declarations', () => {+ it('declare every imported icon with an Astryx icon definition, and nothing else', async () => {+ const definitions = astryxDefinitionsByName();+ /** @type {string[]} */+ const undeclared = [];+ /** @type {string[]} */+ const problems = [];+ const seenNoDefinition = new Set();+ for (const template of await discoverCoreTemplates()) {+ const imported = iconImports(fs.readFileSync(template.filePath, 'utf-8'));+ const declared = template.icons ?? {};+ for (const name of imported) {+ if (Object.hasOwn(declared, name)) continue;+ if (NO_DEFINITION_YET.has(name)) {+ seenNoDefinition.add(name);+ continue;+ }+ undeclared.push(`${template.type}/${template.dirName}: ${name}`);+ }+ for (const [name, definition] of Object.entries(declared)) {+ if (!imported.includes(name)) {+ problems.push(+ `${template.type}/${template.dirName} declares ${name}, which it does not import`,+ );+ }+ if (!definitions.has(definition)) {+ problems.push(+ `${template.type}/${template.dirName}: ${name} names "${definition}", which is not an Astryx icon definition`,+ );+ }+ }+ }+ expect(undeclared).toEqual([]);+ expect(problems).toEqual([]);+ // A name no template imports any more leaves the list.+ expect(+ [...NO_DEFINITION_YET].filter(name => !seenNoDefinition.has(name)),+ ).toEqual([]);+ }, 60_000);+});diff --git a/scripts/check-cli-structure.mjs b/scripts/check-cli-structure.mjsindex c3f3de5e89..6deeb70f4a 100644--- a/scripts/check-cli-structure.mjs+++ b/scripts/check-cli-structure.mjs@@ -171,7 +171,11 @@ for (const kind of dirsIn(DOCTYPES)) {// return union from, so a kind missing there is silently unnarrowable for// consumers (`type === 'schema'` reads as a no-overlap comparison). Checking// the JSDoc catches it at the source rather than in the emitted artifact.- const docType = `${kind[0].toUpperCase()}${kind.slice(1)}Doc`;+ // A kebab kind names its type in PascalCase: `icon-set` is IconSetDoc.+ const docType = `${kind+ .split('-')+ .map(part => `${part[0].toUpperCase()}${part.slice(1)}`)+ .join('')}Doc`;if (!aggregateParserReturns.includes(docType)) {errors.push(`doc-type "${kind}" is missing from the @returns union of authoring/doctypes/parse.mjs (expected ${docType})`,