All files / packages/design-tokens/src/style-dictionary/formats json-flat-metadata.ts

100% Statements 16/16
100% Branches 2/2
100% Functions 5/5
100% Lines 16/16

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                          1x 3x 3x 3x   3x                 1x 3x   3x 3x             3x 3x     3x               1x 2x   1x         1x      
import type { Dictionary, FormatFn } from 'style-dictionary/types';
 
import type { StyleDictionaryHost } from '../style-dictionary-host.js';
import { flatTokenFields } from '../utils/flat-token-fields.js';
import { buildVariantExtensions } from '../utils/variant-extensions.js';
 
/**
 * Sort top-level keys only so token-name order matches across OS / Style Dictionary
 * iteration order, without reordering keys inside each token object (snapshot stability).
 *
 * @param {Record<string, object>} flatTokens
 * @returns {Record<string, object>}
 */
const sortTopLevelKeysOnly = (flatTokens) => {
  const sorted = {};
  for (const key of Object.keys(flatTokens).sort()) {
    sorted[key] = flatTokens[key];
  }
  return sorted;
};
 
/**
 * Formatter for the JSON flat metadata format
 *
 * @param {Object} dictionary
 * @returns {string}
 */
const jsonFlatMetadataFormatter = (dictionary: Dictionary) => {
  const flatTokens = {};
 
  dictionary.allTokens.forEach((token) => {
    const fields = flatTokenFields(token);
 
    // Variant-aware tokens also carry resolved blocks under a dedicated
    // $extensions namespace: color scheme (light/dark) under
    // com.salesforce-ux.mode, density (comfy/compact) under
    // com.salesforce-ux.density. The flat `darkValue` field is retained
    // alongside for backwards compatibility.
    const variantExtensions = buildVariantExtensions(token);
    flatTokens[token.name] = variantExtensions ? { ...fields, $extensions: variantExtensions } : fields;
  });
 
  return JSON.stringify(sortTopLevelKeysOnly(flatTokens), null, 2);
};
 
/**
 * Style Dictionary registration for the JSON flat metadata format
 *
 * @param {StyleDictionary} StyleDictionary
 */
export const jsonFlatMetadataFormat = (StyleDictionary: StyleDictionaryHost) => {
  StyleDictionary.registerFormat({
    name: 'json/flat-full',
    format: (({ dictionary }) => jsonFlatMetadataFormatter(dictionary)) satisfies FormatFn,
  });
};
 
// Export internal functions for testing
export const _testExports = {
  jsonFlatMetadataFormatter,
};