/
declaration.ts
116 lines (94 loc) · 2.79 KB
/
declaration.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
106
107
108
109
110
111
112
113
114
115
116
export enum ParameterHint {
File,
Directory
}
export enum ParameterType {
String,
Number,
Boolean,
Map,
Mixed,
Array
}
export enum ParameterScope {
TypeDoc, TypeScript
}
export interface DeclarationOption {
name: string;
component?: string;
short?: string;
help: string;
type?: ParameterType;
hint?: ParameterHint;
scope?: ParameterScope;
map?: {};
mapError?: string;
defaultValue?: any;
convert?: (param: OptionDeclaration, value?: any) => any;
}
export class OptionDeclaration {
name: string;
short: string;
component: string;
help: string;
type: ParameterType;
hint: ParameterHint;
scope: ParameterScope;
protected map: Object | Map<string, any> | 'object';
mapError: string;
isArray: boolean;
defaultValue: any;
constructor(data: DeclarationOption) {
for (let key in data) {
this[key] = data[key];
}
this.type = this.type || ParameterType.String;
this.scope = this.scope || ParameterScope.TypeDoc;
}
getNames(): string[] {
const result = [this.name.toLowerCase()];
if (this.short) {
result.push(this.short.toLowerCase());
}
return result;
}
convert(value: any, errorCallback?: Function): any {
switch (this.type) {
case ParameterType.Number:
value = parseInt(value, 10);
break;
case ParameterType.Boolean:
value = (typeof value === void 0 ? true : !!value);
break;
case ParameterType.String:
value = value || '';
break;
case ParameterType.Array:
if (!value) {
value = [];
} else if (typeof value === 'string') {
value = value.split(',');
}
break;
case ParameterType.Map:
const map = this.map;
if (map !== 'object') {
const key = value ? (value + '').toLowerCase() : '';
const values = Object.keys(map).map(key => map[key]);
if (map instanceof Map) {
value = map.has(key) ? map.get(key) : value;
} else if (key in map) {
value = map[key];
} else if (values.indexOf(value) === -1 && errorCallback) {
if (this.mapError) {
errorCallback(this.mapError);
} else {
errorCallback('Invalid value for option "%s".', this.name);
}
}
}
break;
}
return value;
}
}