Code coverage report for src/index.js

Statements: 100% (48 / 48)      Branches: 100% (20 / 20)      Functions: 100% (5 / 5)      Lines: 100% (28 / 28)      Ignored: 1 branch     

All files » src/ » index.js
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                      1 1 1 1                 1 18       18     1 9   9 19 19   19 19 19   19 19 1     18 18   18   18     9               1 8 8       8        
import './guard';
import hook from './hook';
import postcss from 'postcss';
import { dirname, join, relative, resolve } from 'path';
import { readFileSync } from 'fs';
 
import ExtractImports from 'postcss-modules-extract-imports';
import LocalByDefault from 'postcss-modules-local-by-default';
import Scope from 'postcss-modules-scope';
import Parser from './parser';
 
const defaultRoot = process.cwd();
const tokensByFile = {};
let plugins = [LocalByDefault, ExtractImports, Scope];
let root = defaultRoot;
 
/**
 * @param  {string}   sourceString The file content
 * @param  {string}   sourcePath
 * @param  {string}   trace
 * @param  {function} pathFetcher
 * @return {object}
 */
function load(sourceString, sourcePath, trace, pathFetcher) {
  const result = postcss(plugins.concat(new Parser({ pathFetcher, trace })))
    .process(sourceString, {from: sourcePath})
    .root;
 
  return result.tokens;
}
 
hook(filename => {
  let importNr = 0;
 
  const fetch = (_newPath, _relativeTo, _trace) => {
    const newPath = _newPath.replace(/^["']|["']$/g, '');
    const trace = _trace || String.fromCharCode(importNr++);
 
    const relativeDir = dirname(_relativeTo);
    const rootRelativePath = resolve(relativeDir, newPath);
    const fileRelativePath = resolve(join(root, relativeDir), newPath);
 
    const tokens = tokensByFile[fileRelativePath];
    if (tokens) {
      return tokens;
    }
 
    const source = readFileSync(fileRelativePath, 'utf-8');
    const exportTokens = load(source, rootRelativePath, trace, fetch);
 
    tokensByFile[fileRelativePath] = exportTokens;
 
    return exportTokens;
  };
 
  return fetch(relative(root, filename), '/');
});
 
/**
 * @param  {object} opts
 * @param  {array}  opts.u
 * @param  {array}  opts.use
 */
export default function configure(opts = {}) {
  const customPlugins = opts.u || opts.use;
  plugins = Array.isArray(customPlugins)
    ? customPlugins
    : [LocalByDefault, ExtractImports, Scope];
 
  root = opts.root && typeof opts.root === 'string'
    ? opts.root
    : defaultRoot;
}