-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathdynamic-param-interfaces.ts
299 lines (280 loc) · 10.5 KB
/
dynamic-param-interfaces.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import {
EventParameterDocumentation,
DetailedObjectType,
ParsedDocumentationResult,
DetailedFunctionType,
DocumentationTag,
} from '@electron/docs-parser';
import chalk from 'chalk';
import d from 'debug';
import _ from 'lodash';
import * as utils from './utils.js';
const debug = d('dynamic-param');
type ParamInterface = EventParameterDocumentation &
DetailedObjectType & {
/**
* The original arg type
*/
tName?: string;
extends?: string;
};
// Object of interfaces we need to declare
const paramInterfacesToDeclare: Record<string, ParamInterface> = {};
// Interfaces that we would declare with these prefixes should remove them before declaration
const impoliteInterfaceNames = ['Get', 'Set', 'Show'];
const polite = (s: string): string => {
for (let i = 0; i < impoliteInterfaceNames.length; i++) {
if (s.startsWith(impoliteInterfaceNames[i]))
return polite(s.substring(impoliteInterfaceNames[i].length));
}
return s;
};
// Ignore descriptions when comparing objects
const ignoreDescriptions = <T extends EventParameterDocumentation>(
props: T[],
): Pick<T, Exclude<keyof T, 'description'>>[] =>
_.map(props, (p) => {
const { description, ...toReturn } = p;
return toReturn;
}).sort((a, b) => a.name.localeCompare(b.name));
const noDescriptionCache = new WeakMap();
const unsetDescriptions = (o: any): any => {
if (noDescriptionCache.has(o)) return noDescriptionCache.get(o);
if (typeof o !== 'object' || !o) return o;
const val = Array.isArray(o)
? o.map((item) => unsetDescriptions(item))
: Object.keys(o).reduce((accum: any, key: string) => {
if (key === 'description') return accum;
accum[key] = unsetDescriptions(o[key]);
return accum;
}, {});
noDescriptionCache.set(o, val);
return val;
};
// Given a parameter create a new interface and return it's name + array modifier
// IName is the proposed interface name prefix
// backupIName is a slightly longer IName in case IName is already taken
const createParamInterface = (
param: ParamInterface,
IName = '',
backupIName = '',
finalBackupIName = '',
): string => {
const maybeArray = (type: string) => (param.collection ? `Array<${type}>` : type);
const potentialExistingArgType = polite(IName);
const potentialExistingArgName = _.lowerFirst(polite(IName));
let argType = polite(IName) + _.upperFirst(_.camelCase(param.name));
let argName = param.name;
// TODO: Note. It is still possible for even backupIName to be already used
let usingExistingParamInterface = false;
_.forIn(paramInterfacesToDeclare, (value, key) => {
const test = unsetDescriptions(
_.assign({}, param, {
name: argName,
tName: argType,
required: value.required,
additionalTags: (param as any).additionalTags || [],
}),
);
const potentialTest = unsetDescriptions(
_.assign({}, param, {
name: potentialExistingArgName,
tName: potentialExistingArgType,
required: value.required,
additionalTags: (param as any).additionalTags || [],
}),
);
const unsetValue = unsetDescriptions(value);
if (_.isEqual(test, unsetValue) || _.isEqual(potentialTest, unsetValue)) {
usingExistingParamInterface = true;
debug(
chalk.cyan(
`Using existing type for param name ${argType} --> ${key} in Interface: ${_.upperFirst(
param.tName,
)} --- This is because their structure is identical`,
),
);
argType = key;
return false;
}
});
if (usingExistingParamInterface) {
return maybeArray(argType);
}
if (
paramInterfacesToDeclare[argType] &&
!_.isEqual(
ignoreDescriptions(paramInterfacesToDeclare[argType].properties),
ignoreDescriptions(param.properties),
)
) {
if (backupIName) {
return createParamInterface(param, backupIName, finalBackupIName);
}
console.error(
argType,
IName,
backupIName,
finalBackupIName,
ignoreDescriptions(paramInterfacesToDeclare[argType].properties),
'\n',
ignoreDescriptions(param.properties),
);
throw Error(`Interface "${argType}" has already been declared`);
}
// Update the params interfaces we still have to define
paramInterfacesToDeclare[argType] = param;
paramInterfacesToDeclare[argType].name = argName;
paramInterfacesToDeclare[argType].tName = argType;
return maybeArray(argType);
};
const flushParamInterfaces = (
API: ParsedDocumentationResult,
addToOutput: (lines: string[]) => void,
) => {
const declared: Record<string, ParamInterface> = {};
while (Object.keys(paramInterfacesToDeclare).length > 0) {
const nestedInterfacesToDeclare: Record<string, ParamInterface> = {};
Object.keys(paramInterfacesToDeclare)
.sort((a, b) =>
paramInterfacesToDeclare[a].tName!.localeCompare(paramInterfacesToDeclare[b].tName!),
)
.forEach((paramKey) => {
if (paramKey === 'Event') {
throw 'Unexpected dynamic Event type, should be routed through the Event handler';
}
if (declared[paramKey]) {
const toDeclareCheck: ParamInterface = Object.assign(
{},
paramInterfacesToDeclare[paramKey],
);
const declaredCheck: ParamInterface = Object.assign({}, declared[paramKey]);
for (const prop of ['type', 'collection', 'required', 'description'] as Array<
keyof ParamInterface
>) {
delete toDeclareCheck[prop];
delete declaredCheck[prop];
}
if (!_.isEqual(toDeclareCheck, declaredCheck)) {
throw new Error('Ruh roh, "' + paramKey + '" is already declared');
}
delete paramInterfacesToDeclare[paramKey];
return;
}
declared[paramKey] = paramInterfacesToDeclare[paramKey];
const param = paramInterfacesToDeclare[paramKey];
const paramAPI: string[] = [];
paramAPI.push(
`interface ${_.upperFirst(param.tName)}${
param.extends ? ` extends ${param.extends}` : ''
} {`,
);
param.properties = param.properties || [];
param.properties.forEach((paramProperty) => {
if (paramProperty.description) {
utils.extendArray(
paramAPI,
utils.wrapComment(paramProperty.description, paramProperty.additionalTags),
);
}
if (!Array.isArray(paramProperty.type) && paramProperty.type.toLowerCase() === 'object') {
let argType =
(paramProperty as any).__type || _.upperFirst(_.camelCase(paramProperty.name));
if (API.some((a) => a.name === argType)) {
paramProperty.type = argType;
debug(
chalk.red(
`Auto-correcting type from Object --> ${argType} in Interface: ${_.upperFirst(
param.tName,
)} --- This should be fixed in the docs`,
),
);
} else {
nestedInterfacesToDeclare[argType] = paramProperty as ParamInterface;
nestedInterfacesToDeclare[argType].name = paramProperty.name;
nestedInterfacesToDeclare[argType].tName = argType;
paramProperty.type = argType;
}
}
if (Array.isArray(paramProperty.type)) {
paramProperty.type = paramProperty.type.map((paramPropertyType) => {
const functionProp = paramPropertyType as DetailedFunctionType;
if (paramPropertyType.type === 'Function' && functionProp.parameters) {
return {
...paramPropertyType,
// FIXME: functionProp should slot in here perfectly
type: utils.genMethodString(
DynamicParamInterfaces,
param,
functionProp as any,
true,
),
};
} else if (
typeof paramPropertyType.type === 'string' &&
paramPropertyType.type.toLowerCase() === 'object'
) {
let argType =
(paramProperty as any).__type || _.upperFirst(_.camelCase(paramProperty.name));
if (API.some((a) => a.name === argType)) {
paramPropertyType.type = argType;
debug(
chalk.red(
`Auto-correcting type from Object --> ${argType} in Interface: ${_.upperFirst(
param.tName,
)} --- This should be fixed in the docs`,
),
);
} else {
nestedInterfacesToDeclare[argType] = paramPropertyType as ParamInterface;
nestedInterfacesToDeclare[argType].name = paramProperty.name;
nestedInterfacesToDeclare[argType].tName = argType;
paramPropertyType.type = argType;
}
}
return paramPropertyType;
});
}
const isReadonly = (paramProperty.additionalTags || []).includes(
DocumentationTag.AVAILABILITY_READONLY,
)
? 'readonly '
: '';
if (
!Array.isArray(paramProperty.type) &&
paramProperty.type.toLowerCase() === 'function'
) {
// FIXME: functionProp should slot in here perfectly
paramAPI.push(
`${isReadonly}${paramProperty.name}${
utils.isOptional(paramProperty) ? '?' : ''
}: ${utils.genMethodString(
DynamicParamInterfaces,
param,
paramProperty as any,
true,
)};`,
);
} else {
paramAPI.push(
`${isReadonly}${paramProperty.name}${
utils.isOptional(paramProperty) ? '?' : ''
}: ${utils.typify(paramProperty)};`,
);
}
});
paramAPI.push('}');
addToOutput(
paramAPI.map((l, index) => (index === 0 || index === paramAPI.length - 1 ? l : ` ${l}`)),
);
delete paramInterfacesToDeclare[paramKey];
});
Object.assign(paramInterfacesToDeclare, nestedInterfacesToDeclare);
}
return Object.keys(declared);
};
export class DynamicParamInterfaces {
static createParamInterface = createParamInterface;
static flushParamInterfaces = flushParamInterfaces;
}
utils.setParamInterfaces(DynamicParamInterfaces);