-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
generateTypes.js
381 lines (381 loc) · 14.4 KB
/
generateTypes.js
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
"use strict";
function generateTypes(obj, maxDepth = 1) {
class CustomTypes {
counter = 0;
typeDefinitionMap = new Map();
definitionTypeMap = new Map();
nextCounter() {
this.counter++;
return this.counter;
}
toString() {
let index = 0;
const typePathIndexMap = new Map();
for (const [obj, path] of objectPathDepthMap.entries()) {
const type = objectTypeMap.get(obj);
if (!type) {
continue;
}
typePathIndexMap.set(type, { path, index });
index++;
}
return Array.from(this.typeDefinitionMap.entries())
.sort(([type1], [type2]) => (typePathIndexMap.get(type1)?.index ?? 0) - (typePathIndexMap.get(type2)?.index ?? 0))
.map(([type, definition]) => `// ${typePathIndexMap.get(type)?.path ?? ''}\ninterface ${type}${definition}`)
.join('\n\n');
}
set({ type, definition }) {
this.typeDefinitionMap.set(type, definition);
this.definitionTypeMap.set(definition, type);
}
getByDefinition(definition) {
return this.definitionTypeMap.get(definition);
}
}
const builtInPrototypeNameMap = new Map();
const obsidianPrototypeNameMap = new Map();
const DEPTH_LIMIT_REACHED_TYPE_NAME = 'DepthLimitReached';
const customTypes = new CustomTypes();
const objectTypeMap = new Map();
const objectPathDepthMap = new Map();
const functionObjectMap = new Map();
const fixDuplicatesMap = new Map();
function main() {
if (maxDepth === 0) {
maxDepth = Number.MAX_SAFE_INTEGER;
}
initBuiltInPrototypeNameMap();
initObjectPathMap();
inferType({
obj,
inArray: false,
path: 'root',
depth: 1
});
return customTypes.toString();
}
function initBuiltInPrototypeNameMap() {
const obsidian = window.require('obsidian');
for (const [key, value] of entriesSafe(obsidian)) {
if (typeof value === 'function') {
obsidianPrototypeNameMap.set(value.prototype, key);
}
}
fixDuplicatesMap.set(obsidian.TFile, null);
fixDuplicatesMap.set(obsidian.TFolder, null);
builtInPrototypeNameMap.set(window, 'Window');
builtInPrototypeNameMap.set(document, 'Document');
builtInPrototypeNameMap.set(Promise.prototype, 'Promise<unknown>');
builtInPrototypeNameMap.set(Object.prototype, 'Object');
builtInPrototypeNameMap.set(Symbol.prototype, 'Symbol');
builtInPrototypeNameMap.set(WeakMap.prototype, 'WeakMap<object, unknown>');
builtInPrototypeNameMap.set(WeakSet.prototype, 'WeakSet<object>');
builtInPrototypeNameMap.set(BigInt.prototype, 'BigInt');
builtInPrototypeNameMap.set(Node.prototype, 'Node');
builtInPrototypeNameMap.set(Event.prototype, 'Event');
builtInPrototypeNameMap.set(HTMLElement.prototype, 'HTMLElement');
builtInPrototypeNameMap.set(SVGElement.prototype, 'SVGElement');
builtInPrototypeNameMap.set(DocumentFragment.prototype, 'DocumentFragment');
builtInPrototypeNameMap.set(ArrayBuffer.prototype, 'ArrayBuffer');
builtInPrototypeNameMap.set(Int8Array.prototype, 'Int8Array');
builtInPrototypeNameMap.set(Uint8Array.prototype, 'Uint8Array');
builtInPrototypeNameMap.set(Float32Array.prototype, 'Float32Array');
builtInPrototypeNameMap.set(Float64Array.prototype, 'Float64Array');
builtInPrototypeNameMap.set(Error.prototype, 'Error');
builtInPrototypeNameMap.set(TypeError.prototype, 'TypeError');
builtInPrototypeNameMap.set(ReferenceError.prototype, 'ReferenceError');
builtInPrototypeNameMap.set(SyntaxError.prototype, 'SyntaxError');
for (const key of Object.getOwnPropertyNames(window).filter((key) => key.match(/HTML.+Element/))) {
const htmlElementClass = window[key];
builtInPrototypeNameMap.set(htmlElementClass.prototype, key);
}
}
function initObjectPathMap() {
const queue = [];
queue.push({
obj,
path: 'root',
depth: 1
});
while (queue.length > 0) {
const entry = queue.shift();
if (!entry) {
continue;
}
const { obj, path, depth } = entry;
console.debug(`Preprocessing: ${path} (depth: ${depth})`);
if (depth > maxDepth) {
continue;
}
if (obj === null || obj === undefined) {
continue;
}
if (typeof obj !== 'object' && typeof obj !== 'function') {
continue;
}
if (objectPathDepthMap.has(obj)) {
continue;
}
if (builtInPrototypeNameMap.has(obj)) {
continue;
}
let isDuplicate = false;
for (const [fn, sampleObj] of fixDuplicatesMap.entries()) {
if (obj instanceof fn) {
if (sampleObj) {
isDuplicate = true;
break;
}
fixDuplicatesMap.set(fn, obj);
}
}
if (isDuplicate) {
continue;
}
objectPathDepthMap.set(obj, path);
if (typeof obj === 'object') {
if (Array.isArray(obj)) {
for (let index = 0; index < obj.length; index++) {
queue.push({
obj: obj[index],
path: `${path}[${index}]`,
depth: depth + 1
});
}
}
else if (Object.getPrototypeOf(obj) === Map.prototype) {
const map = obj;
queue.push({
obj: Array.from(map.keys()),
path: `Array.from(${path}.keys())`,
depth
});
queue.push({
obj: Array.from(map.values()),
path: `Array.from(${path}.values())`,
depth
});
}
else if (Object.getPrototypeOf(obj) === Set.prototype) {
queue.push({
obj: Array.from(obj),
path,
depth
});
}
else {
queue.push({
obj: Object.getPrototypeOf(obj),
path: `${path}.__proto__`,
depth: depth + 1
});
for (const [key, value] of sortedEntries(obj)) {
queue.push({
obj: value,
path: isValidIdentifier(key) ? `${path}.${key}` : `${path}['${key}']`,
depth: depth + 1
});
}
}
}
else {
if (Object.keys(obj).length > 0) {
const mappedObj = Object.assign({}, obj);
functionObjectMap.set(obj, mappedObj);
queue.push({
obj: mappedObj,
path,
depth
});
}
}
}
}
function sortedEntries(obj) {
return entriesSafe(obj).sort(([key1, value1], [key2, value2]) => (Number(typeof value1 === 'function') - Number(typeof value2 === 'function')) || key1.localeCompare(key2));
}
function entriesSafe(obj) {
const record = obj;
return Object.getOwnPropertyNames(record).map((key) => {
try {
return [key, record[key]];
}
catch (e) {
return [key, undefined];
}
});
}
function inferType({ obj, inArray, path, depth }) {
console.debug(`Inferring type: ${path} (depth: ${depth})`);
for (const [fn, sampleObj] of fixDuplicatesMap.entries()) {
if (obj instanceof fn) {
obj = sampleObj;
}
}
if (obj === null) {
return 'null';
}
if (obj === undefined) {
return 'undefined';
}
let type = objectTypeMap.get(obj) ?? '';
if (type) {
return type;
}
if (typeof obj === 'object') {
if (Array.isArray(obj)) {
type = inferArrayItemType({
arr: obj,
path,
depth
}) + '[]';
}
else if (Object.getPrototypeOf(obj) === Map.prototype) {
const map = obj;
const keysType = inferArrayItemType({
arr: Array.from(map.keys()),
path: `Array.from(${path}.keys())`,
depth
});
const valuesType = inferArrayItemType({
arr: Array.from(map.values()),
path: `Array.from(${path}.values())`,
depth
});
type = `Map<${keysType}, ${valuesType}>`;
}
else if (Object.getPrototypeOf(obj) === Set.prototype) {
const itemsType = inferArrayItemType({
arr: Array.from(obj),
path: `Array.from(${path}.keys())`,
depth
});
type = `Set<${itemsType}>`;
}
else {
type = inferObjectType({
obj,
path,
depth
});
}
}
else if (typeof obj === 'function') {
type = inferFunctionSignature({
fn: obj,
path,
inArray,
depth
});
}
else {
return typeof obj;
}
if (type !== DEPTH_LIMIT_REACHED_TYPE_NAME) {
objectTypeMap.set(obj, type);
if (hasAdditionalKeys(obj)) {
const objType = inferObjectType({
obj: functionObjectMap.get(obj) ?? {},
path,
depth
});
type = `${type} & ${objType}`;
objectTypeMap.set(obj, type);
}
}
return type;
}
function inferArrayItemType({ arr, path, depth }) {
console.debug(`Inferring array type: ${path} (depth: ${depth})`);
if (arr.length === 0) {
return 'unknown';
}
const arrayTypes = new Set(arr.map((item, index) => inferType({
obj: item,
inArray: true,
path: `${path}[${index}]`,
depth
})));
const typesString = Array.from(arrayTypes).join(' | ');
return arrayTypes.size > 1 ? `(${typesString})` : typesString;
}
function inferObjectType({ obj, path, depth }) {
console.debug(`Inferring object type: ${path} (depth: ${depth})`);
const proto = Object.getPrototypeOf(obj);
let builtInType = builtInPrototypeNameMap.get(obj) ?? '';
if (builtInType) {
return builtInType;
}
builtInType = builtInPrototypeNameMap.get(proto) ?? '';
if (builtInType && builtInType !== 'Object') {
return builtInType;
}
if (depth > maxDepth) {
return DEPTH_LIMIT_REACHED_TYPE_NAME;
}
const prefix = obsidianPrototypeNameMap.get(obj) ?? obsidianPrototypeNameMap.get(proto) ?? 'Type';
const type = `${prefix}${customTypes.nextCounter()}`;
objectTypeMap.set(obj, type);
const typeOfProto = inferType({
obj: proto,
inArray: false,
path: `${path}.__proto__`,
depth: depth + 1
});
const objectFieldsStr = sortedEntries(obj)
.map(([key, value]) => {
let formattedKey = isValidIdentifier(key) ? key : `'${key}'`;
const inferredType = inferType({
obj: value,
inArray: hasAdditionalKeys(value),
path: isValidIdentifier(key) ? `${path}.${formattedKey}` : `${path}[${formattedKey}]`,
depth: depth + 1
});
if (formattedKey === 'constructor') {
formattedKey += type;
}
if (typeof value === 'undefined') {
return ` ${formattedKey}?: unknown;`;
}
else if (typeof value === 'function' && !hasAdditionalKeys(value)) {
return ` ${formattedKey}${inferredType};`;
}
else {
return ` ${formattedKey}: ${inferredType};`;
}
})
.join('\n');
if (objectFieldsStr) {
const extendsStr = typeOfProto === 'Object' || typeOfProto === 'null' ? '' : ` extends ${typeOfProto}`;
const definition = `${extendsStr} {\n${objectFieldsStr}\n}`;
const typeWithSameDefinition = customTypes.getByDefinition(definition);
if (typeWithSameDefinition) {
return typeWithSameDefinition;
}
customTypes.set({
type,
definition
});
return type;
}
else {
objectTypeMap.set(obj, typeOfProto);
return typeOfProto;
}
}
function inferFunctionSignature({ fn, path, inArray, depth }) {
console.debug(`Inferring function type: ${path} (depth: ${depth})`);
const fnStr = fn.toString();
const paramList = Array(fn.length).fill(0).map((_, i) => `arg${i + 1}: unknown`).join(', ');
const isAsync = fnStr.includes(' v(this,void 0,') || fnStr.includes('await ');
const returnType = isAsync ? 'Promise<unknown>' : 'unknown';
return inArray ? `((${paramList}) => ${returnType})` : `(${paramList}): ${returnType}`;
}
function isValidIdentifier(key) {
return /^[A-Za-z_$][A-Za-z_$0-9]*$/.test(key);
}
function hasAdditionalKeys(obj) {
return typeof obj !== 'object' && obj !== null && obj !== undefined && Object.keys(obj).length > 0;
}
return main();
}