-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregenerate.js
More file actions
88 lines (64 loc) · 2.49 KB
/
regenerate.js
File metadata and controls
88 lines (64 loc) · 2.49 KB
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
import { promises } from "node:fs";
import path from "node:path";
import ignored from "./ignore.js";
import mappings from "./mappings.js";
const [ignoredFiles, ignoredDirectories] = ignored;
const { readdir: readDirectoryAsync, writeFile: writeFileAsync } = promises;
const [, , cwd = process.cwd()] = process.argv;
const identifier = name => mappings[name] || name;
// Do not match type definition files *.d.ts but match *.ts:
// https://stackoverflow.com/a/43493203/1384679
const extension = /(^.?|\.[^d]|[^.]d|[^.][^d])\.ts$/i;
const testFilePattern = /\.test\.[tj]s$/i;
const typesFilePattern = /types\.[tj]s$/i;
const importFormat = ""; // js = ".js";
const indexName = "/index"; // js = "/index.js";
const outputFormat = ".ts"; // js = ".js";
const main = async cwd => {
console.log(`Indexing files in ${cwd}...`);
const entries = await readDirectoryAsync(cwd, { withFileTypes: true });
const files = entries
.filter(x => x.isFile())
.map(x => x.name)
.filter(x => extension.test(x))
.filter(x => !testFilePattern.test(x))
.filter(x => !typesFilePattern.test(x))
.filter(x => !ignoredFiles.includes(x));
const directories = entries
.filter(x => x.isDirectory())
.map(x => x.name)
.filter(x => !ignoredDirectories.includes(x));
for (const directory of directories) {
await main(path.join(cwd, directory));
}
const submodules = files.map(filePath => {
const { base: fileName } = path.parse(filePath);
const splitted = fileName.split(".");
const id = identifier(splitted.slice(0, splitted.length - 1).join("_"));
const extension = `.${splitted[splitted.length - 1]}`;
return [fileName.replace(extension, importFormat), id, extension];
});
const dependencies = [
...submodules,
...directories.map(x => [`${x}${indexName}`, identifier(x), ""])
];
const importDeclarations = dependencies
.map(([fileName, id]) =>
id !== "index" ? `import ${id} from './${fileName}'` : ""
)
.join("\r\n");
const exportDeclarationBody = dependencies
.map(([, id]) => (id !== "index" ? id : ""))
.join(", ");
const exportDeclaration = `export { ${exportDeclarationBody} }`;
const defaultExport = `export default { ${exportDeclarationBody} }`;
console.log(`Indexed files in ${cwd}:`);
const moduleContents = [
importDeclarations,
exportDeclaration,
defaultExport
].join("\r\n\r\n");
console.log(moduleContents);
await writeFileAsync(path.join(cwd, `index${outputFormat}`), moduleContents);
};
main(cwd);