/
tsparse.ts
73 lines (64 loc) · 1.73 KB
/
tsparse.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
#!/usr/bin/env node
import {ArgumentParser} from 'argparse';
import * as ts from 'typescript';
import * as fs from 'fs';
import * as path from 'path';
export interface Span {
kind: string;
fullStart: number;
start: number;
end: number;
children?: Span[];
}
export interface ParsedFile {
sourceText: string;
spans: Span,
}
let parser = new ArgumentParser({
addHelp: true,
});
parser.addArgument(['-o', '--out'], {
help: 'output path',
});
parser.addArgument(['infile'], {
help: 'input file',
});
let args = parser.parseArgs();
let outfile = process.stdout;
if (args.out) {
outfile = fs.createWriteStream(args.out);
}
let sourceText = fs.readFileSync(args.infile, 'utf8');
let sf = ts.createSourceFile(args.infile, sourceText, ts.ScriptTarget.ES5, true);
function gatherSpans(node: ts.Node): Span {
let children: Span[] = [];
ts.forEachChild(node, (n) => { children.push(gatherSpans(n)); });
if (children.length == 0) {
children = undefined;
}
return {
kind: ts.SyntaxKind[node.kind],
fullStart: node.getFullStart(),
start: node.getStart(),
end: node.getEnd(),
children,
};
}
function readDataFile(name: string): string {
return fs.readFileSync(path.join(__dirname, name), 'utf8');
}
let data: ParsedFile = {
sourceText,
spans: gatherSpans(sf),
};
outfile.write(readDataFile('vis.html'));
outfile.write(`<style>${readDataFile('style.css')}</style>`);
outfile.write('<script>');
outfile.write('(function(data) {');
outfile.write(readDataFile('tsvis.js'));
let json = JSON.stringify(data).replace(/<\/script/g, '</script');
outfile.write(`})(${json});\n`);
outfile.write('</script>')
if (outfile !== process.stdout) {
outfile.end();
}