All files / packages/icons/scripts build.ts

0% Statements 0/218
0% Branches 0/42
0% Functions 0/35
0% Lines 0/212

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
/*
 * Builds the `@salesforce-ux/icons` distribution.
 *
 * For each icon type (standard, utility, action, doctype, custom) it copies the
 * source SVGs into dist, generates ltr/rtl sprite sheets, and rasterizes PNGs.
 * It then emits the published-contract JSON (`ui.icons.json` and per-category
 * `*-icons-metadata.json`) at the dist root and zips the SVG/PNG assets. Output
 * is kept byte-compatible with the legacy gulp build.
 */
import fs from 'node:fs/promises';
import path from 'node:path';
import { createWriteStream } from 'node:fs';
import { ZipArchive } from 'archiver';
import SVGSpriter from 'svg-sprite';
 
import type {
  BuildContext,
  IconType,
  IconTypeConfig,
  IconFile,
  SpriteSheetResult,
  UiIconsCategory,
  UiIconsEntry,
} from '../src/types.js';
 
// Dynamic import for Sharp to avoid TypeScript module resolution issues
const sharp = (await import('sharp')).default;
 
const ALL_ICON_TYPES: IconType[] = ['standard', 'utility', 'action', 'doctype', 'custom'];
const OUTPUT_ZIP_FILE_BASE = 'salesforce-lightning-design-system-icons';
const PNG_SIZE_SUFFIXES = [120, 60] as const;
const LEGACY_FILL_REGEX = /fill="#\S{3,6}"/g;
const LEGACY_UTILITY_FILL = 'fill="rgb(84, 105, 141)"';
const LEGACY_SPRITE_ROOT =
  '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">';
const LEGACY_SPRITE_ROOT_WITH_DISPLAY_NONE =
  '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" display="none">';
 
/* Logs a build progress line with a consistent `[icons-build]` prefix. */
function logStep(message: string): void {
  console.log(`[icons-build] ${message}`);
}
 
const ICON_TYPE_CONFIGS: Record<IconType, IconTypeConfig> = {
  standard: {
    type: 'standard',
    sourceDir: 'standard',
    distDir: 'standard',
    spriteFileName: 'symbols.svg',
    pngSize: 100,
  },
  utility: {
    type: 'utility',
    sourceDir: 'utility',
    distDir: 'utility',
    spriteFileName: 'symbols.svg',
    pngSize: 60,
  },
  action: {
    type: 'action',
    sourceDir: 'action',
    distDir: 'action',
    spriteFileName: 'symbols.svg',
    pngSize: 96,
  },
  doctype: {
    type: 'doctype',
    sourceDir: 'doctype',
    distDir: 'doctype',
    spriteFileName: 'symbols.svg',
    pngSize: 64,
  },
  custom: {
    type: 'custom',
    sourceDir: 'custom',
    distDir: 'custom',
    spriteFileName: 'symbols.svg',
    pngSize: 100,
  },
};
 
/*
 * Parses the icon types to build from CLI args. Returns all types when no
 * `--type=` flag is present; throws on an unrecognized type.
 */
function parseIconTypes(args: string[]): IconType[] {
  const typeArg = args.find((arg) => arg.startsWith('--type='));
  if (!typeArg) {
    return ALL_ICON_TYPES;
  }
 
  const requested = typeArg
    .replace('--type=', '')
    .split(',')
    .map((entry) => entry.trim())
    .filter(Boolean) as IconType[];
 
  for (const iconType of requested) {
    if (!(iconType in ICON_TYPE_CONFIGS)) {
      throw new Error(`Unsupported icon type: ${iconType}`);
    }
  }
 
  return requested;
}
 
/* Removes any previous dist output and recreates the dist + distRoot folders. */
async function cleanDist(context: BuildContext): Promise<void> {
  logStep(`clean: removing ${context.distDir}`);
  await fs.rm(context.distDir, { recursive: true, force: true });
  await fs.mkdir(context.distDir, { recursive: true });
  await fs.mkdir(context.distRoot, { recursive: true });
  logStep(`clean: created ${context.distDir}`);
}
 
/* Returns the absolute paths of every file under a directory, recursively. */
async function listFilesRecursive(dir: string): Promise<string[]> {
  const entries = await fs.readdir(dir, { withFileTypes: true });
  const paths = await Promise.all(
    entries.map(async (entry) => {
      const absolutePath = path.join(dir, entry.name);
      if (entry.isDirectory()) {
        return listFilesRecursive(absolutePath);
      }
      return absolutePath;
    }),
  );
 
  return paths.flat();
}
 
/*
 * Collects SVGs from the given subgroups (e.g. 'common', 'ltr') of an icon-type
 * directory into a symbol -> source-path map. Earlier groups win on conflict,
 * and missing group directories are skipped.
 */
async function listGroupSvgFiles(sourceTypeDir: string, groups: string[]): Promise<Map<string, string>> {
  const map = new Map<string, string>();
  for (const group of groups) {
    const groupDir = path.join(sourceTypeDir, group);
    let filesInGroup: string[] = [];
    try {
      filesInGroup = await listFilesRecursive(groupDir);
    } catch {
      continue;
    }
    for (const filePath of filesInGroup) {
      if (!filePath.endsWith('.svg')) {
        continue;
      }
      const symbol = normalizeSymbol(path.basename(filePath));
      if (!map.has(symbol)) {
        map.set(symbol, filePath);
      }
    }
  }
  return map;
}
 
/* Strips a trailing `.svg` extension to yield the bare symbol name. */
function normalizeSymbol(fileName: string): string {
  return fileName.replace(/\.svg$/i, '');
}
 
/*
 * Copies an icon type's source SVGs verbatim into the dist tree and returns an
 * IconFile descriptor for each symbol. Falls back to a flat directory scan when
 * the common/ltr group layout is absent.
 */
async function copySvgs(context: BuildContext, iconType: IconType): Promise<IconFile[]> {
  const config = ICON_TYPE_CONFIGS[iconType];
  const sourceTypeDir = path.join(context.sourceSvgDir, config.sourceDir);
  const distTypeDir = path.join(context.distRoot, config.distDir);
  let symbolToSource = await listGroupSvgFiles(sourceTypeDir, ['common', 'ltr']);
  if (symbolToSource.size === 0) {
    const sourceFiles = (await listFilesRecursive(sourceTypeDir)).filter((filePath) =>
      filePath.endsWith('.svg'),
    );
    symbolToSource = new Map(
      sourceFiles.map((filePath) => [normalizeSymbol(path.basename(filePath)), filePath]),
    );
  }
  logStep(`copySvgs:${iconType}: found ${symbolToSource.size} SVG files`);
 
  let copied = 0;
  for (const [symbol, sourcePath] of symbolToSource.entries()) {
    const targetPath = path.join(distTypeDir, `${symbol}.svg`);
    const svgContent = await fs.readFile(sourcePath, 'utf8');
 
    await fs.mkdir(path.dirname(targetPath), { recursive: true });
    await fs.writeFile(targetPath, svgContent, 'utf8');
    copied += 1;
  }
  logStep(`copySvgs:${iconType}: copied ${copied} SVG files`);
 
  return Array.from(symbolToSource.entries()).map(([symbol, sourcePath]) => ({
    type: iconType,
    fileName: `${symbol}.svg`,
    symbol,
    absolutePath: sourcePath,
    relativePath: `${symbol}.svg`,
  }));
}
 
/*
 * Builds the ltr (`symbols.svg`) and rtl (`symbols-rtl.svg`) sprite sheets for
 * an icon type via svg-sprite, applying legacy-compatible id/href and fill
 * rewrites, and writes them to the type's sprite output directory.
 */
async function generateSprites(
  context: BuildContext,
  iconType: IconType,
  icons: IconFile[],
): Promise<SpriteSheetResult> {
  const config = ICON_TYPE_CONFIGS[iconType];
  const spriteOutputDir = path.join(context.distRoot, `${iconType}-sprite`);
  const sourceTypeDir = path.join(context.sourceSvgDir, config.sourceDir);
 
  const createSpriter = (spriteFileName: string) =>
    new SVGSpriter({
      shape: {
        id: {
          generator: (name: string) => {
            const base = path.basename(name);
            return normalizeSymbol(base);
          },
        },
      },
      mode: {
        symbol: {
          inline: false,
          dest: '.',
          sprite: spriteFileName,
        },
      },
      svg: {
        xmlDeclaration: false,
        doctypeDeclaration: false,
        namespaceIDs: false,
        namespaceClassnames: false,
      },
    });
 
  const defaultSpriter = createSpriter(config.spriteFileName);
  const rtlSpriter = createSpriter('symbols-rtl.svg');
  const groupedRtl = await listGroupSvgFiles(sourceTypeDir, ['common', 'rtl']);
 
  logStep(`generateSprites:${iconType}: preparing ${icons.length} default symbols`);
  for (const icon of icons) {
    const content = await fs.readFile(icon.absolutePath, 'utf8');
    defaultSpriter.add(icon.absolutePath, icon.fileName, content);
  }
 
  logStep(`generateSprites:${iconType}: preparing ${groupedRtl.size} rtl symbols`);
  for (const [symbol, sourcePath] of groupedRtl.entries()) {
    const content = await fs.readFile(sourcePath, 'utf8');
    rtlSpriter.add(sourcePath, `${symbol}.svg`, content);
  }
 
  const compile = async (
    spriter: SVGSpriter,
    iconTypeName: IconType,
    spriteName: string,
  ): Promise<string> => {
    const compileResult = await new Promise<
      Record<string, Record<string, { path: string; contents: Buffer }>>
    >((resolve, reject) => {
      spriter.compile((error, result) => {
        if (error) {
          reject(error);
          return;
        }
        resolve(result);
      });
    });
 
    const symbolMode = compileResult.symbol;
    const spriteResource = symbolMode?.sprite;
    if (!symbolMode || !spriteResource) {
      throw new Error(`svg-sprite did not return symbol mode result for ${iconTypeName}`);
    }
 
    let spriteContents = spriteResource.contents.toString('utf8');
    spriteContents = spriteContents.replace(/id="[^"]*--([^"]+)"/g, 'id="$1"');
    spriteContents = spriteContents.replace(/xlink:href="#[^"]*--([^"]+)"/g, 'xlink:href="#$1"');
    spriteContents = spriteContents.replace(/href="#[^"]*--([^"]+)"/g, 'href="#$1"');
    spriteContents = spriteContents.replace(LEGACY_SPRITE_ROOT, LEGACY_SPRITE_ROOT_WITH_DISPLAY_NONE);
    if (iconTypeName !== 'doctype') {
      // Match legacy gulp behavior: strip hard-coded fills from non-doctype sprites.
      spriteContents = spriteContents.replace(LEGACY_FILL_REGEX, '');
      spriteContents = spriteContents.replace(/" \/>/g, '"/>');
    }
 
    await fs.mkdir(spriteOutputDir, { recursive: true });
    const spritePath = path.join(spriteOutputDir, spriteName);
    await fs.writeFile(spritePath, spriteContents, 'utf8');
    return spritePath;
  };
 
  const spritePath = await compile(defaultSpriter, iconType, config.spriteFileName);
  const rtlSpritePath = await compile(rtlSpriter, iconType, 'symbols-rtl.svg');
  logStep(`generateSprites:${iconType}: wrote ${spritePath}`);
  logStep(`generateSprites:${iconType}: wrote ${rtlSpritePath}`);
 
  return {
    type: iconType,
    spritePath,
    rtlSpritePath,
    symbols: icons.map((icon) => icon.symbol),
  };
}
 
/* Returns the human-readable category description embedded in ui.icons.json. */
function getCategoryDescription(iconType: IconType): string {
  switch (iconType) {
    case 'action':
      return 'Actions can be seen throughout the interface and represent actions a user can take on any given screen.';
    case 'doctype':
      return 'Doctype icons represent document file formats and common content classes.';
    case 'standard':
      return 'Standard object and feature icons used across Salesforce experiences.';
    case 'utility':
      return 'Utility icons represent generic actions, controls, and status affordances.';
    case 'custom':
      return 'Custom icons are available for the identity of user created objects.';
    default:
      return '';
  }
}
 
/*
 * Writes `ui.icons.json` at the dist root: one category per icon type, each
 * listing its unique, alphabetically sorted symbols. Matches the legacy
 * published layout.
 */
async function generateJson(context: BuildContext, iconsByType: Record<IconType, IconFile[]>): Promise<void> {
  logStep('generateJson: building ui.icons.json');
  const categories: UiIconsCategory[] = context.iconTypes.map((iconType) => {
    const uniqueSymbols = new Set<string>();
    for (const icon of iconsByType[iconType]) {
      uniqueSymbols.add(icon.symbol);
    }
 
    const icons = Array.from(uniqueSymbols)
      .sort((a, b) => a.localeCompare(b))
      .map<UiIconsEntry>((symbol) => ({
        sprite: iconType,
        symbol,
      }));
 
    return {
      name: iconType,
      description: getCategoryDescription(iconType),
      icons,
    };
  });
 
  // Write to the dist root (alongside the *-icons-metadata.json files), matching the
  // legacy published layout. The nested distRoot folder only holds zipped SVG/PNG assets.
  const jsonPath = path.join(context.distDir, 'ui.icons.json');
  await fs.writeFile(jsonPath, `${JSON.stringify(categories, null, 2)}\n`, 'utf8');
  logStep(`generateJson: wrote ${jsonPath}`);
}
 
/**
 * Emit per-category `{type}-icons-metadata.json` files at the dist root, matching the
 * legacy `@salesforce-ux/icons` published contract. Each file is a flat map of
 * `{ [symbol]: { synonyms: string[] } }` aggregated from `model/metadata/{type}/*.json`.
 * Consumers (e.g. sds-sandbox) import these directly by path.
 */
async function generateMetadata(context: BuildContext): Promise<void> {
  logStep('generateMetadata: building *-icons-metadata.json');
  const metadataRoot = path.join(context.rootDir, 'model', 'metadata');
 
  for (const iconType of context.iconTypes) {
    const metadataDir = path.join(metadataRoot, iconType);
    let files: string[];
    try {
      files = (await fs.readdir(metadataDir)).filter((file) => file.endsWith('.json'));
    } catch {
      logStep(`generateMetadata:${iconType}: no metadata directory, skipping`);
      continue;
    }
 
    files.sort((a, b) => a.localeCompare(b));
    const categoryMetadata: Record<string, { synonyms: string[] }> = {};
    for (const file of files) {
      const symbol = normalizeSymbol(path.basename(file, '.json'));
      const raw = await fs.readFile(path.join(metadataDir, file), 'utf8');
      const parsed = JSON.parse(raw) as { synonyms?: string[] };
      categoryMetadata[symbol] = { synonyms: parsed.synonyms ?? [] };
    }
 
    const outputPath = path.join(context.distDir, `${iconType}-icons-metadata.json`);
    await fs.writeFile(outputPath, `${JSON.stringify(categoryMetadata)}\n`, 'utf8');
    logStep(`generateMetadata:${iconType}: wrote ${outputPath} (${files.length} icons)`);
  }
}
 
/*
 * Rasterizes every dist SVG for an icon type into legacy-compatible _120 and
 * _60 PNGs using Sharp, scaling from the type's base size and applying the
 * legacy utility fill and custom-icon size quirks.
 */
async function rasterizePngs(context: BuildContext, iconType: IconType): Promise<void> {
  const config = ICON_TYPE_CONFIGS[iconType];
  const distTypeDir = path.join(context.distRoot, config.distDir);
  const baseSize = config.pngSize;
 
  // Find all SVG files in the dist directory for this icon type
  const svgFiles = (await listFilesRecursive(distTypeDir)).filter((filePath) => filePath.endsWith('.svg'));
  logStep(`rasterizePngs:${iconType}: found ${svgFiles.length} SVG files`);
 
  // Rasterize each SVG to legacy-compatible _120 and _60 PNG outputs.
  let rasterized = 0;
  for (const svgPath of svgFiles) {
    const basePath = svgPath.replace(/\.svg$/i, '');
    const svgContent = await fs.readFile(svgPath, 'utf8');
    const rasterSource =
      iconType === 'utility' ? svgContent.replace(LEGACY_FILL_REGEX, LEGACY_UTILITY_FILL) : svgContent;
    const svgBuffer = Buffer.from(rasterSource, 'utf8');
    const metadata = await sharp(svgBuffer).metadata();
    const sourceWidth = metadata.width ?? baseSize;
    const sourceHeight = metadata.height ?? baseSize;
 
    for (const size of PNG_SIZE_SUFFIXES) {
      const pngPath = `${basePath}_${size}.png`;
      let targetWidth = Math.max(1, Math.round((sourceWidth * size) / baseSize));
      let targetHeight = Math.max(1, Math.round((sourceHeight * size) / baseSize));
      // Legacy custom icon raster output is consistently 1px smaller at _120.
      if (iconType === 'custom' && size === 120) {
        targetWidth = Math.max(1, targetWidth - 1);
        targetHeight = Math.max(1, targetHeight - 1);
      }
      await sharp(svgBuffer)
        .resize(targetWidth, targetHeight, {
          fit: 'fill',
        })
        .png({
          compressionLevel: 9, // Maximum compression (replacement for imagemin-zopfli)
          quality: 100,
        })
        .toFile(pngPath);
    }
    rasterized += 1;
    if (rasterized % 100 === 0 || rasterized === svgFiles.length) {
      logStep(`rasterizePngs:${iconType}: ${rasterized}/${svgFiles.length}`);
    }
  }
  logStep(`rasterizePngs:${iconType}: completed`);
}
 
/*
 * Zips the SVG/PNG assets under distRoot into the distribution archive. Writes
 * to a `.tmp` file first and renames on success so the final zip is never
 * left partially written.
 */
async function createZip(context: BuildContext): Promise<void> {
  const zipName = path.basename(context.zipPath);
  const tempZipPath = `${context.zipPath}.tmp`;
  logStep(`createZip: writing ${context.zipPath}`);
  await fs.rm(context.zipPath, { force: true });
  await fs.rm(tempZipPath, { force: true });
 
  const output = createWriteStream(tempZipPath);
  const archive = new ZipArchive({ zlib: { level: 9 } });
 
  await new Promise<void>((resolve, reject) => {
    output.on('close', () => resolve());
    output.on('error', reject);
    archive.on('error', reject);
 
    archive.pipe(output);
    archive.glob('**/*', {
      cwd: context.distRoot,
      dot: true,
      ignore: [zipName, `${zipName}.tmp`],
    });
    void archive.finalize();
  });
  await fs.rename(tempZipPath, context.zipPath);
  logStep('createZip: completed');
}
 
/*
 * Runs the per-type pipeline for a single icon type: copy SVGs, generate
 * sprites, rasterize PNGs. Returns the type's IconFile descriptors.
 */
async function runForType(context: BuildContext, iconType: IconType): Promise<IconFile[]> {
  logStep(`type:${iconType}: start`);
  const icons = await copySvgs(context, iconType);
  await generateSprites(context, iconType, icons);
  await rasterizePngs(context, iconType);
  logStep(`type:${iconType}: done`);
  return icons;
}
 
/*
 * Entry point: resolves the build context, cleans dist, runs the per-type
 * pipeline for each requested icon type, then emits the JSON contract files
 * and the asset zip.
 */
async function main(): Promise<void> {
  const rootDir = path.resolve(import.meta.dirname, '..');
  const iconTypes = parseIconTypes(process.argv.slice(2));
  const distDir = path.join(rootDir, 'dist');
  const distRoot = path.join(distDir, OUTPUT_ZIP_FILE_BASE);
 
  const context: BuildContext = {
    rootDir,
    sourceSvgDir: path.join(rootDir, 'svg'),
    distDir,
    distRoot,
    zipPath: path.join(distDir, `${OUTPUT_ZIP_FILE_BASE}.zip`),
    iconTypes,
  };
  logStep(`build:start types=${iconTypes.join(',')}`);
 
  await cleanDist(context);
 
  const iconsByType = {} as Record<IconType, IconFile[]>;
  for (const iconType of iconTypes) {
    iconsByType[iconType] = await runForType(context, iconType);
  }
 
  await generateJson(context, iconsByType);
  await generateMetadata(context);
  await createZip(context);
  logStep('build:complete');
}
 
await main();