All files / packages/sds-cli/src main.js

0% Statements 0/102
0% Branches 0/35
0% Functions 0/24
0% Lines 0/97

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                                                                                                                                                                                                                                                                                                                                                                                                                   
import theo from 'theo';
import path from 'path';
import fs from 'fs-extra';
import { fileURLToPath } from 'url';
import * as glob from 'glob';
import postcss from 'postcss';
import { packageDirectory } from 'package-directory';
import postcssCmpHooks from './plugins/postcss-component-hooks.cjs';
 
// Register custom formats
import './formats/mappings.js';
import './transformers/font-scale.js';
import './transformers/color.js';
 
// Override the default "raw" transform
theo.registerTransform('raw', ['fontscale/web', 'color/web']);
 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = await packageDirectory();
const root = path.resolve(__dirname, '../');
const nodeModules = path.resolve(repoRoot, 'node_modules');
const buildDir = path.resolve(root, '.build/');
const tmpDir = path.resolve(root, '.tmp/');
const hooksDir = path.resolve(nodeModules, '@salesforce-ux/sds-styling-hooks/src/props');
 
// console.log(repoRoot);
 
const formats = [
  {
    format: 'custom-props.css',
    transform: 'raw',
  },
  {
    format: 'raw.json',
    transform: 'raw',
  },
];
 
// Clean up before we start
const prep = async (options) => {
  fs.removeSync(getOutputDir(options));
  fs.removeSync(buildDir);
  fs.removeSync(tmpDir);
};
 
const getOutputDir = (options) => {
  if (options.outputDir) {
    return path.resolve(repoRoot, options.outputDir);
  }
  return path.resolve(repoRoot, 'dist');
};
 
const getSrcDir = (options) => {
  if (options.srcDir) {
    return path.resolve(repoRoot, options.srcDir);
  }
};
 
const createTmpFiles = async (entries, options) => {
  const processed = new Set();
  await fs.ensureDir(path.resolve(root, `.tmp/`));
  for (const file of entries) {
    const name = path.parse(file).name;
    const json = await fs.readJson(file);
    json.global.namespace = options.ns;
    fs.writeJsonSync(path.resolve(root, `.tmp/${name}.json`), json);
    processed.add(path.resolve(root, `.tmp/${name}.json`));
  }
  return processed;
};
 
const createMainHooksFile = async () => {
  const tmpFiles = await fs.readdir(path.resolve(root, `.tmp/`));
  const normalizedPaths = tmpFiles.reduce((arr, foo) => {
    foo = path.resolve(root, `.tmp/${foo}`);
    if (!foo.includes('hooks')) arr.push(foo);
    return arr;
  }, []);
  fs.writeJsonSync(path.resolve(root, `.tmp/hooks.json`), {
    imports: normalizedPaths,
  });
};
 
const generateHooks = async () => {
  const tmpFiles = await fs.readdir(path.resolve(root, `.tmp/`));
  tmpFiles.forEach((file) => {
    const name = path.parse(file).name;
    formats.map((type) => {
      theo
        .convert({
          transform: {
            type: type.transform,
            file: path.resolve(root, `.tmp/${file}`),
          },
          format: {
            type: type.format,
          },
          resolveMetaAliases: true,
        })
        .then((data) => {
          fs.outputFileSync(path.resolve(buildDir, `${name}.${type.format}`), data);
        })
        .catch((error) => console.error(`Something went wrong: ${error} in ${file}`));
    });
  });
};
 
const generateComponentMappings = async (options) => {
  if (!options.components) return;
  const css = [];
  const props = glob.sync(path.resolve(nodeModules, `@salesforce-ux/sds-components/src/sds/*/*.css`));
  props.map(async (file, key) => {
    const name = path.parse(file).name;
    const raw = fs.readFileSync(file);
    await postcss([postcssCmpHooks({ ns: options.ns })])
      .process(raw, { from: file })
      .then((results) => {
        css.push(...results.messages.mappings);
        fs.outputFile(
          path.join(getOutputDir(options), `/${options.ns}/${name}/${name}.mappings.css`),
          `:host { ${results.messages.mappings.join('')} }`,
          (err) => err,
        );
        return css;
      });
  });
};
 
const cloneComponents = async (options) => {
  const filterDirectories = (src, folder) => {
    const directory = path.parse(src).dir;
    if (src.endsWith(folder) || directory.endsWith(folder)) {
      return true;
    }
  };
  const filterFunc = (src, dest) => {
    if (
      filterDirectories(src, '__tests__') ||
      filterDirectories(src, '__stories__') ||
      filterDirectories(src, '__assets__')
    ) {
      return false;
    }
    return true;
  };
  fs.pathExists(path.resolve(nodeModules, `@salesforce-ux/sds-primitives/src/sds`), (err, exists) => {
    if (err) console.error(err);
    if (exists) {
      fs.copySync(
        path.resolve(nodeModules, `@salesforce-ux/sds-primitives/src/sds`),
        path.resolve(getSrcDir(options), options.ns),
        {
          filter: filterFunc,
        },
      );
    } else {
      console.log('cannot find @salesforce-ux/sds-primitives, please ensure the package is installed');
    }
  });
};
 
const cleanUp = async (options) => {
  fs.copySync(buildDir, getOutputDir(options));
  fs.removeSync(buildDir);
  fs.removeSync(tmpDir);
};
 
export async function createMappings(options) {
  const categories = options.categories && options.categories.join('|');
  const props = glob.sync(path.resolve(hooksDir, `**/*(${categories}).json`));
 
  fs.pathExists(getOutputDir(options), async (err, exists) => {
    if (err) console.error(err);
    if (options.force) {
      if (exists) {
        console.log('folder exists, but --force is true, so we will overwrite it');
      }
      await prep(options);
      await createTmpFiles(props, options);
      await createMainHooksFile();
      await generateHooks();
      await generateComponentMappings(options);
      await cleanUp(options);
      console.log(`Your styling hooks have been generated and are available in ${getOutputDir(options)}`);
    } else if (exists) {
      console.log(`The folder ${getOutputDir(options)} already exists. Use --force to overwrite it.`);
    }
  });
}
 
export async function ejectComponents(options) {
  fs.pathExists(getSrcDir(options), async (err, exists) => {
    if (err) console.error(err);
    if (exists) {
      await cloneComponents(options);
    } else {
      console.log(`cannot find ${getSrcDir(options)}, please ensure your lwc components reside there`);
    }
  });
}