/
load-parser-opts.ts
71 lines (63 loc) 路 1.87 KB
/
load-parser-opts.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
import {ParserPreset} from '@commitlint/types';
function isObjectLike(obj: unknown): obj is Record<string, unknown> {
return Boolean(obj) && typeof obj === 'object'; // typeof null === 'object'
}
function isParserOptsFunction<T extends ParserPreset>(
obj: T
): obj is T & {
parserOpts: (
cb: (_: never, parserOpts: Record<string, unknown>) => unknown
) => Record<string, unknown> | undefined;
} {
return typeof obj.parserOpts === 'function';
}
export async function loadParserOpts(
pendingParser: string | ParserPreset | Promise<ParserPreset> | undefined
): Promise<ParserPreset | undefined> {
if (!pendingParser || typeof pendingParser !== 'object') {
return undefined;
}
// Await for the module, loaded with require
const parser = await pendingParser;
// exit early if there is no opts
if (!parser.parserOpts) {
return parser;
}
// Pull nested parserOpts, might happen if overwritten with a module in main config
if (typeof parser.parserOpts === 'object') {
// Await parser opts if applicable
const opts = await parser.parserOpts;
parser.parserOpts =
isObjectLike(opts) && isObjectLike(opts.parserOpts)
? opts.parserOpts
: opts;
return parser;
}
// Create parser opts from factory
if (
isParserOptsFunction(parser) &&
typeof parser.name === 'string' &&
parser.name.startsWith('conventional-changelog-')
) {
return new Promise((resolve) => {
const result = parser.parserOpts((_: never, opts) => {
resolve({
...parser,
parserOpts: opts.parserOpts,
});
});
// If result has data or a promise, the parser doesn't support factory-init
// due to https://github.com/nodejs/promises-debugging/issues/16 it just quits, so let's use this fallback
if (result) {
Promise.resolve(result).then((opts) => {
resolve({
...parser,
parserOpts: opts.parserOpts,
});
});
}
return;
});
}
return parser;
}