UNPKG

1.77 kBJavaScriptView Raw
1'use strict';
2const babelPipeline = require('./lib/babel-pipeline');
3const normalizeExtensions = require('./lib/extensions');
4const {hasExtension, normalizeGlobs, classify} = require('./lib/globs');
5const loadConfig = require('./lib/load-config');
6
7const configCache = new Map();
8const helperCache = new Map();
9
10function load(projectDir, overrides) {
11 const cacheKey = `${JSON.stringify(overrides)}\n${projectDir}`;
12 if (helperCache.has(cacheKey)) {
13 return helperCache.get(cacheKey);
14 }
15
16 let conf;
17 let babelConfig;
18 if (configCache.has(projectDir)) {
19 ({conf, babelConfig} = configCache.get(projectDir));
20 } else {
21 conf = loadConfig({resolveFrom: projectDir});
22 babelConfig = babelPipeline.validate(conf.babel);
23 configCache.set(projectDir, {conf, babelConfig});
24 }
25
26 if (overrides) {
27 conf = {...conf, ...overrides};
28 if (overrides.extensions) {
29 // Ignore extensions from the Babel config. Assume all extensions are
30 // provided in the override.
31 babelConfig = null;
32 }
33 }
34
35 const extensions = normalizeExtensions(conf.extensions || [], babelConfig);
36 const globs = {cwd: projectDir, ...normalizeGlobs(conf.files, conf.helpers, conf.sources, extensions.all)};
37
38 const helper = Object.freeze({
39 classifyFile: file => classify(file, globs),
40 classifyImport: importPath => {
41 if (hasExtension(globs.extensions, importPath)) {
42 // The importPath has one of the test file extensions: we can classify
43 // it directly.
44 return classify(importPath, globs);
45 }
46
47 // Add the first extension. If multiple extensions are available, assume
48 // patterns are not biased to any particular extension.
49 return classify(`${importPath}.${globs.extensions[0]}`, globs);
50 }
51 });
52 helperCache.set(cacheKey, helper);
53 return helper;
54}
55
56exports.load = load;