25 lines
1.3 KiB
JavaScript
25 lines
1.3 KiB
JavaScript
const fs=require('fs');
|
|
const espree=require('/opt/homebrew/lib/node_modules/eslint/node_modules/espree/dist/espree.cjs');
|
|
const src=fs.readFileSync('index.html','utf8');
|
|
const m=src.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);
|
|
const code=m[1];
|
|
const base=src.slice(0,src.indexOf('<script')).split('\n').length;
|
|
const toks=espree.tokenize(code,{ecmaVersion:2022,loc:true});
|
|
const codeLines=code.split('\n');
|
|
function parses(c){try{espree.parse(c,{ecmaVersion:2022,sourceType:'script',allowReturnOutsideFunction:true});return true;}catch(e){return false;}}
|
|
// map each token to its absolute char offset in code, then remove that single char
|
|
// build offset index: line/col -> char index
|
|
const lineStarts=[0];
|
|
for(const ln of codeLines){ lineStarts.push(lineStarts[lineStarts.length-1]+ln.length+1); }
|
|
let hits=[];
|
|
for(const t of toks){
|
|
if(!'{([]}'.includes(t.value)) continue;
|
|
const off=lineStarts[t.loc.start.line-1]+t.loc.start.column;
|
|
const mod=code.slice(0,off)+code.slice(off+1);
|
|
if(parses(mod)){
|
|
hits.push({val:t.value, line:t.loc.start.line, col:t.loc.start.column, file:t.loc.start.line+base-1, ctx:codeLines[t.loc.start.line-1]});
|
|
}
|
|
}
|
|
console.log('bracket removals that PARSE: '+hits.length);
|
|
for(const h of hits) console.log(' remove '+h.val+' at FILE line '+h.file+' col '+h.col+' :: '+JSON.stringify(h.ctx));
|