An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): experimental icon sets — wrapping a large real icon library (#8013)
Joey05e3cb0e1f84
diff --git a/.changeset/cli-icon-sets-real-library.md b/.changeset/cli-icon-sets-real-library.mdnew file mode 100644index 0000000000..7fbebee900--- /dev/null+++ b/.changeset/cli-icon-sets-real-library.md@@ -0,0 +1,15 @@+---+'@astryxdesign/cli': patch+---++[experimental] Icon sets: wrapping a large icon library that names its looks in its exports works in seconds and gives one icon per glyph. Only the experimental icon commands, the icon-set guide, and `integration check` on an icon set change.++- **Large libraries.** `experimental icon new-set --from` reads a library of 20,000 exports in about ten seconds instead of minutes, and in text mode says on stderr that it is reading and what it found. `iconNewSet` and `iconAdd` report reading progress for large modules through the shared `logger` (stderr, text mode only); called directly, they stay silent until `logger.setSilent(false)`.+- **Libraries of looks.** A library whose export names end in style, size and weight words (`XOutline24WGHT500Icon`), never direction words like `Up` and `Down`, gives one icon per glyph, named `x` (`XIcon`), in the look the set's default variant names, else the library's usual default; suggestions and `add` name icons by glyph, `add --variant filled --all` picks each glyph's filled look, a refresh keeps every icon an earlier release wrapped, and a refresh with a new `--default-variant` moves each glyph to that look. Every command that records the default variant takes it from the look each icon's export draws, refuses a look word the library does not have, and never adds a second export of an icon.+- **Variants on an existing set.** `experimental icon new-set <set> --variants outline,filled` without `--from` declares variants (a set with icons keeps its default variant, or, with none declared, takes the look its icons draw; a set whose library's export names name no looks keeps it on a refresh too, refuses `--variants` that leave it out, and the refusal names the `add --variant` run that adds the other look), and `--display-name` and `--description` rewrite the descriptor, in place; `add --variant` names an undeclared variant with that command.+- **Commands that run as printed.** Every command `new-set`, `add` and `map` print names the set, with `--set` where the command takes it; the commands `add` lists repeat `--default` and `--id`; `--new-definition` and `new-definition` take kebab-case as the definitions list shows it, and an unknown `--definition` suggests a name the next command takes.+- **Search.** `experimental icon star` no longer offers `start`, a plural matches its singular, `go home` finds the icon mapped to `home`, and a letter or two never matches inside a word.+- **Checks.** A set's own definitions pass `integration check --strict`, and the generated module and its declaration file pass after a formatter rewrites them.+- **Theme icons.** Each `themeIcons` entry is sized to its box by CSS, so a component that writes its own size attributes still fills the theme's icon box.++@josephfarinadiff --git a/docs/specs/AST-084-icon-sets/spec.md b/docs/specs/AST-084-icon-sets/spec.mdindex 2b7c3dae36..d8ab0a881f 100644--- a/docs/specs/AST-084-icon-sets/spec.md+++ b/docs/specs/AST-084-icon-sets/spec.md@@ -169,11 +169,19 @@ 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,- which answers only when nothing scores 60 or more. An icon also answers to+ leads), 60 when the query starts one of its words, 40 for a partial match+ (three letters or more inside a word). A word's plural or singular is an+ exact match (`stars` for `star`); a word that only starts with the query+ (`start`) answers only when nothing matches a whole word, and a partial+ match only when nothing scores 60 or more. A query is scored as typed+ first; only when nothing answers it with a whole word are the words that+ only phrase it (`go`, `the`, `icon`) left out of a query of several words,+ so `go home` asks for `home` and `arrow up to line` still names+ `arrow-up-to-line`. An icon also answers tothe name and words of every definition it draws. Equal scores are ordered byset 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+ name match on the whole id, then on its plural or singular, before one on+ an id part, and an exact meaningmatch 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 ofthat set (`icon.setIcons`), and `--definitions` lists every Astryx@@ -224,7 +232,9 @@ icon, and the CLI verifies it, writes the files, and checks the set.Icons join it only at promotion.- **FR12 — The theme map.** A set exports the map `themeMap` names: one entryper built-in definition in `map`, each its icon's artwork, so a theme sets- `icons: themeIcons`.+ `icons: themeIcons`. Each entry is sized to the theme's icon box by CSS+ (`style` width and height `1em`) as well as by attributes, so an icon whose+ component writes its own size attributes still draws at the box's size.### Authoring@@ -266,6 +276,17 @@ icon, and the CLI verifies it, writes the files, and checks the set.`draft`). Never an icon `map` already uses, one whose `id` is anotherdefinition's name, a negated form (`lock-open`, `bell-off`), or theopposite direction (`ellipsis-vertical` for `moreHorizontal`).+ A library whose export names end in look words (a style, a size, a+ weight: `XOutline24WGHT500Icon`), read from its trailing words that a few+ values fill on nearly every export and that are numbered or include a+ style word, never a direction word (`ArrowUp` and `ArrowDown` are two+ glyphs), gives one icon per glyph, named+ without them (`x`, `XIcon`), in the look the default variant names, else+ the library's usual default (`outline`, `regular`), else the middle of a+ numbered series; the receipt names the looks it found and how many+ exports draw the icons. Reading a module of a thousand exports or more,+ here, on a refresh, and in `add`, prints its progress on stderr in text+ mode, naming the module as given.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;@@ -284,8 +305,19 @@ icon, and the CLI verifies it, writes the files, and checks the set.`@types/react` and `@astryxdesign/cli` peers it does not declare, and a`typecheck` script running `integration check --strict` when it hasnone. `--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+ `default`; `--display-name` and `--description` fill the descriptor.+ Without `--from`, over an existing set, those four options update it in+ place and leave its icons, `map`, and generated module as they are; a+ variant an icon has must stay declared, a set with icons keeps its+ default variant (in a library of looks the refusal names the `--from`+ run that moves it), and the receipt carries `updated`. A set whose+ icons' export names name no looks keeps its default variant on a+ refresh too, since its icons keep their exports; the refusal names the+ `add --variant <name> --from <module> --all --set <set>` run that adds the look. Over an existing set, `--variants` without+ `--default-variant` keeps the set's default variant while it stays+ declared; in a library of looks, it takes the look the icons' exports+ draw, which `--variants` must list. Run again with `--from`, it+ refreshes the icons that module supplies (those the generatedmodule re-exports or adapts from it) and keeps `map` entries whose iconexists; every other icon (the author's `./` artwork, another library's)is kept with its `map` entries and variants, a library icon whose `id`@@ -302,14 +334,33 @@ icon, and the CLI verifies it, writes the files, and checks the set.when its `license` is still the one `new-set` wrote (the package's own,or `UNLICENSED`); a `license` the author changed is kept, and thereceipt names both. Later runs keep the descriptor's `license`. The- package's own `license` is never written.+ package's own `license` is never written. In a library of looks, a look+ the set already wraps keeps its icon and `id`, so a set wrapped one look+ at a time loses and renames nothing, and a new glyph comes in once; a+ new `--default-variant` moves each glyph's own icon to the look it+ names, and the icon keeps its `id` and export. A new+ `--default-variant` that is none of the library's look words is+ refused, the look words named, and nothing is 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. 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 `./`+ that declared variant of an existing icon, and names a variant the set+ does not declare with the command that declares it, which names the+ set's default variant. Each command it+ lists names the set with `--set` and repeats `--default` and `--id` as+ passed, so it runs as printed. A new definition is named in camelCase or kebab-case and written+ in camelCase. From a library of looks it names the icon by its glyph;+ when the set already exports that glyph's name for another export of the+ library, the export keeps its look words in its id and name, or takes+ its name from `--id`, and when its first look word that differs from+ the wrapped export's is a declared variant other than the default, the+ listing adds the command that adds it as that icon's variant. 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 a library of looks, the glyph's look of that name), in one write; an+ icon from another module is left alone and not listed as missing, and a+ glyph drawn in no look of that name, or whose own export is that look,+ is listed as missing. For a `./`file outside package.json `files`, it names the `files` array thatpublishes it.- `experimental icon map <definition> <icon>` writes one `map` entry,@@ -323,7 +374,10 @@ icon, and the CLI verifies it, writes the files, and checks the set.writes `experimental.iconSet`.- The generated module re-exports each library component, or wraps a dataexport with the adapter, and rewrites its declaration file and theme map- with every change.+ with every change. It and its declaration file are read statement by+ statement however a formatter left them, with or without semicolons,+ so a formatted module is+ rewritten and checked like the one the CLI wrote.- **FR14 — The export contract.** Every icon and variant is a named`<Name>Icon` export of the package's public entry: a React component, or anadapter call, that takes SVG props, draws with `currentColor`, and fills its@@ -352,7 +406,7 @@ icon, and the CLI verifies it, writes the files, and checks the set.| `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 the- `icon map` command that fixes it, and suggests icons by the rule `new-set`+ `icon map` command, with `--set`, that fixes it, and suggests icons by the rule `new-set`uses (FR13), never from part of a word. When the package's entry exportsneither 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 ofdiff --git a/packages/cli/api/icon/_adapter.mjs b/packages/cli/api/icon/_adapter.mjsindex d0e5df5dbc..097df0cd56 100644--- a/packages/cli/api/icon/_adapter.mjs+++ b/packages/cli/api/icon/_adapter.mjs@@ -6,8 +6,8 @@** @position api/icon — adapter for api/icon/{search,detail,list,use,map,add,* new-set,new-definition}; it also carries the icon ranking, the icon-set- * writer, the set and definition authoring writes, and the config writer- * the leaves use+ * writer, the set and definition authoring writes, the default-look+ * rule, and the config writer the leaves use*/import * as fs from 'node:fs';@@ -28,6 +28,7 @@ export {importLine,leadingReading,matchIcon,+ answeringMatches,rankIcons,scoreIcon,} from '../../foundation/discovery/icon-ranking.mjs';@@ -37,6 +38,7 @@ export {setConfigString} from '../../foundation/config/config-writer.mjs';export {assertIconExport,checkNewDefinition,+ definitionNameFromInput,definitionFile,findLocalIconSet,writeDefinitionFile,@@ -53,6 +55,9 @@ export {iconExportName,iconNaming,modulePrefix,+ moduleNaming,+ iconNamingWithoutLook,+ splitLook,setModuleNote,variantExportName,writeGeneratedIcons,@@ -65,6 +70,7 @@ export {} from '../../foundation/discovery/icon-set-writer.mjs';export {exportValueKind} from '../../foundation/discovery/module-exports.mjs';export {addIconDefinition, addIconSet} from './_authoring.mjs';+export {checkVariantLook, drawnLooks} from './_default-look.mjs';/*** Refuse a command that writes to a project or package when `cwd` is outsidediff --git a/packages/cli/api/icon/_authoring.mjs b/packages/cli/api/icon/_authoring.mjsindex 53469d263d..4e96aaecab 100644--- a/packages/cli/api/icon/_authoring.mjs+++ b/packages/cli/api/icon/_authoring.mjs@@ -13,6 +13,7 @@import * as fs from 'node:fs';import * as path from 'node:path';import {AstryxError} from '../error.mjs';+import {logger} from '../logger.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';import {assertWithin,@@ -41,7 +42,11 @@ import {iconSetDataText,journalFile,librarySource,+ everyLibraryIcon,libraryIcons,+ libraryLooks,+ lookPositions,+ moduleNaming,nonIconExports,resolveIconSource,peerNote,@@ -50,6 +55,12 @@ import {writeGeneratedIcons,writeIconSetData,} from '../../foundation/discovery/icon-set-writer.mjs';+import {+ describedLooks,+ drawnLooks,+ resolveDefaultLook,+} from './_default-look.mjs';+import {shellArg} from '../../foundation/text/shell-arg.mjs';import {astryxIconDefinitions} from '../../foundation/discovery/icon-definition-discovery.mjs';import {suggestedIcons} from '../../foundation/discovery/icon-set-checks.mjs';import {@@ -99,7 +110,7 @@ function quoteJs(value) {*/export async function addIconSet(name, options) {const {cwd = process.cwd(), dryRun = false, from} = options;- const looks = variantOptions(options);+ const given = variantOptions(options);const exclude =typeof options.exclude === 'string'? options.exclude@@ -192,7 +203,30 @@ export async function addIconSet(name, options) {dryRun,from,exclude,- looks,+ looks: given,+ describe: {+ displayName: options.displayName,+ description: options.description,+ },+ packageDir,+ rootPath,+ manifestPath: projectPath(path.relative(packageDir, manifestFile)),+ });+ }+ // Without --from, an existing set takes new variants, a default variant, a+ // display name or a description in place, and nothing else changes.+ if (+ from == null &&+ fs.existsSync(docFile) &&+ fs.existsSync(dataFile) &&+ (given != null ||+ options.displayName?.trim() ||+ options.description?.trim())+ ) {+ return redeclareIconSet(name, {+ cwd,+ dryRun,+ looks: given,describe: {displayName: options.displayName,description: options.description,@@ -227,14 +261,48 @@ export async function addIconSet(name, options) {let skipped = [];/** @type {ReturnType<typeof librarySource>} */let library = null;+ /** @type {{summary: import('../../foundation/discovery/icon-set-writer.mjs').LibraryLookSummary | null}} */+ const lookFound = {summary: null};+ // Without --from the set has no icons yet, so no look to match.+ let looks =+ from == null+ ? resolveDefaultLook({+ name,+ given,+ current: undefined,+ icons: 0,+ drawn: null,+ library: null,+ }).looks+ : null;if (from != null) {const source = await iconAuthoring(() =>resolveIconSource(from, {packageDir, pkg}),);- const found = libraryIcons(source.file, {exclude});+ const found = libraryIcons(source.file, {+ exclude,+ // The library's look words decide the default before any glyph is+ // picked, so each icon's export draws it.+ prefer: positions => {+ looks = resolveDefaultLook({+ name,+ given,+ current: undefined,+ icons: 0,+ drawn: null,+ library: {module: source.module, positions},+ }).looks;+ return looks ? [looks.default] : [];+ },+ module: source.module,+ progress: line => logger.warn(line),+ summary: each => {+ lookFound.summary = each;+ },+ });if (found.length === 0) {throw new AstryxError(- `"${from}" exports no icon components this command can read. If its icons are data (objects or SVG strings), run \`astryx experimental icon new-set ${name}\`, declare an "adapter" in ${name}.icons.json, and run this command again; or add icons one at a time with \`astryx experimental icon add <Export> --from ${from}\`.`,+ `"${from}" exports no icon components this command can read. If its icons are data (objects or SVG strings), run \`astryx experimental icon new-set ${name}\`, declare an "adapter" in ${name}.icons.json, and run this command again; or add icons one at a time with \`astryx experimental icon add <Export> --from ${from} --set ${name}\`.`,undefined,ERROR_CODES.ERR_NOT_FOUND,);@@ -452,14 +520,196 @@ export async function addIconSet(name, options) {`Left out ${skipped.length} exports that are not icons: ${skipped.slice(0, 12).join(', ')}${skipped.length > 12 ? ', …' : ''}.`,]: []),- ...mappedNotes(map),- ...suggestionNotes(suggestions),+ ...(from != null && lookFound.summary == null+ ? [`Found ${icons.length} icons in ${from}.`]+ : []),+ ...(from != null && lookFound.summary != null+ ? lookNotes(lookFound.summary, icons.length, from, looks, name)+ : []),+ ...mappedNotes(map, name),+ ...suggestionNotes(suggestions, name),'Run `astryx integration check` to see the icon definitions still to map.',];}return result;}+/**+ * A set descriptor's source with `--display-name` and `--description`+ * written into its fields; the rest as it was.+ * @param {string} source+ * @param {{displayName?: string, description?: string}} describe+ */+function describedDoc(source, describe) {+ let out = source;+ for (const [field, value] of /** @type {const} */ ([+ ['displayName', describe.displayName],+ ['description', describe.description],+ ])) {+ if (!value?.trim()) continue;+ out = out.replace(+ new RegExp(`^(\\s*${field}:\\s*)(['"\`])(?:\\\\.|(?!\\2).)*\\2,?$`, 'mu'),+ (_, lead) => `${lead}${quoteJs(value.trim())},`,+ );+ }+ return out;+}++/**+ * `new-set <name>` without `--from` over an existing set: declare its+ * variants and default variant, and rewrite its display name and+ * description, in place. Its icons, map and generated module stay as they+ * are. A variant an icon still has must stay declared, and the default+ * variant is one no icon lists as an extra look. A set with icons keeps its+ * default variant: only a refresh with `--from` from a library whose names+ * name its looks moves it. With none declared,+ * its default is the look its icons' exports draw.+ * @param {string} name+ * @param {{cwd: string, dryRun: boolean, looks: Looks | null, describe: {displayName?: string, description?: string}, packageDir: string, rootPath: string, manifestPath: string}} options+ */+async function redeclareIconSet(+ name,+ {cwd, dryRun, looks: given, describe, packageDir, rootPath, manifestPath},+) {+ return iconAuthoring(async () => {+ const where = await findLocalIconSet(cwd, name);+ const {set} = where;+ const current = set.data.default?.variant;+ const drawn =+ given && set.data.icons.length > 0+ ? drawnLooks(set, packageDir, module =>+ libraryPositions(module, where, Boolean(set.data.adapter)),+ )+ : null;+ const {looks} = resolveDefaultLook({+ name,+ given,+ current,+ icons: set.data.icons.length,+ drawn,+ library: null,+ });+ if (looks) {+ const declared = new Set(looks.variants);+ const dropped = set.data.icons.flatMap(icon =>+ (icon.variants ?? [])+ .filter(each => !declared.has(each.variant))+ .map(each => `${icon.id} (${each.variant})`),+ );+ if (dropped.length > 0) {+ throw new AstryxError(+ `These icons still have a variant --variants leaves out: ${dropped.slice(0, 8).join(', ')}${dropped.length > 8 ? ', …' : ''}. Keep it in --variants.`,+ [+ {+ name: `--variants ${[...new Set([...looks.variants, ...set.data.icons.flatMap(icon => (icon.variants ?? []).map(each => each.variant))])].join(',')}`,+ reason: 'keep every variant an icon has',+ },+ ],+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ const asExtra = set.data.icons+ .filter(icon =>+ (icon.variants ?? []).some(each => each.variant === looks.default),+ )+ .map(icon => icon.id);+ if (asExtra.length > 0) {+ throw new AstryxError(+ `"${looks.default}" can't be the default variant: ${asExtra.length} icons list it as another look (${asExtra.slice(0, 8).join(', ')}${asExtra.length > 8 ? ', …' : ''}), and each icon's own export draws the default.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ }+ const next = {+ ...set.data,+ ...(looks+ ? {variants: looks.variants, default: {variant: looks.default}}+ : {}),+ };+ const docFile = path.join(set.dir, `${set.name}.doc.mjs`);+ const docBefore = fs.readFileSync(docFile, 'utf-8');+ const docAfter = describedDoc(docBefore, describe);+ const dataChanged =+ iconSetDataText(next) !== fs.readFileSync(set.dataPath, 'utf-8');+ /** @type {string[]} */+ const files = [];+ if (dataChanged) {+ files.push(projectPath(path.relative(packageDir, set.dataPath)));+ }+ if (docAfter !== docBefore) {+ files.push(projectPath(path.relative(packageDir, docFile)));+ }+ if (!dryRun) {+ if (dataChanged) writeIconSetData(set, next);+ if (docAfter !== docBefore) {+ journalFile(docFile);+ fs.writeFileSync(docFile, docAfter);+ }+ }+ const result = receipt(+ 'icon-set',+ name,+ {path: rootPath, created: false},+ manifestPath,+ files,+ dryRun,+ );+ result.data.icons = set.data.icons.length;+ result.data.updated = true;+ // A look the icons' own library draws comes from that library, so its+ // command runs as printed; any other look comes from a module the+ // author names.+ /** @param {string} variant */+ const fromFor = variant =>+ drawn != null && drawn.positions.some(each => each.has(variant))+ ? shellArg(drawn.module)+ : '<module>';+ const added = (looks?.variants ?? []).filter(+ variant =>+ variant !== looks?.default &&+ !(set.data.variants ?? []).includes(variant),+ );+ result.data.notes = [+ files.length === 0+ ? `Icon set "${name}" already declares this; nothing changed.`+ : `Updated icon set "${name}" in place; its icons, map and generated module are unchanged.`,+ ...(added.length > 0+ ? [+ `Give each icon its ${added.join(', ')} look: ${added.map(variant => `\`astryx experimental icon add --variant ${variant} --from ${fromFor(variant)} --all --set ${name}\``).join(', ')}, or one icon with \`astryx experimental icon add <Export> --from <module> --id <icon> --variant <name> --set ${name}\`.`,+ ]+ : []),+ ];+ return result;+ });+}++/**+ * The receipt's notes for a library that draws each icon in several looks+ * (a style, a size, a weight): what it found, the look the set took, and+ * how to add another look as a variant.+ * @param {import('../../foundation/discovery/icon-set-writer.mjs').LibraryLookSummary} summary+ * @param {number} count icons in the set+ * @param {string} from+ * @param {{variants: string[], default: string} | null} looks+ * @param {string} name the set's name+ * @returns {string[]}+ */+function lookNotes(summary, count, from, looks, name) {+ const described = describedLooks(summary.positions);+ const taken = [...summary.preferred].reverse().join(' ');+ const styles = new Set(summary.positions.flat());+ const others = (looks?.variants ?? []).filter(+ variant => variant !== looks?.default && styles.has(variant),+ );+ return [+ `Found ${count} icons in ${from}, each drawn in several looks (${described}) by ${summary.exports} exports. The set wraps each icon once, in the ${taken} look, named without the look words (\`x\`, \`XIcon\`).`,+ others.length > 0+ ? `Add the ${others.join(', ')} look${others.length > 1 ? 's' : ''} as variant${others.length > 1 ? 's' : ''}: ${others.map(variant => `\`astryx experimental icon add --variant ${variant} --from ${from} --all --set ${name}\``).join(', ')}.`+ : `To offer another look as a variant, declare it with \`astryx experimental icon new-set ${name} --variants ${[...summary.preferred].reverse()[0]},<look>\` (no --from: the set's icons stay as they are) and run \`astryx experimental icon add --variant <look> --from ${from} --all --set ${name}\`.`,+ ];+}+/*** An icon's words from its id: each part, leaving out a bare number* (`volume-2` is `volume`) unless the id is only numbers.@@ -520,36 +770,40 @@ function definitionSuggestions(icons, map) {/*** The receipt's note for the suggestions, if any.* @param {Array<{definition: string, icon: string}>} suggestions+ * @param {string} name the set's name*/-function suggestionNotes(suggestions) {+function suggestionNotes(suggestions, name) {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>\`.`,+ `${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> --set ${name}\`.`,];}/*** The receipt's note for the entries an exact name wrote, if any.* @param {Record<string, string>} map+ * @param {string} name the set's name*/-function mappedNotes(map) {+function mappedNotes(map, name) {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>\`.`,+ `${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> --set ${name}\`.`,];}+/** @typedef {import('./_default-look.mjs').Looks} Looks */+/** 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.+ * declare, or null when neither is given. Unless named, `default` is the+ * first variant until {@link resolveDefaultLook} decides it.* @param {{variants?: string[] | string, defaultVariant?: string}} options- * @returns {{variants: string[], default: string} | null}+ * @returns {Looks | null}*/function variantOptions(options) {const given =@@ -594,7 +848,28 @@ function variantOptions(options) {ERROR_CODES.ERR_INVALID_ARGUMENT,);}- return {variants, default: chosen || variants[0]};+ return {variants, default: chosen || variants[0], named: Boolean(chosen)};+}++/**+ * The look positions of a library the set's generated module names, or+ * null when it can't be read.+ * @param {string} module+ * @param {{packageDir: string, pkg: Record<string, any>}} where+ * @param {boolean} adapter+ * @returns {Array<Set<string>> | null}+ */+function libraryPositions(module, where, adapter) {+ try {+ const source = resolveIconSource(module, where);+ return moduleNaming(source.file, {+ adapter,+ module,+ progress: line => logger.warn(line),+ }).positions;+ } catch {+ return null;+ }}/**@@ -632,7 +907,7 @@ 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[], looks: {variants: string[], default: string} | null, describe: {displayName?: string, description?: string}, packageDir: string, rootPath: string, manifestPath: string}} options+ * @param {{cwd: string, dryRun: boolean, from: string, exclude: string[], looks: Looks | null, describe: {displayName?: string, description?: string}, packageDir: string, rootPath: string, manifestPath: string}} options*/async function refreshIconSet(name,@@ -641,7 +916,7 @@ async function refreshIconSet(dryRun,from,exclude,- looks,+ looks: given,describe,packageDir,rootPath,@@ -651,15 +926,46 @@ async function refreshIconSet(return iconAuthoring(async () => {const where = await findLocalIconSet(cwd, name);const {set} = where;+ const current = set.data.default?.variant;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, {+ const everyIcon = everyLibraryIcon(source.file, {adapter: Boolean(set.data.adapter),exclude: excluded,+ module: source.module,+ progress: line => logger.warn(line),});+ const libraryLookPositions = lookPositions(everyIcon.map(icon => icon.id));+ // The look the icons from this library draw now decides whether a named+ // default moves them.+ const {looks, moved} = resolveDefaultLook({+ name,+ given,+ current,+ icons: set.data.icons.length,+ drawn: drawnLooks(set, packageDir, () => libraryLookPositions, {+ module: source.module,+ }),+ library: {module: source.module, positions: libraryLookPositions},+ });+ if (looks) {+ const asExtra = set.data.icons+ .filter(icon =>+ (icon.variants ?? []).some(each => each.variant === looks.default),+ )+ .map(icon => icon.id);+ if (asExtra.length > 0) {+ throw new AstryxError(+ `"${looks.default}" can't be the default variant: ${asExtra.length} icons list it as another look (${asExtra.slice(0, 8).join(', ')}${asExtra.length > 8 ? ', …' : ''}), and each icon's own export draws the default.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ }+// 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@@ -686,6 +992,41 @@ async function refreshIconSet(const bySource = new Map(supplied.map(icon => [origins.get(icon.export)?.source, icon]),);+ // A library that draws each icon in several looks gives one icon per+ // glyph. A look the set already wraps keeps its icon as it is (a set an+ // earlier release wrapped one look at a time keeps every icon and id);+ // only a glyph the set has no look of comes in once, in the look the+ // set's default variant or the library's usual default prefers. A new+ // default variant moves each glyph's own icon to the look it names, so+ // its export draws the default; the icon keeps its id, name and fields.+ const preferred = looks?.default ?? current;+ const {icons: looksOf} = libraryLooks(+ everyIcon,+ preferred ? [preferred] : [],+ );+ const iconByExport = new Map(everyIcon.map(icon => [icon.export, icon]));+ /** @type {string[]} the set's exports whose statement now names another look */+ const repicked = [];+ const found = looksOf.flatMap(icon => {+ const wrapped = (icon.looks ?? []).filter(look => bySource.has(look));+ if (wrapped.length === 0) return [icon];+ return wrapped.map(look => {+ const prior = /** @type {{id: string, export: string}} */ (+ bySource.get(look)+ );+ if (moved && prior.id === icon.id && !bySource.has(icon.export)) {+ repicked.push(prior.export);+ return icon;+ }+ const own = /** @type {(typeof everyIcon)[number]} */ (+ iconByExport.get(look)+ );+ // Read by the glyph's id when the set already names it so.+ return prior.id === icon.id+ ? {...own, id: icon.id, name: icon.name}+ : own;+ });+ });/** @param {{export: string, name: string, id: string}} icon */const priorOf = icon =>bySource.get(icon.export) ??@@ -734,9 +1075,8 @@ async function refreshIconSet(// `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 keptExports = new Set(fromLibrary.map(each => each.export));+ const gone = supplied.filter(icon => !keptExports.has(icon.export));const isExcluded = (/** @type {{export: string}} */ icon) =>excludedNames.has(origins.get(icon.export)?.source ?? '') ||excludedNames.has(icon.export);@@ -782,20 +1122,7 @@ async function refreshIconSet(// --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())},`,- );- }+ let docAfter = describedDoc(docBefore, describe);// 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,@@ -853,8 +1180,9 @@ async function refreshIconSet(})).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),+ // renamed icon keeps its export. An icon moved to the new default+ // look keeps its export, which now names that look.+ [...gone.map(icon => icon.export), ...repicked],);files.push(...written.files);try {@@ -913,8 +1241,8 @@ async function refreshIconSet(`${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(', ')}.`,]: []),- ...mappedNotes(byName),- ...suggestionNotes(suggestions),+ ...mappedNotes(byName, name),+ ...suggestionNotes(suggestions, name),...(goneMissing.length > 0? [`${goneMissing.length} icons the library no longer exports were removed from the set: ${goneMissing.map(icon => icon.id).join(', ')}.`,diff --git a/packages/cli/api/icon/_default-look.mjs b/packages/cli/api/icon/_default-look.mjsnew file mode 100644index 0000000000..651ab4a8d4--- /dev/null+++ b/packages/cli/api/icon/_default-look.mjs@@ -0,0 +1,474 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The one rule for an icon set's default variant: it is the look each+ * icon's own export draws.+ * @input the set's data and generated module, the wrapped library's look+ * words, and the variants and default variant a command names+ * @output the variants and default variant to write, or an AstryxError that+ * names the library's look words, the command that moves the look, or the+ * variant to add when the library's names name no looks+ * @position used by `new-set` (create, refresh, in place) and by+ * `add --variant` (one icon or `--all`); every command that writes or keeps+ * `default.variant`, or adds a look, asks this module first+ */++import {AstryxError} from '../error.mjs';+import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';+import {+ generatedModulePath,+ generatedOrigins,+ iconIdOf,+ preferredLook,+ sameIconModule,+ splitLook,+} from '../../foundation/discovery/icon-set-writer.mjs';+import {shellArg} from '../../foundation/text/shell-arg.mjs';++/**+ * The variants and default variant a command declares.+ * @typedef {object} Looks+ * @property {string[]} variants+ * @property {string} default+ * @property {boolean} [named] whether `--default-variant` named the default+ */++/**+ * What a set's icons draw now, read from the look words of the library+ * exports its generated module re-exports.+ * @typedef {object} DrawnLooks+ * @property {string} module the library most of the set's icons come from+ * @property {Array<Set<string>>} positions that library's look positions,+ * the last word of a name first; empty when its names encode no looks+ * @property {Array<string | null>} words the word most icons' exports have+ * at each position+ * @property {number} icons how many of the set's icons come from it+ */++/**+ * @typedef {import('../../foundation/discovery/icon-set-discovery.mjs').DiscoveredIconSet} LookSet+ */++/**+ * A library's look words in the order its names write them, one position+ * after another: `filled or outline; 24; wght300, wght400, wght500`.+ * @param {string[][]} positions each position's words, sorted, the last+ * word of a name first+ */+export function describedLooks(positions) {+ return [...positions]+ .reverse()+ .map(words =>+ words.length > 3+ ? `${words[0]} to ${words.at(-1)}`+ : words.join(words.length === 2 ? ' or ' : ', '),+ )+ .join('; ');+}++/** @param {Array<Set<string>>} positions */+const sortedWords = positions =>+ positions.map(position => [...position].sort());++/**+ * The words of the positions that name a style (`filled`, `outline`), not+ * only numbers (`24`, `wght400`): the words a variant is usually named by.+ * @param {Array<Set<string>>} positions+ */+function styleWords(positions) {+ return sortedWords(positions)+ .filter(words => words.some(word => !/^[a-z]*\d+$/u.test(word)))+ .reverse()+ .flat();+}++/**+ * The look the set's icons draw at the first position, in name order, whose+ * drawn word is one of `among`; else at the first style position.+ * @param {Array<Set<string>>} positions+ * @param {Array<string | null>} words the drawn word at each position+ * @param {string[]} [among]+ * @returns {string | null}+ */+function drawnWord(positions, words, among = []) {+ for (let index = positions.length - 1; index >= 0; index--) {+ const word = words[index];+ if (word != null && among.includes(word)) return word;+ }+ for (let index = positions.length - 1; index >= 0; index--) {+ const word = words[index];+ if (+ word != null &&+ [...positions[index]].some(w => !/^[a-z]*\d+$/u.test(w))+ )+ return word;+ }+ return null;+}++/**+ * What the set's icons draw now ({@link DrawnLooks}), or null when no icon+ * re-exports a named library export.+ * @param {LookSet} set+ * @param {string} packageDir+ * @param {(module: string) => Array<Set<string>> | null} positionsOf the+ * look positions of a library the set's generated module names+ * @param {{module?: string}} [options] `module`: read only the icons that+ * come from this library+ * @returns {DrawnLooks | null}+ */+export function drawnLooks(set, packageDir, positionsOf, options = {}) {+ const origins = generatedOrigins(+ packageDir,+ generatedModulePath(set, packageDir),+ );+ /** @type {Map<string, string[]>} */+ const byModule = new Map();+ for (const icon of set.data.icons) {+ if ((icon.module ?? set.data.module) !== set.data.module) continue;+ const origin = origins.get(icon.export);+ if (!origin || origin.source === 'default') continue;+ if (+ options.module != null &&+ !sameIconModule(origin.module, options.module)+ )+ continue;+ const sources = byModule.get(origin.module) ?? [];+ sources.push(origin.source);+ byModule.set(origin.module, sources);+ }+ const ranked = [...byModule].sort(+ (a, b) =>+ b[1].length - a[1].length || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0),+ );+ if (ranked.length === 0) return null;+ for (const [module, sources] of ranked) {+ const positions = positionsOf(module) ?? [];+ if (positions.length === 0) continue;+ /** @type {Array<Map<string, number>>} */+ const counts = positions.map(() => new Map());+ for (const source of sources) {+ const {look} = splitLook(iconIdOf(source).split('-'), positions);+ look.forEach((word, index) => {+ if (word != null) {+ counts[index].set(word, (counts[index].get(word) ?? 0) + 1);+ }+ });+ }+ const words = counts.map(count => {+ /** @type {string | null} */+ let best = null;+ let most = 0;+ for (const [word, n] of [...count].sort((a, b) =>+ a[0] < b[0] ? -1 : 1,+ )) {+ if (n > most) {+ best = word;+ most = n;+ }+ }+ return best;+ });+ return {module, positions, words, icons: sources.length};+ }+ const [module, sources] = ranked[0];+ return {module, positions: [], words: [], icons: sources.length};+}++/**+ * The refusal for a look word the library does not have.+ * @param {string} word+ * @param {string} flag `--default-variant` or `--variant`+ * @param {string} module+ * @param {Array<Set<string>>} positions+ */+function unknownLook(word, flag, module, positions) {+ return new AstryxError(+ `"${word}" is no look of ${module}: its exports name their looks with ${describedLooks(sortedWords(positions))}. Name one of these words, so each icon's export draws that look.`,+ styleWords(positions).map(each => ({+ name: `${flag} ${each}`,+ reason: `a look ${module} names`,+ })),+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+}++/**+ * The command that wraps the library again in a new default look.+ * @param {string} name+ * @param {string | undefined} module+ * @param {Looks} looks+ */+function refreshCommand(name, module, looks) {+ return `astryx experimental icon new-set ${name} --from ${module ? shellArg(module) : '<module>'} --variants ${looks.variants.join(',')} --default-variant ${looks.default}`;+}++/**+ * The refusal for a default variant that would move in place.+ * @param {string} name+ * @param {number} count icons that draw `now`+ * @param {string} now the look they draw+ * @param {Looks} looks+ * @param {string | undefined} module+ * @param {string | undefined} current+ */+function inPlaceMove(name, count, now, looks, module, current) {+ return new AstryxError(+ `Icon set "${name}" can't ${current != null ? `move its default variant from "${current}" to "${looks.default}"` : `take "${looks.default}" as its default variant`} in place: each of its ${count} icons still draws "${now}". Wrap the library again with the new default, so each icon takes that look.`,+ [+ {+ name: refreshCommand(name, module, looks),+ reason: 'wrap the library again in the new default look',+ },+ ],+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+}++/**+ * The refusal for a default variant that would move on a set whose+ * library's export names name no looks. The icons' exports stay as they+ * are on every path, so only another variant gives them another look.+ * @param {string} name+ * @param {number} count the set's icons+ * @param {string} current the set's default variant+ * @param {Looks} looks+ */+function unencodedMove(name, count, current, looks) {+ const variants = [...new Set([current, ...looks.variants])];+ return new AstryxError(+ `Icon set "${name}" can't move its default variant from "${current}" to "${looks.default}": its icons' export names name no looks, so each of its ${count} icons draws "${current}", the look its icons' module draws. Keep "${current}" as the default, declare "${looks.default}" as a variant, and add it from the module that draws it (fill <module> with that module).`,+ [+ {+ name: `astryx experimental icon new-set ${name} --variants ${variants.join(',')} --default-variant ${current}`,+ reason: `declare ${looks.default} as a variant and keep ${current} as the default`,+ },+ {+ name: `astryx experimental icon add --variant ${looks.default} --from <module> --all --set ${name}`,+ reason: `give each icon its ${looks.default} look from the module that draws it`,+ },+ ],+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+}++/**+ * The refusal for `--variants` that leave out the default variant of a set+ * whose library's export names name no looks. Its icons keep their exports,+ * so they still draw the default, and the set must keep declaring it.+ * @param {string} name+ * @param {number} count the set's icons+ * @param {string} current the set's default variant+ * @param {Looks} looks+ * @param {string} from ` --from <module>` on a refresh, else empty+ */+function droppedDefault(name, count, current, looks, from) {+ const others = looks.variants.filter(variant => variant !== current);+ return new AstryxError(+ `--variants (${looks.variants.join(', ')}) leaves out "${current}", the default variant of icon set "${name}". Its icons' export names name no looks, so each of its ${count} icons still draws "${current}", the look its icons' module draws. List "${current}" in --variants, and add each other look as a variant from the module that draws it (fill <module> with that module).`,+ [+ {+ name: `astryx experimental icon new-set ${name}${from} --variants ${[current, ...others].join(',')}`,+ reason: `keep ${current}, the look each icon draws, as the default`,+ },+ ...others.map(variant => ({+ name: `astryx experimental icon add --variant ${variant} --from <module> --all --set ${name}`,+ reason: `give each icon its ${variant} look from the module that draws it`,+ })),+ ],+ ERROR_CODES.ERR_INVALID_OPTION,+ );+}++/**+ * The variants and default variant to write for a command that declares+ * looks, and whether the set's icons must move to a new look. Every path+ * that writes `default.variant` uses it:+ *+ * - The drawn look is read from every look word of the exports the set+ * wraps (`drawn`), or, with no icons from the library yet, is the look+ * the library is wrapped in by default.+ * - A named default must be a look word the library has.+ * - A named default other than the drawn look moves the icons only on a+ * refresh (`library` given), where each glyph that has the look takes it;+ * in place it is refused with the refresh command.+ * - With none named, the default is the drawn look, which `--variants` must+ * list.+ *+ * A library whose names encode no looks has no look words: there the named+ * variant, the set's current default, or the first variant is the default.+ * Its icons keep their exports on every path, so a set with icons keeps a+ * declared default, `--variants` must list it, and with none declared the+ * command names it.+ * @param {object} args+ * @param {string} args.name the set+ * @param {Looks | null} args.given the variants and default the command names+ * @param {string | undefined} args.current the set's `default.variant`+ * @param {number} args.icons how many icons the set has+ * @param {DrawnLooks | null} args.drawn what the set's icons draw now+ * @param {{module: string, positions: Array<Set<string>>} | null} args.library+ * the library `--from` wraps; null in place+ * @returns {{looks: Looks | null, moved: boolean}}+ */+export function resolveDefaultLook({+ name,+ given,+ current,+ icons,+ drawn,+ library,+}) {+ if (!given) return {looks: null, moved: false};+ const refresh = library != null;+ const positions =+ library != null ? library.positions : (drawn?.positions ?? []);+ const module = library?.module ?? drawn?.module;+ const now = drawn != null && drawn.positions.length > 0 ? drawn : null;+ if (positions.length === 0) {+ return unencodedDefault({name, given, current, icons, module, refresh});+ }+ if (given.named) {+ const chosen = given.default;+ const index = positions.findIndex(position => position.has(chosen));+ if (index < 0) {+ throw unknownLook(+ chosen,+ '--default-variant',+ /** @type {string} */ (module),+ positions,+ );+ }+ const drawnHere = now?.words[index] ?? null;+ if (now != null && drawnHere != null && drawnHere !== chosen) {+ if (!refresh) {+ throw inPlaceMove(name, now.icons, drawnHere, given, module, current);+ }+ return {looks: given, moved: true};+ }+ return {looks: given, moved: false};+ }+ const words = now != null ? now.words : preferredLook(positions, []);+ const look = drawnWord(positions, words, given.variants);+ if (look == null || !given.variants.includes(look)) {+ const shown = look ?? '<look>';+ throw new AstryxError(+ `None of --variants (${given.variants.join(', ')}) is the look ${now != null ? `the set's ${now.icons} icons draw` : `${module} is wrapped in by default`} ("${shown}"), and each icon's own export draws the default variant. List it in --variants, or name the default with --default-variant.`,+ [+ {+ name: `astryx experimental icon new-set ${name}${refresh ? ` --from ${shellArg(/** @type {string} */ (module))}` : ''} --variants ${[shown, ...given.variants].join(',')}`,+ reason: `declare ${shown}, the look each icon draws, as the default`,+ },+ ],+ ERROR_CODES.ERR_INVALID_OPTION,+ );+ }+ return {looks: {...given, default: look}, moved: false};+}++/**+ * {@link resolveDefaultLook} for a library whose names encode no looks.+ * @param {{name: string, given: Looks, current: string | undefined, icons: number, module: string | undefined, refresh: boolean}} args+ * @returns {{looks: Looks, moved: boolean}}+ */+function unencodedDefault({name, given, current, icons, module, refresh}) {+ if (given.named) {+ if (current != null && given.default !== current && icons > 0) {+ throw unencodedMove(name, icons, current, given);+ }+ return {looks: given, moved: false};+ }+ if (current != null && given.variants.includes(current)) {+ return {looks: {...given, default: current}, moved: false};+ }+ const from = refresh && module ? ` --from ${shellArg(module)}` : '';+ if (current != null && icons > 0) {+ throw droppedDefault(name, icons, current, given, from);+ }+ if (current == null && icons > 0) {+ throw new AstryxError(+ `Icon set "${name}" declares no default variant, and its icons' export names name none of ${given.variants.join(', ')}. Name the look its ${icons} icons draw with --default-variant.`,+ given.variants.map(variant => ({+ name: `astryx experimental icon new-set ${name}${from} --variants ${given.variants.join(',')} --default-variant ${variant}`,+ reason: `if each icon draws ${variant}`,+ })),+ ERROR_CODES.ERR_INVALID_OPTION,+ );+ }+ return {looks: given, moved: false};+}++/**+ * The default variant a command that declares `variant` beside the set's+ * variants names: the set's own, else the look its icons draw.+ * @param {LookSet} set+ * @param {DrawnLooks | null} drawn+ * @returns {string | null}+ */+function keptDefault(set, drawn) {+ const current = set.data.default?.variant;+ if (current) return current;+ if (drawn == null || drawn.positions.length === 0) return null;+ return drawnWord(drawn.positions, drawn.words, set.data.variants ?? []);+}++/**+ * The command that declares `variant` beside the set's variants. It names+ * the default variant the set keeps, so it runs as printed.+ * @param {LookSet} set+ * @param {string} variant+ * @param {DrawnLooks | null} drawn+ * @returns {{name: string, reason: string}}+ */+export function declareVariantSuggestion(set, variant, drawn) {+ const kept = keptDefault(set, drawn) ?? '<default>';+ const declared = set.data.variants ?? [];+ const variants = [+ ...new Set([+ ...(declared.includes(kept) ? [] : [kept]),+ ...declared,+ variant,+ ]),+ ];+ return {+ name: `astryx experimental icon new-set ${set.name} --variants ${variants.join(',')} --default-variant ${kept}`,+ reason:+ kept === '<default>'+ ? 'declare the variants; fill <default> with the look the icons draw'+ : 'declare the variants',+ };+}++/**+ * Check that `add --variant` may add `variant` to the set's icons: a look+ * word the library has, not the look each icon's own export draws (the+ * default, declared or drawn), and declared by the set.+ * @param {object} args+ * @param {LookSet} args.set+ * @param {string} args.variant+ * @param {string} args.module the module the variant comes from+ * @param {Array<Set<string>>} args.positions that module's look positions+ * @param {DrawnLooks | null} args.drawn what the set's icons draw now+ */+export function checkVariantLook({set, variant, module, positions, drawn}) {+ if (positions.length > 0 && !positions.some(each => each.has(variant))) {+ throw unknownLook(variant, '--variant', module, positions);+ }+ const drawnPositions = drawn?.positions ?? [];+ const index = drawnPositions.findIndex(each => each.has(variant));+ const drawnHere = index >= 0 ? drawn?.words[index] : null;+ if (set.data.default?.variant === variant || drawnHere === variant) {+ throw new AstryxError(+ `"${variant}" is the look each icon's own export in "${set.name}" already draws${set.data.default?.variant === variant ? ' (its default variant)' : ''}, so a variant of it would export the same artwork twice.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ 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${keptDefault(set, drawn) == null ? ', and name the look its icons draw now as the default variant in place of <default>' : ''}.`,+ [declareVariantSuggestion(set, variant, drawn)],+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+}diff --git a/packages/cli/api/icon/_records.mjs b/packages/cli/api/icon/_records.mjsindex 3611deec7d..6458554501 100644--- a/packages/cli/api/icon/_records.mjs+++ b/packages/cli/api/icon/_records.mjs@@ -15,6 +15,7 @@ import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';export {+ answeringMatches,iconRecord,importLine,leadingReading,diff --git a/packages/cli/api/icon/add/add.mjs b/packages/cli/api/icon/add/add.mjsindex 4e6b19251f..0bf0ec6bdd 100644--- a/packages/cli/api/icon/add/add.mjs+++ b/packages/cli/api/icon/add/add.mjs@@ -31,6 +31,7 @@ import {astryxIconDefinitions,authoring,checkNewDefinition,+ definitionNameFromInput,closestNames,findLocalIconSet,iconIdOf,@@ -40,12 +41,19 @@ import {generatedNamesOf,generatedOrigins,iconModulePackage,- iconNaming,localSourceNote,definitionNameOf,libraryIcons,- modulePrefix,+ moduleNaming,+ iconNamingWithoutLook,+ iconNaming,+ iconExportName,+ sameIconModule,+ splitLook,variantExportName,+ answeringMatches,+ checkVariantLook,+ drawnLooks,rankIcons,resolveIconSource,setModuleNote,@@ -56,6 +64,8 @@ import {refuseOutsideProject,} from '../_adapter.mjs';import {passed, refuseIgnoredPairs} from '../_options.mjs';+import {logger} from '../../logger.mjs';+import {shellArg} from '../../../foundation/text/shell-arg.mjs';/** The lowest score a definition match needs: an exact word or name. */const FIT_FLOOR = 80;@@ -79,7 +89,7 @@ export async function iconAdd(exportName, options) {from,set: selector,definition: givenDefinition,- newDefinition,+ newDefinition: givenNewDefinition,description,words,useDefault = false,@@ -88,6 +98,11 @@ export async function iconAdd(exportName, options) {all = false,} = options ?? {};refuseOutsideProject(cwd, 'experimental icon add', 'the icon-set package');+ // The docs' kebab-case (`ai-helper`) names the same new definition.+ const newDefinition =+ givenNewDefinition == null+ ? undefined+ : definitionNameFromInput(givenNewDefinition);// `--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).@@ -177,14 +192,21 @@ export async function iconAdd(exportName, options) {const generated = generatedModulePath(set, packageDir);const module = set.data.module;// A library prefix every icon export shares (`feather` in `featherEye`)- // is left out of the id and the set's export name, as the bulk wrap does.- // A ./ path is the author's own files, named as written: never a library- // prefix (`CheckDouble` and `CheckDoubleSolid` share `check`).- const shared =+ // is left out of the id and the set's export name, as the bulk wrap does,+ // and so are the look words a library's names end in (`Outline24WGHT500`+ // in `XOutline24WGHT500Icon`). A ./ path is the author's own files, named+ // as written: never a library prefix (`CheckDouble` and+ // `CheckDoubleSolid` share `check`).+ const libraryNaming =useDefault || source.module.startsWith('./')- ? []- : modulePrefix(source.file, {adapter: Boolean(set.data.adapter)});+ ? {prefix: [], positions: []}+ : moduleNaming(source.file, {+ adapter: Boolean(set.data.adapter),+ module: source.module,+ progress: line => logger.warn(line),+ });const nameWords = iconIdOf(exportName).split('-');+ const shared = libraryNaming.prefix;const prefix =shared.length > 0 &&nameWords.length > shared.length &&@@ -199,11 +221,32 @@ export async function iconAdd(exportName, options) {sourceExport,);const known = set.data.icons.find(each => already.includes(each.export));- const naming = known+ const glyph = known? {id: known.id, name: known.export}- : iconNaming(exportName, prefix);- const id = givenId ?? naming.id;+ : iconNamingWithoutLook(exportName, {+ prefix,+ positions: libraryNaming.positions,+ });const asVariant = variant != null;+ // The set may already export the glyph's name for another export of the+ // library (its outline look, when this is the filled one). This export+ // then keeps its look words in its id and name, or takes its name from+ // --id, and the listing offers it as a variant of that icon instead.+ const origin = generatedOrigins(packageDir, generated).get(glyph.name);+ const glyphTaken =+ !known &&+ !asVariant &&+ origin != null &&+ !(+ sameIconModule(origin.module, source.module) &&+ origin.source === sourceExport+ );+ const naming = !glyphTaken+ ? glyph+ : givenId != null+ ? {id: givenId, name: nameFromId(givenId)}+ : iconNaming(exportName, prefix);+ const id = givenId ?? naming.id;// The name the set exports it as: `<Name>Icon`, or for a variant the// icon's name with the variant's name.const baseIcon = set.data.icons.find(each => each.id === id);@@ -219,7 +262,20 @@ export async function iconAdd(exportName, options) {}if (definition == null && newDefinition == null && !asVariant) {- return definitionMatches(set, exportName, from, id);+ return definitionMatches(set, exportName, from, id, {+ useDefault,+ id: givenId,+ look:+ glyphTaken && origin != null+ ? lookVariantOf(+ iconNaming(exportName, prefix).id,+ iconNaming(origin.source, prefix).id,+ libraryNaming.positions,+ set,+ )+ : null,+ glyphId: glyph.id,+ });}/** @type {{name: string, description: string, words: string[]} | null} */@@ -250,7 +306,7 @@ export async function iconAdd(exportName, options) {}),),{- name: `--new-definition ${definition} --description '<what it is for>' --words a,b`,+ name: `--new-definition ${definitionNameFromInput(definition)} --description '<what it is for>' --words a,b`,reason: 'add it as your own definition',},],@@ -262,6 +318,15 @@ export async function iconAdd(exportName, options) {const icons = set.data.icons.map(each => ({...each}));const existing = icons.find(each => each.id === id);if (asVariant) {+ checkVariantLook({+ set,+ variant,+ module: source.module,+ positions: libraryNaming.positions,+ drawn: drawnLooks(set, packageDir, each =>+ sameIconModule(each, source.module) ? libraryNaming.positions : null,+ ),+ });if (!existing) {throw new AstryxError(`Icon set "${set.name}" has no icon "${id}" to add a variant to. Add the icon first, or pass --id.`,@@ -275,6 +340,18 @@ export async function iconAdd(exportName, options) {ERROR_CODES.ERR_NOT_FOUND,);}+ const own = generatedOrigins(packageDir, generated).get(existing.export);+ if (+ own != null &&+ own.source === sourceExport &&+ sameIconModule(own.module, source.module)+ ) {+ throw new AstryxError(+ `"${sourceExport}" is icon "${id}"'s own export, which draws its default look, so it can't be its ${variant} variant too.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }const variants = [...(existing.variants ?? [])];const same = variants.find(each => each.export === setName);if (!same) {@@ -394,9 +471,13 @@ export async function iconAdd(exportName, options) {* @param {string} exportName* @param {string} from* @param {string} id+ * @param {{useDefault?: boolean, id?: string, look?: string | null, glyphId?: string}} passed the+ * options the author passed, repeated in each listed command so it runs as+ * printed; `look`, when the set already has an icon for the export's+ * glyph (`glyphId`): the variant it is of that icon* @returns {import('../icon.type.mjs').IconDefinitionMatchesResponse}*/-function definitionMatches(set, exportName, from, id) {+function definitionMatches(set, exportName, from, id, passed = {}) {const astryx = astryxIconDefinitions().definitions.map(each => ({doc: each.doc,source: /** @type {const} */ ('astryx'),@@ -432,14 +513,19 @@ function definitionMatches(set, exportName, from, id) {/** @type {Map<string, {score: number, reason: string}>} */const best = new Map();for (const query of queries) {- for (const match of rankIcons([asSet], query)) {+ for (const match of answeringMatches(rankIcons([asSet], query))) {const prior = best.get(match.export);if (!prior || match.score > prior.score) {best.set(match.export, {score: match.score, reason: match.reason});}}}- const base = `astryx experimental icon add ${exportName} --from ${from}`;+ const base = [+ `astryx experimental icon add ${exportName} --from ${shellArg(from)}`,+ `--set ${shellArg(set.name)}`,+ ...(passed.useDefault ? ['--default'] : []),+ ...(passed.id != null ? [`--id ${shellArg(passed.id)}`] : []),+ ].join(' ');const matches = all.filter(({doc}) => best.has(doc.name)).map(({doc, source}) => {@@ -463,6 +549,15 @@ function definitionMatches(set, exportName, from, id) {).slice(0, MATCH_LIMIT);const fits = matches.some(match => match.score >= FIT_FLOOR);+ const asLook =+ passed.look && passed.glyphId+ ? [+ `astryx experimental icon add ${exportName} --from ${shellArg(from)}`,+ `--set ${shellArg(set.name)}`,+ ...(passed.useDefault ? ['--default'] : []),+ `--id ${passed.glyphId} --variant ${passed.look}`,+ ].join(' ')+ : null;const name = id.replace(/-([a-z0-9])/gu, (_, c) => c.toUpperCase());return {type: 'icon.definitionMatches',@@ -474,6 +569,7 @@ function definitionMatches(set, exportName, from, id) {newDefinition: fits? null: `${base} --new-definition ${/^[a-z]/u.test(name) ? name : `icon${name}`} --description '<what the icon is for>' --words <word>,<word>`,+ ...(asLook ? {variant: asLook} : {}),},};}@@ -502,29 +598,34 @@ async function addVariantForAll({cwd, from, selector, variant}) {}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)});+ // In a library that draws each icon in several looks, the variant is the+ // glyph's look the variant's name picks (`filled`), and an icon is known+ // by any look of its glyph.+ /** @type {Array<Set<string>>} */+ let positions = [];+ const found = libraryIcons(source.file, {+ adapter: Boolean(set.data.adapter),+ prefer: [variant],+ module: source.module,+ progress: line => logger.warn(line),+ summary: each => {+ positions = each.positions.map(words => new Set(words));+ },+ });+ checkVariantLook({+ set,+ variant,+ module: source.module,+ positions,+ drawn: drawnLooks(set, packageDir, each =>+ sameIconModule(each, source.module) ? positions : null,+ ),+ });const byId = new Map(found.map(each => [each.id, each]));+ const byLook = new Map(+ found.flatMap(each => (each.looks ?? []).map(look => [look, 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@@ -548,6 +649,8 @@ async function addVariantForAll({cwd, from, selector, variant}) {const already = [];/** @type {string[]} */const missing = [];+ /** @type {string[]} icons whose own export is the one the variant picks */+ const own = [];const icons = set.data.icons.map(icon => {const origin = origins.get(icon.export);if (origin && iconModulePackage(origin.module) !== variantPackage) {@@ -557,6 +660,7 @@ async function addVariantForAll({cwd, from, selector, variant}) {origin && origin.source !== 'default' ? origin.source : undefined;const match =(librarySource ? byLibraryExport.get(librarySource) : undefined) ??+ (librarySource ? byLook.get(librarySource) : undefined) ??byName.get(icon.export) ??byId.get(icon.id);if (!match) {@@ -567,6 +671,21 @@ async function addVariantForAll({cwd, from, selector, variant}) {missing.push(icon.id);return icon;}+ // A glyph the library draws in no look of that name has no variant,+ // and neither has one whose own export is the one that look picks.+ if (match.look && !match.look.includes(variant)) {+ missing.push(icon.id);+ return icon;+ }+ if (+ match.export === librarySource &&+ origin != null &&+ sameIconModule(origin.module, source.module)+ ) {+ own.push(icon.id);+ missing.push(icon.id);+ return icon;+ }const name = variantExportName(icon.export, variant);const variants = [...(icon.variants ?? [])];if (variants.some(each => each.variant === variant)) {@@ -583,6 +702,29 @@ async function addVariantForAll({cwd, from, selector, variant}) {added.push(icon.id);return {...icon, variants};});+ if (+ added.length === 0 &&+ already.length === 0 &&+ own.length > 0 &&+ set.data.default?.variant == null+ ) {+ // The module is the one the icons' own exports come from, so the+ // variant names the look they draw now: the set's undeclared default.+ const variants = [+ variant,+ ...(set.data.variants ?? []).filter(each => each !== variant),+ ];+ throw new AstryxError(+ `"${source.module}" is the module the ${own.length} icons of "${set.name}" come from: its exports are those icons in the look they draw now, so "${variant}" is that look and can't be a variant of them. "${set.name}" declares no default variant; declare "${variant}" as the default first.`,+ [+ {+ name: `astryx experimental icon new-set ${set.name} --variants ${variants.join(',')} --default-variant ${variant}`,+ reason: `declare ${variant}, the look each icon draws, as the default`,+ },+ ],+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }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.`,@@ -627,3 +769,47 @@ async function addVariantForAll({cwd, from, selector, variant}) {},};}++/**+ * The set's export name for an id: `x-filled` is `XFilledIcon`.+ * @param {string} id+ */+function nameFromId(id) {+ return iconExportName(+ id+ .split('-')+ .map(word => word[0].toUpperCase() + word.slice(1))+ .join(''),+ );+}++/**+ * The variant an export of a library of looks is of the icon the set+ * already wraps for its glyph: its word at the first look position, in name+ * order, where it differs from the wrapped export. That word is a variant+ * only when the set declares it and it is not the default, which the icon's+ * own export draws. Otherwise null, so the listing offers no variant+ * command that the set's data would refuse.+ * @param {string} id the export's id, look words kept+ * @param {string} wrappedId the wrapped export's id, look words kept+ * @param {Array<Set<string>>} positions the library's look positions, the+ * last word first+ * @param {import('../../../foundation/discovery/icon-set-discovery.mjs').DiscoveredIconSet} set+ * @returns {string | null}+ */+function lookVariantOf(id, wrappedId, positions, set) {+ const {look} = splitLook(id.split('-'), positions);+ const {look: wrapped} = splitLook(wrappedId.split('-'), positions);+ let word = null;+ for (let index = look.length - 1; index >= 0; index--) {+ if (look[index] !== wrapped[index]) {+ word = look[index];+ break;+ }+ }+ return word != null &&+ (set.data.variants ?? []).includes(word) &&+ word !== set.data.default?.variant+ ? word+ : null;+}diff --git a/packages/cli/api/icon/all-or-nothing.test.mjs b/packages/cli/api/icon/all-or-nothing.test.mjsindex 040e10a357..12a9514bc1 100644--- a/packages/cli/api/icon/all-or-nothing.test.mjs+++ b/packages/cli/api/icon/all-or-nothing.test.mjs@@ -184,6 +184,7 @@ const COMMANDS = [displayName: 'Acme Glyphs',description: 'Acme glyphs.',variants: 'outline,solid',+ defaultVariant: 'outline',}),],[diff --git a/packages/cli/api/icon/icon.test.mjs b/packages/cli/api/icon/icon.test.mjsindex 8894608968..9f63533a68 100644--- a/packages/cli/api/icon/icon.test.mjs+++ b/packages/cli/api/icon/icon.test.mjs@@ -15,7 +15,7 @@ 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 {answeringMatches, rankIcons, scoreIcon} from './_records.mjs';import {glyphsData,writeIconPackage,@@ -504,3 +504,91 @@ describe('partial matches answer only when nothing better does (FR6)', () => {expect(found).toEqual([['home', 40]]);});});++describe('a word matches whole words (FR6)', () => {+ /** @param {Array<{id: string, words?: string[]}>} icons @param {Record<string, string>} [map] */+ const setOf = (icons, map = {}) =>+ /** @type {any} */ ({+ name: 'brand',+ package: '@acme/brand-icons',+ data: {+ schemaVersion: 1,+ module: '@acme/brand-icons',+ icons: icons.map(each => ({+ export: `${each.id.replace(/(^|-)(\w)/gu, (_, __, c) => c.toUpperCase())}Icon`,+ words: each.id.split('-'),+ ...each,+ })),+ map,+ },+ });+ /** @param {any} set @param {string} query */+ const answer = (set, query) =>+ answeringMatches(rankIcons([set], query)).map(each => each.id);++ it('never offers a longer word that only starts with the query beside a whole-word answer', () => {+ const set = setOf([+ {id: 'star'},+ {id: 'chevron-left-stack', words: ['chevron', 'start']},+ {id: 'house', words: ['house', 'home', 'start']},+ ]);+ expect(answer(set, 'star')).toEqual(['star']);+ // With no whole-word answer, a word start still answers.+ expect(answer(setOf([{id: 'house', words: ['start']}]), 'star')).toEqual([+ 'house',+ ]);+ });++ it('ranks the whole id first when the query is its plural', () => {+ const set = setOf([{id: 'ai-stars'}, {id: 'star'}, {id: 'stars-shine'}]);+ const ranked = rankIcons([set], 'stars');+ expect(ranked[0]).toMatchObject({id: 'star', score: 90});+ expect(answer(set, 'stars')).toEqual(['star', 'ai-stars', 'stars-shine']);+ expect(+ rankIcons([setOf([{id: 'stars'}, {id: 'star-off'}])], 'star')[0].id,+ ).toBe('stars');+ });++ it('meets a plural and its singular as the same word', () => {+ const set = setOf([{id: 'ai-stars'}, {id: 'start-flag'}]);+ expect(answer(set, 'star')).toEqual(['ai-stars']);+ expect(answer(setOf([{id: 'star'}]), 'stars')).toEqual(['star']);+ });++ it('leaves out the words that only phrase a query', () => {+ const set = setOf([{id: 'house'}, {id: 'arrow-right'}], {home: 'house'});+ expect(answer(set, 'go home')).toEqual(['house']);+ expect(answer(set, 'the home icon')).toEqual(['house']);+ // A query of filler words alone is read as written.+ expect(answer(set, 'go')).toEqual([]);+ });++ it('scores a query as typed before it leaves out filler words, so an exact name keeps its score', () => {+ const set = setOf([+ {id: 'arrow-up-to-line'},+ {id: 'arrow-up'},+ {id: 'line'},+ {id: 'a-arrow-down'},+ {id: 'arrow-down'},+ {id: 'house'},+ ]);+ const top = (/** @type {string} */ query) => rankIcons([set], query)[0];+ expect(top('arrow up to line')).toMatchObject({+ id: 'arrow-up-to-line',+ score: 90,+ });+ expect(answer(set, 'arrow up to line')).toEqual(['arrow-up-to-line']);+ expect(top('a arrow down')).toMatchObject({id: 'a-arrow-down', score: 90});+ expect(answer(set, 'a arrow down')).toEqual(['a-arrow-down']);+ // With no exact answer as typed, the filler words still drop.+ expect(answer(set, 'go house')).toEqual(['house']);+ });++ it('never matches a letter or two inside a word', () => {+ const set = setOf([{id: 'box'}, {id: 'text'}, {id: 'next-page'}]);+ expect(answer(set, 'x')).toEqual([]);+ expect(answer(set, 'ex')).toEqual([]);+ // Three letters still find a part of a word.+ expect(answer(set, 'ext')).toEqual(['next-page', 'text']);+ });+});diff --git a/packages/cli/api/icon/icon.type.mjs b/packages/cli/api/icon/icon.type.mjsindex 4b2151d538..9008aa93ee 100644--- a/packages/cli/api/icon/icon.type.mjs+++ b/packages/cli/api/icon/icon.type.mjs@@ -183,7 +183,7 @@* @property {string} from - The module the icon is exported from: a package, a package subpath, or a relative path in this package.* @property {string} [set] - The set to edit, when the package ships several.* @property {string} [definition] - The icon definition to map the icon to.- * @property {string} [newDefinition] - Add the set's own definition with this name and map the icon to it.+ * @property {string} [newDefinition] - Add the set's own definition with this name (camelCase, or kebab-case written as camelCase) and map the icon to it.* @property {string} [description] - With `newDefinition`: what the icon is for.* @property {string[]} [words] - With `newDefinition`: words people search for.* @property {boolean} [useDefault] - The module's default export is the icon.@@ -249,6 +249,7 @@* @property {string} data.id - The id the icon would get.* @property {IconDefinitionMatch[]} data.matches - At most 10, best first.* @property {string | null} data.newDefinition - The command that adds the set's own definition, when no match fits.+ * @property {string} [data.variant] - When the set already has an icon for the export's glyph from another export of the library: the command that adds this export as that icon's variant.*//**@@ -293,7 +294,7 @@* @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} [defaultVariant] - With `variants`: the variant each icon's own export draws; when absent, the look the icons' exports draw in a library whose names encode looks; otherwise the set's current default, else, on a set without icons, the first variant. A set with icons changes it only with `from`, and only in a library whose names encode looks.* @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.*/@@ -324,6 +325,7 @@* @property {string} [from]* @property {number} [icons] - With `from`: how many icons it wrote.* @property {boolean} [refreshed] - With `from` on an existing set: the set was refreshed, not created.+ * @property {boolean} [updated] - Without `from` on an existing set: its variants, default variant, display name, or description were updated in place, 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.diff --git a/packages/cli/api/icon/iconAdd.doc.mjs b/packages/cli/api/icon/iconAdd.doc.mjsindex daa3f1e210..5b2fdd5f44 100644--- a/packages/cli/api/icon/iconAdd.doc.mjs+++ b/packages/cli/api/icon/iconAdd.doc.mjs@@ -53,7 +53,7 @@ export const doc = {name: 'options.newDefinition',type: 'string',description:- "Add the set's own definition with this name, then map the icon to it.",+ "Add the set's own definition with this name, in camelCase (`aiHelper`) or kebab-case (`ai-helper`), then map the icon to it.",},{name: 'options.description',@@ -119,7 +119,7 @@ export const doc = {},{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',+ 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, is the look each icon's own export already draws, or is no look word of a library whose export names encode looks",},{code: 'ERR_FILE_EXISTS', when: 'another icon already has the id'},{diff --git a/packages/cli/api/icon/iconNewDefinition.doc.mjs b/packages/cli/api/icon/iconNewDefinition.doc.mjsindex 0f9ed625ef..93356d94c6 100644--- a/packages/cli/api/icon/iconNewDefinition.doc.mjs+++ b/packages/cli/api/icon/iconNewDefinition.doc.mjs@@ -19,7 +19,8 @@ export const doc = {{name: 'name',type: 'string',- description: 'camelCase definition name.',+ description:+ 'The definition name, in camelCase (`rocketLaunch`) or kebab-case (`rocket-launch`); it is written in camelCase.',required: true,},{@@ -66,7 +67,7 @@ export const doc = {throws: [{code: 'ERR_INVALID_ARGUMENT',- when: 'the name is not camelCase, or Astryx already has it',+ when: 'the name is neither camelCase nor kebab-case, or Astryx already has it',},{code: 'ERR_MISSING_ARGUMENT',diff --git a/packages/cli/api/icon/iconNewSet.doc.mjs b/packages/cli/api/icon/iconNewSet.doc.mjsindex aad74745a0..575844909a 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, 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.",+ "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. A library whose export names end in style, size and weight words gives one icon per glyph, named without those words, in the look the default variant names, else the library's usual default (outline, regular, the middle weight). Over an existing set, `from` refreshes it; without `from`, `variants`, `defaultVariant`, `displayName` and `description` update it in place and leave its icons, map and generated module unchanged (a variant an icon has must stay declared, and a set with icons keeps its default variant). 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 an existing set is changed only as above. Experimental: it may change or be removed in a patch release.",importPath: '@astryxdesign/cli/api',signature:'iconNewSet(name: string, options?: IconNewSetOptions): Promise<IconNewSetResponse>',@@ -56,7 +56,7 @@ export const doc = {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.",+ "With variants: the variant each icon's own export draws, written to the data file's default. In a library whose export names encode looks, it must be one of the library's look words, and when absent it is the look the icons' exports draw (with from and no icons yet, the library's usual default), which variants must list. Otherwise, when absent, an existing set keeps its default while variants declares it; a set without icons takes the first variant, and a set with icons and none declared needs it. Without from, a set with icons refuses a default other than the look they draw; when its icons' export names name no looks, it refuses one other than its declared default with from too.",},{name: 'options.displayName',@@ -81,11 +81,11 @@ export const doc = {throws: [{code: 'ERR_INVALID_ARGUMENT',- when: 'the name is not lowercase kebab-case, package.json has no name, or a variant name or the default variant is invalid',+ when: 'the name is not lowercase kebab-case, package.json has no name, or a variant name or the default variant is invalid; the default variant is no look word of a library whose export names encode looks; or the default variant would change on a set that has icons: without `from` (wrap the library again with `from` and `defaultVariant`), or with or without it when the export names of its icons name no looks (add the look as a variant instead)',},{code: 'ERR_INVALID_OPTION',- when: '`exclude` is given without `from`, or `defaultVariant` without `variants`',+ when: '`exclude` is given without `from`, or `defaultVariant` without `variants`; `variants` leave out the default variant: the look the icons draw in a library whose export names encode looks, or the declared default of a set with icons whose export names name no looks; or such a set declares no default and `defaultVariant` names none',},{code: 'ERR_FILE_EXISTS',diff --git a/packages/cli/api/icon/search/search.mjs b/packages/cli/api/icon/search/search.mjsindex a45582db75..5e3b767617 100644--- a/packages/cli/api/icon/search/search.mjs+++ b/packages/cli/api/icon/search/search.mjs@@ -12,10 +12,12 @@import {AstryxError} from '../../error.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';import {loadIconSets} from '../_adapter.mjs';-import {rankIcons, setsNamed, unusableSet} from '../_records.mjs';--/** The lowest score of a whole-word or word-start match. */-const WORD_SCORE = 60;+import {+ answeringMatches,+ rankIcons,+ setsNamed,+ unusableSet,+} from '../_records.mjs';/*** Every icon of one set, by id: `--set <name> --all-icons`, so an author can read@@ -75,11 +77,10 @@ export async function iconSearch(query, {cwd, set, limit}) {if (searched.length === 0) throw unusableSet(sets, withdrawn, set);}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;+ // A word start (`start` for `star`) answers only when nothing matches a+ // whole word, and a partial match (`pin` inside `shopping`) only when+ // nothing matches a whole word or a word start.+ const matches = answeringMatches(ranked);return {type: 'icon.search',data: {diff --git a/packages/cli/api/integration/add-helpers.mjs b/packages/cli/api/integration/add-helpers.mjsindex 6b52dff112..c4ea794c1d 100644--- a/packages/cli/api/integration/add-helpers.mjs+++ b/packages/cli/api/integration/add-helpers.mjs@@ -131,7 +131,10 @@ export function packageJsonFilesUpdate(}}- if ((pkg.exports !== undefined || createExports) && publicExports.length > 0) {+ if (+ (pkg.exports !== undefined || createExports) &&+ publicExports.length > 0+ ) {const authored = pkg.exports;/** @type {Record<string, unknown>} */let exportsMap;@@ -483,7 +486,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, refreshed?: boolean, renamed?: Array<{from: string, to: string}>, mapped?: Array<{definition: string, icon: string}>, suggestions?: Array<{definition: string, icon: string, word: string}>, notes?: string[]}}}+ * @returns {{type: 'integration.add', data: Omit<import('./integration-authoring.type.mjs').IntegrationAddData, 'kind'> & {kind: K, icons?: number, refreshed?: boolean, updated?: 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/authoring-checks.mjs b/packages/cli/api/integration/authoring-checks.mjsindex 0b45c690d5..21ff7dbe72 100644--- a/packages/cli/api/integration/authoring-checks.mjs+++ b/packages/cli/api/integration/authoring-checks.mjs@@ -57,12 +57,7 @@ import {} from './validate-integration.mjs';import {rootProblem} from '../../foundation/integrations/validate-contributions.mjs';import {normalizeProviderId} from '../../foundation/identity/provider-identity.mjs';--/** @param {string} value */-export function shellArg(value) {- if (/^[A-Za-z0-9@/._-]+$/.test(value)) return value;- return `'${value.replace(/'/g, `'\\''`)}'`;-}+import {shellArg} from '../../foundation/text/shell-arg.mjs';/*** The provider ID a package without a name is checked under: a valid barediff --git a/packages/cli/api/integration/authoring-checks.test.mjs b/packages/cli/api/integration/authoring-checks.test.mjsindex 9cc16a00a9..29de742433 100644--- a/packages/cli/api/integration/authoring-checks.test.mjs+++ b/packages/cli/api/integration/authoring-checks.test.mjs@@ -28,7 +28,6 @@ import {integrationComponentConflicts,integrationDocConflicts,integrationTemplateConflicts,- shellArg,} from './authoring-checks.mjs';import {warmIntegrationChecks} from '../../test-utils/warm-integration-checks.mjs';@@ -383,13 +382,6 @@ describe('integrationTemplateConflicts', () => {expect(conflict?.message).not.toContain('set replaces');});- it('shell-quotes unusual ids instead of allowing command substitution', () => {- expect(shellArg('safe/id')).toBe('safe/id');- expect(shellArg('my$thing')).toBe("'my$thing'");- expect(shellArg("a'b")).toBe("'a'\\''b'");- expect(shellArg('foo`id`')).toBe("'foo`id`'");- });-it('returns a malformed template once as an invalid_template issue', async () => {fs.writeFileSync(path.join(tmpDir, 'package.json'),diff --git a/packages/cli/api/logger.mjs b/packages/cli/api/logger.mjsindex 675bde9d8c..7f5dbbe9c2 100644--- a/packages/cli/api/logger.mjs+++ b/packages/cli/api/logger.mjs@@ -3,7 +3,8 @@/*** @file The one `Logger`. Source of truth: the `Logger` type is generated from* the JSDoc here, and `logger` is the single instance every side-effecting- * command (`upgrade`, `init`, `themeBuild`) writes progress through.+ * command (`upgrade`, `init`, `themeBuild`, the experimental icon commands)+ * writes progress through.** It is silent by default, so a programmatic caller (or `--json` mode) sees* nothing but the returned `{type, data}`. The CLI calls `logger.setSilent(false)`diff --git a/packages/cli/assets/docs/tree/icon-sets.doc.mjs b/packages/cli/assets/docs/tree/icon-sets.doc.mjsindex c2d37fd08e..e0b8b2689d 100644--- a/packages/cli/assets/docs/tree/icon-sets.doc.mjs+++ b/packages/cli/assets/docs/tree/icon-sets.doc.mjs@@ -139,7 +139,7 @@ astryx experimental icon add --variant solid --from @heroicons/react/24/solid --},{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.",+ 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 (when omitted, the look a library that names its looks draws; otherwise the set's current default, else, on a set without icons, the first variant; a set with icons changes it only with `--from`, and only in a library that names its looks). `--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',@@ -177,7 +177,7 @@ astryx experimental icon add --variant solid --from @heroicons/react/24/solid --},{type: 'prose',- 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.",+ 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 component that writes its own `width` and `height` attributes (24, from a `size` prop, say) still fills its box when it passes `style` through to its svg: the `Icon` component and `themeIcons` size the svg with CSS, which overrides size attributes. The test checks that too.',},{type: 'code',@@ -191,6 +191,8 @@ for (const [name, Icon] of Object.entries(icons)) {const html = renderToStaticMarkup(createElement(Icon, {className: 'x'}));if (!/class="([^"]* )?x( [^"]*)?"/.test(html)) throw new Error(\`\${name} drops className\`);if (!html.includes('currentColor')) throw new Error(\`\${name} has a fixed color\`);+ const styled = renderToStaticMarkup(createElement(Icon, {style: {width: '1em'}}));+ if (!styled.includes('width:1em')) throw new Error(\`\${name} drops style, so CSS cannot size it\`);}`,},],@@ -215,6 +217,10 @@ for (const [name, Icon] of Object.entries(icons)) {'A subpath per style','`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`)',],+ [+ 'Every look in its export names (`XOutline24WGHT500Icon`, `XFilled24WGHT500Icon`)',+ "`experimental icon new-set meta --from @acme/vector-icons` wraps each glyph once as `x` (`XIcon`), in the look `--default-variant` names or the library's usual default (outline, the middle weight). For another look: `experimental icon new-set meta --variants outline,filled` declares it in place, then `experimental icon add --variant filled --from @acme/vector-icons --all`",+ ],['One file per icon, default export','`experimental icon add Rocket --from @acme/glyph-library/rocket --default --definition rocket`',@@ -262,7 +268,7 @@ export function adapt(data) {content: [{type: 'prose',- text: 'The generated module also exports `themeIcons`: one entry per built-in definition in `map`, each an element of your own icon, hidden from assistive technology and sized `1em`. The CLI rewrites it on every `experimental icon add` and `experimental icon map`, so you never write it by hand, and `integration check` proves it matches `map`. A theme uses it in one line:',+ text: "The generated module also exports `themeIcons`: one entry per built-in definition in `map`, each an element of your own icon, hidden from assistive technology and sized `1em` by its attributes and by CSS (its `style`), so it fills the theme's icon box even when your component writes its own size attributes. The CLI rewrites it on every `experimental icon add` and `experimental icon map`, so you never write it by hand, and `integration check` proves it matches `map`. A theme uses it in one line:",},{type: 'code',diff --git a/packages/cli/clients/cli/commands/experimental-icon-add.doc.mjs b/packages/cli/clients/cli/commands/experimental-icon-add.doc.mjsindex 6db71d122d..180a735944 100644--- a/packages/cli/clients/cli/commands/experimental-icon-add.doc.mjs+++ b/packages/cli/clients/cli/commands/experimental-icon-add.doc.mjs@@ -30,7 +30,7 @@ export const doc = {flag: '--new-definition <name>',param: 'options.newDefinition',description:- "Add your set's own definition, then map the icon to it; needs --description and --words",+ "Add your set's own definition, named in camelCase (aiHelper) or kebab-case (ai-helper), then map the icon to it; needs --description and --words",},{flag: '--description <text>',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 b69d412daf..6d5db6b49f 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@@ -18,7 +18,8 @@ export const doc = {name: 'name',param: 'name',required: true,- description: 'The definition name, in camelCase (rocketLaunch)',+ description:+ 'The definition name, in camelCase (rocketLaunch) or kebab-case (rocket-launch)',},],options: [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 47aa98947a..72dd060822 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, 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.",+ "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. A library whose export names end in looks (XOutline24WGHT500Icon) gives one icon per glyph, by its glyph id (x), in the look the default variant names, else the library's usual default. Run it again with --from to refresh. --variants and --default-variant declare the set's variants; over an existing set without --from, they, --display-name and --description update the set in place and leave its icons as they are; a set with icons changes its default variant only with --from, and only in a library whose export names encode looks. Experimental: it may change or be removed in a patch release.",fn: 'iconNewSet',args: [{@@ -49,7 +49,7 @@ export const doc = {flag: '--default-variant <variant>',param: 'options.defaultVariant',description:- "With --variants: the variant each icon's own export draws (the first variant when omitted)",+ "With --variants: the variant each icon's own export draws. When omitted: in a library whose export names encode looks, the look the icons draw (the library's usual default for a new set), which --variants must list; otherwise the set's current default, which --variants must list when the set has icons, else, on a set without icons, the first variant. A set with icons changes it only with --from, and only in a library whose export names encode looks",},{flag: '--display-name <text>',diff --git a/packages/cli/clients/cli/commands/experimental/icon.mjs b/packages/cli/clients/cli/commands/experimental/icon.mjsindex 0f3fde693a..ee1d813e76 100644--- a/packages/cli/clients/cli/commands/experimental/icon.mjs+++ b/packages/cli/clients/cli/commands/experimental/icon.mjs@@ -20,6 +20,7 @@ import {getCliInvocation,} from '../../../../foundation/env/package-manager.mjs';import {jsonOut} from '../../../../foundation/response/json.mjs';+import {logger} from '../../../../api/logger.mjs';import {resultSet} from '../../../../foundation/debug/index.mjs';import {emit,@@ -140,7 +141,7 @@ export function registerExperimentalIcon(group, program) {),),text(- `Built-in definitions are the ones every set maps. Map one: ${run} experimental icon map <definition> <icon id>`,+ `Built-in definitions are the ones every set maps. Map one: ${run} experimental icon map <definition> <icon id> --set <set>`,),);return answered;@@ -157,7 +158,9 @@ export function registerExperimentalIcon(group, program) {`${each.id}: ${each.words.join(', ')}${each.definitions.length > 0 ? ` = ${each.definitions.join(', ')}` : ''}`,),),- text(`Map one: ${run} experimental icon map <definition> <id>`),+ text(+ `Map one: ${run} experimental icon map <definition> <id> --set ${set}`,+ ),);return answered;}@@ -308,6 +311,9 @@ export function registerExperimentalIcon(group, program) {* @param {(result: any) => void} print*/const run = async (call, print) => {+ // Reading a large library reports its progress through the shared+ // logger: on stderr in text mode, never under --json.+ logger.setSilent(Boolean(program.opts().json));let result;try {result = await call();@@ -436,7 +442,7 @@ export function registerExperimentalIcon(group, program) {return;}if (result.type === 'icon.definitionMatches') {- const {matches, newDefinition} = result.data;+ const {matches, newDefinition, variant} = result.data;emit(section(`Icon definitions for ${result.data.export} (${matches.length})`,@@ -466,6 +472,13 @@ export function registerExperimentalIcon(group, program) {),]: []),+ ...(variant+ ? [+ text(+ `The set already has this glyph in another look. Add this one as its variant: ${formatCliCommand(variant)}`,+ ),+ ]+ : []),text(`All icon definitions: ${cli} docs cli/experimental/icon-definitions`,),@@ -500,17 +513,25 @@ export function registerExperimentalIcon(group, program) {const {root, manifest, files, written, dryRun} = data;const state = dryRun ? 'plan' : written ? 'ok' : 'unchanged';const refreshed = data.refreshed === true;+ const updated = data.updated === true;+ const What = `${what[0].toUpperCase()}${what.slice(1)}`;emit(section(refreshed? dryRun? `Refresh ${what} plan`- : `${what[0].toUpperCase()}${what.slice(1)} refreshed`- : dryRun- ? `New ${what} plan`- : written- ? `New ${what} added`- : `New ${what} unchanged`,+ : `${What} refreshed`+ : updated+ ? dryRun+ ? `${What} update plan`+ : written && files.length > 0+ ? `${What} updated`+ : `${What} unchanged`+ : 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@@ -542,7 +563,7 @@ export function registerExperimentalIcon(group, program) {list(data.suggestions.map(each =>- `${each.definition} -> ${each.icon} (${each.word}): ${formatCliCommand(`astryx experimental icon map ${each.definition} ${each.icon}`)}`,+ `${each.definition} -> ${each.icon} (${each.word}): ${formatCliCommand(`astryx experimental icon map ${each.definition} ${each.icon} --set ${data.name}`)}`,),),]diff --git a/packages/cli/clients/cli/commands/icon-authoring.test.mjs b/packages/cli/clients/cli/commands/icon-authoring.test.mjsindex 46d6620036..918394e0a2 100644--- a/packages/cli/clients/cli/commands/icon-authoring.test.mjs+++ b/packages/cli/clients/cli/commands/icon-authoring.test.mjs@@ -347,7 +347,7 @@ describe('icon add', () => {name: 'delete',source: 'astryx',command:- 'astryx experimental icon add Bin --from @acme/glyph-library --definition delete',+ 'astryx experimental icon add Bin --from @acme/glyph-library --set outline --definition delete',});expect(dataOf('outline').icons).toEqual([]);});@@ -415,8 +415,12 @@ describe('icon add', () => {const refused = await json(args);expect(refused.code).toBe(1);expect(refused.body.code).toBe('ERR_INVALID_ARGUMENT');- expect(refused.body.error).toContain('variant "solid" is not in variants');- expect(refused.body.error).toContain('Declare it in "variants"');+ expect(refused.body.error).toBe(+ 'Icon set "outline" declares no variant "solid". Declare it first, and name the look its icons draw now as the default variant in place of <default>.',+ );+ expect(refused.body.suggestions[0].name).toBe(+ 'astryx experimental icon new-set outline --variants <default>,solid --default-variant <default>',+ );expect(dataOf('outline')).toEqual(before);const dataPath = path.join(@@ -980,7 +984,7 @@ describe('a library of icon data, through the adapter', () => {);// A built-in mapping lands in the theme map, and the types follow.expect(text).toContain(- "close: createElement(XIcon, {'aria-hidden': true, 'width': '1em', 'height': '1em'}),",+ "close: createElement(XIcon, {'aria-hidden': true, 'width': '1em', 'height': '1em', 'style': {'width': '1em', 'height': '1em'}}),",);const types = fs.readFileSync(path.join(pkg, 'icon-sets', 'outline', 'outline.generated.d.ts'),diff --git a/packages/cli/clients/cli/commands/icon-library-looks.test.mjs b/packages/cli/clients/cli/commands/icon-library-looks.test.mjsnew file mode 100644index 0000000000..7db861ea2c--- /dev/null+++ b/packages/cli/clients/cli/commands/icon-library-looks.test.mjs@@ -0,0 +1,2010 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file A library that draws each icon in several looks, named in its+ * exports (`XOutline24WGHT400Icon`): one root barrel of default re-exports+ * and a file per export, as large vector libraries ship. `new-set`, `add`+ * and a refresh wrap each glyph once, by its glyph id, in the look the set+ * prefers.+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {createRequire} from 'node:module';+import {pathToFileURL} from 'node:url';+import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import {runCli} from '../../../test-utils/run-cli.mjs';+import {doc as newSetDoc} from '../../../api/icon/iconNewSet.doc.mjs';+import {+ libraryIcons,+ lookPositions,+} from '../../../foundation/discovery/icon-set-writer.mjs';++/** @type {string} */+let tmp;+/** @type {string} */+let pkg;++const STYLES = ['Filled', 'Outline'];+const WEIGHTS = [300, 400, 500];++/**+ * Write `@acme/vector-icons`: each glyph in every style and weight, and+ * `Heart` filled only.+ * @param {string[]} glyphs+ */+function writeVectorLibrary(glyphs) {+ const lib = path.join(pkg, 'node_modules', '@acme', 'vector-icons');+ fs.mkdirSync(path.join(lib, 'icons'), {recursive: true});+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ name: '@acme/vector-icons',+ version: '0.2.6',+ type: 'module',+ exports: {'.': './index.js', './*Icon': './icons/*Icon.js'},+ }),+ );+ /** @type {string[]} */+ const names = [];+ for (const glyph of glyphs) {+ for (const style of glyph === 'Heart' ? ['Filled'] : STYLES) {+ for (const weight of WEIGHTS) {+ names.push(`${glyph}${style}24WGHT${weight}Icon`);+ }+ }+ }+ for (const name of names) {+ fs.writeFileSync(+ path.join(lib, 'icons', `${name}.js`),+ 'export default function h(props) { return null; }\n',+ );+ }+ fs.writeFileSync(+ path.join(lib, 'index.js'),+ [+ "export {renderIcon} from './types.js';",+ ...names.map(+ name => `export {default as ${name}} from './icons/${name}.js';`,+ ),+ '',+ ].join('\n'),+ );+ fs.writeFileSync(+ path.join(lib, 'types.js'),+ 'export function renderIcon(Icon, props) { return null; }\n',+ );+ return path.join(lib, 'index.js');+}++const GLYPHS = ['X', 'Star', 'ArrowDown', 'Search', 'Trash', 'Heart'];++beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-icon-looks-'));+ pkg = path.join(tmp, 'icons');+ fs.mkdirSync(pkg, {recursive: true});+ fs.writeFileSync(+ path.join(pkg, 'package.json'),+ JSON.stringify(+ {+ name: '@acme/icons',+ version: '1.0.0',+ license: 'MIT',+ type: 'module',+ exports: {'.': './index.js'},+ dependencies: {'@acme/vector-icons': '^0.2.6'},+ },+ null,+ 2,+ ),+ );+ fs.writeFileSync(path.join(pkg, 'index.js'), 'export {};\n');+});+afterEach(() => {+ fs.rmSync(tmp, {recursive: true, force: true});+});++/** @param {string[]} args */+async function json(args) {+ const res = await runCli([...args, '--json'], pkg);+ return {code: res.code, body: JSON.parse(res.stdout)};+}++/** @param {string} set */+const dataOf = set =>+ JSON.parse(+ fs.readFileSync(+ path.join(pkg, 'icon-sets', set, `${set}.icons.json`),+ 'utf-8',+ ),+ );++/** @param {string} set */+const generatedOf = set =>+ fs.readFileSync(+ path.join(pkg, 'icon-sets', set, `${set}.generated.js`),+ 'utf-8',+ );++const NEW_SET = [+ 'experimental',+ 'icon',+ 'new-set',+ 'brand',+ '--from',+ '@acme/vector-icons',+];++describe('the looks a library names its exports by', () => {+ it('finds the trailing style, size and weight words, and none in a library of glyph names', () => {+ const file = writeVectorLibrary(GLYPHS);+ const icons = libraryIcons(file);+ expect(icons.map(icon => icon.id)).toEqual([+ 'arrow-down',+ 'heart',+ 'search',+ 'star',+ 'trash',+ 'x',+ ]);+ const x = icons.find(icon => icon.id === 'x');+ // The outline look, the middle weight.+ expect(x).toMatchObject({export: 'XOutline24WGHT400Icon', name: 'XIcon'});+ expect(x?.looks).toHaveLength(6);+ // A glyph drawn only filled comes in filled.+ expect(icons.find(icon => icon.id === 'heart')?.export).toBe(+ 'HeartFilled24WGHT400Icon',+ );+ expect(+ libraryIcons(file, {prefer: ['filled']}).find(icon => icon.id === 'x')+ ?.export,+ ).toBe('XFilled24WGHT400Icon');+ // Glyph names with numbers are not looks.+ expect(+ lookPositions(+ Array.from({length: 40}, (_, index) =>+ index % 2 ? `clock-${index}` : `arrow-${index}`,+ ),+ ),+ ).toEqual([]);+ });+});++describe('a library whose names end in directions', () => {+ it('groups no looks, and maps each arrow and chevron definition by its exact name', async () => {+ const lib = path.join(pkg, 'node_modules', '@acme', 'arrow-icons');+ fs.mkdirSync(lib, {recursive: true});+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ name: '@acme/arrow-icons',+ version: '1.0.0',+ type: 'module',+ exports: {'.': './index.js'},+ }),+ );+ const names = ['Arrow', 'Chevron', 'Caret', 'Triangle', 'Hand', 'Pointer']+ .flatMap(glyph =>+ ['Up', 'Down', 'Left', 'Right'].map(way => `${glyph}${way}Icon`),+ )+ .sort();+ fs.writeFileSync(+ path.join(lib, 'index.js'),+ names+ .map(name => `export function ${name}(props) { return null; }`)+ .join('\n') + '\n',+ );+ expect(libraryIcons(path.join(lib, 'index.js'))).toHaveLength(24);+ expect(+ lookPositions(+ names.map(name =>+ name+ .replace(/Icon$/u, '')+ .replace(/([a-z])([A-Z])/gu, '$1-$2')+ .toLowerCase(),+ ),+ ),+ ).toEqual([]);+ const {code, body} = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'arrows',+ '--from',+ '@acme/arrow-icons',+ ]);+ expect(code, JSON.stringify(body)).toBe(0);+ const data = dataOf('arrows');+ expect(data.icons).toHaveLength(24);+ expect(data.map).toMatchObject({+ arrowUp: 'arrow-up',+ arrowDown: 'arrow-down',+ arrowLeft: 'arrow-left',+ arrowRight: 'arrow-right',+ chevronUp: 'chevron-up',+ chevronDown: 'chevron-down',+ chevronLeft: 'chevron-left',+ chevronRight: 'chevron-right',+ });+ expect(generatedOf('arrows')).toContain(+ "export {ArrowUpIcon} from '@acme/arrow-icons';",+ );+ });+});++describe('new-set --from a library of looks', () => {+ it('wraps each glyph once by its glyph id, says what it found, and suggests only the default look', async () => {+ writeVectorLibrary(GLYPHS);+ const {code, body} = await json(NEW_SET);+ expect(code, JSON.stringify(body)).toBe(0);+ const data = dataOf('brand');+ expect(+ data.icons.map((/** @type {{id: string}} */ icon) => icon.id),+ ).toEqual(['arrow-down', 'heart', 'search', 'star', 'trash', 'x']);+ expect(generatedOf('brand')).toContain(+ "export {XOutline24WGHT400Icon as XIcon} from '@acme/vector-icons';",+ );+ expect(data.map).toMatchObject({arrowDown: 'arrow-down', star: 'star'});+ const notes = body.data.notes.join('\n');+ expect(notes).toContain(+ 'Found 6 icons in @acme/vector-icons, each drawn in several looks (filled or outline; 24; wght300, wght400, wght500) by 33 exports.',+ );+ expect(notes).toContain('in the outline 24 wght400 look');+ expect(body.data.suggestions).toEqual(+ expect.arrayContaining([+ expect.objectContaining({definition: 'close', icon: 'x'}),+ ]),+ );+ expect(JSON.stringify(body.data.suggestions)).not.toMatch(+ /filled|wght|outline/u,+ );+ });++ it('takes the look the set’s default variant names', async () => {+ writeVectorLibrary(GLYPHS);+ const {code} = await json([+ ...NEW_SET,+ '--variants',+ 'outline,filled',+ '--default-variant',+ 'filled',+ ]);+ expect(code).toBe(0);+ expect(generatedOf('brand')).toContain(+ "export {XFilled24WGHT400Icon as XIcon} from '@acme/vector-icons';",+ );+ });++ it('adds another look as a variant of every glyph, and lists a glyph drawn in no such look as missing', async () => {+ writeVectorLibrary(GLYPHS);+ await json([...NEW_SET, '--variants', 'outline,filled']);+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ '--variant',+ 'filled',+ '--from',+ '@acme/vector-icons',+ '--all',+ ]);+ expect(added.code, JSON.stringify(added.body)).toBe(0);+ // Heart's own export is its only look, filled: no second export of it.+ expect(added.body.data.missing).toEqual(['heart']);+ expect(generatedOf('brand')).not.toContain('HeartFilledIcon');+ expect(generatedOf('brand')).toContain(+ "export {XFilled24WGHT400Icon as XFilledIcon} from '@acme/vector-icons';",+ );+ const outlineOnly = await json([+ ...NEW_SET.slice(0, 3),+ 'outline-set',+ '--from',+ '@acme/vector-icons',+ '--variants',+ 'filled,outline',+ '--default-variant',+ 'filled',+ ]);+ expect(outlineOnly.code).toBe(0);+ const outline = await json([+ 'experimental',+ 'icon',+ 'add',+ '--set',+ 'outline-set',+ '--variant',+ 'outline',+ '--from',+ '@acme/vector-icons',+ '--all',+ ]);+ expect(outline.body.data.missing).toEqual(['heart']);+ });+});++describe('add <Export> --from a library of looks', () => {+ it('names the icon by its glyph and lists the definitions that fit it', async () => {+ writeVectorLibrary(GLYPHS);+ await json(['experimental', 'icon', 'new-set', 'brand']);+ const listed = await json([+ 'experimental',+ 'icon',+ 'add',+ 'XOutline24WGHT500Icon',+ '--from',+ '@acme/vector-icons',+ ]);+ expect(listed.code, JSON.stringify(listed.body)).toBe(0);+ expect(listed.body.data.id).toBe('x');+ expect(listed.body.data.matches[0].name).toBe('close');+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ 'XOutline24WGHT500Icon',+ '--from',+ '@acme/vector-icons',+ '--definition',+ 'close',+ ]);+ expect(added.code, JSON.stringify(added.body)).toBe(0);+ expect(dataOf('brand').map).toMatchObject({close: 'x'});+ expect(generatedOf('brand')).toContain(+ "export {XOutline24WGHT500Icon as XIcon} from '@acme/vector-icons';",+ );+ });+});++describe('a refresh of a set an earlier release wrapped one look at a time', () => {+ it('keeps every icon and id it has, removes none, and brings a new glyph in once', async () => {+ // Too few exports to show looks: each export is its own icon, as an+ // earlier release wrapped every library.+ writeVectorLibrary(['X', 'Star', 'ArrowDown']);+ expect((await json(NEW_SET)).code).toBe(0);+ await json([+ 'experimental',+ 'icon',+ 'map',+ 'close',+ 'x-outline-24-wght400',+ ]);+ const before = dataOf('brand');+ expect(before.icons).toHaveLength(18);+ writeVectorLibrary(GLYPHS);+ const refreshed = await json(NEW_SET);+ expect(refreshed.code, JSON.stringify(refreshed.body)).toBe(0);+ const after = dataOf('brand');+ const ids = after.icons.map((/** @type {{id: string}} */ icon) => icon.id);+ for (const icon of before.icons) expect(ids).toContain(icon.id);+ expect(ids).toEqual(expect.arrayContaining(['search', 'trash', 'heart']));+ expect(ids).not.toContain('search-outline-24-wght400');+ expect(after.map.close).toBe('x-outline-24-wght400');+ const notes = refreshed.body.data.notes.join('\n');+ expect(notes).not.toMatch(/no longer exports|new id/u);+ });+});++describe('commands add prints run as printed', () => {+ it('repeats --default, --set and --id in each listed command', async () => {+ writeVectorLibrary(GLYPHS);+ await json(['experimental', 'icon', 'new-set', 'brand']);+ const from = '@acme/vector-icons/XOutline24WGHT500Icon';+ const listed = await json([+ 'experimental',+ 'icon',+ 'add',+ 'XIcon',+ '--from',+ from,+ '--default',+ '--set',+ 'brand',+ ]);+ expect(listed.code, JSON.stringify(listed.body)).toBe(0);+ const [first] = listed.body.data.matches;+ expect(first.name).toBe('close');+ expect(first.command).toBe(+ `astryx experimental icon add XIcon --from ${from} --set brand --default --definition close`,+ );+ // The printed command runs.+ const args = first.command.split(' ').slice(1);+ const ran = await json(args);+ expect(ran.code, JSON.stringify(ran.body)).toBe(0);+ expect(dataOf('brand').map).toMatchObject({close: 'x'});+ });+});++describe('a new definition named in kebab-case', () => {+ it('is the camelCase definition, from add and from new-definition', async () => {+ writeVectorLibrary(GLYPHS);+ await json(['experimental', 'icon', 'new-set', 'brand']);+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ 'HeartFilled24WGHT500Icon',+ '--from',+ '@acme/vector-icons',+ '--new-definition',+ 'ai-helper',+ '--description',+ 'The AI helper.',+ '--words',+ 'assistant,ai',+ ]);+ expect(added.code, JSON.stringify(added.body)).toBe(0);+ expect(dataOf('brand').map).toMatchObject({aiHelper: 'heart'});+ expect(+ fs.existsSync(+ path.join(pkg, 'icon-sets', 'brand', 'definitions', 'aiHelper.doc.mjs'),+ ),+ ).toBe(true);+ const made = await json([+ 'experimental',+ 'icon',+ 'new-definition',+ 'company-logo',+ '--description',+ 'The company logo.',+ '--words',+ 'logo,brand',+ ]);+ expect(made.code, JSON.stringify(made.body)).toBe(0);+ expect(+ fs.existsSync(+ path.join(+ pkg,+ 'icon-sets',+ 'brand',+ 'definitions',+ 'companyLogo.doc.mjs',+ ),+ ),+ ).toBe(true);+ });++ it('is what an unknown --definition suggests, and the suggestion runs', async () => {+ writeVectorLibrary(GLYPHS);+ await json(['experimental', 'icon', 'new-set', 'brand']);+ const base = [+ 'experimental',+ 'icon',+ 'add',+ 'StarOutline24WGHT400Icon',+ '--from',+ '@acme/vector-icons',+ ];+ const refused = await json([...base, '--definition', 'brand-mark']);+ expect(refused.code).not.toBe(0);+ const suggestion = refused.body.suggestions.find(+ (/** @type {{name: string}} */ each) =>+ each.name.startsWith('--new-definition'),+ );+ expect(suggestion.name).toMatch(/^--new-definition brandMark /u);+ const ran = await json([+ ...base,+ '--new-definition',+ 'brandMark',+ '--description',+ 'The brand mark.',+ '--words',+ 'brand',+ ]);+ expect(ran.code, JSON.stringify(ran.body)).toBe(0);+ });+});++describe('new-set without --from over an existing set', () => {+ it('declares a variant in place, so add can give icons that look', async () => {+ writeVectorLibrary(GLYPHS);+ await json(NEW_SET);+ const before = generatedOf('brand');+ const refused = await json([+ 'experimental',+ 'icon',+ 'add',+ 'StarFilled24WGHT400Icon',+ '--from',+ '@acme/vector-icons',+ '--id',+ 'star',+ '--variant',+ 'filled',+ ]);+ expect(refused.code).not.toBe(0);+ expect(refused.body.error).toBe(+ 'Icon set "brand" declares no variant "filled". Declare it first.',+ );+ expect(refused.body.suggestions[0].name).toBe(+ 'astryx experimental icon new-set brand --variants outline,filled --default-variant outline',+ );+ const declared = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'brand',+ '--variants',+ 'outline,filled',+ '--description',+ 'Brand icons, every glyph.',+ ]);+ expect(declared.code, JSON.stringify(declared.body)).toBe(0);+ expect(dataOf('brand')).toMatchObject({+ variants: ['outline', 'filled'],+ default: {variant: 'outline'},+ });+ expect(generatedOf('brand')).toBe(before);+ expect(+ fs.readFileSync(+ path.join(pkg, 'icon-sets', 'brand', 'brand.doc.mjs'),+ 'utf-8',+ ),+ ).toContain("description: 'Brand icons, every glyph.',");+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ '--variant',+ 'filled',+ '--from',+ '@acme/vector-icons',+ '--all',+ ]);+ expect(added.code, JSON.stringify(added.body)).toBe(0);+ expect(generatedOf('brand')).toContain(+ "export {StarFilled24WGHT400Icon as StarFilledIcon} from '@acme/vector-icons';",+ );+ // A variant an icon has stays declared.+ const dropping = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'brand',+ '--variants',+ 'outline,bold',+ ]);+ expect(dropping.code).not.toBe(0);+ expect(dropping.body.error).toMatch(+ /^These icons still have a variant --variants leaves out: arrow-down \(filled\)/u,+ );+ });++ it('still refuses to overwrite a set when nothing is asked of it', async () => {+ writeVectorLibrary(GLYPHS);+ await json(NEW_SET);+ const again = await json(['experimental', 'icon', 'new-set', 'brand']);+ expect(again.code).not.toBe(0);+ expect(again.body.error).toMatch(/^Refusing to overwrite existing file/u);+ });+});++describe('generated files a formatter rewrote', () => {+ it.each([+ [+ 'a house style',+ {singleQuote: true, bracketSpacing: false, trailingComma: 'all'},+ ],+ ['Prettier defaults', {}],+ ['no semicolons', {semi: false}],+ [+ 'a house style without semicolons',+ {semi: false, singleQuote: true, bracketSpacing: false},+ ],+ ])(+ 'pass integration check and take the next command (%s)',+ async (_, options) => {+ const prettier = await import('prettier');+ writeVectorLibrary(GLYPHS);+ await json(NEW_SET);+ await json(['experimental', 'icon', 'map', 'close', 'x']);+ const dir = path.join(pkg, 'icon-sets', 'brand');+ for (const [file, parser] of [+ ['brand.generated.js', 'babel'],+ ['brand.generated.d.ts', 'typescript'],+ ]) {+ const full = path.join(dir, file);+ const formatted = await prettier.format(+ fs.readFileSync(full, 'utf-8'),+ {parser, printWidth: 60, ...options},+ );+ expect(formatted).not.toBe(fs.readFileSync(full, 'utf-8'));+ fs.writeFileSync(full, formatted);+ }+ const check = await runCli(['integration', 'check', '--json'], pkg);+ const codes = JSON.stringify(JSON.parse(check.stdout));+ for (const code of [+ 'icon_module_invalid',+ 'icon_generated_types_mismatch',+ 'icon_theme_map_mismatch',+ ]) {+ expect(codes, code).not.toContain(code);+ }+ // The writer reads the formatted module and writes the next entry.+ const mapped = await json([+ 'experimental',+ 'icon',+ 'map',+ 'close',+ 'trash',+ ]);+ expect(mapped.code, JSON.stringify(mapped.body)).toBe(0);+ expect(generatedOf('brand')).toContain('close: createElement(TrashIcon');+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ 'HeartFilled24WGHT400Icon',+ '--from',+ '@acme/vector-icons',+ '--definition',+ 'warning',+ ]);+ expect(added.code, JSON.stringify(added.body)).toBe(0);+ // React is imported once, and the module reads back as it was written.+ expect(+ generatedOf('brand').match(/import \{\s*createElement\s*\} from/gu),+ ).toHaveLength(1);+ const again = await runCli(['integration', 'check', '--json'], pkg);+ expect(JSON.stringify(JSON.parse(again.stdout))).not.toContain(+ 'icon_generated_types_mismatch',+ );+ const remapped = await json([+ 'experimental',+ 'icon',+ 'map',+ 'close',+ 'x',+ ]);+ expect(remapped.code, JSON.stringify(remapped.body)).toBe(0);+ },+ );++ it('fails a declaration file that no longer matches, without semicolons too', async () => {+ const prettier = await import('prettier');+ writeVectorLibrary(GLYPHS);+ await json(NEW_SET);+ await json(['experimental', 'icon', 'map', 'close', 'x']);+ const types = path.join(pkg, 'icon-sets', 'brand', 'brand.generated.d.ts');+ const formatted = await prettier.format(+ fs+ .readFileSync(types, 'utf-8')+ .replace('readonly close', 'readonly shut'),+ {parser: 'typescript', semi: false},+ );+ fs.writeFileSync(types, formatted);+ const check = await runCli(['integration', 'check', '--json'], pkg);+ expect(JSON.stringify(JSON.parse(check.stdout))).toContain(+ 'icon_generated_types_mismatch',+ );+ });+});++describe('themeIcons with a component that writes its own size', () => {+ it('sizes each entry with CSS, which overrides the 24px attributes it writes', async () => {+ writeVectorLibrary(GLYPHS);+ // Like a large vector library: `size` (24) wins over width and height.+ const lib = path.join(pkg, 'node_modules', '@acme', 'vector-icons');+ fs.writeFileSync(+ path.join(lib, 'icons', 'XOutline24WGHT400Icon.js'),+ [+ "import {createElement} from 'react';",+ 'export default function X({size = 24, ...rest}) {',+ " return createElement('svg', {...rest, width: size, height: size, viewBox: '0 0 24 24', fill: 'currentColor'});",+ '}',+ '',+ ].join('\n'),+ );+ const require = createRequire(import.meta.url);+ fs.symlinkSync(+ path.dirname(require.resolve('react/package.json')),+ path.join(pkg, 'node_modules', 'react'),+ 'dir',+ );+ await json(NEW_SET);+ await json(['experimental', 'icon', 'map', 'close', 'x']);+ const {themeIcons} = await import(+ pathToFileURL(path.join(pkg, 'icon-sets', 'brand', 'brand.generated.js'))+ .href+ );+ const {renderToStaticMarkup} = await import('react-dom/server');+ const html = renderToStaticMarkup(themeIcons.close);+ expect(html).toContain('width="24"');+ expect(html).toContain('style="width:1em;height:1em"');+ });+});++describe('reading a large library', () => {+ it('says so on stderr in text mode, with what it found, and keeps JSON one document', async () => {+ // 170 glyphs, each its own last word (`GlyphAa`, `GlyphAb`, …).+ const letters = 'abcdefghijklmnopqrstuvwxyz';+ writeVectorLibrary(+ Array.from(+ {length: 170},+ (_, index) =>+ `Glyph${letters[Math.floor(index / 26)].toUpperCase()}${letters[index % 26]}`,+ ),+ );+ const text = await runCli([...NEW_SET, '--dry-run'], pkg);+ expect(text.code).toBe(0);+ expect(text.stderr).toContain(+ 'Reading 1021 exports of @acme/vector-icons...',+ );+ expect(text.stderr).toContain(+ 'Found 170 icons in @acme/vector-icons, drawn by 1020 exports in their looks.',+ );+ const asJson = await runCli([...NEW_SET, '--dry-run', '--json'], pkg);+ expect(asJson.stderr).not.toContain('Reading');+ expect(JSON.parse(asJson.stdout).data.icons).toBe(170);+ });+});++describe('reading a large library again', () => {+ /** 170 glyphs in every look: 1,021 exports. */+ const manyGlyphs = () => {+ const letters = 'abcdefghijklmnopqrstuvwxyz';+ return Array.from(+ {length: 170},+ (_, index) =>+ `Glyph${letters[Math.floor(index / 26)].toUpperCase()}${letters[index % 26]}`,+ );+ };++ it('reports progress on a refresh, on an add listing, and names the module as given on add --all', async () => {+ writeVectorLibrary(manyGlyphs());+ await json([...NEW_SET, '--variants', 'outline,filled']);+ const refresh = await runCli([...NEW_SET, '--dry-run'], pkg);+ expect(refresh.code, refresh.stdout).toBe(0);+ expect(refresh.stderr).toContain(+ 'Reading 1021 exports of @acme/vector-icons...',+ );+ expect(refresh.stderr).toContain(+ 'Found 1020 exports in @acme/vector-icons.',+ );+ const listing = await runCli(+ [+ 'experimental',+ 'icon',+ 'add',+ 'GlyphAaOutline24WGHT400Icon',+ '--from',+ '@acme/vector-icons',+ ],+ pkg,+ );+ expect(listing.code, listing.stdout).toBe(0);+ expect(listing.stderr).toContain(+ 'Reading 1021 exports of @acme/vector-icons...',+ );+ const all = await runCli(+ [+ 'experimental',+ 'icon',+ 'add',+ '--variant',+ 'filled',+ '--from',+ '@acme/vector-icons',+ '--all',+ ],+ pkg,+ );+ expect(all.code, all.stdout).toBe(0);+ expect(all.stderr).toContain(+ 'Reading 1021 exports of @acme/vector-icons...',+ );+ expect(all.stderr).not.toContain('index.js');+ });+});++describe('the default variant over an existing set', () => {+ it('stays when --variants adds a variant in place without --default-variant', async () => {+ writeVectorLibrary(GLYPHS);+ await json([+ ...NEW_SET,+ '--variants',+ 'outline,filled',+ '--default-variant',+ 'filled',+ ]);+ const updated = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'brand',+ '--variants',+ 'outline,filled,bold',+ ]);+ expect(updated.code, JSON.stringify(updated.body)).toBe(0);+ // The next command it prints names the set, so it runs in a package of+ // several sets too.+ expect(updated.body.data.notes.join(' ')).toContain(+ '`astryx experimental icon add --variant bold --from <module> --all --set brand`',+ );+ expect(dataOf('brand')).toMatchObject({+ variants: ['outline', 'filled', 'bold'],+ default: {variant: 'filled'},+ });+ // A refresh with --variants keeps it too.+ const refreshed = await json([+ ...NEW_SET,+ '--variants',+ 'outline,filled,bold',+ ]);+ expect(refreshed.code, JSON.stringify(refreshed.body)).toBe(0);+ expect(dataOf('brand').default).toEqual({variant: 'filled'});+ });++ it('moves in place only on a set with no icons; a set with icons names the refresh that moves it', async () => {+ writeVectorLibrary(GLYPHS);+ await json([+ ...NEW_SET,+ '--variants',+ 'outline,filled',+ '--default-variant',+ 'filled',+ ]);+ const before = fs.readFileSync(+ path.join(pkg, 'icon-sets', 'brand', 'brand.icons.json'),+ 'utf-8',+ );+ const move = [+ 'experimental',+ 'icon',+ 'new-set',+ 'brand',+ '--variants',+ 'outline,filled',+ '--default-variant',+ 'outline',+ ];+ const refused = await json(move);+ expect(refused.code).not.toBe(0);+ expect(refused.body.code).toBe('ERR_INVALID_ARGUMENT');+ expect(refused.body.error).toContain(+ 'each of its 6 icons still draws "filled"',+ );+ const refresh = refused.body.suggestions[0].name;+ expect(refresh).toBe(+ 'astryx experimental icon new-set brand --from @acme/vector-icons --variants outline,filled --default-variant outline',+ );+ expect(+ fs.readFileSync(+ path.join(pkg, 'icon-sets', 'brand', 'brand.icons.json'),+ 'utf-8',+ ),+ ).toBe(before);+ expect(generatedOf('brand')).toContain(+ "export {XFilled24WGHT400Icon as XIcon} from '@acme/vector-icons';",+ );+ const refreshed = await json(refresh.split(' ').slice(1));+ expect(refreshed.code, JSON.stringify(refreshed.body)).toBe(0);+ expect(dataOf('brand').default).toEqual({variant: 'outline'});+ expect(generatedOf('brand')).toContain(+ "export {XOutline24WGHT400Icon as XIcon} from '@acme/vector-icons';",+ );++ await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'empty',+ '--variants',+ 'outline,filled',+ ]);+ const emptyMoved = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'empty',+ '--variants',+ 'outline,filled',+ '--default-variant',+ 'filled',+ ]);+ expect(emptyMoved.code, JSON.stringify(emptyMoved.body)).toBe(0);+ expect(dataOf('empty').default).toEqual({variant: 'filled'});+ });++ it('heads an in-place update "Icon set updated", and its plan "Icon set update plan"', async () => {+ writeVectorLibrary(GLYPHS);+ await json([...NEW_SET, '--variants', 'outline,filled']);+ const declare = [+ 'experimental',+ 'icon',+ 'new-set',+ 'brand',+ '--variants',+ 'outline,filled,bold',+ ];+ const plan = await runCli([...declare, '--dry-run'], pkg);+ expect(plan.code, plan.stdout).toBe(0);+ expect(plan.stdout).toContain('Icon set update plan');+ expect(plan.stdout).not.toContain('New icon set');+ const updated = await runCli(declare, pkg);+ expect(updated.code, updated.stdout).toBe(0);+ expect(updated.stdout).toContain('Icon set updated');+ expect(updated.stdout).not.toContain('New icon set');+ const again = await json(declare);+ expect(again.body.data.updated).toBe(true);+ const unchanged = await runCli(declare, pkg);+ expect(unchanged.stdout).toContain('Icon set unchanged');+ });++ it('is named in the command add prints to declare a variant, so it runs as printed', async () => {+ writeVectorLibrary(GLYPHS);+ await json([+ ...NEW_SET,+ '--variants',+ 'filled',+ '--default-variant',+ 'filled',+ ]);+ const declare =+ 'astryx experimental icon new-set brand --variants filled,outline --default-variant filled';+ const one = await json([+ 'experimental',+ 'icon',+ 'add',+ 'StarOutline24WGHT400Icon',+ '--from',+ '@acme/vector-icons',+ '--id',+ 'star',+ '--variant',+ 'outline',+ ]);+ expect(one.code).not.toBe(0);+ expect(one.body.suggestions[0].name).toBe(declare);+ const all = await json([+ 'experimental',+ 'icon',+ 'add',+ '--variant',+ 'outline',+ '--from',+ '@acme/vector-icons',+ '--all',+ ]);+ expect(all.code).not.toBe(0);+ expect(all.body.suggestions[0].name).toBe(declare);+ const ran = await json(declare.split(' ').slice(1));+ expect(ran.code, JSON.stringify(ran.body)).toBe(0);+ expect(dataOf('brand').default).toEqual({variant: 'filled'});+ });+});++describe('add <Export> for a glyph the set already wraps in another look', () => {+ it('lists commands that run as printed: a definition under the look-kept name, or a variant of the glyph', async () => {+ writeVectorLibrary(GLYPHS);+ await json([...NEW_SET, '--variants', 'outline,filled']);+ expect(generatedOf('brand')).toContain(+ "export {XOutline24WGHT400Icon as XIcon} from '@acme/vector-icons';",+ );+ const base = [+ 'experimental',+ 'icon',+ 'add',+ 'XFilled24WGHT500Icon',+ '--from',+ '@acme/vector-icons',+ ];+ const listed = await json(base);+ expect(listed.code, JSON.stringify(listed.body)).toBe(0);+ expect(listed.body.data.variant).toBe(+ 'astryx experimental icon add XFilled24WGHT500Icon --from @acme/vector-icons --set brand --id x --variant filled',+ );+ const close = listed.body.data.matches.find(+ (/** @type {{name: string}} */ each) => each.name === 'close',+ );+ expect(close.command).toBe(+ 'astryx experimental icon add XFilled24WGHT500Icon --from @acme/vector-icons --set brand --definition close',+ );+ const text = await runCli(base, pkg);+ expect(text.stdout).toContain('Add this one as its variant');+ const asDefinition = await json(close.command.split(' ').slice(1));+ expect(asDefinition.code, JSON.stringify(asDefinition.body)).toBe(0);+ expect(asDefinition.body.data.icon.export).toBe('XFilled24WGHT500Icon');+ const asVariant = await json(listed.body.data.variant.split(' ').slice(1));+ expect(asVariant.code, JSON.stringify(asVariant.body)).toBe(0);+ expect(generatedOf('brand')).toContain(+ "export {XFilled24WGHT500Icon as XFilledIcon} from '@acme/vector-icons';",+ );+ });++ it('lists a variant command only for a declared look other than the default, and every listed command runs as printed', async () => {+ writeVectorLibrary(GLYPHS);+ await json([...NEW_SET, '--variants', 'outline,filled']);+ expect(dataOf('brand').default).toEqual({variant: 'outline'});+ const snapshot = path.join(tmp, 'snapshot');+ fs.cpSync(pkg, snapshot, {recursive: true});+ const restore = () => {+ fs.rmSync(pkg, {recursive: true, force: true});+ fs.cpSync(snapshot, pkg, {recursive: true});+ };+ /** @param {string} exportName */+ const listedCommands = async exportName => {+ const listed = await json([+ 'experimental',+ 'icon',+ 'add',+ exportName,+ '--from',+ '@acme/vector-icons',+ ]);+ expect(listed.code, JSON.stringify(listed.body)).toBe(0);+ const {data} = listed.body;+ return {+ variant: data.variant ?? null,+ commands: [+ ...data.matches.map(+ (/** @type {{command: string}} */ m) => m.command,+ ),+ ...(data.newDefinition ? [data.newDefinition] : []),+ ...(data.variant ? [data.variant] : []),+ ].filter(command => !command.includes('<')),+ };+ };+ // Same style as the wrapped export, another weight: the weight word is+ // no declared variant, so no variant command is listed.+ const sameStyle = await listedCommands('XOutline24WGHT500Icon');+ expect(sameStyle.variant).toBeNull();+ // Another style: the style word is a declared variant, not the default.+ const otherStyle = await listedCommands('XFilled24WGHT500Icon');+ expect(otherStyle.variant).toBe(+ 'astryx experimental icon add XFilled24WGHT500Icon --from @acme/vector-icons --set brand --id x --variant filled',+ );+ for (const command of [...sameStyle.commands, ...otherStyle.commands]) {+ restore();+ const ran = await json(command.split(' ').slice(1));+ expect(ran.code, `${command}\n${JSON.stringify(ran.body)}`).toBe(0);+ }+ expect(sameStyle.commands.length).toBeGreaterThan(0);+ });++ it('names the export from --id', async () => {+ writeVectorLibrary(GLYPHS);+ await json(NEW_SET);+ const added = await json([+ 'experimental',+ 'icon',+ 'add',+ 'XFilled24WGHT500Icon',+ '--from',+ '@acme/vector-icons',+ '--id',+ 'x-filled',+ '--definition',+ 'close',+ ]);+ expect(added.code, JSON.stringify(added.body)).toBe(0);+ expect(added.body.data.icon).toMatchObject({+ id: 'x-filled',+ export: 'XFilledIcon',+ });+ expect(generatedOf('brand')).toContain(+ "export {XFilled24WGHT500Icon as XFilledIcon} from '@acme/vector-icons';",+ );+ });+});++describe('progress lines', () => {+ it('reach stderr through the CLI’s text-mode output only', async () => {+ const letters = 'abcdefghijklmnopqrstuvwxyz';+ writeVectorLibrary(+ Array.from(+ {length: 170},+ (_, index) =>+ `Glyph${letters[Math.floor(index / 26)].toUpperCase()}${letters[index % 26]}`,+ ),+ );+ await json(NEW_SET);+ const listing = [+ 'experimental',+ 'icon',+ 'add',+ 'GlyphAaOutline24WGHT400Icon',+ '--from',+ '@acme/vector-icons',+ ];+ const text = await runCli(listing, pkg);+ expect(text.stderr).toContain('Reading 1021 exports');+ const asJson = await runCli([...listing, '--json'], pkg);+ expect(asJson.stderr).not.toContain('Reading');+ JSON.parse(asJson.stdout);+ // The command writes no chatter of its own: the logger is the one path.+ const source = fs.readFileSync(+ new URL('./experimental/icon.mjs', import.meta.url),+ 'utf-8',+ );+ expect(source).not.toMatch(/console\.(?:error|warn|log)/u);+ });+});++describe('a refresh to a default the library names no look by', () => {+ it('refuses, writes nothing, and names the look words it found', async () => {+ writeVectorLibrary(GLYPHS);+ await json([+ ...NEW_SET,+ '--variants',+ 'filled,outline',+ '--default-variant',+ 'filled',+ ]);+ const dir = path.join(pkg, 'icon-sets', 'brand');+ const snapshot = () =>+ Object.fromEntries(+ fs+ .readdirSync(dir)+ .sort()+ .map(file => [file, fs.readFileSync(path.join(dir, file), 'utf-8')]),+ );+ const before = snapshot();+ const refused = await json([+ ...NEW_SET,+ '--variants',+ 'solid,outline',+ '--default-variant',+ 'solid',+ ]);+ expect(refused.code).not.toBe(0);+ expect(refused.body.code).toBe('ERR_INVALID_ARGUMENT');+ expect(refused.body.error).toContain('"solid"');+ expect(refused.body.error).toContain('filled or outline');+ expect(+ refused.body.suggestions.map((/** @type {any} */ each) => each.name),+ ).toEqual(['--default-variant filled', '--default-variant outline']);+ expect(snapshot()).toEqual(before);+ expect(generatedOf('brand')).toContain(+ "export {XFilled24WGHT400Icon as XIcon} from '@acme/vector-icons';",+ );+ });+});++describe('--variants over a set with icons and no declared default', () => {+ it('takes the look the icons draw as the default, so add gives no second export of it', async () => {+ writeVectorLibrary(GLYPHS);+ await json(NEW_SET);+ expect(generatedOf('brand')).toContain(+ "export {XOutline24WGHT400Icon as XIcon} from '@acme/vector-icons';",+ );+ const declared = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'brand',+ '--variants',+ 'filled,outline',+ ]);+ expect(declared.code, JSON.stringify(declared.body)).toBe(0);+ expect(dataOf('brand')).toMatchObject({+ variants: ['filled', 'outline'],+ default: {variant: 'outline'},+ });+ await json([+ 'experimental',+ 'icon',+ 'add',+ '--variant',+ 'outline',+ '--from',+ '@acme/vector-icons',+ '--all',+ ]);+ const generated = generatedOf('brand');+ expect(generated.match(/XOutline24WGHT400Icon/gu)).toHaveLength(1);+ expect(generated).not.toContain('XOutlineIcon');+ expect(dataOf('brand').default).toEqual({variant: 'outline'});+ });++ it('refuses a --default-variant other than the look the icons draw', async () => {+ writeVectorLibrary(GLYPHS);+ await json(NEW_SET);+ const before = fs.readFileSync(+ path.join(pkg, 'icon-sets', 'brand', 'brand.icons.json'),+ 'utf-8',+ );+ const refused = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'brand',+ '--variants',+ 'filled,outline',+ '--default-variant',+ 'filled',+ ]);+ expect(refused.code).not.toBe(0);+ expect(refused.body.code).toBe('ERR_INVALID_ARGUMENT');+ expect(refused.body.error).toContain('still draws "outline"');+ expect(+ fs.readFileSync(+ path.join(pkg, 'icon-sets', 'brand', 'brand.icons.json'),+ 'utf-8',+ ),+ ).toBe(before);+ });+});++describe('progress through the logger', () => {+ const manyGlyphs = () => {+ const letters = 'abcdefghijklmnopqrstuvwxyz';+ return Array.from(+ {length: 170},+ (_, index) =>+ `Glyph${letters[Math.floor(index / 26)].toUpperCase()}${letters[index % 26]}`,+ );+ };++ /** @param {() => Promise<unknown>} fn */+ async function stderrOf(fn) {+ /** @type {string[]} */+ const lines = [];+ const original = console.error;+ console.error = (/** @type {unknown[]} */ ...args) => {+ lines.push(args.join(' '));+ };+ try {+ await fn();+ } finally {+ console.error = original;+ }+ return lines;+ }++ it('reaches stderr from a direct API call once the logger is on, and stays quiet while it is silent', async () => {+ writeVectorLibrary(manyGlyphs());+ const {iconNewSet} = await import('../../../api/icon/new-set/new-set.mjs');+ const {logger} = await import('../../../api/logger.mjs');+ const call = () =>+ iconNewSet('brand', {+ cwd: pkg,+ from: '@acme/vector-icons',+ dryRun: true,+ });+ try {+ logger.setSilent(true);+ expect(await stderrOf(call)).toEqual([]);+ logger.setSilent(false);+ const heard = await stderrOf(call);+ expect(heard).toContain('Reading 1021 exports of @acme/vector-icons...');+ } finally {+ logger.setSilent(true);+ }+ });++ it('is no option of the API calls', async () => {+ writeVectorLibrary(GLYPHS);+ const {iconNewSet} = await import('../../../api/icon/new-set/new-set.mjs');+ await expect(+ iconNewSet('brand', {+ cwd: pkg,+ from: '@acme/vector-icons',+ dryRun: true,+ // @ts-expect-error the option is gone+ progress: () => {},+ }),+ ).rejects.toThrow('Option "progress" does not apply');+ });+});++describe('the default variant on every path', () => {+ const PLAIN = '@acme/plain-icons';+ const PLAIN_SOLID = '@acme/plain-icons/solid';++ /**+ * Write `@acme/plain-icons`, whose export names name no looks: its root+ * module draws each glyph in outline, and `/solid` draws the same names+ * solid.+ * @param {string[]} glyphs+ */+ function writePlainLibrary(glyphs) {+ const lib = path.join(pkg, 'node_modules', '@acme', 'plain-icons');+ fs.mkdirSync(path.join(lib, 'solid'), {recursive: true});+ fs.writeFileSync(+ path.join(lib, 'package.json'),+ JSON.stringify({+ name: PLAIN,+ version: '1.0.0',+ type: 'module',+ exports: {'.': './index.js', './solid': './solid/index.js'},+ }),+ );+ const source = glyphs+ .map(glyph => `export function ${glyph}Icon(props) { return null; }\n`)+ .join('');+ fs.writeFileSync(path.join(lib, 'index.js'), source);+ fs.writeFileSync(path.join(lib, 'solid', 'index.js'), source);+ const manifest = path.join(pkg, 'package.json');+ const data = JSON.parse(fs.readFileSync(manifest, 'utf-8'));+ data.dependencies[PLAIN] = '^1.0.0';+ fs.writeFileSync(manifest, `${JSON.stringify(data, null, 2)}\n`);+ }++ /**+ * @typedef {object} Library+ * @property {string} module the module a set wraps+ * @property {() => void} write+ * @property {(look: string) => string} moduleOf the module that draws a look+ * @property {(glyph: string, look: string) => string} exportOf the+ * export that draws a glyph in a look+ * @property {(source: string, module: string) => string | null} lookOf the+ * look a library export draws+ * @property {(glyph: string, look: string) => boolean} glyphHas+ * @property {{drawn: string, other: string}} usual the look a set wraps+ * without a default, and another+ * @property {{drawn: string, other: string}} declared the default a set+ * declares, and another+ */++ /** @param {string} word */+ const capital = word => word[0].toUpperCase() + word.slice(1);++ /** @type {Record<string, Library>} */+ const LIBRARIES = {+ 'looks in names': {+ module: '@acme/vector-icons',+ write: () => writeVectorLibrary(GLYPHS),+ moduleOf: () => '@acme/vector-icons',+ exportOf: (glyph, look) => `${glyph}${capital(look)}24WGHT400Icon`,+ lookOf: source =>+ /Filled/u.test(source)+ ? 'filled'+ : /Outline/u.test(source)+ ? 'outline'+ : null,+ glyphHas: (glyph, look) => glyph !== 'heart' || look === 'filled',+ usual: {drawn: 'outline', other: 'filled'},+ declared: {drawn: 'filled', other: 'outline'},+ },+ 'no looks in names': {+ module: PLAIN,+ write: () => writePlainLibrary(GLYPHS),+ moduleOf: look => (look === 'solid' ? PLAIN_SOLID : PLAIN),+ exportOf: glyph => `${glyph}Icon`,+ lookOf: (_source, module) =>+ module === PLAIN_SOLID ? 'solid' : module === PLAIN ? 'outline' : null,+ glyphHas: () => true,+ usual: {drawn: 'outline', other: 'solid'},+ declared: {drawn: 'outline', other: 'solid'},+ },+ };++ /**+ * Every file of the package but its libraries, for a byte-for-byte+ * comparison.+ * @param {string} dir+ * @returns {Record<string, string>}+ */+ function snapshot(dir = pkg) {+ /** @type {Record<string, string>} */+ const files = {};+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ if (entry.name === 'node_modules') continue;+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) Object.assign(files, snapshot(full));+ else files[path.relative(pkg, full)] = fs.readFileSync(full, 'utf-8');+ }+ return files;+ }++ /**+ * The set as written: each icon's own export draws the default variant+ * (where the library draws the glyph in it), each variant draws its own+ * look and never the icon's, and no library export is exported twice.+ * A default the author named for a library whose names name no looks is+ * the author's word: the command can't read what its icons draw, so only+ * the variants are checked.+ * @param {Library} lib+ * @param {string | null} expected the default variant the set must record+ * @param {{authored?: boolean}} [options]+ */+ function expectEveryIconDrawsDefault(lib, expected, options = {}) {+ const data = dataOf('brand');+ expect(data.default?.variant ?? null).toBe(expected);+ /** @type {Map<string, {source: string, module: string}>} */+ const originOf = new Map();+ /** @type {string[]} */+ const origins = [];+ for (const [, source, name, module] of generatedOf('brand').matchAll(+ /export \{(\w+)(?: as (\w+))?\} from '([^']+)';/gu,+ )) {+ if (!module.startsWith('@acme/')) continue;+ originOf.set(name ?? source, {source, module});+ origins.push(`${module} ${source}`);+ }+ expect(origins.length, 'no library export is exported twice').toBe(+ new Set(origins).size,+ );+ /** @param {string} name */+ const lookOfExport = name => {+ const origin = originOf.get(name);+ return origin ? lib.lookOf(origin.source, origin.module) : null;+ };+ for (const icon of data.icons) {+ const own = lookOfExport(icon.export);+ if (+ expected != null &&+ !options.authored &&+ lib.glyphHas(icon.id, expected)+ ) {+ expect(own, `${icon.id} draws the default`).toBe(expected);+ }+ for (const variant of icon.variants ?? []) {+ const drawn = lookOfExport(variant.export);+ expect(drawn, `${icon.id} ${variant.variant}`).toBe(variant.variant);+ expect(drawn, `${icon.id} ${variant.variant} is another look`).not.toBe(+ own,+ );+ }+ }+ }++ /** @param {string} command a printed command, `astryx …` */+ async function runPrinted(command) {+ const ran = await json(command.split(' ').slice(1));+ expect(ran.code, `${command}: ${JSON.stringify(ran.body)}`).toBe(0);+ return ran;+ }++ /**+ * The commands a result prints: its suggestions, and each command quoted+ * in its notes.+ * @param {any} body+ * @returns {string[]}+ */+ function printedCommands(body) {+ return [+ ...(body.suggestions ?? []).map((/** @type {any} */ each) => each.name),+ ...(body.data?.notes ?? []).flatMap((/** @type {string} */ note) =>+ [...note.matchAll(/`(astryx [^`]+)`/gu)].map(match => match[1]),+ ),+ ].filter(command => command.startsWith('astryx experimental icon '));+ }++ /**+ * Each printed command names the set it acts on: `new-set brand`, or+ * `--set brand` on a command that takes one.+ * @param {any} body+ */+ function expectEveryCommandNamesTheSet(body) {+ for (const command of printedCommands(body)) {+ if (/^astryx experimental icon new-set /u.test(command)) {+ expect(command).toMatch(+ /^astryx experimental icon new-set brand(?: |$)/u,+ );+ } else {+ expect(command, command).toMatch(/ --set brand(?: |$)/u);+ }+ }+ }++ /**+ * A printed command with its named placeholders filled: the module that+ * draws the look it adds, a look other than the set's default, the look+ * the icons draw, and an icon and definition of the receipt.+ * @param {string} command+ * @param {Library} lib+ * @param {{drawn: string, other: string}} looks+ * @param {any} body+ */+ function filled(command, lib, looks, body) {+ const another =+ dataOf('brand').default?.variant === looks.other+ ? looks.drawn+ : looks.other;+ const withLook = command+ .replaceAll('<look>', another)+ .replaceAll('<name>', another)+ .replaceAll('<default>', looks.drawn);+ const variant = /--variant (\S+)/u.exec(withLook)?.[1] ?? looks.other;+ const pair = body.data?.suggestions?.[0] ?? body.data?.mapped?.[0];+ return withLook+ .replaceAll('<module>', lib.moduleOf(variant))+ .replaceAll('<Export>', lib.exportOf('Search', variant))+ .replaceAll('<icon>', pair?.icon ?? 'search')+ .replaceAll('<definition>', pair?.definition ?? 'search');+ }++ /**+ * Run every command a receipt's notes print, its named placeholders+ * filled.+ * @param {any} body+ * @param {Library} lib+ * @param {{drawn: string, other: string}} looks+ * @param {() => void} check+ */+ async function runPrintedNotes(body, lib, looks, check) {+ const commands = printedCommands({data: body.data});+ for (const command of commands) {+ await runPrinted(filled(command, lib, looks, body));+ check();+ }+ }++ /** @type {Record<string, {declaresDefault: boolean, setup: (lib: Library, looks: {drawn: string, other: string}) => Promise<void>}>} */+ const STATES = {+ 'no set': {declaresDefault: false, setup: async () => {}},+ 'wrapped with no variants': {+ declaresDefault: false,+ setup: async lib => {+ await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'brand',+ '--from',+ lib.module,+ ]);+ },+ },+ 'with variants, default declared': {+ declaresDefault: true,+ setup: async (lib, looks) => {+ await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'brand',+ '--from',+ lib.module,+ '--variants',+ `${looks.drawn},${looks.other}`,+ '--default-variant',+ looks.drawn,+ ]);+ },+ },+ 'with variants, default undeclared': {+ declaresDefault: false,+ setup: async (lib, looks) => {+ await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'brand',+ '--from',+ lib.module,+ ]);+ const file = path.join(pkg, 'icon-sets', 'brand', 'brand.icons.json');+ const data = JSON.parse(fs.readFileSync(file, 'utf-8'));+ fs.writeFileSync(+ file,+ `${JSON.stringify({...data, variants: [looks.drawn, looks.other].sort()}, null, 2)}\n`,+ );+ },+ },+ };++ const CHOICES = {+ drawn: 'named default is the drawn look',+ other: 'named default is another existing look',+ unknown: 'named default is an unknown word',+ none: 'no default named',+ drop: 'no default named, --variants leave out the drawn look',+ };++ /**+ * @typedef {{write: string | null, authored?: boolean} | {refuse: 'looks' | 'refresh' | 'drawn' | 'declare' | 'keep' | 'name' | 'own' | 'drop'}} Expected+ * What a path must do: write the set with this default, or refuse naming+ * the look words (`looks`), the refresh (`refresh`), the look already+ * drawn (`drawn`), the declaration to run first (`declare`), the variant+ * to add in place of a moved default (`keep`), the default to name+ * (`name`), the icon's own export (`own`), or the `--variants` that keep+ * the drawn look as the default (`drop`).+ */++ /**+ * The command for a path, and what it must do.+ * @param {string} libName+ * @param {string} route+ * @param {{declaresDefault: boolean}} state+ * @param {{drawn: string, other: string}} looks+ * @param {keyof typeof CHOICES} choice+ * @param {string[]} named `--set brand` when the package has two sets+ * @returns {{args: string[], expect: Expected}}+ */+ function plan(libName, route, state, looks, choice, named) {+ const lib = LIBRARIES[libName];+ const encoded = libName === 'looks in names';+ const word = {drawn: looks.drawn, other: looks.other, unknown: 'solid'}[+ /** @type {'drawn'} */ (choice)+ ];+ const declare = {+ drawn: [+ '--variants',+ `${looks.drawn},${looks.other}`,+ '--default-variant',+ looks.drawn,+ ],+ other: ['--variants', looks.other, '--default-variant', looks.other],+ unknown: [+ '--variants',+ `solid,${looks.drawn}`,+ '--default-variant',+ 'solid',+ ],+ none: ['--variants', `${looks.other},${looks.drawn}`],+ drop: ['--variants', looks.other],+ }[choice];+ const newSet = ['experimental', 'icon', 'new-set', 'brand'];+ if (route !== 'add --variant' && route !== 'add --variant --all') {+ const args = [+ ...newSet,+ ...(route === 'in place' ? [] : ['--from', lib.module]),+ ...declare,+ ];+ if (encoded) {+ return {+ args,+ expect:+ choice === 'drop'+ ? {refuse: 'drop'}+ : choice === 'unknown'+ ? {refuse: 'looks'}+ : choice === 'other'+ ? route === 'in place'+ ? {refuse: 'refresh'}+ : {write: looks.other}+ : {write: looks.drawn},+ };+ }+ // The command can't read the look a module draws: a set that+ // declares its default keeps it, and one that declares none takes+ // the default the command names.+ if (route === 'create --from') {+ return {+ args,+ expect:+ choice === 'drawn'+ ? {write: looks.drawn}+ : {write: looks.other, authored: true},+ };+ }+ return {+ args,+ expect:+ choice === 'drawn'+ ? {write: looks.drawn}+ : choice === 'other'+ ? state.declaresDefault+ ? {refuse: 'keep'}+ : {write: looks.other, authored: true}+ : state.declaresDefault+ ? choice === 'drop'+ ? {refuse: 'drop'}+ : {write: looks.drawn}+ : {refuse: 'name'},+ };+ }+ const look = choice === 'unknown' ? looks.drawn : word;+ const module = lib.moduleOf(look);+ const args =+ route === 'add --variant'+ ? [+ 'experimental',+ 'icon',+ 'add',+ lib.exportOf('Star', look),+ '--from',+ module,+ '--id',+ 'star',+ '--variant',+ word,+ ...named,+ ]+ : [+ 'experimental',+ 'icon',+ 'add',+ '--variant',+ word,+ '--from',+ module,+ '--all',+ ...named,+ ];+ const declared = dataOf('brand').variants ?? [];+ const kept = dataOf('brand').default?.variant ?? null;+ if (choice === 'unknown') return {args, expect: {refuse: 'looks'}};+ if (choice === 'drawn') {+ return {+ args,+ expect:+ encoded || state.declaresDefault+ ? {refuse: 'drawn'}+ : declared.includes(word)+ ? {refuse: 'own'}+ : {refuse: 'declare'},+ };+ }+ return {+ args,+ expect: declared.includes(word) ? {write: kept} : {refuse: 'declare'},+ };+ }++ const ROUTES = [+ 'in place',+ 'refresh',+ 'add --variant',+ 'add --variant --all',+ ];+ // A second set wraps the same library, so a printed command that names+ // no set fails as printed.+ const SETS = ['one set', 'two sets'];+ const CASES = Object.keys(LIBRARIES)+ .flatMap(libName => {+ // A library whose names name no looks has no look words, so no word+ // is unknown to it.+ const choices = Object.keys(CHOICES).filter(+ choice => libName === 'looks in names' || choice !== 'unknown',+ );+ return [+ ...choices.map(choice => ({+ libName,+ route: 'create --from',+ state: 'no set',+ choice,+ })),+ ...ROUTES.flatMap(route =>+ Object.keys(STATES)+ .filter(state => state !== 'no set')+ .flatMap(state =>+ choices+ .filter(+ choice =>+ !route.startsWith('add') ||+ (choice !== 'none' && choice !== 'drop'),+ )+ .map(choice => ({libName, route, state, choice})),+ ),+ ),+ ];+ })+ .flatMap(each => SETS.map(sets => ({...each, sets})))+ .map(each => ({+ ...each,+ title: `${each.libName} · ${each.sets} · ${each.route} · ${each.state} · ${+ each.route.startsWith('add')+ ? CHOICES[/** @type {keyof typeof CHOICES} */ (each.choice)].replace(+ 'named default',+ 'variant',+ )+ : CHOICES[/** @type {keyof typeof CHOICES} */ (each.choice)]+ }`,+ }));++ it('covers every library, path, set and choice', () => {+ expect(+ CASES.filter(each => each.libName === 'looks in names'),+ ).toHaveLength(2 * 53);+ expect(+ CASES.filter(each => each.libName === 'no looks in names'),+ ).toHaveLength(2 * 40);+ });++ for (const {title, libName, sets, route, state: stateName, choice} of CASES)+ it(title, async () => {+ const lib = LIBRARIES[libName];+ lib.write();+ const two = sets === 'two sets';+ if (two) {+ const spare = await json([+ 'experimental',+ 'icon',+ 'new-set',+ 'spare',+ '--from',+ lib.module,+ ]);+ expect(spare.code, JSON.stringify(spare.body)).toBe(0);+ }+ /** @returns {Record<string, string>} */+ const spareFiles = () =>+ Object.fromEntries(+ Object.entries(snapshot()).filter(([file]) =>+ file.startsWith(path.join('icon-sets', 'spare')),+ ),+ );+ const state = STATES[stateName];+ const looks = state.declaresDefault ? lib.declared : lib.usual;+ await state.setup(lib, looks);+ const spareBefore = spareFiles();+ const step = plan(+ libName,+ route,+ state,+ looks,+ /** @type {keyof typeof CHOICES} */ (choice),+ two ? ['--set', 'brand'] : [],+ );+ const before = snapshot();+ const res = await json(step.args);+ expectEveryCommandNamesTheSet(res.body);+ await checkRefusalOrWrite({lib, route, choice, step, looks, res, before});+ expect(spareFiles(), 'every printed command acts on its own set').toEqual(+ spareBefore,+ );+ });++ /**+ * The code each new-set refusal raises, and the words its reference doc+ * lists that refusal by under that code.+ */+ const NEW_SET_REFUSALS = /** @type {const} */ ({+ looks: [+ 'ERR_INVALID_ARGUMENT',+ 'no look word of a library whose export names encode looks',+ ],+ refresh: ['ERR_INVALID_ARGUMENT', 'without `from`'],+ keep: [+ 'ERR_INVALID_ARGUMENT',+ 'when the export names of its icons name no looks',+ ],+ drop: ['ERR_INVALID_OPTION', '`variants` leave out the default variant'],+ name: ['ERR_INVALID_OPTION', 'declares no default'],+ });++ /**+ * Check that a path wrote the set it must, or refused as it must, and run+ * the commands it printed.+ * @param {object} args+ * @param {Library} args.lib+ * @param {string} args.route+ * @param {string} args.choice+ * @param {{args: string[], expect: Expected}} args.step+ * @param {{drawn: string, other: string}} args.looks+ * @param {{code: number, body: any}} args.res+ * @param {Record<string, string>} args.before+ */+ async function checkRefusalOrWrite({+ lib,+ route,+ choice,+ step,+ looks,+ res,+ before,+ }) {+ if ('write' in step.expect) {+ const expected = step.expect.write;+ const options = {authored: step.expect.authored};+ expect(res.code, JSON.stringify(res.body)).toBe(0);+ expectEveryIconDrawsDefault(lib, expected, options);+ await runPrintedNotes(res.body, lib, looks, () =>+ expectEveryIconDrawsDefault(lib, expected, options),+ );+ return;+ }+ expect(res.code, JSON.stringify(res.body)).not.toBe(0);+ expect(snapshot()).toEqual(before);+ if (!route.startsWith('add')) {+ const kind = /** @type {keyof typeof NEW_SET_REFUSALS} */ (+ step.expect.refuse+ );+ const [code, phrase] = NEW_SET_REFUSALS[kind];+ expect(res.body.code, JSON.stringify(res.body)).toBe(code);+ const listed = newSetDoc.throws?.find(each => each.code === code);+ expect(listed?.when).toContain(phrase);+ }+ /** @type {string[]} */+ const suggestions = (res.body.suggestions ?? []).map(+ (/** @type {any} */ each) => each.name,+ );+ switch (step.expect.refuse) {+ case 'looks':+ expect(res.body.error).toContain('filled or outline');+ break;+ case 'drawn':+ expect(res.body.error).toContain('already draws');+ break;+ case 'own': {+ if (route === 'add --variant') {+ expect(res.body.error).toContain('own export');+ break;+ }+ // Every icon's own export comes from this module: the variant is+ // the look they draw now, the default the set must declare.+ expect(res.body.error).toBe(+ `"${lib.moduleOf(looks.drawn)}" is the module the ${GLYPHS.length} icons of "brand" come from: its exports are those icons in the look they draw now, so "${looks.drawn}" is that look and can't be a variant of them. "brand" declares no default variant; declare "${looks.drawn}" as the default first.`,+ );+ expect(suggestions).toEqual([+ `astryx experimental icon new-set brand --variants ${looks.drawn},${looks.other} --default-variant ${looks.drawn}`,+ ]);+ await runPrinted(suggestions[0]);+ expectEveryIconDrawsDefault(lib, looks.drawn);+ const again = await json(step.args);+ expect(again.code, JSON.stringify(again.body)).not.toBe(0);+ expect(again.body.error).toContain('already draws');+ break;+ }+ case 'refresh': {+ const refresh = `astryx experimental icon new-set brand --from ${lib.module}`;+ expect(suggestions[0]).toMatch(new RegExp(`^${refresh} `, 'u'));+ await runPrinted(suggestions[0]);+ expectEveryIconDrawsDefault(lib, looks.other);+ break;+ }+ case 'keep': {+ // No run moves the default; each printed command runs, the+ // module placeholder filled with the module that draws the look.+ expect(res.body.error).toContain('export names name no looks');+ expect(suggestions.length).toBeGreaterThan(0);+ for (const command of suggestions) {+ expect(command).not.toMatch(/new-set brand --from /u);+ await runPrinted(+ command.replace('<module>', lib.moduleOf(looks.other)),+ );+ }+ expectEveryIconDrawsDefault(lib, looks.drawn);+ expect(+ dataOf('brand').icons.every((/** @type {any} */ icon) =>+ (icon.variants ?? []).some(+ (/** @type {any} */ each) => each.variant === looks.other,+ ),+ ),+ ).toBe(true);+ break;+ }+ case 'name': {+ if (choice === 'drop') {+ // The command names only the variants it was given: the+ // default it writes is the author's word.+ expect(suggestions).toEqual([+ `astryx experimental icon new-set brand${route === 'refresh' ? ` --from ${lib.module}` : ''} --variants ${looks.other} --default-variant ${looks.other}`,+ ]);+ await runPrinted(suggestions[0]);+ expectEveryIconDrawsDefault(lib, looks.other, {authored: true});+ break;+ }+ const named = suggestions.find(command =>+ command.endsWith(` --default-variant ${looks.drawn}`),+ );+ expect(named, suggestions.join('\n')).toBeDefined();+ await runPrinted(/** @type {string} */ (named));+ expectEveryIconDrawsDefault(lib, looks.drawn);+ break;+ }+ case 'declare': {+ expect(suggestions[0]).toMatch(+ /^astryx experimental icon new-set brand --variants /u,+ );+ // A placeholder is filled with the look the message names: the+ // look the icons draw now.+ await runPrinted(suggestions[0].replaceAll('<default>', looks.drawn));+ const kept = dataOf('brand').default?.variant ?? null;+ expect(kept).toBe(looks.drawn);+ const again = await json(step.args);+ if (choice === 'drawn') {+ expect(again.code, JSON.stringify(again.body)).not.toBe(0);+ expect(again.body.error).toContain('already draws');+ break;+ }+ expect(again.code, JSON.stringify(again.body)).toBe(0);+ expectEveryIconDrawsDefault(lib, kept);+ break;+ }+ case 'drop': {+ // The set keeps the look its icons draw: each printed command+ // runs, the module placeholder filled with the module that draws+ // the other look.+ expect(res.body.error).toContain(`"${looks.drawn}"`);+ expect(suggestions[0]).toMatch(+ new RegExp(+ `^astryx experimental icon new-set brand(?: --from \\S+)? --variants ${looks.drawn},${looks.other}$`,+ 'u',+ ),+ );+ for (const command of suggestions) {+ await runPrinted(+ command.replace('<module>', lib.moduleOf(looks.other)),+ );+ }+ expectEveryIconDrawsDefault(lib, looks.drawn);+ break;+ }+ }+ }+});diff --git a/packages/cli/foundation/discovery/doc-types.mjs b/packages/cli/foundation/discovery/doc-types.mjsindex e880520769..1b0d40f4c1 100644--- a/packages/cli/foundation/discovery/doc-types.mjs+++ b/packages/cli/foundation/discovery/doc-types.mjs@@ -27,7 +27,8 @@* none), and a `<topic>.doc.<lang>.mjs` overlay against* `ReferenceTranslationDoc`;* - themes root: `ThemeDoc`;- * - iconSets root: `IconSetDoc`.+ * - iconSets root: `IconSetDoc`, and a set's own definition (stamped+ * `type: 'icon-definition'`) `IconDefinitionDoc`.* Every finding is a warning, names the field, and says how to fix it.** @input Doc files with the root each was found in, the package root, and the@@ -312,7 +313,13 @@ function expectedType(ts, root, exportName, node, core = false) {return {typeExpr: authoring('ThemeDoc'), typeName: 'ThemeDoc'};}if (root === 'icon-sets') {- return {typeExpr: authoring('IconSetDoc'), typeName: 'IconSetDoc'};+ // A set's own definitions live in its folder too.+ return shape?.stamp === 'icon-definition'+ ? {+ typeExpr: authoring('IconDefinitionDoc'),+ typeName: 'IconDefinitionDoc',+ }+ : {typeExpr: authoring('IconSetDoc'), typeName: 'IconSetDoc'};}if (translation) {return {diff --git a/packages/cli/foundation/discovery/doc-types.test.mjs b/packages/cli/foundation/discovery/doc-types.test.mjsindex cef65c821d..ea3aa9f3b7 100644--- a/packages/cli/foundation/discovery/doc-types.test.mjs+++ b/packages/cli/foundation/discovery/doc-types.test.mjs@@ -12,6 +12,7 @@ import * as path from 'node:path';import {createRequire} from 'node:module';import {afterEach, beforeEach, describe, expect, it} from 'vitest';import {unusableTypeScriptReason} from './project-typescript.mjs';+import {iconDefinitionSource} from './icon-set-writer.mjs';import {checkDocTypes,DOC_TYPES_TYPESCRIPT_MISSING_REASON,@@ -716,6 +717,33 @@ describe('checkDocTypes', () => {);});+ it("checks a set's own definition, as new-definition writes it, against IconDefinitionDoc", async () => {+ withTypeScript();+ write(+ 'icon-sets/brand/definitions/aiHelper.doc.mjs',+ iconDefinitionSource({+ name: 'aiHelper',+ description: 'The AI helper.',+ words: ['assistant', 'ai'],+ }),+ );+ write(+ 'icon-sets/brand/definitions/broken.doc.mjs',+ "export default {type: 'icon-definition', name: 'broken', description: 'D', words: 'one'};\n",+ );+ const report = await check([+ ['icon-sets/brand/definitions/aiHelper.doc.mjs', 'icon-sets'],+ ['icon-sets/brand/definitions/broken.doc.mjs', 'icon-sets'],+ ]);+ expect(report.docs).toBe(2);+ expect(summary(report)).toEqual([+ 'icon-sets/brand/definitions/broken.doc.mjs default words wrong_type',+ ]);+ expect(new Set(report.findings.map(f => f.type))).toEqual(+ new Set(['IconDefinitionDoc']),+ );+ });+it('checks nothing with a TypeScript older than 4.9, even when every doc is TypeScript', async () => {const fake = path.join(pkg, 'node_modules', 'typescript');fs.mkdirSync(fake, {recursive: true});diff --git a/packages/cli/foundation/discovery/icon-ranking.mjs b/packages/cli/foundation/discovery/icon-ranking.mjsindex 3921157e89..467ddff040 100644--- a/packages/cli/foundation/discovery/icon-ranking.mjs+++ b/packages/cli/foundation/discovery/icon-ranking.mjs@@ -9,8 +9,18 @@* 90 an exact match in the reading the searched sets favor (below)* 80 an exact match in the other reading* 60 one of its words starts with the query- * 40 a partial match: the id or a word contains the query, or every- * word of the query starts one of the icon's words or id parts+ * 40 a partial match: the id or a word contains the query (three+ * letters or more), or every word of the query starts one of the+ * icon's words or id parts+ *+ * A word matches a whole word: a word's plural or singular (`stars` for+ * `star`) is an exact match, while a longer word that only starts with it+ * (`start`) is a word-start match, and {@link answeringMatches} keeps+ * word-start and partial matches only when nothing matches a whole word.+ * A query is scored as typed first. Only when nothing answers it with a+ * whole word are the words that only phrase it (`go`, `the`, `icon`) left+ * out of a query of several words, so `go home` asks for `home` while+ * `arrow up to line` still names `arrow-up-to-line`.** An exact match is a NAME match when the query is the icon's id, or one of* its words that is also a part of its id (`trash` for `trash-2`); it is a@@ -26,7 +36,8 @@** Equal scores keep the set order first (the project's set, then load* order), so the project's set always leads at a score. Within one set, a- * name match on the whole id comes before one on a part of it, and a meaning+ * name match on the whole id (or its plural or singular) comes before one on+ * a part of it, and a meaning* match whose query sits earlier among the icon's tags comes first (sets list* an icon's most telling tags first). Remaining ties keep id order, so the* same installation always answers the same way.@@ -93,7 +104,9 @@ const squash = value => value.toLowerCase().replace(/[\s_-]+/g, '');* @property {boolean} meaning the query is one of the icon's tags (never* both: a tag is a word that is not the id or one of its parts)* @property {number} rank within-tier key, lower first: for a name match 0- * (whole id) or 1 (an id part); for a meaning match the tag's position+ * (whole id), 1 (the whole id's plural or singular), 2 (an id part), or 3+ * (an id part's plural or singular); for a meaning match the tag's+ * position* @property {string} reason*/@@ -127,10 +140,27 @@ export function matchIcon(query, icon, definitions = []) {tier: 'exact',name: wholeId || partWord,meaning: !wholeId && !partWord,- rank: wholeId ? 0 : partWord ? 1 : tagAt,+ rank: wholeId ? 0 : partWord ? 2 : tagAt,reason: wholeId ? `id "${icon.id}"` : `word "${query}"`,};}+ const plural = icon.words.find(word => sameWord(word, query));+ if (plural) {+ const named = parts.has(plural);+ return {+ tier: 'exact',+ name: named,+ meaning: !named,+ // The whole id's plural or singular right after the whole id, then+ // after the word itself, wherever it sits.+ rank: named+ ? plural === icon.id+ ? 1+ : 3+ : tags.length + tags.indexOf(plural),+ reason: `word "${plural}"`,+ };+ }const prefix = icon.words.find(word => word.startsWith(query));if (prefix) {return {@@ -141,7 +171,11 @@ export function matchIcon(query, icon, definitions = []) {reason: `word "${prefix}" starts with "${query}"`,};}- const contains = [icon.id, ...icon.words].find(text => text.includes(query));+ // A letter or two inside a word (`x` in `box`) says nothing about it.+ const contains =+ query.replace(/\s+/gu, '').length >= 3+ ? [icon.id, ...icon.words].find(text => text.includes(query))+ : undefined;if (contains) {return {tier: 'partial',@@ -170,6 +204,72 @@ export function matchIcon(query, icon, definitions = []) {return null;}+/**+ * Whether two words are one word's singular and plural (`star`, `stars`;+ * `box`, `boxes`), never the same word.+ * @param {string} a+ * @param {string} b+ */+function sameWord(a, b) {+ if (a === b || /\s/u.test(a) || /\s/u.test(b)) return false;+ const [short, long] = a.length < b.length ? [a, b] : [b, a];+ return short.length >= 2 && (long === `${short}s` || long === `${short}es`);+}++/**+ * Words that phrase a query without naming anything: left out of a query of+ * several words that nothing answers as typed (`go home` asks for `home`).+ */+const FILLER_WORDS = new Set([+ 'a',+ 'an',+ 'the',+ 'go',+ 'to',+ 'my',+ 'of',+ 'for',+ 'icon',+ 'icons',+]);++/**+ * A query as typed: trimmed and lower-case, one space between words.+ * @param {string} query+ */+function typedQuery(query) {+ return query.trim().toLowerCase().split(/\s+/u).filter(Boolean).join(' ');+}++/**+ * The query without the words that only phrase it, when it has several+ * words and some word names something; else the query as typed.+ * @param {string} query+ */+export function iconQuery(query) {+ const words = typedQuery(query).split(' ').filter(Boolean);+ const named = words.filter(word => !FILLER_WORDS.has(word));+ return (words.length > 1 && named.length > 0 ? named : words).join(' ');+}++/**+ * The matches that answer a query: the whole-word ones (a definition or an+ * exact match, 80 and up) when there are any, else word starts (60) when+ * there are any, else partial matches. A longer word that only starts with+ * the query (`start` for `star`) never stands beside a whole-word answer.+ * @template {{score: number}} T+ * @param {T[]} ranked best first+ * @returns {T[]}+ */+export function answeringMatches(ranked) {+ for (const floor of [80, 60]) {+ if (ranked.some(each => each.score >= floor)) {+ return ranked.filter(each => each.score >= floor);+ }+ }+ return ranked;+}+/*** The score of one match, given which exact reading leads.* @param {IconMatch} match@@ -249,13 +349,30 @@ export function withDefinitionWords(icon, definitions, lookup) {}/**- * Every icon in `sets` that answers the query, ranked (FR6).+ * Every icon in `sets` that answers the query, ranked. The query is+ * scored as typed; when nothing answers it with a whole word (80 and up),+ * it is scored again without its filler words ({@link iconQuery}).* @param {DiscoveredIconSet[]} sets in tie order* @param {string} query* @returns {IconMatchEntry[]}*/export function rankIcons(sets, query) {- const term = query.trim().toLowerCase();+ const typed = typedQuery(query);+ const asTyped = rankTerm(sets, typed);+ if (asTyped.some(each => each.score >= 80)) return asTyped;+ const named = iconQuery(query);+ if (named === typed) return asTyped;+ const withoutFiller = rankTerm(sets, named);+ return withoutFiller.length > 0 ? withoutFiller : asTyped;+}++/**+ * {@link rankIcons} for one normalized query.+ * @param {DiscoveredIconSet[]} sets+ * @param {string} term+ * @returns {IconMatchEntry[]}+ */+function rankTerm(sets, term) {const astryx = astryxDefinitionsByName();/** @type {Array<{set: DiscoveredIconSet, icon: IconSetIcon, definitions: string[], match: IconMatch, setIndex: number}>} */const hits = [];diff --git a/packages/cli/foundation/discovery/icon-set-checks.mjs b/packages/cli/foundation/discovery/icon-set-checks.mjsindex f48428c7ef..a67def470a 100644--- a/packages/cli/foundation/discovery/icon-set-checks.mjs+++ b/packages/cli/foundation/discovery/icon-set-checks.mjs@@ -57,6 +57,7 @@ import {otherNamesOf,generatedTypesText,readGeneratedStatements,+ generatedTypesMatch,} from './icon-set-writer.mjs';import {exportValueKind,@@ -67,6 +68,7 @@ import {} from './module-exports.mjs';import {astryxIconDefinitions} from './icon-definition-discovery.mjs';import {rankIcons} from './icon-ranking.mjs';+import {shellArg} from '../text/shell-arg.mjs';import {issueError,issueWarning,@@ -276,16 +278,17 @@ function checkContract(set, packageName, pkg, unchecked) {const actual = fs.existsSync(typesFile)? fs.readFileSync(typesFile, 'utf-8'): null;- // 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');+ // The declarations must match, statement by statement, however a+ // formatter left the file; the header comment is the writer's and+ // changes between releases.if (expected != null &&- (actual == null || code(actual) !== code(expected))+ (actual == null ||+ !generatedTypesMatch(+ actual,+ expected,+ /** @type {string} */ (typesRel),+ ))) {issues.push(issueError(@@ -359,12 +362,12 @@ function checkDefinitions(set) {if (mapped.has(doc.name) || !doc.builtIn) continue;const suggestion = suggestIcon(set, doc);const hint = suggestion- ? ` Suggested: astryx experimental icon map ${doc.name} ${suggestion.icon}.`+ ? ` Suggested: astryx experimental icon map ${doc.name} ${suggestion.icon} --set ${set.name}.`: '';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: run \`astryx experimental icon map ${doc.name} <icon id>\` with the icon that draws it${findHint(set, doc)}.${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> --set ${set.name}\` with the icon that draws it${findHint(set, doc)}.${hint}`,),);}@@ -382,7 +385,7 @@ function checkDefinitions(set) {issues.push(issueWarning(ICON_DEFINITION_UNUSED,- `${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}.` : ''}`,+ `${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> --set ${set.name}\`, or remove definitions/${doc.name}.doc.mjs.${suggestion ? ` Suggested: astryx experimental icon map ${doc.name} ${suggestion.icon} --set ${set.name}.` : ''}`,),);}@@ -538,13 +541,7 @@ export function suggestedIcons(set, doc) {...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),- }));+ const icons = suggestionIndex(set.data.icons);/** 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;@@ -636,6 +633,29 @@ export function suggestedIcons(set, doc) {return found.slice(0, SUGGESTIONS_PER_DEFINITION);}+/**+ * Each icon as the suggestion rules read it: its id's words as written and+ * in singular form, and the library's other names for it (the same ones+ * `map` accepts). Built once per list of icons, so suggesting for every+ * definition of a large library reads each icon once.+ * @type {WeakMap<object, Array<{id: string, words: string[], raw: string[], other: string[]}>>}+ */+const suggestionIndexes = new WeakMap();++/** @param {Array<{id: string, words?: string[]}>} list */+function suggestionIndex(list) {+ const cached = suggestionIndexes.get(list);+ if (cached) return cached;+ const index = list.map(icon => ({+ id: icon.id,+ words: icon.id.split('-').map(stem),+ raw: icon.id.split('-'),+ other: otherNamesOf(icon),+ }));+ suggestionIndexes.set(list, index);+ return index;+}+/*** A word in its singular form, so a plural meets its singular and nothing* else: `languages` meets `language`, `arrows` meets `arrow`. Only a@@ -934,10 +954,10 @@ function findHint(set, doc) {each => each.score >= FIND_FLOOR,);if (found.length > 0) {- return ` (icons matching "${query}": \`astryx experimental icon ${query} --set ${set.name}\`)`;+ return ` (icons matching "${query}": \`astryx experimental icon ${shellArg(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>`)';+ 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 ${doc.name} --set ${set.name}\`)`;}/**diff --git a/packages/cli/foundation/discovery/icon-set-checks.test.mjs b/packages/cli/foundation/discovery/icon-set-checks.test.mjsindex 49df228d4f..167cd717a7 100644--- a/packages/cli/foundation/discovery/icon-set-checks.test.mjs+++ b/packages/cli/foundation/discovery/icon-set-checks.test.mjs@@ -655,16 +655,20 @@ describe('icon definitions (map)', () => {// 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>`',+ '`astryx experimental icon map error <icon id> --set glyphs`',);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(+ /icons matching "([^"]+)": `astryx experimental icon ('[^']+'|\S+) --set glyphs`/u.exec(issue.message,);if (query) {+ // A query of several words is one shell word, so it runs as printed.+ expect(query[2]).toBe(+ query[1].includes(' ') ? `'${query[1]}'` : query[1],+ );expect(rankIcons([readSet()], query[1]).length).toBeGreaterThan(0);} else {expect(issue.message).toContain(@@ -758,7 +762,7 @@ describe('icon definitions (map)', () => {);const rubbish = unused.find(issue => issue.message.includes('"rubbish"'));expect(rubbish?.message).toContain(- 'Suggested: astryx experimental icon map rubbish trash.',+ 'Suggested: astryx experimental icon map rubbish trash --set glyphs.',);const [coverage] = iconSetCoverage({name: '@acme/glyphs',diff --git a/packages/cli/foundation/discovery/icon-set-writer.mjs b/packages/cli/foundation/discovery/icon-set-writer.mjsindex a9fba62b70..28957097b9 100644--- a/packages/cli/foundation/discovery/icon-set-writer.mjs+++ b/packages/cli/foundation/discovery/icon-set-writer.mjs@@ -723,20 +723,405 @@ export function modulePrefix(file, options) {return libraryPrefix(prefixNames(iconCandidates(file, options)));}+/**+ * How a module names its icons: the library prefix every icon export shares+ * ({@link modulePrefix}) and the look words its names end in+ * ({@link lookPositions}), read from its icon exports once. A large module+ * reports its reading, as {@link libraryIcons} does.+ * @param {string} file+ * @param {{adapter?: boolean, module?: string, progress?: (line: string) => void}} [options]+ * `module`: the module as the author named it, for progress; `progress`:+ * hears the reading of a large module+ * @returns {{prefix: string[], positions: Array<Set<string>>}}+ */+export function moduleNaming(file, options = {}) {+ const label = options.module ?? path.basename(file);+ let count = 0;+ return readingLibrary(+ file,+ {label, progress: options.progress},+ () => {+ const candidates = iconCandidates(file, options);+ count = candidates.length;+ const prefix = libraryPrefix(prefixNames(candidates));+ const positions = lookPositions(+ candidates.map(each => iconNaming(each.name, prefix).id),+ );+ return {prefix, positions};+ },+ () => `Found ${count} icon exports in ${label}.`,+ );+}++/**+ * An export's id and set name ({@link iconNaming}) without the look words+ * its library's names end in ({@link lookPositions}):+ * `XOutline24WGHT500Icon` is `x`, `XIcon`.+ * @param {string} name+ * @param {{prefix: string[], positions: Array<Set<string>>}} naming+ * @returns {{id: string, name: string}}+ */+export function iconNamingWithoutLook(name, {prefix, positions}) {+ const named = iconNaming(name, prefix);+ const {base} = splitLook(named.id.split('-'), positions);+ if (base.length === named.id.split('-').length) return named;+ const pascal = base+ .map(word => word[0].toUpperCase() + word.slice(1))+ .join('');+ return {id: base.join('-'), name: iconExportName(pascal)};+}++/** A library with at least this many exports reports its reading. */+const PROGRESS_FROM = 1000;++/** Fewer icons than this never show a library's look positions. */+const LOOK_MIN_ICONS = 20;++/** More words than this in one trailing position are glyph names. */+const LOOK_MAX_VALUES = 12;++/** Words that name a look's style, never a glyph. */+const LOOK_STYLE_WORDS = new Set([+ 'default',+ 'regular',+ 'outline',+ 'outlined',+ 'line',+ 'linear',+ 'stroke',+ 'filled',+ 'fill',+ 'solid',+ 'bold',+ 'light',+ 'thin',+ 'duotone',+ 'twotone',+ 'mini',+ 'micro',+ 'sharp',+ 'round',+ 'rounded',+ 'bulk',+ 'broken',+]);++/** Words that name a glyph's direction (`ArrowUp`), never a look. */+const DIRECTION_WORDS = new Set([+ 'up',+ 'down',+ 'left',+ 'right',+ 'top',+ 'bottom',+ 'start',+ 'end',+ 'north',+ 'south',+ 'east',+ 'west',+]);++/**+ * Whether the words that fill a trailing position name a look: each is+ * numbered (`24`, `wght500`) or one is a style word, and none is a+ * direction word. `ArrowUp` and `ArrowDown` are two glyphs, not two looks.+ * @param {string[]} words+ */+function namesLook(words) {+ if (words.some(word => DIRECTION_WORDS.has(word))) return false;+ return (+ words.every(word => /^[a-z]*\d+$/u.test(word)) ||+ words.some(word => LOOK_STYLE_WORDS.has(word))+ );+}++/**+ * The trailing words a library encodes its looks with: a style, a size, a+ * weight (`XOutline24WGHT500Icon` is `x` in the `outline`, `24`, `wght500`+ * look). A trailing position is a look position when, across at least+ * {@link LOOK_MIN_ICONS} icons, at most {@link LOOK_MAX_VALUES} words fill+ * it, each on at least 5% of the icons and together on at least 90%, and+ * those words name a look ({@link namesLook}); the positions are read from+ * the end while they hold. Glyph names never meet that bar (`trash-2` and+ * `clock-10` are a few icons each, and `up` and `down` are directions), so+ * a library that encodes no looks has none. Reads each id once per+ * position and keeps only counts.+ * @param {string[]} ids every icon's id+ * @returns {Array<Set<string>>} the look positions, the last word first+ */+export function lookPositions(ids) {+ if (ids.length < LOOK_MIN_ICONS) return [];+ /** @type {Array<Set<string>>} */+ const positions = [];+ const least = Math.max(2, Math.ceil(ids.length * 0.05));+ while (positions.length < 4) {+ /** @type {Map<string, number>} */+ const counts = new Map();+ for (const id of ids) {+ const words = id.split('-');+ const {base} = splitLook(words, positions);+ if (base.length < 2 || base.length < words.length - positions.length) {+ continue;+ }+ const last = /** @type {string} */ (base.at(-1));+ counts.set(last, (counts.get(last) ?? 0) + 1);+ }+ const values = [...counts].filter(([, count]) => count >= least);+ if (values.length === 0 || values.length > LOOK_MAX_VALUES) break;+ const covered = values.reduce((sum, [, count]) => sum + count, 0);+ if (covered < ids.length * 0.9) break;+ if (!namesLook(values.map(([value]) => value))) break;+ positions.push(new Set(values.map(([value]) => value)));+ }+ return positions;+}++/**+ * An id's glyph words and its look words, by {@link lookPositions}:+ * `x-outline-24-wght500` is `x` with `[wght500, 24, outline]`, null where+ * the id has no look word.+ * @param {string[]} words+ * @param {Array<Set<string>>} positions+ * @returns {{base: string[], look: Array<string | null>}}+ */+export function splitLook(words, positions) {+ let end = words.length;+ /** @type {Array<string | null>} */+ const look = positions.map(() => null);+ for (const [index, position] of positions.entries()) {+ const last = words[end - 1];+ if (end < 2 || last == null || !position.has(last)) break;+ look[index] = last;+ end--;+ }+ return {base: end === words.length ? words : words.slice(0, end), look};+}++/** Style words a library's default look is usually named by. */+const DEFAULT_STYLE_WORDS = ['default', 'regular', 'outline', 'outlined'];++/**+ * The word each look position prefers: a word of `prefer` it has (the set's+ * default variant), else a usual default style word, else the middle of a+ * series of numbered words (`wght300` … `wght700` gives `wght500`), else+ * its first word in order.+ * @param {Array<Set<string>>} positions+ * @param {string[]} [prefer]+ * @returns {string[]}+ */+export function preferredLook(positions, prefer = []) {+ const wanted = prefer.map(word => word.toLowerCase());+ return positions.map(position => {+ const values = [...position].sort();+ const chosen =+ wanted.find(word => position.has(word)) ??+ DEFAULT_STYLE_WORDS.find(word => position.has(word));+ if (chosen) return chosen;+ const numbered = values.map(value => /^([a-z]*)(\d+)$/u.exec(value));+ const lead = numbered[0]?.[1];+ if (+ values.length > 1 &&+ numbered.every(match => match != null && match[1] === lead)+ ) {+ const series = values+ .map((value, index) => ({+ value,+ n: Number(/** @type {RegExpExecArray} */ (numbered[index])[2]),+ }))+ .sort((a, b) => a.n - b.n);+ return series[Math.floor((series.length - 1) / 2)].value;+ }+ return values[0];+ });+}++/**+ * One icon a library gives.+ * @typedef {object} LibraryIcon+ * @property {string} export the library export it reads+ * @property {string} id+ * @property {string} name the name the set exports it as+ * @property {boolean} adapt+ * @property {string[]} aliases the ids of the other names the library+ * exports the icon as, leaving out the library's own name (`lucide-trash`)+ * @property {Array<string | null>} [look] in a library that encodes looks:+ * this export's look words by position, the last word first+ * @property {string[]} [looks] in a library that encodes looks: every+ * export that draws the glyph, this one included+ */++/**+ * The words a library's looks are named by, and the look a set takes from+ * it: what {@link libraryIcons} found, for the receipt.+ * @typedef {object} LibraryLookSummary+ * @property {string[][]} positions each position's words, sorted, the last+ * word of a name first+ * @property {string[]} preferred the word taken in each position+ * @property {number} exports how many exports draw the icons+ */+/*** Every icon a whole library exports, for wrapping it at once: one entry per* component (and, with an adapter, per data export), read by its `…Icon`* export when it has one (an alias of the same value is recorded once), with* its id and the name the set exports it as from the name, the library* prefix left out ({@link libraryPrefix}).+ *+ * A library that encodes looks in its export names ({@link lookPositions})+ * gives one icon per glyph: the look {@link preferredLook} prefers, its id+ * and name without the look words (`XOutline24WGHT500Icon` is `x`,+ * `XIcon`), and its `looks`, every export that draws the glyph.* @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, aliases: string[]}>}- * `aliases`: the ids of the other names the library exports the icon as,- * leaving out the library's own name (`lucide-trash`)+ * @param {{adapter?: boolean, exclude?: string[], prefer?: string[] | ((positions: Array<Set<string>>) => string[]), module?: string, progress?: (line: string) => void, summary?: (summary: LibraryLookSummary) => void}} [options]+ * `adapter`: whether the set declares one; `exclude`: export names that+ * are not icons; `prefer`: look words to prefer (the set's default+ * variant), or a function that gives them from the library's look+ * positions before any glyph is picked; `module`: the module as the author named it, for progress;+ * `progress`: hears the reading of a large module;+ * `summary`: hears the looks found, when the library has any+ * @returns {LibraryIcon[]}*/export function libraryIcons(file, options = {}) {+ const label = options.module ?? path.basename(file);+ /** @type {LibraryIcon[]} */+ let all = [];+ return readingLibrary(+ file,+ {label, progress: options.progress},+ () => {+ all = collectLibraryIcons(file, options);+ const prefer =+ typeof options.prefer === 'function'+ ? options.prefer(lookPositions(all.map(icon => icon.id)))+ : options.prefer;+ const grouped = libraryLooks(all, prefer);+ if (grouped.positions.length > 0) {+ options.summary?.({+ positions: grouped.positions.map(position => [...position].sort()),+ preferred: grouped.preferred,+ exports: all.length,+ });+ }+ return grouped.icons;+ },+ icons =>+ icons.length === all.length+ ? `Found ${icons.length} icons in ${label}.`+ : `Found ${icons.length} icons in ${label}, drawn by ${all.length} exports in their looks.`,+ );+}++/**+ * Read a library with its progress reported: when `progress` is given and+ * the module has {@link PROGRESS_FROM} exports or more, a line before `read`+ * runs and the line `found` gives after.+ * @template T+ * @param {string} file+ * @param {{label: string, progress?: (line: string) => void}} reading+ * `label`: the module as the author named it+ * @param {() => T} read+ * @param {(result: T) => string} found+ * @returns {T}+ */+function readingLibrary(file, {label, progress}, read, found) {+ const exportCount = progress ? followedExportNames(file).length : 0;+ if (progress == null || exportCount < PROGRESS_FROM) return read();+ progress(`Reading ${exportCount} exports of ${label}...`);+ const result = read();+ progress(found(result));+ return result;+}++/**+ * The library's icons grouped by glyph when its export names encode looks+ * ({@link libraryIcons}), with the look positions and the words preferred.+ * Without look positions the icons are returned as they are.+ * @param {LibraryIcon[]} all every icon, one per export+ * @param {string[]} [prefer]+ * @returns {{icons: LibraryIcon[], positions: Array<Set<string>>, preferred: string[]}}+ */+export function libraryLooks(all, prefer = []) {+ const positions = lookPositions(all.map(icon => icon.id));+ if (positions.length === 0) return {icons: all, positions, preferred: []};+ const preferred = preferredLook(positions, prefer);+ // How far a look is from the preferred one, as a sortable key: the+ // position first in the name (the style) counts most.+ const distance = (/** @type {Array<string | null>} */ look) => {+ let key = '';+ for (let index = look.length - 1; index >= 0; index--) {+ key += look[index] === preferred[index] ? '0' : '1';+ }+ return key;+ };+ /** @type {Map<string, {best: LibraryIcon, look: Array<string | null>, key: string, looks: string[]}>} */+ const byGlyph = new Map();+ for (const icon of all) {+ const {base, look} = splitLook(icon.id.split('-'), positions);+ const id = base.join('-');+ const key = distance(look);+ const group = byGlyph.get(id);+ if (!group) {+ byGlyph.set(id, {best: icon, look, key, looks: [icon.export]});+ continue;+ }+ group.looks.push(icon.export);+ if (+ key < group.key ||+ (key === group.key && icon.export < group.best.export)+ ) {+ group.best = icon;+ group.look = look;+ group.key = key;+ }+ }+ /** @type {LibraryIcon[]} */+ const icons = [];+ for (const [id, {best, look, looks}] of byGlyph) {+ const pascal = id+ .split('-')+ .map(word => word[0].toUpperCase() + word.slice(1))+ .join('');+ icons.push({+ ...best,+ id,+ name: iconExportName(pascal),+ aliases: best.aliases.filter(alias => !byGlyph.has(alias)),+ look,+ looks: looks.sort(),+ });+ }+ icons.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));+ return {icons, positions, preferred};+}++/**+ * Every icon a library exports, one per export: {@link libraryIcons} before+ * looks are grouped. A large module reports its reading, as+ * {@link libraryIcons} does.+ * @param {string} file+ * @param {{adapter?: boolean, exclude?: string[], module?: string, progress?: (line: string) => void}} [options]+ * `module`: the module as the author named it, for progress; `progress`:+ * hears the reading of a large module+ * @returns {LibraryIcon[]}+ */+export function everyLibraryIcon(file, options = {}) {+ const label = options.module ?? path.basename(file);+ return readingLibrary(+ file,+ {label, progress: options.progress},+ () => collectLibraryIcons(file, options),+ icons => `Found ${icons.length} exports in ${label}.`,+ );+}++/**+ * {@link everyLibraryIcon} without progress.+ * @param {string} file+ * @param {{adapter?: boolean, exclude?: string[]}} [options]+ * @returns {LibraryIcon[]}+ */+function collectLibraryIcons(file, options = {}) {const candidates = iconCandidates(file, options);/** @type {Map<string, {names: string[], adapt: boolean, scalar: string | null}>} */const byOrigin = new Map();@@ -830,16 +1215,29 @@ export function iconDefinitionSource(doc) {}/**- * Check a new icon definition for a set: a camelCase name no Astryx- * definition has, a description, and at least one lower-case word.+ * A new definition's name as written in a command: camelCase as given, or+ * kebab-case as the docs list definitions (`ai-helper` is `aiHelper`).+ * @param {string} name+ */+export function definitionNameFromInput(name) {+ return /^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$/u.test(name)+ ? name.replace(/-([a-z0-9])/gu, (_, c) => c.toUpperCase())+ : name;+}++/**+ * Check a new icon definition for a set: a camelCase name (or its kebab-case+ * form, {@link definitionNameFromInput}) no Astryx definition has, a+ * description, and at least one lower-case word.* @param {DiscoveredIconSet} set- * @param {{name: string, description?: string, words?: string[]}} doc+ * @param {{name: string, description?: string, words?: string[]}} given* @returns {{name: string, description: string, words: string[]}}*/-export function checkNewDefinition(set, doc) {+export function checkNewDefinition(set, given) {+ const doc = {...given, name: definitionNameFromInput(given.name)};if (!/^[a-z][a-zA-Z0-9]*$/u.test(doc.name)) {throw new IconSetAuthoringError(- `Invalid icon definition name "${doc.name}": use camelCase starting with a lower-case letter.`,+ `Invalid icon definition name "${doc.name}": use camelCase (aiHelper) or kebab-case (ai-helper), starting with a lower-case letter.`,'ERR_INVALID_ARGUMENT',);}@@ -919,8 +1317,11 @@ const GENERATED_HEADER = [/*** The top-level statements of a generated module, one normalized line each,- * however the file was formatted: whitespace collapsed, no padding inside- * braces, no trailing comma. Comments are dropped.+ * however a formatter left the file (Prettier's line breaks, double quotes,+ * trailing commas, semicolons or none): whitespace collapsed, no padding+ * inside braces or parentheses, no trailing comma, type members separated by+ * `; ` with none before the closing brace, no statement semicolon, and+ * single-quoted strings. Comments are dropped.* @param {string} text* @param {string} label the module's path, for the error* @returns {string[]}@@ -935,17 +1336,110 @@ function generatedStatements(text, label) {'ERR_INVALID_ARGUMENT',);}- return ast.program.body.map(node =>- text- .slice(- /** @type {number} */ (node.start),- /** @type {number} */ (node.end),- )- .replace(/\s+/gu, ' ')- .replace(/\{ /gu, '{')- .replace(/,? \}/gu, '}')- .replace(/,\}/gu, '}'),- );+ return ast.program.body.map(node => {+ const start = /** @type {number} */ (node.start);+ // A formatter without semicolons ends each type member with a line+ // break, which collapses to a space: give each member its separator.+ const separators = typeMemberEnds(node)+ .filter(end => !/^\s*[;,]/u.test(text.slice(end, end + 1)))+ .filter(end => !/[;,]$/u.test(text.slice(end - 1, end)))+ .sort((a, b) => b - a);+ let statement = text.slice(start, /** @type {number} */ (node.end));+ for (const end of separators) {+ const at = end - start;+ statement = `${statement.slice(0, at)};${statement.slice(at)}`;+ }+ return normalizedStatement(statement);+ });+}++/**+ * One statement's text in the normalized form {@link generatedStatements}+ * gives.+ * @param {string} statement+ */+function normalizedStatement(statement) {+ return statement+ .replace(/\s+/gu, ' ')+ .replace(/"((?:[^"'\\]|\\.)*)"/gu, "'$1'")+ .replace(/([{(]) /gu, '$1')+ .replace(/[,;]? ?([})])/gu, '$1')+ .trim()+ .replace(/ ?;$/u, '');+}++/**+ * Where each type member of a statement ends (the members of every type+ * literal and interface in it).+ * @param {any} node+ * @returns {number[]}+ */+function typeMemberEnds(node) {+ /** @type {number[]} */+ const ends = [];+ /** @param {any} each */+ const visit = each => {+ if (each == null || typeof each !== 'object') return;+ if (Array.isArray(each)) {+ for (const item of each) visit(item);+ return;+ }+ if (typeof each.type !== 'string') return;+ const members =+ each.type === 'TSTypeLiteral'+ ? each.members+ : each.type === 'TSInterfaceBody'+ ? each.body+ : null;+ if (members) {+ for (const member of members) ends.push(member.end);+ }+ for (const key of Object.keys(each)) {+ if (+ key === 'loc' ||+ key === 'leadingComments' ||+ key === 'trailingComments' ||+ key === 'innerComments'+ ) {+ continue;+ }+ visit(each[key]);+ }+ };+ visit(node);+ return ends;+}++/**+ * A normalized statement as the generated module writes it: with its+ * semicolon, except after a declaration that ends in its own block.+ * @param {string} statement+ */+function terminated(statement) {+ return /^(?:export (?:default )?)?(?:declare )?(?:abstract )?(?:async )?(?:function\b|class\b|interface\b|enum\b|namespace\b|module\b)/u.test(+ statement,+ )+ ? statement+ : `${statement};`;+}++/**+ * Whether a generated declaration file declares what its generated module+ * gives, statement by statement however a formatter left either file+ * ({@link generatedStatements}); the header comment is ignored.+ * @param {string} actual the declaration file as it is+ * @param {string} expected {@link generatedTypesText} for the module+ * @param {string} label the declaration file's path, for a parse error+ */+export function generatedTypesMatch(actual, expected, label) {+ let have;+ try {+ have = generatedStatements(actual, label);+ } catch {+ return false;+ }+ const want = generatedStatements(expected, label);+ return have.length === want.length && have.every((s, i) => s === want[i]);}/** The local name the generated module gives the set's adapter. */@@ -955,7 +1449,7 @@ const ADAPTER_LOCAL = 'adaptIcon';export const THEME_MAP_NAME = 'themeIcons';/** How the generated module imports React for its theme map. */-const REACT_IMPORT = "import {createElement} from 'react';";+const REACT_IMPORT = "import {createElement} from 'react'";/** The built-in icon definitions: the shared names a theme map covers. */const BUILT_IN = new Set(ICON_NAMES);@@ -987,10 +1481,15 @@ export function generatedModulePath(set, packageDir) {* component*/-/** The props every theme-map element gets: sized to its box, hidden from assistive tech. */+/**+ * The props every theme-map element gets: hidden from assistive tech, and+ * sized to its box by CSS as well as by attributes. A theme's icon sits in a+ * box whose font size is the icon size; CSS width and height override the+ * svg's own size attributes, so a component that writes its own (`size`+ * 24, ignoring `width` and `height`) still draws at the box's size.+ */const THEME_ELEMENT_PROPS =- "{'aria-hidden': true, 'width': '1em', 'height': '1em'}";-+ "{'aria-hidden': true, 'width': '1em', 'height': '1em', 'style': {'width': '1em', 'height': '1em'}}";/*** The declaration file's text for a generated module's statements: each@@ -1003,10 +1502,11 @@ export function generatedTypesText(statements) {/** @type {string[]} */const lines = [];const react = new Set();- for (const statement of statements) {+ for (const given of statements) {+ const statement = normalizedStatement(given);if (statement.startsWith('import ')) continue;if (/^export (?:\*|\{[^}]*\}) from /u.test(statement)) {- lines.push(statement);+ lines.push(terminated(statement));continue;}const adapted = new RegExp(@@ -1020,7 +1520,7 @@ export function generatedTypesText(statements) {);continue;}- const theme = /^export const (\w+) = \{(.*)\};$/u.exec(statement);+ const theme = /^export const (\w+) = \{(.*)\}$/u.exec(statement);if (theme &&(theme[1] === THEME_MAP_NAME || statement.includes('createElement('))@@ -1091,46 +1591,47 @@ export function generatedModuleText(};const themeName = data.themeMap === THEME_MAP_NAME ? THEME_MAP_NAME : null;const lines = before == null ? [] : generatedStatements(before, generated);+ const lineSet = new Set(lines);// Written once, below: the adapter's import, React's createElement, and- // the theme map.- const adapterImport = new RegExp(`\\bas ${ADAPTER_LOCAL}\\b`, 'u');- const dropped = [...new Set(remove)].map(- name =>- new RegExp(- `(?:\\bas ${name}(?:Source)?\\}|^export const ${name} = |^export \\{${name}\\} |^import ${name}Source )`,- 'u',- ),- );+ // the theme map. Every lookup below is by name, so a library of twenty+ // thousand icons is written in one pass.+ const removed = new Set(remove);// A re-export binds no local name, so the theme map reads each re-exported// icon through an import that mirrors its re-export. Those imports are// rewritten with the theme map.const themeImport = (/** @type {string} */ line) =>themeName != null &&line.startsWith('import {') &&- lines.includes(`export${line.slice('import'.length)}`);- const managed = (/** @type {string} */ line) =>- dropped.some(pattern => pattern.test(line)) ||- adapterImport.test(line) ||- line === REACT_IMPORT ||- themeImport(line) ||- (themeName != null && line.startsWith(`export const ${themeName} = `));+ lineSet.has(`export${line.slice('import'.length)}`);+ const managed = (/** @type {string} */ line) => {+ const name = statementName(line);+ if (name != null) {+ if (removed.has(name)) return true;+ if (name.endsWith('Source') && removed.has(name.slice(0, -6))) {+ return true;+ }+ if (name === ADAPTER_LOCAL) return true;+ }+ return (+ line === REACT_IMPORT ||+ themeImport(line) ||+ (themeName != null && line.startsWith(`export const ${themeName} = `))+ );+ };const imports = new Set(lines.filter(line => line.startsWith('import ') && !managed(line)),);const exports = new Set(lines.filter(line => !line.startsWith('import ') && !managed(line)),);+ /** @type {Map<string, string>} each exported name → its statement */+ const exported = new Map();+ for (const line of exports) {+ const name = statementName(line);+ if (name != null && !exported.has(name)) exported.set(name, line);+ }/** @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(- `(?:\\bas\\s+${name}\\s*\\}|^export\\s+\\{\\s*${name}\\s*\\}|^export const\\s+${name}\\b)`,- 'u',- ).test(line),- );+ const existing = name => exported.get(name);for (const icon of icons) {const specifier = specifierOf(icon.from);/** @type {string[]} */@@ -1141,29 +1642,32 @@ export function generatedModuleText(const local = `${icon.name}Source`;wantImports.push(icon.source === 'default'- ? `import ${local} from '${specifier}';`- : `import {${icon.source === local ? local : `${icon.source} as ${local}`}} from '${specifier}';`,+ ? `import ${local} from '${specifier}'`+ : `import {${icon.source === local ? local : `${icon.source} as ${local}`}} from '${specifier}'`,);- want.push(`export const ${icon.name} = ${ADAPTER_LOCAL}(${local});`);+ want.push(`export const ${icon.name} = ${ADAPTER_LOCAL}(${local})`);} else {want.push(icon.source === icon.name- ? `export {${icon.name}} from '${specifier}';`- : `export {${icon.source} as ${icon.name}} from '${specifier}';`,+ ? `export {${icon.name}} from '${specifier}'`+ : `export {${icon.source} as ${icon.name}} from '${specifier}'`,);}const prior = existing(icon.name);if (prior) {if (prior !== want[0]) {throw new IconSetAuthoringError(- `The generated icons module already exports ${icon.name} as \`${prior}\`. Pass another name, or edit ${generated}.`,+ `The generated icons module already exports ${icon.name} as \`${terminated(prior)}\`. Pass another name, or edit ${generated}.`,'ERR_FILE_EXISTS',);}continue;}for (const line of wantImports) imports.add(line);- for (const line of want) exports.add(line);+ for (const line of want) {+ exports.add(line);+ exported.set(icon.name, line);+ }}const needsAdapter = [...exports].some(line =>line.includes(`= ${ADAPTER_LOCAL}(`),@@ -1186,12 +1690,9 @@ export function generatedModuleText(theme.push(` ${name}: createElement(${exportName}, ${THEME_ELEMENT_PROPS}),`,);- const reexport = [...exports].find(line =>- new RegExp(- `^export \\{(?:\\w+ as )?${exportName}\\} from `,- 'u',- ).test(line),- );+ const line = exported.get(exportName);+ const reexport =+ line != null && line.startsWith('export {') ? line : undefined;if (reexport) {themeImports.add(`import${reexport.slice('export'.length)}`);}@@ -1201,15 +1702,17 @@ export function generatedModuleText(const adapterLine =needsAdapter && data.adapter? [- `import {${data.adapter.export} as ${ADAPTER_LOCAL}} from '${specifierOf(data.adapter.module)}';`,+ `import {${data.adapter.export} as ${ADAPTER_LOCAL}} from '${specifierOf(data.adapter.module)}'`,]: [];const js = [...GENERATED_HEADER,- ...(themeName ? [REACT_IMPORT] : []),- ...adapterLine,- ...[...imports, ...themeImports].sort(),- ...[...exports].sort(),+ ...[+ ...(themeName ? [REACT_IMPORT] : []),+ ...adapterLine,+ ...[...imports, ...themeImports].sort(),+ ...[...exports].sort(),+ ].map(terminated),...(themeName? theme.length > 0? [`export const ${themeName} = {`, ...theme, '};']@@ -1226,6 +1729,25 @@ export function generatedModuleText(};}+/**+ * The name one generated statement binds: the name an export exports+ * (`export {A as B} from …` is `B`, `export {A} from …` is `A`, `export+ * const A = …` is `A`), or the local name an import binds (`import {A as+ * BSource} from …` is `BSource`, `import BSource from …` is `BSource`).+ * Null for anything else.+ * @param {string} line+ * @returns {string | null}+ */+function statementName(line) {+ const named =+ /^(?:export|import) \{\s*([$\w]+)(?:\s+as\s+([$\w]+))?\s*\}/u.exec(line);+ if (named) return named[2] ?? named[1];+ const constant = /^export const ([$\w]+)\b/u.exec(line);+ if (constant) return constant[1];+ const plain = /^import ([$\w]+) from /u.exec(line);+ return plain ? plain[1] : null;+}+/*** Every name the generated module already exports one library export as: `export {featherSun as SunIcon} from '…'` or the import an adapted* icon reads (`import {featherSun as SunIconSource} from '…'`). Adding the@@ -1256,7 +1778,7 @@ export function generatedNamesOf(packageDir, generated, from, source) {.join('/');if (!specifier.startsWith('.')) specifier = `./${specifier}`;}- const tail = ` from '${specifier}';`;+ const tail = ` from '${specifier}'`;for (const statement of statements) {if (!statement.endsWith(tail)) continue;const head = statement.slice(0, -tail.length);@@ -1318,7 +1840,7 @@ export function generatedOrigins(packageDir, generated) {return `./${rel}`;};for (const statement of statements) {- const reexport = /^export \{(\w+)(?: as (\w+))?\} from '([^']+)';$/u.exec(+ const reexport = /^export \{(\w+)(?: as (\w+))?\} from '([^']+)'$/u.exec(statement,);if (reexport) {@@ -1328,7 +1850,7 @@ export function generatedOrigins(packageDir, generated) {});continue;}- const adapted = /^import \{(\w+) as (\w+)Source\} from '([^']+)';$/u.exec(+ const adapted = /^import \{(\w+) as (\w+)Source\} from '([^']+)'$/u.exec(statement,);if (adapted) {@@ -1338,7 +1860,7 @@ export function generatedOrigins(packageDir, generated) {});continue;}- const adaptedDefault = /^import (\w+)Source from '([^']+)';$/u.exec(+ const adaptedDefault = /^import (\w+)Source from '([^']+)'$/u.exec(statement,);if (adaptedDefault) {@@ -1562,12 +2084,30 @@ export function entryWiringNote(packageDir, pkg, generated, options = {}) {inside(typesFile) &&fs.existsSync(typesFile) &&!isBuiltOrCommonJs(packageDir, typesFile) &&- !fs.readFileSync(typesFile, 'utf-8').includes(lineFor(typesFile))+ !hasStatement(typesFile, lineFor(typesFile))? ` and \`${lineFor(typesFile)}\` to ${rel(typesFile)}`: '';return `Add \`${lineFor(entry)}\` to ${rel(entry)}${alsoTypes}, so the icons import from ${module}.`;}+/**+ * Whether a file has a statement, however a formatter left it+ * ({@link generatedStatements}); a file that does not parse is searched for+ * the text as written.+ * @param {string} file+ * @param {string} statement+ */+function hasStatement(file, statement) {+ const text = fs.readFileSync(file, 'utf-8');+ try {+ return generatedStatements(text, file).includes(+ normalizedStatement(statement),+ );+ } catch {+ return text.includes(statement);+ }+}+/*** Whether the set's own module exports `name`, read without running it, and* the line its entry needs when it does not ({@link entryWiringNote}).diff --git a/packages/cli/foundation/discovery/icon-set-writer.test.mjs b/packages/cli/foundation/discovery/icon-set-writer.test.mjsindex cf966fdb1c..0c2140de8a 100644--- a/packages/cli/foundation/discovery/icon-set-writer.test.mjs+++ b/packages/cli/foundation/discovery/icon-set-writer.test.mjs@@ -2,8 +2,15 @@/** @file Icon ids from export names (AST-084): a dimension stays one word. */+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';import {describe, expect, it} from 'vitest';-import {iconIdOf} from './icon-set-writer.mjs';+import {+ entryWiringNote,+ generatedModuleText,+ iconIdOf,+} from './icon-set-writer.mjs';describe('iconIdOf', () => {it.each([@@ -24,3 +31,74 @@ describe('iconIdOf', () => {expect(iconIdOf(name)).toBe(id);});});++describe('generatedModuleText over a large library', () => {+ it('writes twenty thousand icons in one pass, and rewrites them unchanged', () => {+ const icons = Array.from({length: 20000}, (_, index) => ({+ name: `Glyph${index}Icon`,+ from: '@acme/big-library',+ source: `Glyph${index}Outline24Icon`,+ adapt: false,+ }));+ const data = /** @type {any} */ ({+ schemaVersion: 1,+ module: '@acme/big-icons',+ icons: [],+ map: {},+ });+ const started = Date.now();+ const first = generatedModuleText(+ '/pkg',+ 'big.generated.js',+ null,+ data,+ icons,+ );+ const again = generatedModuleText(+ '/pkg',+ 'big.generated.js',+ first.js,+ data,+ icons,+ );+ // Quadratic matching took minutes here; a single pass takes well under+ // a second.+ expect(Date.now() - started).toBeLessThan(5000);+ expect(again.js).toBe(first.js);+ expect(first.js).toContain(+ "export {Glyph19999Outline24Icon as Glyph19999Icon} from '@acme/big-library';",+ );+ });+});++describe('entryWiringNote over a types file a formatter rewrote', () => {+ it.each([+ [+ 'double quotes, no semicolon',+ 'export * from "./icon-sets/brand/brand.generated.js"\n',+ ],+ [+ 'the line as written',+ "export * from './icon-sets/brand/brand.generated.js';\n",+ ],+ ])('names no line the types file already has (%s)', (_, types) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-wiring-'));+ try {+ const pkg = {+ name: '@acme/icons',+ type: 'module',+ exports: {'.': {types: './index.d.ts', default: './index.js'}},+ };+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkg));+ fs.writeFileSync(path.join(dir, 'index.js'), 'export {};\n');+ fs.writeFileSync(path.join(dir, 'index.d.ts'), types);+ expect(+ entryWiringNote(dir, pkg, './icon-sets/brand/brand.generated.js'),+ ).toBe(+ "Add `export * from './icon-sets/brand/brand.generated.js';` to index.js, so the icons import from @acme/icons.",+ );+ } finally {+ fs.rmSync(dir, {recursive: true, force: true});+ }+ });+});diff --git a/packages/cli/foundation/discovery/module-exports.mjs b/packages/cli/foundation/discovery/module-exports.mjsindex 4b3687bfd4..9e640129ef 100644--- a/packages/cli/foundation/discovery/module-exports.mjs+++ b/packages/cli/foundation/discovery/module-exports.mjs@@ -161,17 +161,48 @@ const nodesByTree = new WeakMap();* @returns {readonly any[]}*/function nodesOfType(node, type) {+ return cachedNodes(node, `all\0${type}`, () =>+ collectNodesOfType(node, type, []),+ );+}++/**+ * The module declarations of `type` at a program's top level, in source+ * order: a library file is read without a walk of every function in it. A+ * declaration nested in a namespace is not one of them. Only the readers of+ * icon-set libraries use this: the parse-failure and re-export checks,+ * {@link moduleExportOrigin} and the readers built on it, and+ * {@link followedExportNames}. {@link bindingOrigin}, and so+ * {@link aliasedOrigin}, {@link elementPropOrigins} and+ * {@link moduleExportOrigins}, read with {@link nodesOfType}, as do the+ * other readers.+ * @param {any} program+ * @param {string} type+ * @returns {readonly any[]}+ */+function moduleDeclarations(program, type) {+ return cachedNodes(program, `top\0${type}`, () =>+ program.body.filter((/** @type {any} */ each) => each.type === type),+ );+}++/**+ * @param {any} node+ * @param {string} key+ * @param {() => readonly any[]} find+ * @returns {readonly any[]}+ */+function cachedNodes(node, key, find) {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);- }+ const cached = byType.get(key);+ if (cached) return cached;+ const found = find();+ byType.set(key, found);return found;}@@ -315,7 +346,7 @@ export function moduleParseFailure(file) {};}for (const type of ['ExportNamedDeclaration', 'ExportAllDeclaration']) {- for (const node of nodesOfType(ast.program, type)) {+ for (const node of moduleDeclarations(ast.program, type)) {const specifier = node.source?.value;if (typeof specifier !== 'string' || !specifier.startsWith('.')) {continue;@@ -344,7 +375,7 @@ export function unfollowedReexports(file) {/** @type {Set<string>} */const missing = new Set();for (const type of ['ExportNamedDeclaration', 'ExportAllDeclaration']) {- for (const node of nodesOfType(ast.program, type)) {+ for (const node of moduleDeclarations(ast.program, type)) {const specifier = node.source?.value;if (typeof specifier !== 'string' || node.exportKind === 'type') continue;if (!resolveModuleOrPackage(specifier, file)) missing.add(specifier);@@ -608,11 +639,12 @@ export function moduleExportNames(file) {/*** Every export of a module with where it is declared, in one pass: the same- * answers as {@link moduleExportOrigin} for each name, read once per module.+ * answers as the whole-tree {@link exportOrigin} for each name, read once per+ * module.* Pass one `memo` to calls that read the same package, so a module behind* many barrels is read once; a memo keeps value and type reads apart, and* nothing is kept between memos. One difference follows ESM where- * {@link moduleExportOrigin} does not: a name re-exported by name from a+ * {@link exportOrigin} does not: a name re-exported by name from a* module that cannot be followed is absent, never filled from `export *`.* @param {string} file* @param {{types?: boolean, memo?: Map<string, Map<string, {file: string, name: string}>>}} [options]@@ -697,7 +729,7 @@ function exportOriginsOf(file, read) {origin =result.origins.get(local) ??(result.low < Infinity- ? moduleExportOrigin(target, local, new Set(), {types})+ ? exportOrigin(target, local, new Set(), nodesOfType, types): null);}} else {@@ -1087,23 +1119,34 @@ export function staticExportObject(file, exportNames) {/*** 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}>>}>}+ * the name it exports, in source order. Each reader of export declarations+ * has its own index, since the readers can find different declarations.+ * @type {WeakMap<object, Map<Function, {declarations: any[], specifiers: Map<string, Array<{node: any, specifier: any}>>}>>}*/const namedExportIndexes = new WeakMap();/** The same index with type-only exports included. */const typedExportIndexes = new WeakMap();-/** @param {any} program @param {boolean} [types] include type-only exports */-function namedExportIndex(program, types = false) {+/**+ * @param {any} program+ * @param {boolean} [types] include type-only exports+ * @param {(node: any, type: string) => readonly any[]} [read] how the+ * module's export declarations are read+ */+function namedExportIndex(program, types = false, read = nodesOfType) {const indexes = types ? typedExportIndexes : namedExportIndexes;- const cached = indexes.get(program);+ let byReader = indexes.get(program);+ if (!byReader) {+ byReader = new Map();+ indexes.set(program, byReader);+ }+ const cached = byReader.get(read);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')) {+ for (const node of read(program, 'ExportNamedDeclaration')) {if (node.exportKind === 'type' && !types) continue;if (node.declaration) declarations.push(node);for (const specifier of node.specifiers ?? []) {@@ -1120,7 +1163,7 @@ function namedExportIndex(program, types = false) {}}const index = {declarations, specifiers};- indexes.set(program, index);+ byReader.set(read, index);return index;}@@ -1142,6 +1185,21 @@ export function moduleExportOrigin(seen = new Set(),{types = false} = {},) {+ return exportOrigin(file, exportName, seen, moduleDeclarations, types);+}++/**+ * {@link moduleExportOrigin} with the reader of a module's export+ * declarations: {@link moduleDeclarations} for icon-set libraries, or+ * {@link nodesOfType} for every other caller.+ * @param {string} file+ * @param {string} exportName+ * @param {Set<string>} seen+ * @param {(node: any, type: string) => readonly any[]} read+ * @param {boolean} [types] also follow type-only exports and declarations+ * @returns {{file: string, name: string} | null}+ */+function exportOrigin(file, exportName, seen, read, types = false) {const identity = `${file}\0${exportName}`;if (seen.has(identity)) return null;seen.add(identity);@@ -1152,7 +1210,7 @@ export function moduleExportOrigin(} catch {return null;}- const {declarations, specifiers} = namedExportIndex(ast.program, types);+ const {declarations, specifiers} = namedExportIndex(ast.program, types, read);for (const node of declarations) {if (declarationExports(node.declaration, exportName, types)) {return {file, name: exportName};@@ -1163,28 +1221,28 @@ export function moduleExportOrigin(if (node.source) {const target = resolveModuleOrPackage(node.source.value, file);const origin = target- ? moduleExportOrigin(target, local, seen, {types})+ ? exportOrigin(target, local, seen, read, types): null;if (origin) return origin;continue;}- return bindingOrigin(ast, file, local, seen, types);+ return bindingOrigin(ast, file, local, seen, types, read);}if (exportName === 'default') {- for (const node of nodesOfType(ast.program, 'ExportDefaultDeclaration')) {+ for (const node of read(ast.program, 'ExportDefaultDeclaration')) {const declaration = node.declaration;if (!types && !runtimeDefault(declaration)) continue;if (declaration.type === 'Identifier') {- return bindingOrigin(ast, file, declaration.name, seen, types);+ return bindingOrigin(ast, file, declaration.name, seen, types, read);}return {file, name: 'default'};}}- for (const node of nodesOfType(ast.program, 'ExportAllDeclaration')) {+ for (const node of read(ast.program, 'ExportAllDeclaration')) {if ((node.exportKind === 'type' && !types) || node.exported) continue;const target = resolveModuleOrPackage(node.source?.value, file);const origin = target- ? moduleExportOrigin(target, exportName, seen, {types})+ ? exportOrigin(target, exportName, seen, read, types): null;if (origin) return origin;}@@ -1240,7 +1298,10 @@ function originGapReason(file, exportName, seen = new Set()) {}/** @type {string | null} */let local = null;- for (const node of nodesOfType(ast.program, 'ExportNamedDeclaration')) {+ for (const node of moduleDeclarations(+ ast.program,+ 'ExportNamedDeclaration',+ )) {for (const specifier of node.specifiers ?? []) {const exported = specifier.exported?.name ?? specifier.exported?.value;if (exported !== exportName) continue;@@ -1261,7 +1322,10 @@ function originGapReason(file, exportName, seen = new Set()) {}}if (exportName === 'default') {- for (const node of nodesOfType(ast.program, 'ExportDefaultDeclaration')) {+ for (const node of moduleDeclarations(+ ast.program,+ 'ExportDefaultDeclaration',+ )) {if (node.declaration?.type === 'Identifier') {local = node.declaration.name;}@@ -1269,7 +1333,10 @@ function originGapReason(file, exportName, seen = new Set()) {}if (!local) {// Bound behind `export *`: the module it comes from says why.- for (const node of nodesOfType(ast.program, 'ExportAllDeclaration')) {+ for (const node of moduleDeclarations(+ ast.program,+ 'ExportAllDeclaration',+ )) {if (node.exportKind === 'type' || node.exported) continue;const target = resolveModuleOrPackage(node.source?.value, file);if (@@ -1330,7 +1397,10 @@ export function followedExportNames(}/** @type {Set<string>} */const names = new Set();- for (const node of nodesOfType(ast.program, 'ExportNamedDeclaration')) {+ for (const node of moduleDeclarations(+ ast.program,+ 'ExportNamedDeclaration',+ )) {if (node.exportKind === 'type' && !types) continue;const declaration = node.declaration;if (declaration && (declaration.declare !== true || types)) {@@ -1360,7 +1430,7 @@ export function followedExportNames(}}}- for (const node of nodesOfType(ast.program, 'ExportAllDeclaration')) {+ for (const node of moduleDeclarations(ast.program, 'ExportAllDeclaration')) {if ((node.exportKind === 'type' && !types) || node.exported) continue;const target = resolveModuleOrPackage(node.source?.value, file);if (target) {@@ -1422,7 +1492,7 @@ export function exportValueKind(file, exportName) {return 'unknown';};if (origin.name === 'default') {- const [node] = nodesOfType(ast.program, 'ExportDefaultDeclaration');+ const [node] = moduleDeclarations(ast.program, 'ExportDefaultDeclaration');return node ? kindOf(node.declaration) : 'unknown';}for (const statement of ast.program.body) {@@ -1479,7 +1549,7 @@ export function exportScalarType(file, exportName) {return null;};if (origin.name === 'default') {- const [node] = nodesOfType(ast.program, 'ExportDefaultDeclaration');+ const [node] = moduleDeclarations(ast.program, 'ExportDefaultDeclaration');return node ? typeOf(node.declaration) : null;}for (const statement of ast.program.body) {@@ -1630,9 +1700,18 @@ export function elementPropOrigins(file, {sources, name, prop, unwrap}) {* @param {string} local* @param {Set<string>} seen* @param {boolean} [types] also follow `import type`+ * @param {(node: any, type: string) => readonly any[]} [read] how an+ * imported module's export declarations are read* @returns {{file: string, name: string} | null}*/-function bindingOrigin(ast, file, local, seen, types = false) {+function bindingOrigin(+ ast,+ file,+ local,+ seen,+ types = false,+ read = nodesOfType,+) {for (const node of ast.program.body) {if (node.type !== 'ImportDeclaration' ||@@ -1646,9 +1725,7 @@ function bindingOrigin(ast, file, local, seen, types = false) {const imported =specifier.imported?.name ?? specifier.imported?.value ?? local;const target = resolveModuleOrPackage(node.source.value, file);- return target- ? moduleExportOrigin(target, imported, seen, {types})- : null;+ return target ? exportOrigin(target, imported, seen, read, types) : null;}}return {file, name: local};diff --git a/packages/cli/foundation/discovery/module-exports.test.mjs b/packages/cli/foundation/discovery/module-exports.test.mjsindex f1935b9fcb..fbe94514d8 100644--- a/packages/cli/foundation/discovery/module-exports.test.mjs+++ b/packages/cli/foundation/discovery/module-exports.test.mjs@@ -11,9 +11,11 @@ import * as os from 'node:os';import * as path from 'node:path';import {elementPropOrigins,+ followedExportNames,moduleExportOrigin,moduleExportOrigins,moduleExportSource,+ moduleExportsName,staticExportObject,} from './module-exports.mjs';@@ -276,6 +278,86 @@ describe('elementPropOrigins', () => {);expect(elementPropOrigins(app, THEME)).toEqual([null]);});++ it('follows an import to an export declared inside a namespace, as the whole-tree reader finds it', () => {+ const themes = write(+ 'themes.ts',+ 'namespace Palette {\n export const ocean = {};\n}\n',+ );+ const app = write(+ 'Namespaced.tsx',+ "import {Theme} from '@acme/core';\nimport {ocean} from './themes';\nexport const A = () => <Theme theme={ocean} />;\n",+ );+ // The icon-set reader, which reads only the top level, runs first on+ // the same parsed module and leaves the whole-tree answer unchanged.+ expect(moduleExportOrigin(themes, 'ocean')).toBeNull();+ expect(elementPropOrigins(app, THEME)).toEqual([+ {file: themes, name: 'ocean'},+ ]);+ });+});++describe('an export declared inside a namespace', () => {+ const NAMESPACE =+ 'export namespace Button {\n export function Inner() { return null; }\n}\n';++ it('counts for the stable reader, as it always has', () => {+ const file = write('button.ts', NAMESPACE);+ expect(moduleExportSource(file, 'Inner')).toBe(file);+ expect(moduleExportsName(file, 'Inner')).toBe(true);+ });++ it('is no export of the module for the icon-set reader, which reads only its top level', () => {+ const file = write('button.ts', NAMESPACE);+ expect(moduleExportOrigin(file, 'Inner')).toBeNull();+ expect(followedExportNames(file)).not.toContain('Inner');+ });++ it('counts for the one-pass reader, in value and type reads, after the icon-set reader reads the module', () => {+ const file = write('button.ts', NAMESPACE);+ expect(+ moduleExportOrigin(file, 'Inner', undefined, {types: true}),+ ).toBeNull();+ for (const types of [false, true]) {+ expect(moduleExportOrigins(file, {types}).get('Inner')).toEqual({+ file,+ name: 'Inner',+ });+ }+ });+});++describe('the one-pass reader beside the icon-set reader', () => {+ it('reads namespace and type exports as the whole-tree reader does, while the icon-set reader skips nested declarations', () => {+ const file = write(+ 'mixed.ts',+ [+ 'export namespace Shapes {',+ ' export const circle = 1;',+ ' export interface Corner {}',+ '}',+ 'export interface Size {}',+ 'export const top = 2;',+ '',+ ].join('\n'),+ );+ expect(moduleExportOrigin(file, 'circle')).toBeNull();+ expect(+ moduleExportOrigin(file, 'Corner', undefined, {types: true}),+ ).toBeNull();+ expect(moduleExportOrigin(file, 'Size', undefined, {types: true})).toEqual({+ file,+ name: 'Size',+ });+ const names = types =>+ [...moduleExportOrigins(file, {types}).keys()].sort();+ expect(names(false)).toEqual(['circle', 'top']);+ expect(names(true)).toEqual(['Corner', 'Shapes', 'Size', 'circle', 'top']);+ expect(moduleExportOrigins(file, {types: true}).get('Corner')).toEqual({+ file,+ name: 'Corner',+ });+ });});describe('moduleExportOrigins', () => {diff --git a/packages/cli/foundation/text/shell-arg.mjs b/packages/cli/foundation/text/shell-arg.mjsnew file mode 100644index 0000000000..7685fdfae7--- /dev/null+++ b/packages/cli/foundation/text/shell-arg.mjs@@ -0,0 +1,17 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file One command-line word for a printed command: a value as written when+ * the shell reads it as one plain word, else single-quoted, so a printed+ * command runs as printed and never substitutes anything.+ */++/**+ * A value as one shell word.+ * @param {string} value+ * @returns {string}+ */+export function shellArg(value) {+ if (/^[A-Za-z0-9@/._-]+$/.test(value)) return value;+ return `'${value.replace(/'/g, `'\\''`)}'`;+}diff --git a/packages/cli/foundation/text/shell-arg.test.mjs b/packages/cli/foundation/text/shell-arg.test.mjsnew file mode 100644index 0000000000..ba89f059ea--- /dev/null+++ b/packages/cli/foundation/text/shell-arg.test.mjs@@ -0,0 +1,17 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file shellArg: one shell word for a printed command. */++import {describe, expect, it} from 'vitest';+import {shellArg} from './shell-arg.mjs';++describe('shellArg', () => {+ it('shell-quotes unusual ids instead of allowing command substitution', () => {+ expect(shellArg('safe/id')).toBe('safe/id');+ expect(shellArg('@acme/icons/24/solid')).toBe('@acme/icons/24/solid');+ expect(shellArg('my$thing')).toBe("'my$thing'");+ expect(shellArg("a'b")).toBe("'a'\\''b'");+ expect(shellArg('foo`id`')).toBe("'foo`id`'");+ expect(shellArg('arrow up')).toBe("'arrow up'");+ });+});