41 lines
1.6 KiB
JavaScript
41 lines
1.6 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});
|
|
function balanced(subset){
|
|
const st=[]; const open={')':'(',']':'[','}':'{'};
|
|
for(const t of subset){
|
|
const v=t.value;
|
|
if(v==='{'||v==='('||v==='[') st.push(v);
|
|
else if(v==='}'||v===')'||v===']'){ if(!st.length||st[st.length-1]!==open[v]) return false; st.pop(); }
|
|
}
|
|
return st.length===0;
|
|
}
|
|
// sanity: full set should NOT balance
|
|
console.log('full balances?', balanced(toks));
|
|
// find the { token whose removal balances everything; report candidates
|
|
const cand=[];
|
|
for(let i=0;i<toks.length;i++){
|
|
if(toks[i].value==='{'){
|
|
const sub=toks.slice(0,i).concat(toks.slice(i+1));
|
|
if(balanced(sub)){ cand.push({i, line:toks[i].loc.start.line, col:toks[i].loc.start.column}); }
|
|
}
|
|
}
|
|
console.log('removable { candidates (file line):');
|
|
const cl=code.split('\n');
|
|
for(const c of cand.slice(0,8)){
|
|
const fl=c.line+base-1;
|
|
console.log(' script-line '+c.line+' col '+c.col+' => FILE line '+fl+' : '+JSON.stringify(cl[c.line-1]));
|
|
}
|
|
// also test removing a '(' in case it's a paren issue
|
|
const pc=[];
|
|
for(let i=0;i<toks.length;i++){
|
|
if(toks[i].value==='('){
|
|
if(balanced(toks.slice(0,i).concat(toks.slice(i+1)))) pc.push({line:toks[i].loc.start.line,col:toks[i].loc.start.column});
|
|
}
|
|
}
|
|
if(pc.length) console.log('removable ( candidates:', pc.slice(0,4).map(p=>'L'+(p.line+base-1)));
|