An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): experimental icon sets — authoring fixes from fresh-agent Heroicons and Lucide runs (#7964)
Joey2a50a8064997
diff --git a/.changeset/cli-icon-sets-authoring.md b/.changeset/cli-icon-sets-authoring.mdnew file mode 100644index 0000000000..936848d6b6--- /dev/null+++ b/.changeset/cli-icon-sets-authoring.md@@ -0,0 +1,17 @@+---+'@astryxdesign/cli': patch+---++[experimental] Icon sets: authoring a set from a library takes fewer steps and fewer guesses. Only the experimental icon commands, the icon-set guide, and `astryx template` in a project that sets `experimental.iconSet` change; without the opt-in, every stable command reads as before except the `experimental` group's summary in `astryx help` and `astryx manifest`, which now names icon sets: "Try features that may change in a patch release: icon sets (find icons, build an icon-set package)" (it read "Try features that may change or be removed in a patch release").++- **`experimental icon new-set`.** `--from` maps a definition only when an icon has its exact name and lists those entries for review; other likely icons come back as at most three suggestions per definition, never written. It records the library and version as `source`, copies the library's license notices and takes its license, keeps `--exclude` in the data file's `exclude` for every refresh, and names the exports it left out as not icons. It writes only the set's own files: its receipt names, as text to copy, the entry change that makes the set's icons import from the package by name (never editing a built or CommonJS entry), the `react` and optional `@types/react` and `@astryxdesign/cli` peers, and the `typecheck` script the package is missing, and `integration check` names the same entry change, once, until it is made. `--variants` and `--default-variant` declare variants; `--display-name` and `--description` fill the descriptor, on a refresh too; a refresh that first records the library also copies its license notices and takes its license, and a refresh changes only the icons the refreshed library supplies (your own `./` artwork and other libraries' icons keep their map entries and variants, and `add --all` leaves them alone), knows an existing icon by the library export it re-exports, so the icon keeps its export name exactly, its map entries, variants, and words when its id changes, and the change is listed under `renamed`. Ids keep a dimension as one word (`squares-2x2`), a library's other names for an icon become its words, and `…Provider` and `…Context` exports are never icons. A library of 1,600 icons is read in about two seconds.+- **`experimental icon add` and `map`.** `add --variant <name> --from <module> --all` adds a variant for every icon at once; a `./` file is named as written, and the receipt names the package.json `files` that publishes it. `map --pairs a=b,c=d` writes many entries in one checked write, and both accept a definition's kebab id; `map` names an icon by its id, its export name in any case, or another name its library exports it as, never by one word of its id.+- **Options decided in pairs.** Every icon command refuses two options it would not both honor, with `ERR_INVALID_OPTION` (such as `--list --definitions`, `--definitions --limit 3`, `--all-icons` with a query, `add --all --id`, or `new-set --exclude` without `--from`), instead of ignoring one.+- **All or nothing.** When `new-set`, `add`, `map`, or `new-definition` fails partway, every file is as it was and the error is `ERR_WRITE_FAILED`.+- **Sets named consistently.** Every icon command that names a set (`--set` with a query or `--all-icons`, `<set>/<id>`, `use`, and `add`, `map`, `new-definition` in the package) reports a set that is not there as missing and an invalid one as withdrawn, with why, both `ERR_NOT_FOUND`.+- **Listing.** `experimental icon --set <set> --all-icons` lists every icon of a set (`icon.setIcons`) and `--definitions` lists every Astryx definition, built in or optional (`icon.definitions`). Search shows partial matches only when nothing better matches.+- **Templates.** A mapped icon drops the library's sizing props (`size`, `strokeWidth`, `absoluteStrokeWidth`), reported as `dropped`, and comments on a rewritten import line are kept.+- **Definitions.** Thirteen new icon definitions (`rotate`, `flipHorizontal`, `flipVertical`, `alignStart`, `alignCenter`, `alignEnd`, `panelLeft`, `panelRight`, `gitBranch`, `gitFork`, `scale`, `cpu`, `textCase`), declared by the templates that draw them. Built-in and optional definitions gain common glyph names as words; seven optional definitions lose a word that named a different thing, so a search for that word no longer finds a set's icon through them: `star` (`bookmark`), `database` (`table`), `raiseHand` (`stop`), `redo` (`forward`), `activity` (`monitor`), `archive` (`store`), `mobile` (`device`).+- **Checks.** `integration check` suggests icons by the same rule and lists each optional definition with its description and words; the version-drift warning gives the refresh command.++@josephfarinadiff --git a/docs/specs/AST-084-icon-sets/spec.md b/docs/specs/AST-084-icon-sets/spec.mdindex aed4b811b7..2b7c3dae36 100644--- a/docs/specs/AST-084-icon-sets/spec.md+++ b/docs/specs/AST-084-icon-sets/spec.md@@ -138,8 +138,9 @@ icon, and the CLI verifies it, writes the files, and checks the set.`default.variant`, the one each icon's own `export` draws. A variant is anamed look the set supplies (for example outline or solid); size comesfrom CSS;- - optional `source` (the upstream library and version), `generated`- (FR13), `adapter` (FR13), and `themeMap` (FR12).+ - optional `source` (the upstream library and version), `exclude` (library+ exports that are not icons, FR13), `generated` (FR13), `adapter` (FR13),+ and `themeMap` (FR12).A data file that fails this shape, repeats an `id`, maps a name that isneither an Astryx definition nor one of the set's own, maps to a missing@@ -168,12 +169,15 @@ icon, and the CLI verifies it, writes the files, and checks the set.`export`, `import` line, `words`, `definitions`, `variants`, `reason`, and`score`: 100 for a definition the set maps to the icon, 90 or 80 for anexact 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.+ leads), 60 when the query starts one of its words, 40 for a partial match,+ which answers only when nothing scores 60 or more. 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; `--set` with `--all-icons` and no words lists every icon of+ that set (`icon.setIcons`), and `--definitions` lists every Astryx+ definition (`icon.definitions`).- **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@@ -197,19 +201,24 @@ icon, and the CLI verifies it, writes the files, and checks the set.`map` names for the definition. Every reference uses the mapped export,under an alias when the name is taken; a mapped default import becomes theset's named import aliased to its local name. Nothing is guessed from names,- and a `likely` match is only suggested.+ and a `likely` match is only suggested. One key covers a name imported from+ two modules (outline and solid `TrashIcon`); each keeps its variant when its+ module belongs to an installed set. A mapped icon's elements lose the+ library's sizing props (`size`, `strokeWidth`, `absoluteStrokeWidth`): size+ comes from CSS (FR14). Comments on a rewritten import line are kept.- **FR10 — The template reports every icon.** The result, and the copyreceipt, 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`.+ the rule, and the sizing props `dropped`) 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.@@ -220,21 +229,96 @@ icon, and the CLI verifies it, writes the files, and checks the set.### 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:+ icon command refuses, with `ERR_INVALID_OPTION` and before it writes a+ file, two options it would not both honor: a listing (`--list`,+ `--definitions`, `--all-icons`) with a query, another listing, or an+ option it ignores; a `<set>/<id>` query with `--set` or `--limit`;+ `add --all` with an export name, `--definition`, `--new-definition`,+ `--description`, `--words`, `--default`, or `--id`; `add --definition`+ with `--new-definition`; `add --description` or `--words` without+ `--new-definition`; `map --pairs` with a definition, an icon, or+ `--remove`, and `map --remove` with an icon; and `new-set --exclude`+ without `--from` or `--default-variant` without `--variants`. Every+ command reads modules statically, and its writes are all or nothing: when+ it fails, every file is as it was and the error has a stable code+ (`ERR_WRITE_FAILED` for a write that fails). It writes only the set's own+ files, the manifest root, and the set's root and manifest in an existing+ package.json `files` (architecture:cli-surface INV16); every other change+ the package needs, it names as the exact text to add:- `experimental icon new-set <name>` writes the descriptor, an empty datafile, the generated module (`generated`) with its declaration file and anempty theme map, and the manifest root. `--from <module>` wraps everycomponent 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.+ name is an icon's whole `id`, and lists those entries for review. For an+ unmapped definition it returns, never writes, up to three suggestions,+ in this order: an icon whose `id` is the definition's name spelled with or+ without hyphens or with a plural `s` (`light-bulb` for `lightbulb`,+ `languages` for `language`); an icon whose library gives it the+ definition's name as another name; icons whose `id` starts with the+ definition's name as written, most of its words first; an icon whose `id`+ is one of its words; an icon whose library gives it one of its words as+ another name; then two-word ids whose first word is a one-word word+ exactly and whose second word only sizes, shapes, or numbers it+ (`grid-2x2`, `plus-circle`; never `card-sim` or `fast-forward`). A plural+ joins only its own singular, never a longer id (`users` is not+ `user-plus`), and no other ending is taken off (`drafting` is not+ `draft`). Never an icon `map` already uses, one whose `id` is another+ definition's name, a negated form (`lock-open`, `bell-off`), or the+ opposite direction (`ellipsis-vertical` for `moreHorizontal`).+ Ids keep a dimension as one word (`Squares2X2Icon` is `squares-2x2`)+ and split a one-letter word from a digit (`CalendarX2` is+ `calendar-x-2`); a shared library prefix is left out of ids and names;+ an icon exported under several names is recorded once, its other names+ as words; `…Provider` and `…Context` components+ are never icons; and `--exclude` adds exports that are not icons to the+ data file's `exclude`, which every refresh honors. From an installed+ package it records `source` (the library and version), copies the+ library's license notices into the set, and takes the library's license+ for the descriptor. Its receipt names, as the exact text to add, the+ entry change that makes the generated module public (an `export *` line+ for an entry file in the package, relative to it; for a package with no+ entry, `index.js`, `index.d.ts`, and their package.json `main`, `types`,+ and `exports`; for a built or CommonJS entry, the line for the source it+ is built from, never the built file), the `react` and optional+ `@types/react` and `@astryxdesign/cli` peers it does not declare, and a+ `typecheck` script running `integration check --strict` when it has+ none. `--variants` and `--default-variant` declare `variants` and+ `default`; `--display-name` and `--description` fill the descriptor. Run+ again, it refreshes the icons that module supplies (those the generated+ module re-exports or adapts from it) and keeps `map` entries whose icon+ exists; every other icon (the author's `./` artwork, another library's)+ is kept with its `map` entries and variants, a library icon whose `id`+ or export one of those has is left out and named, and each icon the+ module no longer exports, or that `exclude` now names, is removed and+ named for that reason, with the `map` entries that named it. An existing+ icon is known by the library export its generated module re-exports, then+ by its own export, then by its `id`; one matched this way keeps its export+ unchanged, its `map` entries, and every other field, and an `id` the+ current rule spells differently is reported under `renamed`+ (`add --variant <name> --all` meets an icon the same way). A refresh+ copies the library's license notices the set lacks, and the run that+ first records `source` takes the library's license for the descriptor+ when its `license` is still the one `new-set` wrote (the package's own,+ or `UNLICENSED`); a `license` the author changed is kept, and the+ receipt names both. Later runs keep the descriptor's `license`. The+ package's own `license` is never written.- `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;+ that declared variant of an existing icon. With `--variant <name> --all`+ and no export, it adds that variant for every icon from that module's+ package whose `id` an export of the module has, in one write; an icon+ from another module is left alone and not listed as missing. For a `./`+ file outside package.json `files`, it names the `files` array that+ publishes it.+ - `experimental icon map <definition> <icon>` writes one `map` entry,+ `--remove` removes one, and `--pairs` writes many in one checked write;+ here and in `add --definition` a definition may be named by its kebab+ id. `map` names an icon only by its `id`, its export name in any case,+ or another name its library exports it as (a word it carries that is+ not a part of its `id`); a part of an `id` alone (`glass` for+ `magnifying-glass`) is refused with the icons that carry it;`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@@ -267,12 +351,17 @@ icon, and the CLI verifies it, writes the files, and checks the set.| `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+ A definition finding names the definition's description and words and the+ `icon map` command that fixes it, and suggests icons by the rule `new-set`+ uses (FR13), never from part of a word. When the package's entry exports+ neither the set's theme map nor any of its icons, one `icon_export_missing`+ names the same entry change the `new-set` receipt names (FR13), in place of+ a finding per icon: for a built entry, the source it is built from, never+ the built file. A CommonJS entry the reader cannot read is listed as not+ checked instead. 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 andnever failing, even under `--strict` or `--next`, in the validate result'sadditivefield `iconSets` (each `{set, unmappedDefinitions, suggestions,@@ -301,7 +390,11 @@ message}`) names each template or namespace doc that sets `stability`, andproject. `experimental icon use` adds `warning` to its receipt, printed as a`[warn]` line, when the project declares an `@astryxdesign/cli` range (inany dependency field) that admits such a release; a project that declares no- range, or a `workspace:`, `file:`, or `link:` one, gets none.+ range, or a `workspace:`, `file:`, or `link:` one, gets none. A CLI reads a+ set's data file strictly: a key it does not know withdraws the set, naming+ the key (FR17). `exclude` is read only by a CLI whose data-file reference+ lists it, and `new-set` writes it only when `--exclude` is given; a set+ without it is read by every CLI that has `astryx experimental icon`.- **FR17 — Doctor and discover read sets only with the opt-in.** In a projectthat sets `experimental.iconSet`, the project's set is one of: valid(`selected`), not installed (`missing`), or installed but withdrawn@@ -310,9 +403,11 @@ message}`) names each template or namespace doc that sets `stability`, andor one that was withdrawn, saying which and why, and warns when two packagesship 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+ `experimental icon` with `--set` (with words or `--all-icons`) or+ `<set>/<id>`, `experimental icon use`, and `discover <package>/<set>` name a+ withdrawn set as withdrawn, with its reason, rather than as not installed,+ each with `ERR_NOT_FOUND`; `add`, `map`, and `new-definition` name a+ withdrawn set in the package being authored the same way. `astryx discover` reads `icon-set` asa kind: `--type icon-set`, catalog entries with `iconCount` and`definitions`, and `discover <package>/<set>`; a withdrawn set is notlisted. Without the opt-in, Doctor has no such check and reports no icon-setdiff --git a/packages/cli/README.md b/packages/cli/README.mdindex 581cfc6024..ceb1476183 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -96,24 +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` |-| `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` |+| 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 in a patch release: icon sets (find icons, build an icon-set package) | 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`. -->diff --git a/packages/cli/api/icon/_adapter.mjs b/packages/cli/api/icon/_adapter.mjsindex 4468e7ab25..d0e5df5dbc 100644--- a/packages/cli/api/icon/_adapter.mjs+++ b/packages/cli/api/icon/_adapter.mjs@@ -15,7 +15,10 @@ 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 {+ IconSetAuthoringError,+ allOrNothing,+} 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';@@ -44,6 +47,9 @@ export {resolveIconSource,generatedModulePath,generatedNamesOf,+ generatedOrigins,+ iconModulePackage,+ sameIconModule,iconExportName,iconNaming,modulePrefix,@@ -51,6 +57,10 @@ export {variantExportName,writeGeneratedIcons,writeIconSetData,+ definitionNameOf,+ iconIdIn,+ iconsWithWord,+ localSourceNote,THEME_MAP_NAME,} from '../../foundation/discovery/icon-set-writer.mjs';export {exportValueKind} from '../../foundation/discovery/module-exports.mjs';@@ -87,14 +97,17 @@ function hasPackageJsonAbove(dir) {}/**- * Run one authoring step, turning its errors into AstryxErrors.+ * Run one authoring command so its writes are all or nothing, turning its+ * errors into AstryxErrors.* @template T* @param {() => T | Promise<T>} step* @returns {Promise<T>}*/export async function authoring(step) {try {- return await step();+ // All or nothing: a failure after some writes puts every file back+ // (AST-084 FR13).+ return await allOrNothing(step);} catch (error) {if (error instanceof IconSetAuthoringError) {throw new AstryxError(diff --git a/packages/cli/api/icon/_authoring.mjs b/packages/cli/api/icon/_authoring.mjsindex 9061dc56c6..53469d263d 100644--- a/packages/cli/api/icon/_authoring.mjs+++ b/packages/cli/api/icon/_authoring.mjs@@ -33,17 +33,29 @@ import {findLocalIconSet,generatedModulePath,generatedModuleText,+ generatedOrigins,+ sameIconModule,generatedTypesPath,THEME_MAP_NAME,+ entryWiringNote,iconSetDataText,+ journalFile,+ librarySource,libraryIcons,+ nonIconExports,resolveIconSource,- setModuleNote,+ peerNote,+ typecheckNote,writeDefinitionFile,writeGeneratedIcons,writeIconSetData,} from '../../foundation/discovery/icon-set-writer.mjs';import {astryxIconDefinitions} from '../../foundation/discovery/icon-definition-discovery.mjs';+import {suggestedIcons} from '../../foundation/discovery/icon-set-checks.mjs';+import {+ resolveProjectTypeScript,+ TYPESCRIPT_FIX,+} from '../../foundation/discovery/project-typescript.mjs';import {KEBAB_NAME_RE,applyWrites,@@ -82,11 +94,12 @@ function quoteJs(value) {* 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+ * @param {{cwd?: string, dryRun?: boolean, from?: string, exclude?: string[] | string, variants?: string[] | string, defaultVariant?: string, displayName?: string, description?: 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 looks = variantOptions(options);const exclude =typeof options.exclude === 'string'? options.exclude@@ -98,7 +111,7 @@ export async function addIconSet(name, options) {throw new AstryxError('--exclude names library exports to leave out, so it needs --from.',undefined,- ERROR_CODES.ERR_INVALID_ARGUMENT,+ ERROR_CODES.ERR_INVALID_OPTION,);}if (!KEBAB_NAME_RE.test(name)) {@@ -179,6 +192,11 @@ export async function addIconSet(name, options) {dryRun,from,exclude,+ looks,+ describe: {+ displayName: options.displayName,+ description: options.description,+ },packageDir,rootPath,manifestPath: projectPath(path.relative(packageDir, manifestFile)),@@ -203,6 +221,12 @@ export async function addIconSet(name, options) {let map = {};/** @type {import('../../foundation/discovery/icon-set-writer.mjs').GeneratedIcon[]} */let exportsToWrite = [];+ /** @type {Array<{definition: string, icon: string, word: string}>} */+ let suggestions = [];+ /** @type {string[]} */+ let skipped = [];+ /** @type {ReturnType<typeof librarySource>} */+ let library = null;if (from != null) {const source = await iconAuthoring(() =>resolveIconSource(from, {packageDir, pkg}),@@ -218,9 +242,12 @@ export async function addIconSet(name, options) {icons = found.map(icon => ({id: icon.id,export: icon.name,- words: icon.id.split('-'),+ words: [...new Set([...idWords(icon.id), ...icon.aliases])],}));map = exactDefinitionMap(icons, {});+ skipped = nonIconExports(source.file, {exclude});+ suggestions = definitionSuggestions(icons, map);+ library = librarySource(source.module, packageDir);exportsToWrite = found.map(icon => ({name: icon.name,from: source.module,@@ -231,7 +258,14 @@ export async function addIconSet(name, options) {const data = {schemaVersion: /** @type {const} */ (1),module: pkg.name,+ ...(library+ ? {source: {package: library.package, version: library.version}}+ : {}),+ ...(exclude.length > 0 ? {exclude: [...new Set(exclude)].sort()} : {}),generated,+ ...(looks+ ? {variants: looks.variants, default: {variant: looks.default}}+ : {}),themeMap: THEME_MAP_NAME,map,icons,@@ -240,20 +274,21 @@ export async function addIconSet(name, options) {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 displayName = options.displayName?.trim() || kebabToTitle(name);+ // The artwork license is the wrapped library's, else the package's own;+ // the author edits it when the artwork comes from elsewhere.const license =- typeof pkg.license === 'string' && pkg.license.trim() !== ''+ library?.license ??+ (typeof pkg.license === 'string' && pkg.license.trim() !== ''? pkg.license- : 'UNLICENSED';+ : 'UNLICENSED');const docContents = ["/** @type {import('@astryxdesign/cli/authoring').IconSetDoc} */",'export default {'," type: 'icon-set',",` name: ${quoteJs(name)},`,` displayName: ${quoteJs(displayName)},`,- ` description: ${quoteJs(`${displayName} icons.`)},`,+ ` description: ${quoteJs(options.description?.trim() || `${displayName} icons.`)},`,' maintained: true,',` license: ${quoteJs(license)},`,'};',@@ -273,6 +308,16 @@ export async function addIconSet(name, options) {contents: generatedText.js,createOnly: true,});+ // The wrapped library's license notices travel with its artwork.+ for (const notice of library?.notices ?? []) {+ const target = assertWithin(notice, setDir, {label: 'license notice'});+ if (!library || fs.existsSync(target)) continue;+ plans.push({+ path: target,+ contents: fs.readFileSync(path.join(library.dir, notice), 'utf-8'),+ createOnly: true,+ });+ }const typesPath = generatedTypesPath(generated);if (typesPath && generatedText.dts != null) {plans.push({@@ -308,6 +353,10 @@ export async function addIconSet(name, options) {};if (!dryRun) {let rollback = () => {};+ // Every file this writes, the manifest included, is journaled first, so+ // a failure anywhere puts each back (AST-084 FR13).+ for (const plan of plans) journalFile(plan.path);+ journalFile(manifestFile);try {rollback = applyWrites(plans);rootReceipt = await patchIntegrationRoot(@@ -366,19 +415,45 @@ export async function addIconSet(name, options) {);{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,- );+ if (from != null) {+ result.data.mapped = Object.entries(map).map(([definition, icon]) => ({+ definition,+ icon,+ }));+ result.data.suggestions = suggestions;+ }+ // `integration check --strict` type-checks the set's typed doc files.+ const typescript = resolveProjectTypeScript([packageDir]);+ /** @type {Record<string, any>} */+ const packageAfter = pkgUpdate ? JSON.parse(pkgUpdate.contents) : pkg;result.data.notes = [- ...(moduleNote ? [moduleNote] : []),+ // First, so a long receipt never hides it: the strict check needs it.+ ...(typescript?.ts+ ? []+ : [+ typescript+ ? `\`integration check --strict\` type-checks the set's doc files with this package's TypeScript, ${typescript.version}, which has no compiler API. ${TYPESCRIPT_FIX}`+ : "`integration check --strict` type-checks the set's doc files with TypeScript, which this package does not have: run `npm install -D typescript@6` (TypeScript 5.0 through 6).",+ ]),+ // What the package needs that the CLI leaves to its author+ // (architecture:cli-surface INV16), each as the exact change to make.+ ...[+ entryWiringNote(packageDir, packageAfter, generated),+ peerNote(packageAfter),+ typecheckNote(packageAfter),+ ].filter(note => note != null),+ ...(options.description?.trim()+ ? []+ : [+ `The set's description is a placeholder ("${displayName} icons."): apps and discover show it. Pass --description when you create a set, or edit ${projectPath(path.relative(packageDir, docFile))}.`,+ ]),+ ...(skipped.length > 0+ ? [+ `Left out ${skipped.length} exports that are not icons: ${skipped.slice(0, 12).join(', ')}${skipped.length > 12 ? ', …' : ''}.`,+ ]+ : []),+ ...mappedNotes(map),+ ...suggestionNotes(suggestions),'Run `astryx integration check` to see the icon definitions still to map.',];}@@ -386,8 +461,26 @@ export async function addIconSet(name, options) {}/**- * 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.+ * An icon's words from its id: each part, leaving out a bare number+ * (`volume-2` is `volume`) unless the id is only numbers.+ * @param {string} id+ */+function idWords(id) {+ const parts = id.split('-');+ const named = parts.filter(part => !/^[0-9]+$/u.test(part));+ return named.length > 0 ? named : parts;+}++/** @param {string} name a camelCase definition name, as a kebab id */+const definitionId = name =>+ name.replace(/([a-z0-9])([A-Z])/gu, '$1-$2').toLowerCase();++/**+ * The `map` entries an exact name gives: each Astryx definition whose name+ * is an icon's id (`delete` → icon `delete`). A word alone never maps: a+ * library's `trash` may not mean what a template's delete means, so it is a+ * suggestion ({@link definitionSuggestions}). Entries the map already has are+ * kept.* @param {Array<{id: string}>} icons* @param {Record<string, string>} map*/@@ -397,18 +490,113 @@ function exactDefinitionMap(icons, map) {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;+ const id = definitionId(doc.name);+ if (ids.has(id)) next[doc.name] = id;}return next;}+/**+ * The icons each still-unmapped Astryx definition might map to+ * ({@link suggestedIcons}). Never written; the author chooses with+ * `astryx experimental icon map <definition> <icon>`.+ * @param {Array<{id: string, words: string[]}>} icons+ * @param {Record<string, string>} map+ * @returns {Array<{definition: string, icon: string, word: string}>}+ */+function definitionSuggestions(icons, map) {+ const set = {data: {icons, map}};+ return astryxIconDefinitions()+ .definitions.map(each => each.doc)+ .filter(doc => !map[doc.name])+ .flatMap(doc =>+ suggestedIcons(set, doc).map(each => ({definition: doc.name, ...each})),+ )+ .sort((a, b) =>+ a.definition < b.definition ? -1 : a.definition > b.definition ? 1 : 0,+ );+}++/**+ * The receipt's note for the suggestions, if any.+ * @param {Array<{definition: string, icon: string}>} suggestions+ */+function suggestionNotes(suggestions) {+ if (suggestions.length === 0) return [];+ const count = new Set(suggestions.map(each => each.definition)).size;+ return [+ `${count} unmapped icon definitions have possible icons (listed under Suggestions; nothing was written for them). Check each meaning, then map the ones that fit: \`astryx experimental icon map <definition> <icon>\`.`,+ ];+}++/**+ * The receipt's note for the entries an exact name wrote, if any.+ * @param {Record<string, string>} map+ */+function mappedNotes(map) {+ const count = Object.keys(map).length;+ if (count === 0) return [];+ return [+ `${count} icon definitions were mapped because an icon has their exact name (listed under Mapped by name). A library can draw another meaning under the same name, such as a backspace key named delete: check each, and remap with \`astryx experimental icon map <definition> <icon>\`.`,+ ];+}++/** A variant name: lower-kebab, such as `outline` or `mini-solid`. */+const VARIANT_NAME_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;++/**+ * The variants and default variant `--variants` and `--default-variant`+ * declare, or+ * null when neither is given. The default is the first variant unless named.+ * @param {{variants?: string[] | string, defaultVariant?: string}} options+ * @returns {{variants: string[], default: string} | null}+ */+function variantOptions(options) {+ const given =+ typeof options.variants === 'string'+ ? options.variants.split(',')+ : options.variants;+ const variants = [+ ...new Set((given ?? []).map(each => each.trim()).filter(Boolean)),+ ];+ const chosen = options.defaultVariant?.trim();+ if (variants.length === 0) {+ if (chosen) {+ throw new AstryxError(+ "--default-variant names one of the set's variants, so it needs --variants.",+ [+ {+ name: `--variants ${chosen},<other>`,+ reason: 'declare the variants',+ },+ ],+ ERROR_CODES.ERR_INVALID_OPTION,+ );+ }+ return null;+ }+ for (const variant of variants) {+ if (!VARIANT_NAME_RE.test(variant)) {+ throw new AstryxError(+ `Invalid variant name "${variant}": use lower-kebab, such as outline or solid.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ }+ if (chosen && !variants.includes(chosen)) {+ throw new AstryxError(+ `--default-variant "${chosen}" is not one of --variants (${variants.join(', ')}).`,+ variants.map(each => ({+ name: `--default-variant ${each}`,+ reason: 'a declared variant',+ })),+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ return {variants, default: chosen || variants[0]};+}+/*** Run an icon-set authoring step, turning its errors into AstryxErrors.* @template T@@ -444,74 +632,254 @@ async function iconAuthoring(step) {* 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+ * @param {{cwd: string, dryRun: boolean, from: string, exclude: string[], looks: {variants: string[], default: string} | null, describe: {displayName?: string, description?: string}, packageDir: string, rootPath: string, manifestPath: string}} options*/async function refreshIconSet(name,- {cwd, dryRun, from, exclude, packageDir, rootPath, manifestPath},+ {+ cwd,+ dryRun,+ from,+ exclude,+ looks,+ describe,+ packageDir,+ rootPath,+ manifestPath,+ },) {return iconAuthoring(async () => {const where = await findLocalIconSet(cwd, name);const {set} = where;const source = resolveIconSource(from, where);+ // Exports left out before stay out; --exclude adds to them.+ const excluded = [+ ...new Set([...(set.data.exclude ?? []), ...exclude]),+ ].sort();const found = libraryIcons(source.file, {adapter: Boolean(set.data.adapter),- exclude,+ exclude: excluded,});- 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 ?? [])])],- };+ // A refresh changes only the icons the refreshed module supplies: those+ // the generated module re-exports or adapts from it. Every other icon+ // (your own `./` artwork, another library's) is kept as it is, with its+ // map entries and variants.+ const generatedBefore = generatedModulePath(set, packageDir);+ const origins = generatedOrigins(packageDir, generatedBefore);+ /** @param {{export: string, module?: string}} icon */+ const suppliedHere = icon => {+ if ((icon.module ?? set.data.module) !== set.data.module) return false;+ const origin = origins.get(icon.export);+ return origin != null && sameIconModule(origin.module, source.module);+ };+ const supplied = set.data.icons.filter(suppliedHere);+ const others = set.data.icons.filter(icon => !suppliedHere(icon));+ // An existing icon is the same icon when the library still exports it:+ // its identity is the library export its generated module re-exports+ // (`HiSquares2X2Icon`), then its public export, then its id. Ids and+ // public names are derived, and a newer rule may spell them differently+ // (`squares-2-x2` is now `squares-2x2`); an icon matched this way keeps+ // its public export byte for byte, every field it had (its variants, the+ // words the author added, its module), and its map entries.+ const byId = new Map(supplied.map(icon => [icon.id, icon]));+ const byExport = new Map(supplied.map(icon => [icon.export, icon]));+ const bySource = new Map(+ supplied.map(icon => [origins.get(icon.export)?.source, icon]),+ );+ /** @param {{export: string, name: string, id: string}} icon */+ const priorOf = icon =>+ bySource.get(icon.export) ??+ byExport.get(icon.name) ??+ byId.get(icon.id) ??+ null;+ const otherIds = new Set(others.map(icon => icon.id));+ const otherExports = new Set(others.map(icon => icon.export));+ /** @type {string[]} library icons left out: an icon of yours has the id or name */+ const shadowed = [];+ /** @type {Map<string, string>} old id → new id */+ const renames = new Map();+ /** @type {Map<string, string>} the library export → the set's export */+ const publicName = new Map();+ const fromLibrary = found.flatMap(icon => {+ const prior = priorOf(icon);+ const name = prior?.export ?? icon.name;+ if (!prior && (otherIds.has(icon.id) || otherExports.has(name))) {+ shadowed.push(icon.id);+ return [];+ }+ if (prior && prior.id !== icon.id) renames.set(prior.id, icon.id);+ publicName.set(icon.export, name);+ // The words its old id gave are the old rule's, not the author's.+ const oldIdWords =+ prior && prior.id !== icon.id ? new Set(idWords(prior.id)) : new Set();+ return [+ {+ ...(prior ?? {}),+ id: icon.id,+ export: name,+ words: [+ ...new Set([+ ...idWords(icon.id),+ ...icon.aliases,+ ...(prior?.words ?? []).filter(word => !oldIdWords.has(word)),+ ]),+ ],+ },+ ];});+ const icons = [...fromLibrary, ...others];+ // The icons this module supplied that it no longer exports: they leave+ // the set and its generated module, and the receipt names them.+ // Each is named for why it left: `--exclude` (or the data file's+ // `exclude`) names its library export, or the library no longer exports+ // it.+ const excludedNames = new Set(excluded);+ const gone = supplied.filter(+ icon => !fromLibrary.some(each => each.export === icon.export),+ );+ const isExcluded = (/** @type {{export: string}} */ icon) =>+ excludedNames.has(origins.get(icon.export)?.source ?? '') ||+ excludedNames.has(icon.export);+ const goneExcluded = gone.filter(isExcluded);+ const goneMissing = gone.filter(icon => !isExcluded(icon));+ const excludedIds = new Set(goneExcluded.map(icon => icon.id));const ids = new Set(icons.map(icon => icon.id));/** @type {Record<string, string>} */const kept = {};- /** @type {string[]} */- const lost = [];+ // The data file's `map` names only icons in the set (its parser refuses+ // anything else), so each lost entry's icon is one of these.+ /** @type {{excluded: string[], missing: string[]}} */+ const lost = {excluded: [], missing: []};for (const [definition, id] of Object.entries(set.data.map ?? {})) {- if (ids.has(id)) kept[definition] = id;- else lost.push(`${definition} -> "${id}"`);+ const now = renames.get(id) ?? id;+ if (ids.has(now)) kept[definition] = now;+ else if (excludedIds.has(id)) {+ lost.excluded.push(`${definition} -> "${id}"`);+ } else lost.missing.push(`${definition} -> "${id}"`);}const generated = generatedModulePath(set, packageDir);+ const library = librarySource(source.module, packageDir);+ const map = exactDefinitionMap(icons, kept);+ const suggestions = definitionSuggestions(icons, map);const next = {...set.data,+ ...(library+ ? {source: {package: library.package, version: library.version}}+ : {}),+ ...(excluded.length > 0 ? {exclude: excluded} : {}),generated,+ ...(looks+ ? {variants: looks.variants, default: {variant: looks.default}}+ : {}),...(set.data.themeMap ? {} : {themeMap: THEME_MAP_NAME}),- map: exactDefinitionMap(icons, kept),+ map,icons,};/** @type {string[]} */const files = [];+ const dataChanged =+ iconSetDataText(next) !== fs.readFileSync(set.dataPath, 'utf-8');+ // --display-name and --description rewrite the descriptor's fields.+ const docFile = path.join(set.dir, `${set.name}.doc.mjs`);+ const docBefore = fs.readFileSync(docFile, 'utf-8');+ let docAfter = docBefore;+ for (const [field, value] of /** @type {const} */ ([+ ['displayName', describe.displayName],+ ['description', describe.description],+ ])) {+ if (!value?.trim()) continue;+ docAfter = docAfter.replace(+ new RegExp(+ `^(\\s*${field}:\\s*)(['"\`])(?:\\\\.|(?!\\2).)*\\2,?$`,+ 'mu',+ ),+ (_, lead) => `${lead}${quoteJs(value.trim())},`,+ );+ }+ // A refresh that first records the library as the set's source does what+ // `new-set --from` does: the descriptor takes the library's license, but+ // only over the value `new-set` wrote by default (the package's license,+ // or UNLICENSED), never over one the author chose. Either way the+ // receipt names both values.+ /** @type {string | null} */+ let licenseNote = null;+ if (library?.license && !set.data.source) {+ const license = library.license;+ const licenseRe = /^(\s*license:\s*)(['"`])((?:\\.|(?!\2).)*)\2,?$/mu;+ const current = licenseRe.exec(docBefore)?.[3] ?? null;+ const packageLicense =+ typeof where.pkg.license === 'string' && where.pkg.license.trim() !== ''+ ? where.pkg.license+ : 'UNLICENSED';+ const docRel = projectPath(path.relative(packageDir, docFile));+ if (current === license) {+ // Already the library's.+ } else if (current == null || current === packageLicense) {+ docAfter = docAfter.replace(+ licenseRe,+ (_, lead) => `${lead}${quoteJs(license)},`,+ );+ licenseNote = `The set's license in ${docRel} changed from "${current ?? '(none)'}" to "${license}", the license of ${library.package}, whose artwork it now wraps. Edit it if the artwork's license differs.`;+ } else {+ licenseNote = `The set's license in ${docRel} stays "${current}", which you set; ${library.package} is licensed "${license}". Change it if the artwork is the library's.`;+ }+ }+ if (docAfter !== docBefore) {+ files.push(projectPath(path.relative(packageDir, docFile)));+ }+ // The library's license notices travel with its artwork, as new-set+ // copies them: each one the set directory does not have yet.+ const libraryDir = library?.dir ?? '';+ const notices = (library?.notices ?? [])+ .map(notice => ({+ notice,+ target: assertWithin(notice, set.dir, {label: 'license notice'}),+ }))+ .filter(({target}) => !fs.existsSync(target));+ for (const {target} of notices) {+ files.push(projectPath(path.relative(packageDir, target)));+ }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),+ found+ .map(icon => ({+ name: publicName.get(icon.export) ?? icon.name,+ from: source.module,+ source: icon.export,+ adapt: icon.adapt,+ }))+ .filter(icon => publicName.has(icon.source)),+ // The icons the library no longer exports leave the module too; a+ // renamed icon keeps its export.+ gone.map(icon => icon.export),);files.push(...written.files);try {writeIconSetData(set, next);+ // The descriptor last: the command's journal puts it back with the+ // rest if anything after it fails (AST-084 FR13).+ for (const {notice, target} of notices) {+ journalFile(target);+ fs.writeFileSync(+ target,+ fs.readFileSync(path.join(libraryDir, notice)),+ );+ }+ if (docAfter !== docBefore) {+ journalFile(docFile);+ fs.writeFileSync(docFile, docAfter);+ }} catch (error) {written.undo();throw error;}}- files.push(projectPath(path.relative(packageDir, set.dataPath)));+ if (dataChanged) {+ files.push(projectPath(path.relative(packageDir, set.dataPath)));+ }const result = receipt('icon-set',name,@@ -521,13 +889,60 @@ async function refreshIconSet(dryRun,);result.data.icons = icons.length;+ result.data.refreshed = true;+ // Every entry an exact name gives, kept or new, so a refresh lists+ // them for review again.+ const byName = Object.fromEntries(+ Object.entries(map).filter(+ ([definition, id]) =>+ !(definition in kept) || id === definitionId(definition),+ ),+ );+ result.data.mapped = Object.entries(byName).map(([definition, icon]) => ({+ definition,+ icon,+ }));+ result.data.suggestions = suggestions;+ if (renames.size > 0) {+ result.data.renamed = [...renames].map(([from, to]) => ({from, to}));+ }result.data.notes = [- ...(lost.length > 0+ ...(licenseNote ? [licenseNote] : []),+ ...(renames.size > 0? [- `These map entries named icons the library no longer exports and were removed: ${lost.join(', ')}.`,+ `${renames.size} icons have a new id under this release's id rule, and keep their map entries, variants, and words: ${[...renames].map(([from, to]) => `${from} -> ${to}`).join(', ')}.`,]: []),- 'Run `astryx integration check` to see the icon definitions still to map.',+ ...mappedNotes(byName),+ ...suggestionNotes(suggestions),+ ...(goneMissing.length > 0+ ? [+ `${goneMissing.length} icons the library no longer exports were removed from the set: ${goneMissing.map(icon => icon.id).join(', ')}.`,+ ]+ : []),+ ...(lost.missing.length > 0+ ? [+ `These map entries named those icons and were removed: ${lost.missing.join(', ')}.`,+ ]+ : []),+ ...(goneExcluded.length > 0+ ? [+ `Left out by --exclude, and removed from the set: ${goneExcluded.map(icon => icon.id).join(', ')}.`,+ ]+ : []),+ ...(lost.excluded.length > 0+ ? [+ `These map entries named icons --exclude left out and were removed: ${lost.excluded.join(', ')}.`,+ ]+ : []),+ ...(shadowed.length > 0+ ? [+ `Left out ${shadowed.length} library icons whose id or name an icon of yours from another module already has: ${shadowed.join(', ')}.`,+ ]+ : []),+ astryxIconDefinitions().definitions.every(({doc}) => map[doc.name])+ ? 'Every Astryx icon definition is mapped.'+ : 'Run `astryx integration check` to see the icon definitions still to map.',];return result;});diff --git a/packages/cli/api/icon/_options.mjs b/packages/cli/api/icon/_options.mjsindex 3cf33b2976..22609e7639 100644--- a/packages/cli/api/icon/_options.mjs+++ b/packages/cli/api/icon/_options.mjs@@ -1,10 +1,11 @@// 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.+ * @file The options each icon call takes, and the option pairs it cannot+ * honor together; either is refused, so a caller never gets a silent success+ * that did not do what it asked (spec:AST-042 FR5).*- * @position api/icon — read by api/icon/new-set and api/icon/new-definition+ * @position api/icon — read by every icon leaf*/import {AstryxError} from '../error.mjs';@@ -12,7 +13,16 @@ 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-set': new Set([+ 'cwd',+ 'dryRun',+ 'from',+ 'exclude',+ 'variants',+ 'defaultVariant',+ 'displayName',+ 'description',+ ]),'icon-definition': new Set(['cwd','dryRun',@@ -39,3 +49,28 @@ export function refuseOtherOptions(kind, options) {}}}++/**+ * Refuse two options given together when the call would ignore one of them+ * (spec:AST-042 FR5): each pair names the two as the caller writes them+ * (`--list`, `a query`), and `given` says which the caller passed. A pair is+ * refused with `ERR_INVALID_OPTION`, in the order the list gives, before any+ * file is written.+ * @param {Record<string, boolean>} given each option's label, and whether it was passed+ * @param {ReadonlyArray<readonly [string, string]>} pairs+ */+export function refuseIgnoredPairs(given, pairs) {+ for (const [a, b] of pairs) {+ if (given[a] && given[b]) {+ throw new AstryxError(+ `${a} and ${b} cannot be used together`,+ undefined,+ ERROR_CODES.ERR_INVALID_OPTION,+ );+ }+ }+}++/** @param {unknown} value whether an option was passed at all */+export const passed = value =>+ value !== undefined && value !== null && value !== false && value !== '';diff --git a/packages/cli/api/icon/_records.mjs b/packages/cli/api/icon/_records.mjsindex a4c7729ef5..3611deec7d 100644--- a/packages/cli/api/icon/_records.mjs+++ b/packages/cli/api/icon/_records.mjs@@ -11,6 +11,8 @@* @position api/icon — shared by the search, detail, and list leaves*/+import {AstryxError} from '../error.mjs';+import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';export {iconRecord,@@ -53,6 +55,29 @@ export function withdrawnReason(withdrawn, selector) {: null;}+/**+ * The one error every icon entry point gives for a set selector that names+ * no valid installed set (AST-084 FR17): withdrawn, with its reason, when it+ * names an installed set that was withdrawn; else not installed. Both are+ * `ERR_NOT_FOUND`, with the closest valid sets as suggestions.+ * @param {Array<{name: string, package: string}>} sets the valid sets+ * @param {Array<{name: string, package: string, reason: string}>} withdrawn+ * @param {string} selector+ * @returns {AstryxError}+ */+export function unusableSet(sets, withdrawn, selector) {+ return 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,+ );+}+/*** Suggestions for a name that matched nothing: the closest candidates first.* @param {string} wanteddiff --git a/packages/cli/api/icon/add/add.mjs b/packages/cli/api/icon/add/add.mjsindex 959042e7c7..4e6b19251f 100644--- a/packages/cli/api/icon/add/add.mjs+++ b/packages/cli/api/icon/add/add.mjs@@ -38,7 +38,12 @@ import {exportValueKind,generatedModulePath,generatedNamesOf,+ generatedOrigins,+ iconModulePackage,iconNaming,+ localSourceNote,+ definitionNameOf,+ libraryIcons,modulePrefix,variantExportName,rankIcons,@@ -50,6 +55,7 @@ import {writeIconSetData,refuseOutsideProject,} from '../_adapter.mjs';+import {passed, refuseIgnoredPairs} from '../_options.mjs';/** The lowest score a definition match needs: an exact word or name. */const FIT_FLOOR = 80;@@ -63,24 +69,72 @@ const MATCH_LIMIT = 10;* 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 {string | undefined} exportName the export the set exposes the icon as; absent with `all`* @param {import('../icon.type.mjs').IconAddOptions} options- * @returns {Promise<import('../icon.type.mjs').IconAddResponse | import('../icon.type.mjs').IconDefinitionMatchesResponse>}+ * @returns {Promise<import('../icon.type.mjs').IconAddResponse | import('../icon.type.mjs').IconDefinitionMatchesResponse | import('../icon.type.mjs').IconAddVariantsResponse>}*/export async function iconAdd(exportName, options) {const {cwd = process.cwd(),from,set: selector,- definition,+ definition: givenDefinition,newDefinition,description,words,useDefault = false,variant,id: givenId,+ all = false,} = options ?? {};refuseOutsideProject(cwd, 'experimental icon add', 'the icon-set package');+ // `--all` adds a declared variant to existing icons, so it names no icon+ // and maps nothing; a description and words describe only a new+ // definition (spec:AST-042 FR5).+ refuseIgnoredPairs(+ {+ 'an export name': passed(exportName),+ '--definition': passed(givenDefinition),+ '--new-definition': passed(newDefinition),+ '--description': passed(description),+ '--words': passed(words),+ '--default': passed(useDefault),+ '--id': passed(givenId),+ '--all': passed(all),+ },+ [+ ['--all', 'an export name'],+ ['--all', '--definition'],+ ['--all', '--new-definition'],+ ['--all', '--description'],+ ['--all', '--words'],+ ['--all', '--default'],+ ['--all', '--id'],+ ['--definition', '--new-definition'],+ ['--definition', '--description'],+ ['--definition', '--words'],+ ],+ );+ for (const [flag, value] of /** @type {const} */ ([+ ['--description', description],+ ['--words', words],+ ])) {+ if (passed(value) && !passed(newDefinition)) {+ throw new AstryxError(+ `${flag} describes a new definition, so it needs --new-definition`,+ [+ {+ name: `--new-definition <name> --description '<what it is for>' --words a,b`,+ reason: 'add your own definition',+ },+ ],+ ERROR_CODES.ERR_INVALID_OPTION,+ );+ }+ }+ if (all) {+ return authoring(() => addVariantForAll({cwd, from, selector, variant}));+ }return authoring(async () => {if (typeof exportName !== 'string' ||@@ -99,15 +153,13 @@ export async function iconAdd(exportName, options) {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;+ // The docs' kebab id (`eye-slash`) names the same definition.+ const definition =+ givenDefinition == null+ ? undefined+ : definitionNameOf(givenDefinition, mappableDefinitions(set));const source = resolveIconSource(from, where);const sourceExport = useDefault ? 'default' : exportName;assertIconExport(source.file, source.module, sourceExport);@@ -126,9 +178,12 @@ export async function iconAdd(exportName, options) {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)});+ // A ./ path is the author's own files, named as written: never a library+ // prefix (`CheckDouble` and `CheckDoubleSolid` share `check`).+ const shared =+ useDefault || source.module.startsWith('./')+ ? []+ : modulePrefix(source.file, {adapter: Boolean(set.data.adapter)});const nameWords = iconIdOf(exportName).split('-');const prefix =shared.length > 0 &&@@ -305,7 +360,15 @@ export async function iconAdd(exportName, options) {JSON.stringify(next) !== JSON.stringify(set.data) ||created != null ||generatedChanged;- const note = setModuleNote(set, where, generated, setName);+ // A ./ file publishes only when package.json `files` lists it; the+ // author adds it (architecture:cli-surface INV16).+ const note =+ [+ localSourceNote(packageDir, source.module),+ setModuleNote(set, where, generated, setName),+ ]+ .filter(Boolean)+ .join(' ') || null;return {type: /** @type {const} */ ('icon.add'),data: {@@ -414,3 +477,153 @@ function definitionMatches(set, exportName, from, id) {},};}++/**+ * `--all`: add one variant for every icon of the set whose library export+ * has a counterpart in `from` with the same id (`TrashIcon` in the solid+ * module is the solid variant of `trash`), in one write.+ * @param {{cwd: string, from: string | undefined, selector: string | undefined, variant: string | undefined}} args+ * @returns {Promise<import('../icon.type.mjs').IconAddVariantsResponse>}+ */+async function addVariantForAll({cwd, from, selector, variant}) {+ if (variant == null || variant === '') {+ throw new AstryxError(+ '--all adds one variant for every icon: pass --variant with the variant, such as solid.',+ undefined,+ ERROR_CODES.ERR_MISSING_ARGUMENT,+ );+ }+ if (typeof from !== 'string' || from.trim() === '') {+ throw new AstryxError(+ 'Pass --from with the module that exports the variant, such as @heroicons/react/24/solid.',+ undefined,+ ERROR_CODES.ERR_MISSING_ARGUMENT,+ );+ }+ const where = await findLocalIconSet(cwd, selector);+ const {packageDir, set} = where;+ const declared = set.data.variants ?? [];+ if (!declared.includes(variant)) {+ throw new AstryxError(+ `Icon set "${set.name}" declares no variant "${variant}"${declared.length > 0 ? ` (it declares ${declared.join(', ')})` : ''}. Declare it first.`,+ [+ {+ name: `astryx experimental icon new-set ${set.name} --from <its library> --variants ${[...new Set([...(declared.length > 0 ? declared : ['<default>']), variant])].join(',')}`,+ reason: 'declare the variants',+ },+ ],+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ if (set.data.default?.variant === variant) {+ throw new AstryxError(+ `"${variant}" is the set's default variant: each icon's own export already draws it.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ const source = resolveIconSource(from, where);+ const found = libraryIcons(source.file, {adapter: Boolean(set.data.adapter)});+ const byId = new Map(found.map(each => [each.id, each]));+ // An existing icon is known by the library export it re-exports, then by+ // its own export, then by its id: an icon whose id or name an older rule+ // wrote (`squares-2-x2`, `Squares2X2Icon`) still meets its variant+ // (`HiSquares2X2Icon` in the solid module).+ const byLibraryExport = new Map(found.map(each => [each.export, each]));+ const byName = new Map(found.map(each => [each.name, each]));+ const origins = generatedOrigins(+ packageDir,+ generatedModulePath(set, packageDir),+ );+ // Only icons from the same package as the variant module can have a+ // variant there: an icon from your own `./` file, or from another library,+ // is left as it is and never listed as missing.+ const variantPackage = iconModulePackage(source.module);+ const generated = generatedModulePath(set, packageDir);+ /** @type {import('../../../foundation/discovery/icon-set-writer.mjs').GeneratedIcon[]} */+ const toWrite = [];+ /** @type {string[]} */+ const added = [];+ /** @type {string[]} */+ const already = [];+ /** @type {string[]} */+ const missing = [];+ const icons = set.data.icons.map(icon => {+ const origin = origins.get(icon.export);+ if (origin && iconModulePackage(origin.module) !== variantPackage) {+ return icon;+ }+ const librarySource =+ origin && origin.source !== 'default' ? origin.source : undefined;+ const match =+ (librarySource ? byLibraryExport.get(librarySource) : undefined) ??+ byName.get(icon.export) ??+ byId.get(icon.id);+ if (!match) {+ missing.push(icon.id);+ return icon;+ }+ if (match.adapt && !set.data.adapter) {+ missing.push(icon.id);+ return icon;+ }+ const name = variantExportName(icon.export, variant);+ const variants = [...(icon.variants ?? [])];+ if (variants.some(each => each.variant === variant)) {+ already.push(icon.id);+ return icon;+ }+ toWrite.push({+ name,+ from: source.module,+ source: match.export,+ adapt: match.adapt,+ });+ variants.push({variant, export: name});+ added.push(icon.id);+ return {...icon, variants};+ });+ if (added.length === 0 && already.length === 0) {+ throw new AstryxError(+ `"${source.module}" exports no icon with the id of an icon in "${set.name}". Pass the module that exports the ${variant} variant under the same names.`,+ undefined,+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }+ const next = {+ ...set.data,+ ...(set.data.generated ? {} : {generated}),+ ...(set.data.themeMap ? {} : {themeMap: THEME_MAP_NAME}),+ icons,+ };+ /** @type {string[]} */+ const files = [];+ const written = writeGeneratedIcons(packageDir, generated, next, toWrite);+ files.push(...written.files);+ const dataChanged = JSON.stringify(next) !== JSON.stringify(set.data);+ if (dataChanged) {+ try {+ writeIconSetData(set, next);+ } catch (error) {+ written.undo();+ throw error;+ }+ files.push(+ path.relative(packageDir, set.dataPath).split(path.sep).join('/'),+ );+ }+ return {+ type: /** @type {const} */ ('icon.addVariants'),+ data: {+ set: set.name,+ package: set.package,+ variant,+ from: source.module,+ added: added.length,+ already: already.length,+ missing,+ files,+ changed: dataChanged || written.changed,+ },+ };+}diff --git a/packages/cli/api/icon/all-or-nothing.test.mjs b/packages/cli/api/icon/all-or-nothing.test.mjsnew file mode 100644index 0000000000..040e10a357--- /dev/null+++ b/packages/cli/api/icon/all-or-nothing.test.mjs@@ -0,0 +1,283 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Every icon authoring write is all or nothing (AST-084 FR13): for each+ * command, a failure injected at each of its file writes in turn leaves+ * every file in the package byte-identical, and the command fails with+ * `ERR_WRITE_FAILED`, never an unknown error.+ */++import * as os from 'node:os';+import * as path from 'node:path';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';++// Counts the command's file writes, and fails the one numbered `failAt`.+const fault = vi.hoisted(() => ({+ root: /** @type {string | null} */ (null),+ count: 0,+ failAt: 0,+}));++vi.mock('node:fs', async importOriginal => {+ const actual = /** @type {typeof import('node:fs')} */ (+ await importOriginal()+ );+ /**+ * @param {unknown} target a path, or a file descriptor+ */+ const hit = target => {+ if (fault.root == null) return;+ if (+ typeof target === 'string' &&+ !path.resolve(target).startsWith(fault.root)+ ) {+ return;+ }+ fault.count += 1;+ if (fault.count === fault.failAt) {+ fault.root = null;+ throw Object.assign(new Error('EIO: i/o error (injected)'), {+ code: 'EIO',+ });+ }+ };+ /** @type {any} */+ const mocked = {+ ...actual,+ /** @type {typeof actual.writeFileSync} */+ writeFileSync: (file, ...rest) => {+ hit(file);+ return actual.writeFileSync(file, ...rest);+ },+ /** @type {typeof actual.renameSync} */+ renameSync: (from, to) => {+ hit(to);+ return actual.renameSync(from, to);+ },+ /** @type {typeof actual.copyFileSync} */+ copyFileSync: (from, to, mode) => {+ hit(to);+ return actual.copyFileSync(from, to, mode);+ },+ };+ return {...mocked, default: mocked};+});++const fs = await import('node:fs');+const {iconNewSet} = await import('./new-set/new-set.mjs');+const {iconNewDefinition} = await import('./new-definition/new-definition.mjs');+const {iconAdd} = await import('./add/add.mjs');+const {iconMap} = await import('./map/map.mjs');++/** @type {string} */+let tmp;+beforeEach(() => {+ tmp = fs.realpathSync(+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-icon-atomic-')),+ );+ fault.root = null;+});+afterEach(() => {+ fault.root = null;+ fs.rmSync(tmp, {recursive: true, force: true});+});++/**+ * An icon-set package `@acme/icons` with an installed library of two icons+ * (and a solid variant module), and a local artwork file.+ * @returns {string}+ */+function makePackage() {+ const dir = fs.mkdtempSync(path.join(tmp, 'pkg-'));+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ `${JSON.stringify(+ {+ name: '@acme/icons',+ version: '1.0.0',+ license: 'MIT',+ type: 'module',+ exports: {'.': './index.js'},+ files: ['index.js'],+ dependencies: {'@acme/glyph-library': '^2.0.0'},+ },+ null,+ 2,+ )}\n`,+ );+ fs.writeFileSync(path.join(dir, 'index.js'), 'export {};\n');+ const lib = path.join(dir, 'node_modules', '@acme', 'glyph-library');+ fs.mkdirSync(lib, {recursive: true});+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ name: '@acme/glyph-library',+ version: '2.0.0',+ license: 'ISC',+ type: 'module',+ exports: {'.': './index.js', './solid': './solid.js'},+ }),+ );+ fs.writeFileSync(path.join(lib, 'LICENSE'), 'MIT License\n');+ fs.writeFileSync(+ path.join(lib, 'index.js'),+ 'export const Bin = props => null;\nexport const Close = props => null;\n',+ );+ fs.writeFileSync(+ path.join(lib, 'solid.js'),+ 'export const Bin = props => null;\nexport const Close = props => null;\n',+ );+ fs.mkdirSync(path.join(dir, 'art'));+ fs.writeFileSync(+ path.join(dir, 'art', 'spark.js'),+ 'export const Spark = props => null;\n',+ );+ return dir;+}++/**+ * Every file and folder under `dir` (the installed library aside), with its+ * bytes.+ * @param {string} dir+ * @returns {Record<string, string>}+ */+function snapshot(dir) {+ /** @type {Record<string, string>} */+ const found = {};+ /** @param {string} at */+ const walk = at => {+ for (const entry of fs.readdirSync(at, {withFileTypes: true})) {+ const full = path.join(at, entry.name);+ const rel = path.relative(dir, full);+ if (entry.name === 'node_modules') continue;+ if (entry.isDirectory()) {+ found[`${rel}/`] = '';+ walk(full);+ } else {+ found[rel] = fs.readFileSync(full).toString('base64');+ }+ }+ };+ walk(dir);+ return found;+}++const FROM = '@acme/glyph-library';++/**+ * Each command, with what the package holds before it runs.+ * @type {Array<[string, (dir: string) => Promise<unknown>, (dir: string) => Promise<unknown>]>}+ */+const COMMANDS = [+ [+ 'new-set --from',+ async () => {},+ dir => iconNewSet('glyphs', {cwd: dir, from: FROM}),+ ],+ [+ 'new-set refresh with --display-name and --description',+ dir => iconNewSet('glyphs', {cwd: dir, from: FROM}),+ dir =>+ iconNewSet('glyphs', {+ cwd: dir,+ from: FROM,+ displayName: 'Acme Glyphs',+ description: 'Acme glyphs.',+ variants: 'outline,solid',+ }),+ ],+ [+ 'a refresh that first records the source (notices and license)',+ dir => iconNewSet('glyphs', {cwd: dir}),+ dir => iconNewSet('glyphs', {cwd: dir, from: FROM}),+ ],+ [+ 'add --new-definition',+ dir => iconNewSet('glyphs', {cwd: dir}),+ dir =>+ iconAdd('Bin', {+ cwd: dir,+ from: FROM,+ newDefinition: 'binIt',+ description: 'Put something in the bin.',+ words: ['bin'],+ }),+ ],+ [+ 'add --from ./file',+ dir => iconNewSet('glyphs', {cwd: dir}),+ dir =>+ iconAdd('Spark', {cwd: dir, from: './art/spark.js', definition: 'close'}),+ ],+ [+ 'add --variant --all',+ dir =>+ iconNewSet('glyphs', {cwd: dir, from: FROM, variants: 'outline,solid'}),+ dir =>+ iconAdd(undefined, {+ cwd: dir,+ from: `${FROM}/solid`,+ variant: 'solid',+ all: true,+ }),+ ],+ [+ 'map',+ dir => iconNewSet('glyphs', {cwd: dir, from: FROM}),+ dir => iconMap('delete', 'bin', {cwd: dir}),+ ],+ [+ 'map --pairs',+ dir => iconNewSet('glyphs', {cwd: dir, from: FROM}),+ dir =>+ iconMap(undefined, undefined, {+ cwd: dir,+ pairs: 'delete=bin,check=close',+ }),+ ],+ [+ 'new-definition --icon',+ dir => iconNewSet('glyphs', {cwd: dir, from: FROM}),+ dir =>+ iconNewDefinition('binIt', {+ cwd: dir,+ description: 'Put something in the bin.',+ words: ['bin'],+ icon: 'bin',+ }),+ ],+];++describe('every icon authoring write is all or nothing', () => {+ it.each(COMMANDS)(+ '%s: a failure at any write leaves every file as it was',+ async (_, prepare, run) => {+ // A clean run counts the command's writes.+ const counted = makePackage();+ await prepare(counted);+ fault.count = 0;+ fault.failAt = 0;+ fault.root = counted;+ await run(counted);+ fault.root = null;+ const writes = fault.count;+ expect(writes).toBeGreaterThan(0);++ for (let at = 1; at <= writes; at++) {+ const dir = makePackage();+ await prepare(dir);+ const before = snapshot(dir);+ fault.count = 0;+ fault.failAt = at;+ fault.root = dir;+ await expect(+ run(dir),+ `write ${at} of ${writes}`,+ ).rejects.toMatchObject({code: 'ERR_WRITE_FAILED'});+ fault.root = null;+ expect(snapshot(dir), `write ${at} of ${writes}`).toEqual(before);+ }+ },+ 60_000,+ );+});diff --git a/packages/cli/api/icon/detail/detail.mjs b/packages/cli/api/icon/detail/detail.mjsindex dc470e4c2c..f715440933 100644--- a/packages/cli/api/icon/detail/detail.mjs+++ b/packages/cli/api/icon/detail/detail.mjs@@ -18,7 +18,7 @@ import {importLine,rankIcons,setsNamed,- withdrawnReason,+ unusableSet,} from '../_records.mjs';/**@@ -33,18 +33,7 @@ export async function iconDetail(reference, {cwd}) {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 === 0) throw unusableSet(sets, withdrawn, selector);if (named.length > 1) {throw new AstryxError(`Icon set name "${selector}" is installed by ${named.map(each => each.package).join(' and ')}`,diff --git a/packages/cli/api/icon/error-codes.test.mjs b/packages/cli/api/icon/error-codes.test.mjsindex 5b6647263b..b74604d0e0 100644--- a/packages/cli/api/icon/error-codes.test.mjs+++ b/packages/cli/api/icon/error-codes.test.mjs@@ -133,8 +133,11 @@ const CASES = {ERR_MISSING_ARGUMENT: () => icon('', {cwd: app()}),ERR_INVALID_ARGUMENT: () => icon('close', {cwd: app(), limit: 0}),ERR_NOT_FOUND: () => icon('glyphs/nope', {cwd: app()}),+ ERR_INVALID_OPTION: () => icon('close', {cwd: app(), list: true}),},iconAdd: {+ ERR_INVALID_OPTION: () =>+ iconAdd('XIcon', {cwd: pkg(), from: './icons/x.js', all: true}),ERR_PROJECT_REQUIRED: () =>iconAdd('XIcon', {cwd: outside(), from: './x.js'}),ERR_INVALID_ARGUMENT: () =>@@ -171,6 +174,8 @@ const CASES = {},iconMap: {ERR_PROJECT_REQUIRED: () => iconMap('close', 'x', {cwd: outside()}),+ ERR_INVALID_OPTION: () =>+ iconMap('close', undefined, {cwd: pkg(), pairs: 'close=x'}),ERR_MISSING_ARGUMENT: () => iconMap('', 'x', {cwd: pkg()}),ERR_INVALID_ARGUMENT: () =>iconMap('close', 'x', {cwd: withSecondSet(pkg())}),@@ -221,6 +226,8 @@ const CASES = {iconNewSet: {ERR_PROJECT_REQUIRED: () => iconNewSet('outline', {cwd: outside()}),ERR_INVALID_ARGUMENT: () => iconNewSet('Outline', {cwd: bare()}),+ ERR_INVALID_OPTION: () =>+ iconNewSet('outline', {cwd: bare(), exclude: 'Meta'}),ERR_FILE_EXISTS: async () => {const dir = bare();await iconNewSet('outline', {cwd: dir});@@ -249,27 +256,27 @@ const CASES = {},iconNewDefinition: {ERR_PROJECT_REQUIRED: () =>- iconNewDefinition('rotate', {cwd: outside(), ...DEFINITION}),+ iconNewDefinition('random', {cwd: outside(), ...DEFINITION}),ERR_INVALID_ARGUMENT: () =>iconNewDefinition('Not-Camel', {cwd: pkg(), ...DEFINITION}),ERR_MISSING_ARGUMENT: () =>- iconNewDefinition('rotate', {cwd: pkg(), words: ['turn']}),+ iconNewDefinition('random', {cwd: pkg(), words: ['turn']}),ERR_FILE_EXISTS: async () => {const dir = pkg();- await iconNewDefinition('rotate', {cwd: dir, ...DEFINITION});- return iconNewDefinition('rotate', {cwd: dir, ...DEFINITION});+ await iconNewDefinition('random', {cwd: dir, ...DEFINITION});+ return iconNewDefinition('random', {cwd: dir, ...DEFINITION});},ERR_NOT_FOUND: () =>- iconNewDefinition('rotate', {cwd: pkg(), ...DEFINITION, icon: 'nope'}),+ iconNewDefinition('random', {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});+ return iconNewDefinition('random', {cwd: dir, ...DEFINITION});},ERR_WRITE_FAILED: () => {const dir = pkg();lock(path.join(dir, 'icon-sets', 'glyphs', 'definitions'));- return iconNewDefinition('rotate', {cwd: dir, ...DEFINITION});+ return iconNewDefinition('random', {cwd: dir, ...DEFINITION});},},};diff --git a/packages/cli/api/icon/icon.doc.mjs b/packages/cli/api/icon/icon.doc.mjsindex 6cbd1a0087..4633e0a557 100644--- a/packages/cli/api/icon/icon.doc.mjs+++ b/packages/cli/api/icon/icon.doc.mjs@@ -44,6 +44,20 @@ export const doc = {description:'Max matches, a positive integer (default 10). `matchCount` counts every match.',},+ {+ name: 'options.allIcons',+ type: 'boolean',+ description:+ 'With options.set and no query: every icon of that set, by id.',+ default: 'false',+ },+ {+ name: 'options.definitions',+ type: 'boolean',+ description:+ 'Every Astryx icon definition: name, whether it is built in, description, and words. Takes no query or other option.',+ default: 'false',+ },{name: 'options.cwd',type: 'string',@@ -61,6 +75,16 @@ export const doc = {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.definitions',+ description:+ 'With definitions: every Astryx icon definition, with whether it is built in, its description, and its words.',+ },+ {+ type: 'icon.setIcons',+ description:+ 'With set and all: every icon of that set by id, with its export, words, and the definitions it draws.',+ },{type: 'icon.list',description:@@ -74,11 +98,15 @@ export const doc = {},{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',+ when: '`limit` is not a positive integer, `allIcons` is given without `set`, or a set name two packages share is not qualified with its package',+ },+ {+ code: 'ERR_INVALID_OPTION',+ when: 'two options are given that the call cannot both honor: `list`, `definitions`, or `allIcons` with any other listing, a query, `set` (not `allIcons`), or `limit`; or a `<set>/<id>` query with `set` or `limit`',},{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',+ when: 'the set named by `<set>/<id>` or `options.set` (with words or `allIcons`) is not installed or is withdrawn (the message says which, and why), or the set has no such icon; suggestions name the closest',},],examples: [diff --git a/packages/cli/api/icon/icon.mjs b/packages/cli/api/icon/icon.mjsindex 1adbad2437..a02aa86b52 100644--- a/packages/cli/api/icon/icon.mjs+++ b/packages/cli/api/icon/icon.mjs@@ -21,6 +21,9 @@ 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';+import {iconSetIcons} from './search/search.mjs';+import {astryxIconDefinitions} from './_adapter.mjs';+import {passed, refuseIgnoredPairs} from './_options.mjs';/** The default `limit` for `icon.search`. */export const DEFAULT_ICON_LIMIT = 10;@@ -36,15 +39,47 @@ const REFERENCE_RE = /^[^\s/][^\s]*\/[a-z0-9]+(?:-[a-z0-9]+)*$/u;* @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>}+ * @returns {Promise<import('./icon.type.mjs').IconSearchResponse | import('./icon.type.mjs').IconDetailResponse | import('./icon.type.mjs').IconListResponse | import('./icon.type.mjs').IconSetIconsResponse | import('./icon.type.mjs').IconDefinitionsResponse>}*/export async function icon(query, options = {}) {const {cwd = process.cwd(),list = false,set,- limit = DEFAULT_ICON_LIMIT,+ limit: givenLimit,+ allIcons = false,+ definitions = false,} = options;+ const given = typeof query === 'string' ? query.trim() : '';+ // Every listing takes nothing the others take, and a query or one icon+ // takes no listing (spec:AST-042 FR5).+ refuseIgnoredPairs(+ {+ 'a query': given !== '',+ '--list': passed(list),+ '--definitions': passed(definitions),+ '--all-icons': passed(allIcons),+ '--set': passed(set),+ '--limit': passed(givenLimit),+ 'a <set>/<id> query': REFERENCE_RE.test(given),+ },+ [+ ['--list', 'a query'],+ ['--list', '--definitions'],+ ['--list', '--all-icons'],+ ['--list', '--set'],+ ['--list', '--limit'],+ ['--definitions', 'a query'],+ ['--definitions', '--all-icons'],+ ['--definitions', '--set'],+ ['--definitions', '--limit'],+ ['--all-icons', 'a query'],+ ['--all-icons', '--limit'],+ ['a <set>/<id> query', '--set'],+ ['a <set>/<id> query', '--limit'],+ ],+ );+ const limit = givenLimit ?? DEFAULT_ICON_LIMIT;if (query != null && typeof query !== 'string') {throw new AstryxError(`Invalid icon query: ${String(query)}`,@@ -53,20 +88,34 @@ export async function icon(query, options = {}) {);}const term = (query ?? '').trim();- if (list) {- if (term) {+ if (list) return iconList({cwd});+ if (definitions) {+ return {+ type: /** @type {const} */ ('icon.definitions'),+ data: {+ definitions: astryxIconDefinitions().definitions.map(({doc}) => ({+ name: doc.name,+ builtIn: doc.builtIn === true,+ description: doc.description,+ words: doc.words,+ })),+ },+ };+ }+ if (allIcons) {+ if (set == null) {throw new AstryxError(- '--list takes no query',+ '--all-icons lists every icon of one set: pass --set',[{- name: 'astryx experimental icon --list',- reason: 'list the installed sets',+ name: 'astryx experimental icon --set <name> --all-icons',+ reason: "list one set's icons",},],ERROR_CODES.ERR_INVALID_ARGUMENT,);}- return iconList({cwd});+ return iconSetIcons({cwd, set});}if (!term) {throw new AstryxError(diff --git a/packages/cli/api/icon/icon.test.mjs b/packages/cli/api/icon/icon.test.mjsindex f4a0a64b27..8894608968 100644--- a/packages/cli/api/icon/icon.test.mjs+++ b/packages/cli/api/icon/icon.test.mjs@@ -11,10 +11,14 @@ 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 {iconMap} from './map/map.mjs';+import {iconAdd} from './add/add.mjs';+import {iconNewDefinition} from './new-definition/new-definition.mjs';import {ICON_NAMES} from '../../authoring/doctypes/icon-set/icon-names.mjs';import {rankIcons, scoreIcon} from './_records.mjs';import {glyphsData,+ writeIconPackage,writeIconSetProject,} from '../../test-utils/icon-set-fixture.mjs';@@ -331,9 +335,18 @@ describe('icon.list', () => {expect(set.coverage.own).toEqual([]);});+ it('refuses --set and --limit with one icon, which they would not change', async () => {+ for (const options of [{set: 'glyphs'}, {limit: 2}]) {+ await expect(+ icon('glyphs/trash', {cwd, ...options}),+ ).rejects.toMatchObject({code: 'ERR_INVALID_OPTION'});+ }+ });+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',+ code: 'ERR_INVALID_OPTION',+ message: '--list and a query cannot be used together',});await expect(icon('', {cwd})).rejects.toMatchObject({code: 'ERR_MISSING_ARGUMENT',@@ -372,3 +385,122 @@ describe('a withdrawn set, named', () => {});});});++describe('every entry point that names a set reports it the same way (FR17)', () => {+ /** @type {string} */+ let app;+ /** @type {string} */+ let authored;+ beforeEach(() => {+ app = writeIconSetProject(path.join(tmp, 'entry-app'), {+ packages: [{}, {name: '@acme/lines', data: '{nope'}],+ });+ // A package being authored with one valid set and one withdrawn one.+ authored = path.join(tmp, 'entry-pkg', 'glyphs');+ writeIconPackage(authored);+ const broken = path.join(authored, 'icon-sets', 'lines');+ fs.mkdirSync(broken, {recursive: true});+ fs.copyFileSync(+ path.join(authored, 'icon-sets', 'glyphs', 'glyphs.doc.mjs'),+ path.join(broken, 'lines.doc.mjs'),+ );+ fs.writeFileSync(+ path.join(broken, 'lines.doc.mjs'),+ fs+ .readFileSync(path.join(broken, 'lines.doc.mjs'), 'utf8')+ .replace('"name": "glyphs"', '"name": "lines"'),+ );+ fs.writeFileSync(path.join(broken, 'lines.icons.json'), '{nope');+ });++ /** @type {Array<[string, 'installed' | 'authored', (cwd: string, set: string) => Promise<unknown>]>} */+ const ENTRY_POINTS = [+ [+ 'a query with --set',+ 'installed',+ (dir, set) => icon('close', {cwd: dir, set}),+ ],+ [+ '--set with --all-icons',+ 'installed',+ (dir, set) => icon(undefined, {cwd: dir, set, allIcons: true}),+ ],+ ['<set>/<id>', 'installed', (dir, set) => icon(`${set}/x`, {cwd: dir})],+ ['use', 'installed', (dir, set) => iconUse(set, {cwd: dir})],+ [+ 'map --set',+ 'authored',+ (dir, set) => iconMap('close', 'x', {cwd: dir, set}),+ ],+ [+ 'add --set',+ 'authored',+ (dir, set) =>+ iconAdd('XIcon', {+ cwd: dir,+ set,+ from: './icons/x.js',+ definition: 'close',+ }),+ ],+ [+ 'new-definition --set',+ 'authored',+ (dir, set) =>+ iconNewDefinition('binIt', {+ cwd: dir,+ set,+ description: 'Put something in the bin.',+ words: ['bin'],+ }),+ ],+ ];++ it.each(ENTRY_POINTS)('%s: a missing set', async (_label, kind, run) => {+ await expect(+ run(kind === 'installed' ? app : authored, 'nope'),+ ).rejects.toMatchObject({+ code: 'ERR_NOT_FOUND',+ message:+ kind === 'installed'+ ? 'No installed icon set named "nope"'+ : 'No icon set named "nope" in this package',+ });+ });++ it.each(ENTRY_POINTS)('%s: a withdrawn set', async (_label, kind, run) => {+ await expect(+ run(kind === 'installed' ? app : authored, 'lines'),+ ).rejects.toMatchObject({+ code: 'ERR_NOT_FOUND',+ message: expect.stringMatching(+ kind === 'installed'+ ? /^Icon set "lines" is installed but withdrawn: .*not valid JSON/u+ : /^Icon set "lines" is in this package but withdrawn: .*not valid JSON/u,+ ),+ });+ });+});++describe('partial matches answer only when nothing better does (FR6)', () => {+ /** @param {string} query */+ const ids = async query => {+ const result = await icon(query, {cwd, set: 'glyphs'});+ if (result.type !== 'icon.search') throw new Error(result.type);+ return result.data.matches.map(match => [match.id, match.score]);+ };++ it('leaves out a partial match when a word starts with the query', async () => {+ // `se` starts `search`, and is only inside `house` (home).+ const found = await ids('se');+ expect(found.map(([id]) => id)).toContain('search');+ expect(found.map(([id]) => id)).not.toContain('home');+ expect(found.every(([, score]) => Number(score) >= 60)).toBe(true);+ });++ it('answers with partial matches when nothing scores 60 or more', async () => {+ // `ouse` starts no word; it is inside `house`.+ const found = await ids('ouse');+ expect(found).toEqual([['home', 40]]);+ });+});diff --git a/packages/cli/api/icon/icon.type.mjs b/packages/cli/api/icon/icon.type.mjsindex e64080312d..4b2151d538 100644--- a/packages/cli/api/icon/icon.type.mjs+++ b/packages/cli/api/icon/icon.type.mjs@@ -142,6 +142,21 @@* @property {string} [cwd]* @property {string} [set] - The set to edit, when the package ships several.* @property {boolean} [remove] - Remove the definition's entry instead.+ * @property {string | string[]} [pairs] - Many entries at once, as `<definition>=<icon>` pairs separated by commas or spaces; then no definition or icon is passed. All are checked before any is written.+ */++/**+ * `astryx --json experimental icon map --pairs <definition>=<icon>,...`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconMapManyResponse+ * @property {'icon.mapMany'} type+ * @property {object} data+ * @property {string} data.set+ * @property {string} data.package+ * @property {string} data.file - The data file, relative to the package.+ * @property {Array<{definition: string, icon: string, previous: string | null, changed: boolean}>} data.entries - Each pair, in order, and what 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.*//**@@ -154,7 +169,7 @@* @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.icon - The id of the icon now mapped (the icon may be named by any name `map` accepts); 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.@@ -174,6 +189,24 @@* @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.+ * @property {boolean} [all] - With `variant` and `from`, and no export name: add that variant for every icon whose id an export of `from` has.+ */++/**+ * `astryx --json experimental icon add --variant <name> --from <module> --all`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconAddVariantsResponse+ * @property {'icon.addVariants'} type+ * @property {object} data+ * @property {string} data.set+ * @property {string} data.package+ * @property {string} data.variant+ * @property {string} data.from - The module the variant exports are read from.+ * @property {number} data.added - Icons that gained the variant.+ * @property {number} data.already - Icons that already had it.+ * @property {string[]} data.missing - Ids of icons `from` has no export for; they keep no such variant.+ * @property {string[]} data.files - Files written, relative to the package.+ * @property {boolean} data.changed*//**@@ -190,7 +223,7 @@* @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.+ * @property {string} [data.note] - What the package still needs, as text to copy: the entry line that exports the icon from the set's module, and the package.json `files` that publishes a `./` source.*//**@@ -226,6 +259,29 @@* @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).+ * @property {boolean} [allIcons] - With `set` and no query: every icon of that set.+ * @property {boolean} [definitions] - Every Astryx icon definition, and nothing else.+ */++/**+ * `astryx --json experimental icon --definitions`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconDefinitionsResponse+ * @property {'icon.definitions'} type+ * @property {object} data+ * @property {Array<{name: string, builtIn: boolean, description: string, words: string[]}>} data.definitions - Every Astryx icon definition, by name; `builtIn` ones every set maps.+ */++/**+ * `astryx --json experimental icon --set <name> --all-icons`.+ * @experimental May change or be removed in a patch release.+ * @typedef {object} IconSetIconsResponse+ * @property {'icon.setIcons'} type+ * @property {object} data+ * @property {string} data.set+ * @property {string} data.package+ * @property {number} data.iconCount+ * @property {Array<{id: string, export: string, words: string[], definitions: string[]}>} data.icons - Every icon, by id, with the definitions `map` names it for.*//**@@ -236,6 +292,10 @@* @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.+ * @property {string[] | string} [variants] - The variants the set supplies, such as `outline,solid`; a string is split on commas.+ * @property {string} [defaultVariant] - With `variants`: the variant each icon's own export draws; the first variant when absent.+ * @property {string} [displayName] - The descriptor's display name; the set name in title case when absent.+ * @property {string} [description] - The descriptor's one-line description; `<Display name> icons.` when absent.*//**@@ -263,7 +323,11 @@* @property {boolean} dryRun* @property {string} [from]* @property {number} [icons] - With `from`: how many icons it wrote.- * @property {string[]} [notes] - What the author does next.+ * @property {boolean} [refreshed] - With `from` on an existing set: the set was refreshed, not created.+ * @property {Array<{from: string, to: string}>} [renamed] - On a refresh: the icons whose id this release's id rule changes, matched by the export the library still has; each keeps its `map` entries, variants, and words.+ * @property {Array<{definition: string, icon: string}>} [mapped] - With `from`: the `map` entries an icon with the definition's exact name gives (on a refresh, every such entry, kept or new); check each.+ * @property {Array<{definition: string, icon: string, word: string}>} [suggestions] - With `from`: for each unmapped Astryx definition, up to three icons it might map to, best first: the definition's name in another spelling or as another name of an icon, ids that start with it, an id or another name that is one of its words, then two-word ids that are a one-word word sized, shaped, or numbered (`grid-2x2`); never a negated form, the opposite direction, or an icon already mapped. `word` is the name or word that matched. Never written.+ * @property {string[]} [notes] - What the author does next, including each change the package needs that the CLI never makes itself (its entry, peers, scripts), as text to copy.*//**diff --git a/packages/cli/api/icon/iconAdd.doc.mjs b/packages/cli/api/icon/iconAdd.doc.mjsindex ee3e273cd0..daa3f1e210 100644--- a/packages/cli/api/icon/iconAdd.doc.mjs+++ b/packages/cli/api/icon/iconAdd.doc.mjs@@ -13,10 +13,10 @@ export const doc = {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.",+ "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 ./ path to a file inside this package), 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. With `variant`, `from`, and `all` and no export name, it adds that variant for every icon of the set whose id an export of `from` has, in one write. 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>',+ 'iconAdd(exportName: string | undefined, options: IconAddOptions): Promise<IconAddResponse | IconDefinitionMatchesResponse | IconAddVariantsResponse>',keywords: ['icon','icon set',@@ -28,10 +28,10 @@ export const doc = {params: [{name: 'exportName',- type: 'string',+ type: 'string | undefined',description:- 'The export the set exposes the icon as, such as `Bin`; the set exports it as `<Name>Icon`.',- required: true,+ 'The export the set exposes the icon as, such as `Bin`; the set exports it as `<Name>Icon`. Omitted with `options.all`.',+ required: false,},{name: 'options.from',@@ -82,6 +82,13 @@ export const doc = {type: 'string',description: "The icon's id, instead of the one its name gives.",},+ {+ name: 'options.all',+ type: 'boolean',+ description:+ 'With `variant` and `from`, and no export name: add that variant for every icon of the set whose id an export of `from` has (`TrashIcon` in a solid module becomes the solid variant of `trash`).',+ default: 'false',+ },{name: 'options.cwd',type: 'string',@@ -94,6 +101,11 @@ export const doc = {description:'The icon registered, the definition mapped, and the files written.',},+ {+ type: 'icon.addVariants',+ description:+ 'With all: how many icons gained the variant, how many had it, the ids the module has no export for, and the files written.',+ },{type: 'icon.definitionMatches',description:@@ -103,13 +115,17 @@ export const doc = {throws: [{code: 'ERR_NOT_FOUND',- when: 'the module does not export the name, or the definition is unknown',+ when: 'the module does not export the name, the definition is unknown, or `set` names no set in the package or one that is withdrawn (with why)',},{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_INVALID_OPTION',+ when: 'an option is given that the call would ignore: `all` with an export name, `definition`, `newDefinition`, `description`, `words`, `useDefault`, or `id`; `definition` with `newDefinition`; or `description` or `words` without `newDefinition`',+ },{code: 'ERR_PROJECT_REQUIRED',when: 'the folder is outside any project and has no package.json at or above it',diff --git a/packages/cli/api/icon/iconMap.doc.mjs b/packages/cli/api/icon/iconMap.doc.mjsindex 95d86e4fe8..fe1e089458 100644--- a/packages/cli/api/icon/iconMap.doc.mjs+++ b/packages/cli/api/icon/iconMap.doc.mjs@@ -13,22 +13,23 @@ export const doc = {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.",+ "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, named by its name or kebab id. The icon must be in the set, named by its id, its export name in any case, or another name its library exports it as (`trash-2` or `Trash2`), never by one word of its id; the entry records its id. 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>',+ 'iconMap(definition: string | undefined, icon?: string, options?: IconMapOptions): Promise<IconMapResponse | IconMapManyResponse>',keywords: ['icon', 'icon set', 'map', 'icon definition', 'register'],params: [{name: 'definition',- type: 'string',- description: 'The icon definition.',- required: true,+ type: 'string | undefined',+ description: 'The icon definition. Omit with `options.pairs`.',+ required: false,},{name: 'icon',type: 'string',- description: 'An icon id in the set. Omit with `remove`.',+ description:+ 'An icon in the set, named by its id, its export name in any case (`TrashIcon`, `trashicon`), or another name its library exports it as, as an id or as the library spells it (`trash-2`, `Trash2`); never one word of its id. Omit with `remove`.',},{name: 'options.cwd',@@ -46,8 +47,19 @@ export const doc = {description: "Remove the definition's entry.",default: 'false',},+ {+ name: 'options.pairs',+ type: 'string | string[]',+ description:+ 'Many entries at once: `<definition>=<icon>` pairs separated by commas or spaces, with no definition or icon argument; each icon is named as the icon argument is. Every pair is checked before any is written.',+ },],returns: [+ {+ type: 'icon.mapMany',+ description:+ 'With pairs: the set, the data file, each entry with the icon it replaced, and whether the file changed.',+ },{type: 'icon.map',description:@@ -57,19 +69,23 @@ export const doc = {throws: [{code: 'ERR_NOT_FOUND',- when: 'the definition is unknown, or the set has no such icon',+ when: 'the definition is unknown, the set has no such icon, or `set` names no set in the package or one that is withdrawn (with why)',},{code: 'ERR_INVALID_ARGUMENT',when: 'the package ships several sets and none is named',},+ {+ code: 'ERR_INVALID_OPTION',+ when: '`pairs` is given with a definition, an icon, or `remove`, or `remove` with an icon',+ },{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`',+ when: 'the definition is missing, or the icon without `remove`',},{code: 'ERR_PATH_TRAVERSAL',diff --git a/packages/cli/api/icon/iconNewDefinition.doc.mjs b/packages/cli/api/icon/iconNewDefinition.doc.mjsindex 16d0f9c9f1..0f9ed625ef 100644--- a/packages/cli/api/icon/iconNewDefinition.doc.mjs+++ b/packages/cli/api/icon/iconNewDefinition.doc.mjs@@ -75,7 +75,7 @@ export const doc = {{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',+ when: 'the package ships no icon set, `set` names no set in it or one that is withdrawn (with why), or the set has no such icon',},{code: 'ERR_PROJECT_REQUIRED',@@ -93,7 +93,7 @@ export const doc = {examples: [{label: 'Add and map a definition',- code: "await iconNewDefinition('rotate', {description: 'Rotate an image or shape.', words: ['turn', 'spin'], icon: 'rotate-cw'});",+ code: "await iconNewDefinition('random', {description: 'Pick something at random.', words: ['dice', 'shuffle', 'chance'], icon: 'dice-5'});",},],command: 'experimental icon new-definition',diff --git a/packages/cli/api/icon/iconNewSet.doc.mjs b/packages/cli/api/icon/iconNewSet.doc.mjsindex 1032db8e53..aad74745a0 100644--- a/packages/cli/api/icon/iconNewSet.doc.mjs+++ b/packages/cli/api/icon/iconNewSet.doc.mjs@@ -10,7 +10,7 @@ export const doc = {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.",+ "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, records the installed library and version as the data file's source, copies the library's license notices into the set, uses the library's license, maps each Astryx definition whose name is an icon id, and returns up to three likely icons for each other definition as suggestions (by its name, its words, and the other names the library gives an icon; never a part of a word, a negated form, or the opposite direction), never written. 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. It never writes the package's entry, exports, main, types, files list, peers, or scripts: its notes name each change the package needs as text to copy. 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>',@@ -46,6 +46,30 @@ export const doc = {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.',},+ {+ name: 'options.variants',+ type: 'string[] | string',+ description:+ "The variants the set supplies, lower-kebab names such as outline and solid; a string is split on commas. Written to the data file's variants.",+ },+ {+ name: 'options.defaultVariant',+ type: 'string',+ description:+ "With variants: the variant each icon's own export draws, written to the data file's default; the first variant when absent.",+ },+ {+ name: 'options.displayName',+ type: 'string',+ description:+ "The descriptor's display name; the set name in title case when absent.",+ },+ {+ name: 'options.description',+ type: 'string',+ description:+ "The descriptor's one-line description; '<Display name> icons.' when absent.",+ },],returns: [{@@ -57,7 +81,11 @@ export const doc = {throws: [{code: 'ERR_INVALID_ARGUMENT',- when: 'the name is not lowercase kebab-case, or package.json has no name',+ when: 'the name is not lowercase kebab-case, package.json has no name, or a variant name or the default variant is invalid',+ },+ {+ code: 'ERR_INVALID_OPTION',+ when: '`exclude` is given without `from`, or `defaultVariant` without `variants`',},{code: 'ERR_FILE_EXISTS',diff --git a/packages/cli/api/icon/iconUse.doc.mjs b/packages/cli/api/icon/iconUse.doc.mjsindex ec02695048..3f7d2dfb24 100644--- a/packages/cli/api/icon/iconUse.doc.mjs+++ b/packages/cli/api/icon/iconUse.doc.mjs@@ -38,7 +38,10 @@ export const doc = {},],throws: [- {code: 'ERR_NOT_FOUND', when: 'no installed set has the name'},+ {+ code: 'ERR_NOT_FOUND',+ when: 'no installed set has the name, or the set it names is withdrawn (the message says which, and why)',+ },{code: 'ERR_INVALID_ARGUMENT',when: 'two installed packages ship a set with the name',diff --git a/packages/cli/api/icon/map/map.mjs b/packages/cli/api/icon/map/map.mjsindex 3054ed1d23..bc02a75376 100644--- a/packages/cli/api/icon/map/map.mjs+++ b/packages/cli/api/icon/map/map.mjs@@ -19,21 +19,44 @@ import {refuseOutsideProject,writeGeneratedIcons,writeIconSetData,+ definitionNameOf,+ iconIdIn,+ iconsWithWord,} from '../_adapter.mjs';+import {passed, refuseIgnoredPairs} from '../_options.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 {string | undefined} definition omitted with `pairs`+ * @param {string | undefined} icon an icon in the set: its id, its export name in any case, or another name its library exports it as; omit with `remove`* @param {import('../icon.type.mjs').IconMapOptions} [options]- * @returns {Promise<import('../icon.type.mjs').IconMapResponse>}+ * @returns {Promise<import('../icon.type.mjs').IconMapResponse | import('../icon.type.mjs').IconMapManyResponse>}*/export async function iconMap(definition, icon, options = {}) {- const {cwd = process.cwd(), set: selector, remove = false} = options;+ const {cwd = process.cwd(), set: selector, remove = false, pairs} = options;refuseOutsideProject(cwd, 'experimental icon map', 'the icon-set package');+ // `--pairs` names every entry itself, and `--remove` names no icon+ // (spec:AST-042 FR5).+ refuseIgnoredPairs(+ {+ 'a definition': passed(definition),+ 'an icon': passed(icon),+ '--remove': passed(remove),+ '--pairs': passed(pairs),+ },+ [+ ['--pairs', 'a definition'],+ ['--pairs', 'an icon'],+ ['--pairs', '--remove'],+ ['--remove', 'an icon'],+ ],+ );+ if (pairs != null) {+ return authoring(() => mapMany({cwd, selector, pairs}));+ }return authoring(async () => {if (typeof definition !== 'string' || definition.trim() === '') {throw new AstryxError(@@ -55,6 +78,10 @@ export async function iconMap(definition, icon, options = {}) {);}const {packageDir, set} = await findLocalIconSet(cwd, selector);+ // The docs' kebab id (`eye-slash`) names the same definition, and a+ // library's other name for an icon (`trash-2`) names the same icon.+ definition = definitionNameOf(definition, mappableDefinitions(set));+ if (!remove) icon = iconIdIn(set, /** @type {string} */ (icon)) ?? icon;const map = {...(set.data.map ?? {})};const previous = map[definition] ?? null;if (remove) {@@ -78,11 +105,8 @@ export async function iconMap(definition, icon, options = {}) {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',- })),+ `Icon set "${set.name}" has no icon "${icon}". Name an icon by its id, its export name, or another name its library exports it as; a word it carries is not its name.`,+ refusalSuggestions(set, /** @type {string} */ (icon), ids),ERROR_CODES.ERR_NOT_FOUND,);}@@ -120,3 +144,104 @@ export async function iconMap(definition, icon, options = {}) {};});}++/**+ * `--pairs`: write many `map` entries in one checked write, all or none.+ * @param {{cwd: string, selector: string | undefined, pairs: string | string[]}} options+ * @returns {Promise<import('../icon.type.mjs').IconMapManyResponse>}+ */+async function mapMany({cwd, selector, pairs}) {+ const items = (Array.isArray(pairs) ? pairs : [pairs])+ .flatMap(each => String(each).split(/[\s,]+/u))+ .filter(Boolean);+ if (items.length === 0) {+ throw new AstryxError(+ 'Pass --pairs with <definition>=<icon> entries, such as close=x-mark,search=magnifying-glass.',+ undefined,+ ERROR_CODES.ERR_MISSING_ARGUMENT,+ );+ }+ const {packageDir, set} = await findLocalIconSet(cwd, selector);+ const known = mappableDefinitions(set);+ const ids = set.data.icons.map(each => each.id);+ const map = {...(set.data.map ?? {})};+ /** @type {Array<{definition: string, icon: string, previous: string | null, changed: boolean}>} */+ const entries = [];+ for (const item of items) {+ const match = /^([^=]+)=([^=]+)$/u.exec(item);+ if (!match) {+ throw new AstryxError(+ `"${item}" is not a <definition>=<icon> pair.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ const name = definitionNameOf(match[1], known);+ const id = iconIdIn(set, match[2]) ?? match[2];+ if (!known.has(name)) {+ throw new AstryxError(+ `"${name}" is not an icon definition. Nothing was written.`,+ closestNames(name, [...known]).map(each => ({+ name: each,+ reason: 'a known icon definition',+ })),+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }+ if (!ids.includes(id)) {+ throw new AstryxError(+ `Icon set "${set.name}" has no icon "${id}" (for ${name}). Name an icon by its id, its export name, or another name its library exports it as; a word it carries is not its name. Nothing was written.`,+ refusalSuggestions(set, id, ids),+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }+ const previous = map[name] ?? null;+ map[name] = id;+ entries.push({+ definition: name,+ icon: id,+ previous,+ changed: previous !== id,+ });+ }+ const changed = entries.some(each => each.changed);+ /** @type {string[]} */+ const files = [];+ if (changed) {+ const next = {...set.data, map};+ 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.mapMany'),+ data: {+ set: set.name,+ package: set.package,+ file: path.relative(packageDir, set.dataPath).split(path.sep).join('/'),+ entries,+ changed,+ ...(files.length > 0 ? {files} : {}),+ },+ };+}++/**+ * The icons a refused name may have meant: those that carry it as a word+ * (`glass` → `magnifying-glass`), then the closest ids.+ * @param {import('../../../foundation/discovery/icon-set-discovery.mjs').DiscoveredIconSet} set+ * @param {string} name+ * @param {string[]} ids+ */+function refusalSuggestions(set, name, ids) {+ return [...new Set([...iconsWithWord(set, name), ...closestNames(name, ids)])]+ .slice(0, 5)+ .map(each => ({name: each, reason: 'an icon in this set'}));+}diff --git a/packages/cli/api/icon/new-definition/new-definition.mjs b/packages/cli/api/icon/new-definition/new-definition.mjsindex aadf08f6a2..b50059a7c2 100644--- a/packages/cli/api/icon/new-definition/new-definition.mjs+++ b/packages/cli/api/icon/new-definition/new-definition.mjs@@ -9,7 +9,11 @@* new-definition` command*/-import {addIconDefinition, refuseOutsideProject} from '../_adapter.mjs';+import {+ addIconDefinition,+ authoring,+ refuseOutsideProject,+} from '../_adapter.mjs';import {refuseOtherOptions} from '../_options.mjs';/**@@ -27,6 +31,6 @@ export async function iconNewDefinition(name, options = {}) {'experimental icon new-definition','the icon-set package',);- const {data} = await addIconDefinition(name, options);+ const {data} = await authoring(() => addIconDefinition(name, options));return {type: 'icon.newDefinition', data};}diff --git a/packages/cli/api/icon/new-set/new-set.mjs b/packages/cli/api/icon/new-set/new-set.mjsindex 63c1890686..4f33039f7d 100644--- a/packages/cli/api/icon/new-set/new-set.mjs+++ b/packages/cli/api/icon/new-set/new-set.mjs@@ -9,7 +9,7 @@* command*/-import {addIconSet, refuseOutsideProject} from '../_adapter.mjs';+import {addIconSet, authoring, refuseOutsideProject} from '../_adapter.mjs';import {refuseOtherOptions} from '../_options.mjs';/**@@ -27,6 +27,6 @@ export async function iconNewSet(name, options = {}) {'experimental icon new-set','the integration package',);- const {data} = await addIconSet(name, options);+ const {data} = await authoring(() => 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.mjsindex 0c16fbc700..f5229ae7d5 100644--- a/packages/cli/api/icon/new-set/new-set.test.mjs+++ b/packages/cli/api/icon/new-set/new-set.test.mjs@@ -6,6 +6,7 @@ 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';+import {cliVersion} from '../../../foundation/release/run-context.mjs';/** @type {string} */let tmpDir;@@ -85,7 +86,7 @@ describe('iconNewSet (experimental icon new-set)', () => {expect(left).toEqual([]);});- it('names the line for the entry file, relative to it, when the entry is not at the package root', async () => {+ it('names the export line for the entry file, relative to it, and leaves the entry as it was', async () => {setup({license: 'MIT'});const pkgFile = path.join(tmpDir, 'package.json');fs.writeFileSync(@@ -99,12 +100,41 @@ describe('iconNewSet (experimental icon new-set)', () => {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([+ // The entry is the author's (architecture:cli-surface INV16).+ expect(read('src/index.js')).toBe('export {};\n');+ expect(+ result.data.notes?.filter(note => note.includes('export * from')),+ ).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.',]);});+ for (const [label, main, text] of [+ ['a built entry under dist', './dist/index.js', 'export {};\n'],+ ['a CommonJS entry', './index.cjs', 'module.exports = {};\n'],+ ]) {+ it(`names no file to edit for ${label}, and leaves it as it was`, async () => {+ setup({license: 'MIT'});+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({+ ...JSON.parse(read('package.json')),+ type: 'module',+ exports: {'.': main},+ }),+ );+ fs.mkdirSync(path.dirname(path.join(tmpDir, main)), {recursive: true});+ fs.writeFileSync(path.join(tmpDir, main), text);+ const result = await iconNewSet('outline', {cwd: tmpDir});+ expect(read(main)).toBe(text);+ expect(+ result.data.notes?.filter(note => note.includes('export * from')),+ ).toEqual([+ `${main.slice(2)} is built or CommonJS, so the CLI names no file to edit: add \`export * from './icon-sets/outline/outline.generated.js';\` (relative to that file) to the source module your build compiles into it, and to its types, then build, so the icons and \`themeIcons\` import from @acme/icons.`,+ ]);+ });+ }+it('adds no export line when the entry already exports the generated module', async () => {setup({license: 'MIT'});fs.writeFileSync(@@ -121,9 +151,12 @@ describe('iconNewSet (experimental icon new-set)', () => {"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.',- ]);+ expect(read('src/index.js')).toBe(+ "export * from '../icon-sets/outline/outline.generated.js';\n",+ );+ expect(+ result.data.notes?.filter(note => note.includes('export * from')),+ ).toEqual([]);});it('writes a typed descriptor and a starter data file, declares the root, and adds it to files', async () => {@@ -149,12 +182,29 @@ describe('iconNewSet (experimental icon new-set)', () => {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\';`.',+ // What the package needs is the author's to change (INV16): each+ // note is the exact change, and the CLI makes none of them.+ '"@acme/icons" has no entry, so its icons cannot be imported by name. Create index.js and index.d.ts, each with `export * from \'./icon-sets/outline/outline.generated.js\';`, and add to package.json: `"main": "./index.js", "types": "./index.d.ts", "exports": {".": {"types": "./index.d.ts", "default": "./index.js"}}`. Add "index.js" and "index.d.ts" to "files".',+ `Declare the peers your set needs; add to package.json "peerDependencies": \`{"react": ">=18", "@types/react": ">=18", "@astryxdesign/cli": ">=${cliVersion()}"}\` and to "peerDependenciesMeta": \`{"@types/react": {"optional": true}, "@astryxdesign/cli": {"optional": true}}\`.`,+ 'Run `integration check --strict` in your build; add to package.json "scripts": `"typecheck": "astryx integration check --strict"`.',+ 'The set\'s description is a placeholder ("Outline icons."): apps and discover show it. Pass --description when you create a set, or edit icon-sets/outline/outline.doc.mjs.','Run `astryx integration check` to see the icon definitions still to map.',],},});+ // No entry, peer, or script is written: package policy is the author's.+ expect(fs.existsSync(path.join(tmpDir, 'index.js'))).toBe(false);+ expect(fs.existsSync(path.join(tmpDir, 'index.d.ts'))).toBe(false);+ const pkgAfter = JSON.parse(read('package.json'));+ for (const key of [+ 'main',+ 'types',+ 'exports',+ 'peerDependencies',+ 'scripts',+ ]) {+ expect(pkgAfter).not.toHaveProperty(key);+ }// The generated module starts with an empty theme map, and its types.expect(read('icon-sets/outline/outline.generated.js')).toContain('export const themeIcons = {};',@@ -198,14 +248,14 @@ describe('iconNewSet (experimental icon new-set)', () => {]);});- it('creates the manifest on first add and never creates a files field', async () => {+ it('creates the manifest on first add, and never creates a files list', 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();+ expect(JSON.parse(read('package.json'))).not.toHaveProperty('files');// No package license: the descriptor says so instead of guessing one.expect(read('icon-sets/brand-glyphs/brand-glyphs.doc.mjs')).toContain("license: 'UNLICENSED'",diff --git a/packages/cli/api/icon/option-pairs.test.mjs b/packages/cli/api/icon/option-pairs.test.mjsnew file mode 100644index 0000000000..c489b4cc19--- /dev/null+++ b/packages/cli/api/icon/option-pairs.test.mjs@@ -0,0 +1,368 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Every pair of options an icon command declares has a decided result+ * (spec:AST-042 FR5): for each command, the pairs come from its CommandDoc+ * (its options and its optional arguments; a required argument is always+ * given), and each pair is either+ * - refused together with `ERR_INVALID_OPTION` (the `refused` table), or+ * - composed: the call succeeds with both (the `composes` table), or+ * - prevented by another rule: the call fails with another code the+ * function documents (every other pair).+ * A pair that succeeds without being listed as composing fails this test, so+ * a new option, or a change that starts ignoring one, is decided in review.+ */++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 {writeIconSetProject} from '../../test-utils/icon-set-fixture.mjs';+import {icon} from './icon.mjs';+import {iconAdd} from './add/add.mjs';+import {iconMap} from './map/map.mjs';+import {iconNewSet} from './new-set/new-set.mjs';+import {iconNewDefinition} from './new-definition/new-definition.mjs';+import {iconUse} from './use/use.mjs';+import {doc as iconCommand} from '../../clients/cli/commands/experimental-icon.doc.mjs';+import {doc as addCommand} from '../../clients/cli/commands/experimental-icon-add.doc.mjs';+import {doc as mapCommand} from '../../clients/cli/commands/experimental-icon-map.doc.mjs';+import {doc as newSetCommand} from '../../clients/cli/commands/experimental-icon-new-set.doc.mjs';+import {doc as newDefinitionCommand} from '../../clients/cli/commands/experimental-icon-new-definition.doc.mjs';+import {doc as useCommand} from '../../clients/cli/commands/experimental-icon-use.doc.mjs';+import {doc as iconFn} from './icon.doc.mjs';+import {doc as addFn} from './iconAdd.doc.mjs';+import {doc as mapFn} from './iconMap.doc.mjs';+import {doc as newSetFn} from './iconNewSet.doc.mjs';+import {doc as newDefinitionFn} from './iconNewDefinition.doc.mjs';+import {doc as useFn} from './iconUse.doc.mjs';++/** @type {string} */+let tmp;+beforeAll(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-icon-pairs-'));+});+afterAll(() => {+ fs.rmSync(tmp, {recursive: true, force: true});+});++const FROM = '@acme/glyph-library';++/**+ * An icon-set package `@acme/icons` with an installed library, and, unless+ * `bare`, its set `glyphs` made from that library with two variants.+ * @param {{bare?: boolean}} [options]+ * @returns {Promise<string>}+ */+async function makePackage({bare = false} = {}) {+ const dir = fs.mkdtempSync(path.join(tmp, 'pkg-'));+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ `${JSON.stringify({name: '@acme/icons', version: '1.0.0', license: 'MIT', type: 'module'}, null, 2)}\n`,+ );+ const lib = path.join(dir, 'node_modules', '@acme', 'glyph-library');+ fs.mkdirSync(lib, {recursive: true});+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ name: '@acme/glyph-library',+ version: '2.0.0',+ type: 'module',+ exports: {'.': './index.js', './solid': './solid.js'},+ }),+ );+ const icons =+ 'export const Bin = props => null;\nexport const Close = props => null;\n';+ fs.writeFileSync(path.join(lib, 'index.js'), icons);+ fs.writeFileSync(path.join(lib, 'solid.js'), icons);+ if (!bare) {+ await iconNewSet('glyphs', {+ cwd: dir,+ from: FROM,+ variants: 'outline,solid',+ });+ }+ return dir;+}++/**+ * @typedef {object} Case+ * @property {any} command the CommandDoc+ * @property {any} fn the FunctionDoc+ * @property {(...args: any[]) => Promise<unknown>} call+ * @property {() => Promise<string>} cwd a fresh folder for one call+ * @property {Record<string, unknown>} values a value for each API parameter+ * @property {Array<[string, string]>} refused pairs refused together+ * @property {Array<[string, string]>} composes pairs that succeed together+ */++/** @type {Record<string, Case>} */+const CASES = {+ 'experimental icon': {+ command: iconCommand,+ fn: iconFn,+ call: icon,+ cwd: async () =>+ writeIconSetProject(fs.mkdtempSync(path.join(tmp, 'app-'))),+ values: {+ query: 'trash',+ 'options.list': true,+ 'options.set': 'glyphs',+ 'options.limit': 3,+ 'options.definitions': true,+ 'options.allIcons': true,+ },+ refused: [+ ['query', '--list'],+ ['query', '--definitions'],+ ['query', '--all-icons'],+ ['--list', '--set'],+ ['--list', '--limit'],+ ['--list', '--definitions'],+ ['--list', '--all-icons'],+ ['--set', '--definitions'],+ ['--limit', '--definitions'],+ ['--limit', '--all-icons'],+ ['--definitions', '--all-icons'],+ ],+ composes: [+ ['query', '--set'],+ ['query', '--limit'],+ ['--set', '--all-icons'],+ ],+ },+ 'experimental icon add': {+ command: addCommand,+ fn: addFn,+ call: iconAdd,+ cwd: () => makePackage(),+ values: {+ exportName: 'Bin',+ 'options.from': FROM,+ 'options.definition': 'delete',+ 'options.newDefinition': 'binIt',+ 'options.description': 'Put something in the bin.',+ 'options.words': ['bin'],+ 'options.useDefault': true,+ 'options.variant': 'solid',+ 'options.all': true,+ 'options.id': 'bin',+ 'options.set': 'glyphs',+ },+ refused: [+ ['export', '--all'],+ ['--definition', '--new-definition'],+ ['--definition', '--description'],+ ['--definition', '--words'],+ ['--definition', '--all'],+ ['--new-definition', '--all'],+ ['--description', '--all'],+ ['--words', '--all'],+ ['--default', '--all'],+ ['--all', '--id'],+ // A description and words describe only a new definition.+ ['export', '--description'],+ ['export', '--words'],+ ['--from', '--description'],+ ['--from', '--words'],+ ['--description', '--words'],+ ['--description', '--default'],+ ['--description', '--variant'],+ ['--description', '--id'],+ ['--description', '--set'],+ ['--words', '--default'],+ ['--words', '--variant'],+ ['--words', '--id'],+ ['--words', '--set'],+ ],+ composes: [['export', '--from']],+ },+ 'experimental icon map': {+ command: mapCommand,+ fn: mapFn,+ call: iconMap,+ cwd: () => makePackage(),+ values: {+ definition: 'delete',+ icon: 'bin',+ 'options.set': 'glyphs',+ 'options.remove': true,+ 'options.pairs': 'close=close',+ },+ refused: [+ ['definition', '--pairs'],+ ['icon', '--remove'],+ ['icon', '--pairs'],+ ['--remove', '--pairs'],+ ],+ composes: [+ ['definition', 'icon'],+ ['definition', '--remove'],+ ['--set', '--pairs'],+ ],+ },+ 'experimental icon new-set': {+ command: newSetCommand,+ fn: newSetFn,+ call: iconNewSet,+ cwd: () => makePackage({bare: true}),+ values: {+ name: 'glyphs',+ 'options.dryRun': true,+ 'options.from': FROM,+ 'options.exclude': 'Close',+ 'options.variants': 'outline,solid',+ 'options.defaultVariant': 'solid',+ 'options.displayName': 'Glyphs',+ 'options.description': 'Glyph icons.',+ },+ refused: [+ // `--exclude` needs `--from`, `--default-variant` needs `--variants`.+ ['--dry-run', '--exclude'],+ ['--dry-run', '--default-variant'],+ ['--exclude', '--variants'],+ ['--exclude', '--default-variant'],+ ['--exclude', '--display-name'],+ ['--exclude', '--description'],+ ['--from', '--default-variant'],+ ['--default-variant', '--display-name'],+ ['--default-variant', '--description'],+ ],+ composes: [+ ['--dry-run', '--from'],+ ['--dry-run', '--variants'],+ ['--dry-run', '--display-name'],+ ['--dry-run', '--description'],+ ['--from', '--exclude'],+ ['--from', '--variants'],+ ['--from', '--display-name'],+ ['--from', '--description'],+ ['--variants', '--default-variant'],+ ['--variants', '--display-name'],+ ['--variants', '--description'],+ ['--display-name', '--description'],+ ],+ },+ 'experimental icon new-definition': {+ command: newDefinitionCommand,+ fn: newDefinitionFn,+ call: iconNewDefinition,+ cwd: () => makePackage(),+ values: {+ name: 'binIt',+ 'options.dryRun': true,+ 'options.set': 'glyphs',+ 'options.description': 'Put something in the bin.',+ 'options.words': ['bin'],+ 'options.icon': 'bin',+ },+ refused: [],+ composes: [['--description', '--words']],+ },+ 'experimental icon use': {+ command: useCommand,+ fn: useFn,+ call: iconUse,+ cwd: async () =>+ writeIconSetProject(fs.mkdtempSync(path.join(tmp, 'app-'))),+ values: {set: 'glyphs'},+ refused: [],+ composes: [],+ },+};++/**+ * The pair members a command declares: its optional arguments, by name, and+ * its options, by long flag; each with the API parameter it sets.+ * @param {any} command+ * @returns {Array<{label: string, param: string}>}+ */+function members(command) {+ return [+ ...(command.args ?? [])+ .filter((/** @type {any} */ arg) => arg.required !== true)+ .map((/** @type {any} */ arg) => ({label: arg.name, param: arg.param})),+ ...(command.options ?? []).map((/** @type {any} */ option) => ({+ label: option.flag.split(/[\s,]/u)[0],+ param: option.param,+ })),+ ];+}++/** @param {[string, string]} pair */+const key = ([a, b]) => [a, b].sort().join(' + ');++describe.each(Object.entries(CASES))('%s', (_name, spec) => {+ const declared = members(spec.command);+ const labels = declared.map(each => each.label);+ /** @type {Array<[string, string]>} */+ const pairs = [];+ for (let i = 0; i < declared.length; i++) {+ for (let j = i + 1; j < declared.length; j++) {+ pairs.push([declared[i].label, declared[j].label]);+ }+ }+ const refused = new Set(spec.refused.map(key));+ const composes = new Set(spec.composes.map(key));+ const documented = new Set(+ (spec.fn.throws ?? []).map((/** @type {any} */ each) => each.code),+ );++ it('names only pairs the command declares, each in one table', () => {+ for (const pair of [...spec.refused, ...spec.composes]) {+ expect(labels, key(pair)).toEqual(expect.arrayContaining(pair));+ }+ expect([...refused].filter(each => composes.has(each))).toEqual([]);+ for (const {param} of declared) {+ expect(Object.keys(spec.values), param).toContain(param);+ }+ });++ if (pairs.length === 0) return;+ it.each(pairs)('%s with %s', async (a, b) => {+ const given = new Set([a, b]);+ const cwd = await spec.cwd();+ // Required arguments are always given, in order; the rest only when+ // they are one of the pair.+ const args = (spec.command.args ?? []).map((/** @type {any} */ arg) =>+ arg.required === true || given.has(arg.name)+ ? spec.values[arg.param]+ : undefined,+ );+ /** @type {Record<string, unknown>} */+ const options = {cwd};+ for (const {label, param} of declared) {+ if (given.has(label) && param.startsWith('options.')) {+ options[param.slice('options.'.length)] = spec.values[param];+ }+ }+ /** @type {any} */+ let error = null;+ try {+ await spec.call(...args, options);+ } catch (thrown) {+ error = thrown;+ }+ const pair = key([a, b]);+ if (refused.has(pair)) {+ expect(error?.code, `${pair}: ${error?.message}`).toBe(+ 'ERR_INVALID_OPTION',+ );+ } else if (composes.has(pair)) {+ expect(error, `${pair}: ${error?.message}`).toBeNull();+ } else {+ // Prevented by another rule: a documented code, never a silent+ // success and never an unknown error.+ expect(+ error,+ `${pair} succeeded but is not listed as composing`,+ ).not.toBeNull();+ expect(error.code, `${pair}: ${error.message}`).not.toBe(+ 'ERR_INVALID_OPTION',+ );+ expect([...documented], `${pair}: ${error.message}`).toContain(+ error.code,+ );+ }+ });+});diff --git a/packages/cli/api/icon/search/search.mjs b/packages/cli/api/icon/search/search.mjsindex 08963a3885..a45582db75 100644--- a/packages/cli/api/icon/search/search.mjs+++ b/packages/cli/api/icon/search/search.mjs@@ -12,7 +12,54 @@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';+import {rankIcons, setsNamed, unusableSet} from '../_records.mjs';++/** The lowest score of a whole-word or word-start match. */+const WORD_SCORE = 60;++/**+ * Every icon of one set, by id: `--set <name> --all-icons`, so an author can read+ * a whole library's ids, words, and the definitions each icon draws.+ * @param {{cwd: string, set: string}} options+ * @returns {Promise<import('../icon.type.mjs').IconSetIconsResponse>}+ */+export async function iconSetIcons({cwd, set}) {+ const {sets, withdrawn} = await loadIconSets(cwd);+ const named = setsNamed(sets, set);+ if (named.length === 0) throw unusableSet(sets, withdrawn, set);+ if (named.length > 1) {+ throw new AstryxError(+ `"${set}" names ${named.length} sets; name one as <package>/<set>`,+ named.map(each => ({+ name: `${each.package}/${each.name}`,+ reason: 'name the package',+ })),+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ const [only] = named;+ /** @type {Map<string, string[]>} */+ const drawn = new Map();+ for (const [definition, id] of Object.entries(only.data.map ?? {})) {+ drawn.set(id, [...(drawn.get(id) ?? []), definition]);+ }+ return {+ type: 'icon.setIcons',+ data: {+ set: only.name,+ package: only.package,+ iconCount: only.data.icons.length,+ icons: [...only.data.icons]+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))+ .map(icon => ({+ id: icon.id,+ export: icon.export,+ words: icon.words,+ definitions: (drawn.get(icon.id) ?? []).sort(),+ })),+ },+ };+}/*** Rank every installed icon against a query.@@ -25,20 +72,14 @@ export async function iconSearch(query, {cwd, set, limit}) {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,- );- }+ if (searched.length === 0) throw unusableSet(sets, withdrawn, set);}- const matches = rankIcons(searched, query);+ const ranked = rankIcons(searched, query);+ // A partial match (`pin` inside `shopping`) answers only when nothing+ // matches a whole word or a word start.+ const matches = ranked.some(each => each.score >= WORD_SCORE)+ ? ranked.filter(each => each.score >= WORD_SCORE)+ : ranked;return {type: 'icon.search',data: {diff --git a/packages/cli/api/icon/use/use.mjs b/packages/cli/api/icon/use/use.mjsindex d8a9a29f5b..079bd89d8b 100644--- a/packages/cli/api/icon/use/use.mjs+++ b/packages/cli/api/icon/use/use.mjs@@ -18,7 +18,7 @@ import {refuseOutsideProject,setConfigString,} from '../_adapter.mjs';-import {closest, setsNamed, withdrawnReason} from '../_records.mjs';+import {setsNamed, unusableSet} from '../_records.mjs';/*** Make an installed set the project's icon set.@@ -45,18 +45,7 @@ export async function iconUse(selector, {cwd = process.cwd()} = {}) {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 === 0) throw unusableSet(sets, withdrawn, selector);if (named.length > 1) {throw new AstryxError(`Two installed packages ship an icon set named "${selector}"; name it with its package.`,diff --git a/packages/cli/api/integration/add-helpers.mjs b/packages/cli/api/integration/add-helpers.mjsindex 697389aef5..6b52dff112 100644--- a/packages/cli/api/integration/add-helpers.mjs+++ b/packages/cli/api/integration/add-helpers.mjs@@ -483,7 +483,7 @@ export async function loadCurrentManifest(manifestFile, manifestExists) {* @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[]}}}+ * @returns {{type: 'integration.add', data: Omit<import('./integration-authoring.type.mjs').IntegrationAddData, 'kind'> & {kind: K, icons?: number, refreshed?: boolean, renamed?: Array<{from: string, to: string}>, mapped?: Array<{definition: string, icon: string}>, suggestions?: Array<{definition: string, icon: string, word: string}>, notes?: string[]}}}*/export function receipt(kind, name, root, manifestPath, files, dryRun) {return {diff --git a/packages/cli/api/integration/validate-integration.type.mjs b/packages/cli/api/integration/validate-integration.type.mjsindex 64f896f632..cfe1349695 100644--- a/packages/cli/api/integration/validate-integration.type.mjs+++ b/packages/cli/api/integration/validate-integration.type.mjs@@ -126,8 +126,9 @@* 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.+ * unmapped definition (built-in, optional, or the set's own), the best icon+ * `integration check` gives it, by the rule `experimental icon new-set`+ * uses for its suggestions, 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 readerdiff --git a/packages/cli/api/template/template.type.mjs b/packages/cli/api/template/template.type.mjsindex 0508e58fa7..e760845ad9 100644--- a/packages/cli/api/template/template.type.mjs+++ b/packages/cli/api/template/template.type.mjs@@ -96,7 +96,7 @@* @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<{source: {module: string, export: string}, target: {set: string, package: string, id: string, module: string, export: string}, by: 'match' | 'definition', dropped?: string[]}>} 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. `dropped` names the library's sizing props (`size`, `strokeWidth`, `absoluteStrokeWidth`) removed from the icon's elements: an icon set's icons take their size from CSS.* @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/assets/docs/tree/icon-definitions.doc.mjs b/packages/cli/assets/docs/tree/icon-definitions.doc.mjsindex 679df3ba62..aa06b60434 100644--- a/packages/cli/assets/docs/tree/icon-definitions.doc.mjs+++ b/packages/cli/assets/docs/tree/icon-definitions.doc.mjs@@ -18,7 +18,7 @@ export const docs = {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.',+ 'Every icon definition: what an icon stands for, and the shared name icon sets map their icons to.',keywords: ['icon definition','icon definitions',@@ -42,7 +42,7 @@ export const docs = {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.",+ 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, marked [built-in], are the shared names Core renders (the semantic icon names in `astryx docs icons`); every set maps them, and `integration check` fails until it does. The others are optional: map each one your library draws. `map` keys a definition by its camelCase name, shown after the id (`eyeSlash`); `experimental icon map` and `--pairs` take either spelling. 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.mjsindex 2c67a48102..3da6c3469e 100644--- a/packages/cli/assets/docs/tree/icon-set-files.doc.mjs+++ b/packages/cli/assets/docs/tree/icon-set-files.doc.mjs@@ -28,6 +28,6 @@ export const docs = {'IconDefinitionDoc',],description:- 'Experimental. Every field of the files an icon set is made of: the descriptor, the data file, and an icon definition.',+ '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.mjsindex a82377ea9b..c2d37fd08e 100644--- a/packages/cli/assets/docs/tree/icon-sets.doc.mjs+++ b/packages/cli/assets/docs/tree/icon-sets.doc.mjs@@ -24,7 +24,7 @@ export const docs = {'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.',+ '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',@@ -42,7 +42,7 @@ export const docs = {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.',+ 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; one icon may draw several definitions (`file` and `document` can both be your `document` icon). 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',@@ -61,7 +61,11 @@ export const docs = {},{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}.",+ text: "`outline.doc.mjs` is the descriptor: name, display name and description (`--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}.",+ },+ {+ type: 'prose',+ text: "The set's icons import from your package by name, so your package's entry must re-export the generated module. The command writes only the set's own files: your entry, `exports`, `main`, `types`, `files`, peers, and scripts are yours, and the receipt names each change to make as text to copy. For an entry file in the package (and the declaration file package.json names) that is the line `export * from './icon-sets/outline/outline.generated.js';`, relative to it; for a package with no entry, `index.js` and `index.d.ts` with that line and the package.json `main`, `types`, and `exports` that name them; for a built or CommonJS entry, the line to add to the source it is built from. `integration check` names the same change until you make it, and the receipt also names the peers and the `typecheck` script to add. `integration check --strict` type-checks the set's doc files with your package's TypeScript; the receipt says when it is missing (`npm install -D typescript@6`).",},],},@@ -71,7 +75,7 @@ export const docs = {content: [{type: 'prose',- text: 'Pick an icon from the library and ask which definitions fit it. Nothing is written yet:',+ text: 'Pick an icon from the library and ask which definitions fit it. Nothing is written yet. To read every icon a set already has, one line each with its words and the definitions it draws, run `astryx experimental icon --set <set> --all-icons`; `astryx experimental icon <set>/<id>` reads one, or says the id does not exist:',},{type: 'code',@@ -98,11 +102,11 @@ export const docs = {{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",+ code: "astryx experimental icon add Dice5 --from @acme/glyph-library --new-definition random --description 'Pick something at random.' --words dice,shuffle,chance",},{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.',+ text: '`experimental icon map <definition> <icon>` points a definition at an icon the set already has (a definition is named in camelCase, `eyeSlash`, or by the kebab id the definitions list shows, `eye-slash`; an icon by its id, its export name in any case, or another name its library exports it as, such as `trash-2`, never by one word of its id), `experimental icon map --pairs close=x-mark,search=magnifying-glass` writes many entries at once (checked together, all or none; an entry the map already has is replaced, and the receipt shows what it was), and `--remove` drops an entry. `experimental icon new-definition <name> --description ... --words ... --icon <id>` adds your own definition for an icon you already have. `experimental icon --definitions` lists every Astryx definition, built in or not, with its words (`--json` for a script).',},],},@@ -117,11 +121,29 @@ export const docs = {},{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.",+ text: "Every component the library exports becomes an icon (an alias of one component is recorded once), named `<Name>Icon`, with an id from its name (`Squares2X2Icon` is `squares-2x2`: a dimension stays one word). `map` is filled only where a definition's name is an icon's id (`delete` → icon `delete`), and the receipt lists those entries under Mapped by name: a library can draw another meaning under the same name (one library's `delete` is a backspace key), so check each. An icon whose id is only one of a definition's words (`trash` for `delete`) may mean something else in this library, so the receipt lists it under Suggestions, with the `experimental icon map <definition> <icon>` command for each, and writes nothing for it: check the meaning, then run the ones that fit. Run it again after a library release to refresh the icons that library supplies; `map` entries whose icon still exists are kept, and the receipt names any icon the library dropped, any icon `--exclude` left out, and the `map` entries each took with it. Icons you added from your own files or another library are left as they are. An icon you already have is known by the library export it re-exports, so it keeps its export name exactly, its `map` entries, variants, and words, even when a newer CLI spells its id differently or your `--exclude` lets a library prefix come off new ids; the receipt lists each changed id under `renamed`. A refresh with `--dry-run` writes nothing and prints the Mapped by name and Suggestions lists again; `--display-name` and `--description` on a refresh rewrite the descriptor. Variants added with `add --variant … --all` are kept too; run that `add` again to pick up icons the release added. `experimental icon --list` shows how many definitions the set maps.",+ },+ {+ type: 'prose',+ text: "With a package or package subpath, it also records the installed library and version as the data file's `source`, so `integration check` warns when your dependency moves to another version; copies the library's LICENSE (and NOTICE) files into the set directory; and sets the descriptor's `license` to the library's. A set you started without `--from` gets the same the first time a refresh records its source, unless you already changed `license`: a `license` you set is kept (the receipt names the library's), and every later refresh keeps it too. Your package.json `license` is never changed. Edit `license` when the artwork's license differs from the library's package license.",},{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`.',+ text: 'A library with a module per style supplies variants. Declare them when you create the set, then add a variant for every icon in one run:',+ },+ {+ type: 'code',+ lang: 'bash',+ code: `astryx experimental icon new-set heroicons --from @heroicons/react/24/outline --variants outline,solid --default-variant outline --description 'Heroicons, outline and solid.'+astryx experimental icon add --variant solid --from @heroicons/react/24/solid --all`,+ },+ {+ type: 'prose',+ text: "A library that redraws its artwork for small sizes (Heroicons' 20px mini and 16px micro) ships each of those as its own set in its own package (their export names match the 24px ones), not as variants: a variant's size comes from CSS. `--variants` lists the variants; `--default-variant` names the one each icon's own export draws (the first variant when omitted). `--all` adds the variant for every icon whose id an export of `--from` has (`TrashIcon` in the solid module becomes `TrashSolidIcon`, the solid variant of `trash`), and the receipt lists the icons the module has no export for. Running it again changes nothing.",+ },+ {+ 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. Components named `…Provider` or `…Context` are never icons either. Leave out any other export that is not an icon with `--exclude meta,version`: the data file keeps the list in `exclude`, so a refresh leaves them out too. When a library exports one icon under several names (`Trash2` and `Trash`), the icon is recorded once and its other names become words, so `experimental icon trash-2` finds it and `experimental icon map delete trash-2` maps it. `experimental icon add` reads the prefix the same way, and reuses the icon an export already has, so its commands need no `--id`.',},],},@@ -146,7 +168,7 @@ export const docs = {},{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:",+ 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 this line to your package's entry and its types; `experimental icon new-set` names the exact line and file in its receipt (see add an icon set):",},{type: 'code',@@ -155,7 +177,7 @@ export const docs = {},{type: 'prose',- text: 'An optional render test you can copy:',+ text: "An optional render test you can copy. Save it inside your package directory and run it there, since it imports your package by name through its `exports`, and install `react-dom` first (`npm install -D react-dom`). A library may add its own classes beside yours, so it checks the class list. A library that sets `width` and `height` attributes (24, say) still fills its box: CSS sizing, such as the `Icon` component's, overrides SVG size attributes.",},{type: 'code',@@ -167,7 +189,7 @@ 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 (!/class="([^"]* )?x( [^"]*)?"/.test(html)) throw new Error(\`\${name} drops className\`);if (!html.includes('currentColor')) throw new Error(\`\${name} has a fixed color\`);}`,},@@ -191,7 +213,7 @@ for (const [name, Icon] of Object.entries(icons)) {],['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`)',+ '`experimental icon add --variant solid --from @acme/glyph-library/solid --all` for every icon at once, or `experimental icon add Bin --from @acme/glyph-library/solid --id bin --variant solid` for one (the set must declare the variant: `new-set --variants`)',],['One file per icon, default export',@@ -207,7 +229,7 @@ for (const [name, Icon] of Object.entries(icons)) {],['Your own component files',- '`experimental icon add Rocket --from ./src/icons/rocket.js --definition rocket`',+ "`experimental icon add Rocket --from ./src/icons/rocket.js --definition rocket`, and `--id rocket --variant solid` for its other looks. The file exports a component named as written (no library prefix is taken off), with a declaration file beside it (`rocket.d.ts`) or written in TypeScript, since the set's types re-export its own; when package.json lists `files` and none covers it, the receipt names the `files` array that publishes its folder.",],],},@@ -258,7 +280,7 @@ export const brand = defineTheme({name: 'brand', icons: themeIcons});`,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:",+ 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 and the `experimental icon map <definition> <icon id>` command that fixes it, so you or your agent can pick the icon. It names a search of your set (`experimental icon <word> --set <set>`) only when that search finds icons, and suggests one icon: the first of the suggestions `experimental icon new-set` gives for that definition. It never matches part of a word, and never writes a suggestion. Its icon-set codes:",},{type: 'list',@@ -286,7 +308,7 @@ export const brand = defineTheme({name: 'brand', icons: themeIcons});`,},{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.',+ 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` → `npm install -D typescript@6` when the receipt asks → `integration check` → `experimental icon add` (or `experimental icon map`) for each definition it lists → `integration check` passes.',},],},@@ -299,8 +321,12 @@ export const brand = defineTheme({name: 'brand', icons: themeIcons});`,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.',+ "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, and the format may change in a patch release. A CLI reads a set only when it knows every key the set's data file uses: a key it does not know withdraws the set, naming the key. `exclude` is read only by a CLI whose data-file reference lists it ({@link schema:icon-set-data}); a set without `exclude` is read by every CLI that has `astryx experimental icon`. 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}).",+ "Every built-in definition needs an icon, because Core renders it. When your library has no icon with that exact meaning, map the closest one, or add your own artwork as a component file in your package (`experimental icon add <Name> --from ./src/icons/<name>.js --definition <definition>`; a ./ path is named as written). Artwork you draw is yours: note its license beside the library's, for example in a NOTICE file in the set directory.",+ 'The generated declaration file imports React types, so declare `@types/react` as an optional peer for TypeScript users.',+ 'Keep the wrapped library in `dependencies`: your generated module re-exports its components, so apps get it with your package, and `integration check` compares its range with the version the data file records.',+ "`integration check --strict` type-checks the set's doc files; it does not type-check the generated declaration file against React's types. Run `tsc` with `@types/react` installed to check those.",+ 'Your package needs `react` (the theme map and adapter use it) as a peer, as Core does. The `experimental icon new-set` receipt names the peers your package.json does not declare yet, as the JSON to add: `react` (`>=18`), and `@types/react` and `@astryxdesign/cli` (from the release that wrote the set) as optional peers; and the `typecheck` script (`astryx integration check --strict`) when there is none.',],},],@@ -329,7 +355,11 @@ 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.",+ 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. A mapped icon loses its library's sizing props (`size`, `strokeWidth`, `absoluteStrokeWidth`), since a set's icons take their size from CSS; the report names them as `dropped`. Comments on a rewritten import line are kept.",+ },+ {+ type: 'prose',+ text: "Each `icons` key is the name the template imports from its module, not a local alias. When a template imports the same name from two modules, such as `TrashIcon` from a library's outline and solid modules, one key covers both: both draw the same definition. Each then becomes the project set's variant of the same name when its module belongs to an installed set that declares the variant (so solid stays solid), else the set's default.",},],},@@ -363,11 +393,11 @@ astryx experimental icon use outline # make it the project's icon set`,],['`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.',+ 'In an app, 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. In your icon-set package, check with `astryx integration check` instead: plain `doctor` diagnoses an app.',],['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.',+ '`icon.search`, `icon.detail`, `icon.list`, `icon.setIcons`, `icon.definitions`, `icon.use`, `icon.map`, `icon.mapMany`, `icon.add`, `icon.addVariants`, `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.mjsindex b68002886e..bc3da04a18 100644--- a/packages/cli/assets/icons/definitions/activity.doc.mjs+++ b/packages/cli/assets/icons/definitions/activity.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'activity',description: 'Activity or live status over time.',- words: ['pulse', 'monitor', 'live'],+ words: ['pulse', 'live'],};diff --git a/packages/cli/assets/icons/definitions/alignCenter.doc.mjs b/packages/cli/assets/icons/definitions/alignCenter.doc.mjsnew file mode 100644index 0000000000..a217731c53--- /dev/null+++ b/packages/cli/assets/icons/definitions/alignCenter.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: 'alignCenter',+ description: 'Center text or items.',+ words: ['center align', 'centre', 'text align'],+};diff --git a/packages/cli/assets/icons/definitions/alignEnd.doc.mjs b/packages/cli/assets/icons/definitions/alignEnd.doc.mjsnew file mode 100644index 0000000000..5ce403d895--- /dev/null+++ b/packages/cli/assets/icons/definitions/alignEnd.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: 'alignEnd',+ description:+ 'Align text or items to the end edge: the right in a left-to-right layout, the left in a right-to-left one.',+ words: ['align end', 'right align', 'justify right', 'text align'],+};diff --git a/packages/cli/assets/icons/definitions/alignStart.doc.mjs b/packages/cli/assets/icons/definitions/alignStart.doc.mjsnew file mode 100644index 0000000000..a79f9258e5--- /dev/null+++ b/packages/cli/assets/icons/definitions/alignStart.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: 'alignStart',+ description:+ 'Align text or items to the start edge: the left in a left-to-right layout, the right in a right-to-left one.',+ words: ['align start', 'left align', 'justify left', 'text align'],+};diff --git a/packages/cli/assets/icons/definitions/archive.doc.mjs b/packages/cli/assets/icons/definitions/archive.doc.mjsindex 1c299d7fcb..6656093a36 100644--- a/packages/cli/assets/icons/definitions/archive.doc.mjs+++ b/packages/cli/assets/icons/definitions/archive.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'archive',description: 'Archive an item.',- words: ['store', 'box'],+ words: ['box', 'stash'],};diff --git a/packages/cli/assets/icons/definitions/arrowsUpDown.doc.mjs b/packages/cli/assets/icons/definitions/arrowsUpDown.doc.mjsindex 7e9762b47c..8f3b521b03 100644--- a/packages/cli/assets/icons/definitions/arrowsUpDown.doc.mjs+++ b/packages/cli/assets/icons/definitions/arrowsUpDown.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'arrowsUpDown',description: 'Show that a column can be sorted.',- words: ['sort', 'sortable', 'reorder'],+ words: ['sort', 'sortable', 'reorder', 'arrow up down'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/attach.doc.mjs b/packages/cli/assets/icons/definitions/attach.doc.mjsindex ce58b55b03..eccdaba9b0 100644--- a/packages/cli/assets/icons/definitions/attach.doc.mjs+++ b/packages/cli/assets/icons/definitions/attach.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'attach',description: 'Attach a file.',- words: ['attachment', 'paperclip'],+ words: ['attachment', 'paperclip', 'paper clip'],};diff --git a/packages/cli/assets/icons/definitions/audio.doc.mjs b/packages/cli/assets/icons/definitions/audio.doc.mjsindex 70116ee2e4..e0a7713cd9 100644--- a/packages/cli/assets/icons/definitions/audio.doc.mjs+++ b/packages/cli/assets/icons/definitions/audio.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'audio',description: 'Sound or volume.',- words: ['sound', 'volume', 'speaker'],+ words: ['sound', 'volume', 'speaker', 'speaker wave'],};diff --git a/packages/cli/assets/icons/definitions/cart.doc.mjs b/packages/cli/assets/icons/definitions/cart.doc.mjsindex 7add31abe6..e51ec5a00f 100644--- a/packages/cli/assets/icons/definitions/cart.doc.mjs+++ b/packages/cli/assets/icons/definitions/cart.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'cart',description: 'A shopping cart.',- words: ['shop', 'buy', 'checkout'],+ words: ['shop', 'buy', 'checkout', 'shopping cart'],};diff --git a/packages/cli/assets/icons/definitions/checkDouble.doc.mjs b/packages/cli/assets/icons/definitions/checkDouble.doc.mjsindex 7c70bc0093..f47dbb9ee1 100644--- a/packages/cli/assets/icons/definitions/checkDouble.doc.mjs+++ b/packages/cli/assets/icons/definitions/checkDouble.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'checkDouble',description: 'Show that something was copied or read.',- words: ['copied', 'read', 'seen'],+ words: ['copied', 'read', 'seen', 'double check', 'check check'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/chevronsLeft.doc.mjs b/packages/cli/assets/icons/definitions/chevronsLeft.doc.mjsindex 50ff5d71cb..f2959369e6 100644--- a/packages/cli/assets/icons/definitions/chevronsLeft.doc.mjs+++ b/packages/cli/assets/icons/definitions/chevronsLeft.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'chevronsLeft',description: 'Jump to the first item or page.',- words: ['first', 'start'],+ words: ['first', 'start', 'chevron double left'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/chevronsRight.doc.mjs b/packages/cli/assets/icons/definitions/chevronsRight.doc.mjsindex 0eb5f99d27..447c0a232f 100644--- a/packages/cli/assets/icons/definitions/chevronsRight.doc.mjs+++ b/packages/cli/assets/icons/definitions/chevronsRight.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'chevronsRight',description: 'Jump to the last item or page.',- words: ['last', 'end'],+ words: ['last', 'end', 'chevron double right'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/close.doc.mjs b/packages/cli/assets/icons/definitions/close.doc.mjsindex 6ce30429be..05fc8a8bee 100644--- a/packages/cli/assets/icons/definitions/close.doc.mjs+++ b/packages/cli/assets/icons/definitions/close.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'close',description: 'Dismiss or close a dialog, panel, tag or banner.',- words: ['dismiss', 'cancel', 'remove'],+ words: ['dismiss', 'cancel', 'remove', 'x', 'x mark'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/collapse.doc.mjs b/packages/cli/assets/icons/definitions/collapse.doc.mjsindex c3f1f9a1a8..3a9615139b 100644--- a/packages/cli/assets/icons/definitions/collapse.doc.mjs+++ b/packages/cli/assets/icons/definitions/collapse.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'collapse',description: 'Make something smaller or exit full screen.',- words: ['minimize', 'shrink'],+ words: ['minimize', 'shrink', 'arrows pointing in'],};diff --git a/packages/cli/assets/icons/definitions/compose.doc.mjs b/packages/cli/assets/icons/definitions/compose.doc.mjsindex 58fbc12d79..8487e25e1b 100644--- a/packages/cli/assets/icons/definitions/compose.doc.mjs+++ b/packages/cli/assets/icons/definitions/compose.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'compose',description: 'Write something new, such as a message or post.',- words: ['write', 'new message', 'draft'],+ words: ['write', 'new message', 'draft', 'square pen', 'pencil square'],};diff --git a/packages/cli/assets/icons/definitions/conversation.doc.mjs b/packages/cli/assets/icons/definitions/conversation.doc.mjsindex 4f7690c50d..623fdb13a5 100644--- a/packages/cli/assets/icons/definitions/conversation.doc.mjs+++ b/packages/cli/assets/icons/definitions/conversation.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'conversation',description: 'A conversation between people.',- words: ['chat', 'discussion', 'thread'],+ words: ['chat', 'discussion', 'thread', 'chat bubbles', 'messages square'],};diff --git a/packages/cli/assets/icons/definitions/copy.doc.mjs b/packages/cli/assets/icons/definitions/copy.doc.mjsindex df44baaa2f..3c46d225e0 100644--- a/packages/cli/assets/icons/definitions/copy.doc.mjs+++ b/packages/cli/assets/icons/definitions/copy.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'copy',description: 'Copy to the clipboard.',- words: ['duplicate', 'clipboard'],+ words: ['duplicate', 'clipboard', 'document duplicate'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/cpu.doc.mjs b/packages/cli/assets/icons/definitions/cpu.doc.mjsnew file mode 100644index 0000000000..5b1f838717--- /dev/null+++ b/packages/cli/assets/icons/definitions/cpu.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: 'cpu',+ description: 'A processor or compute resource.',+ words: ['processor', 'chip', 'compute', 'hardware'],+};diff --git a/packages/cli/assets/icons/definitions/database.doc.mjs b/packages/cli/assets/icons/definitions/database.doc.mjsindex 60a8c7596e..e9339ebdca 100644--- a/packages/cli/assets/icons/definitions/database.doc.mjs+++ b/packages/cli/assets/icons/definitions/database.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'database',description: 'A database or stored data.',- words: ['data', 'storage', 'table'],+ words: ['data', 'storage'],};diff --git a/packages/cli/assets/icons/definitions/desktop.doc.mjs b/packages/cli/assets/icons/definitions/desktop.doc.mjsindex a92d2d8b35..71c79394ad 100644--- a/packages/cli/assets/icons/definitions/desktop.doc.mjs+++ b/packages/cli/assets/icons/definitions/desktop.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'desktop',description: 'A desktop computer, or the desktop layout of a page.',- words: ['computer', 'monitor', 'screen'],+ words: ['computer', 'monitor', 'screen', 'computer desktop'],};diff --git a/packages/cli/assets/icons/definitions/discount.doc.mjs b/packages/cli/assets/icons/definitions/discount.doc.mjsindex 0d4cd06837..aec0e5f073 100644--- a/packages/cli/assets/icons/definitions/discount.doc.mjs+++ b/packages/cli/assets/icons/definitions/discount.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'discount',description: 'A discount, coupon, or percentage off.',- words: ['coupon', 'sale', 'percent'],+ words: ['coupon', 'sale', 'percent', 'percent badge'],};diff --git a/packages/cli/assets/icons/definitions/download.doc.mjs b/packages/cli/assets/icons/definitions/download.doc.mjsindex 550832880e..574f9666e6 100644--- a/packages/cli/assets/icons/definitions/download.doc.mjs+++ b/packages/cli/assets/icons/definitions/download.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'download',description: 'Download a file.',- words: ['export', 'save file'],+ words: ['export', 'save file', 'arrow down tray'],};diff --git a/packages/cli/assets/icons/definitions/emoji.doc.mjs b/packages/cli/assets/icons/definitions/emoji.doc.mjsindex dedb908f46..164885744c 100644--- a/packages/cli/assets/icons/definitions/emoji.doc.mjs+++ b/packages/cli/assets/icons/definitions/emoji.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'emoji',description: 'Add an emoji or a reaction.',- words: ['smile', 'reaction', 'face'],+ words: ['smile', 'reaction', 'face', 'face smile'],};diff --git a/packages/cli/assets/icons/definitions/error.doc.mjs b/packages/cli/assets/icons/definitions/error.doc.mjsindex ceddca9084..98f6ec9eb7 100644--- a/packages/cli/assets/icons/definitions/error.doc.mjs+++ b/packages/cli/assets/icons/definitions/error.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'error',description: 'Show that something failed.',- words: ['failed', 'invalid', 'problem'],+ words: ['failed', 'invalid', 'problem', 'x circle', 'circle x'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/expand.doc.mjs b/packages/cli/assets/icons/definitions/expand.doc.mjsindex d79af6cb44..71be118f0f 100644--- a/packages/cli/assets/icons/definitions/expand.doc.mjs+++ b/packages/cli/assets/icons/definitions/expand.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'expand',description: 'Make something larger or full screen.',- words: ['maximize', 'fullscreen', 'enlarge'],+ words: ['maximize', 'fullscreen', 'enlarge', 'arrows pointing out'],};diff --git a/packages/cli/assets/icons/definitions/experiment.doc.mjs b/packages/cli/assets/icons/definitions/experiment.doc.mjsindex bfc1ea8aea..595eaebb6b 100644--- a/packages/cli/assets/icons/definitions/experiment.doc.mjs+++ b/packages/cli/assets/icons/definitions/experiment.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'experiment',description: 'An experiment, test, or lab feature.',- words: ['lab', 'test', 'beta'],+ words: ['lab', 'test', 'beta', 'test tube'],};diff --git a/packages/cli/assets/icons/definitions/externalLink.doc.mjs b/packages/cli/assets/icons/definitions/externalLink.doc.mjsindex 868c3fa34a..7b5155621a 100644--- a/packages/cli/assets/icons/definitions/externalLink.doc.mjs+++ b/packages/cli/assets/icons/definitions/externalLink.doc.mjs@@ -5,6 +5,12 @@ export default {type: 'icon-definition',name: 'externalLink',description: 'Open a link in a new tab or another site.',- words: ['open', 'new tab', 'external'],+ words: [+ 'open',+ 'new tab',+ 'external',+ 'arrow top right on square',+ 'square arrow out up right',+ ],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/eyeSlash.doc.mjs b/packages/cli/assets/icons/definitions/eyeSlash.doc.mjsindex 1bceb06d20..f3425260a9 100644--- a/packages/cli/assets/icons/definitions/eyeSlash.doc.mjs+++ b/packages/cli/assets/icons/definitions/eyeSlash.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'eyeSlash',description: 'Hide something, or show that it is hidden.',- words: ['hide', 'hidden', 'invisible'],+ words: ['hide', 'hidden', 'invisible', 'eye off'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/flipHorizontal.doc.mjs b/packages/cli/assets/icons/definitions/flipHorizontal.doc.mjsnew file mode 100644index 0000000000..71d3f88e9c--- /dev/null+++ b/packages/cli/assets/icons/definitions/flipHorizontal.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: 'flipHorizontal',+ description: 'Mirror an image or shape left to right.',+ words: ['mirror', 'flip', 'reflect'],+};diff --git a/packages/cli/assets/icons/definitions/flipVertical.doc.mjs b/packages/cli/assets/icons/definitions/flipVertical.doc.mjsnew file mode 100644index 0000000000..1c969a17cc--- /dev/null+++ b/packages/cli/assets/icons/definitions/flipVertical.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: 'flipVertical',+ description: 'Mirror an image or shape top to bottom.',+ words: ['mirror', 'flip', 'upside down'],+};diff --git a/packages/cli/assets/icons/definitions/folderAdd.doc.mjs b/packages/cli/assets/icons/definitions/folderAdd.doc.mjsindex 19d8155054..6767d0c0fb 100644--- a/packages/cli/assets/icons/definitions/folderAdd.doc.mjs+++ b/packages/cli/assets/icons/definitions/folderAdd.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'folderAdd',description: 'Create a new folder.',- words: ['new folder'],+ words: ['new folder', 'folder plus'],};diff --git a/packages/cli/assets/icons/definitions/gitBranch.doc.mjs b/packages/cli/assets/icons/definitions/gitBranch.doc.mjsnew file mode 100644index 0000000000..3f76d91f84--- /dev/null+++ b/packages/cli/assets/icons/definitions/gitBranch.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: 'gitBranch',+ description: 'A branch of a code repository.',+ words: ['branch', 'version control', 'repository'],+};diff --git a/packages/cli/assets/icons/definitions/gitFork.doc.mjs b/packages/cli/assets/icons/definitions/gitFork.doc.mjsnew file mode 100644index 0000000000..6022f0ef07--- /dev/null+++ b/packages/cli/assets/icons/definitions/gitFork.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: 'gitFork',+ description: 'A fork: a copy of a repository someone develops separately.',+ words: ['fork', 'repository', 'version control'],+};diff --git a/packages/cli/assets/icons/definitions/info.doc.mjs b/packages/cli/assets/icons/definitions/info.doc.mjsindex d75199779e..90fa75027b 100644--- a/packages/cli/assets/icons/definitions/info.doc.mjs+++ b/packages/cli/assets/icons/definitions/info.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'info',description: 'Give more information or help.',- words: ['information', 'help', 'about'],+ words: ['information', 'help', 'about', 'information circle'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/location.doc.mjs b/packages/cli/assets/icons/definitions/location.doc.mjsindex f2d9d7b250..80c9e0cdc6 100644--- a/packages/cli/assets/icons/definitions/location.doc.mjs+++ b/packages/cli/assets/icons/definitions/location.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'location',description: 'A place or address.',- words: ['place', 'address', 'map'],+ words: ['place', 'address', 'map', 'map pin'],};diff --git a/packages/cli/assets/icons/definitions/mention.doc.mjs b/packages/cli/assets/icons/definitions/mention.doc.mjsindex 179ffd4605..dd3089b32f 100644--- a/packages/cli/assets/icons/definitions/mention.doc.mjs+++ b/packages/cli/assets/icons/definitions/mention.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'mention',description: 'Mention someone or show an email address.',- words: ['at', 'email', 'handle'],+ words: ['at', 'email', 'handle', 'at symbol', 'at sign'],};diff --git a/packages/cli/assets/icons/definitions/menu.doc.mjs b/packages/cli/assets/icons/definitions/menu.doc.mjsindex 9e87147e31..1c48ae7c07 100644--- a/packages/cli/assets/icons/definitions/menu.doc.mjs+++ b/packages/cli/assets/icons/definitions/menu.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'menu',description: 'Open the main navigation menu.',- words: ['hamburger', 'navigation'],+ words: ['hamburger', 'navigation', 'bars'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/microphone.doc.mjs b/packages/cli/assets/icons/definitions/microphone.doc.mjsindex cdc6f543e2..be71555990 100644--- a/packages/cli/assets/icons/definitions/microphone.doc.mjs+++ b/packages/cli/assets/icons/definitions/microphone.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'microphone',description: 'Start voice input or audio recording.',- words: ['voice', 'audio', 'record'],+ words: ['voice', 'audio', 'record', 'mic'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/mobile.doc.mjs b/packages/cli/assets/icons/definitions/mobile.doc.mjsindex 6467fa5f30..4e8dd135f8 100644--- a/packages/cli/assets/icons/definitions/mobile.doc.mjs+++ b/packages/cli/assets/icons/definitions/mobile.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'mobile',description: 'A phone, or the mobile layout of a page.',- words: ['phone', 'smartphone', 'device'],+ words: ['phone', 'smartphone'],};diff --git a/packages/cli/assets/icons/definitions/money.doc.mjs b/packages/cli/assets/icons/definitions/money.doc.mjsindex cb70d3a300..9648b2bf0f 100644--- a/packages/cli/assets/icons/definitions/money.doc.mjs+++ b/packages/cli/assets/icons/definitions/money.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'money',description: 'Money, prices or payments.',- words: ['price', 'payment', 'cost', 'currency'],+ words: ['price', 'payment', 'cost', 'currency', 'currency dollar'],};diff --git a/packages/cli/assets/icons/definitions/moreHorizontal.doc.mjs b/packages/cli/assets/icons/definitions/moreHorizontal.doc.mjsindex 84ed897780..b67f417492 100644--- a/packages/cli/assets/icons/definitions/moreHorizontal.doc.mjs+++ b/packages/cli/assets/icons/definitions/moreHorizontal.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'moreHorizontal',description: 'Open more actions for an item.',- words: ['more', 'overflow', 'actions'],+ words: ['more', 'overflow', 'actions', 'ellipsis', 'ellipsis horizontal'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/notificationActive.doc.mjs b/packages/cli/assets/icons/definitions/notificationActive.doc.mjsindex 12b33e2bfb..3b4e810a0f 100644--- a/packages/cli/assets/icons/definitions/notificationActive.doc.mjs+++ b/packages/cli/assets/icons/definitions/notificationActive.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'notificationActive',description: 'New or unread notifications.',- words: ['ringing', 'unread', 'new alert'],+ words: ['ringing', 'unread', 'new alert', 'bell alert', 'bell ring'],};diff --git a/packages/cli/assets/icons/definitions/notificationOff.doc.mjs b/packages/cli/assets/icons/definitions/notificationOff.doc.mjsindex bd2fd65775..a352ed7688 100644--- a/packages/cli/assets/icons/definitions/notificationOff.doc.mjs+++ b/packages/cli/assets/icons/definitions/notificationOff.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'notificationOff',description: 'Turn notifications off, or show that they are muted.',- words: ['mute', 'silence', 'notifications off'],+ words: ['mute', 'silence', 'notifications off', 'bell slash', 'bell off'],};diff --git a/packages/cli/assets/icons/definitions/panelLeft.doc.mjs b/packages/cli/assets/icons/definitions/panelLeft.doc.mjsnew file mode 100644index 0000000000..3a4344864d--- /dev/null+++ b/packages/cli/assets/icons/definitions/panelLeft.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: 'panelLeft',+ description:+ 'Show or hide a side panel on the left, such as a navigation sidebar.',+ words: ['sidebar', 'left panel', 'drawer', 'toggle sidebar'],+};diff --git a/packages/cli/assets/icons/definitions/panelRight.doc.mjs b/packages/cli/assets/icons/definitions/panelRight.doc.mjsnew file mode 100644index 0000000000..e4fd0f1b2b--- /dev/null+++ b/packages/cli/assets/icons/definitions/panelRight.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: 'panelRight',+ description:+ 'Show or hide a side panel on the right, such as a details or inspector pane.',+ words: ['right panel', 'inspector', 'details pane', 'drawer'],+};diff --git a/packages/cli/assets/icons/definitions/raiseHand.doc.mjs b/packages/cli/assets/icons/definitions/raiseHand.doc.mjsindex e1a53c527e..e7006349ff 100644--- a/packages/cli/assets/icons/definitions/raiseHand.doc.mjs+++ b/packages/cli/assets/icons/definitions/raiseHand.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'raiseHand',description: 'Raise a hand to ask or speak.',- words: ['hand', 'ask', 'stop'],+ words: ['hand', 'ask', 'hand raised'],};diff --git a/packages/cli/assets/icons/definitions/redo.doc.mjs b/packages/cli/assets/icons/definitions/redo.doc.mjsindex 12ef0329ba..1a355994ff 100644--- a/packages/cli/assets/icons/definitions/redo.doc.mjs+++ b/packages/cli/assets/icons/definitions/redo.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'redo',description: 'Redo the last change that was undone.',- words: ['again', 'repeat', 'forward'],+ words: ['again', 'repeat', 'arrow uturn right'],};diff --git a/packages/cli/assets/icons/definitions/refresh.doc.mjs b/packages/cli/assets/icons/definitions/refresh.doc.mjsindex b26ebcd1e5..064aacd823 100644--- a/packages/cli/assets/icons/definitions/refresh.doc.mjs+++ b/packages/cli/assets/icons/definitions/refresh.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'refresh',description: 'Reload or refresh data.',- words: ['reload', 'sync', 'retry'],+ words: ['reload', 'sync', 'retry', 'arrow path'],};diff --git a/packages/cli/assets/icons/definitions/rotate.doc.mjs b/packages/cli/assets/icons/definitions/rotate.doc.mjsnew file mode 100644index 0000000000..4d9b755d92--- /dev/null+++ b/packages/cli/assets/icons/definitions/rotate.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: 'rotate',+ description: 'Rotate an image, shape, or view.',+ words: ['turn', 'spin', 'orientation'],+};diff --git a/packages/cli/assets/icons/definitions/scale.doc.mjs b/packages/cli/assets/icons/definitions/scale.doc.mjsnew file mode 100644index 0000000000..4f74b9cb12--- /dev/null+++ b/packages/cli/assets/icons/definitions/scale.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: 'scale',+ description:+ 'A balance scale: law, fairness, or weighing one option against another.',+ words: ['balance', 'legal', 'justice', 'compare'],+};diff --git a/packages/cli/assets/icons/definitions/search.doc.mjs b/packages/cli/assets/icons/definitions/search.doc.mjsindex a02ac33fb1..f8ff54de3b 100644--- a/packages/cli/assets/icons/definitions/search.doc.mjs+++ b/packages/cli/assets/icons/definitions/search.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'search',description: 'Search or find something.',- words: ['find', 'lookup', 'magnifier'],+ words: ['find', 'lookup', 'magnifier', 'magnifying glass'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/send.doc.mjs b/packages/cli/assets/icons/definitions/send.doc.mjsindex e921123687..7c0d5277a1 100644--- a/packages/cli/assets/icons/definitions/send.doc.mjs+++ b/packages/cli/assets/icons/definitions/send.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'send',description: 'Send a message.',- words: ['submit', 'post'],+ words: ['submit', 'post', 'paper airplane'],};diff --git a/packages/cli/assets/icons/definitions/settings.doc.mjs b/packages/cli/assets/icons/definitions/settings.doc.mjsindex bc61671b36..2868d4e678 100644--- a/packages/cli/assets/icons/definitions/settings.doc.mjs+++ b/packages/cli/assets/icons/definitions/settings.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'settings',description: 'Open settings or preferences.',- words: ['gear', 'preferences', 'options'],+ words: ['gear', 'preferences', 'options', 'cog'],};diff --git a/packages/cli/assets/icons/definitions/star.doc.mjs b/packages/cli/assets/icons/definitions/star.doc.mjsindex b1ac05a6ce..ffee1541bb 100644--- a/packages/cli/assets/icons/definitions/star.doc.mjs+++ b/packages/cli/assets/icons/definitions/star.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'star',description: 'Favorite or rate something.',- words: ['favorite', 'rating', 'bookmark'],+ words: ['favorite', 'rating'],};diff --git a/packages/cli/assets/icons/definitions/stop.doc.mjs b/packages/cli/assets/icons/definitions/stop.doc.mjsindex c16430e912..f116cb74e7 100644--- a/packages/cli/assets/icons/definitions/stop.doc.mjs+++ b/packages/cli/assets/icons/definitions/stop.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'stop',description: 'Stop or cancel a running action.',- words: ['halt', 'end', 'cancel'],+ words: ['halt', 'end', 'cancel', 'square', 'circle stop'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/success.doc.mjs b/packages/cli/assets/icons/definitions/success.doc.mjsindex fb7ec393a6..630998382f 100644--- a/packages/cli/assets/icons/definitions/success.doc.mjs+++ b/packages/cli/assets/icons/definitions/success.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'success',description: 'Show that something worked.',- words: ['ok', 'complete', 'passed'],+ words: ['ok', 'complete', 'passed', 'check circle', 'circle check'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/textCase.doc.mjs b/packages/cli/assets/icons/definitions/textCase.doc.mjsnew file mode 100644index 0000000000..f0078c83f4--- /dev/null+++ b/packages/cli/assets/icons/definitions/textCase.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: 'textCase',+ description: 'Change the letter case of text, such as upper or lower case.',+ words: ['uppercase', 'lowercase', 'capitalize', 'case', 'case sensitive'],+};diff --git a/packages/cli/assets/icons/definitions/thumbsDown.doc.mjs b/packages/cli/assets/icons/definitions/thumbsDown.doc.mjsindex 108365f50f..4dfe9104df 100644--- a/packages/cli/assets/icons/definitions/thumbsDown.doc.mjs+++ b/packages/cli/assets/icons/definitions/thumbsDown.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'thumbsDown',description: 'Give negative feedback.',- words: ['dislike', 'bad'],+ words: ['dislike', 'bad', 'hand thumb down'],};diff --git a/packages/cli/assets/icons/definitions/thumbsUp.doc.mjs b/packages/cli/assets/icons/definitions/thumbsUp.doc.mjsindex 4dece26d42..cf60632527 100644--- a/packages/cli/assets/icons/definitions/thumbsUp.doc.mjs+++ b/packages/cli/assets/icons/definitions/thumbsUp.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'thumbsUp',description: 'Approve or give positive feedback.',- words: ['approve', 'good', 'like'],+ words: ['approve', 'good', 'like', 'hand thumb up'],};diff --git a/packages/cli/assets/icons/definitions/trendDown.doc.mjs b/packages/cli/assets/icons/definitions/trendDown.doc.mjsindex c475e5e3da..226603fcee 100644--- a/packages/cli/assets/icons/definitions/trendDown.doc.mjs+++ b/packages/cli/assets/icons/definitions/trendDown.doc.mjs@@ -5,5 +5,11 @@ export default {type: 'icon-definition',name: 'trendDown',description: 'Show a value going down.',- words: ['decrease', 'decline', 'down'],+ words: [+ 'decrease',+ 'decline',+ 'down',+ 'arrow trending down',+ 'trending down',+ ],};diff --git a/packages/cli/assets/icons/definitions/trendUp.doc.mjs b/packages/cli/assets/icons/definitions/trendUp.doc.mjsindex 49fcc4f9aa..32438f958b 100644--- a/packages/cli/assets/icons/definitions/trendUp.doc.mjs+++ b/packages/cli/assets/icons/definitions/trendUp.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'trendUp',description: 'Show a value going up.',- words: ['increase', 'growth', 'up'],+ words: ['increase', 'growth', 'up', 'arrow trending up', 'trending up'],};diff --git a/packages/cli/assets/icons/definitions/undo.doc.mjs b/packages/cli/assets/icons/definitions/undo.doc.mjsindex b3d109bcd9..cfd1e1898c 100644--- a/packages/cli/assets/icons/definitions/undo.doc.mjs+++ b/packages/cli/assets/icons/definitions/undo.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'undo',description: 'Undo the last change.',- words: ['revert', 'back'],+ words: ['revert', 'back', 'arrow uturn left'],};diff --git a/packages/cli/assets/icons/definitions/upload.doc.mjs b/packages/cli/assets/icons/definitions/upload.doc.mjsindex 321a10799e..8587faca80 100644--- a/packages/cli/assets/icons/definitions/upload.doc.mjs+++ b/packages/cli/assets/icons/definitions/upload.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'upload',description: 'Upload a file or content.',- words: ['import', 'attach file'],+ words: ['import', 'attach file', 'arrow up tray'],builtIn: true,};diff --git a/packages/cli/assets/icons/definitions/userAdd.doc.mjs b/packages/cli/assets/icons/definitions/userAdd.doc.mjsindex e04341ec05..8b9bcef24a 100644--- a/packages/cli/assets/icons/definitions/userAdd.doc.mjs+++ b/packages/cli/assets/icons/definitions/userAdd.doc.mjs@@ -5,5 +5,5 @@ export default {type: 'icon-definition',name: 'userAdd',description: 'Invite or add a person.',- words: ['invite', 'add person'],+ words: ['invite', 'add person', 'user plus'],};diff --git a/packages/cli/assets/icons/definitions/warning.doc.mjs b/packages/cli/assets/icons/definitions/warning.doc.mjsindex e77ea3c760..091ee4b3fc 100644--- a/packages/cli/assets/icons/definitions/warning.doc.mjs+++ b/packages/cli/assets/icons/definitions/warning.doc.mjs@@ -5,6 +5,6 @@ export default {type: 'icon-definition',name: 'warning',description: 'Warn about something that needs attention.',- words: ['caution', 'alert'],+ words: ['caution', 'alert', 'exclamation triangle', 'triangle alert'],builtIn: true,};diff --git a/packages/cli/assets/templates/pages/canvas-editor/template.doc.mjs b/packages/cli/assets/templates/pages/canvas-editor/template.doc.mjsindex 0be68ee934..76a158db7a 100644--- a/packages/cli/assets/templates/pages/canvas-editor/template.doc.mjs+++ b/packages/cli/assets/templates/pages/canvas-editor/template.doc.mjs@@ -18,8 +18,11 @@ export const doc = {isReady: true,category: 'Tools - Canvas Editor',icons: {+ CaseSensitive: 'textCase',Download: 'download',File: 'file',+ FlipHorizontal2: 'flipHorizontal',+ FlipVertical2: 'flipVertical',Grip: 'drag',Image: 'image',Italic: 'italic',@@ -27,9 +30,15 @@ export const doc = {LockOpen: 'unlock',Menu: 'menu',Minus: 'remove',+ PanelLeft: 'panelLeft',+ PanelRight: 'panelRight',Plus: 'add',Redo2: 'redo',+ RotateCw: 'rotate',Strikethrough: 'strikethrough',+ TextAlignCenter: 'alignCenter',+ TextAlignEnd: 'alignEnd',+ TextAlignStart: 'alignStart',Underline: 'underline',Undo2: 'undo',X: 'close',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 9df9f663c8..2d4bc9b0e2 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,5 +9,10 @@ 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'},+ icons: {+ BeakerIcon: 'experiment',+ BoltIcon: 'bolt',+ CpuChipIcon: 'cpu',+ CubeIcon: 'package',+ },};diff --git a/packages/cli/assets/templates/pages/table-comparison/template.doc.mjs b/packages/cli/assets/templates/pages/table-comparison/template.doc.mjsindex ca6aa56cfe..760a291c17 100644--- a/packages/cli/assets/templates/pages/table-comparison/template.doc.mjs+++ b/packages/cli/assets/templates/pages/table-comparison/template.doc.mjs@@ -14,6 +14,7 @@ export const doc = {Box: 'package',CircleCheck: 'success',CircleX: 'error',+ Cpu: 'cpu',FileText: 'document',Image: 'image',Plus: 'add',diff --git a/packages/cli/assets/templates/pages/table-tree/template.doc.mjs b/packages/cli/assets/templates/pages/table-tree/template.doc.mjsindex 62a4a9c77d..4d4de955c3 100644--- a/packages/cli/assets/templates/pages/table-tree/template.doc.mjs+++ b/packages/cli/assets/templates/pages/table-tree/template.doc.mjs@@ -29,6 +29,9 @@ export const doc = {Eye: 'eye',File: 'file',Folder: 'folder',+ GitBranch: 'gitBranch',+ GitFork: 'gitFork',+ Scale: 'scale',Search: 'search',ShieldCheck: 'shield',Star: 'star',diff --git a/packages/cli/authoring/doctypes/icon-definition/icon-definition.doc.mjs b/packages/cli/authoring/doctypes/icon-definition/icon-definition.doc.mjsindex 978b9bd6bb..85795f5ae2 100644--- a/packages/cli/authoring/doctypes/icon-definition/icon-definition.doc.mjs+++ b/packages/cli/authoring/doctypes/icon-definition/icon-definition.doc.mjs@@ -62,13 +62,13 @@ export const doc = {examples: [{label:- "A set's own definition at icon-sets/outline/definitions/rotate.doc.mjs",+ "A set's own definition at icon-sets/outline/definitions/random.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'],+ name: 'random',+ description: 'Pick something at random.',+ words: ['dice', 'shuffle', 'chance'],};`,},],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.mjsindex cb0e2bda46..cf851f4640 100644--- a/packages/cli/authoring/doctypes/icon-set/icon-set-data.doc.mjs+++ b/packages/cli/authoring/doctypes/icon-set/icon-set-data.doc.mjs@@ -37,6 +37,12 @@ export const doc = {description:'The upstream library and version the file was generated from. Omit it for a set with no upstream.',},+ {+ name: 'exclude',+ type: 'string[]',+ description:+ 'Library exports that are not icons. `experimental icon new-set --from` leaves them out every time it wraps or refreshes the set; `--exclude` adds to the list. A CLI whose reference does not list this key withdraws a set that sets it, naming the key; leave it out for a set those CLIs must read.',+ },{name: 'generated',type: 'string',diff --git a/packages/cli/authoring/doctypes/icon-set/parse.mjs b/packages/cli/authoring/doctypes/icon-set/parse.mjsindex 4a108ac58a..3192fb9b47 100644--- a/packages/cli/authoring/doctypes/icon-set/parse.mjs+++ b/packages/cli/authoring/doctypes/icon-set/parse.mjs@@ -145,6 +145,7 @@ const dataSchema = z}).strict().optional(),+ exclude: z.array(exportSchema).optional(),variants: z.array(variantNameSchema).min(1).optional(),default: z.object({variant: variantNameSchema.optional()})diff --git a/packages/cli/authoring/doctypes/icon-set/type.ts b/packages/cli/authoring/doctypes/icon-set/type.tsindex 94feb8cd83..1bd68f5593 100644--- a/packages/cli/authoring/doctypes/icon-set/type.ts+++ b/packages/cli/authoring/doctypes/icon-set/type.ts@@ -146,6 +146,11 @@ export interface IconSetData {module: string;/** The upstream library, absent for a set with no upstream. */source?: IconSetSource;+ /**+ * Library exports that are not icons, left out every time+ * `astryx experimental icon new-set --from` wraps or refreshes the set.+ */+ exclude?: string[];/*** 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 setdiff --git a/packages/cli/authoring/doctypes/template/template.doc.mjs b/packages/cli/authoring/doctypes/template/template.doc.mjsindex 99ac547ec2..9ae215e002 100644--- a/packages/cli/authoring/doctypes/template/template.doc.mjs+++ b/packages/cli/authoring/doctypes/template/template.doc.mjs@@ -69,7 +69,7 @@ export const doc = {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.",+ "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. A name imported from two modules (`TrashIcon` from an outline and a solid module) needs one key, and each import keeps its variant when its module belongs to an installed set.",},{name: 'isReady',diff --git a/packages/cli/authoring/doctypes/template/type.ts b/packages/cli/authoring/doctypes/template/type.tsindex a984db0228..08045629ad 100644--- a/packages/cli/authoring/doctypes/template/type.ts+++ b/packages/cli/authoring/doctypes/template/type.ts@@ -57,7 +57,8 @@ export interface BaseTemplateDoc extends AuthoredDocGraphFields {* (`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.+ * key is reported as mapped or kept. A name imported from two modules+ * (`TrashIcon` from an outline and a solid module) needs one key.* @experimental May change or be removed in a patch release. */icons?: Record<string, string>;diff --git a/packages/cli/clients/cli/commands/doctor.mjs b/packages/cli/clients/cli/commands/doctor.mjsindex 9e46e02888..99388404b2 100644--- a/packages/cli/clients/cli/commands/doctor.mjs+++ b/packages/cli/clients/cli/commands/doctor.mjs@@ -355,26 +355,25 @@ function unmappedBlocks(listed) {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}`}`,- ),- ),- ]- : [],+ {fields: ['set', 'unmapped']},),+ // One line per definition: what it means and its words, so an author+ // can pick from the text alone; a suggested icon when one fits.+ ...listed.map(each => {+ const suggested = new Map(+ each.suggestions.map(({definition, icon}) => [definition, icon]),+ );+ const setFlag = listed.length === 1 ? '' : ` --set ${each.set}`;+ return list(+ each.unmappedDefinitions.map(+ definition =>+ `${definition.name}: ${definition.description} Words: ${definition.words.join(', ')}.${suggested.has(definition.name) ? ` Suggested: astryx experimental icon map ${definition.name} ${suggested.get(definition.name)}${setFlag}` : ''}`,+ ),+ );+ }),text(- 'Mapping these is optional and never fails a check. --json lists each with its description and words.',+ 'Mapping these is optional and never fails a check. Map one with `astryx experimental icon map <definition> <icon id>`; list your icons with `astryx experimental icon --set <set> --all-icons`; see how many definitions each set maps with `astryx experimental icon --list`.',),];}diff --git a/packages/cli/clients/cli/commands/experimental-icon-add.doc.mjs b/packages/cli/clients/cli/commands/experimental-icon-add.doc.mjsindex 600bfe19b5..6db71d122d 100644--- a/packages/cli/clients/cli/commands/experimental-icon-add.doc.mjs+++ b/packages/cli/clients/cli/commands/experimental-icon-add.doc.mjs@@ -11,15 +11,15 @@ export const doc = {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.",+ "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. With --variant <name> --from <module> --all and no export, it adds that variant for every icon whose id the module exports. Experimental: it may change or be removed in a patch release.",fn: 'iconAdd',- args: [{name: 'export', param: 'exportName', required: true}],+ args: [{name: 'export', param: 'exportName', required: false}],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',+ 'The module the icon is exported from: a package, a subpath, or a ./ path to a file inside this package',},{flag: '--definition <name>',@@ -55,6 +55,12 @@ export const doc = {description:"Add the export as this variant of an existing icon: one of the set's declared variants, such as solid",},+ {+ flag: '--all',+ param: 'options.all',+ description:+ 'With --variant and --from, and no export: add that variant for every icon whose id the module exports, in one run',+ },{flag: '--id <id>',param: 'options.id',@@ -75,9 +81,13 @@ export const doc = {label: 'Add and map',cli: 'astryx experimental icon add Bin --from @acme/glyph-library --definition delete',},+ {+ label: 'Add the solid variant of every icon',+ cli: 'astryx experimental icon add --variant solid --from @heroicons/react/24/solid --all',+ },{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",+ cli: "astryx experimental icon add Dice5 --from @acme/glyph-library --new-definition random --description 'Pick something at random.' --words dice,shuffle,chance",},{label: 'Add a solid variant',diff --git a/packages/cli/clients/cli/commands/experimental-icon-map.doc.mjs b/packages/cli/clients/cli/commands/experimental-icon-map.doc.mjsindex 04d316d63b..a2ec8fe3b4 100644--- a/packages/cli/clients/cli/commands/experimental-icon-map.doc.mjs+++ b/packages/cli/clients/cli/commands/experimental-icon-map.doc.mjs@@ -11,10 +11,10 @@ export const doc = {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.",+ "Run inside an icon-set package. Sets `map[<definition>]` to the icon's id in the set's data file; name the icon by its id, its export name in any case, or another name its library exports it as (`trash-2` or `Trash2`), never by one word of its id, and the definition by its name or kebab id; `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: 'definition', param: 'definition', required: false},{name: 'icon', param: 'icon', required: false},],options: [@@ -28,12 +28,22 @@ export const doc = {param: 'options.remove',description: "Remove the definition's entry; takes no icon",},+ {+ flag: '--pairs <list>',+ param: 'options.pairs',+ description:+ 'Many entries in one write: <definition>=<icon> pairs, comma-separated; checked together, all or none; an existing entry is replaced',+ },],examples: [{label: 'Map a definition',cli: 'astryx experimental icon map delete trash',},+ {+ label: 'Map many at once',+ cli: 'astryx experimental icon map --pairs close=x-mark,error=x-circle,search=magnifying-glass',+ },{label: 'Remove an entry',cli: 'astryx experimental icon map delete --remove',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.mjsindex c6ce95991e..b69d412daf 100644--- a/packages/cli/clients/cli/commands/experimental-icon-new-definition.doc.mjs+++ b/packages/cli/clients/cli/commands/experimental-icon-new-definition.doc.mjs@@ -51,7 +51,7 @@ export const doc = {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",+ cli: "astryx experimental icon new-definition random --description 'Pick something at random.' --words dice,shuffle,chance --icon dice-5",},],outsideProject: 'refuse',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.mjsindex 199fdb01a1..47aa98947a 100644--- a/packages/cli/clients/cli/commands/experimental-icon-new-set.doc.mjs+++ b/packages/cli/clients/cli/commands/experimental-icon-new-set.doc.mjs@@ -11,7 +11,7 @@ export const doc = {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.",+ "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, records the library and its version as the set's source, copies its license notice, and maps each Astryx icon definition whose name is an icon's id; definitions an icon only shares a word with are listed as suggestions, never written. Run it again to refresh. --variants and --default-variant declare the set's variants. Experimental: it may change or be removed in a patch release.",fn: 'iconNewSet',args: [{@@ -39,6 +39,29 @@ export const doc = {description:'With --from: comma-separated export names of the library that are not icons',},+ {+ flag: '--variants <list>',+ param: 'options.variants',+ description:+ 'Comma-separated variants the set supplies, such as outline,solid',+ },+ {+ flag: '--default-variant <variant>',+ param: 'options.defaultVariant',+ description:+ "With --variants: the variant each icon's own export draws (the first variant when omitted)",+ },+ {+ flag: '--display-name <text>',+ param: 'options.displayName',+ description:+ "The set's display name (the name in title case when omitted)",+ },+ {+ flag: '--description <text>',+ param: 'options.description',+ description: "The set's one-line description",+ },],examples: [{@@ -49,6 +72,10 @@ export const doc = {label: 'Wrap a whole icon library',cli: 'astryx experimental icon new-set outline --from @acme/glyph-library',},+ {+ label: 'Wrap a library with two variants',+ cli: 'astryx experimental icon new-set heroicons --from @heroicons/react/24/outline --variants outline,solid --default-variant outline',+ },{label: 'Preview the files',cli: 'astryx experimental icon new-set outline --dry-run --json',diff --git a/packages/cli/clients/cli/commands/experimental-icon.doc.mjs b/packages/cli/clients/cli/commands/experimental-icon.doc.mjsindex ae2d74798a..590211e660 100644--- a/packages/cli/clients/cli/commands/experimental-icon.doc.mjs+++ b/packages/cli/clients/cli/commands/experimental-icon.doc.mjs@@ -14,9 +14,9 @@ export const doc = {namespace: 'cli/commands',stability: 'experimental',summary:- 'Find an icon by meaning in the installed icon sets, with its import line',+ 'Find an icon by meaning, or build an icon set from a library (guide: astryx docs cli/experimental/icon-sets)',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.",+ "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. Start a set with `new-set <name> --from <library>`; the guide is `astryx docs cli/experimental/icon-sets`. 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@@ -43,6 +43,18 @@ export const doc = {param: 'options.limit',description: 'Max number of matches, a positive integer (default 10)',},+ {+ flag: '--definitions',+ param: 'options.definitions',+ description:+ 'Every Astryx icon definition, one line each: name, built in or not, description, words',+ },+ {+ flag: '--all-icons',+ param: 'options.allIcons',+ description:+ 'With --set and no words: every icon of that set, one line each (id, words, definitions)',+ },],examples: [{label: 'Find by meaning', cli: 'astryx experimental icon delete'},@@ -51,6 +63,10 @@ export const doc = {cli: 'astryx experimental icon outline/trash',},{label: 'Installed sets', cli: 'astryx experimental icon --list --json'},+ {+ label: 'Every icon of one set',+ cli: 'astryx experimental icon --set outline --all-icons',+ },{label: 'One set, top 3',cli: 'astryx experimental icon arrow --set outline --limit 3',diff --git a/packages/cli/clients/cli/commands/experimental.doc.mjs b/packages/cli/clients/cli/commands/experimental.doc.mjsindex 8df791dde3..b6e766c06e 100644--- a/packages/cli/clients/cli/commands/experimental.doc.mjs+++ b/packages/cli/clients/cli/commands/experimental.doc.mjs@@ -13,7 +13,8 @@ export const doc = {displayName: 'astryx experimental',namespace: 'cli/commands',stability: 'experimental',- summary: 'Try features that may change or be removed in a patch release',+ summary:+ 'Try features that may change in a patch release: icon sets (find icons, build an icon-set package)',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'],diff --git a/packages/cli/clients/cli/commands/experimental/icon.mjs b/packages/cli/clients/cli/commands/experimental/icon.mjsindex 3ccfbe214e..0f3fde693a 100644--- a/packages/cli/clients/cli/commands/experimental/icon.mjs+++ b/packages/cli/clients/cli/commands/experimental/icon.mjs@@ -68,7 +68,7 @@ export function registerExperimentalIcon(group, program) {fn: iconFn,action: async (/** @type {string[] | string | undefined} */ words,- /** @type {{list?: boolean, set?: string, limit?: string}} */ options,+ /** @type {{list?: boolean, set?: string, limit?: string, allIcons?: boolean, definitions?: boolean}} */ options,) => {const json = program.opts().json || false;const query = Array.isArray(words) ? words.join(' ') : words;@@ -83,6 +83,8 @@ export function registerExperimentalIcon(group, program) {list: options.list ?? false,set: options.set,limit,+ allIcons: options.allIcons ?? false,+ definitions: options.definitions ?? false,});} catch (e) {const err =@@ -100,13 +102,24 @@ export function registerExperimentalIcon(group, program) {resultKind: 'mixed',empty: result.data.matchCount === 0,})- : result.type === 'icon.list'+ : result.type === 'icon.definitions'? resultSet({- count: result.data.sets.length,+ count: result.data.definitions.length,resultKind: 'mixed',- empty: result.data.sets.length === 0,})- : resultSet({count: 1, resultKind: 'mixed', directMatch: true});+ : result.type === 'icon.setIcons'+ ? resultSet({+ count: result.data.icons.length,+ resultKind: 'mixed',+ empty: result.data.icons.length === 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);@@ -114,6 +127,40 @@ export function registerExperimentalIcon(group, program) {}const run = getCliInvocation();+ if (result.type === 'icon.definitions') {+ const {definitions} = result.data;+ emit(+ section(+ `Icon definitions (${definitions.length}, ${definitions.filter(each => each.builtIn).length} built-in)`,+ ),+ list(+ definitions.map(+ each =>+ `${each.name} [${each.builtIn ? 'built-in' : 'optional'}]: ${each.description} Words: ${each.words.join(', ')}.`,+ ),+ ),+ text(+ `Built-in definitions are the ones every set maps. Map one: ${run} experimental icon map <definition> <icon id>`,+ ),+ );+ return answered;+ }+ if (result.type === 'icon.setIcons') {+ const {set, iconCount, icons} = result.data;+ emit(+ section(`Icons in ${set} (${iconCount})`),+ // One line each, so a whole library reads at a glance:+ // id, then its words, then the definitions it draws.+ list(+ icons.map(+ each =>+ `${each.id}: ${each.words.join(', ')}${each.definitions.length > 0 ? ` = ${each.definitions.join(', ')}` : ''}`,+ ),+ ),+ text(`Map one: ${run} experimental icon map <definition> <id>`),+ );+ return answered;+ }if (result.type === 'icon.search') {const {query: q, matchCount, matches} = result.data;if (matches.length === 0) {@@ -129,13 +176,17 @@ export function registerExperimentalIcon(group, program) {? `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.+ // The import draws the icon's default look; its other variants+ // are named with their exports and read with `icon <set>/<id>`.records(matches.map(({variants, ...match}) => ({...match,...(variants.length > 0- ? {variant: variants.map(each => each.variant).join(', ')}+ ? {+ variant: variants+ .map(each => `${each.variant} (${each.export})`)+ .join(', '),+ }: {}),})),{@@ -175,7 +226,7 @@ export function registerExperimentalIcon(group, program) {}),...(variants.length > 0? [- section('Variants'),+ section('Other variants'),records(variants, {fields: ['variant', 'module', 'export', 'import'],}),@@ -239,6 +290,18 @@ export function registerExperimentalIcon(group, program) {},});+ /**+ * The set an authoring subcommand edits. `experimental icon` declares+ * `--set` too, so Commander gives the parent a `--set` written after a+ * subcommand's name; the subcommand reads it there.+ * @param {{set?: unknown}} options the subcommand's own options+ * @returns {string | undefined}+ */+ const setOf = options => {+ const value = options.set ?? iconCli.opts().set;+ return typeof value === 'string' ? value : undefined;+ };+/*** Run one authoring call and print its receipt, or its error.* @param {() => Promise<any>} call@@ -284,36 +347,51 @@ export function registerExperimentalIcon(group, program) {defineCommand(iconCli, iconMapCommand, {fn: iconMapFn,action: (- /** @type {string} */ definition,+ /** @type {string | undefined} */ definition,/** @type {string | undefined} */ iconId,- /** @type {{set?: string, remove?: boolean}} */ options,+ /** @type {{set?: string, remove?: boolean, pairs?: string}} */ options,) =>run(() =>iconMap(definition, iconId, {cwd: process.cwd(),- set: options.set,+ set: setOf(options),remove: options.remove ?? false,+ pairs: options.pairs,}),- ({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}".`,- ),- ),+ (/** @type {any} */ {type, data}) =>+ type === 'icon.mapMany'+ ? emit(+ text(+ `[ok] ${data.entries.filter((/** @type {{changed: boolean}} */ each) => each.changed).length} of ${data.entries.length} map entries changed in ${data.file}.`,+ ),+ list(+ data.entries.map(+ (+ /** @type {{definition: string, icon: string, previous: string | null}} */ each,+ ) =>+ `${each.definition} = "${each.icon}"${each.previous && each.previous !== each.icon ? ` (was "${each.previous}")` : ''}`,+ ),+ ),+ )+ : 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 {string | undefined} */ exportName,/** @type {Record<string, string | boolean | undefined>} */ options,) =>run(@@ -321,7 +399,7 @@ export function registerExperimentalIcon(group, program) {iconAdd(exportName, {cwd: process.cwd(),from: /** @type {string} */ (options.from),- set: /** @type {string | undefined} */ (options.set),+ set: setOf(options),definition: /** @type {string | undefined} */ (options.definition),newDefinition: /** @type {string | undefined} */ (options.newDefinition@@ -336,9 +414,27 @@ export function registerExperimentalIcon(group, program) {useDefault: options.default === true,variant: /** @type {string | undefined} */ (options.variant),id: /** @type {string | undefined} */ (options.id),+ all: options.all === true,}),result => {const cli = getCliInvocation();+ if (result.type === 'icon.addVariants') {+ const {data} = result;+ emit(+ text(+ `[ok] ${data.variant}: ${data.added} icons gained it${data.already > 0 ? `, ${data.already} already had it` : ''}, read from ${data.from}.`,+ ),+ ...(data.files.length > 0 ? [list(data.files)] : []),+ ...(data.missing.length > 0+ ? [+ text(+ `${data.missing.length} icons have no ${data.variant} export in ${data.from} and keep none: ${data.missing.join(', ')}`,+ ),+ ]+ : []),+ );+ return;+ }if (result.type === 'icon.definitionMatches') {const {matches, newDefinition} = result.data;emit(@@ -403,22 +499,54 @@ export function registerExperimentalIcon(group, program) {) => {const {root, manifest, files, written, dryRun} = data;const state = dryRun ? 'plan' : written ? 'ok' : 'unchanged';+ const refreshed = data.refreshed === true;emit(section(- dryRun- ? `New ${what} plan`- : written- ? `New ${what} added`- : `New ${what} unchanged`,+ refreshed+ ? dryRun+ ? `Refresh ${what} plan`+ : `${what[0].toUpperCase()}${what.slice(1)} refreshed`+ : dryRun+ ? `New ${what} plan`+ : written+ ? `New ${what} added`+ : `New ${what} unchanged`,),text(`[${state}] ${data.name}`),+ // What the command did (or, in a dry run, would do): never a step+ // left for the author.text(root != null- ? `${root.created ? 'Declare' : 'Use'} experimental.iconSets root ${root.path} in ${manifest}.`- : `Update ${manifest}.`,+ ? root.created+ ? `${dryRun ? 'Would declare' : 'Declared'} the experimental.iconSets root ${root.path} in ${manifest}.`+ : `The experimental.iconSets root ${root.path} in ${manifest} is unchanged.`+ : `${dryRun ? 'Would update' : 'Updated'} ${manifest}.`,),...(files.length > 0 ? [list(files)] : []),+ // What to do next comes before the long lists, so it never scrolls+ // away....(data.notes ?? []).map(note => text(`[next] ${note}`)),+ ...(data.mapped && data.mapped.length > 0+ ? [+ section(`Mapped by name (${data.mapped.length}, check each)`),+ list(+ data.mapped.map(each => `${each.definition} = ${each.icon}`),+ ),+ ]+ : []),+ ...(data.suggestions && data.suggestions.length > 0+ ? [+ section(+ `Suggestions (${data.suggestions.length} for ${new Set(data.suggestions.map(each => each.definition)).size} definitions, not written)`,+ ),+ list(+ data.suggestions.map(+ each =>+ `${each.definition} -> ${each.icon} (${each.word}): ${formatCliCommand(`astryx experimental icon map ${each.definition} ${each.icon}`)}`,+ ),+ ),+ ]+ : []),);};@@ -426,7 +554,7 @@ export function registerExperimentalIcon(group, program) {fn: iconNewSetFn,action: (/** @type {string} */ name,- /** @type {{dryRun?: boolean, from?: string, exclude?: string}} */ options,+ /** @type {{dryRun?: boolean, from?: string, exclude?: string, variants?: string, defaultVariant?: string, displayName?: string, description?: string}} */ options,) =>run(() =>@@ -435,6 +563,10 @@ export function registerExperimentalIcon(group, program) {dryRun: options.dryRun,from: options.from,exclude: options.exclude,+ variants: options.variants,+ defaultVariant: options.defaultVariant,+ displayName: options.displayName,+ description: options.description,}),printNew('icon set'),),@@ -451,7 +583,7 @@ export function registerExperimentalIcon(group, program) {iconNewDefinition(name, {cwd: process.cwd(),dryRun: options.dryRun,- set: options.set,+ set: setOf(options),description: options.description,words: options.words,icon: options.icon,diff --git a/packages/cli/clients/cli/commands/icon-authoring.test.mjs b/packages/cli/clients/cli/commands/icon-authoring.test.mjsindex 86ba4a0aae..46d6620036 100644--- a/packages/cli/clients/cli/commands/icon-authoring.test.mjs+++ b/packages/cli/clients/cli/commands/icon-authoring.test.mjs@@ -115,8 +115,14 @@ describe('experimental icon new-set --from', () => {]);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'",+ // The package's entry is the author's: the receipt names the exact line+ // and the entry stays as it was (architecture:cli-surface INV16).+ expect(body.data.files).not.toContain('index.js');+ expect(fs.readFileSync(path.join(pkg, 'index.js'), 'utf-8')).toBe(+ 'export {};\n',+ );+ expect(body.data.notes).toContain(+ "Add `export * from './icon-sets/outline/outline.generated.js';` to index.js, so the icons import from @acme/icons.",);const data = dataOf('outline');expect(data.generated).toBe('./icon-sets/outline/outline.generated.js');@@ -124,8 +130,19 @@ describe('experimental icon new-set --from', () => {{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'});+ // `delete` has the word bin, but a word alone is only a suggestion: a+ // library's bin may not mean delete. Nothing is written for it.+ expect(data.map).toEqual({});+ expect(body.data.suggestions).toContainEqual({+ definition: 'delete',+ icon: 'bin',+ word: 'bin',+ });+ // The installed library and version are the set's source.+ expect(data.source).toEqual({+ package: '@acme/glyph-library',+ version: '2.0.0',+ });const generated = fs.readFileSync(path.join(pkg, 'icon-sets', 'outline', 'outline.generated.js'),'utf-8',@@ -146,7 +163,121 @@ describe('experimental icon new-set --from', () => {'@acme/glyph-library',]);expect(again.code).toBe(0);- expect(dataOf('outline').map).toMatchObject({delete: 'bin'});+ expect(dataOf('outline').map).toEqual({});+ expect(again.body.data.suggestions).toContainEqual({+ definition: 'delete',+ icon: 'bin',+ word: 'bin',+ });+ });++ it('maps a definition only by its exact name, and prints the rest as suggestions', async () => {+ // A library icon named after a definition (`close`) maps; a word (`bin`)+ // does not.+ fs.writeFileSync(+ path.join(+ pkg,+ 'node_modules',+ '@acme',+ 'glyph-library',+ 'icons',+ 'close.js',+ ),+ 'export const Close = props => null;\n',+ );+ fs.appendFileSync(+ path.join(pkg, 'node_modules', '@acme', 'glyph-library', 'index.js'),+ "export {Close} from './icons/close.js';\n",+ );+ const res = await runCli(+ [+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ],+ pkg,+ );+ expect(res.code).toBe(0);+ expect(dataOf('outline').map).toEqual({close: 'close'});+ expect(res.stdout).toContain('Suggestions');+ expect(res.stdout).toContain('experimental icon map delete bin');+ });++ it('--variants and --default-variant declare the variants; the library license notice is copied', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ fs.writeFileSync(path.join(lib, 'LICENSE'), 'MIT License\n');+ const pkgJson = JSON.parse(+ fs.readFileSync(path.join(lib, 'package.json'), 'utf-8'),+ );+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({...pkgJson, license: 'ISC'}),+ );+ const {code, body} = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'glyphs',+ '--from',+ '@acme/glyph-library',+ '--variants',+ 'outline,solid',+ '--default-variant',+ 'outline',+ ]);+ expect(code).toBe(0);+ const data = dataOf('glyphs');+ expect(data.variants).toEqual(['outline', 'solid']);+ expect(data.default).toEqual({variant: 'outline'});+ expect(body.data.files).toContain('icon-sets/glyphs/LICENSE');+ // No TypeScript here: the receipt says the strict check needs one.+ expect(body.data.notes.join(' ')).toContain('npm install -D typescript@6');+ expect(+ fs.readFileSync(+ path.join(pkg, 'icon-sets', 'glyphs', 'LICENSE'),+ 'utf-8',+ ),+ ).toBe('MIT License\n');+ expect(+ fs.readFileSync(+ path.join(pkg, 'icon-sets', 'glyphs', 'glyphs.doc.mjs'),+ 'utf-8',+ ),+ ).toContain("license: 'ISC'");+ const check = JSON.stringify(+ JSON.parse(+ (await runCli(['integration', 'check', '--json'], pkg)).stdout,+ ),+ );+ expect(check).not.toContain('icon_license_notice_missing');+ });++ it('refuses a --default-variant that is not a variant, and --default-variant without --variants', async () => {+ const bad = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'glyphs',+ '--variants',+ 'outline,solid',+ '--default-variant',+ 'mini',+ ]);+ expect(bad.code).toBe(1);+ expect(bad.body.error).toContain('not one of --variants');+ const lone = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'glyphs',+ '--default-variant',+ 'outline',+ ]);+ expect(lone.code).toBe(1);+ expect(lone.body.error).toContain('needs --variants');});it('the theme map reads each re-exported icon through an import, so the generated module loads', async () => {@@ -239,7 +370,14 @@ describe('icon add', () => {definition: 'delete',changed: true,});- expect(first.body.data.note).toContain('export * from');+ // The entry is not wired yet: the note names the line, and the entry+ // stays the author's.+ expect(first.body.data.note).toBe(+ "Add `export * from './icon-sets/outline/outline.generated.js';` to index.js, so the icons import from @acme/icons.",+ );+ expect(fs.readFileSync(path.join(pkg, 'index.js'), 'utf-8')).toBe(+ 'export {};\n',+ );const data = dataOf('outline');expect(data.map).toEqual({delete: 'bin'});expect(data.icons[0]).toMatchObject({id: 'bin', export: 'BinIcon'});@@ -555,13 +693,13 @@ describe('experimental icon map and new-definition', () => {'experimental','icon','map',- 'rotate',+ 'orbit','cross',]);expect(unknown.code).toBe(1);expect(unknown.body.suggestions).toContainEqual(expect.objectContaining({- name: 'astryx experimental icon new-definition rotate --set outline',+ name: 'astryx experimental icon new-definition orbit --set outline',}),);const noIcon = await json([@@ -943,13 +1081,29 @@ describe('the library prefix ignores constants', () => {'GlyphXIcon','MetaIcon',]);- expect((await wrap(['--exclude', 'meta'])).code).toBe(0);- expect(exportsOf()).toEqual(['EyeIcon', 'TrashIcon', 'XIcon']);+ // Excluding meta lets the prefix come off the new ids; each existing icon+ // is the same icon (the same library export), so it keeps its public+ // export, and only meta leaves the module.+ const excluded = await wrap(['--exclude', 'meta']);+ expect(excluded.code).toBe(0);+ expect(exportsOf()).toEqual([+ 'GlyphEyeIcon',+ 'GlyphTrashIcon',+ 'GlyphXIcon',+ ]);+ expect(dataOf('outline').icons.map((/** @type {any} */ i) => i.id)).toEqual(+ ['eye', 'trash', 'x'],+ );+ expect(excluded.body.data.renamed).toEqual([+ {from: 'glyph-eye', to: 'eye'},+ {from: 'glyph-trash', to: 'trash'},+ {from: 'glyph-x', to: 'x'},+ ]);const generated = fs.readFileSync(path.join(pkg, 'icon-sets', 'outline', 'outline.generated.js'),'utf-8',);- expect(generated).not.toContain('Glyph');+ expect(generated).not.toContain('MetaIcon');expect(generated).not.toContain('README');expect(generated).not.toContain('notes');// icon add reuses the icon the wrap already made for an export, even@@ -967,9 +1121,13 @@ describe('the library prefix ignores constants', () => {expect(added.code).toBe(0);expect(added.body.data.icon).toMatchObject({id: 'trash',- export: 'TrashIcon',+ export: 'GlyphTrashIcon',});- expect(exportsOf()).toEqual(['EyeIcon', 'TrashIcon', 'XIcon']);+ expect(exportsOf()).toEqual([+ 'GlyphEyeIcon',+ 'GlyphTrashIcon',+ 'GlyphXIcon',+ ]);});it('--exclude needs --from', async () => {@@ -1033,3 +1191,1655 @@ describe('module resolution', () => {expect(check.stdout).not.toContain('icon_export_missing');}, 60_000);});++describe('experimental icon add --variant --all', () => {+ beforeEach(() => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ const pkgJson = JSON.parse(+ fs.readFileSync(path.join(lib, 'package.json'), 'utf-8'),+ );+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ ...pkgJson,+ exports: {...pkgJson.exports, './solid': './solid.js'},+ }),+ );+ // The solid module exports the same names; it has no Cross.+ fs.writeFileSync(+ path.join(lib, 'solid.js'),+ 'export function BinIcon(props) { return null; }\n',+ );+ });++ it('adds the variant for every icon the module exports by the same id, in one run', async () => {+ expect(+ (+ await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'glyphs',+ '--from',+ '@acme/glyph-library',+ '--variants',+ 'outline,solid',+ ])+ ).code,+ ).toBe(0);+ const {code, body} = await json([+ 'experimental',+ 'icon',+ 'add',+ '--variant',+ 'solid',+ '--from',+ '@acme/glyph-library/solid',+ '--all',+ ]);+ expect(code).toBe(0);+ expect(body.type).toBe('icon.addVariants');+ expect(body.data).toMatchObject({added: 1, already: 0, missing: ['cross']});+ const bin = dataOf('glyphs').icons.find(+ (/** @type {{id: string}} */ each) => each.id === 'bin',+ );+ expect(bin.variants).toEqual([{variant: 'solid', export: 'BinSolidIcon'}]);+ const generated = fs.readFileSync(+ path.join(pkg, 'icon-sets', 'glyphs', 'glyphs.generated.js'),+ 'utf-8',+ );+ expect(generated).toContain(+ "export {BinIcon as BinSolidIcon} from '@acme/glyph-library/solid';",+ );+ // Again: nothing changes.+ const again = await json([+ 'experimental',+ 'icon',+ 'add',+ '--variant',+ 'solid',+ '--from',+ '@acme/glyph-library/solid',+ '--all',+ ]);+ expect(again.body.data).toMatchObject({+ added: 0,+ already: 1,+ changed: false,+ });+ });++ it('refuses an undeclared variant, and an export name with --all', async () => {+ await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'glyphs',+ '--from',+ '@acme/glyph-library',+ ]);+ const undeclared = await json([+ 'experimental',+ 'icon',+ 'add',+ '--variant',+ 'solid',+ '--from',+ '@acme/glyph-library/solid',+ '--all',+ ]);+ expect(undeclared.code).toBe(1);+ expect(undeclared.body.error).toContain('declares no variant "solid"');+ const named = await json([+ 'experimental',+ 'icon',+ 'add',+ 'BinIcon',+ '--variant',+ 'solid',+ '--from',+ '@acme/glyph-library/solid',+ '--all',+ ]);+ expect(named.code).toBe(1);+ expect(named.body.error).toBe(+ '--all and an export name cannot be used together',+ );+ expect(named.body.code).toBe('ERR_INVALID_OPTION');+ });+});++describe('experimental icon map --pairs', () => {+ it('writes many entries in one write, all or none', async () => {+ await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ]);+ const bad = await json([+ 'experimental',+ 'icon',+ 'map',+ '--pairs',+ 'close=cross,delete=nope',+ ]);+ expect(bad.code).toBe(1);+ expect(bad.body.error).toContain('no icon "nope"');+ expect(dataOf('outline').map).toEqual({});+ const {code, body} = await json([+ 'experimental',+ 'icon',+ 'map',+ '--pairs',+ 'close=cross,delete=bin',+ ]);+ expect(code).toBe(0);+ expect(body.type).toBe('icon.mapMany');+ expect(body.data.entries).toEqual([+ {definition: 'close', icon: 'cross', previous: null, changed: true},+ {definition: 'delete', icon: 'bin', previous: null, changed: true},+ ]);+ expect(dataOf('outline').map).toEqual({close: 'cross', delete: 'bin'});+ // The theme map follows: close is built in.+ expect(+ fs.readFileSync(+ path.join(pkg, 'icon-sets', 'outline', 'outline.generated.js'),+ 'utf-8',+ ),+ ).toContain('close: createElement(CrossIcon,');+ });+});++describe('experimental icon new-set receipt', () => {+ it('takes --display-name and --description, and suggests icons by name words, never one map already names', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ fs.writeFileSync(+ path.join(lib, 'icons', 'video.js'),+ 'export const VideoCamera = props => null;\nexport const Camera = props => null;\nexport const Clipboard = props => null;\n',+ );+ fs.appendFileSync(+ path.join(lib, 'index.js'),+ "export {VideoCamera, Camera, Clipboard} from './icons/video.js';\n",+ );+ const {code, body} = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ '--display-name',+ 'Acme Outline',+ '--description',+ 'Outline icons from the Acme glyph library.',+ ]);+ expect(code).toBe(0);+ const doc = fs.readFileSync(+ path.join(pkg, 'icon-sets', 'outline', 'outline.doc.mjs'),+ 'utf-8',+ );+ expect(doc).toContain("displayName: 'Acme Outline'");+ expect(doc).toContain(+ "description: 'Outline icons from the Acme glyph library.'",+ );+ // `video` gets video-camera (its name's words) before camera (a word);+ // clipboard is mapped to the clipboard definition, so copy never gets it.+ const video = body.data.suggestions.filter(+ (/** @type {{definition: string}} */ each) => each.definition === 'video',+ );+ expect(+ video.map((/** @type {{icon: string}} */ each) => each.icon),+ ).toEqual(['video-camera', 'camera']);+ expect(dataOf('outline').map).toMatchObject({clipboard: 'clipboard'});+ expect(+ body.data.suggestions.some(+ (/** @type {{icon: string}} */ each) => each.icon === 'clipboard',+ ),+ ).toBe(false);+ });+});++describe('experimental icon new-set: aliases, providers, exclude, peers', () => {+ beforeEach(() => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ fs.writeFileSync(+ path.join(lib, 'icons', 'extra.js'),+ [+ 'export const Trash = props => null;',+ 'export const PanelLeftClose = props => null;',+ 'export function GlyphProvider(props) { return props.children; }',+ 'export const Meta = props => null;',+ '',+ ].join('\n'),+ );+ fs.appendFileSync(+ path.join(lib, 'index.js'),+ "export {Trash, Trash as Trash2, PanelLeftClose, GlyphProvider, Meta} from './icons/extra.js';\n",+ );+ });++ it('records other names as words, skips providers, keeps --exclude, and declares peers', async () => {+ fs.writeFileSync(+ path.join(pkg, 'package.json'),+ JSON.stringify({+ ...JSON.parse(fs.readFileSync(path.join(pkg, 'package.json'), 'utf-8')),+ dependencies: {'@acme/glyph-library': '^2.0.0', react: '^19.0.0'},+ }),+ );+ const first = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ '--exclude',+ 'Meta',+ ]);+ expect(first.code).toBe(0);+ let data = dataOf('outline');+ const ids = data.icons.map((/** @type {{id: string}} */ each) => each.id);+ expect(ids).toContain('trash');+ expect(ids).not.toContain('trash-2');+ expect(ids).not.toContain('glyph-provider');+ expect(ids).not.toContain('meta');+ expect(data.exclude).toEqual(['Meta']);+ // The receipt names the exports it left out.+ expect(first.body.data.notes.join(' ')).toMatch(+ /Left out \d+ exports that are not icons: .*GlyphProvider/u,+ );+ expect(+ data.icons.find((/** @type {{id: string}} */ each) => each.id === 'trash')+ .words,+ ).toContain('trash-2');+ // close is never suggested panel-left-close: a suggestion starts with+ // the definition's name.+ expect(+ first.body.data.suggestions.some(+ (/** @type {{definition: string, icon: string}} */ each) =>+ each.definition === 'close' && each.icon === 'panel-left-close',+ ),+ ).toBe(false);+ // Peers: the receipt names the exact JSON to add; package.json keeps its+ // dependencies as they were (architecture:cli-surface INV16).+ const manifest = JSON.parse(+ fs.readFileSync(path.join(pkg, 'package.json'), 'utf-8'),+ );+ expect(manifest).not.toHaveProperty('peerDependencies');+ expect(manifest.dependencies).toEqual({+ '@acme/glyph-library': '^2.0.0',+ react: '^19.0.0',+ });+ expect(first.body.data.notes).toContainEqual(+ expect.stringMatching(+ /^Declare the peers your set needs; add to package\.json "peerDependencies": `\{"react": ">=18", "@types\/react": ">=18", "@astryxdesign\/cli": ">=[^"]+"\}` and to "peerDependenciesMeta": `\{"@types\/react": \{"optional": true\}, "@astryxdesign\/cli": \{"optional": true\}\}`\.$/u,+ ),+ );++ // A refresh without --exclude still leaves Meta out, and says it refreshed.+ const again = await runCli(+ [+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ],+ pkg,+ );+ expect(again.code).toBe(0);+ expect(again.stdout).toContain('Icon set refreshed');+ expect(again.stdout).not.toContain('New icon set added');+ data = dataOf('outline');+ expect(+ data.icons.some((/** @type {{id: string}} */ each) => each.id === 'meta'),+ ).toBe(false);++ // map takes the kebab id of a definition and another name of an icon.+ const mapped = await json([+ 'experimental',+ 'icon',+ 'map',+ 'eye-slash',+ 'cross',+ ]);+ expect(mapped.code).toBe(0);+ expect(mapped.body.data).toMatchObject({+ definition: 'eyeSlash',+ icon: 'cross',+ });+ const alias = await json([+ 'experimental',+ 'icon',+ 'map',+ 'delete',+ 'trash-2',+ ]);+ expect(alias.code).toBe(0);+ expect(alias.body.data.icon).toBe('trash');+ // The same other name as the library exports it.+ const libraryName = await json([+ 'experimental',+ 'icon',+ 'map',+ 'delete',+ 'Trash2',+ ]);+ expect(libraryName.code, JSON.stringify(libraryName.body)).toBe(0);+ expect(libraryName.body.data.icon).toBe('trash');+ const pairs = await json([+ 'experimental',+ 'icon',+ 'map',+ '--pairs',+ 'more-horizontal=bin,delete=trash-2',+ ]);+ expect(pairs.code).toBe(0);+ expect(dataOf('outline').map).toMatchObject({+ moreHorizontal: 'bin',+ delete: 'trash',+ });+ });+});++describe('blind run 3 fixes', () => {+ it('refreshes a set whose icons have variants', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ const pkgJson = JSON.parse(+ fs.readFileSync(path.join(lib, 'package.json'), 'utf-8'),+ );+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ ...pkgJson,+ exports: {...pkgJson.exports, './solid': './solid.js'},+ }),+ );+ fs.writeFileSync(+ path.join(lib, 'solid.js'),+ 'export function BinIcon(props) { return null; }\n',+ );+ const create = [+ 'experimental',+ 'icon',+ 'new-set',+ 'glyphs',+ '--from',+ '@acme/glyph-library',+ '--variants',+ 'outline,solid',+ ];+ expect((await json(create)).code).toBe(0);+ expect(+ (+ await json([+ 'experimental',+ 'icon',+ 'add',+ '--variant',+ 'solid',+ '--from',+ '@acme/glyph-library/solid',+ '--all',+ ])+ ).code,+ ).toBe(0);+ const again = await json(create);+ expect(again.code).toBe(0);+ expect(again.body.data.refreshed).toBe(true);+ const bin = dataOf('glyphs').icons.find(+ (/** @type {{id: string}} */ each) => each.id === 'bin',+ );+ expect(bin.variants).toEqual([{variant: 'solid', export: 'BinSolidIcon'}]);+ });++ it('suggests the export with its Icon suffix, lists a set by id, and says what new-set did', async () => {+ const created = await runCli(+ [+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ],+ pkg,+ );+ expect(created.stdout).toContain(+ 'Declared the experimental.iconSets root ./icon-sets in astryx.integration.mjs.',+ );+ expect(created.stdout).toContain(+ "Add `export * from './icon-sets/outline/outline.generated.js';` to index.js, so the icons import from @acme/icons.",+ );+ const missing = await json([+ 'experimental',+ 'icon',+ 'add',+ 'Rocket',+ '--from',+ '@acme/glyph-library',+ ]);+ expect(missing.code).toBe(1);+ const bin = await json([+ 'experimental',+ 'icon',+ 'add',+ 'Bi',+ '--from',+ '@acme/glyph-library',+ ]);+ expect(bin.code).toBe(1);+ fs.appendFileSync(+ path.join(pkg, 'node_modules', '@acme', 'glyph-library', 'index.js'),+ "export {Bin as XMarkIcon} from './icons/bin.js';\n",+ );+ const suffix = await json([+ 'experimental',+ 'icon',+ 'add',+ 'XMark',+ '--from',+ '@acme/glyph-library',+ ]);+ expect(suffix.code).toBe(1);+ expect(suffix.body.suggestions[0]).toMatchObject({name: 'XMarkIcon'});+ const listed = await json([+ 'experimental',+ 'icon',+ '--set',+ 'outline',+ '--all-icons',+ ]);+ expect(listed.code).toBe(0);+ expect(listed.body.type).toBe('icon.setIcons');+ expect(+ listed.body.data.icons.map((/** @type {{id: string}} */ each) => each.id),+ ).toEqual(['bin', 'cross']);+ const text = await runCli(+ ['experimental', 'icon', '--set', 'outline', '--all-icons'],+ pkg,+ );+ expect(text.stdout).toContain('Icons in outline (2)');+ expect(text.stdout).toMatch(/^- bin: bin$/mu);+ });+});++describe('blind run 4 fixes', () => {+ it('names a ./ file icon as written', async () => {+ await json(['experimental', 'icon', 'new-set', 'outline']);+ fs.mkdirSync(path.join(pkg, 'src', 'icons'), {recursive: true});+ fs.writeFileSync(+ path.join(pkg, 'src', 'icons', 'check-double.js'),+ 'export const CheckDouble = props => null;\nexport const CheckDoubleSolid = props => null;\n',+ );+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ 'CheckDouble',+ '--from',+ './src/icons/check-double.js',+ '--definition',+ 'checkDouble',+ ]);+ expect(added.code).toBe(0);+ expect(added.body.data.icon).toMatchObject({+ id: 'check-double',+ export: 'CheckDoubleIcon',+ });+ });++ it('--definitions lists every definition, marking built-ins', async () => {+ const {code, body} = await json(['experimental', 'icon', '--definitions']);+ expect(code).toBe(0);+ expect(body.type).toBe('icon.definitions');+ const close = body.data.definitions.find(+ (/** @type {{name: string}} */ each) => each.name === 'close',+ );+ expect(close).toMatchObject({builtIn: true});+ expect(close.words).toContain('x');+ const text = await runCli(['experimental', 'icon', '--definitions'], pkg);+ expect(text.stdout).toMatch(/^- close \[built-in\]: /mu);+ });++ it('suggests an icon by another name its library gives it, and new-set names the typecheck script and a description note', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ fs.writeFileSync(+ path.join(lib, 'icons', 'face.js'),+ 'export const FaceSlightlySmiling = props => null;\n',+ );+ fs.appendFileSync(+ path.join(lib, 'index.js'),+ "export {FaceSlightlySmiling, FaceSlightlySmiling as Smile} from './icons/face.js';\n",+ );+ const {code, body} = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ]);+ expect(code).toBe(0);+ expect(body.data.suggestions).toContainEqual({+ definition: 'emoji',+ icon: 'face-slightly-smiling',+ word: 'smile',+ });+ expect(body.data.notes.join(' ')).toContain('description is a placeholder');+ const manifest = JSON.parse(+ fs.readFileSync(path.join(pkg, 'package.json'), 'utf-8'),+ );+ // The script is the author's to add: the receipt names the exact line.+ expect(manifest).not.toHaveProperty('scripts');+ expect(body.data.notes).toContain(+ 'Run `integration check --strict` in your build; add to package.json "scripts": `"typecheck": "astryx integration check --strict"`.',+ );+ });+});++describe('blind run 5 fixes', () => {+ it('names the ./ source folder files needs, maps by export name, and suggests by spelling and stem', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ fs.writeFileSync(+ path.join(lib, 'icons', 'more.js'),+ [+ 'export const LightBulb = props => null;',+ 'export const TrendingUp = props => null;',+ 'export const LockOpen = props => null;',+ '',+ ].join('\n'),+ );+ fs.appendFileSync(+ path.join(lib, 'index.js'),+ "export {LightBulb, TrendingUp, LockOpen, LockOpen as Unlock} from './icons/more.js';\n",+ );+ fs.writeFileSync(+ path.join(pkg, 'package.json'),+ JSON.stringify({+ ...JSON.parse(fs.readFileSync(path.join(pkg, 'package.json'), 'utf-8')),+ files: ['index.js', 'icon-sets', 'astryx.integration.mjs'],+ }),+ );+ const {body} = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ]);+ const pairs = body.data.suggestions.map(+ (/** @type {{definition: string, icon: string}} */ each) =>+ `${each.definition}>${each.icon}`,+ );+ expect(pairs).toContain('lightbulb>light-bulb');+ expect(pairs).toContain('trendUp>trending-up');+ expect(pairs).toContain('unlock>lock-open');+ // map takes the export name, in any case.+ const byExport = await json([+ 'experimental',+ 'icon',+ 'map',+ 'close',+ 'CrossIcon',+ ]);+ expect(byExport.body.data).toMatchObject({+ definition: 'close',+ icon: 'cross',+ });+ // A ./ file's folder is named for files, so the icon ships; files stays+ // the author's (architecture:cli-surface INV16).+ fs.mkdirSync(path.join(pkg, 'art'), {recursive: true});+ fs.writeFileSync(+ path.join(pkg, 'art', 'check-double.js'),+ 'export const CheckDouble = props => null;\n',+ );+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ 'CheckDouble',+ '--from',+ './art/check-double.js',+ '--definition',+ 'checkDouble',+ ]);+ expect(added.code).toBe(0);+ expect(added.body.data.files).not.toContain('package.json');+ expect(+ JSON.parse(fs.readFileSync(path.join(pkg, 'package.json'), 'utf-8'))+ .files,+ ).toEqual(['index.js', 'icon-sets', 'astryx.integration.mjs']);+ expect(added.body.data.note).toContain(+ './art/check-double.js is not in package.json "files", so it would not be published; set "files" to `["index.js","icon-sets","astryx.integration.mjs","art"]`.',+ );+ const text = await runCli(['experimental', 'icon', '--definitions'], pkg);+ expect(text.stdout).toMatch(/^- activity \[optional\]: /mu);+ });+});++describe('blind run 6 fixes', () => {+ it('never suggests the opposite direction, and names only a ./ file folder for files', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ fs.writeFileSync(+ path.join(lib, 'icons', 'dots.js'),+ 'export const EllipsisHorizontal = props => null;\nexport const EllipsisVertical = props => null;\n',+ );+ fs.appendFileSync(+ path.join(lib, 'index.js'),+ "export {EllipsisHorizontal, EllipsisVertical} from './icons/dots.js';\n",+ );+ const {body} = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ]);+ const more = body.data.suggestions+ .filter(+ (/** @type {{definition: string}} */ each) =>+ each.definition === 'moreHorizontal',+ )+ .map((/** @type {{icon: string}} */ each) => each.icon);+ expect(more).toEqual(['ellipsis-horizontal']);+ const manifestFile = path.join(pkg, 'package.json');+ fs.writeFileSync(+ manifestFile,+ JSON.stringify({+ ...JSON.parse(fs.readFileSync(manifestFile, 'utf-8')),+ files: ['index.js', 'icon-sets'],+ }),+ );+ fs.mkdirSync(path.join(pkg, 'src', 'icons'), {recursive: true});+ fs.writeFileSync(+ path.join(pkg, 'src', 'icons', 'check-double.js'),+ 'export const CheckDouble = props => null;\n',+ );+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ 'CheckDouble',+ '--from',+ './src/icons/check-double.js',+ '--definition',+ 'checkDouble',+ ]);+ expect(added.body.data.note).toContain(+ 'set "files" to `["index.js","icon-sets","src/icons"]`.',+ );+ });+});++describe('blind run 7 fixes', () => {+ it('a refresh rewrites the description, lists only files it changes, and words leave out bare numbers', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ fs.writeFileSync(+ path.join(lib, 'icons', 'volume.js'),+ 'export const Volume2 = props => null;\n',+ );+ fs.appendFileSync(+ path.join(lib, 'index.js'),+ "export {Volume2} from './icons/volume.js';\n",+ );+ const args = [+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ];+ await json(args);+ const volume = dataOf('outline').icons.find(+ (/** @type {{id: string}} */ each) => each.id === 'volume-2',+ );+ expect(volume.words).toEqual(['volume']);+ const dry = await json([...args, '--dry-run']);+ expect(dry.body.data.files).toEqual([]);+ const described = await json([+ ...args,+ '--description',+ "Acme's outline icons.",+ ]);+ expect(described.body.data.files).toEqual([+ 'icon-sets/outline/outline.doc.mjs',+ ]);+ expect(+ fs.readFileSync(+ path.join(pkg, 'icon-sets', 'outline', 'outline.doc.mjs'),+ 'utf-8',+ ),+ ).toContain("description: 'Acme\\'s outline icons.',");+ });+});++describe('blind run 8 fixes', () => {+ it('a refresh lists every exact-name entry for review again', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ fs.writeFileSync(+ path.join(lib, 'icons', 'close.js'),+ 'export const Close = props => null;\n',+ );+ fs.appendFileSync(+ path.join(lib, 'index.js'),+ "export {Close} from './icons/close.js';\n",+ );+ const args = [+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ];+ expect((await json(args)).body.data.mapped).toEqual([+ {definition: 'close', icon: 'close'},+ ]);+ const again = await json([...args, '--dry-run']);+ expect(again.body.data.mapped).toEqual([+ {definition: 'close', icon: 'close'},+ ]);+ });+});++describe('package wiring stays the author’s', () => {+ /**+ * Every issue the check reports, by code and message.+ * @returns {Promise<Array<{code: string, message: string}>>}+ */+ async function checkIssues() {+ const body = JSON.parse(+ (await runCli(['integration', 'check', '--json'], pkg)).stdout,+ );+ /** @type {Array<{code: string, message: string}>} */+ const found = [];+ /** @param {unknown} node */+ const walk = node => {+ if (Array.isArray(node)) node.forEach(walk);+ else if (node && typeof node === 'object') {+ const each = /** @type {Record<string, unknown>} */ (node);+ if (typeof each.code === 'string' && typeof each.message === 'string') {+ found.push({code: each.code, message: each.message});+ }+ Object.values(each).forEach(walk);+ }+ };+ walk(body.data);+ return found;+ }++ it('integration check names the same entry change as the new-set receipt, once, until the author makes it', async () => {+ const {body} = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ]);+ const note =+ "Add `export * from './icon-sets/outline/outline.generated.js';` to index.js, so the icons import from @acme/icons.";+ expect(body.data.notes).toContain(note);+ const missing = (await checkIssues()).filter(+ each => each.code === 'icon_export_missing',+ );+ expect([...new Set(missing.map(each => each.message))]).toEqual([+ `Icon set "outline": its icons are not exported from "@acme/icons" yet. ${note}`,+ ]);+ // The author adds the line; the finding is gone.+ fs.appendFileSync(+ path.join(pkg, 'index.js'),+ "export * from './icon-sets/outline/outline.generated.js';\n",+ );+ expect(+ (await checkIssues()).filter(each => each.code === 'icon_export_missing'),+ ).toEqual([]);+ });++ it('integration check never fails a built or CommonJS entry over the wiring it cannot read', async () => {+ fs.writeFileSync(+ path.join(pkg, 'package.json'),+ JSON.stringify({+ ...JSON.parse(fs.readFileSync(path.join(pkg, 'package.json'), 'utf-8')),+ exports: {'.': './dist/index.cjs'},+ }),+ );+ fs.mkdirSync(path.join(pkg, 'dist'));+ fs.writeFileSync(+ path.join(pkg, 'dist', 'index.cjs'),+ 'module.exports = {};\n',+ );+ await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ]);+ expect(fs.readFileSync(path.join(pkg, 'dist', 'index.cjs'), 'utf-8')).toBe(+ 'module.exports = {};\n',+ );+ expect(+ (await checkIssues()).filter(each =>+ each.message.includes('are not exported from'),+ ),+ ).toEqual([]);+ });+});++describe('a refresh that first records the source', () => {+ it('copies the library notices and takes its license, as new-set --from does', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ fs.writeFileSync(path.join(lib, 'LICENSE'), 'ISC License\n');+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ ...JSON.parse(fs.readFileSync(path.join(lib, 'package.json'), 'utf-8')),+ license: 'ISC',+ }),+ );+ expect(+ (await json(['experimental', 'icon', 'new-set', 'glyphs'])).code,+ ).toBe(0);+ const doc = path.join(pkg, 'icon-sets', 'glyphs', 'glyphs.doc.mjs');+ expect(fs.readFileSync(doc, 'utf-8')).toContain("license: 'MIT'");+ const pkgBefore = fs.readFileSync(path.join(pkg, 'package.json'), 'utf-8');++ const refreshed = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'glyphs',+ '--from',+ '@acme/glyph-library',+ ]);+ expect(refreshed.code).toBe(0);+ expect(refreshed.body.data.refreshed).toBe(true);+ expect(refreshed.body.data.files).toEqual(+ expect.arrayContaining([+ 'icon-sets/glyphs/glyphs.doc.mjs',+ 'icon-sets/glyphs/LICENSE',+ ]),+ );+ expect(dataOf('glyphs').source).toEqual({+ package: '@acme/glyph-library',+ version: '2.0.0',+ });+ expect(+ fs.readFileSync(+ path.join(pkg, 'icon-sets', 'glyphs', 'LICENSE'),+ 'utf-8',+ ),+ ).toBe('ISC License\n');+ expect(fs.readFileSync(doc, 'utf-8')).toContain("license: 'ISC'");+ expect(refreshed.body.data.notes).toContain(+ 'The set\'s license in icon-sets/glyphs/glyphs.doc.mjs changed from "MIT" to "ISC", the license of @acme/glyph-library, whose artwork it now wraps. Edit it if the artwork\'s license differs.',+ );+ // The package's own license is the author's (INV16).+ expect(fs.readFileSync(path.join(pkg, 'package.json'), 'utf-8')).toBe(+ pkgBefore,+ );+ const strict = await runCli(+ ['integration', 'check', '--strict', '--json'],+ pkg,+ );+ expect(strict.stdout).not.toContain('icon_license_notice_missing');++ // A later refresh keeps the author's license.+ fs.writeFileSync(+ doc,+ fs+ .readFileSync(doc, 'utf-8')+ .replace("license: 'ISC'", "license: 'ISC AND CC-BY-4.0'"),+ );+ await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'glyphs',+ '--from',+ '@acme/glyph-library',+ ]);+ expect(fs.readFileSync(doc, 'utf-8')).toContain(+ "license: 'ISC AND CC-BY-4.0'",+ );+ });+});++describe('a first-source refresh over a license the author chose', () => {+ it('keeps it, and the receipt names both licenses', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ ...JSON.parse(fs.readFileSync(path.join(lib, 'package.json'), 'utf-8')),+ license: 'ISC',+ }),+ );+ await json(['experimental', 'icon', 'new-set', 'glyphs']);+ const doc = path.join(pkg, 'icon-sets', 'glyphs', 'glyphs.doc.mjs');+ fs.writeFileSync(+ doc,+ fs+ .readFileSync(doc, 'utf-8')+ .replace("license: 'MIT'", "license: 'CC-BY-4.0'"),+ );+ const refreshed = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'glyphs',+ '--from',+ '@acme/glyph-library',+ ]);+ expect(refreshed.code).toBe(0);+ expect(fs.readFileSync(doc, 'utf-8')).toContain("license: 'CC-BY-4.0'");+ expect(refreshed.body.data.notes).toContain(+ 'The set\'s license in icon-sets/glyphs/glyphs.doc.mjs stays "CC-BY-4.0", which you set; @acme/glyph-library is licensed "ISC". Change it if the artwork is the library\'s.',+ );+ });+});++describe('map names an icon only by its id, export name, or another library name', () => {+ beforeEach(() => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ fs.writeFileSync(+ path.join(lib, 'icons', 'glass.js'),+ 'export const MagnifyingGlass = props => null;\n',+ );+ fs.appendFileSync(+ path.join(lib, 'index.js'),+ "export {MagnifyingGlass, MagnifyingGlass as Search} from './icons/glass.js';\n",+ );+ });++ it('refuses a word an icon carries, with the icons that carry it, and writes nothing', async () => {+ await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ]);+ const dataFile = path.join(+ pkg,+ 'icon-sets',+ 'outline',+ 'outline.icons.json',+ );+ const before = fs.readFileSync(dataFile, 'utf-8');++ const word = await json([+ 'experimental',+ 'icon',+ 'map',+ 'moreHorizontal',+ 'glass',+ ]);+ expect(word.code).toBe(1);+ expect(word.body.error).toContain('has no icon "glass"');+ expect(word.body.error).toContain('a word it carries is not its name');+ expect(+ word.body.suggestions.map(+ (/** @type {{name: string}} */ each) => each.name,+ ),+ ).toContain('magnifying-glass');++ const pairs = await json([+ 'experimental',+ 'icon',+ 'map',+ '--pairs',+ 'close=cross,moreHorizontal=glass',+ ]);+ expect(pairs.code).toBe(1);+ expect(pairs.body.error).toContain('Nothing was written');+ expect(fs.readFileSync(dataFile, 'utf-8')).toBe(before);++ // The id, the export name in any case, and another library name map.+ for (const [given, id] of [+ ['magnifying-glass', 'magnifying-glass'],+ ['magnifyingglassicon', 'magnifying-glass'],+ ['MagnifyingGlass', 'magnifying-glass'],+ ['search', 'magnifying-glass'],+ ['Search', 'magnifying-glass'],+ ]) {+ const ok = await json(['experimental', 'icon', 'map', 'search', given]);+ expect(ok.code, given).toBe(0);+ expect(ok.body.data.icon, given).toBe(id);+ }+ });+});++describe('a refresh after the id rule changes', () => {+ it('carries a renamed icon’s map entries, variants, and words, matched by its export, and reports the rename', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ fs.writeFileSync(+ path.join(lib, 'icons', 'squares.js'),+ 'export const Squares2X2Icon = props => null;\n',+ );+ fs.appendFileSync(+ path.join(lib, 'index.js'),+ "export {Squares2X2Icon} from './icons/squares.js';\n",+ );+ const args = [+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ '--variants',+ 'outline,solid',+ ];+ expect((await json(args)).code).toBe(0);+ // Rewrite the data file as the old id rule wrote it: `squares-2-x2`,+ // with that rule's words, a word the author added, a variant, and a map+ // entry.+ const dataFile = path.join(+ pkg,+ 'icon-sets',+ 'outline',+ 'outline.icons.json',+ );+ const data = dataOf('outline');+ const icon = data.icons.find(+ (/** @type {{export: string}} */ each) =>+ each.export === 'Squares2X2Icon',+ );+ Object.assign(icon, {+ id: 'squares-2-x2',+ words: ['squares', 'x2', 'tiles'],+ variants: [{variant: 'solid', export: 'Squares2X2SolidIcon'}],+ });+ data.map = {...data.map, moreHorizontal: 'squares-2-x2'};+ fs.writeFileSync(dataFile, `${JSON.stringify(data, null, 2)}\n`);++ const refreshed = await json(args);+ expect(refreshed.code).toBe(0);+ expect(refreshed.body.data.renamed).toEqual([+ {from: 'squares-2-x2', to: 'squares-2x2'},+ ]);+ const notes = refreshed.body.data.notes.join(' ');+ expect(notes).toContain('squares-2-x2 -> squares-2x2');+ expect(notes).not.toContain('no longer exports');+ const after = dataOf('outline');+ expect(after.map.moreHorizontal).toBe('squares-2x2');+ const renamed = after.icons.find(+ (/** @type {{export: string}} */ each) =>+ each.export === 'Squares2X2Icon',+ );+ expect(renamed).toMatchObject({+ id: 'squares-2x2',+ variants: [{variant: 'solid', export: 'Squares2X2SolidIcon'}],+ });+ expect(renamed.words).toContain('tiles');+ expect(renamed.words).not.toContain('x2');+ expect(+ after.icons.some(+ (/** @type {{id: string}} */ each) => each.id === 'squares-2-x2',+ ),+ ).toBe(false);+ // The export stays in the generated module.+ expect(+ fs.readFileSync(+ path.join(pkg, 'icon-sets', 'outline', 'outline.generated.js'),+ 'utf-8',+ ),+ ).toContain('Squares2X2Icon');+ });+});++describe('add --variant --all after the id rule changes', () => {+ it('meets an icon whose id an older rule wrote by its export name', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ ...JSON.parse(fs.readFileSync(path.join(lib, 'package.json'), 'utf-8')),+ exports: {'.': './index.js', './solid': './solid.js'},+ }),+ );+ fs.writeFileSync(+ path.join(lib, 'icons', 'squares.js'),+ 'export const Squares2X2Icon = props => null;\n',+ );+ fs.appendFileSync(+ path.join(lib, 'index.js'),+ "export {Squares2X2Icon} from './icons/squares.js';\n",+ );+ fs.writeFileSync(+ path.join(lib, 'solid.js'),+ 'export const Squares2X2Icon = props => null;\n',+ );+ await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ '--variants',+ 'outline,solid',+ ]);+ const dataFile = path.join(+ pkg,+ 'icon-sets',+ 'outline',+ 'outline.icons.json',+ );+ const data = dataOf('outline');+ data.icons.find(+ (/** @type {{export: string}} */ each) =>+ each.export === 'Squares2X2Icon',+ ).id = 'squares-2-x2';+ fs.writeFileSync(dataFile, `${JSON.stringify(data, null, 2)}\n`);+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ '--variant',+ 'solid',+ '--from',+ '@acme/glyph-library/solid',+ '--all',+ ]);+ expect(added.code).toBe(0);+ expect(added.body.data.missing).not.toContain('squares-2-x2');+ expect(+ dataOf('outline').icons.find(+ (/** @type {{id: string}} */ each) => each.id === 'squares-2-x2',+ ).variants,+ ).toEqual([{variant: 'solid', export: 'Squares2X2SolidIcon'}]);+ });+});++describe('--set through the CLI selects the set add, map, and new-definition edit', () => {+ beforeEach(async () => {+ for (const set of ['one', 'two']) {+ await json([+ 'experimental',+ 'icon',+ 'new-set',+ set,+ '--from',+ '@acme/glyph-library',+ ]);+ }+ // A third set that is withdrawn: its data file is not JSON.+ const broken = path.join(pkg, 'icon-sets', 'lines');+ fs.mkdirSync(broken, {recursive: true});+ fs.writeFileSync(+ path.join(broken, 'lines.doc.mjs'),+ fs+ .readFileSync(path.join(pkg, 'icon-sets', 'one', 'one.doc.mjs'), 'utf8')+ .replace("name: 'one'", "name: 'lines'"),+ );+ fs.writeFileSync(path.join(broken, 'lines.icons.json'), '{nope');+ });++ /** @type {Array<[string, (set: string) => string[], string]>} the command, its words, the icon it maps */+ const COMMANDS = [+ [+ 'map',+ set => ['experimental', 'icon', 'map', 'delete', 'bin', '--set', set],+ 'bin',+ ],+ [+ 'add',+ set => [+ 'experimental',+ 'icon',+ 'add',+ 'Rocket',+ '--from',+ '@acme/glyph-library/rocket',+ '--default',+ '--definition',+ 'delete',+ '--set',+ set,+ ],+ 'rocket',+ ],+ [+ 'new-definition',+ set => [+ 'experimental',+ 'icon',+ 'new-definition',+ 'binIt',+ '--description',+ 'Put something in the bin.',+ '--words',+ 'bin',+ '--icon',+ 'bin',+ '--set',+ set,+ ],+ 'bin',+ ],+ ];++ it.each(COMMANDS)(+ '%s --set edits that set and leaves the other',+ async (_name, args, id) => {+ const before = fs.readFileSync(+ path.join(pkg, 'icon-sets', 'one', 'one.icons.json'),+ 'utf-8',+ );+ const res = await json(args('two'));+ expect(res.code, JSON.stringify(res.body)).toBe(0);+ expect(+ fs.readFileSync(+ path.join(pkg, 'icon-sets', 'one', 'one.icons.json'),+ 'utf-8',+ ),+ ).toBe(before);+ expect(Object.values(dataOf('two').map)).toContain(id);+ },+ );++ it.each(COMMANDS)('%s --set with a missing set', async (_name, args) => {+ const res = await json(args('nope'));+ expect(res.code).toBe(1);+ expect(res.body).toMatchObject({+ code: 'ERR_NOT_FOUND',+ error: 'No icon set named "nope" in this package',+ });+ });++ it.each(COMMANDS)('%s --set with a withdrawn set', async (_name, args) => {+ const res = await json(args('lines'));+ expect(res.code).toBe(1);+ expect(res.body.code).toBe('ERR_NOT_FOUND');+ expect(res.body.error).toMatch(+ /^Icon set "lines" is in this package but withdrawn: .*not valid JSON/u,+ );+ });+});++describe('a refresh of a set wrapped from a prefixed library by an older id rule', () => {+ it('matches each icon by the library export it re-exports, and keeps its public export byte for byte', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'hero');+ fs.mkdirSync(lib, {recursive: true});+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ name: '@acme/hero',+ version: '1.0.0',+ type: 'module',+ exports: {'.': './index.js'},+ }),+ );+ fs.writeFileSync(+ path.join(lib, 'index.js'),+ [+ 'export const HiSquares2X2Icon = props => null;',+ 'export const HiTrashIcon = props => null;',+ 'export const HiXMarkIcon = props => null;',+ '',+ ].join('\n'),+ );+ const args = [+ 'experimental',+ 'icon',+ 'new-set',+ 'hero',+ '--from',+ '@acme/hero',+ ];+ expect((await json(args)).code).toBe(0);+ const setDir = path.join(pkg, 'icon-sets', 'hero');+ const generatedFile = path.join(setDir, 'hero.generated.js');+ const typesFile = path.join(setDir, 'hero.generated.d.ts');+ // Rewrite the set as an older id rule wrote it: id `squares-2-x2`,+ // public export `Squares2X2Icon`, re-exporting `HiSquares2X2Icon`, with+ // a map entry and an author's word.+ const data = dataOf('hero');+ const squares = data.icons.find(+ (/** @type {{id: string}} */ each) => each.id === 'squares-2x2',+ );+ const newName = squares.export;+ Object.assign(squares, {+ id: 'squares-2-x2',+ export: 'Squares2X2Icon',+ words: ['squares', 'x2', 'grid-view'],+ });+ data.map = {...data.map, moreHorizontal: 'squares-2-x2'};+ fs.writeFileSync(+ path.join(setDir, 'hero.icons.json'),+ `${JSON.stringify(data, null, 2)}\n`,+ );+ for (const file of [generatedFile, typesFile]) {+ fs.writeFileSync(+ file,+ fs.readFileSync(file, 'utf-8').replaceAll(newName, 'Squares2X2Icon'),+ );+ }+ expect(fs.readFileSync(generatedFile, 'utf-8')).toContain(+ "export {HiSquares2X2Icon as Squares2X2Icon} from '@acme/hero';",+ );++ const refreshed = await json(args);+ expect(refreshed.code).toBe(0);+ expect(refreshed.body.data.renamed).toEqual([+ {from: 'squares-2-x2', to: 'squares-2x2'},+ ]);+ expect(refreshed.body.data.notes.join(' ')).not.toContain(+ 'no longer exports',+ );+ const after = dataOf('hero');+ expect(after.map.moreHorizontal).toBe('squares-2x2');+ const kept = after.icons.find(+ (/** @type {{id: string}} */ each) => each.id === 'squares-2x2',+ );+ expect(kept.export).toBe('Squares2X2Icon');+ expect(kept.words).toContain('grid-view');+ const generated = fs.readFileSync(generatedFile, 'utf-8');+ expect(generated).toContain(+ "export {HiSquares2X2Icon as Squares2X2Icon} from '@acme/hero';",+ );+ expect(generated).not.toContain(+ newName === 'Squares2X2Icon' ? '\0' : newName,+ );+ // The set still checks: its types match its module, and, once the entry+ // re-exports it, every icon export resolves.+ fs.appendFileSync(+ path.join(pkg, 'index.js'),+ "export * from './icon-sets/hero/hero.generated.js';\n",+ );+ const check = await runCli(['integration', 'check', '--json'], pkg);+ expect(check.stdout).not.toContain('icon_generated_types_mismatch');+ expect(check.stdout).not.toContain('icon_export_missing');+ });+});++describe('add --variant --all on a set an older id rule wrote from a prefixed library', () => {+ it('meets each icon by the library export it re-exports', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'hero');+ fs.mkdirSync(lib, {recursive: true});+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ name: '@acme/hero',+ version: '1.0.0',+ type: 'module',+ exports: {'.': './index.js', './solid': './solid.js'},+ }),+ );+ const source =+ 'export const HiSquares2X2Icon = props => null;\nexport const HiTrashIcon = props => null;\n';+ fs.writeFileSync(path.join(lib, 'index.js'), source);+ fs.writeFileSync(path.join(lib, 'solid.js'), source);+ await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'hero',+ '--from',+ '@acme/hero',+ '--variants',+ 'outline,solid',+ ]);+ const setDir = path.join(pkg, 'icon-sets', 'hero');+ const data = dataOf('hero');+ const squares = data.icons.find(+ (/** @type {{id: string}} */ each) => each.id === 'squares-2x2',+ );+ const newName = squares.export;+ Object.assign(squares, {id: 'squares-2-x2', export: 'Squares2X2Icon'});+ fs.writeFileSync(+ path.join(setDir, 'hero.icons.json'),+ `${JSON.stringify(data, null, 2)}\n`,+ );+ for (const file of ['hero.generated.js', 'hero.generated.d.ts']) {+ const full = path.join(setDir, file);+ fs.writeFileSync(+ full,+ fs.readFileSync(full, 'utf-8').replaceAll(newName, 'Squares2X2Icon'),+ );+ }+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ '--variant',+ 'solid',+ '--from',+ '@acme/hero/solid',+ '--all',+ ]);+ expect(added.code, JSON.stringify(added.body)).toBe(0);+ expect(added.body.data.missing).toEqual([]);+ expect(+ dataOf('hero').icons.find(+ (/** @type {{id: string}} */ each) => each.id === 'squares-2-x2',+ ).variants,+ ).toEqual([{variant: 'solid', export: 'Squares2X2SolidIcon'}]);+ });+});++describe('a refresh after the library drops an icon', () => {+ it('names the icon it removed and the map entry that lost it', async () => {+ const args = [+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ];+ await json(args);+ await json(['experimental', 'icon', 'map', 'close', 'cross']);+ const index = path.join(+ pkg,+ 'node_modules',+ '@acme',+ 'glyph-library',+ 'index.js',+ );+ fs.writeFileSync(+ index,+ fs+ .readFileSync(index, 'utf-8')+ .replace("export {Cross} from './icons/cross.js';\n", ''),+ );+ const refreshed = await json(args);+ expect(refreshed.code).toBe(0);+ expect(refreshed.body.data.notes).toEqual(+ expect.arrayContaining([+ 'These map entries named those icons and were removed: close -> "cross".',+ '1 icons the library no longer exports were removed from the set: cross.',+ ]),+ );+ });+});++describe('a refresh changes only the icons the refreshed module supplies', () => {+ beforeEach(() => {+ // A second library, and your own artwork.+ const other = path.join(pkg, 'node_modules', '@acme', 'other-library');+ fs.mkdirSync(other, {recursive: true});+ fs.writeFileSync(+ path.join(other, 'package.json'),+ JSON.stringify({+ name: '@acme/other-library',+ version: '1.0.0',+ type: 'module',+ exports: {'.': './index.js'},+ }),+ );+ fs.writeFileSync(+ path.join(other, 'index.js'),+ 'export const Rocket = props => null;\n',+ );+ fs.mkdirSync(path.join(pkg, 'art'), {recursive: true});+ fs.writeFileSync(+ path.join(pkg, 'art', 'spark.js'),+ 'export const Spark = props => null;\n',+ );+ fs.writeFileSync(+ path.join(pkg, 'art', 'spark.d.ts'),+ 'export declare const Spark: (props: object) => null;\n',+ );+ });++ it('keeps your ./ artwork and another library’s icon, with their map entries and module lines, and still removes a library icon that went away', async () => {+ const args = [+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ];+ expect((await json(args)).code).toBe(0);+ for (const add of [+ ['Spark', '--from', './art/spark.js', '--definition', 'sparkles'],+ ['Rocket', '--from', '@acme/other-library', '--definition', 'rocket'],+ ]) {+ const added = await json(['experimental', 'icon', 'add', ...add]);+ expect(added.code, JSON.stringify(added.body)).toBe(0);+ }+ await json(['experimental', 'icon', 'map', 'close', 'cross']);+ const generatedFile = path.join(+ pkg,+ 'icon-sets',+ 'outline',+ 'outline.generated.js',+ );+ const before = fs.readFileSync(generatedFile, 'utf-8');+ const sparkLine = before+ .split('\n')+ .find(line => line.includes('SparkIcon') && line.includes('art/spark'));+ const rocketLine = before+ .split('\n')+ .find(+ line => line.includes('RocketIcon') && line.includes('other-library'),+ );+ expect(sparkLine).toBeTruthy();+ expect(rocketLine).toBeTruthy();+ // The library drops Cross.+ const index = path.join(+ pkg,+ 'node_modules',+ '@acme',+ 'glyph-library',+ 'index.js',+ );+ fs.writeFileSync(+ index,+ fs+ .readFileSync(index, 'utf-8')+ .replace("export {Cross} from './icons/cross.js';\n", ''),+ );++ const refreshed = await json(args);+ expect(refreshed.code).toBe(0);+ const data = dataOf('outline');+ const ids = data.icons.map((/** @type {{id: string}} */ each) => each.id);+ expect(ids).toEqual(expect.arrayContaining(['bin', 'spark', 'rocket']));+ expect(ids).not.toContain('cross');+ expect(data.map).toMatchObject({sparkles: 'spark', rocket: 'rocket'});+ expect(data.map).not.toHaveProperty('close');+ const after = fs.readFileSync(generatedFile, 'utf-8');+ expect(after).toContain(/** @type {string} */ (sparkLine));+ expect(after).toContain(/** @type {string} */ (rocketLine));+ const notes = refreshed.body.data.notes.join('\n');+ expect(notes).toContain(+ '1 icons the library no longer exports were removed from the set: cross.',+ );+ expect(notes).toContain('close -> "cross"');+ expect(notes).not.toMatch(/spark|rocket/u);+ });++ it('add --variant --all leaves icons from other modules alone and never lists them as missing', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ ...JSON.parse(fs.readFileSync(path.join(lib, 'package.json'), 'utf-8')),+ exports: {'.': './index.js', './solid': './solid.js'},+ }),+ );+ // The solid module also exports a Spark: it is not your Spark.+ fs.writeFileSync(+ path.join(lib, 'solid.js'),+ 'export const Bin = props => null;\nexport const Spark = props => null;\n',+ );+ await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ '--variants',+ 'outline,solid',+ ]);+ await json([+ 'experimental',+ 'icon',+ 'add',+ 'Spark',+ '--from',+ './art/spark.js',+ '--definition',+ 'sparkles',+ ]);+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ '--variant',+ 'solid',+ '--from',+ '@acme/glyph-library/solid',+ '--all',+ ]);+ expect(added.code, JSON.stringify(added.body)).toBe(0);+ expect(added.body.data.missing).toEqual(['cross']);+ const spark = dataOf('outline').icons.find(+ (/** @type {{id: string}} */ each) => each.id === 'spark',+ );+ expect(spark.variants).toBeUndefined();+ });+});++describe('a refresh with --exclude', () => {+ it('names the icons --exclude left out, never as ones the library no longer exports', async () => {+ const args = [+ 'experimental',+ 'icon',+ 'new-set',+ 'outline',+ '--from',+ '@acme/glyph-library',+ ];+ await json(args);+ await json(['experimental', 'icon', 'map', 'close', 'cross']);+ const refreshed = await json([...args, '--exclude', 'Cross']);+ expect(refreshed.code).toBe(0);+ const notes = refreshed.body.data.notes;+ expect(notes).toEqual(+ expect.arrayContaining([+ 'Left out by --exclude, and removed from the set: cross.',+ 'These map entries named icons --exclude left out and were removed: close -> "cross".',+ ]),+ );+ expect(notes.join('\n')).not.toContain('no longer exports');+ expect(dataOf('outline').exclude).toEqual(['Cross']);+ });+});diff --git a/packages/cli/clients/cli/commands/icon-options-wiring.test.mjs b/packages/cli/clients/cli/commands/icon-options-wiring.test.mjsnew file mode 100644index 0000000000..4d969b2787--- /dev/null+++ b/packages/cli/clients/cli/commands/icon-options-wiring.test.mjs@@ -0,0 +1,158 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Every option an icon CommandDoc declares reaches the API function it+ * names (spec:AST-042 FR1, architecture:cli-surface INV6): for each icon+ * command and each of its options, the CLI runs with that option, and the+ * test asserts the function received the parameter the option's `param`+ * names. The API functions are replaced by recorders, so nothing is read or+ * written. `--set` on a subcommand is also given before the subcommand's own+ * arguments and after them, since `experimental icon` declares `--set` too.+ */++import {beforeEach, describe, expect, it, vi} from 'vitest';+import {runCli} from '../../../test-utils/run-cli.mjs';+import {doc as iconCommand} from './experimental-icon.doc.mjs';+import {doc as addCommand} from './experimental-icon-add.doc.mjs';+import {doc as mapCommand} from './experimental-icon-map.doc.mjs';+import {doc as useCommand} from './experimental-icon-use.doc.mjs';+import {doc as newSetCommand} from './experimental-icon-new-set.doc.mjs';+import {doc as newDefinitionCommand} from './experimental-icon-new-definition.doc.mjs';++const calls = vi.hoisted(+ () => /** @type {Array<{fn: string, args: unknown[]}>} */ ([]),+);++/**+ * A recorder for one API function: it records its arguments and fails, so+ * the CLI prints an error and renders no result.+ * @param {string} fn+ */+function recorder(fn) {+ return async (/** @type {unknown[]} */ ...args) => {+ calls.push({fn, args});+ throw Object.assign(new Error('recorded'), {code: 'ERR_NOT_FOUND'});+ };+}++vi.mock('../../../api/icon/icon.mjs', async importOriginal => ({+ .../** @type {object} */ (await importOriginal()),+ icon: recorder('icon'),+}));+vi.mock('../../../api/icon/add/add.mjs', async importOriginal => ({+ .../** @type {object} */ (await importOriginal()),+ iconAdd: recorder('iconAdd'),+}));+vi.mock('../../../api/icon/map/map.mjs', async importOriginal => ({+ .../** @type {object} */ (await importOriginal()),+ iconMap: recorder('iconMap'),+}));+vi.mock('../../../api/icon/use/use.mjs', async importOriginal => ({+ .../** @type {object} */ (await importOriginal()),+ iconUse: recorder('iconUse'),+}));+vi.mock('../../../api/icon/new-set/new-set.mjs', async importOriginal => ({+ .../** @type {object} */ (await importOriginal()),+ iconNewSet: recorder('iconNewSet'),+}));+vi.mock(+ '../../../api/icon/new-definition/new-definition.mjs',+ async importOriginal => ({+ .../** @type {object} */ (await importOriginal()),+ iconNewDefinition: recorder('iconNewDefinition'),+ }),+);++beforeEach(() => {+ calls.length = 0;+});++/** @type {Array<[string, any, string]>} the command, its doc, its function */+const COMMANDS = [+ ['experimental icon', iconCommand, 'icon'],+ ['experimental icon add', addCommand, 'iconAdd'],+ ['experimental icon map', mapCommand, 'iconMap'],+ ['experimental icon use', useCommand, 'iconUse'],+ ['experimental icon new-set', newSetCommand, 'iconNewSet'],+ [+ 'experimental icon new-definition',+ newDefinitionCommand,+ 'iconNewDefinition',+ ],+];++/**+ * The words that run one command with one option: the command, its required+ * arguments, and the option (with a value when it takes one).+ * @param {string} name+ * @param {any} command+ * @param {any} option+ * @param {'after' | 'before'} [where] the option after the arguments, or+ * before them+ */+function argv(name, command, option, where = 'after') {+ const required = (command.args ?? [])+ .filter((/** @type {any} */ arg) => arg.required === true)+ .map(() => 'glyphs');+ const [flag, value] = option.flag.split(/\s+/u);+ const given = value ? [flag, flag === '--limit' ? '3' : 'glyphs'] : [flag];+ return [+ ...name.split(' '),+ ...(where === 'before' ? [...given, ...required] : [...required, ...given]),+ ];+}++/**+ * The options object the recorded call passed (its last argument).+ * @param {string} fn+ * @returns {Record<string, unknown>}+ */+function received(fn) {+ const call = calls.find(each => each.fn === fn);+ if (!call) throw new Error(`${fn} was not called`);+ return /** @type {Record<string, unknown>} */ (call.args.at(-1));+}++describe.each(COMMANDS)('%s', (name, command, fn) => {+ const options = command.options ?? [];+ if (options.length === 0) {+ it('declares no option', () => {+ expect(options).toEqual([]);+ });+ return;+ }+ it.each(options.map((/** @type {any} */ option) => [option.flag, option]))(+ '%s reaches the API',+ async (_flag, option) => {+ await runCli(argv(name, command, option), {cwd: process.cwd()});+ const key = option.param.replace(/^options\./u, '');+ const value = received(fn)[key];+ expect(value, `${option.flag} -> ${option.param}`).not.toBeUndefined();+ expect(value, `${option.flag} -> ${option.param}`).not.toBe(false);+ },+ );+});++describe('--set on a subcommand, which experimental icon declares too', () => {+ it.each([+ ['experimental icon add', addCommand, 'iconAdd'],+ ['experimental icon map', mapCommand, 'iconMap'],+ [+ 'experimental icon new-definition',+ newDefinitionCommand,+ 'iconNewDefinition',+ ],+ ])(+ '%s takes --set before or after its arguments',+ async (name, command, fn) => {+ const option = command.options.find((/** @type {any} */ each) =>+ each.flag.startsWith('--set '),+ );+ for (const where of /** @type {const} */ (['after', 'before'])) {+ calls.length = 0;+ await runCli(argv(name, command, option, where), {cwd: process.cwd()});+ expect(received(fn).set, where).toBe('glyphs');+ }+ },+ );+});diff --git a/packages/cli/clients/cli/commands/icon.test.mjs b/packages/cli/clients/cli/commands/icon.test.mjsindex b5b78e5d87..976f45ce9d 100644--- a/packages/cli/clients/cli/commands/icon.test.mjs+++ b/packages/cli/clients/cli/commands/icon.test.mjs@@ -33,7 +33,7 @@ describe('astryx experimental icon', () => {/import: +import \{TrashIcon\} from '@acme\/glyphs';/,);expect(res.stdout).toMatch(/package: +@acme\/glyphs/);- expect(res.stdout).toMatch(/variant: +solid/);+ expect(res.stdout).toMatch(/variant: +solid \(TrashSolidIcon\)/);const many = await runCli(['experimental', 'icon', 'magni', 'fier', '--json'],cwd,diff --git a/packages/cli/clients/cli/commands/template.mjs b/packages/cli/clients/cli/commands/template.mjsindex c27deb66a1..b25003408b 100644--- a/packages/cli/clients/cli/commands/template.mjs+++ b/packages/cli/clients/cli/commands/template.mjs@@ -49,7 +49,10 @@ function iconLines(icons) {return [...icons.mapped.map(each =>- `icons: mapped ${each.source.export} (${each.source.module}) -> ${each.target.export} (${each.target.module}) by ${each.by}`,+ `icons: mapped ${each.source.export} (${each.source.module}) -> ${each.target.export} (${each.target.module}) by ${each.by}` ++ (each.dropped && each.dropped.length > 0+ ? `; dropped ${each.dropped.join(', ')} (size comes from CSS)`+ : ''),),...icons.kept.map(each =>diff --git a/packages/cli/foundation/discovery/icon-set-checks.mjs b/packages/cli/foundation/discovery/icon-set-checks.mjsindex 600ac2956b..f48428c7ef 100644--- a/packages/cli/foundation/discovery/icon-set-checks.mjs+++ b/packages/cli/foundation/discovery/icon-set-checks.mjs@@ -51,7 +51,10 @@ import {} from './icon-set-discovery.mjs';import {inspectPackageExport} from './package-exports.mjs';import {+ THEME_MAP_NAME,+ entryWiringNote,generatedTypesPath,+ otherNamesOf,generatedTypesText,readGeneratedStatements,} from './icon-set-writer.mjs';@@ -63,6 +66,7 @@ import {staticExportBindings,} from './module-exports.mjs';import {astryxIconDefinitions} from './icon-definition-discovery.mjs';+import {rankIcons} from './icon-ranking.mjs';import {issueError,issueWarning,@@ -272,7 +276,17 @@ function checkContract(set, packageName, pkg, unchecked) {const actual = fs.existsSync(typesFile)? fs.readFileSync(typesFile, 'utf-8'): null;- if (expected != null && actual !== expected) {+ // The header comment is the writer's, and changes between releases;+ // the declarations are what must match.+ const code = (/** @type {string} */ text) =>+ text+ .split('\n')+ .filter(line => !line.startsWith('//'))+ .join('\n');+ if (+ expected != null &&+ (actual == null || code(actual) !== code(expected))+ ) {issues.push(issueError(ICON_GENERATED_TYPES_MISMATCH,@@ -350,7 +364,7 @@ function checkDefinitions(set) {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}`,+ `${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: run \`astryx experimental icon map ${doc.name} <icon id>\` with the icon that draws it${findHint(set, doc)}.${hint}`,),);}@@ -368,7 +382,7 @@ function checkDefinitions(set) {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}.` : ''}`,+ `${label} declares the icon definition "${doc.name}", but "map" names no icon for it. Map it with \`astryx experimental icon map ${doc.name} <icon id>\`, or remove definitions/${doc.name}.doc.mjs.${suggestion ? ` Suggested: astryx experimental icon map ${doc.name} ${suggestion.icon}.` : ''}`,),);}@@ -383,9 +397,8 @@ function checkDefinitions(set) {* 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+ * unmapped definition, built-in, optional, or the set's own, the best icon+ * {@link suggestedIcons} gives, if any* @property {IconSetUnchecked[]} unchecked what the checks could not judge:* never counted, never failing, even under `--strict`*/@@ -433,25 +446,247 @@ export function iconSetCoverage(loaded, unchecked = new Map()) {}/**- * 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.+ * The best icon {@link suggestedIcons} gives for a definition, or null when+ * it gives none.* @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};+ const [first] = suggestedIcons(set, doc);+ return first ? {map: doc.name, icon: first.icon} : null;+}++/**+ * Words that turn an icon into the opposite or a variation of its first+ * words: `lock-open`, `bell-off`, `video-camera-slash`, `audio-lines-x`.+ */+const NEGATING_WORDS = new Set([+ 'off',+ 'slash',+ 'x',+ 'open',+ 'minus',+ 'ban',+ 'dashed',+ 'dot',+ 'code',+ 'formatting',+ 'exclamation',+ 'question',+ 'warning',+]);++/** Direction words that mean the other way. */+/** @type {Record<string, string>} */+const OPPOSITES = {+ horizontal: 'vertical',+ vertical: 'horizontal',+ left: 'right',+ right: 'left',+ up: 'down',+ down: 'up',+ in: 'out',+ out: 'in',+};++/**+ * A second id word that only sizes, shapes, or numbers the first: a number+ * or dimension (`2`, `3x3`), or one of a few style words. The icon then+ * still draws what its first word names.+ */+const QUALIFIER_RE =+ /^(?:\d+(?:x\d+)?|circle|square|small|big|large|alt|horizontal|vertical)$/u;++/** How many icons one definition is suggested at most. */+export const SUGGESTIONS_PER_DEFINITION = 3;++/**+ * The icons a definition might map to, best first, at most three, in the+ * order AST-084 FR13 gives: the name in another spelling, an icon the library+ * gives the name as another name, ids that start with the name (`video` →+ * `video-camera`, never `close` → `panel-left-close`), an id that is one of+ * its words (`delete` → `trash`), another name that is one of its words, and+ * two-word ids that are a one-word word sized, shaped, or numbered+ * (`grid-2x2`). An icon `map` already names+ * for another definition, or whose id is another definition's name, is left+ * out: it has a meaning of its own. Never a negated form or the opposite+ * direction, and never a guess from parts of words.+ * @param {{data: {icons: Array<{id: string, words?: string[]}>, map?: Record<string, string>}, definitions?: Array<{doc: {name: string}}>}} set+ * @param {{name: string, words: string[]}} doc+ * @returns {Array<{icon: string, word: string}>}+ */+export function suggestedIcons(set, doc) {+ const toId = (/** @type {string} */ name) =>+ name.replace(/([a-z0-9])([A-Z])/gu, '$1-$2').toLowerCase();+ const nameId = toId(doc.name);+ const nameWords = nameId.split('-').map(stem);+ const map = set.data.map ?? {};+ const taken = new Set([+ ...Object.entries(map)+ .filter(([name]) => name !== doc.name)+ .map(([, id]) => id),+ ...[...astryxIconDefinitions().definitions, ...(set.definitions ?? [])]+ .map(each => toId(each.doc.name))+ .filter(id => id !== nameId),+ ]);+ const wordIds = doc.words.map(word =>+ word.trim().toLowerCase().replace(/\s+/gu, '-'),+ );+ // Every word the definition is known by, stemmed: its name's and its words'.+ const meaning = new Set([+ ...nameWords,+ ...wordIds.flatMap(id => id.split('-')).map(stem),+ ]);+ const icons = set.data.icons.map(icon => ({+ id: icon.id,+ words: icon.id.split('-').map(stem),+ raw: icon.id.split('-'),+ // The library's other names for it, the same ones `map` accepts.+ other: otherNamesOf(icon),+ }));+ /** How many of the definition's words an id has: more is a better fit. */+ const fit = (/** @type {string[]} */ words) =>+ words.filter(word => meaning.has(word)).length;+ /**+ * Candidates best first: most of the definition's words, then fewest+ * extra words, then by id.+ * @param {typeof icons} list+ */+ const ranked = list =>+ [...list].sort(+ (a, b) =>+ fit(b.words) - fit(a.words) ||+ a.words.length - b.words.length ||+ (a.id < b.id ? -1 : a.id > b.id ? 1 : 0),+ );+ // An id that turns the definition around (`ellipsis-vertical` for+ // moreHorizontal) is never its icon.+ const opposite = new Set(+ nameWords.flatMap(word => (OPPOSITES[word] ? [OPPOSITES[word]] : [])),+ );+ const negated = (/** @type {string[]} */ words) =>+ words.some(word => NEGATING_WORDS.has(word) || opposite.has(word));+ /** @type {Array<{icon: string, word: string}>} */+ const found = [];+ const add = (/** @type {string} */ icon, /** @type {string} */ word) => {+ if (taken.has(icon) || found.some(each => each.icon === icon)) return;+ found.push({icon, word});+ };+ const squashed = nameId.replace(/-/gu, '');+ // 1. The name itself, spelled with or without hyphens or a plural+ // (`lightbulb` → `light-bulb`, `language` → `languages`).+ for (const icon of icons) {+ if (+ icon.id === nameId ||+ icon.id.replace(/-/gu, '') === squashed ||+ (icon.words.length === nameWords.length &&+ icon.words.every((word, index) => word === nameWords[index]))+ ) {+ add(icon.id, nameId);+ }}- return null;+ // 2. An icon the library once named after the definition, or that it+ // gives the definition's name as another name (Lucide's+ // `more-horizontal` on `ellipsis`, `unlock` on `lock-open`).+ for (const icon of icons) {+ if (icon.other.includes(nameId)) add(icon.id, nameId);+ }+ // 3. Ids that start with the name as written (`video` → `video-camera`),+ // never a negated form. A plural is not the same start: `users` is not+ // `user-plus`, and `apps` is not `app-window`.+ const nameRaw = nameId.split('-');+ ranked(+ icons.filter(+ icon =>+ icon.raw.length > nameRaw.length &&+ nameRaw.every((word, index) => icon.raw[index] === word) &&+ !negated(icon.raw.slice(nameRaw.length)),+ ),+ ).forEach(icon => add(icon.id, nameId));+ // 4. An icon whose whole id is one of the definition's words.+ for (const id of wordIds) {+ if (icons.some(icon => icon.id === id)) add(id, id.replace(/-/gu, ' '));+ }+ // 5. Another name the library gives an icon that is one of the+ // definition's words (Lucide's `smile` on `face-slightly-smiling`).+ for (const [index, id] of wordIds.entries()) {+ for (const icon of icons) {+ if (icon.other.includes(id)) add(icon.id, doc.words[index]);+ }+ }+ // 6. Last, two-word ids that are a one-word word with only a size, shape,+ // or number after it (`columns` → `columns-3`, `plus` → `plus-circle`,+ // `grid` → `grid-2x2`), best fit first. Any other second word names+ // another thing (`card-sim`, `fast-forward`, `hand-coins`), so it is+ // never suggested from a word alone.+ for (const word of doc.words) {+ if (!/^[a-z]{3,}$/u.test(word)) continue;+ ranked(+ icons.filter(+ icon =>+ icon.raw.length === 2 &&+ icon.raw[0] === word &&+ icon.raw[1] !== word &&+ QUALIFIER_RE.test(icon.raw[1]) &&+ !negated(icon.raw.slice(1)),+ ),+ ).forEach(icon => add(icon.id, word));+ }+ return found.slice(0, SUGGESTIONS_PER_DEFINITION);+}++/**+ * A word in its singular form, so a plural meets its singular and nothing+ * else: `languages` meets `language`, `arrows` meets `arrow`. Only a+ * trailing plural `s` comes off (not `ss`, and not from a short word); a+ * verb ending never does, so `drafting` never meets `draft`.+ * @param {string} word+ */+function stem(word) {+ if (word.length > 3 && word.endsWith('s') && !word.endsWith('ss')) {+ return word.slice(0, -1);+ }+ return word;+}++/**+ * The change that makes a set's generated module part of its package's+ * entry ({@link entryWiringNote}), or null when the entry exports its theme+ * map or any of its icons, the set has no generated module on disk, or the+ * entry is an `exports` target not built yet (listed as not checked).+ * @param {DiscoveredIconSet} set+ * @param {string} packageDir+ * @param {string} packageName+ * @param {(specifier: string) => string | null} unbuiltTarget+ * @returns {string | null}+ */+function entryNotWired(set, packageDir, packageName, unbuiltTarget) {+ const generated = set.data.generated;+ if (!generated || !fs.existsSync(path.join(packageDir, generated))) {+ return null;+ }+ if (splitSpecifier(set.data.module).name !== packageName) return null;+ if (unbuiltTarget(set.data.module)) return null;+ const pkg = readJson(path.join(packageDir, 'package.json'));+ if (!pkg) return null;+ const note = entryWiringNote(packageDir, pkg, generated, {+ module: set.data.module,+ name: set.data.themeMap ?? THEME_MAP_NAME,+ });+ if (!note) return null;+ const entry = resolveIconModule(set.data.module, packageDir, {+ name: packageName,+ dir: packageDir,+ });+ const someIcon =+ entry &&+ set.data.icons.some(+ icon =>+ (icon.module ?? set.data.module) === set.data.module &&+ exportOriginVerdict(entry, icon.export)?.verdict !== 'lacks',+ );+ return someIcon ? null : note;}/**@@ -559,10 +794,22 @@ function checkExports(set, packageDir, packageName, unchecked) {.definitions.filter(definition => definition.doc.builtIn).map(definition => definition.doc.name),);+ // A generated module the package's entry does not export yet: one finding+ // with the exact change \`new-set\` names in its receipt, not one per icon.+ const wiring = entryNotWired(set, packageDir, packageName, unbuiltTarget);+ if (wiring) {+ issues.push(+ issueError(+ ICON_EXPORT_MISSING,+ `${label}: its icons are not exported from "${set.data.module}" yet. ${wiring}`,+ ),+ );+ }/** @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;+ if (wiring && module === set.data.module) continue;iconOrigins.set(icon.id,originOf(module, icon.export, `icon "${icon.id}"`, {icon: icon.id}),@@ -595,6 +842,7 @@ function checkExports(set, packageDir, packageName, unchecked) {);return issues;}+ if (wiring) return issues;const mapOrigin = originOf(set.data.module,themeMap,@@ -665,6 +913,33 @@ function checkExports(set, packageDir, packageName, unchecked) {return issues;}+/** The lowest search score a find hint needs: a whole word or a word start. */+const FIND_FLOOR = 60;++/**+ * A search that finds icons for a definition in the set, named only when it+ * answers: the definition's name, then each of its words, as a query against+ * the set's icon ids and words. Empty when none answers, so the message never+ * names a search that finds nothing.+ * @param {DiscoveredIconSet} set+ * @param {{name: string, words: string[]}} doc+ */+function findHint(set, doc) {+ const queries = [+ doc.name.replace(/([a-z0-9])([A-Z])/gu, '$1 $2').toLowerCase(),+ ...doc.words,+ ];+ for (const query of queries) {+ const found = rankIcons([set], query).filter(+ each => each.score >= FIND_FLOOR,+ );+ if (found.length > 0) {+ return ` (icons matching "${query}": \`astryx experimental icon ${query} --set ${set.name}\`)`;+ }+ }+ return ' (no icon in the set has its name or words: pick the library icon that draws it; if the library has none, map the closest, or add your own artwork with `astryx experimental icon add <Name> --from ./src/icons/<name>.js --definition <definition>`)';+}+/*** The upstream checks of one set: version drift and license notices.* @param {DiscoveredIconSet} set@@ -693,7 +968,7 @@ function checkUpstream(set, packageDir, pkg) {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.`,+ `${label} was generated from ${source.package}@${source.version}, but the package resolves ${source.package}@${installed}. Refresh it: \`astryx experimental icon new-set ${set.name} --from <the ${source.package} module it wraps>\`, then rerun any \`add --variant … --all\`.`,),);} else if (@@ -704,7 +979,7 @@ function checkUpstream(set, packageDir, pkg) {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.`,+ `${label} was generated from ${source.package}@${source.version}, but the package depends on ${source.package}@${range}. Refresh it: \`astryx experimental icon new-set ${set.name} --from <the ${source.package} module it wraps>\`, then rerun any \`add --variant … --all\`.`,),);}diff --git a/packages/cli/foundation/discovery/icon-set-checks.test.mjs b/packages/cli/foundation/discovery/icon-set-checks.test.mjsindex 97b5e6ddf5..49df228d4f 100644--- a/packages/cli/foundation/discovery/icon-set-checks.test.mjs+++ b/packages/cli/foundation/discovery/icon-set-checks.test.mjs@@ -10,7 +10,11 @@ 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 {+ iconSetCoverage,+ iconSetIssues,+ suggestedIcons,+} 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';@@ -22,6 +26,13 @@ import {writeIconPackage,} from '../../test-utils/icon-set-fixture.mjs';import {ICON_NAMES} from '../../authoring/doctypes/icon-set/icon-names.mjs';+import {rankIcons} from './icon-ranking.mjs';+import {astryxIconDefinitions} from './icon-definition-discovery.mjs';+import {discoverIconSetDirectory} from './icon-set-discovery.mjs';++/** The fixture package's one set, as discovery reads it. */+const readSet = () =>+ discoverIconSetDirectory(path.join(dir, 'icon-sets'), '@acme/glyphs').sets[0];/** @type {string} */let tmp;@@ -641,6 +652,26 @@ describe('icon definitions (map)', () => {// 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);+ // Each names the command that maps it, never a hand edit of the data.+ const error = builtIn.find(issue => issue.message.includes('"error"'));+ expect(error?.message).toContain(+ '`astryx experimental icon map error <icon id>`',+ );+ expect(error?.message).not.toContain('add it to "map"');+ // A find hint names a search only when that search finds icons.+ for (const issue of builtIn) {+ const query =+ /icons matching "([^"]+)": `astryx experimental icon \1 --set glyphs`/u.exec(+ issue.message,+ );+ if (query) {+ expect(rankIcons([readSet()], query[1]).length).toBeGreaterThan(0);+ } else {+ expect(issue.message).toContain(+ 'no icon in the set has its name or words',+ );+ }+ }// An issue is only ever an error or a warning.expect(issues.every(issue => ['error', 'warning'].includes(issue.severity)),@@ -692,23 +723,23 @@ describe('icon definitions (map)', () => {});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'))});+ const issues = issuesOf({data: data(d => (d.map.orbit = '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/,+ /map "orbit" \(icon "home"\) is not an icon definition\. Declare it in definitions\/orbit\.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')),+ data: data(d => (d.map.orbit = 'home')),definitions: {- rotate: definitionSource('rotate'),+ orbit: definitionSource('orbit'),garbage: definitionSource('garbage', {words: ['bin', 'trash']}),- // The trash icon is tagged garbage, and `tra` starts its id: neither- // is a suggestion. No guessing.+ // The trash icon has the word garbage, so it is a suggestion; `tra`+ // only starts its id, so that is not. Never part of a word.rubbish: definitionSource('rubbish', {words: ['garbage', 'tra']}),delete: definitionSource('delete'),},@@ -726,7 +757,9 @@ describe('icon definitions (map)', () => {'astryx experimental icon map garbage trash',);const rubbish = unused.find(issue => issue.message.includes('"rubbish"'));- expect(rubbish?.message).not.toContain('Suggested');+ expect(rubbish?.message).toContain(+ 'Suggested: astryx experimental icon map rubbish trash.',+ );const [coverage] = iconSetCoverage({name: '@acme/glyphs',iconSets: path.join(dir, 'icon-sets'),@@ -735,9 +768,10 @@ describe('icon definitions (map)', () => {definition: 'garbage',icon: 'trash',});- expect(- coverage.suggestions.some(each => each.definition === 'rubbish'),- ).toBe(false);+ expect(coverage.suggestions).toContainEqual({+ definition: 'rubbish',+ icon: 'trash',+ });expect(issues.find(issue => issue.code === 'icon_definition_shadowed')?.message,).toContain('Astryx now has');@@ -745,7 +779,7 @@ describe('icon definitions (map)', () => {it('a definition file that does not read makes the set invalid', () => {const issues = issuesOf({- definitions: {rotate: definitionSource('Rotate')},+ definitions: {orbit: definitionSource('Orbit')},});expect(issues).toEqual([expect.objectContaining({code: 'invalid_icon_set'}),@@ -903,3 +937,82 @@ describe('the codes and severities FR15 lists', () => {expect(listed).toEqual(raised);});});++describe('suggestions join a plural only to its singular', () => {+ /**+ * @param {string[]} ids+ * @param {{name: string, words?: string[]}} doc+ */+ const suggest = (ids, {name, words = []}) =>+ suggestedIcons(+ {data: {icons: ids.map(id => ({id, words: id.split('-')})), map: {}}},+ {name, words},+ ).map(each => each.icon);++ it('never offers a grid of squares for stop, whose word is square', () => {+ expect(suggest(['squares-2x2'], {name: 'stop', words: ['square']})).toEqual(+ [],+ );+ expect(+ suggest(['squares-2x2', 'square'], {name: 'stop', words: ['square']}),+ ).toEqual(['square']);+ });++ it('meets a plural and its singular of the same word, either way', () => {+ expect(suggest(['squares'], {name: 'square'})).toEqual(['squares']);+ expect(suggest(['square'], {name: 'squares'})).toEqual(['square']);+ expect(suggest(['arrows'], {name: 'arrow'})).toEqual(['arrows']);+ expect(suggest(['arrow'], {name: 'arrows'})).toEqual(['arrow']);+ });++ it('never bridges a verb ending or a plural to a longer id', () => {+ // `drafting` is not `draft`; `users` does not start `user-plus`.+ expect(+ suggest(['drafting-compass'], {name: 'compose', words: ['draft']}),+ ).toEqual([]);+ expect(suggest(['user-plus', 'user-cog'], {name: 'users'})).toEqual([]);+ expect(suggest(['tool-case'], {name: 'wrench', words: ['tools']})).toEqual(+ [],+ );+ });+});++describe('suggestions from a definition word never bridge to another meaning', () => {+ const definitions = new Map(+ astryxIconDefinitions().definitions.map(({doc}) => [doc.name, doc]),+ );+ /** @param {string} name @param {string[]} ids */+ const suggest = (name, ids) =>+ suggestedIcons(+ {data: {icons: ids.map(id => ({id, words: id.split('-')})), map: {}}},+ /** @type {any} */ (definitions.get(name)),+ ).map(each => each.icon);++ it.each([+ ['creditCard', 'card-sim'],+ ['bolt', 'fast-forward'],+ ['archive', 'store'],+ ['mobile', 'device-tablet'],+ ['raiseHand', 'stop-circle'],+ ['star', 'bookmark-square'],+ ['database', 'table-cells'],+ ['redo', 'forward'],+ ['activity', 'monitor'],+ ['stop', 'square-square'],+ ['moreHorizontal', 'ellipsis-vertical'],+ ])('%s never suggests %s', (name, id) => {+ expect(suggest(name, [id])).toEqual([]);+ });++ it('still suggests a word with only a size, shape, or number after it', () => {+ expect(suggest('gridView', ['grid-2x2'])).toEqual(['grid-2x2']);+ expect(suggest('viewColumns', ['columns-3'])).toEqual(['columns-3']);+ expect(suggest('add', ['plus-circle'])).toEqual(['plus-circle']);+ });++ it('finds the glyph a library names in two words through the definition’s words', () => {+ expect(suggest('raiseHand', ['hand-raised'])).toEqual(['hand-raised']);+ expect(suggest('location', ['map-pin'])).toEqual(['map-pin']);+ expect(suggest('textCase', ['case-sensitive'])).toEqual(['case-sensitive']);+ });+});diff --git a/packages/cli/foundation/discovery/icon-set-writer.mjs b/packages/cli/foundation/discovery/icon-set-writer.mjsindex de38e94e8a..b3270d70b9 100644--- a/packages/cli/foundation/discovery/icon-set-writer.mjs+++ b/packages/cli/foundation/discovery/icon-set-writer.mjs@@ -24,6 +24,7 @@import * as fs from 'node:fs';import * as path from 'node:path';import {randomUUID} from 'node:crypto';+import {AsyncLocalStorage} from 'node:async_hooks';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';@@ -34,8 +35,11 @@ import {levenshteinDistance} from '../text/string-utils.mjs';import {astryxDefinitionsByName} from './icon-definition-discovery.mjs';import {discoverIconSetDirectory,+ NOTICE_FILE_RE,resolveIconModule,} from './icon-set-discovery.mjs';+import {findInstalledPackage} from '../fs/paths.mjs';+import {cliVersion} from '../release/run-context.mjs';import {exportScalarType,exportValueKind,@@ -64,16 +68,31 @@ export class IconSetAuthoringError extends Error {/*** `XMarkIcon` → `x-mark`; `Trash2` → `trash-2`; `ArrowUpDown` →- * `arrow-up-down`: an icon id from an export name.+ * `arrow-up-down`; `Squares2X2Icon` and `Grid2x2` → `squares-2x2`,+ * `grid-2x2`: an icon id from an export name. A dimension (a digit, `x` or+ * `X`, a digit) stays one word.* @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();+ return (+ name+ .replace(/Icon$/u, '')+ // `2X2` and `2x2` are one word: lower the x first.+ .replace(/([0-9])[xX](?=[0-9])/gu, '$1x')+ // A one-letter word before a digit ends there: `CalendarX2` is+ // `calendar-x-2`, as its library names it.+ .replace(/([a-z][A-Z])(?=[0-9])/gu, '$1-')+ // A lower-case letter before a capital or a digit ends a word, except+ // the x inside a dimension.+ .replace(/([a-z])(?=[A-Z0-9])/gu, (match, letter, offset, whole) =>+ letter === 'x' && /[0-9]/u.test(whole[offset - 1] ?? '')+ ? letter+ : `${letter}-`,+ )+ .replace(/([0-9])([A-Z])/gu, '$1-$2')+ .replace(/([A-Z])([A-Z][a-z])/gu, '$1-$2')+ .toLowerCase()+ );}/**@@ -180,12 +199,17 @@ export async function findLocalIconSet(cwd, selector) {? found.errors.find(error => error.name === selector): null;if (broken) {- throw new IconSetAuthoringError(broken.message, 'ERR_INVALID_ARGUMENT');+ // The same report every icon entry point gives a withdrawn set+ // (AST-084 FR17): withdrawn, with why, never "not there".+ throw new IconSetAuthoringError(+ `Icon set "${selector}" is in this package but withdrawn: ${broken.message}`,+ 'ERR_NOT_FOUND',+ );}const names = found.sets.map(set => set.name);if (named.length === 0 && selector) {throw new IconSetAuthoringError(- `This package has no icon set "${selector}".`,+ `No icon set named "${selector}" in this package`,'ERR_NOT_FOUND',names.map(name => ({name, reason: 'an icon set in this package'})),);@@ -207,6 +231,7 @@ const DATA_KEYS = ['schemaVersion','module','source',+ 'exclude','generated','adapter','variants',@@ -306,6 +331,87 @@ export function writeIconSetData(set, next, {extraDefinitions = []} = {}) {};}+/**+ * The files one authoring command has changed, each with the bytes it had+ * before (null: it did not exist), and the folders it created. Every write of+ * an icon authoring command records here first, so a command that fails+ * after some of its writes puts every file back (AST-084 FR13).+ * @typedef {{files: Map<string, Buffer | null>, dirs: string[]}} WriteJournal+ */++/** @type {AsyncLocalStorage<WriteJournal>} */+const journals = new AsyncLocalStorage();++/**+ * Record a file's bytes before the running command writes or removes it, and+ * the folders above it that do not exist yet. Outside {@link allOrNothing}+ * this does nothing.+ * @param {string} file+ */+export function journalFile(file) {+ const journal = journals.getStore();+ if (!journal) return;+ const full = path.resolve(file);+ if (journal.files.has(full)) return;+ journal.files.set(full, fs.existsSync(full) ? fs.readFileSync(full) : null);+ /** @type {string | null} */+ let missing = null;+ for (+ let dir = path.dirname(full);+ !fs.existsSync(dir) && path.dirname(dir) !== dir;+ dir = path.dirname(dir)+ ) {+ missing = dir;+ }+ if (missing && !journal.dirs.includes(missing)) journal.dirs.push(missing);+}++/**+ * Run one authoring command so its writes are all or nothing: when it throws,+ * every file it wrote gets its old bytes back (a file it created is removed,+ * with the folders it created), and the error is rethrown. A file system+ * error becomes `ERR_WRITE_FAILED`.+ * @template T+ * @param {() => T | Promise<T>} step+ * @returns {Promise<T>}+ */+export async function allOrNothing(step) {+ /** @type {WriteJournal} */+ const journal = {files: new Map(), dirs: []};+ try {+ return await journals.run(journal, step);+ } catch (error) {+ for (const [file, bytes] of [...journal.files].reverse()) {+ try {+ if (bytes == null) fs.rmSync(file, {force: true});+ else if (!fs.existsSync(file) || !fs.readFileSync(file).equals(bytes)) {+ fs.writeFileSync(file, bytes);+ }+ } catch {+ // Put back what can be put back; the error below names the cause.+ }+ }+ for (const dir of [...journal.dirs].reverse()) {+ try {+ fs.rmSync(dir, {recursive: true, force: true});+ } catch {+ // A path that never became a folder has nothing to remove.+ }+ }+ const code =+ error && typeof error === 'object' && 'code' in error+ ? String(error.code)+ : '';+ if (!(error instanceof IconSetAuthoringError) && /^E[A-Z]+$/u.test(code)) {+ throw new IconSetAuthoringError(+ `Could not write the icon set: ${error instanceof Error ? error.message : String(error)}. No file was changed.`,+ 'ERR_WRITE_FAILED',+ );+ }+ throw error;+ }+}+/*** Replace a file's text atomically.* @param {string} file@@ -316,6 +422,7 @@ function replaceText(file, text) {path.dirname(file),`.${path.basename(file)}.tmp-${randomUUID()}`,);+ journalFile(file);try {fs.writeFileSync(temporary, text, 'utf-8');fs.renameSync(temporary, file);@@ -386,6 +493,51 @@ export function resolveIconSource(from, {packageDir, pkg}) {return {file, module: from};}+/**+ * The installed library a package specifier reads from: its name, version,+ * license, and license notice files, from its own package.json. Null for a+ * ./ path, or when the library is not installed or has no version.+ * @param {string} from a package or package subpath+ * @param {string} packageDir the set's package+ * @returns {{package: string, version: string, license: string | null, dir: string, notices: string[]} | null}+ */+export function librarySource(from, packageDir) {+ if (from.startsWith('.') || path.isAbsolute(from)) return null;+ const parts = from.split('/');+ const name = from.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];+ const dir = findInstalledPackage(packageDir, name, Infinity);+ if (!dir) return null;+ /** @type {Record<string, any>} */+ let pkg;+ try {+ pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'));+ } catch {+ return null;+ }+ if (typeof pkg.version !== 'string' || pkg.version === '') return null;+ /** @type {string[]} */+ let notices = [];+ try {+ notices = fs+ .readdirSync(dir, {withFileTypes: true})+ .filter(file => file.isFile() && NOTICE_FILE_RE.test(file.name))+ .map(file => file.name)+ .sort();+ } catch {+ // No readable notices.+ }+ return {+ package: name,+ version: pkg.version,+ license:+ typeof pkg.license === 'string' && pkg.license.trim() !== ''+ ? pkg.license+ : null,+ dir,+ notices,+ };+}+/** @param {string} base */function resolveFile(base) {const extensions = ['', '.mjs', '.js', '.cjs', '.ts', '.tsx', '.jsx', '.mts'];@@ -419,7 +571,16 @@ export function assertIconExport(file, module, exportName) {? `"${module}" has no default export.`: `"${module}" does not export "${exportName}".`,'ERR_NOT_FOUND',- closestNames(exportName, names).map(name => ({+ [+ ...new Set([+ // `XMark` for `XMarkIcon`: the library's name with its suffix.+ ...names.filter(+ name =>+ name === `${exportName}Icon` || `${name}Icon` === exportName,+ ),+ ...closestNames(exportName, names),+ ]),+ ].map(name => ({name,reason: `an export of ${module}`,})),@@ -434,7 +595,7 @@ 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+ * Left out: `default`, `Icon`, `…Provider` and `…Context` components, SCREAMING_CASE constants, number and boolean* exports, and `exclude`.* @param {string} file* @param {{adapter?: boolean, exclude?: string[]}} [options] `exclude`: export@@ -447,6 +608,9 @@ function iconCandidates(file, {adapter = false, exclude = []} = {}) {const out = [];for (const name of followedExportNames(file)) {if (name === 'default' || name === 'Icon' || skipped.has(name)) continue;+ // A context provider or context (`LucideProvider`) is a component that+ // draws nothing.+ if (/(?:Provider|Context)$/u.test(name)) continue;// SCREAMING_CASE names are constants (`README`, `VERSION`), not icons.if (SCREAMING_CASE_RE.test(name)) continue;const kind = exportValueKind(file, name);@@ -470,6 +634,21 @@ function iconCandidates(file, {adapter = false, exclude = []} = {}) {: out;}+/**+ * The exports of a library that are not icons and that wrapping it leaves+ * out (`Icon`, `LucideProvider`, `createLucideIcon`, constants), so the+ * receipt can say so. Another name of an icon is not listed.+ * @param {string} file+ * @param {{adapter?: boolean, exclude?: string[]}} [options]+ * @returns {string[]}+ */+export function nonIconExports(file, options = {}) {+ const icons = new Set(iconCandidates(file, options).map(each => each.name));+ return followedExportNames(file).filter(+ name => name !== 'default' && !icons.has(name),+ );+}+/*** The names the library prefix is computed over: the icon-like candidates* (stray constants are already left out by {@link iconCandidates}).@@ -550,7 +729,9 @@ export function modulePrefix(file, options) {* @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}>}+ * @returns {Array<{export: string, id: string, name: string, adapt: boolean, aliases: string[]}>}+ * `aliases`: the ids of the other names the library exports the icon as,+ * leaving out the library's own name (`lucide-trash`)*/export function libraryIcons(file, options = {}) {const candidates = iconCandidates(file, options);@@ -564,7 +745,7 @@ export function libraryIcons(file, options = {}) {entry.names.push(name);byOrigin.set(key, entry);}- /** @type {Array<[string, string, boolean, string | null]>} */+ /** @type {Array<[string, string, boolean, string | null, string[]]>} */const chosen = [];for (const [key, {names, adapt, scalar}] of byOrigin) {const local = key.split('\0')[1];@@ -575,17 +756,48 @@ export function libraryIcons(file, options = {}) {[...(withIcon.length > 0 ? withIcon : names)].sort((a, b) => a.length - b.length || (a < b ? -1 : 1),)[0];- chosen.push([key, preferred, adapt, scalar]);+ chosen.push([key, preferred, adapt, scalar, names]);}const prefix = libraryPrefix(prefixNames(chosen.map(([, name, , scalar]) => ({name, scalar}))),);- /** @type {Map<string, {export: string, id: string, name: string, adapt: boolean}>} */+ /** @type {Map<string, {export: string, id: string, name: string, adapt: boolean, aliases: string[]}>} */const byId = new Map();- for (const [, preferred, adapt] of chosen) {+ for (const [, preferred, adapt, , names] of chosen) {const naming = iconNaming(preferred, prefix);if (!naming.id || byId.has(naming.id)) continue;- byId.set(naming.id, {export: preferred, ...naming, adapt});+ // The other names the library exports the same icon as (Lucide's+ // `Trash2` for `Trash`), as ids: an icon is found and mapped by them too.+ const aliases = [+ ...new Set(names.map(name => iconNaming(name, prefix).id)),+ ].filter(alias => alias && alias !== naming.id);+ byId.set(naming.id, {export: preferred, ...naming, adapt, aliases});+ }+ // A word every alias of most icons starts with (`lucide` in+ // `LucideTrash`) is the library's name, not an alias.+ /** @type {Map<string, number>} */+ const leads = new Map();+ for (const icon of byId.values()) {+ for (const alias of icon.aliases) {+ if (alias.endsWith(`-${icon.id}`)) {+ const lead = alias.slice(0, -icon.id.length - 1);+ leads.set(lead, (leads.get(lead) ?? 0) + 1);+ }+ }+ }+ const brand = new Set(+ [...leads]+ .filter(([, count]) => count >= Math.max(2, byId.size / 2))+ .map(([lead]) => lead),+ );+ for (const icon of byId.values()) {+ icon.aliases = icon.aliases+ .filter(+ alias =>+ ![...brand].some(lead => alias.startsWith(`${lead}-`)) &&+ !byId.has(alias),+ )+ .sort();}return [...byId.values()].sort((a, b) =>a.id < b.id ? -1 : a.id > b.id ? 1 : 0,@@ -677,6 +889,7 @@ export function writeDefinitionFile(set, doc) {);}const text = iconDefinitionSource(doc);+ journalFile(file);fs.mkdirSync(path.dirname(file), {recursive: true});try {fs.writeFileSync(file, text, {encoding: 'utf-8', flag: 'wx'});@@ -695,8 +908,10 @@ export function writeDefinitionFile(set, doc) {/** 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.',+ '// Generated by `astryx experimental icon` (new-set, add, map): one export per icon of this set.',+ '// Edit with those commands; a statement added by hand is kept.',+ '// themeIcons has one entry per built-in icon definition in map (the names Core renders), not one per icon;',+ '// the import lines above it give it local names for the re-exported icons.',];/**@@ -917,8 +1132,11 @@ export function generatedModuleText(/** @param {string} name */const existing = name =>[...exports].find(line =>+ // The name the module exports: after `as`, alone in braces, or a+ // const; never the source name of another export (`TrashIcon as+ // TrashSolidIcon` exports TrashSolidIcon).new RegExp(- `(?:\\b(?:as\\s+|export\\s+\\{\\s*|export const\\s+))${name}\\b`,+ `(?:\\bas\\s+${name}\\s*\\}|^export\\s+\\{\\s*${name}\\s*\\}|^export const\\s+${name}\\b)`,'u',).test(line),);@@ -1075,6 +1293,98 @@ export function generatedNamesOf(packageDir, generated, from, source) {return names;}+/**+ * Where each of the set's exports comes from, read from its generated+ * module: the module it re-exports or adapts (a package specifier, or a+ * `./` path from the package root) and the export it reads there+ * (`default` for a default export). `export {HiTrashIcon as TrashIcon} from+ * '@acme/hero'` gives `TrashIcon` → `{module: '@acme/hero', source:+ * 'HiTrashIcon'}`. An existing icon is known by this first: ids and the+ * set's export names are derived from it, and a newer rule may spell them+ * differently; and a refresh changes only the icons its module supplies.+ * @param {string} packageDir+ * @param {string} generated+ * @returns {Map<string, {module: string, source: string}>}+ */+export function generatedOrigins(packageDir, generated) {+ /** @type {Map<string, {module: string, source: string}>} */+ const origins = new Map();+ const file = path.join(packageDir, generated);+ if (!fs.existsSync(file)) return origins;+ let statements;+ try {+ statements = generatedStatements(fs.readFileSync(file, 'utf-8'), generated);+ } catch {+ return origins;+ }+ /** @param {string} specifier as the generated module writes it */+ const fromRoot = specifier => {+ if (!specifier.startsWith('.')) return specifier;+ const rel = path+ .relative(packageDir, path.resolve(path.dirname(file), specifier))+ .split(path.sep)+ .join('/');+ return `./${rel}`;+ };+ for (const statement of statements) {+ const reexport = /^export \{(\w+)(?: as (\w+))?\} from '([^']+)';$/u.exec(+ statement,+ );+ if (reexport) {+ origins.set(reexport[2] ?? reexport[1], {+ module: fromRoot(reexport[3]),+ source: reexport[1],+ });+ continue;+ }+ const adapted = /^import \{(\w+) as (\w+)Source\} from '([^']+)';$/u.exec(+ statement,+ );+ if (adapted) {+ origins.set(adapted[2], {+ module: fromRoot(adapted[3]),+ source: adapted[1],+ });+ continue;+ }+ const adaptedDefault = /^import (\w+)Source from '([^']+)';$/u.exec(+ statement,+ );+ if (adaptedDefault) {+ origins.set(adaptedDefault[1], {+ module: fromRoot(adaptedDefault[2]),+ source: 'default',+ });+ }+ }+ return origins;+}++/**+ * Whether two module specifiers name the same module: the same package+ * specifier, or the same `./` path from the package root.+ * @param {string} a+ * @param {string} b+ */+export function sameIconModule(a, b) {+ const norm = (/** @type {string} */ value) =>+ value.startsWith('.')+ ? `./${path.posix.normalize(value).replace(/^\.\//u, '')}`+ : value;+ return norm(a) === norm(b);+}++/**+ * The package a module specifier belongs to (`@acme/hero` for+ * `@acme/hero/24/solid`), or `.` for a `./` path in the package itself.+ * @param {string} specifier+ */+export function iconModulePackage(specifier) {+ if (specifier.startsWith('.')) return '.';+ const parts = specifier.split('/');+ return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];+}+/*** Write the set's generated module and its declaration file* ({@link generatedModuleText}). Returns whether either changed, and a@@ -1123,6 +1433,7 @@ export function writeGeneratedIcons(*/const put = (target, text, prior, rel) => {if (prior === text) return;+ journalFile(target);fs.mkdirSync(path.dirname(target), {recursive: true});replaceText(target, text);files.push(rel.replace(/^\.\//u, ''));@@ -1153,9 +1464,122 @@ export function writeGeneratedIcons(};}+/**+ * A package entry the CLI names no line for: a built file (under `dist` or+ * `build`) or CommonJS (`.cjs`, `.cts`, or a `.js` file that uses+ * `require` or `module.exports` and no `export`). Its source is what the+ * author edits.+ * @param {string} packageDir+ * @param {string} entry+ */+function isBuiltOrCommonJs(packageDir, entry) {+ const parts = path.relative(packageDir, entry).split(path.sep);+ if (parts.some(part => part === 'dist' || part === 'build')) return true;+ if (/\.c[jt]s$/u.test(entry)) return true;+ if (!/\.js$/u.test(entry)) return false;+ /** @type {string} */+ let text;+ try {+ text = fs.readFileSync(entry, 'utf-8');+ } catch {+ return false;+ }+ return (+ /\bmodule\.exports\b|\bexports\.[$\w]+\s*=|\brequire\(/u.test(text) &&+ !/^\s*export\s/mu.test(text)+ );+}++/**+ * The exact change that makes a set's generated module part of the+ * package's public entry, so its icons and theme map import from the package+ * by name (FR14), or null when the entry already exports `name`. The CLI+ * never makes this change itself: `exports`, `main`, `types`, `files`, and the+ * entry file are the author's (architecture:cli-surface INV16). `new-set`+ * prints it in its receipt and `integration check` in its finding, the same+ * words. A built or CommonJS entry is never named as the file to edit.+ * @param {string} packageDir+ * @param {Record<string, any>} pkg the package's package.json+ * @param {string} generated the generated module's ./ path from the package root+ * @param {{module?: string, name?: string}} [options] `module` the set's+ * module (default the package name); `name` an export the entry must have+ * (default the theme map)+ * @returns {string | null}+ */+export function entryWiringNote(packageDir, pkg, generated, options = {}) {+ const packageName = typeof pkg.name === 'string' ? pkg.name : '';+ const module = options.module ?? packageName;+ const name = options.name ?? THEME_MAP_NAME;+ const target = generated.replace(/\.[cm]?[jt]sx?$/u, '.js');+ const entry = module+ ? resolveIconModule(module, packageDir, {+ name: packageName,+ dir: packageDir,+ })+ : null;+ if (entry && moduleExportOrigin(entry, name)) return null;+ /** @param {string} from a file in the package */+ const lineFor = from => {+ let relative = path+ .relative(path.dirname(from), path.join(packageDir, target))+ .split(path.sep)+ .join('/');+ if (!relative.startsWith('.')) relative = `./${relative}`;+ return `export * from '${relative}';`;+ };+ const rel = (/** @type {string} */ file) =>+ path.relative(packageDir, file).split(path.sep).join('/');+ const inside = (/** @type {string} */ file) => {+ const relative = path.relative(packageDir, file);+ return (+ !relative.startsWith('..') &&+ !path.isAbsolute(relative) &&+ !relative.split(path.sep).includes('node_modules')+ );+ };+ if (!entry) {+ if (+ pkg.exports === undefined &&+ pkg.main === undefined &&+ !fs.existsSync(path.join(packageDir, 'index.js'))+ ) {+ const line = lineFor(path.join(packageDir, 'index.js'));+ const files = Array.isArray(pkg.files)+ ? ` Add "index.js" and "index.d.ts" to "files".`+ : '';+ return `"${module}" has no entry, so its icons cannot be imported by name. Create index.js and index.d.ts, each with \`${line}\`, and add to package.json: \`"main": "./index.js", "types": "./index.d.ts", "exports": {".": {"types": "./index.d.ts", "default": "./index.js"}}\`.${files}`;+ }+ return `"${module}" does not resolve: point its package.json "exports" at a file that has \`export * from '${target}';\` (relative to that file), or build the package.`;+ }+ if (!inside(entry) || isBuiltOrCommonJs(packageDir, entry)) {+ return `${inside(entry) ? rel(entry) : `"${module}"`} is built or CommonJS, so the CLI names no file to edit: add \`export * from '${target}';\` (relative to that file) to the source module your build compiles into it, and to its types, then build, so the icons and \`${THEME_MAP_NAME}\` import from ${module}.`;+ }+ const rootExport =+ pkg.exports && typeof pkg.exports === 'object' ? pkg.exports['.'] : null;+ const typesPath =+ (typeof pkg.types === 'string' && pkg.types) ||+ (typeof pkg.typings === 'string' && pkg.typings) ||+ (rootExport &&+ typeof rootExport === 'object' &&+ typeof rootExport.types === 'string'+ ? rootExport.types+ : null);+ const typesFile = typesPath ? path.resolve(packageDir, typesPath) : null;+ const alsoTypes =+ typesFile &&+ typesFile !== entry &&+ inside(typesFile) &&+ fs.existsSync(typesFile) &&+ !isBuiltOrCommonJs(packageDir, typesFile) &&+ !fs.readFileSync(typesFile, 'utf-8').includes(lineFor(typesFile))+ ? ` and \`${lineFor(typesFile)}\` to ${rel(typesFile)}`+ : '';+ return `Add \`${lineFor(entry)}\` to ${rel(entry)}${alsoTypes}, so the icons import from ${module}.`;+}+/*** Whether the set's own module exports `name`, read without running it, and- * the line its entry needs when it does not.+ * the line its entry needs when it does not ({@link entryWiringNote}).* @param {DiscoveredIconSet} set* @param {{packageDir: string, pkg: Record<string, any>}} where* @param {string} generated the generated module's ./ path from the package root@@ -1163,19 +1587,169 @@ export function writeGeneratedIcons(* @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,+ return entryWiringNote(where.packageDir, where.pkg, generated, {+ module: set.data.module,+ name,});- 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')}';\`.`;+}++/**+ * The peers an icon-set package publishes with, as the guide's "Before you+ * publish" asks, that package.json does not declare yet, as the exact JSON+ * to add, or null when it declares them all: `react` (the theme map and+ * adapter use it), and as optional peers `@types/react` (the generated+ * declaration file imports it) and `@astryxdesign/cli` from this release.+ * The CLI never edits them (architecture:cli-surface INV16).+ * @param {Record<string, any>} pkg+ * @returns {string | null}+ */+export function peerNote(pkg) {+ /** @type {Array<[string, string, boolean]>} */+ const wanted = [+ ['react', '>=18', false],+ ['@types/react', '>=18', true],+ ['@astryxdesign/cli', `>=${cliVersion()}`, true],+ ];+ const missing = wanted.filter(+ ([name]) => pkg.peerDependencies?.[name] == null,+ );+ if (missing.length === 0) return null;+ const peers = missing.map(([name, range]) => `"${name}": "${range}"`);+ const optional = missing+ .filter(([, , isOptional]) => isOptional)+ .map(([name]) => `"${name}": {"optional": true}`);+ return `Declare the peers your set needs; add to package.json "peerDependencies": \`{${peers.join(', ')}}\`${optional.length > 0 ? ` and to "peerDependenciesMeta": \`{${optional.join(', ')}}\`` : ''}.`;+}++/**+ * The `typecheck` script every integration runs in its build, as the line to+ * add, or null when package.json has one.+ * @param {Record<string, any>} pkg+ * @returns {string | null}+ */+export function typecheckNote(pkg) {+ if (pkg.scripts?.typecheck != null) return null;+ return 'Run `integration check --strict` in your build; add to package.json "scripts": `"typecheck": "astryx integration check --strict"`.';+}++/**+ * A definition name as `map` keys it: camelCase. The docs list each+ * definition by its kebab id too (`eye-slash`), so that spelling resolves.+ * @param {string} name+ * @param {Set<string>} known the definitions the set may map+ * @returns {string}+ */+export function definitionNameOf(name, known) {+ if (known.has(name)) return name;+ const camel = name.replace(/-([a-z0-9])/gu, (_, c) => c.toUpperCase());+ return known.has(camel) ? camel : name;+}++/**+ * An icon id in the set, named by its id, its export name in any case+ * (`XMarkIcon`, `xmark`), or another name the library exports the same icon+ * as, as an id or as the library spells it (`trash-2` or `Trash2` for+ * `trash`, recorded in its words; AST-084 FR13). Never by a word alone:+ * null when none of these names an icon.+ * @param {{data: {icons: Array<{id: string, export: string, words: string[]}>}}} set+ * @param {string} id+ * @returns {string | null}+ */+export function iconIdIn(set, id) {+ if (set.data.icons.some(icon => icon.id === id)) return id;+ // The export, or the name the library exports it by (`XMarkIcon`,+ // `XMark`, `X`), in any case.+ const lower = id.toLowerCase();+ const byExport = set.data.icons.find(+ icon =>+ icon.export.toLowerCase() === lower ||+ icon.export.toLowerCase() === `${lower}icon`,+ );+ if (byExport) return byExport.id;+ // A library export name (`Trash2`, `Search`) is spelled as the id it+ // gives (`trash-2`, `search`), which is the icon's id or one of the other+ // names its library exports it as.+ const candidates = [id, ...(/[A-Z]/u.test(id) ? [iconIdOf(id)] : [])];+ for (const candidate of candidates) {+ if (set.data.icons.some(icon => icon.id === candidate)) return candidate;+ // Another name the library exports the icon as: one of its words that+ // is not a part of its own id. A part of an id (`glass` in+ // `magnifying-glass`) names no icon, and neither does a name two icons+ // share.+ const holders = set.data.icons.filter(icon =>+ otherNamesOf(icon).includes(candidate),+ );+ if (holders.length === 1) return holders[0].id;+ }+ return null;+}++/**+ * The other names a library exports an icon as, recorded among its words:+ * each word that is not a part of its id.+ * @param {{id: string, words?: string[]}} icon+ * @returns {string[]}+ */+export function otherNamesOf(icon) {+ const parts = icon.id.split('-');+ return (icon.words ?? []).filter(word => !parts.includes(word));+}++/**+ * The icons that carry `word` but are not named by it, for a refusal's+ * suggestions: `glass` is a word of `magnifying-glass`, not its name.+ * @param {{data: {icons: Array<{id: string, words?: string[]}>}}} set+ * @param {string} word+ * @returns {string[]}+ */+export function iconsWithWord(set, word) {+ return set.data.icons+ .filter(+ icon =>+ (icon.words ?? []).includes(word) || icon.id.split('-').includes(word),+ )+ .map(icon => icon.id)+ .slice(0, 5);+}++/**+ * The package.json `files` change a ./ source needs to ship, or null when+ * the package lists no `files` or one covers it: its own folder (`src/icons`+ * for `./src/icons/x.js`), as the exact array. The CLI never edits `files`+ * (architecture:cli-surface INV16).+ * @param {string} packageDir+ * @param {string} module the source specifier+ * @returns {string | null}+ */+export function localSourceNote(packageDir, module) {+ if (!module.startsWith('./')) return null;+ // The file's own folder (`src/icons`), never more: other files beside+ // the package's source stay unpublished.+ const parts = module.slice(2).split('/');+ const top = parts.length > 1 ? parts.slice(0, -1).join('/') : parts[0];+ if (!top) 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 (!Array.isArray(pkg.files)) return null;+ const normalize = (/** @type {string} */ value) =>+ value.replace(/^\.\//u, '').replace(/\/$/u, '');+ const wanted = normalize(module);+ if (+ pkg.files.some(+ (/** @type {unknown} */ each) =>+ typeof each === 'string' &&+ (wanted === normalize(each) ||+ wanted.startsWith(`${normalize(each)}/`)),+ )+ ) {+ return null;}- 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}.`;+ return `${module} is not in package.json "files", so it would not be published; set "files" to \`${JSON.stringify([...pkg.files, top])}\`.`;}diff --git a/packages/cli/foundation/discovery/icon-set-writer.test.mjs b/packages/cli/foundation/discovery/icon-set-writer.test.mjsnew file mode 100644index 0000000000..cf966fdb1c--- /dev/null+++ b/packages/cli/foundation/discovery/icon-set-writer.test.mjs@@ -0,0 +1,26 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file Icon ids from export names (AST-084): a dimension stays one word. */++import {describe, expect, it} from 'vitest';+import {iconIdOf} from './icon-set-writer.mjs';++describe('iconIdOf', () => {+ it.each([+ ['XMarkIcon', 'x-mark'],+ ['Trash2', 'trash-2'],+ ['ArrowUpDown', 'arrow-up-down'],+ ['Squares2X2Icon', 'squares-2x2'],+ ['Grid2x2', 'grid-2x2'],+ ['Grid2X2Check', 'grid-2x2-check'],+ ['Grid3x3', 'grid-3x3'],+ ['Tally5', 'tally-5'],+ ['H1Icon', 'h1'],+ ['Box', 'box'],+ ['CalendarX2', 'calendar-x-2'],+ ['MapPinXInside', 'map-pin-x-inside'],+ ['Heading1', 'heading-1'],+ ])('%s → %s', (name, id) => {+ expect(iconIdOf(name)).toBe(id);+ });+});diff --git a/packages/cli/foundation/discovery/module-exports.mjs b/packages/cli/foundation/discovery/module-exports.mjsindex 0760f95dae..01ab5a478b 100644--- a/packages/cli/foundation/discovery/module-exports.mjs+++ b/packages/cli/foundation/discovery/module-exports.mjs@@ -146,15 +146,44 @@ const NOT_CHILDREN = new Set([]);/**- * Every node of `type` in the tree, at any depth, in source order.+ * Every node of `type` under each tree walked, by tree and type: a parsed+ * module is cached and never changes, so a library of a thousand icons is+ * walked once per type, not once per export looked up.+ * @type {WeakMap<object, Map<string, readonly any[]>>}+ */+const nodesByTree = new WeakMap();++/**+ * Every node of `type` in the tree, at any depth, in source order. The+ * answer is shared: callers only read it.+ * @param {any} node+ * @param {string} type+ * @returns {readonly any[]}+ */+function nodesOfType(node, type) {+ if (node == null || typeof node !== 'object') return [];+ let byType = nodesByTree.get(node);+ if (!byType) {+ byType = new Map();+ nodesByTree.set(node, byType);+ }+ let found = byType.get(type);+ if (!found) {+ found = collectNodesOfType(node, type, []);+ byType.set(type, found);+ }+ return found;+}++/*** @param {any} node* @param {string} type- * @param {any[]} [found]+ * @param {any[]} found* @returns {any[]}*/-function nodesOfType(node, type, found = []) {+function collectNodesOfType(node, type, found) {if (Array.isArray(node)) {- for (const child of node) nodesOfType(child, type, found);+ for (const child of node) collectNodesOfType(child, type, found);return found;}if (node == null || typeof node !== 'object') return found;@@ -163,7 +192,7 @@ function nodesOfType(node, type, found = []) {if (NOT_CHILDREN.has(key)) continue;const child = node[key];if (child != null && typeof child === 'object') {- nodesOfType(child, type, found);+ collectNodesOfType(child, type, found);}}return found;@@ -890,6 +919,43 @@ export function staticExportObject(file, exportNames) {return null;}+/**+ * A module's runtime named exports, indexed once per parsed tree: the+ * export declarations that declare something, and each export specifier by+ * the name it exports, in source order.+ * @type {WeakMap<object, {declarations: any[], specifiers: Map<string, Array<{node: any, specifier: any}>>}>}+ */+const namedExportIndexes = new WeakMap();++/** @param {any} program */+function namedExportIndex(program) {+ const cached = namedExportIndexes.get(program);+ if (cached) return cached;+ /** @type {any[]} */+ const declarations = [];+ /** @type {Map<string, Array<{node: any, specifier: any}>>} */+ const specifiers = new Map();+ for (const node of nodesOfType(program, 'ExportNamedDeclaration')) {+ if (node.exportKind === 'type') continue;+ if (node.declaration) declarations.push(node);+ for (const specifier of node.specifiers ?? []) {+ if (+ specifier.type !== 'ExportSpecifier' ||+ specifier.exportKind === 'type'+ ) {+ continue;+ }+ const exported = specifier.exported?.name ?? specifier.exported?.value;+ const list = specifiers.get(exported) ?? [];+ list.push({node, specifier});+ specifiers.set(exported, list);+ }+ }+ const index = {declarations, specifiers};+ namedExportIndexes.set(program, index);+ return index;+}+/*** 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@@ -911,30 +977,21 @@ export function moduleExportOrigin(file, exportName, seen = new Set()) {} catch {return null;}- for (const node of nodesOfType(ast.program, 'ExportNamedDeclaration')) {- if (node.exportKind === 'type') continue;+ const {declarations, specifiers} = namedExportIndex(ast.program);+ for (const node of declarations) {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);+ }+ for (const {node, specifier} of specifiers.get(exportName) ?? []) {+ 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')) {diff --git a/packages/cli/foundation/discovery/module-exports.test.mjs b/packages/cli/foundation/discovery/module-exports.test.mjsindex 3da8ee17c4..32577f53eb 100644--- a/packages/cli/foundation/discovery/module-exports.test.mjs+++ b/packages/cli/foundation/discovery/module-exports.test.mjs@@ -9,7 +9,11 @@ import {afterEach, beforeEach, describe, expect, it} from 'vitest';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';-import {moduleExportSource, staticExportObject} from './module-exports.mjs';+import {+ moduleExportOrigin,+ moduleExportSource,+ staticExportObject,+} from './module-exports.mjs';/** @type {string} */let dir;@@ -170,3 +174,36 @@ describe('moduleExportSource', () => {expect(moduleExportSource(file, 'AcmePanel')).toBeNull();});});++describe('a library of thousands of icons', () => {+ it('finds the origin of every export in about linear time', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-many-exports-'));+ try {+ const count = 3000;+ fs.writeFileSync(+ path.join(dir, 'icon.js'),+ 'export function make(name) { return function Icon() { return name; }; }\n',+ );+ const lines = ["import {make} from './icon.js';"];+ for (let i = 0; i < count; i++) {+ lines.push(`const Glyph${i} = make('g${i}');`);+ lines.push(+ `export {Glyph${i}, Glyph${i} as Glyph${i}Icon, Glyph${i} as LucideGlyph${i}};`,+ );+ }+ const file = path.join(dir, 'index.js');+ fs.writeFileSync(file, `${lines.join('\n')}\n`);+ const started = Date.now();+ for (let i = 0; i < count; i++) {+ expect(moduleExportOrigin(file, `Glyph${i}Icon`)).toEqual({+ file,+ name: `Glyph${i}`,+ });+ }+ // Walking the whole module once per lookup took minutes.+ expect(Date.now() - started).toBeLessThan(10_000);+ } finally {+ fs.rmSync(dir, {recursive: true, force: true});+ }+ }, 60_000);+});diff --git a/packages/cli/foundation/discovery/template-icons.mjs b/packages/cli/foundation/discovery/template-icons.mjsindex 7dca5dd06c..9bd2b474a5 100644--- a/packages/cli/foundation/discovery/template-icons.mjs+++ b/packages/cli/foundation/discovery/template-icons.mjs@@ -63,6 +63,9 @@ import {astryxDefinitionsByName} from './icon-definition-discovery.mjs';* @typedef {object} MappedIcon* @property {{module: string, export: string}} source* @property {{set: string, package: string, id: string, module: string, export: string}} target+ * @property {string[]} [dropped] the library's sizing props (`size`,+ * `strokeWidth`, `absoluteStrokeWidth`) removed from its elements: an icon+ * set's icons take their size from CSS* @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@@ -390,6 +393,12 @@ export function iconsNotImported(source, declared) {return Object.keys(declared).filter(key => !keys.has(key));}+/**+ * A library's own sizing props, dropped from a mapped icon: an icon set's+ * icons take their size from CSS.+ */+const SIZING_PROPS = new Set(['size', 'strokeWidth', 'absoluteStrokeWidth']);+/** What a template reads with no icon-set state given: nothing is mapped. */export const NO_ICON_SETS = Object.freeze({sets: [],@@ -520,6 +529,10 @@ export function mapTemplateIcons(source, {sets, choice}, declared = {}) {let insertAt = -1;/** The declared keys reported as mapped or kept so far. */const accounted = new Set();+ /** The local names of mapped imports, as the template wrote them. */+ const mappedLocals = new Set();+ /** @type {Array<[MappedIcon, string]>} each mapped icon and its local name */+ const mappedEntries = [];for (const node of ast.program.body) {if (node.type !== 'ImportDeclaration') continue;@@ -582,7 +595,9 @@ export function mapTemplateIcons(source, {sets, choice}, declared = {}) {added.set(key, entry);}if (local !== entry.local) renames.set(local, entry.local);- icons.mapped.push({+ mappedLocals.add(local);+ /** @type {MappedIcon} */+ const mappedIcon = {source: {module, export: imported},target: {set: target.name,@@ -592,30 +607,74 @@ export function mapTemplateIcons(source, {sets, choice}, declared = {}) {export: chosen.export,},by: match.by,- });+ };+ icons.mapped.push(mappedIcon);+ mappedEntries.push([mappedIcon, local]);}if (keep.length === node.specifiers.length) continue;if (insertAt === -1) insertAt = node.start;+ // Comments inside the statement, and one that trails it on its line,+ // survive the rewrite: those a kept specifier does not carry move to+ // their own lines above it.+ // A kept specifier carries a comment beside it with only whitespace+ // between (`Pencil /* pen */`).+ const keptRanges = keep.map(each => {+ let [a, b] = [each.start, each.end];+ for (const comment of ast.comments ?? []) {+ if (comment.start < node.start || comment.end > node.end) continue;+ if (comment.start >= b && /^\s*$/u.test(source.slice(b, comment.start)))+ b = comment.end;+ }+ for (const comment of [...(ast.comments ?? [])].reverse()) {+ if (comment.start < node.start || comment.end > node.end) continue;+ if (comment.end <= a && /^\s*$/u.test(source.slice(comment.end, a)))+ a = comment.start;+ }+ return [a, b];+ });+ const inside = (ast.comments ?? []).filter(+ (/** @type {any} */ comment) =>+ comment.start >= node.start &&+ comment.end <= node.end &&+ !keptRanges.some(([a, b]) => comment.start >= a && comment.end <= b),+ );+ const trailing = /^[ \t]*(\/\/[^\n]*|\/\*[^\n]*?\*\/)[ \t]*(?=\n|$)/u.exec(+ source.slice(node.end),+ );+ /** @type {string[]} */+ const moved = inside.map((/** @type {any} */ comment) =>+ source.slice(comment.start, comment.end),+ );+ const above = moved.map(comment => `${comment}\n`).join('');if (keep.length === 0) {let end = node.end;+ if (trailing) {+ moved.push(trailing[1]);+ end += trailing[0].length;+ }if (source[end] === '\n') end += 1;- edits.push({start: node.start, end, text: ''});+ edits.push({+ start: node.start,+ end,+ text: moved.map(comment => `${comment}\n`).join(''),+ });} else {+ /** @param {any} each */+ const textOf = each => {+ const [a, b] = keptRanges[keep.indexOf(each)];+ return source.slice(a, b);+ };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(', ')}}`,- ]- : []),+ ...defaults.map(textOf),+ ...(named.length > 0 ? [`{${named.map(textOf).join(', ')}}`] : []),];edits.push({start: node.start,end: node.end,- text: `import ${parts.join(', ')} from ${source.slice(node.source.start, node.source.end)};`,+ text: `${above}import ${parts.join(', ')} from ${source.slice(node.source.start, node.source.end)};`,});}}@@ -678,6 +737,35 @@ export function mapTemplateIcons(source, {sets, choice}, declared = {}) {edits.push({start: node.start, end: node.end, text: next});}});+ // Size comes from CSS in every icon set (its export contract), so a+ // library's own sizing props on a mapped icon are dropped and reported.+ /** @type {Map<string, Set<string>>} local name → props dropped */+ const dropped = new Map();+ walk(ast.program, node => {+ if (node.type !== 'JSXOpeningElement' || node.name.type !== 'JSXIdentifier')+ return;+ const local = node.name.name;+ if (!mappedLocals.has(local)) return;+ for (const attribute of node.attributes) {+ if (+ attribute.type !== 'JSXAttribute' ||+ attribute.name.type !== 'JSXIdentifier' ||+ !SIZING_PROPS.has(attribute.name.name)+ ) {+ continue;+ }+ let start = attribute.start;+ while (start > 0 && /\s/u.test(source[start - 1])) start -= 1;+ edits.push({start, end: attribute.end, text: ''});+ const set = dropped.get(local) ?? new Set();+ set.add(attribute.name.name);+ dropped.set(local, set);+ }+ });+ for (const [entry, local] of mappedEntries) {+ const props = dropped.get(local);+ if (props) entry.dropped = [...props].sort();+ }// A shorthand property is visited as both key and value; keep one edit.const unique = new Map();for (const edit of edits) {diff --git a/packages/cli/foundation/discovery/template-icons.test.mjs b/packages/cli/foundation/discovery/template-icons.test.mjsindex ac41f87533..626c6570c6 100644--- a/packages/cli/foundation/discovery/template-icons.test.mjs+++ b/packages/cli/foundation/discovery/template-icons.test.mjs@@ -125,6 +125,59 @@ describe('mapTemplateIcons', () => {]);});+ it("drops a library's sizing props from a mapped icon and reports them", () => {+ const {source, icons} = map(+ [+ "import {CloseGlyph, PencilGlyph} from '@acme/library';",+ '',+ 'export const A = () => (',+ ' <div>',+ ' <CloseGlyph size={16} strokeWidth={2} className="x" />',+ ' <CloseGlyph',+ ' absoluteStrokeWidth',+ ' />',+ ' <PencilGlyph size={16} />',+ ' </div>',+ ');',+ '',+ ].join('\n'),+ DECLARED,+ );+ expect(source).toContain('<XIcon className="x" />');+ expect(source).toMatch(/<XIcon\s*\/>/u);+ expect(source).not.toContain('absoluteStrokeWidth');+ // A kept icon keeps its props.+ expect(source).toContain('<PencilGlyph size={16} />');+ expect(icons.mapped[0].dropped).toEqual([+ 'absoluteStrokeWidth',+ 'size',+ 'strokeWidth',+ ]);+ expect(icons.kept[0]).not.toHaveProperty('dropped');+ });++ it('keeps comments inside and after a rewritten import line', () => {+ const {source} = map(+ [+ "import {CloseGlyph /* close */, PencilGlyph /* pen */} from '@acme/library'; // tools",+ "import {HomeGlyph} from '@acme/library/home'; // the home link",+ '',+ 'export const A = () => <><CloseGlyph /><PencilGlyph /><HomeGlyph /></>;',+ '',+ ].join('\n'),+ DECLARED,+ );+ expect(source).toContain('/* close */');+ expect(source).toContain('/* pen */');+ expect(source).toContain('// tools');+ expect(source).toContain('// the home link');+ // Each comment is outside any code it would swallow.+ expect(source).toContain(+ "import {PencilGlyph /* pen */} from '@acme/library'; // tools",+ );+ expect(source).toMatch(/^\/\/ the home link$/mu);+ });+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";@@ -455,3 +508,53 @@ describe('icons another installed set ships', () => {]);});});++describe('one key for a name imported from two modules (FR9)', () => {+ it('maps both imports by the one key, and each keeps its variant', () => {+ const LINES = /** @type {any} */ ({+ name: 'lines',+ package: '@acme/lines',+ data: {+ schemaVersion: 1,+ module: '@acme/lines',+ variants: ['outline', 'solid'],+ default: {variant: 'outline'},+ map: {delete: 'trash'},+ icons: [+ {+ id: 'trash',+ export: 'TrashIcon',+ words: ['trash'],+ variants: [+ {+ variant: 'solid',+ export: 'TrashIcon',+ module: '@acme/lines/solid',+ },+ ],+ },+ ],+ },+ });+ const {source, icons} = map(+ [+ "import {TrashIcon} from '@acme/lines';",+ "import {TrashIcon as TrashSolid} from '@acme/lines/solid';",+ 'export const A = () => <><TrashIcon /><TrashSolid /></>;',+ '',+ ].join('\n'),+ {TrashIcon: 'delete'},+ SELECTED,+ [SET, LINES],+ );+ expect(+ icons.mapped.map(each => [each.source.module, each.target.export]),+ ).toEqual([+ ['@acme/lines', 'TrashIcon'],+ ['@acme/lines/solid', 'TrashSolidIcon'],+ ]);+ expect(source).toContain(+ "import {TrashIcon, TrashSolidIcon} from '@acme/glyphs';",+ );+ });+});diff --git a/packages/cli/foundation/doc-compiler/tree.mjs b/packages/cli/foundation/doc-compiler/tree.mjsindex a1149d0942..d00d2d0d6f 100644--- a/packages/cli/foundation/doc-compiler/tree.mjs+++ b/packages/cli/foundation/doc-compiler/tree.mjs@@ -986,7 +986,9 @@ export function iconDefinitionTreeInput(doc, file, provider, providerId) {kind: 'icon-definition',name: doc.name,title: doc.name,- summary: doc.description,+ // Built-in definitions are the ones every set must map; the words are+ // what an author searches the library for.+ summary: `${doc.builtIn ? '[built-in] ' : ''}${doc.description}${doc.words.length > 0 ? ` Words: ${doc.words.join(', ')}.` : ''}`,group: ICON_DEFINITIONS_GROUP,placement: undefined,ref: {selfDoc: doc},diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex 0feb96f746..101fd28604 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -139,6 +139,12 @@ export const doc = {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.mapMany',+ stability: 'experimental',+ description:+ 'Many `map` entries written at once (--pairs): the set, its package, the data file, each entry {definition, icon, previous, changed}, whether anything changed, and the generated files rewritten.',+ },{value: 'icon.map',stability: 'experimental',@@ -151,6 +157,24 @@ export const doc = {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.definitions',+ stability: 'experimental',+ description:+ 'Every Astryx icon definition (--definitions): each {name, builtIn, description, words}.',+ },+ {+ value: 'icon.setIcons',+ stability: 'experimental',+ description:+ 'Every icon of one set (--set with --all-icons): the set, its package, how many icons, and each icon {id, export, words, definitions}, by id.',+ },+ {+ value: 'icon.addVariants',+ stability: 'experimental',+ description:+ 'One variant added for every icon of the set at once (--all): the set, its package, the variant, the module read, how many icons gained it, how many already had it, the ids the module has no export for, the files written, and whether anything changed.',+ },{value: 'icon.definitionMatches',stability: 'experimental',@@ -189,7 +213,7 @@ export const doc = {{value: 'discover.item',description:- '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.',+ "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.",},{value: 'discover.search',diff --git a/packages/cli/test/template-icon-declarations.test.mjs b/packages/cli/test/template-icon-declarations.test.mjsindex b4aeeee4dc..2620cc1b87 100644--- a/packages/cli/test/template-icon-declarations.test.mjs+++ b/packages/cli/test/template-icon-declarations.test.mjs@@ -30,42 +30,28 @@ const NO_DEFINITION_YET = new Set(['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',