import cheerio from "cheerio";
import * as eslexer from "es-module-lexer";
import fetch from "node-fetch";
import fs from "fs";
import slash from "slash";
import glob from "tiny-glob";
import {fileURLToPath} from "url";
async function scan(cwd, pattern) {
  const results = await glob(pattern, {cwd: fileURLToPath(cwd)});
  return results.map((filepath) => new URL(slash(filepath), cwd));
}
async function profileHTML({cwd}) {
  const sizes = {};
  const html = await scan(cwd, "**/*.html");
  let maxSize = 0;
  await Promise.all(html.map(async (file) => {
    const relPath = file.pathname.replace(cwd.pathname, "");
    const size = (await fs.promises.stat(file)).size;
    sizes[relPath] = size;
    if (size > maxSize)
      maxSize = size;
  }));
  return {
    html: sizes,
    maxSize
  };
}
async function profileJS({cwd, entryHTML}) {
  const sizes = {};
  let htmlSize = 0;
  if (entryHTML) {
    let $ = cheerio.load(await fs.promises.readFile(entryHTML));
    let entryScripts = [];
    let visitedEntry = false;
    $("script").each((n, el) => {
      const src = $(el).attr("src");
      const innerHTML = $(el).html();
      if (innerHTML) {
        htmlSize += Buffer.byteLength(innerHTML);
      }
      if (src) {
        entryScripts.push(new URL(src, entryHTML));
      }
    });
    let scanPromises = [];
    await Promise.all(entryScripts.map(parseJS));
    async function parseJS(url) {
      const relPath = url.pathname.replace(cwd.pathname, "");
      if (sizes[relPath])
        return;
      try {
        let code = url.protocol === "file:" ? await fs.promises.readFile(url, "utf8") : await fetch(url.href).then((body) => body.text());
        sizes[relPath] = Buffer.byteLength(code);
        const staticImports = eslexer.parse(code)[0].filter(({d}) => {
          if (!visitedEntry)
            return true;
          return d === -1;
        });
        for (const {n} of staticImports) {
          if (!n)
            continue;
          let nextURL;
          if (n.startsWith("http://") || n.startsWith("https://") || n.startsWith("//"))
            nextURL = new URL(n);
          else if (n[0] === ".")
            nextURL = new URL(n, url);
          else if (n[0] === "/")
            nextURL = new URL(`.${n}`, cwd);
          if (!nextURL)
            continue;
          if (sizes[nextURL.pathname.replace(cwd.pathname, "")])
            continue;
          scanPromises.push(parseJS(nextURL));
        }
      } catch (err) {
        console.warn(`Could not access ${url.href} to include in bundle size`);
      }
      visitedEntry = true;
    }
    await Promise.all(scanPromises);
    htmlSize = Object.values(sizes).reduce((sum, next) => sum + next, 0);
  }
  const js = await scan(cwd, "**/*.(js|mjs|wasm)");
  await Promise.all(js.map(async (file) => {
    const relPath = file.pathname.replace(cwd.pathname, "");
    if (!sizes[relPath])
      sizes[relPath] = (await fs.promises.stat(file)).size;
  }));
  return {
    js: sizes,
    entryHTML: htmlSize || void 0,
    total: Object.values(sizes).reduce((sum, acc) => sum + acc, 0)
  };
}
function kb(bytes) {
  if (bytes === 0)
    return `0 kB`;
  return (Math.round(bytes / 1e3) || 1) + " kB";
}
export {
  kb,
  profileHTML,
  profileJS
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vLi4vc3JjL2NvcmUvYnVpbGQvc3RhdHMudHMiXSwKICAibWFwcGluZ3MiOiAiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQXlCQSxvQkFBb0IsS0FBVSxTQUFpQztBQUM3RCxRQUFNLFVBQVUsTUFBTSxLQUFLLFNBQVMsQ0FBRSxLQUFLLGNBQWM7QUFDekQsU0FBTyxRQUFRLElBQUksQ0FBQyxhQUFhLElBQUksSUFBSSxNQUFNLFdBQVc7QUFBQTtBQUk1RCwyQkFBa0MsQ0FBRSxNQUEwQztBQUM1RSxRQUFNLFFBQW1CO0FBQ3pCLFFBQU0sT0FBTyxNQUFNLEtBQUssS0FBSztBQUM3QixNQUFJLFVBQVU7QUFDZCxRQUFNLFFBQVEsSUFDWixLQUFLLElBQUksT0FBTyxTQUFTO0FBQ3ZCLFVBQU0sVUFBVSxLQUFLLFNBQVMsUUFBUSxJQUFJLFVBQVU7QUFDcEQsVUFBTSxPQUFRLE9BQU0sR0FBRyxTQUFTLEtBQUssT0FBTztBQUM1QyxVQUFNLFdBQVc7QUFDakIsUUFBSSxPQUFPO0FBQV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