// 構文エラーの位置を、行番号つきで出す。
import fs from 'fs';
import vm from 'vm';
const file = process.argv[2] || 'build/index.html';
const s = fs.readFileSync(file, 'utf8');
const re = /<script>([\s\S]*?)<\/script>/g;
let m, n = 0;
while ((m = re.exec(s))) {
  n++;
  const code = m[1];
  try { new vm.Script(code, { filename: `script${n}.js` }); }
  catch (e) {
    console.log(`script#${n}: ${e.message}`);
    const stack = String(e.stack).split('\n');
    console.log(stack.slice(0, 5).join('\n'));
    const lm = stack[0].match(/script\d+\.js:(\d+)/);
    const ln = lm ? Number(lm[1]) : null;
    if (ln) {
      const lines = code.split('\n');
      for (let i = Math.max(0, ln - 4); i < Math.min(lines.length, ln + 2); i++)
        console.log(String(i + 1).padStart(6) + (i + 1 === ln ? ' >> ' : '    ') + lines[i].slice(0, 220));
    }
    process.exit(1);
  }
}
console.log('構文 OK');
