/
generateUserDepsModule.ts
85 lines (74 loc) · 2.06 KB
/
generateUserDepsModule.ts
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
import path from 'path';
import { CosmosConfig } from '../../config';
import slash from 'slash';
import { findUserModulePaths } from './findUserModulePaths';
// Warning: Renderer config must be serializable!
export function generateUserDepsModule(
cosmosConfig: CosmosConfig,
rendererConfig: {}
): string {
const {
rootDir,
fixturesDir,
fixtureFileSuffix,
globalImports
} = cosmosConfig;
const { fixturePaths, decoratorPaths } = findUserModulePaths({
rootDir,
fixturesDir,
fixtureFileSuffix
});
return getCompiledTemplate({
globalImports: genGlobalRequires(globalImports),
rendererConfig: stringifyRendererConfig(rendererConfig),
fixtures: genRequireMap(fixturePaths, rootDir),
decorators: genRequireMap(decoratorPaths, rootDir)
});
}
function genGlobalRequires(paths: string[]) {
if (paths.length === 0) {
return '';
}
// Forward slashes are necessary via slash() to avoid double-escaping
// backslashes on Windows
return [
'',
'// Keeping global imports here is superior to making them bundle entry points',
'// because this way they become hot-reloadable',
...paths.map(importPath => `require('${slash(importPath)}');`),
''
].join(`\n`);
}
function genRequireMap(paths: string[], rootDir: string) {
if (paths.length === 0) {
return '{}';
}
const requireRows = paths.map(p => {
const relPath = slash(path.relative(rootDir, p));
return `
'${relPath}': require('${p}').default`;
});
return `{${requireRows.join(', ')}\n}`;
}
function stringifyRendererConfig(rendererConfig: {}) {
return JSON.stringify(rendererConfig, null, 2);
}
export type TemplateArgs = {
globalImports: string;
rendererConfig: string;
fixtures: string;
decorators: string;
};
function getCompiledTemplate({
globalImports,
rendererConfig,
fixtures,
decorators
}: TemplateArgs) {
return `// This file is automatically generated by Cosmos
${globalImports}
export const rendererConfig = ${rendererConfig};
export const fixtures = ${fixtures};
export const decorators = ${decorators};
`;
}