All files / packages/design-system/scripts/core generate-core-css.js

96.55% Statements 112/116
84.78% Branches 39/46
96% Functions 24/25
96.55% Lines 112/116

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                                                              67x     67x 67x 67x   67x 67x     67x 67x 67x 67x     67x                           67x             13x                       16x                 14x 2x         12x                   31x 32x   9x   5x     4x 4x 4x 4x   4x   4x                               39x                     39x                 18x                           49x                 47x 47x                       47x 47x                           45x 45x   45x 45x     45x 45x     45x   2x 2x                     14x 12x 12x 12x 12x   2x 2x                       14x 2x 2x     12x 12x   12x                   13x 13x 13x                 14x 14x 14x                     11x               11x   11x 11x                     11x                 11x   11x 11x                     13x             13x 11x       13x     13x     13x                         12x               12x 12x   12x     12x 12x 1x 1x 1x     1x       11x     11x 11x 11x 11x     11x 11x     11x 11x   11x 11x   11x 11x       11x     11x 11x     11x 11x       11x 11x   11x 11x   11x                 67x 67x                
#!/usr/bin/env node
/**
 * Generate Core CSS
 * Adapted from design-system-dist/lib/css.js for monorepo
 *
 * This script generates CSS for Salesforce Core by:
 * 1. Parsing SCSS from the design-system dist using @salesforce-ux/scss-parser-aura
 * 2. Injecting styling hooks via PostCSS plugin
 * 3. Optimizing CSS with PostCSS (discard comments, normalize charset, discard empty)
 * 4. Writing output to dist-core/css/ for ui-force-components and shared-slds-impl
 * 5. Appending AgentForce CSS from design-system-2
 */
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import fs from 'fs-extra';
import _ from 'lodash';
import postcss from 'postcss';
import chalk from 'chalk';
import { createRequire } from 'node:module';
 
// PostCSS plugins
import injectStylingHooks from './postcss-inject-styling-hooks.js';
import discardEmpty from 'postcss-discard-empty';
import discardComments from 'postcss-discard-comments';
import normalizeCharset from 'postcss-normalize-charset';
 
// Local utilities
import writeDist from './write-core-dist.js';
import { getSha } from './get-sha.js';
 
// For CommonJS modules that don't have ESM exports
const require = createRequire(import.meta.url);
 
// scss-parser-aura (CommonJS)
const createAuraCss = require('@salesforce-ux/scss-parser-aura');
const parserPlugins = require('@salesforce-ux/scss-parser-aura/plugins');
const parserVersion = require('@salesforce-ux/scss-parser-aura/package.json').version;
 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
 
// Base paths
const packageRoot = path.resolve(__dirname, '../..');
const distPath = path.join(packageRoot, 'dist');
const distCorePath = path.join(packageRoot, 'dist-core/css');
const templatesPath = __dirname;
 
// Parser plugins configuration
export const parserPluginsConfig = {
  sass: [
    parserPlugins.mixin,
    parserPlugins.value,
    parserPlugins.assetPaths,
    parserPlugins.customProps,
    parserPlugins.fn,
    parserPlugins.var,
    parserPlugins.negation,
    parserPlugins.mathPolyfill,
  ],
  css: [parserPlugins.font, parserPlugins.tokenString],
};
 
export const SCOPES_TO_REMOVE = ['kx-scope'];
 
/**
 * Create PostCSS processor with standard plugins
 * @returns {Object} PostCSS processor
 */
export function createProcessor() {
  return postcss()
    .use(injectStylingHooks())
    .use(normalizeCharset())
    .use(discardEmpty())
    .use(discardComments());
}
 
/**
 * Create PostCSS processor for offline CSS (no styling hooks)
 * @returns {Object} PostCSS processor
 */
export function createOfflineProcessor() {
  return postcss().use(normalizeCharset()).use(discardEmpty());
}
 
/**
 * Validate that the dist path exists
 * @param {string} distPathToCheck - Path to check
 * @returns {{ valid: boolean, error?: string }}
 */
export function validateDistPath(distPathToCheck) {
  if (!fs.existsSync(distPathToCheck)) {
    return {
      valid: false,
      error: `dist folder not found: ${distPathToCheck}`,
    };
  }
  return { valid: true };
}
 
/**
 * Get tokens from dependencies
 * @param {string[]} dependencies - Array of dependency paths
 * @param {string} tokenDistPath - Path to token dist directory
 * @returns {string[]} Array of token names
 */
export function getTokens(dependencies, tokenDistPath = distPath) {
  return _(dependencies)
    .filter((p) => /design-tokens/.test(p))
    .filter((p) => {
      return !/bg-actions|bg-standard|bg-custom|design-tokens/.test(path.basename(p));
    })
    .map((p) => path.basename(p).split('.')[0])
    .uniq()
    .map((p) => {
      const r = path.join(tokenDistPath, `design-tokens/dist/${p}.common`);
      let m = {};
      try {
        m = require(r);
      } catch (e) {
        console.log(`Unable to require "${r}"`);
      }
      return _.keys(m);
    })
    .flatten()
    .map(_.kebabCase)
    .value();
}
 
/**
 * Insert header message into CSS
 * @param {string} css - CSS content
 * @param {Object} info - Version and SHA info
 * @param {string} additionalMessage - Additional message to include
 * @param {string} parserVer - Parser version string
 * @returns {string} CSS with header
 */
export function insertMessage(css, info, additionalMessage = '', parserVer = parserVersion) {
  const message = [
    '/*!',
    ` * design-system ${info.version} (${info.SHA})`,
    ` * scss-parser-aura ${parserVer}`,
    ' * ',
    ` * This file is automatically generated.  ${additionalMessage}`,
    ' * Please do not edit or check in changes to this file.',
    ' * If you need changes made, please contact the SLDS Framework team.',
    ' */',
  ].join('\n');
 
  return message + '\n' + (css || '');
}
 
/**
 * Add sldsValidatorAllow annotation for .slds-wcag selector
 * @param {string} css - CSS content
 * @returns {string} CSS with annotation
 */
export function addSldsValidatorAllowAnnotation(css) {
  return css.replace(
    /(.slds-wcag{)/,
    `/* @sldsValidatorAllow */ $1}
$1`,
  );
}
 
/**
 * Wrap CSS with the Core template
 * @param {string} css - CSS content
 * @param {string} template - Template content
 * @returns {string} Wrapped CSS
 */
export function wrapWithTemplate(css, template) {
  return template.replace('#{{SLDS_DEFAULT}}', css);
}
 
/**
 * Read the Core template
 * @param {string} templateDir - Template directory path
 * @returns {string} Template content
 */
export function readCoreTemplate(templateDir = templatesPath) {
  const templatePath = path.join(templateDir, 'index-core.tmpl');
  return fs.readFileSync(templatePath, 'utf8');
}
 
/**
 * Process CSS for Core output
 * @param {string} defaultCss - CSS content
 * @param {string} componentPath - Directory name for ui-force-components
 * @param {boolean} addAnnotation - Whether to add sldsValidatorAllow annotation
 * @param {string} template - Template content
 * @returns {string} Processed CSS
 */
export function processCssForCore(defaultCss, componentPath, addAnnotation, template) {
  const processedCss = addAnnotation ? addSldsValidatorAllowAnnotation(defaultCss) : defaultCss;
  return wrapWithTemplate(processedCss, template);
}
 
/**
 * Generate conditional stylesheet for Core using Omakase @if notation
 * @param {string} defaultCss - CSS content
 * @param {string} componentPath - Directory name for ui-force-components
 * @param {string} sharedPath - Filename for shared-slds-impl
 * @param {Object} options - Options
 * @param {string} options.templateDir - Template directory
 * @param {Function} options.writeFn - Custom write function (for testing)
 * @param {string} options.distCorePath - Override dist-core output path
 */
export function cssDefaultLegacyCombine(defaultCss, componentPath, sharedPath, options = {}) {
  const templateDir = options.templateDir || templatesPath;
  const writeFunction = options.writeFn || writeDist;
 
  try {
    const template = readCoreTemplate(templateDir);
 
    // Add annotation for sldsTemplate
    const addAnnotation = componentPath === 'sldsTemplate';
    const css = processCssForCore(defaultCss, componentPath, addAnnotation, template);
 
    // writeDist expects (result, componentName, sharedFilename, options); pass options so distCorePath is used
    writeFunction({ css }, componentPath, sharedPath, options);
  } catch (err) {
    console.error(chalk.red(`Error generating ${componentPath || sharedPath}:`), err);
    throw err;
  }
}
 
/**
 * Copy Touch CSS to dist-core
 * @param {string} sourcePath - Source file path
 * @param {string} destPath - Destination file path
 * @returns {boolean} True if copied successfully
 */
export function copyTouchCss(sourcePath, destPath) {
  if (fs.existsSync(sourcePath)) {
    fs.ensureDirSync(path.dirname(destPath));
    fs.copyFileSync(sourcePath, destPath);
    console.log(chalk.gray(`Writing file sldsTouch.css to ${destPath} - ${chalk.bgGreen('DONE')}`));
    return true;
  } else {
    console.log(chalk.yellow(`   Warning: Touch CSS not found at ${sourcePath}`));
    return false;
  }
}
 
/**
 * Process offline CSS
 * @param {string} offlineCssPath - Path to offline CSS file
 * @param {Object} info - Version info
 * @param {Object} processor - PostCSS processor
 * @returns {Promise<Object|null>} PostCSS result or null if file not found
 */
export async function processOfflineCss(offlineCssPath, info, processor) {
  if (!fs.existsSync(offlineCssPath)) {
    console.log(chalk.yellow(`   Warning: Offline CSS not found at ${offlineCssPath}`));
    return null;
  }
 
  let offlineCss = fs.readFileSync(offlineCssPath, 'utf8');
  offlineCss = insertMessage(offlineCss, info, '(Only to be used offline)');
 
  return await processor.process(offlineCss, { from: undefined });
}
 
/**
 * Get build info (version and SHA) from dist package.json and git
 * @param {string} distPathForInfo - Path to dist directory containing package.json
 * @param {string} pkgRoot - Package root for git SHA lookup
 * @returns {{ version: string, SHA: string }} Build info object
 */
export function getBuildInfo(distPathForInfo, pkgRoot = packageRoot) {
  const { version } = require(path.join(distPathForInfo, 'package.json'));
  const SHA = getSha(pkgRoot);
  return { version, SHA };
}
 
/**
 * Prepare the output directory by cleaning and recreating it
 * @param {string} outputPath - Path to output directory
 * @param {Function} log - Logging function
 */
export function prepareOutputDirectory(outputPath, log = console.log) {
  log(chalk.gray('   Cleaning dist-core/css...'));
  fs.removeSync(outputPath);
  fs.ensureDirSync(outputPath);
}
 
/**
 * Generate default (unscoped) SLDS CSS
 * @param {Object} opts - Options containing distPath
 * @param {Object} info - Build info (version, SHA)
 * @param {Object} processor - PostCSS processor
 * @returns {Promise<string>} Generated CSS
 */
export async function generateDefaultSlds(opts, info, processor) {
  let { cssTokenized } = createAuraCss({
    entry: path.join(opts.distPath, 'scss/index.scss'),
    getTokens,
    info,
    scopes: SCOPES_TO_REMOVE,
    plugins: parserPluginsConfig,
  });
 
  cssTokenized = insertMessage(cssTokenized, info);
 
  const result = await processor.process(cssTokenized, { from: undefined });
  return result.css;
}
 
/**
 * Generate scoped SLDS CSS with .slds-scope wrapper
 * @param {Object} opts - Options containing distPath
 * @param {Object} info - Build info (version, SHA)
 * @param {Object} processor - PostCSS processor
 * @returns {Promise<string>} Generated CSS
 */
export async function generateScopedSlds(opts, info, processor) {
  let { cssTokenized } = createAuraCss({
    entry: path.join(opts.distPath, 'scss/index-internal.scss'),
    getTokens,
    info,
    scopes: SCOPES_TO_REMOVE,
    plugins: parserPluginsConfig,
    scssBefore: '$reset-wrapping-class: ".slds-scope";',
  });
 
  cssTokenized = insertMessage(cssTokenized, info);
 
  const result = await processor.process(cssTokenized, { from: undefined });
  return result.css;
}
 
/**
 * Write all CSS output files (sldsOffline, slds, sldsTemplate, scopedSlds/scopedSldsTemplate)
 * @param {string} sldsDefault - Default SLDS CSS
 * @param {string} sldsDefaultScoped - Scoped SLDS CSS
 * @param {Object|null} offlineResult - Offline CSS result (or null)
 * @param {Object} opts - Options containing templateDir, writeFn, distCorePath
 */
export function writeAllOutputFiles(sldsDefault, sldsDefaultScoped, offlineResult, opts) {
  const writeOptions = {
    templateDir: opts.templateDir,
    writeFn: opts.writeFn,
    distCorePath: opts.distCorePath,
  };
 
  // Offline CSS (written first to maintain original order)
  if (offlineResult) {
    opts.writeFn(offlineResult, 'sldsOffline', 'sldsOffline', { distCorePath: opts.distCorePath });
  }
 
  // slds.css (shared only)
  cssDefaultLegacyCombine(sldsDefault, null, 'slds', writeOptions);
 
  // sldsTemplate.css (component only, with annotation)
  cssDefaultLegacyCombine(sldsDefault, 'sldsTemplate', null, writeOptions);
 
  // scopedSlds.css and scopedSldsTemplate.css
  cssDefaultLegacyCombine(sldsDefaultScoped, 'scopedSldsTemplate', 'scopedSlds', writeOptions);
}
 
/**
 * Main generation function - orchestrates the Core CSS generation workflow
 * @param {Object} options - Configuration options for testing
 * @param {string} options.distPath - Override dist path
 * @param {string} options.distCorePath - Override dist-core output path
 * @param {string} options.templateDir - Override template directory
 * @param {Function} options.writeFn - Override write function
 * @param {boolean} options.silent - Suppress console output
 */
export async function generateCoreCss(options = {}) {
  const opts = {
    distPath: options.distPath || distPath,
    distCorePath: options.distCorePath || distCorePath,
    templateDir: options.templateDir || templatesPath,
    writeFn: options.writeFn || writeDist,
    silent: options.silent || false,
  };
 
  const log = opts.silent ? () => {} : console.log;
  const logError = opts.silent ? () => {} : console.error;
 
  log(chalk.blue('\nšŸ”§ Generating Core CSS...\n'));
 
  // Validate dist path exists
  const validation = validateDistPath(opts.distPath);
  if (!validation.valid) {
    logError(chalk.red(`āŒ ${validation.error}`));
    logError(chalk.gray('   Run the build script first: yarn workspace @salesforce-ux/design-system build'));
    Iif (!options.distPath) {
      process.exit(1);
    }
    throw new Error(validation.error);
  }
 
  // Prepare output directory
  prepareOutputDirectory(opts.distCorePath, log);
 
  // Get build metadata
  const info = getBuildInfo(opts.distPath, packageRoot);
  log(chalk.gray(`   Version: ${info.version}`));
  log(chalk.gray(`   SHA: ${info.SHA}`));
  log(chalk.gray(`   Parser: scss-parser-aura@${parserVersion}\n`));
 
  // Create PostCSS processors
  const processor = createProcessor();
  const processorOffline = createOfflineProcessor();
 
  // Generate CSS variants
  log(chalk.blue('   Generating default SLDS...'));
  const sldsDefault = await generateDefaultSlds(opts, info, processor);
 
  log(chalk.blue('   Generating scoped SLDS...'));
  const sldsDefaultScoped = await generateScopedSlds(opts, info, processor);
 
  log(chalk.blue('   Generating offline SLDS...'));
  const offlineCssPath = path.join(
    opts.distPath,
    'assets/styles/salesforce-lightning-design-system-offline.css',
  );
  const offlineResult = await processOfflineCss(offlineCssPath, info, processorOffline);
 
  // Write all output files
  log(chalk.blue('\n   Writing output files...'));
  writeAllOutputFiles(sldsDefault, sldsDefaultScoped, offlineResult, opts);
 
  // Copy Touch CSS
  log(chalk.blue('\n   Copying Touch CSS...'));
  const touchSource = path.join(
    opts.distPath,
    'assets/styles/salesforce-lightning-design-system_touch.min.css',
  );
  const touchDest = path.join(opts.distCorePath, 'sfdc/htdocs/_slds/styles/sldsTouch.css');
  copyTouchCss(touchSource, touchDest);
 
  log(chalk.green('\nāœ… Core CSS generation complete!'));
  log(chalk.gray(`   Output: ${opts.distCorePath}\n`));
 
  return {
    sldsDefault,
    sldsDefaultScoped,
    offlineResult: offlineResult?.css,
    distCorePath: opts.distCorePath,
  };
}
 
// Run if called directly
const isMainModule = import.meta.url === `file://${process.argv[1]}`;
Iif (isMainModule) {
  generateCoreCss({}).catch((error) => {
    console.error(chalk.red('āŒ Error generating Core CSS:'), error);
    process.exit(1);
  });
}
 
export default generateCoreCss;