-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
192 lines (190 loc) · 6 KB
/
main.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
#!/usr/bin/env node
// Copyright (c) 2022 System233
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
import * as espree from 'espree'
import { readFile, writeFile } from 'fs/promises'
import { basename, dirname } from 'path';
import {ProtobufModule, SearchModule, ToProtoString} from './index'
import {displayName,version,description,time,commit,refname} from './app.json'
const TITLE=`This file is decompiled by depbjs v${version}.`;
interface OptionType{
text:string;
number:number,
bool:boolean
};
interface Option{
type:keyof OptionType,
required?:boolean,
message:string,
default?:any;
}
const OPTIONS={
// input:{
// type:'text',
// required:true,
// message:'Target script input path.'
// },
output:{
type:'text',
required:true,
message:'Output path of result.'
},
space:{
type:'number',
required:false,
default:4,
message:'Number of indent spaces in .proto output.'
},
depth:{
type:'number',
default:1000,
message:'Maximum recursion depth.'
},
ecmaVersion:{
type:'text',
default:'latest',
message:'ECMA version: 3, 5, 6-12, 2015-2022.'
},
type:{
type:'text',
default:'script',
message:'Source type: script, commonjs, module.'
},
jsx:{
type:'bool',
default:false,
message:'Enable JSX parsing.'
},
format:{
type:'text',
default:'proto',
message:'Output format: json, proto.'
},
notitle:{
type:'bool',
default:false,
message:'Do not show title in output.'
},
help:{
type:'bool',
message:'Show this message.'
},
};
const showTitle=(help:boolean)=>{
(help?console.log:console.error)(`${displayName} ${version} (${refname}:${commit} ${time})`);
}
const showHelp=()=>{
showTitle(true);
console.log(`${description}`);
console.log('Option:')
Object.entries(OPTIONS as Record<string,Option>).forEach(([name,value])=>{
console.log(`\t-${name[0]} --${name}\t${value.message}\t${value.default!=null?`default=${value.default}`:''}`);
})
console.log('usage: depbjs input1.js input2.js ... (or pipe) -o target.proto');
}
const getOptions=()=>{
const set=new Set<number>();
const error=(msg:string)=>{
console.error(`Error: ${msg}`)
showHelp();
process.exit(-1);
}
const options=Object.fromEntries(Object.entries(OPTIONS as Record<string,Option>).map(([name,opt])=>{
const paramNames=[`-${name[0]}`,`--${name}`];
const index=process.argv.findIndex(x=>paramNames.includes(x));
set.add(index);
if(opt.type=='bool'){
return [name,index!=-1]
}
if(index==-1){
if((opt.required&&!opt.default)){
error(`Required '--${name}' option.`);
}
return [name,opt.default];
}
if(index+1>=process.argv.length){
error(`Option '${name}' need a params.`);
}
set.add(index+1);
const value=process.argv[index+1];
if(opt.type=='text'){
return [name,value];
}
return [name,parseFloat(value)];
})) as Record<keyof typeof OPTIONS,any>;
const inputs=process.argv.filter((_,i)=>i>=2&&!set.has(i));
if(!inputs.length){
error(`No script input.`);
}
return {options,inputs};
}
const main=async()=>{
const {options,inputs}=getOptions();
if(options.help){
showHelp();
}else{
showTitle(false);
const read=(path:string)=>{
if(path=='-'){
process.stdin.setEncoding('utf-8');
return new Promise((resolve)=>{
const data:string[]=[];
process.stdin.on('readable',()=>data.push(process.stdin.read()))
process.stdin.on('end',()=>resolve(data.join('')));
});
}else{
return readFile(path,'utf-8')
}
}
const modules=await Promise.all(inputs.map(async path=>{
const source=await read(path);
const module=espree.parse(source,{
ecmaVersion:options.ecmaVersion,
sourceType: options.type,
ecmaFeatures:{
jsx:options.jsx
}
});
return SearchModule(module, options.depth).map(module=>({source:path,module}));
})).then(x=>x.flat());
const getHeader=(path:string)=>{
if(options.notitle){
return '';
}
const inputName=path=='-'?'stdin':path;
return [
'',
TITLE,
`source: ${inputName}`,
''
].map(x=>`// ${x}\n`).join('')+'\n'
}
const wirteToFile=(path:string,data:string,index?:number)=>{
if(path=='-'){
console.log(data);
return;
}
const output=index!=null&&modules.length>1?`${dirname(path)}/${basename(path,'.'+options.format)}.${index}.${options.format}`:options.output;
console.error(`Writing to ${output}`);
return writeFile(output,data);
}
const dump=async(source:string,module:ProtobufModule,index:number)=>{
const data=getHeader(source)+ToProtoString(module,options.space);
return wirteToFile(options.output,data,index);
}
if(modules.length){
if(options.format=='json'){
await wirteToFile(options.output,JSON.stringify(modules,null,options.space),null);
}else if(options.format=='proto'){
await Promise.all(modules.map((module,index)=>dump(module.source,module.module,index)));
}else{
console.error(`Unknown output format '${options.format}'.`)
}
}else{
console.error(`Nothing Found in '${inputs}'.`)
}
}
}
main();