-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
294 lines (258 loc) · 11.1 KB
/
Copy pathcli.js
File metadata and controls
294 lines (258 loc) · 11.1 KB
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
#!/usr/bin/env node
const fs = require("fs").promises;
const fssync = require("fs");
const path = require("path");
const acorn = require("acorn");
let acornTs = null;
try { acornTs = require("acorn-typescript"); } catch {}
const sourceMap = require("source-map");
const crypto = require("crypto");
const zlib = require("zlib");
// ANSI colors
const colors = {
reset: "\x1b[0m",
red: "\x1b[31m",
green: "\x1b[32m",
yellow: "\x1b[33m",
cyan: "\x1b[36m",
blue: "\x1b[34m",
gray: "\x1b[90m"
};
// CLI args
const args = process.argv.slice(2);
const getArg = (flag, def) => {
const i = args.indexOf(flag);
return i >= 0 && args[i + 1] ? args[i + 1] : def;
};
// Config
const config = {
srcDir: path.resolve(getArg("--src", "src")),
outDir: path.resolve(getArg("--out", "out")),
outFile: path.join(path.resolve(getArg("--out", "out")), getArg("--file", "bundle.js")),
outMapFile: path.join(path.resolve(getArg("--out", "out")), getArg("--map", "bundle.js.map")),
cacheDir: path.join(path.resolve(getArg("--out", "out")), ".cache"),
analyze: getArg("--analyze", "false") === "true",
verbose: getArg("--verbose", "false") === "true"
};
// Builtins never to mangle even if locally declared
const hardReserved = new Set([
"console","window","document","global","globalThis",
"fetch","setTimeout","clearTimeout","setInterval","clearInterval",
"JSON","Error","Promise","Array","Object","String","Number","Boolean",
"Symbol","BigInt","Math","Date","RegExp","Map","Set","WeakMap","WeakSet",
"URL","URLSearchParams","Intl","Reflect","Proxy","Function"
]);
// ---------- Utilities ----------
const bytes = n => `${n} B`;
const kb = n => `${(n/1024).toFixed(2)} KB`;
class Cache {
constructor(dir){ this.dir = dir; }
_key(file){ return path.join(this.dir, crypto.createHash("md5").update(file).digest("hex") + ".json"); }
async load(file){
try {
const p = this._key(file);
const s = await fs.readFile(p, "utf8");
return JSON.parse(s);
} catch { return null; }
}
async save(file, data){
await fs.mkdir(this.dir, { recursive: true });
await fs.writeFile(this._key(file), JSON.stringify(data));
}
}
function parseWithAcorn(filename, code) {
const isTs = /\.(ts|tsx)$/.test(filename);
if (isTs && acornTs) {
return acornTs.parse(code, { ecmaVersion: "latest", sourceType: "module" });
}
return acorn.parse(code, { ecmaVersion: "latest", sourceType: "module" });
}
function walk(node, cb, parent = null) {
cb(node, parent);
for (const k in node) {
if (!Object.prototype.hasOwnProperty.call(node, k)) continue;
const v = node[k];
if (v && typeof v === "object") {
if (Array.isArray(v)) v.forEach(n => n && walk(n, cb, node));
else walk(v, cb, node);
}
}
}
// Collect declared, imported, exported
function collectDeclaredBindings(ast) {
const declared = new Set();
const imported = new Set();
const exported = new Set();
function addPatternIds(pat) {
if (!pat) return;
switch (pat.type) {
case "Identifier": declared.add(pat.name); break;
case "ObjectPattern": pat.properties.forEach(prop => {
if (prop.type === "Property") addPatternIds(prop.value);
else if (prop.type === "RestElement") addPatternIds(prop.argument);
}); break;
case "ArrayPattern": pat.elements.forEach(el => addPatternIds(el)); break;
case "RestElement": addPatternIds(pat.argument); break;
case "AssignmentPattern": addPatternIds(pat.left); break;
}
}
walk(ast, (node) => {
if (node.type === "VariableDeclaration") node.declarations.forEach(d => addPatternIds(d.id));
if (node.type === "FunctionDeclaration" && node.id) declared.add(node.id.name);
if (node.type === "ClassDeclaration" && node.id) declared.add(node.id.name);
if ((node.type==="FunctionDeclaration"||node.type==="FunctionExpression"||node.type==="ArrowFunctionExpression") && node.params) node.params.forEach(p => addPatternIds(p));
if (node.type==="CatchClause" && node.param) addPatternIds(node.param);
if (node.type==="ImportDeclaration") node.specifiers.forEach(sp => { if(sp.local?.name) imported.add(sp.local.name); });
if (node.type==="ExportNamedDeclaration") {
if(node.declaration) {
if(node.declaration.id?.name) exported.add(node.declaration.id.name);
if(node.declaration.declarations) node.declaration.declarations.forEach(d => { if(d.id.type==="Identifier") exported.add(d.id.name); });
}
if(node.specifiers) node.specifiers.forEach(sp => { if(sp.exported?.name) exported.add(sp.exported.name); if(sp.local?.name) exported.add(sp.local.name); });
}
if(node.type==="ExportDefaultDeclaration" && node.declaration?.id?.name) exported.add(node.declaration.id.name);
});
return { declared, imported, exported };
}
// Collect free identifiers
function collectFreeIdentifiers(ast, declared, imported) {
const seen = new Set();
walk(ast, (node, parent) => {
if (node.type==="Identifier") {
const name=node.name;
if(parent?.type==="MemberExpression" && parent.property===node && !parent.computed) return;
if(parent?.type==="Property" && parent.key===node && !parent.computed) return;
if(parent?.type==="LabeledStatement") return;
if(parent?.type==="ImportSpecifier" || parent?.type==="ImportDefaultSpecifier" || parent?.type==="ImportNamespaceSpecifier") return;
if(parent?.type==="ExportSpecifier") return;
if(!declared.has(name) && !imported.has(name)) seen.add(name);
}
});
return seen;
}
// Minifier
class Minifier {
constructor(opts={}) { this.names=new Map(); this.counter=0; this.verbose=!!opts.verbose; }
generateName() {
const chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
let name="", c=this.counter++;
do { name = chars[c%chars.length]+name; c=Math.floor(c/chars.length); } while(c>0);
return name+Math.floor(Math.random()*10000);
}
async minifyFile(filename, code, cache) {
const hash = crypto.createHash("md5").update(code).digest("hex");
const cached = await cache.load(filename);
if(cached && cached.hash===hash) return cached.minified;
let ast;
try { ast=parseWithAcorn(filename, code); } catch(e){ return {error:`Parse error: ${e.message}`, line:e.loc?.line, column:e.loc?.column}; }
const {declared, imported, exported} = collectDeclaredBindings(ast);
const free = collectFreeIdentifiers(ast, declared, imported);
const toMangle = new Set();
for(const name of declared){
if(hardReserved.has(name)) continue;
if(imported.has(name) || exported.has(name)) continue;
if(free.has(name)) continue;
try{ if(name in globalThis && typeof globalThis[name]!=="undefined") continue; } catch{}
toMangle.add(name);
}
for(const name of toMangle){
if(!this.names.has(name)){
const mangled=this.generateName();
this.names.set(name, mangled);
if(this.verbose) console.log(`${colors.cyan}mangle${colors.reset} ${name} -> ${mangled}`);
}
}
const literals=[];
const literalRegex=/(['"`])(?:\\[\s\S]|(?!\1).)*\1/g;
let safe = code.replace(literalRegex, m=>{ literals.push(m); return `__LIT_${literals.length-1}__`; });
safe = safe.replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1").replace(/\s+/g," ").replace(/\s*([{}();,:=+\-*/<>])\s*/g,"$1").replace(/;+/g,";");
for(const [orig,mangled] of this.names.entries()){
const re=new RegExp(`(?<!\\.)\\b${orig}\\b`,"g");
safe=safe.replace(re,mangled);
}
literals.forEach((lit,i)=>{ safe=safe.replace(`__LIT_${i}__`,lit); });
try{ parseWithAcorn(filename, safe); } catch(e){ return {error:`Post-minify parse error: ${e.message}`, line:e.loc?.line, column:e.loc?.column}; }
const trimmed=safe.trim();
await cache.save(filename, {hash,minified:trimmed});
return trimmed;
}
}
// Bundle analysis
function analyzeBundle(bundle){
const size=Buffer.byteLength(bundle,"utf8");
return {
sizeBytes:size,
sizeKB:(size/1024).toFixed(2),
lines:bundle.split("\n").length,
functions:(bundle.match(/\bfunction\b/g)||[]).length,
variables:(bundle.match(/\b(let|const|var)\b/g)||[]).length,
gzipBytes:zlib.gzipSync(bundle).length
};
}
// ---------- Main ----------
async function main(){
// Validate src dir
try{
const st = await fs.stat(config.srcDir);
if(!st.isDirectory()) throw new Error("src is not a directory");
}catch{
console.error(`${colors.red}Error:${colors.reset} Source directory not found: ${config.srcDir}`);
process.exit(1);
}
await fs.mkdir(config.outDir,{recursive:true});
// Gather files
let files=(await fs.readdir(config.srcDir)).filter(f=>/\.(js|ts|jsx|tsx)$/.test(f)).map(f=>path.join(config.srcDir,f));
if(files.length===0){ console.error(`${colors.red}Error:${colors.reset} No source files found`); process.exit(1); }
files.sort((a,b)=>a.localeCompare(b));
// ---------- Pre-validate ----------
console.log(colors.cyan+"Validating source files..."+colors.reset);
const preStatuses=[];
for(const file of files){
let code;
try{ code=await fs.readFile(file,"utf8"); } catch(e){ preStatuses.push({file,status:"Failed",error:`Read error: ${e.message}`}); continue; }
try{ parseWithAcorn(file, code); preStatuses.push({file,status:"OK",code}); }
catch(e){ preStatuses.push({file,status:"Failed",error:`Syntax error: ${e.message} (line ${e.loc?.line}, col ${e.loc?.column})`}); }
}
// Show table
preStatuses.forEach(s=>console.log(`${s.status==="OK"?colors.green:colors.red}${s.status.padEnd(8)}${colors.reset} ${s.file}${s.error?` --> ${s.error}`:""}`));
const validFiles=preStatuses.filter(s=>s.status==="OK");
if(validFiles.length===0){ console.error(`${colors.red}Error:${colors.reset} No valid source files. Exiting.`); process.exit(1); }
// ---------- Minify files ----------
const cache=new Cache(config.cacheDir);
const minifier=new Minifier({verbose:config.verbose});
const statuses=[];
for(const s of validFiles){
const file=s.file, code=s.code;
const before=Buffer.byteLength(code,"utf8");
const result=await minifier.minifyFile(file, code, cache);
if(result?.error) statuses.push({file,status:"Failed",color:colors.red,error:result.error});
else{
const after=Buffer.byteLength(result,"utf8");
statuses.push({file,status:"OK",color:colors.green,before,after,content:result});
}
}
// Print minify table
console.log(colors.cyan+"\nMinification results:"+colors.reset);
const hdr=`${"Status".padEnd(8)} ${"Before".padStart(8)} ${"After".padStart(8)} File`;
console.log(colors.gray+hdr+colors.reset);
statuses.forEach(s=>{
const before=s.before!=null?kb(s.before).padStart(8):"".padStart(8);
const after=s.after!=null?kb(s.after).padStart(8):"".padStart(8);
console.log(`${s.color}${s.status.padEnd(8)}${colors.reset} ${before} ${after} ${s.file}${s.error?` (${s.error})`:""}`);
});
// ---------- Bundle ----------
const bundle="(async()=>{\n"+statuses.filter(s=>s.status==="OK").map(s=>s.content).join("\n")+"\n})();\n";
await fs.writeFile(config.outFile,bundle,"utf8");
console.log(`${colors.green}Bundle written:${colors.reset} ${config.outFile}`);
// Optional analysis
if(config.analyze){
const stats=analyzeBundle(bundle);
console.log(colors.cyan+"Bundle analysis:"+colors.reset);
console.log(`Size: ${kb(stats.sizeBytes)} (${stats.lines} lines), Functions: ${stats.functions}, Vars: ${stats.variables}, Gzip: ${kb(stats.gzipBytes)}`);
}
}
// Entrypoint
main().catch(err=>{
console.error(`${colors.red}Fatal Error:${colors.reset} ${err?.stack||err?.message||err}`);
process.exit(1);
});