-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTypeBuilder.js
646 lines (487 loc) · 20.4 KB
/
TypeBuilder.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
/* eslint-disable no-useless-escape */
/* eslint-disable @typescript-eslint/no-this-alias */
/* eslint-disable @typescript-eslint/no-var-requires */
console.log("******************");
console.log("* *");
console.log("* TYPE BUILDER *");
console.log("* *");
console.log("******************");
let pth = require('path');
let fs = require('fs');
let chokidar = require('chokidar');
let stringExtractor = require('extract-string');
let stripComments = require('strip-json-comments');
const mkdirp = require('mkdirp');
let TypeBuilder = function() {
let self = this;
self.replace = function(oldStr, newStr, buf) {
if (!buf || buf.length === 0) {
return '';
}
let re = new RegExp(oldStr, "g");
let outStr = buf.replace(re, newStr);
return outStr;
};
// NOTE this will blow up on function params with comments next to them that contain
// parenthesis
self.extractSelfTypes = function(buf, regex, types, offset=5) {
// extract all dot function stuff
// extract all dot stuff
//let regex = /self(\.[A-Za-z\_]+)+/g;
let result = buf.match(regex);
if (!result) {
// also happens if file has no self references
//console.warn("No types found for " + regex);
return;
}
//console.log(result);
let norm = {};
result.map(function(item) {
//console.log("found " + item);
let key = item.substring(offset); // remove self
// need to support variadic args
key = self.replace('[.][.][.]','_elip_', key);
//thread.console.info(key);
let subtypes = key.split(".");
norm[subtypes[0]] = true;
//thread.console.info(key);
});
//console.log(norm);
Object.keys(norm).map(function(item) {
//thread.console.info('-->' + item);
item = self.replace('_elip_','...', item);
if (Reflect.has(types, item)) {
console.error("ERROR: Multiple definitions found for [" + item + "]");
} else {
types[item] = norm[item];
}
});
};
self.bufferToLines = function(buf) {
if (buf && buf.replace)
return buf.replace(/\r\n/, "\n").split("\n");
else
return [];
};
self.processBuffer = function(buf, typeName, basePath, outRoot) {
let types = {};
let regex;
// grab functions first
let classRefs = {};
regex = /self(\.[A-Z0-9a-z\_]+)+(\s*)[=](\s*)(function|async(\s*)function)([\s\S]*?)[\)]([\s\S]*?)[\{]/g;
self.extractSelfTypes(buf, regex, types);
//console.log(types);
let outTypes = {};
Object.keys(types).map(function(ti) {
let offset = ti.indexOf("=");
let memberName = ti.substring(0,offset).trim();
let decl = ti.substring(offset);
//thread.console.debug("outtypes foo", decl);
if(ti.indexOf(":") >= 0) {
//thread.console.info("typebuilder parsing " + ti);
//let args = decl.substring(decl.indexOf("function") + 8);
let argsSection = decl.substring(decl.indexOf("("));
// look for return type
let endOffset = argsSection.lastIndexOf(")");
let retSection = argsSection.substring(endOffset);
let retType = "any";
let retOffset = retSection.indexOf(":");
if (retOffset >=0) {
let retEndOffset = retSection.lastIndexOf("{");
retType = retSection.substring(retOffset+1, retEndOffset - retOffset).trim();
if ((retType.endsWith("T")||retType.endsWith("DBT")) && !Reflect.has(classRefs, retType)) {
// assume external class reference
classRefs[retType] = true;
} else if (retType.startsWith("Promise<")) {
// dealing w a Promise decl - this is a hack mess
console.log("GOT PROMISE: " + retType);
//retType = retType.trim();
let innerRetType = retType.substring(8,retType.length-1);
if (innerRetType.startsWith("Array<")) {
innerRetType = innerRetType.substring(6,innerRetType.length-1);
}
if (innerRetType != 'any') {
classRefs[innerRetType] = true;
}
console.log("Extracted promise type: " + innerRetType);
}
}
let args = argsSection.substring(1,endOffset);
args = args.trim();
//console.log("args: " + args);
// remove param initializers
let newArgs = [];
args.split(",").map(function(arg) {
//console.log("arg: " + arg);
let ei = arg.indexOf("=");
if (ei >=0) {
// contains default initializer; make optional?
arg = arg.substring(0, ei);
let faOffset = arg.indexOf(":");
if (faOffset >=0) {
let first = arg.substring(0,faOffset);
let last = arg.substring(faOffset+1, arg.length);
arg = first + "?:" + last;
}
}
newArgs.push(arg);
});
args = "(" + newArgs.join(",") + ")";
//console.log("ret section: " + retSection);
//console.log("ret type: " + retType);
ti = memberName + args.trim() + ":" + retType + ";";
console.log("==> " + ti);
let paramList = args.substring(1, args.length-1);
let params = paramList.split(",");
//thread.console.info("params: ", params);
params.map(function(p) {
let tok = p.split(":");
if (tok.length > 1) {
let className = tok[1].trim();
if (className.startsWith("?")) {
className = className.substring(1);
}
if (className.startsWith("Array<")) {
className = className.substring(6,className.length-1);
}
//thread.console.info("class: " + className);
if ((className.endsWith("T")||className.endsWith("DBX")) && !Reflect.has(classRefs, className)) {
// assume external class reference
classRefs[className] = true;
}
}
});
} else {
ti = memberName + ":Function;";
}
// now build final buffer
if (memberName.length > 0) {
outTypes[memberName] = ti;//memberName + ":Function;\n" + ti;
} else {
//thread.console.softError("Skipped " + ti);
}
});
//thread.console.info("typebuilder regex functions", outTypes);
types = {}; // reset types
regex = /self(\.[A-Za-z\_]+)(\s*)\(+/g;
self.extractSelfTypes(buf, regex, types);
let danglingSelfCalls = {};
Object.keys(types).map(function(memberName) {
memberName=memberName.replace(" ","");
let callFunc = memberName.substring(0, memberName.length-1);
if (!outTypes[callFunc]) {
danglingSelfCalls[callFunc] = true;
}
});
//thread.console.info("typebuilder self calls", danglingSelfCalls);
types = {}; // reset types
regex = /self(\.[A-Za-z\_]+)(\s*)\=(?!\=)+/g;
self.extractSelfTypes(buf, regex, types);
let assigns = {};
Object.keys(types).map(function(memberName) {
memberName=memberName.replace(" ","");
let assign = memberName.substring(0, memberName.length-1);
if (!outTypes[assign]) {
assigns[assign] = assign + ": any;";
}
});
//thread.console.info("typebuilder assigns", assigns);
types = {};
regex = /self(\.[A-Za-z\_]T+)+/g;
self.extractSelfTypes(buf, regex, types);
Object.keys(types).map(function(memberName) {
if (outTypes[memberName]) {
// already found as a function
//thread.console.softError("Conflict found for member [" + memberName + "]");
} else {
if (danglingSelfCalls[memberName]) {
console.warn("Dangling reference to self function: " + memberName);
} else if (!danglingSelfCalls[memberName]) {
// unknown member
outTypes[memberName] = memberName + ": any;";
} else if (!assigns[memberName]){
// need to ignore the db autogen methods
if (memberName != "get" && !typeName.endsWith("MgrT"))
console.warn("Possible reference to missing self function: " + memberName);
}
}
});
outTypes = Object.assign(assigns, outTypes);
//thread.console.info("typebuilder out types", outTypes);
types = {};
regex = /type (\s*)([A-Za-z\_]+)T(\s*)=/g;
self.extractSelfTypes(buf, regex, types);
let classDecls = {};
Object.keys(types).map(function(memberName) {
memberName=memberName.replace(" ","");
let typeName = memberName.substring(0, memberName.length-1);
//thread.console.warn("Found type decl for " + typeName);
classDecls[typeName] = true;
});
//thread.console.info("typebuilder class decls", classDecls);
//console.log("===> CURR DIR: " + __dirname);
//console.log("===> BASE PATH: " + basePath);
//let targetPath = __dirname + "/src/types";
//console.log("===> TARGET PATH: " + targetPath);
//let commonPath = __dirname + "/src/common";
//console.log("===> COMMON PATH: " + commonPath);
//let relPath = pth.relative(targetPath, commonPath);
//console.log("===> REL PATH: " + relPath);
// now pull in all imports
let importBuf = "";
let classImports = {};
let lines = self.bufferToLines(buf);
lines.map(function(line) {
let recArr = stringExtractor(line).pattern('import{typeName}from{path}');
if (recArr.length>0) {
let rec = recArr[0];
if (!rec.typeName) {
console.error("ERROR: Failed to get import type name: " + line);
return;
}
rec.typeName = rec.typeName.trim();
rec.path = rec.path.trim();
//console.log(rec);
let typeRec = stringExtractor(rec.typeName).pattern("\{{typeName}\}")[0];
//console.log(typeRec);
if (!typeRec) {
console.error("ERROR: Failed to extract type record: " + line);
return;
}
if (!typeRec.typeName) {
console.error("ERROR: Failed to find type name: " + line);
return;
}
let typeName = typeRec.typeName.trim();
let pathRec = stringExtractor(rec.path).pattern("\"{path}\"")[0];
if (!pathRec) {
// may happen with newer import declarations
console.error("ERROR: Unable to extract path declaration; check source file");
return;
}
//console.log(pathRec);
let pathName = pathRec.path.trim();
if (pathName.indexOf("/common/") >= 0 || pathName.indexOf("/dbtypes/") >= 0) {
console.log(typeName + " " + pathName);
classImports[typeName] = true;
// yeah the path stuff is a little hacky
//console.log("===> FINAL PATH: " + pathName);
//pathName = "./src/" + pathName;
let foo = "import type {" + typeName + "} from \"" + pathName + "\"\n";
//console.log("COMMON ===> " + foo);
importBuf += foo;
}
}
});
// dangling stuff
let extraImportBuf = "";
Object.keys(classRefs).map(function(cr) {
if (cr.endsWith("T")) {
// if not declared locally then import
if (!classImports[cr]) {
//console.log("===> COMMON PATH NAME: " + cr);
//let relPath = pth.relative(cr, outRoot)
//console.log("===> COMMON REL PATH: " + relPath);
let foo = `import {${cr}} from "./${cr}";\n`;
//console.log("===> " + foo);
extraImportBuf += foo;
} else {
extraImportBuf += `// ${cr} declared locally \n`;
}
}
});
//thread.console.info("typebuilder regex", outTypes);
// BUILD THE OUTPUT BUFFER
let typeBuf = `
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/ban-types */
// AUTOGENERATED from TypeBuilder on ${new Date()}
// NOTE: If TSC cannot find a name, it is probably because the
// TypeBuilder missed a dangling import during parsing
// path
// ${basePath}
// copied imports
${importBuf}
// dangling imports
${extraImportBuf}
// unresolved
//${Object.keys(classDecls)}
export type ${typeName} = {\n
`;
let itemArr = [];
Object.keys(outTypes).map(function(typ) {
itemArr.push(outTypes[typ]);
});
typeBuf += " " + itemArr.join("\n ");
typeBuf += `
};\n`;
return typeBuf;
}; // end processBuffer
self.watch = function(filePath, callback) {
let watcher = chokidar.watch([], {
cwd: filePath,
/*
usePolling: true,
interval: 1000,
*/
depth:0
});
watcher.on("all", function (event, rawPath) {
// convert any backslashes to forward
let fullPath = rawPath.replace("\\", "/");
// add, addDir, change, unlink, unlinkDir
callback(fullPath, event);
});
watcher.add(filePath);
return watcher;
};
self.loadFileSync = function (resPath) {
let fullPath = pth.resolve(resPath);
//thread.console.debug("Loading [" + fullPath + "]");
let data = fs.readFileSync(fullPath, 'utf-8');
return data;
};
self.saveFileSync = function (buf, path) {
console.log("SAVING file " + path);
fs.writeFileSync(path, buf, 'utf-8');
};
self.getExt = function(thePath) {
return pth.extname(thePath);
};
self.getBaseName = function(thePath) {
thePath = self.replace("/",".",thePath);
let segs = thePath.split(".");
if (!segs.length) {
// something bad happened
return;
}
if (segs.length === 1) {
return segs[0];
}
let root = segs[segs.length-2];
let extName = segs[segs.length-1];
return root;
};
self.debounce = function(func, wait=150, immediate) {
let timeout;
return function() {
let context = this, args = arguments;
let later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
let callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
self.terminate = true;
self.idle = self.debounce(function() {
console.log("Waiting");
if (self.terminate) {
console.log("Terminating (use -w for watch mode)");
process.exit();
}
}, 2000);
self.scanFiles = function(relPath) {
// build type system
console.log("Scanning " + relPath);
let watcher = self.watch(process.cwd() + relPath,
// process type for each .js file
function(fullPath, event) {
if (fullPath.length === 0 ||
fullPath.startsWith(".")) {
return;
}
console.log(event + ": " + fullPath);
// ignore anything called OLD
if (fullPath.endsWith("OLD.js"))
return;
let extName = self.getExt(fullPath);
if (extName != ".ts" && extName != ".js") {
//console.log("IGNORED " + fullPath);
return;
}
//console.log("PROCESSING " + fullPath + " [" + event + "]");
let actualPath = process.cwd() + relPath + "/" + fullPath;
let typeName = self.getBaseName(fullPath) + "T";
switch(event) {
case 'add':
case 'change':
{
console.log("===> REL PATH: " + relPath);
let outRoot = process.cwd() + "/src/types/";
// some hacky shit here because selftyped/web and selftyped/dsl at different level of indenture
// than /types
if (relPath === "/src/selftyped/web") {
outRoot += "web/";
}
if (relPath === "/src/selftyped/dsl") {
outRoot += "dsl/";
}
mkdirp.sync(outRoot);
let outPath = outRoot + typeName + ".ts";
console.log("===> PROCESSING [" + actualPath + "] to [" + outPath + "]");
let buf = self.loadFileSync(actualPath);
// strip comments may do bad things to the untyped stuff
if (actualPath.indexOf("/src/untyped")<0) {
buf = stripComments(buf);
}
let outBuf = self.processBuffer(buf, typeName, relPath, outRoot);
self.saveFileSync(outBuf, outPath);
/*
exec("/bin/cat src/flow/*.js > src/flow/AllTypes.ts", function(err, stdout, stderr) {
if (err) {
console.log(err);
return;
}
if (stderr) {
console.log(stderr);
}
});
*/
self.idle();
break;
}
case 'unlink':
case 'unlinkDir':
break;
default:
break;
}
}
);
};
self.run = function() {
console.log("Starting");
let args = process.argv;
let runForever = args[2];
if (runForever) {
if (runForever === "-w") {
self.terminate = false;
console.log("Running in watch mode");
} else {
console.error("ERROR: Unknown parameter: " + runForever);
return;
}
} else {
console.log("Running in single pass mode");
}
self.scanFiles("/src/untyped"); // untyped still gets a basic template
//self.scanFiles("/src/common"); // already types; don't overcook
self.scanFiles("/src/selftyped");
self.scanFiles("/src/browser");
console.log("Done"); // we normally don't get here because we go to idle()
self.idle();
};
return self;
};
try {
let tb = new TypeBuilder();
tb.run();
} catch (err) {
console.error(err);
}
module.exports = { class: TypeBuilder };