Skip to content

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

TypeScript

fix(cli): experimental icon sets — name the license notice a library without one needs; a refresh moves per-file icons to the library root (#10458)

Joey79150bc7d4b8
diff --git a/.changeset/cli-icon-sets-license-notice-refresh.md b/.changeset/cli-icon-sets-license-notice-refresh.md
new file mode 100644
index 0000000000..50cb676635
--- /dev/null
+++ b/.changeset/cli-icon-sets-license-notice-refresh.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[experimental] Icon sets: when a wrapped library ships no license file, `integration check` on an icon set, `experimental icon new-set --from`, and a refresh name the NOTICE file to add and where, and the icon-sets guide lists the file names that count. A refresh from a library root moves icons added one file at a time from that library to the root import, keeping their ids, exports, map entries, variants, and words, and the receipt lists them under `moved`. Each keeps that id and export on every later refresh, and refreshing again changes nothing. A refresh keeps an id you chose that is not a spelling of the library name (`dismiss` for `XIcon`), also for an icon that already reads the root; it renames only an id the current rule spells differently. A library icon whose id or name a moved icon already has is left out. An icon whose root export another icon of the set already reads stays on its own import, and the receipt says why. A variant from another file of the package, such as a solid look, stays on its own import, and every export the refresh does not write again stays in the generated module. A `LICENSE` directory counts as a license notice in neither the receipt nor the check.
+
+@josephfarina
diff --git a/docs/specs/AST-084-icon-sets/spec.md b/docs/specs/AST-084-icon-sets/spec.md
index d8ab0a881f..05b8eeb5ac 100644
--- a/docs/specs/AST-084-icon-sets/spec.md
+++ b/docs/specs/AST-084-icon-sets/spec.md
@@ -296,7 +296,9 @@ icon, and the CLI verifies it, writes the files, and checks the set.
data file's `exclude`, which every refresh honors. From an installed
package it records `source` (the library and version), copies the
library's license notices into the set, and takes the library's license
- for the descriptor. Its receipt names, as the exact text to add, the
+ for the descriptor; when the library ships none and the set and package
+ have none, the receipt names the NOTICE file to add under
+ `licenseNoticeMissing`, and nothing is written. Its receipt names, as the exact text to add, the
entry change that makes the generated module public (an `export *` line
for an entry file in the package, relative to it; for a package with no
entry, `index.js`, `index.d.ts`, and their package.json `main`, `types`,
@@ -327,8 +329,20 @@ icon, and the CLI verifies it, writes the files, and checks the set.
icon is known by the library export its generated module re-exports, then
by its own export, then by its `id`; one matched this way keeps its export
unchanged, its `map` entries, and every other field, and an `id` the
- current rule spells differently is reported under `renamed`
+ current rule spells differently from the same library name is reported
+ under `renamed`
(`add --variant <name> --all` meets an icon the same way). A refresh
+ from a package root also refreshes an icon the generated module reads
+ from a file of that package, and each such variant of an icon it
+ refreshes, when the root exports the same icon: an export that resolves
+ to the same file and binding, or an export of the same name when the
+ file export does not resolve. It moves to the root import, keeps its
+ id, export, and other fields, and the icon is reported under `moved`.
+ It is matched only through that root export, and a root icon with its
+ id or export is left out. An export stays on its file, and the receipt
+ says so, when another export of the set already reads that root export
+ or an earlier move takes it. Every export the refresh does not write
+ again stays in the generated module. A refresh
copies the library's license notices the set lacks, and the run that
first records `source` takes the library's license for the descriptor
when its `license` is still the one `new-set` wrote (the package's own,
diff --git a/packages/cli/api/icon/_authoring.mjs b/packages/cli/api/icon/_authoring.mjs
index c6504b9e69..a6e78b360c 100644
--- a/packages/cli/api/icon/_authoring.mjs
+++ b/packages/cli/api/icon/_authoring.mjs
@@ -48,6 +48,7 @@ import {
lookPositions,
moduleNaming,
nonIconExports,
+ packageRootMoves,
resolveIconSource,
peerNote,
typecheckNote,
@@ -61,6 +62,10 @@ import {
resolveDefaultLook,
} from './_default-look.mjs';
import {shellArg} from '../../foundation/text/shell-arg.mjs';
+import {
+ hasLicenseNotice,
+ licenseNoticeFix,
+} from '../../foundation/discovery/icon-set-discovery.mjs';
import {astryxIconDefinitions} from '../../foundation/discovery/icon-definition-discovery.mjs';
import {suggestedIcons} from '../../foundation/discovery/icon-set-checks.mjs';
import {
@@ -481,6 +486,11 @@ export async function addIconSet(name, options) {
writtenFiles,
dryRun,
);
+ const missingNotice = noticeToAdd(
+ library,
+ packageDir,
+ projectPath(path.relative(packageDir, setDir)),
+ );
{
result.data.icons = icons.length;
if (from != null) {
@@ -526,14 +536,38 @@ export async function addIconSet(name, options) {
...(from != null && lookFound.summary != null
? lookNotes(lookFound.summary, icons.length, from, looks, name)
: []),
+ ...(missingNotice ? [missingNotice.note] : []),
...mappedNotes(map, name),
...suggestionNotes(suggestions, name),
'Run `astryx integration check` to see the icon definitions still to map.',
];
+ if (missingNotice) {
+ result.data.licenseNoticeMissing = missingNotice.receipt;
+ }
}
return result;
}
+/**
+ * The license notice the author must add when the wrapped library ships no
+ * license file to copy and the package root has none. The CLI never writes
+ * it: the license text is the author's to state. Null when nothing is
+ * missing.
+ * @param {{package: string, version: string, notices: string[]} | null} library
+ * @param {string} packageDir
+ * @param {string} setDir the set directory, from the package root
+ * @returns {{note: string, receipt: {library: string, path: string}} | null}
+ */
+function noticeToAdd(library, packageDir, setDir) {
+ if (!library || library.notices.length > 0) return null;
+ if (hasLicenseNotice(packageDir)) return null;
+ const named = `${library.package}@${library.version}`;
+ return {
+ note: `${named} ships no LICENSE or NOTICE file to copy, so the set has no license notice. ${licenseNoticeFix(setDir, named)}`,
+ receipt: {library: named, path: `${setDir}/NOTICE`},
+ };
+}
+
/**
* A set descriptor's source with `--display-name` and `--description`
* written into its fields; the rest as it was.
@@ -901,6 +935,70 @@ async function iconAuthoring(step) {
}
}
+/**
+ * Whether an id is one an id rule derives from a library glyph: the glyph id,
+ * or its library export, broken into words another way (`squares-2-x2` for
+ * `squares-2x2`, `glyph-eye` for `glyphEye`). Any other id is the author's.
+ * @param {string} id
+ * @param {{id: string, export: string}} glyph
+ */
+function derivedId(id, glyph) {
+ const flat = (/** @type {string} */ text) =>
+ text.toLowerCase().replace(/[^a-z0-9]/gu, '');
+ return [glyph.id, glyph.export, glyph.export.replace(/Icon$/u, '')]
+ .map(flat)
+ .includes(flat(id));
+}
+
+/**
+ * Keep the root moves that give each root export to one export of the set.
+ * A root export that an export of the set already reads, or that an earlier
+ * move takes, stays where it is. The icon that would move keeps its own file,
+ * and its variants stay with it. Returns the kept moves and the ids of the
+ * icons that stay (with `(<variant>)` for a variant that stays).
+ * @param {{data: {module: string, icons: Array<{id: string, export: string, module?: string, variants?: Array<{variant: string, export: string}>}>}}} set
+ * @param {Map<string, {module: string, source: string}>} origins
+ * @param {string} root
+ * @param {Map<string, {source: string, from: string}>} moves
+ */
+function claimRootMoves(set, origins, root, moves) {
+ /** @type {Map<string, {source: string, from: string}>} */
+ const kept = new Map();
+ /** @type {string[]} */
+ const skipped = [];
+ const claimed = new Set(
+ [...origins.values()]
+ .filter(origin => sameIconModule(origin.module, root))
+ .map(origin => origin.source),
+ );
+ for (const icon of set.data.icons) {
+ if ((icon.module ?? set.data.module) !== set.data.module) continue;
+ const own = moves.get(icon.export);
+ const origin = origins.get(icon.export);
+ const readsRoot = origin != null && sameIconModule(origin.module, root);
+ if (own) {
+ if (claimed.has(own.source)) {
+ skipped.push(icon.id);
+ continue;
+ }
+ claimed.add(own.source);
+ kept.set(icon.export, own);
+ } else if (!readsRoot) continue;
+ for (const each of icon.variants ?? []) {
+ const move = moves.get(each.export);
+ if (!move) continue;
+ if (claimed.has(move.source)) {
+ skipped.push(`${icon.id} (${each.variant})`);
+ continue;
+ }
+ claimed.add(move.source);
+ kept.set(each.export, move);
+ }
+ }
+ skipped.sort();
+ return {moves: kept, skipped};
+}
+
/**
* Wrap a library into an existing set again: its icons are replaced by what
* the library exports now (an icon whose words the author extended keeps
@@ -972,9 +1070,27 @@ async function refreshIconSet(
// map entries and variants.
const generatedBefore = generatedModulePath(set, packageDir);
const origins = generatedOrigins(packageDir, generatedBefore);
+ // A refresh from a package root also supplies the exports that read one
+ // file of that package, when the root exports the same icon. They move to
+ // the root import, so the set has one import style.
+ const {moves: rootMoves, skipped: skippedMoves} = claimRootMoves(
+ set,
+ origins,
+ source.module,
+ packageRootMoves(
+ origins,
+ source,
+ everyIcon.map(icon => icon.export),
+ where,
+ ),
+ );
+ /** @param {string} name the set's export */
+ const libraryExportOf = name =>
+ rootMoves.get(name)?.source ?? origins.get(name)?.source;
/** @param {{export: string, module?: string}} icon */
const suppliedHere = icon => {
if ((icon.module ?? set.data.module) !== set.data.module) return false;
+ if (rootMoves.has(icon.export)) return true;
const origin = origins.get(icon.export);
return origin != null && sameIconModule(origin.module, source.module);
};
@@ -982,15 +1098,18 @@ async function refreshIconSet(
const others = set.data.icons.filter(icon => !suppliedHere(icon));
// An existing icon is the same icon when the library still exports it:
// its identity is the library export its generated module re-exports
- // (`HiSquares2X2Icon`), then its public export, then its id. Ids and
- // public names are derived, and a newer rule may spell them differently
- // (`squares-2-x2` is now `squares-2x2`); an icon matched this way keeps
- // its public export byte for byte, every field it had (its variants, the
- // words the author added, its module), and its map entries.
+ // (`HiSquares2X2Icon`, or the root export a per-file icon moves to), then
+ // its public export, then its id. Ids and public names are derived, and a
+ // newer rule may spell them differently (`squares-2-x2` is now
+ // `squares-2x2`); an icon matched this way keeps its public export byte
+ // for byte, every field it had (its variants, the words the author added,
+ // its module), and its map entries. The same rule holds on every refresh,
+ // so a second refresh changes nothing the first one wrote.
+ const moving = new Set(supplied.filter(icon => rootMoves.has(icon.export)));
const byId = new Map(supplied.map(icon => [icon.id, icon]));
const byExport = new Map(supplied.map(icon => [icon.export, icon]));
const bySource = new Map(
- supplied.map(icon => [origins.get(icon.export)?.source, icon]),
+ supplied.map(icon => [libraryExportOf(icon.export), icon]),
);
// One icon per glyph. A look the set already wraps keeps its icon and id.
// A new glyph comes in once, in the preferred look. A new default variant
@@ -1003,15 +1122,20 @@ async function refreshIconSet(
const iconByExport = new Map(everyIcon.map(icon => [icon.export, icon]));
/** @type {string[]} the set's exports whose statement now names another look */
const repicked = [];
+ /** @type {Map<string, (typeof supplied)[number]>} the new look's export → the icon it now draws */
+ const repickedBy = new Map();
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}} */ (
+ const prior = /** @type {(typeof supplied)[number]} */ (
bySource.get(look)
);
- if (moved && prior.id === icon.id && !bySource.has(icon.export)) {
+ // A moved icon is the glyph its root export draws, whatever its id.
+ const sameGlyph = moving.has(prior) || prior.id === icon.id;
+ if (moved && sameGlyph && !bySource.has(icon.export)) {
repicked.push(prior.export);
+ repickedBy.set(icon.export, prior);
return icon;
}
const own = /** @type {(typeof everyIcon)[number]} */ (
@@ -1023,29 +1147,44 @@ async function refreshIconSet(
: own;
});
});
- /** @param {{export: string, name: string, id: string}} icon */
- const priorOf = icon =>
- bySource.get(icon.export) ??
- byExport.get(icon.name) ??
- byId.get(icon.id) ??
- null;
- const otherIds = new Set(others.map(icon => icon.id));
- const otherExports = new Set(others.map(icon => icon.export));
- /** @type {string[]} library icons left out: an icon of yours has the id or name */
+ /** @param {{export: string}} glyph */
+ const resolvedPrior = glyph =>
+ repickedBy.get(glyph.export) ?? bySource.get(glyph.export) ?? null;
+ // An icon its library export already gives to one glyph is never given to
+ // a second glyph by name or id: that glyph is left out.
+ const resolved = new Set(found.map(resolvedPrior).filter(Boolean));
+ const takenIds = new Set(others.map(icon => icon.id));
+ const takenExports = new Set(others.map(icon => icon.export));
+ /** @type {string[]} library icons left out: an icon of the set has the id or name */
const shadowed = [];
/** @type {Map<string, string>} old id → new id */
const renames = new Map();
/** @type {Map<string, string>} the library export → the set's export */
const publicName = new Map();
const fromLibrary = found.flatMap(icon => {
- const prior = priorOf(icon);
+ const byOrigin = resolvedPrior(icon);
+ const byName = byOrigin
+ ? null
+ : (byExport.get(icon.name) ?? byId.get(icon.id) ?? null);
+ const prior = byOrigin ?? (resolved.has(byName) ? null : byName);
const name = prior?.export ?? icon.name;
- if (!prior && (otherIds.has(icon.id) || otherExports.has(name))) {
+ if (
+ !prior &&
+ (byName || takenIds.has(icon.id) || takenExports.has(name))
+ ) {
shadowed.push(icon.id);
return [];
}
- if (prior && prior.id !== icon.id) renames.set(prior.id, icon.id);
publicName.set(icon.export, name);
+ if (prior && byOrigin && !derivedId(prior.id, icon)) {
+ return [
+ {
+ ...prior,
+ words: [...new Set([...(prior.words ?? []), ...icon.aliases])],
+ },
+ ];
+ }
+ if (prior && prior.id !== icon.id) renames.set(prior.id, icon.id);
// The words its old id gave are the old rule's, not the author's.
const oldIdWords =
prior && prior.id !== icon.id ? new Set(idWords(prior.id)) : new Set();
@@ -1065,6 +1204,32 @@ async function refreshIconSet(
];
});
const icons = [...fromLibrary, ...others];
+ // An icon is listed under `moved` when it or one of its variants moves.
+ /** @type {Array<{id: string, from: string, to: string}>} */
+ const movedIcons = [];
+ /** @type {import('../../foundation/discovery/icon-set-writer.mjs').GeneratedIcon[]} */
+ const movedVariants = [];
+ for (const icon of fromLibrary) {
+ const variantMoves = (icon.variants ?? []).filter(each =>
+ rootMoves.has(each.export),
+ );
+ for (const each of variantMoves) {
+ const move = /** @type {{source: string, from: string}} */ (
+ rootMoves.get(each.export)
+ );
+ movedVariants.push({
+ name: each.export,
+ from: source.module,
+ source: move.source,
+ adapt: iconByExport.get(move.source)?.adapt ?? false,
+ });
+ }
+ const from = (
+ rootMoves.get(icon.export) ?? rootMoves.get(variantMoves[0]?.export)
+ )?.from;
+ if (from) movedIcons.push({id: icon.id, from, to: source.module});
+ }
+ movedIcons.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
// The icons this module supplied that it no longer exports: they leave
// the set and its generated module, and the receipt names them.
// Each is named for why it left: `--exclude` (or the data file's
@@ -1074,7 +1239,7 @@ async function refreshIconSet(
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(libraryExportOf(icon.export) ?? '') ||
excludedNames.has(icon.export);
const goneExcluded = gone.filter(isExcluded);
const goneMissing = gone.filter(icon => !isExcluded(icon));
@@ -1163,22 +1328,31 @@ async function refreshIconSet(
files.push(projectPath(path.relative(packageDir, target)));
}
if (!dryRun) {
+ const rewritten = found
+ .map(icon => ({
+ name: publicName.get(icon.export) ?? icon.name,
+ from: source.module,
+ source: icon.export,
+ adapt: icon.adapt,
+ }))
+ .filter(icon => publicName.has(icon.source))
+ .concat(movedVariants);
+ const rewrittenNames = new Set(rewritten.map(icon => icon.name));
const written = writeGeneratedIcons(
packageDir,
generated,
next,
- found
- .map(icon => ({
- name: publicName.get(icon.export) ?? icon.name,
- from: source.module,
- source: icon.export,
- adapt: icon.adapt,
- }))
- .filter(icon => publicName.has(icon.source)),
+ rewritten,
// The icons the library no longer exports leave the module too; a
// 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],
+ // look keeps its export, which now names that look. An export moved
+ // to the root is written again with the root import. Every other
+ // export stays as it is, because the data file still lists it.
+ [
+ ...gone.map(icon => icon.export),
+ ...repicked,
+ ...[...rootMoves.keys()].filter(name => rewrittenNames.has(name)),
+ ],
);
files.push(...written.files);
try {
@@ -1230,13 +1404,30 @@ async function refreshIconSet(
if (renames.size > 0) {
result.data.renamed = [...renames].map(([from, to]) => ({from, to}));
}
+ if (movedIcons.length > 0) result.data.moved = movedIcons;
+ const missingNotice = hasLicenseNotice(set.dir)
+ ? null
+ : noticeToAdd(
+ library,
+ packageDir,
+ projectPath(path.relative(packageDir, set.dir)),
+ );
+ if (missingNotice) {
+ result.data.licenseNoticeMissing = missingNotice.receipt;
+ }
result.data.notes = [
...(licenseNote ? [licenseNote] : []),
+ ...(missingNotice ? [missingNotice.note] : []),
...(renames.size > 0
? [
`${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(', ')}.`,
]
: []),
+ ...(movedIcons.length > 0
+ ? [
+ `${movedIcons.length} icons now import from ${source.module} instead of one file each, and keep their ids, exports, map entries, variants, and words: ${movedIcons.map(each => each.id).join(', ')}.`,
+ ]
+ : []),
...mappedNotes(byName, name),
...suggestionNotes(suggestions, name),
...(goneMissing.length > 0
@@ -1261,7 +1452,12 @@ async function refreshIconSet(
: []),
...(shadowed.length > 0
? [
- `Left out ${shadowed.length} library icons whose id or name an icon of yours from another module already has: ${shadowed.join(', ')}.`,
+ `Left out ${shadowed.length} library icons whose id or name an icon of the set already has: ${shadowed.join(', ')}.`,
+ ]
+ : []),
+ ...(skippedMoves.length > 0
+ ? [
+ `${skippedMoves.length} icons stay on their own file, because another icon of the set already reads the same export of ${source.module}: ${skippedMoves.join(', ')}.`,
]
: []),
astryxIconDefinitions().definitions.every(({doc}) => map[doc.name])
diff --git a/packages/cli/api/icon/icon.type.mjs b/packages/cli/api/icon/icon.type.mjs
index 9008aa93ee..59b29325c1 100644
--- a/packages/cli/api/icon/icon.type.mjs
+++ b/packages/cli/api/icon/icon.type.mjs
@@ -326,6 +326,8 @@
* @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<{id: string, from: string, to: string}>} [moved] - On a refresh from a package root: the icons that read one file of that package (`from`) and now import from the root (`to`); each keeps its id, export, `map` entries, variants, and words.
+ * @property {{library: string, path: string}} [licenseNoticeMissing] - With `from`: the wrapped library (`name@version`) ships no license file to copy and the set has none. `path` is where to add a NOTICE file that names the library and its license; the CLI never writes it.
* @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/integration/add-helpers.mjs b/packages/cli/api/integration/add-helpers.mjs
index c4ea794c1d..9a8b973009 100644
--- a/packages/cli/api/integration/add-helpers.mjs
+++ b/packages/cli/api/integration/add-helpers.mjs
@@ -486,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, updated?: 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}>, moved?: Array<{id: string, from: string, to: string}>, licenseNoticeMissing?: {library: string, path: 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/assets/docs/tree/icon-sets.doc.mjs b/packages/cli/assets/docs/tree/icon-sets.doc.mjs
index e0b8b2689d..5381b98c71 100644
--- a/packages/cli/assets/docs/tree/icon-sets.doc.mjs
+++ b/packages/cli/assets/docs/tree/icon-sets.doc.mjs
@@ -121,11 +121,11 @@ export const docs = {
},
{
type: 'prose',
- text: "Every component the library exports becomes an icon (an alias of one component is recorded once), named `<Name>Icon`, with an id from its name (`Squares2X2Icon` is `squares-2x2`: a dimension stays one word). `map` is filled only where a definition's name is an icon's id (`delete` → icon `delete`), and the receipt lists those entries under Mapped by name: a library can draw another meaning under the same name (one library's `delete` is a backspace key), so check each. An icon whose id is only one of a definition's words (`trash` for `delete`) may mean something else in this library, so the receipt lists it under Suggestions, with the `experimental icon map <definition> <icon>` command for each, and writes nothing for it: check the meaning, then run the ones that fit. Run it again after a library release to refresh the icons that library supplies; `map` entries whose icon still exists are kept, and the receipt names any icon the library dropped, any icon `--exclude` left out, and the `map` entries each took with it. Icons you added from your own files or another library are left as they are. An icon you already have is known by the library export it re-exports, so it keeps its export name exactly, its `map` entries, variants, and words, even when a newer CLI spells its id differently or your `--exclude` lets a library prefix come off new ids; the receipt lists each changed id under `renamed`. A refresh with `--dry-run` writes nothing and prints the Mapped by name and Suggestions lists again; `--display-name` and `--description` on a refresh rewrite the descriptor. Variants added with `add --variant … --all` are kept too; run that `add` again to pick up icons the release added. `experimental icon --list` shows how many definitions the set maps.",
+ text: "Every component the library exports becomes an icon (an alias of one component is recorded once), named `<Name>Icon`, with an id from its name (`Squares2X2Icon` is `squares-2x2`: a dimension stays one word). `map` is filled only where a definition's name is an icon's id (`delete` → icon `delete`), and the receipt lists those entries under Mapped by name: a library can draw another meaning under the same name (one library's `delete` is a backspace key), so check each. An icon whose id is only one of a definition's words (`trash` for `delete`) may mean something else in this library, so the receipt lists it under Suggestions, with the `experimental icon map <definition> <icon>` command for each, and writes nothing for it: check the meaning, then run the ones that fit. Run it again after a library release to refresh the icons that library supplies; `map` entries whose icon still exists are kept, and the receipt names any icon the library dropped, any icon `--exclude` left out, and the `map` entries each took with it. Icons you added from your own files or another library are left as they are. Icons you added one file at a time from the same package (`--from <package>/dist/XIcon`) move to the root import when you refresh from the package root and the root exports the same icon; each keeps its id, export, `map` entries, variants, and words on that refresh and every later one, and the receipt lists it under `moved`. A library icon whose id or name a moved icon already has is left out. When another icon of the set already reads the same root export, the icon stays on its own file, and the receipt says why. An icon you already have is known by the library export it re-exports, so it keeps its export name exactly, its `map` entries, variants, and words, even when a newer CLI spells its id differently or your `--exclude` lets a library prefix come off new ids; the receipt lists each changed id under `renamed`. An id you chose that is not a spelling of the library name (`dismiss` for `XIcon`) is kept. A refresh with `--dry-run` writes nothing and prints the Mapped by name and Suggestions lists again; `--display-name` and `--description` on a refresh rewrite the descriptor. Variants added with `add --variant … --all` are kept too; run that `add` again to pick up icons the release added. `experimental icon --list` shows how many definitions the set maps.",
},
{
type: 'prose',
- text: "With a package or package subpath, it also records the installed library and version as the data file's `source`, so `integration check` warns when your dependency moves to another version; copies the library's LICENSE (and NOTICE) files into the set directory; and sets the descriptor's `license` to the library's. A set you started without `--from` gets the same the first time a refresh records its source, unless you already changed `license`: a `license` you set is kept (the receipt names the library's), and every later refresh keeps it too. Your package.json `license` is never changed. Edit `license` when the artwork's license differs from the library's package license.",
+ text: "With a package or package subpath, it also records the installed library and version as the data file's `source`, so `integration check` warns when your dependency moves to another version; copies the library's LICENSE (and NOTICE) files into the set directory; and sets the descriptor's `license` to the library's. A set you started without `--from` gets the same the first time a refresh records its source, unless you already changed `license`: a `license` you set is kept (the receipt names the library's), and every later refresh keeps it too. Your package.json `license` is never changed. Edit `license` when the artwork's license differs from the library's package license. When the library ships no license file to copy, the receipt says so under `licenseNoticeMissing` and in its notes, and the CLI writes nothing: add a `NOTICE` file to the set directory (`icon-sets/<set>/NOTICE`) that names the library, its version, and its license. `integration check` accepts a file named `LICENSE`, `LICENCE`, `NOTICE`, or `COPYING`, in any case and with an optional suffix such as `NOTICE.md` or `LICENSE-MIT`, in the set directory or the package root; without one it reports `icon_license_notice_missing`.",
},
{
type: 'prose',
diff --git a/packages/cli/clients/cli/commands/icon-authoring.test.mjs b/packages/cli/clients/cli/commands/icon-authoring.test.mjs
index 918394e0a2..948174a4f4 100644
--- a/packages/cli/clients/cli/commands/icon-authoring.test.mjs
+++ b/packages/cli/clients/cli/commands/icon-authoring.test.mjs
@@ -15,6 +15,7 @@ import {pathToFileURL} from 'node:url';
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
import {runCli} from '../../../test-utils/run-cli.mjs';
import {writeIconSetProject} from '../../../test-utils/icon-set-fixture.mjs';
+import {ICON_NAMES} from '../../../authoring/doctypes/icon-set/icon-names.mjs';
/** @type {string} */
let tmp;
@@ -103,6 +104,45 @@ const dataOf = set =>
),
);
+/**
+ * Refresh a set twice more and expect nothing to change after the refresh
+ * before them: each run exits 0, the ids, exports and map stay the same, and
+ * the data file and the generated module stay the same byte for byte.
+ * @param {string} set
+ * @param {string[]} args the refresh command
+ */
+async function expectStableRefreshes(set, args) {
+ const dir = path.join(pkg, 'icon-sets', set);
+ const files = () =>
+ [`${set}.icons.json`, `${set}.generated.js`].map(file =>
+ fs.readFileSync(path.join(dir, file), 'utf-8'),
+ );
+ const identity = () => {
+ const data = dataOf(set);
+ return {
+ icons: data.icons.map((/** @type {any} */ icon) => [
+ icon.id,
+ icon.export,
+ ...(icon.variants ?? []).map((/** @type {any} */ each) => each.export),
+ ]),
+ map: data.map,
+ };
+ };
+ let before = {files: files(), identity: identity()};
+ for (const run of ['second', 'third']) {
+ const refreshed = await json(args);
+ expect(
+ refreshed.code,
+ `${run} refresh: ${JSON.stringify(refreshed.body)}`,
+ ).toBe(0);
+ expect(refreshed.body.data.renamed, `${run} refresh`).toBeUndefined();
+ const after = {files: files(), identity: identity()};
+ expect(after.identity, `${run} refresh`).toEqual(before.identity);
+ expect(after.files, `${run} refresh`).toEqual(before.files);
+ before = after;
+ }
+}
+
describe('experimental icon new-set --from', () => {
it('wraps every component of a library once, names each <Name>Icon, pre-fills exact map hits, and says what to export', async () => {
const {code, body} = await json([
@@ -2119,6 +2159,58 @@ describe('a refresh that first records the source', () => {
});
});
+describe('a library that ships no license file', () => {
+ it('new-set --from and a refresh name the NOTICE file to add, and write none', async () => {
+ const instruction =
+ 'Add a NOTICE (or LICENSE) file to icon-sets/outline that names @acme/[email protected] and its license: `icon-sets/outline/NOTICE`.';
+ const args = [
+ 'experimental',
+ 'icon',
+ 'new-set',
+ 'outline',
+ '--from',
+ '@acme/glyph-library',
+ ];
+ const created = await json(args);
+ expect(created.code).toBe(0);
+ expect(created.body.data.licenseNoticeMissing).toEqual({
+ library: '@acme/[email protected]',
+ path: 'icon-sets/outline/NOTICE',
+ });
+ expect(created.body.data.notes.join('\n')).toContain(
+ `@acme/[email protected] ships no LICENSE or NOTICE file to copy, so the set has no license notice. ${instruction}`,
+ );
+ const set = path.join(pkg, 'icon-sets', 'outline');
+ expect(
+ fs.readdirSync(set).filter(file => /notice|licen/iu.test(file)),
+ ).toEqual([]);
+ const refreshed = await json(args);
+ expect(refreshed.body.data.licenseNoticeMissing).toEqual(
+ created.body.data.licenseNoticeMissing,
+ );
+ expect(refreshed.body.data.notes.join('\n')).toContain(instruction);
+ const strict = await runCli(
+ ['integration', 'check', '--strict', '--json'],
+ pkg,
+ );
+ // The check's finding gives the same instruction.
+ const finding = JSON.parse(strict.stdout).data.failures.find(
+ (/** @type {{code: string}} */ each) =>
+ each.code === 'icon_license_notice_missing',
+ );
+ expect(finding.message).toContain(instruction);
+
+ // Once the author adds it, nothing asks for it again.
+ fs.writeFileSync(
+ path.join(set, 'NOTICE'),
+ 'Icons from @acme/glyph-library 2.0.0, MIT License.\n',
+ );
+ const again = await json(args);
+ expect(again.body.data.licenseNoticeMissing).toBeUndefined();
+ expect(again.body.data.notes.join('\n')).not.toContain('NOTICE');
+ });
+});
+
describe('a first-source refresh over a license the author chose', () => {
it('keeps it, and the receipt names both licenses', async () => {
const lib = path.join(pkg, 'node_modules', '@acme', 'glyph-library');
@@ -2847,3 +2939,956 @@ describe('a refresh with --exclude', () => {
expect(dataOf('outline').exclude).toEqual(['Cross']);
});
});
+
+describe('a refresh from a library root over icons added one per file', () => {
+ /**
+ * Glyphs of a library whose export names encode the look: one per
+ * built-in definition, so the set can pass the strict check.
+ */
+ const pascal = (/** @type {string} */ name) =>
+ name[0].toUpperCase() + name.slice(1);
+ const glyphs = [
+ ...new Set([...ICON_NAMES.map(pascal), 'Search', 'X']),
+ ].sort();
+ const kebab = (/** @type {string} */ name) =>
+ name.replace(/([a-z])([A-Z])/gu, '$1-$2').toLowerCase();
+ const looks = ['Outline', 'Filled'];
+ /** @param {string} glyph @param {string} look */
+ const fileOf = (glyph, look) => `${glyph}${look}24WGHT500Icon`;
+ const subpath = (/** @type {string} */ file) =>
+ `@acme/weight-icons/dist/${file}`;
+ const weightsRefreshArgs = [
+ 'experimental',
+ 'icon',
+ 'new-set',
+ 'weights',
+ '--from',
+ '@acme/weight-icons',
+ ];
+
+ beforeEach(() => {
+ // A root barrel of default re-exports, and one file per export.
+ const lib = path.join(pkg, 'node_modules', '@acme', 'weight-icons');
+ fs.mkdirSync(path.join(lib, 'dist'), {recursive: true});
+ fs.writeFileSync(
+ path.join(lib, 'package.json'),
+ JSON.stringify({
+ name: '@acme/weight-icons',
+ version: '3.1.0',
+ type: 'module',
+ exports: {'.': './dist/index.js', './dist/*': './dist/*.js'},
+ }),
+ );
+ /** @type {string[]} */
+ const barrel = [];
+ for (const glyph of glyphs) {
+ for (const look of looks) {
+ const file = fileOf(glyph, look);
+ fs.writeFileSync(
+ path.join(lib, 'dist', `${file}.js`),
+ `export default function ${file}(props) { return null; }\n`,
+ );
+ barrel.push(`export {default as ${file}} from './${file}.js';`);
+ }
+ }
+ fs.writeFileSync(
+ path.join(lib, 'dist', 'index.js'),
+ `${barrel.join('\n')}\n`,
+ );
+ const manifest = path.join(pkg, 'package.json');
+ const pkgJson = JSON.parse(fs.readFileSync(manifest, 'utf-8'));
+ pkgJson.dependencies['@acme/weight-icons'] = '^3.1.0';
+ fs.writeFileSync(manifest, JSON.stringify(pkgJson, null, 2));
+ });
+
+ it('moves each per-file icon to the root import, keeps its id, export, map entries, variants and words, and lists the moves', async () => {
+ const created = await json([
+ 'experimental',
+ 'icon',
+ 'new-set',
+ 'weights',
+ '--variants',
+ 'outline,filled',
+ '--default-variant',
+ 'outline',
+ ]);
+ expect(created.code, JSON.stringify(created.body)).toBe(0);
+ for (const [name, glyph, definition] of [
+ ['XIcon', 'X', 'close'],
+ ['SearchIcon', 'Search', 'search'],
+ ]) {
+ const added = await json([
+ 'experimental',
+ 'icon',
+ 'add',
+ name,
+ '--from',
+ subpath(fileOf(glyph, 'Outline')),
+ '--default',
+ '--definition',
+ definition,
+ ]);
+ expect(added.code, JSON.stringify(added.body)).toBe(0);
+ }
+ const variant = await json([
+ 'experimental',
+ 'icon',
+ 'add',
+ 'XIcon',
+ '--variant',
+ 'filled',
+ '--from',
+ subpath(fileOf('X', 'Filled')),
+ '--default',
+ ]);
+ expect(variant.code, JSON.stringify(variant.body)).toBe(0);
+ const set = path.join(pkg, 'icon-sets', 'weights');
+ const before = dataOf('weights');
+ const byId = (/** @type {any} */ data, /** @type {string} */ id) =>
+ data.icons.find((/** @type {{id: string}} */ each) => each.id === id);
+ // An author's own words stay with the icon.
+ before.icons = before.icons.map((/** @type {any} */ icon) =>
+ icon.id === 'x' ? {...icon, words: [...icon.words, 'dismiss']} : icon,
+ );
+ fs.writeFileSync(
+ path.join(set, 'weights.icons.json'),
+ `${JSON.stringify(before, null, 2)}\n`,
+ );
+
+ const refreshed = await json([
+ 'experimental',
+ 'icon',
+ 'new-set',
+ 'weights',
+ '--from',
+ '@acme/weight-icons',
+ ]);
+ expect(refreshed.code, JSON.stringify(refreshed.body)).toBe(0);
+ expect(refreshed.body.data.moved).toEqual([
+ {
+ id: 'search',
+ from: subpath(fileOf('Search', 'Outline')),
+ to: '@acme/weight-icons',
+ },
+ {
+ id: 'x',
+ from: subpath(fileOf('X', 'Outline')),
+ to: '@acme/weight-icons',
+ },
+ ]);
+ expect(refreshed.body.data.notes.join('\n')).toContain(
+ '2 icons now import from @acme/weight-icons instead of one file each, and keep their ids, exports, map entries, variants, and words: search, x.',
+ );
+ const after = dataOf('weights');
+ const ids = after.icons.map((/** @type {{id: string}} */ each) => each.id);
+ // One icon per glyph: the root's other glyphs come in, nothing is doubled.
+ expect(ids.sort()).toEqual(glyphs.map(kebab).sort());
+ expect(byId(after, 'x')).toMatchObject({
+ export: 'XIcon',
+ variants: [
+ {variant: 'filled', export: byId(before, 'x').variants[0].export},
+ ],
+ });
+ expect(byId(after, 'x').words).toContain('dismiss');
+ expect(byId(after, 'search').export).toBe('SearchIcon');
+ expect(after.map).toMatchObject({close: 'x', search: 'search'});
+ const generated = fs.readFileSync(
+ path.join(set, 'weights.generated.js'),
+ 'utf-8',
+ );
+ // One import style: every icon and variant reads the library root.
+ expect(generated).not.toContain('@acme/weight-icons/dist/');
+ expect(generated).toContain(
+ `export {${fileOf('X', 'Outline')} as XIcon} from '@acme/weight-icons';`,
+ );
+ expect(generated).toContain(
+ `export {${fileOf('X', 'Filled')} as ${byId(before, 'x').variants[0].export}} from '@acme/weight-icons';`,
+ );
+ fs.writeFileSync(
+ path.join(pkg, 'index.js'),
+ "export * from './icon-sets/weights/weights.generated.js';\n",
+ );
+ const strict = await runCli(
+ ['integration', 'check', '--strict', '--json'],
+ pkg,
+ );
+ const checked = JSON.parse(strict.stdout).data;
+ // The library ships no license file, so the author adds a NOTICE.
+ expect(JSON.stringify(checked)).toContain('icon_license_notice_missing');
+ fs.writeFileSync(
+ path.join(set, 'NOTICE'),
+ 'Icons from @acme/weight-icons 3.1.0, MIT License.\n',
+ );
+ const passed = JSON.parse(
+ (await runCli(['integration', 'check', '--strict', '--json'], pkg))
+ .stdout,
+ ).data;
+ // The fixture has no TypeScript, so only that skipped work remains.
+ expect(
+ passed.failures.filter(
+ (/** @type {{code: string}} */ each) =>
+ each.code !== 'doc_types_skipped',
+ ),
+ ).toEqual([]);
+ expect(passed.warnings).toBe(0);
+ await expectStableRefreshes('weights', weightsRefreshArgs);
+ });
+
+ const weightSet = () => path.join(pkg, 'icon-sets', 'weights');
+ const weightsGenerated = () =>
+ fs.readFileSync(path.join(weightSet(), 'weights.generated.js'), 'utf-8');
+ /**
+ * A new `weights` set, then each `add` and `map` run, then the entry and
+ * the NOTICE the strict check asks for.
+ * @param {string[][]} runs
+ */
+ const weightsWith = async runs => {
+ const created = await json([
+ 'experimental',
+ 'icon',
+ 'new-set',
+ 'weights',
+ '--variants',
+ 'outline,filled',
+ '--default-variant',
+ 'outline',
+ ]);
+ expect(created.code, JSON.stringify(created.body)).toBe(0);
+ for (const run of runs) {
+ const done = await json(['experimental', 'icon', ...run]);
+ expect(done.code, `${run.join(' ')}: ${JSON.stringify(done.body)}`).toBe(
+ 0,
+ );
+ }
+ fs.writeFileSync(
+ path.join(pkg, 'index.js'),
+ "export * from './icon-sets/weights/weights.generated.js';\n",
+ );
+ fs.writeFileSync(
+ path.join(weightSet(), 'NOTICE'),
+ 'Icons from @acme/weight-icons 3.1.0, MIT License.\n',
+ );
+ };
+ const refreshWeights = () => json(weightsRefreshArgs);
+ /** The strict check's failures, without the skipped TypeScript work. */
+ const strictWeights = async () => {
+ const res = await runCli(
+ ['integration', 'check', '--strict', '--json'],
+ pkg,
+ );
+ const checked = JSON.parse(res.stdout).data;
+ return checked.failures
+ .filter(
+ (/** @type {{code: string}} */ each) =>
+ each.code !== 'doc_types_skipped',
+ )
+ .map(
+ (/** @type {{code: string, message: string}} */ each) =>
+ `${each.code}: ${each.message}`,
+ );
+ };
+ /**
+ * The data file's exports (icons and variants) and the generated module's
+ * exports, each sorted.
+ */
+ const weightsExports = () => {
+ const data = dataOf('weights');
+ const listed = data.icons
+ .flatMap((/** @type {any} */ icon) => [
+ icon.export,
+ ...(icon.variants ?? []).map((/** @type {any} */ each) => each.export),
+ ])
+ .sort();
+ const written = [
+ ...weightsGenerated().matchAll(/^export \{(?:\w+ as )?(\w+)\} from /gmu),
+ ]
+ .map(match => match[1])
+ .sort();
+ return {listed, written};
+ };
+ /** @param {string} id */
+ const weightIcon = id =>
+ dataOf('weights').icons.find(
+ (/** @type {{id: string}} */ each) => each.id === id,
+ );
+
+ it('keeps the id and export of a moved icon whose id is not the root glyph id, and its map entry', async () => {
+ await weightsWith([
+ [
+ 'add',
+ 'DismissIcon',
+ '--from',
+ subpath(fileOf('X', 'Outline')),
+ '--default',
+ '--definition',
+ 'close',
+ ],
+ ]);
+ const before = weightIcon('dismiss');
+ expect(before).toMatchObject({export: 'DismissIcon'});
+
+ const refreshed = await refreshWeights();
+ expect(refreshed.code, JSON.stringify(refreshed.body)).toBe(0);
+ expect(refreshed.body.data.renamed).toBeUndefined();
+ expect(refreshed.body.data.moved).toEqual([
+ {
+ id: 'dismiss',
+ from: subpath(fileOf('X', 'Outline')),
+ to: '@acme/weight-icons',
+ },
+ ]);
+ expect(weightIcon('dismiss')).toMatchObject({
+ export: 'DismissIcon',
+ words: before.words,
+ });
+ expect(weightIcon('x-outline-24-wght500')).toBeUndefined();
+ expect(weightIcon('x')).toBeUndefined();
+ expect(dataOf('weights').map.close).toBe('dismiss');
+ expect(weightsGenerated()).toContain(
+ `export {${fileOf('X', 'Outline')} as DismissIcon} from '@acme/weight-icons';`,
+ );
+ const {listed, written} = weightsExports();
+ expect(written).toEqual(listed);
+ expect(await strictWeights()).toEqual([]);
+ await expectStableRefreshes('weights', weightsRefreshArgs);
+ });
+
+ it('moves a moved icon to a new default look with the other glyphs, and keeps its id and export', async () => {
+ await weightsWith([
+ [
+ 'add',
+ 'DismissIcon',
+ '--from',
+ subpath(fileOf('Search', 'Outline')),
+ '--default',
+ '--definition',
+ 'search',
+ ],
+ [
+ 'add',
+ fileOf('Clock', 'Outline'),
+ '--from',
+ '@acme/weight-icons',
+ '--id',
+ 'clock',
+ '--definition',
+ 'clock',
+ ],
+ [
+ 'add',
+ 'XIcon',
+ '--from',
+ subpath(fileOf('X', 'Outline')),
+ '--default',
+ '--definition',
+ 'close',
+ ],
+ ]);
+ const refreshed = await json([
+ 'experimental',
+ 'icon',
+ 'new-set',
+ 'weights',
+ '--from',
+ '@acme/weight-icons',
+ '--variants',
+ 'filled,outline',
+ '--default-variant',
+ 'filled',
+ ]);
+ expect(refreshed.code, JSON.stringify(refreshed.body)).toBe(0);
+ expect(refreshed.body.data.renamed).toBeUndefined();
+ expect(refreshed.body.data.moved).toEqual([
+ {
+ id: 'dismiss',
+ from: subpath(fileOf('Search', 'Outline')),
+ to: '@acme/weight-icons',
+ },
+ {
+ id: 'x',
+ from: subpath(fileOf('X', 'Outline')),
+ to: '@acme/weight-icons',
+ },
+ ]);
+ expect(weightIcon('x')).toMatchObject({export: 'XIcon'});
+ expect(weightIcon('dismiss')).toMatchObject({export: 'DismissIcon'});
+ expect(weightIcon('search')).toBeUndefined();
+ expect(dataOf('weights').map.close).toBe('x');
+ const generated = weightsGenerated();
+ expect(generated).toContain(
+ `export {${fileOf('X', 'Filled')} as XIcon} from '@acme/weight-icons';`,
+ );
+ expect(generated).not.toContain(fileOf('X', 'Outline'));
+ expect(generated).toContain(
+ `export {${fileOf('Search', 'Filled')} as DismissIcon} from '@acme/weight-icons';`,
+ );
+ expect(generated).toContain(
+ `export {${fileOf('Clock', 'Filled')} as ClockIcon} from '@acme/weight-icons';`,
+ );
+ expect(refreshed.body.data.notes.join('\n')).not.toMatch(
+ /no longer exports|Left out/u,
+ );
+ const {listed, written} = weightsExports();
+ expect(written).toEqual(listed);
+ expect(await strictWeights()).toEqual([]);
+ await expectStableRefreshes('weights', [
+ ...weightsRefreshArgs,
+ '--variants',
+ 'filled,outline',
+ '--default-variant',
+ 'filled',
+ ]);
+ });
+
+ it('leaves out a root glyph whose export a moved icon already has, and names it in the receipt', async () => {
+ await weightsWith([
+ [
+ 'add',
+ 'CloseIcon',
+ '--from',
+ subpath(fileOf('X', 'Outline')),
+ '--default',
+ '--definition',
+ 'close',
+ ],
+ ]);
+ expect(weightIcon('close')).toMatchObject({export: 'CloseIcon'});
+
+ const refreshed = await refreshWeights();
+ expect(refreshed.code, JSON.stringify(refreshed.body)).toBe(0);
+ expect(refreshed.body.data.moved).toEqual([
+ {
+ id: 'close',
+ from: subpath(fileOf('X', 'Outline')),
+ to: '@acme/weight-icons',
+ },
+ ]);
+ expect(weightIcon('close')).toMatchObject({export: 'CloseIcon'});
+ const generated = weightsGenerated();
+ expect(generated).toContain(
+ `export {${fileOf('X', 'Outline')} as CloseIcon} from '@acme/weight-icons';`,
+ );
+ expect(generated).not.toContain(`${fileOf('Close', 'Outline')} as`);
+ expect(refreshed.body.data.notes.join('\n')).toContain(
+ 'Left out 1 library icons whose id or name an icon of the set already has: close.',
+ );
+ const {listed, written} = weightsExports();
+ expect(written).toEqual(listed);
+ expect(await strictWeights()).toEqual([]);
+ await expectStableRefreshes('weights', weightsRefreshArgs);
+ });
+
+ it('moves each icon only through its own root export, skips a move another icon already holds, and keeps every export in use', async () => {
+ // A second file of the package that re-exports the Search glyph.
+ fs.writeFileSync(
+ path.join(
+ pkg,
+ 'node_modules',
+ '@acme',
+ 'weight-icons',
+ 'dist',
+ 'SearchAlt.js',
+ ),
+ `export {default} from './${fileOf('Search', 'Outline')}.js';\n`,
+ );
+ await weightsWith([
+ // Moves, and keeps an id the root glyph does not have.
+ [
+ 'add',
+ 'DismissIcon',
+ '--from',
+ subpath(fileOf('X', 'Outline')),
+ '--default',
+ '--definition',
+ 'close',
+ ],
+ // Moves, and has the id and export of the root's Close glyph.
+ [
+ 'add',
+ 'CloseIcon',
+ '--from',
+ subpath(fileOf('Search', 'Outline')),
+ '--default',
+ '--definition',
+ 'search',
+ ],
+ // Reads the root export the icon before it moves to: stays.
+ [
+ 'add',
+ 'SearchAltIcon',
+ '--from',
+ subpath('SearchAlt'),
+ '--default',
+ '--definition',
+ 'upload',
+ ],
+ // The root's own Clock glyph, read from the root.
+ [
+ 'add',
+ fileOf('Clock', 'Outline'),
+ '--from',
+ '@acme/weight-icons',
+ '--id',
+ 'clock',
+ '--definition',
+ 'clock',
+ ],
+ // Reads the root export the icon before it reads: stays.
+ [
+ 'add',
+ 'ClockAltIcon',
+ '--from',
+ subpath(fileOf('Clock', 'Outline')),
+ '--default',
+ '--definition',
+ 'stop',
+ ],
+ ]);
+ const before = dataOf('weights');
+ const exportOf = (/** @type {string} */ id) =>
+ before.icons.find((/** @type {{id: string}} */ each) => each.id === id)
+ .export;
+
+ const refreshed = await refreshWeights();
+ expect(refreshed.code, JSON.stringify(refreshed.body)).toBe(0);
+ expect(refreshed.body.data.renamed).toBeUndefined();
+ expect(refreshed.body.data.moved).toEqual([
+ {
+ id: 'close',
+ from: subpath(fileOf('Search', 'Outline')),
+ to: '@acme/weight-icons',
+ },
+ {
+ id: 'dismiss',
+ from: subpath(fileOf('X', 'Outline')),
+ to: '@acme/weight-icons',
+ },
+ ]);
+ for (const id of ['dismiss', 'close', 'search-alt', 'clock', 'clock-alt']) {
+ expect(weightIcon(id)?.export, id).toBe(exportOf(id));
+ }
+ const generated = weightsGenerated();
+ expect(generated).toContain(
+ `export {default as SearchAltIcon} from '${subpath('SearchAlt')}';`,
+ );
+ expect(generated).toContain(
+ `export {default as ClockAltIcon} from '${subpath(fileOf('Clock', 'Outline'))}';`,
+ );
+ expect(generated).toContain(
+ `export {${fileOf('Clock', 'Outline')} as ${exportOf('clock')}} from '@acme/weight-icons';`,
+ );
+ const notes = refreshed.body.data.notes.join('\n');
+ expect(notes).toContain(
+ 'Left out 1 library icons whose id or name an icon of the set already has: close.',
+ );
+ expect(notes).toContain(
+ '2 icons stay on their own file, because another icon of the set already reads the same export of @acme/weight-icons: clock-alt, search-alt.',
+ );
+ expect(notes).not.toMatch(/no longer exports/u);
+ const {listed, written} = weightsExports();
+ expect(written).toEqual(listed);
+ expect(await strictWeights()).toEqual([]);
+ await expectStableRefreshes('weights', weightsRefreshArgs);
+ });
+
+ const xFile = subpath(fileOf('X', 'Outline'));
+ const searchFile = subpath(fileOf('Search', 'Outline'));
+ /** @type {Array<[string, string[][]]>} */
+ const states = [
+ ['an empty set', []],
+ [
+ 'an icon read from the root, with an id the author chose',
+ [
+ [
+ 'add',
+ fileOf('X', 'Outline'),
+ '--from',
+ '@acme/weight-icons',
+ '--id',
+ 'dismiss',
+ '--definition',
+ 'close',
+ ],
+ ],
+ ],
+ [
+ 'an icon read from one file, with a variant read from another',
+ [
+ ['add', 'XIcon', '--from', xFile, '--default', '--definition', 'close'],
+ [
+ 'add',
+ 'XIcon',
+ '--variant',
+ 'filled',
+ '--from',
+ subpath(fileOf('X', 'Filled')),
+ '--default',
+ ],
+ ],
+ ],
+ [
+ 'an icon whose id is not the glyph id',
+ [
+ [
+ 'add',
+ 'DismissIcon',
+ '--from',
+ xFile,
+ '--default',
+ '--definition',
+ 'close',
+ ],
+ ],
+ ],
+ [
+ 'an icon with the id and export of another root glyph',
+ [
+ [
+ 'add',
+ 'CloseIcon',
+ '--from',
+ xFile,
+ '--default',
+ '--definition',
+ 'close',
+ ],
+ ],
+ ],
+ [
+ "two icons whose ids name each other's glyphs",
+ [
+ [
+ 'add',
+ 'CloseIcon',
+ '--from',
+ searchFile,
+ '--default',
+ '--definition',
+ 'close',
+ ],
+ [
+ 'add',
+ 'SearchIcon',
+ '--from',
+ xFile,
+ '--default',
+ '--definition',
+ 'search',
+ ],
+ ],
+ ],
+ [
+ 'two icons of the same file',
+ [
+ [
+ 'add',
+ 'DismissIcon',
+ '--from',
+ xFile,
+ '--default',
+ '--definition',
+ 'close',
+ ],
+ ['add', 'XIcon', '--from', xFile, '--default', '--definition', 'error'],
+ ],
+ ],
+ ];
+
+ it.each(states)(
+ 'refreshing twice writes what refreshing once wrote: %s',
+ async (_, runs) => {
+ await weightsWith(runs);
+ const first = await refreshWeights();
+ expect(first.code, JSON.stringify(first.body)).toBe(0);
+ const {listed, written} = weightsExports();
+ expect(written).toEqual(listed);
+ await expectStableRefreshes('weights', weightsRefreshArgs);
+ },
+ );
+});
+
+describe('a refresh from a library root keeps what it does not rewrite', () => {
+ const lib = () => path.join(pkg, 'node_modules', '@acme', 'glyph-library');
+ /** @param {Record<string, string>} more */
+ const addExports = more => {
+ const file = path.join(lib(), 'package.json');
+ const pkgJson = JSON.parse(fs.readFileSync(file, 'utf-8'));
+ fs.writeFileSync(
+ file,
+ JSON.stringify({...pkgJson, exports: {...pkgJson.exports, ...more}}),
+ );
+ };
+ const rootArgs = [
+ 'experimental',
+ 'icon',
+ 'new-set',
+ 'outline',
+ '--from',
+ '@acme/glyph-library',
+ ];
+ const generatedFile = () =>
+ path.join(pkg, 'icon-sets', 'outline', 'outline.generated.js');
+ /** The strict check's findings, by code and message. */
+ const strictCheck = async () => {
+ const res = await runCli(
+ ['integration', 'check', '--strict', '--json'],
+ pkg,
+ );
+ const {failures} = JSON.parse(res.stdout).data;
+ return failures.map(
+ (/** @type {{code: string, message: string}} */ each) =>
+ `${each.code}: ${each.message}`,
+ );
+ };
+
+ beforeEach(() => {
+ fs.writeFileSync(
+ path.join(pkg, 'index.js'),
+ "export * from './icon-sets/outline/outline.generated.js';\n",
+ );
+ });
+
+ it('keeps a look variant on its subpath when the subpath export has the same name as a root export but is another file', async () => {
+ // The solid subpath exports the root's names, with other artwork.
+ addExports({'./solid': './solid/index.js'});
+ fs.mkdirSync(path.join(lib(), 'solid'), {recursive: true});
+ fs.writeFileSync(
+ path.join(lib(), 'solid', 'index.js'),
+ "export {Bin} from './bin.js';\nexport {Cross} from './cross.js';\n",
+ );
+ fs.writeFileSync(
+ path.join(lib(), 'solid', 'bin.js'),
+ 'export function Bin(props) { return null; }\n',
+ );
+ fs.writeFileSync(
+ path.join(lib(), 'solid', 'cross.js'),
+ 'export const Cross = props => null;\n',
+ );
+ expect(
+ (await json([...rootArgs, '--variants', 'outline,solid'])).code,
+ ).toBe(0);
+ const added = await json([
+ 'experimental',
+ 'icon',
+ 'add',
+ '--variant',
+ 'solid',
+ '--from',
+ '@acme/glyph-library/solid',
+ '--all',
+ ]);
+ expect(added.code, JSON.stringify(added.body)).toBe(0);
+ expect(added.body.data).toMatchObject({added: 2});
+ fs.writeFileSync(path.join(pkg, 'NOTICE'), 'MIT License.\n');
+ const before = fs.readFileSync(generatedFile(), 'utf-8');
+ const solidLines = before
+ .split('\n')
+ .filter(line => line.includes("'@acme/glyph-library/solid'"));
+ expect(solidLines).toHaveLength(2);
+ const checkedBefore = await strictCheck();
+
+ const refreshed = await json(rootArgs);
+ expect(refreshed.code, JSON.stringify(refreshed.body)).toBe(0);
+ expect(refreshed.body.data.moved).toBeUndefined();
+ const after = fs.readFileSync(generatedFile(), 'utf-8');
+ for (const line of solidLines) expect(after).toContain(line);
+ expect(after).not.toMatch(/SolidIcon\} from '@acme\/glyph-library'/u);
+ const variants = dataOf('outline').icons.map(
+ (/** @type {{id: string, variants?: unknown[]}} */ each) => [
+ each.id,
+ each.variants,
+ ],
+ );
+ expect(variants).toEqual(
+ expect.arrayContaining([
+ ['bin', [{variant: 'solid', export: 'BinSolidIcon'}]],
+ ['cross', [{variant: 'solid', export: 'CrossSolidIcon'}]],
+ ]),
+ );
+ const checkedAfter = await strictCheck();
+ expect(checkedAfter).toEqual(checkedBefore);
+ expect(checkedAfter.join('\n')).not.toMatch(
+ /icon_export_missing|icon_variant/u,
+ );
+ });
+
+ it('keeps the variant export of an icon it does not supply when that variant reads a file the root exports', async () => {
+ // A subpath to the same file as the root's Cross.
+ addExports({'./cross': './icons/cross.js'});
+ expect(
+ (await json([...rootArgs, '--variants', 'outline,solid'])).code,
+ ).toBe(0);
+ fs.mkdirSync(path.join(pkg, 'art'), {recursive: true});
+ fs.writeFileSync(
+ path.join(pkg, 'art', 'spark.js'),
+ 'export const Spark = props => null;\n',
+ );
+ for (const add of [
+ ['Spark', '--from', './art/spark.js', '--definition', 'sparkles'],
+ [
+ 'Cross',
+ '--from',
+ '@acme/glyph-library/cross',
+ '--id',
+ 'spark',
+ '--variant',
+ 'solid',
+ ],
+ ]) {
+ const added = await json(['experimental', 'icon', 'add', ...add]);
+ expect(added.code, JSON.stringify(added.body)).toBe(0);
+ }
+ fs.writeFileSync(path.join(pkg, 'NOTICE'), 'MIT License.\n');
+ const before = fs.readFileSync(generatedFile(), 'utf-8');
+ const variantLine = before
+ .split('\n')
+ .find(line => line.includes("'@acme/glyph-library/cross'"));
+ expect(variantLine).toBeTruthy();
+ const checkedBefore = await strictCheck();
+
+ const refreshed = await json(rootArgs);
+ expect(refreshed.code, JSON.stringify(refreshed.body)).toBe(0);
+ const spark = dataOf('outline').icons.find(
+ (/** @type {{id: string}} */ each) => each.id === 'spark',
+ );
+ expect(spark.variants).toEqual([
+ {variant: 'solid', export: expect.any(String)},
+ ]);
+ const after = fs.readFileSync(generatedFile(), 'utf-8');
+ // The data file and the module agree: the variant keeps its export.
+ expect(after).toContain(/** @type {string} */ (variantLine));
+ expect(after).toContain(spark.variants[0].export);
+ const checkedAfter = await strictCheck();
+ expect(checkedAfter).toEqual(checkedBefore);
+ expect(checkedAfter.join('\n')).not.toContain('icon_export_missing');
+ });
+
+ it('keeps a root icon and an icon from a subpath of the same export: neither export leaves the module', async () => {
+ // A subpath whose export re-exports the root's Cross under another name.
+ addExports({'./cross-alt': './alt/cross.js'});
+ fs.mkdirSync(path.join(lib(), 'alt'), {recursive: true});
+ fs.writeFileSync(
+ path.join(lib(), 'alt', 'cross.js'),
+ "export {Cross as CrossAlt} from '../icons/cross.js';\n",
+ );
+ expect((await json(rootArgs)).code).toBe(0);
+ const added = await json([
+ 'experimental',
+ 'icon',
+ 'add',
+ 'CrossAlt',
+ '--from',
+ '@acme/glyph-library/cross-alt',
+ '--definition',
+ 'error',
+ ]);
+ expect(added.code, JSON.stringify(added.body)).toBe(0);
+ fs.writeFileSync(path.join(pkg, 'NOTICE'), 'MIT License.\n');
+ const before = dataOf('outline');
+ const exportOf = (/** @type {any} */ data, /** @type {string} */ id) =>
+ data.icons.find((/** @type {{id: string}} */ each) => each.id === id)
+ ?.export;
+ expect(exportOf(before, 'cross')).toBe('CrossIcon');
+ expect(exportOf(before, 'cross-alt')).toBe('CrossAltIcon');
+ const checkedBefore = await strictCheck();
+
+ const refreshed = await json(rootArgs);
+ expect(refreshed.code, JSON.stringify(refreshed.body)).toBe(0);
+ const generated = fs.readFileSync(generatedFile(), 'utf-8');
+ expect(generated).toContain(
+ "export {Cross as CrossIcon} from '@acme/glyph-library';",
+ );
+ expect(generated).toContain(
+ "export {CrossAlt as CrossAltIcon} from '@acme/glyph-library/cross-alt';",
+ );
+ const notes = refreshed.body.data.notes.join('\n');
+ expect(notes).not.toMatch(/no longer exports/u);
+ const after = dataOf('outline');
+ expect(exportOf(after, 'cross')).toBe('CrossIcon');
+ expect(exportOf(after, 'cross-alt')).toBe('CrossAltIcon');
+ expect(refreshed.body.data.moved).toBeUndefined();
+ expect(notes).toContain(
+ '1 icons stay on their own file, because another icon of the set already reads the same export of @acme/glyph-library: cross-alt.',
+ );
+ expect(await strictCheck()).toEqual(checkedBefore);
+ await expectStableRefreshes('outline', rootArgs);
+ });
+
+ it('keeps the id of an icon of one file that moves to the root, on every refresh, and leaves out the root glyph another icon of the same file would take', async () => {
+ addExports({
+ './cross': './icons/cross.js',
+ './cross-alt': './alt/cross.js',
+ });
+ fs.mkdirSync(path.join(lib(), 'alt'), {recursive: true});
+ fs.writeFileSync(
+ path.join(lib(), 'alt', 'cross.js'),
+ "export {Cross as CrossAlt} from '../icons/cross.js';\n",
+ );
+ expect(
+ (await json(['experimental', 'icon', 'new-set', 'outline'])).code,
+ ).toBe(0);
+ for (const add of [
+ [
+ 'Cross',
+ '--from',
+ '@acme/glyph-library/cross',
+ '--id',
+ 'dismiss',
+ '--definition',
+ 'close',
+ ],
+ [
+ 'CrossAlt',
+ '--from',
+ '@acme/glyph-library/cross-alt',
+ '--definition',
+ 'error',
+ ],
+ ]) {
+ const added = await json(['experimental', 'icon', 'add', ...add]);
+ expect(added.code, JSON.stringify(added.body)).toBe(0);
+ }
+ fs.writeFileSync(path.join(pkg, 'NOTICE'), 'MIT License.\n');
+ const before = dataOf('outline');
+ const exportOf = (/** @type {any} */ data, /** @type {string} */ id) =>
+ data.icons.find((/** @type {{id: string}} */ each) => each.id === id)
+ ?.export;
+
+ const refreshed = await json(rootArgs);
+ expect(refreshed.code, JSON.stringify(refreshed.body)).toBe(0);
+ expect(refreshed.body.data.moved).toEqual([
+ {
+ id: 'dismiss',
+ from: '@acme/glyph-library/cross',
+ to: '@acme/glyph-library',
+ },
+ ]);
+ const after = dataOf('outline');
+ expect(exportOf(after, 'dismiss')).toBe(exportOf(before, 'dismiss'));
+ expect(exportOf(after, 'cross-alt')).toBe(exportOf(before, 'cross-alt'));
+ expect(exportOf(after, 'cross')).toBeUndefined();
+ expect(after.map).toMatchObject({close: 'dismiss', error: 'cross-alt'});
+ await expectStableRefreshes('outline', rootArgs);
+ });
+
+ it('a LICENSE directory at the package root is no notice: the receipt asks for one and the check warns', async () => {
+ fs.mkdirSync(path.join(pkg, 'LICENSE'));
+ fs.writeFileSync(path.join(pkg, 'LICENSE', 'MIT.txt'), 'MIT License.\n');
+ const created = await json(rootArgs);
+ expect(created.code, JSON.stringify(created.body)).toBe(0);
+ expect(created.body.data.licenseNoticeMissing).toEqual({
+ library: '@acme/[email protected]',
+ path: 'icon-sets/outline/NOTICE',
+ });
+ expect((await strictCheck()).join('\n')).toContain(
+ 'icon_license_notice_missing',
+ );
+ // A file at the root satisfies both.
+ fs.writeFileSync(path.join(pkg, 'LICENSE.md'), 'MIT License.\n');
+ const again = await json(rootArgs);
+ expect(again.body.data.licenseNoticeMissing).toBeUndefined();
+ expect((await strictCheck()).join('\n')).not.toContain(
+ 'icon_license_notice_missing',
+ );
+ });
+});
diff --git a/packages/cli/foundation/discovery/icon-set-checks.mjs b/packages/cli/foundation/discovery/icon-set-checks.mjs
index a67def470a..c347ac4053 100644
--- a/packages/cli/foundation/discovery/icon-set-checks.mjs
+++ b/packages/cli/foundation/discovery/icon-set-checks.mjs
@@ -44,8 +44,9 @@ import * as path from 'node:path';
import {findInstalledPackage} from '../fs/paths.mjs';
import {satisfiesRange} from '../env/semver.mjs';
import {
- NOTICE_FILE_RE,
discoverIconSetDirectory,
+ hasLicenseNotice,
+ licenseNoticeFix,
resolveIconModule,
splitSpecifier,
} from './icon-set-discovery.mjs';
@@ -1003,14 +1004,11 @@ function checkUpstream(set, packageDir, pkg) {
),
);
}
- const rootNotices = safeList(packageDir).filter(name =>
- NOTICE_FILE_RE.test(name),
- );
- if (set.notices.length === 0 && rootNotices.length === 0) {
+ if (!hasLicenseNotice(set.dir) && !hasLicenseNotice(packageDir)) {
issues.push(
issueWarning(
ICON_LICENSE_NOTICE_MISSING,
- `${label} is generated from ${source.package} but ships no license notice. Copy the library's LICENSE (and NOTICE, if any) into the set directory or the package root.`,
+ `${label} is generated from ${source.package}@${source.version} but ships no license notice. ${licenseNoticeFix(path.relative(packageDir, set.dir).split(path.sep).join('/'), `${source.package}@${source.version}`)} If the library ships a LICENSE or NOTICE file, copy that file there instead.`,
),
);
}
@@ -1026,12 +1024,3 @@ function safeSatisfies(version, range) {
return true;
}
}
-
-/** @param {string} dir */
-function safeList(dir) {
- try {
- return fs.readdirSync(dir);
- } catch {
- return [];
- }
-}
diff --git a/packages/cli/foundation/discovery/icon-set-checks.test.mjs b/packages/cli/foundation/discovery/icon-set-checks.test.mjs
index 167cd717a7..00fd29e767 100644
--- a/packages/cli/foundation/discovery/icon-set-checks.test.mjs
+++ b/packages/cli/foundation/discovery/icon-set-checks.test.mjs
@@ -632,13 +632,61 @@ describe('iconSetIssues', () => {
expect(withUpstream('1.2.0')).toEqual([]);
});
- it('no license notice for a set with an upstream warns', () => {
- expect(withUpstream('1.2.0', false)).toEqual([
+ it('no license notice for a set with an upstream warns, and names the NOTICE file to add and every name that counts', () => {
+ const issues = withUpstream('1.2.0', false);
+ expect(issues).toEqual([
expect.objectContaining({
code: 'icon_license_notice_missing',
severity: 'warning',
}),
]);
+ expect(issues[0].message).toContain(
+ 'Add a NOTICE (or LICENSE) file to icon-sets/glyphs that names [email protected] and its license: `icon-sets/glyphs/NOTICE`.',
+ );
+ expect(issues[0].message).toContain(
+ 'A file named LICENSE, LICENCE, NOTICE, or COPYING, in any case and with an optional suffix such as NOTICE.md or LICENSE-MIT, counts in the set directory or the package root.',
+ );
+ });
+
+ it('each file name the message lists silences the warning', () => {
+ expect(withUpstream('1.2.0', false)).toHaveLength(1);
+ const recheck = () =>
+ iconSetIssues(
+ dir,
+ {name: '@acme/glyphs', iconSets: path.join(dir, 'icon-sets')},
+ new Map(),
+ ).filter(issue => !COVERAGE.has(issue.code));
+ for (const name of [
+ 'NOTICE',
+ 'notice.md',
+ 'LICENSE',
+ 'LICENCE.txt',
+ 'COPYING',
+ 'LICENSE-MIT',
+ ]) {
+ const file = path.join(dir, 'icon-sets', 'glyphs', name);
+ fs.writeFileSync(file, 'x\n');
+ expect(recheck(), name).toEqual([]);
+ fs.rmSync(file);
+ }
+ expect(recheck()).toHaveLength(1);
+ });
+
+ it('a directory named LICENSE counts in neither the set directory nor the package root', () => {
+ expect(withUpstream('1.2.0', false)).toHaveLength(1);
+ const recheck = () =>
+ iconSetIssues(
+ dir,
+ {name: '@acme/glyphs', iconSets: path.join(dir, 'icon-sets')},
+ new Map(),
+ ).filter(issue => !COVERAGE.has(issue.code));
+ for (const where of [dir, path.join(dir, 'icon-sets', 'glyphs')]) {
+ fs.mkdirSync(path.join(where, 'LICENSE'));
+ fs.mkdirSync(path.join(where, 'NOTICE.d'));
+ }
+ expect(recheck()).toEqual([
+ expect.objectContaining({code: 'icon_license_notice_missing'}),
+ ]);
});
});
});
diff --git a/packages/cli/foundation/discovery/icon-set-discovery.mjs b/packages/cli/foundation/discovery/icon-set-discovery.mjs
index 876474d6f0..0c98c14db9 100644
--- a/packages/cli/foundation/discovery/icon-set-discovery.mjs
+++ b/packages/cli/foundation/discovery/icon-set-discovery.mjs
@@ -43,6 +43,31 @@ const SET_NAME_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;
/** A license or notice file a set ships beside its data (FR15). */
export const NOTICE_FILE_RE = /^(?:licen[cs]e|notice|copying)(?:[.-].*)?$/iu;
+/**
+ * What to add when a set wraps a library and has no license notice: a
+ * NOTICE file in the set directory, with the file names that count. The
+ * CLI never writes it, because the license text is the author's to state.
+ * @param {string} setDir the set directory, from the package root
+ * @param {string} library the library as `name@version`
+ */
+export function licenseNoticeFix(setDir, library) {
+ return `Add a NOTICE (or LICENSE) file to ${setDir} that names ${library} and its license: \`${setDir}/NOTICE\`. A file named LICENSE, LICENCE, NOTICE, or COPYING, in any case and with an optional suffix such as NOTICE.md or LICENSE-MIT, counts in the set directory or the package root.`;
+}
+
+/**
+ * Whether a directory has a license or notice file ({@link NOTICE_FILE_RE}).
+ * @param {string} dir
+ */
+export function hasLicenseNotice(dir) {
+ try {
+ return fs
+ .readdirSync(dir, {withFileTypes: true})
+ .some(file => file.isFile() && NOTICE_FILE_RE.test(file.name));
+ } catch {
+ return false;
+ }
+}
+
/**
* One installed icon set: its descriptor, its data, and where it came from.
* @typedef {object} DiscoveredIconSet
diff --git a/packages/cli/foundation/discovery/icon-set-writer.mjs b/packages/cli/foundation/discovery/icon-set-writer.mjs
index 28957097b9..b98fa05e30 100644
--- a/packages/cli/foundation/discovery/icon-set-writer.mjs
+++ b/packages/cli/foundation/discovery/icon-set-writer.mjs
@@ -1898,6 +1898,63 @@ export function iconModulePackage(specifier) {
return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
}
+/**
+ * The set's exports that read one file of a package, where a refresh from
+ * that package's root can read them from the root instead. An export moves
+ * when the root exports the same icon: an export that resolves to the same
+ * file and binding. When the subpath export cannot be resolved, a root
+ * export of the same name counts. Each maps to the root's
+ * export and the module it reads now. Empty unless `root` is a package
+ * root, not a subpath or a ./ path.
+ * @param {Map<string, {module: string, source: string}>} origins the
+ * set's exports ({@link generatedOrigins})
+ * @param {{file: string, module: string}} root the refreshed module
+ * @param {string[]} rootExports the root's icon exports
+ * @param {{packageDir: string, pkg: Record<string, any>}} where
+ * @returns {Map<string, {source: string, from: string}>}
+ */
+export function packageRootMoves(origins, root, rootExports, where) {
+ /** @type {Map<string, {source: string, from: string}>} */
+ const moves = new Map();
+ if (iconModulePackage(root.module) !== root.module) return moves;
+ if (root.module.startsWith('.')) return moves;
+ const subpaths = [...origins].filter(
+ ([, origin]) =>
+ !origin.module.startsWith('.') &&
+ origin.module !== root.module &&
+ iconModulePackage(origin.module) === root.module,
+ );
+ if (subpaths.length === 0) return moves;
+ /** @param {{file: string, name: string}} origin */
+ const keyOf = origin => `${origin.file}\0${origin.name}`;
+ /** @type {Map<string, string>} */
+ const byOrigin = new Map();
+ for (const name of rootExports) {
+ const origin = moduleExportOrigin(root.file, name);
+ if (origin && !byOrigin.has(keyOf(origin))) {
+ byOrigin.set(keyOf(origin), name);
+ }
+ }
+ const names = new Set(rootExports);
+ const self = {
+ name: typeof where.pkg.name === 'string' ? where.pkg.name : '',
+ dir: where.packageDir,
+ };
+ for (const [name, origin] of subpaths) {
+ const file = resolveIconModule(origin.module, where.packageDir, self);
+ const resolved = file ? moduleExportOrigin(file, origin.source) : null;
+ // A name match counts only when the subpath export cannot be resolved.
+ // A resolved export is the same icon only when it reads the same file.
+ const source = resolved
+ ? byOrigin.get(keyOf(resolved))
+ : names.has(origin.source)
+ ? origin.source
+ : undefined;
+ if (source) moves.set(name, {source, from: origin.module});
+ }
+ return moves;
+}
+
/**
* Write the set's generated module and its declaration file
* ({@link generatedModuleText}). Returns whether either changed, and a
diff --git a/packages/cli/foundation/discovery/icon-set-writer.test.mjs b/packages/cli/foundation/discovery/icon-set-writer.test.mjs
index 0c2140de8a..d8c63ef7dd 100644
--- a/packages/cli/foundation/discovery/icon-set-writer.test.mjs
+++ b/packages/cli/foundation/discovery/icon-set-writer.test.mjs
@@ -10,6 +10,7 @@ import {
entryWiringNote,
generatedModuleText,
iconIdOf,
+ packageRootMoves,
} from './icon-set-writer.mjs';
describe('iconIdOf', () => {
@@ -102,3 +103,61 @@ describe('entryWiringNote over a types file a formatter rewrote', () => {
}
});
});
+
+describe('packageRootMoves', () => {
+ it('moves an export to the root only when it reads the file the root exports; a name match counts only when the subpath does not resolve', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-root-moves-'));
+ try {
+ const lib = path.join(dir, 'node_modules', '@acme', 'glyphs');
+ fs.mkdirSync(path.join(lib, 'solid'), {recursive: true});
+ fs.writeFileSync(
+ path.join(lib, 'package.json'),
+ JSON.stringify({
+ name: '@acme/glyphs',
+ version: '1.0.0',
+ type: 'module',
+ exports: {
+ '.': './index.js',
+ './solid': './solid/index.js',
+ './bin': './bin.js',
+ './gone': './gone.js',
+ },
+ }),
+ );
+ fs.writeFileSync(
+ path.join(lib, 'index.js'),
+ "export {Bin as BinIcon} from './bin.js';\nexport {Cross} from './cross.js';\nexport {Star} from './star.js';\n",
+ );
+ fs.writeFileSync(path.join(lib, 'bin.js'), 'export const Bin = 1;\n');
+ fs.writeFileSync(path.join(lib, 'cross.js'), 'export const Cross = 1;\n');
+ fs.writeFileSync(path.join(lib, 'star.js'), 'export const Star = 1;\n');
+ fs.writeFileSync(
+ path.join(lib, 'solid', 'index.js'),
+ 'export const Cross = 2;\n',
+ );
+ const origins = new Map([
+ // The same file and binding, under another name: it moves.
+ ['BinOutlineIcon', {module: '@acme/glyphs/bin', source: 'Bin'}],
+ // The same name, but other artwork: it stays.
+ ['CrossSolidIcon', {module: '@acme/glyphs/solid', source: 'Cross'}],
+ // The subpath does not resolve, so the name decides.
+ ['StarIcon', {module: '@acme/glyphs/gone', source: 'Star'}],
+ // Not a subpath of this package.
+ ['SparkIcon', {module: './art/spark.js', source: 'Star'}],
+ ['OtherIcon', {module: '@acme/other/star', source: 'Star'}],
+ ]);
+ const moves = packageRootMoves(
+ origins,
+ {file: path.join(lib, 'index.js'), module: '@acme/glyphs'},
+ ['BinIcon', 'Cross', 'Star'],
+ {packageDir: dir, pkg: {name: '@acme/icons'}},
+ );
+ expect(Object.fromEntries(moves)).toEqual({
+ BinOutlineIcon: {source: 'BinIcon', from: '@acme/glyphs/bin'},
+ StarIcon: {source: 'Star', from: '@acme/glyphs/gone'},
+ });
+ } finally {
+ fs.rmSync(dir, {recursive: true, force: true});
+ }
+ });
+});