-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
105 lines (85 loc) · 2.36 KB
/
index.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { extname, relative, isAbsolute } from "path";
import * as fs from "fs";
import * as store from "data-store";
import { digest, findModulePath, extensions } from "./file";
import { findImportsByName, findImportsByNameAsync } from "./find.by.name";
export interface TFindImportsOptions {
findChild: boolean;
log: boolean; // log result imports
baseUrl: string[];
}
function logStrings(strs: string[]) {
console.log(strs.join("\n"));
}
function filenamekey(filename: string) {
return digest(filename);
}
const findStore = store("FINDIMPORTS");
findStore.clear(); // clear memory data
const uniqueArray = function(arrArg: string[]) {
return arrArg.filter(function(elem, pos, arr) {
return arr.indexOf(elem) === pos;
});
};
function findAllImports(
filename: string,
options: TFindImportsOptions
): string[] {
if (!filename || !fs.existsSync(filename)) {
console.log(`${filename} not find.`);
return [];
}
const { findChild, log, baseUrl } = options;
const key = filenamekey(filename);
const storeItems = findStore.get(key);
const dataImports: string[] = storeItems || findImportsByName(filename);
if (log) {
logStrings(dataImports);
}
const abPaths = (items: string[]): string[] => {
const strs: string[] = [];
items.forEach(p => {
const r = findModulePath(filename, p, {
baseUrl
});
if (r) {
strs.push(r);
} else if (!extname(p)) {
// filter not in extensions
strs.push(p);
}
});
findStore.set(key, [...strs]);
return strs;
};
if (findChild) {
const items = abPaths(dataImports).reduce((prev, next) => {
const s = findStore.get(filenamekey(next));
if (s) return [...prev];
if (
!fs.existsSync(next) ||
extensions.findIndex(e => e === extname(next)) < 0
) {
return [...prev];
}
return [...prev, ...findImports(next, options)];
}, dataImports);
return uniqueArray(abPaths(items));
} else {
return uniqueArray(abPaths(dataImports));
}
}
export function findImports(filename: string, options: TFindImportsOptions) {
const paths = findAllImports(filename, options);
return paths.map(ele => {
if (isAbsolute(ele)) {
return relative(options.baseUrl[0], ele);
}
return ele;
});
}
export default {
findImports,
findImportsByName,
findImportsByNameAsync
};