-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
66 lines (47 loc) · 1.82 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
// * data
import languages from './languages';
const DEFAULT_STRING_LITERALS = ["'", '"', '`'];
// * validators
import { resolverValidator, excludeValidator, stringLiteralsValidator } from './validators';
// * types
import { type Resolver } from './languages';
type Options = {
stringSensitive?: boolean;
stringLiterals?: string[];
exclude?: RegExp[];
};
const cmtu = (resolver: Resolver, options?: Options) => {
const { stringSensitive, stringLiterals = DEFAULT_STRING_LITERALS, exclude } = options ?? {};
resolverValidator(resolver);
stringSensitive && stringLiteralsValidator(stringLiterals);
excludeValidator(exclude);
let pattern = typeof resolver === 'string' ? resolver : Object.values(resolver).join('|');
if (stringSensitive) {
pattern =
stringLiterals.reduce((stringPatterns, stringLiteral) => {
const stringPattern = `${stringLiteral}(?:\\[\s\S]|[^"])*${stringLiteral}|`;
return stringPatterns + stringPattern;
}, '') + pattern;
}
const commentRegex = new RegExp(pattern, 'gm');
const exec = (code: string, replace: boolean = true): [string, string[]] => {
const matches: string[] = [];
code = code.replace(commentRegex, match => {
if (stringSensitive && stringLiterals.some(sl => match.startsWith(sl))) return match;
if (exclude?.some(regex => regex.test(match))) return match;
matches.push(match);
return replace ? '' : match;
});
return [code, matches];
};
return {
strip: (code: string) => exec(code, true)[0],
extract: (code: string) => exec(code, false)[1],
magic: (code: string) => exec(code, true),
};
};
cmtu.stringSensitive = (resolver: Resolver, options?: Omit<Options, 'stringSensitive'>) => {
return cmtu(resolver, { ...options, stringSensitive: true });
};
cmtu.Languages = languages;
module.exports = cmtu;