import esbuild from "esbuild";
import fs from "fs";
import {fileURLToPath} from "url";
import os from "os";
import {transform} from "@astrojs/compiler";
import {decode} from "sourcemap-codec";
import {getViteTransform, transformWithVite} from "./styles.js";
function isSSR(options) {
  if (options === void 0) {
    return false;
  }
  if (typeof options === "boolean") {
    return options;
  }
  if (typeof options == "object") {
    return !!options.ssr;
  }
  return false;
}
function astro({config, devServer}) {
  let platform;
  let viteTransform;
  return {
    name: "@astrojs/vite-plugin-astro",
    enforce: "pre",
    configResolved(resolvedConfig) {
      platform = os.platform();
      viteTransform = getViteTransform(resolvedConfig);
    },
    async load(id, opts) {
      if (!id.endsWith(".astro")) {
        return null;
      }
      const normalizedID = fileURLToPath(new URL(`file://${id}`));
      const isPage = normalizedID.startsWith(fileURLToPath(config.pages)) || normalizedID.startsWith(fileURLToPath(config.layouts));
      let source = await fs.promises.readFile(id, "utf8");
      let tsResult;
      try {
        tsResult = await transform(source, {
          as: isPage ? "document" : "fragment",
          site: config.buildOptions.site,
          sourcefile: id,
          sourcemap: "both",
          internalURL: "astro/internal",
          preprocessStyle: async (value, attrs) => {
            const lang = `.${(attrs == null ? void 0 : attrs.lang) || "css"}`.toLowerCase();
            const result = await transformWithVite({value, lang, id, transformHook: viteTransform, ssr: isSSR(opts)});
            if (!result) {
              return result;
            }
            let map2;
            if (result.map) {
              if (typeof result.map === "string") {
                map2 = result.map;
              } else if (result.map.mappings) {
                map2 = result.map.toString();
              }
            }
            return {code: result.code, map: map2};
          }
        });
        if (platform === "darwin") {
          tsResult.code = tsResult.code.replace(/\x00/g, "");
        }
        const {code, map} = await esbuild.transform(tsResult.code, {loader: "ts", sourcemap: "external", sourcefile: id});
        return {
          code,
          map
        };
      } catch (err) {
        if (err.stack.includes("wasm-function")) {
          const search = new URLSearchParams({
            labels: "compiler",
            title: "\u{1F41B} BUG: `@astrojs/compiler` panic",
            body: `### Describe the Bug

\`@astrojs/compiler\` encountered an unrecoverable error when compiling the following file.

**${id.replace(fileURLToPath(config.projectRoot), "")}**
\`\`\`astro
${source}
\`\`\`
`
          });
          err.url = `https://github.com/snowpackjs/astro/issues/new?${search.toString()}`;
          err.message = `Error: Uh oh, the Astro compiler encountered an unrecoverable error!

Please open
a GitHub issue using the link below:
${err.url}`;
          err.stack = `    at ${id}`;
        }
        if (err.errors && (tsResult == null ? void 0 : tsResult.map)) {
          const json = JSON.parse(tsResult.map);
          const mappings = decode(json.mappings);
          const focusMapping = mappings[err.errors[0].location.line + 1];
          if (Array.isArray(focusMapping) && focusMapping.length) {
            err.sourceLoc = {file: id, line: (focusMapping[0][2] || 0) + 1, column: (focusMapping[0][3] || 0) + 1};
          }
        }
        throw err;
      }
    },
    async handleHotUpdate(context) {
      if (devServer) {
        return devServer.handleHotUpdate(context);
      }
    }
  };
}
export {
  astro as default
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vc3JjL3ZpdGUtcGx1Z2luLWFzdHJvL2luZGV4LnRzIl0sCiAgIm1hcHBpbmdzIjogIkFBS0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBRUE7QUFRQSxlQUFlLFNBQTBEO0FBQ3ZFLE1BQUksWUFBWSxRQUFXO0FBQ3pCLFdBQU87QUFBQTtBQUVULE1BQUksT0FBTyxZQUFZLFdBQVc7QUFDaEMsV0FBTztBQUFBO0FBRVQsTUFBSSxPQUFPLFdBQVcsVUFBVTtBQUM5QixXQUFPLENBQUMsQ0FBQyxRQUFRO0FBQUE7QUFFbkIsU0FBTztBQUFBO0FBSU0sZUFBZSxDQUFFLFFBQVEsWUFBOEM7QUFDcEYsTUFBSTtBQUNKLE1BQUk7QUFDSixTQUFPO0FBQUEsSUFDTCxNQUFNO0FBQUEsSUFDTixTQUFTO0FBQUEsSUFDVCxlQUFlLGdCQUFnQjtBQUM3QixpQkFBVyxHQUFHO0FBQ2Qsc0JBQWdCLGlCQUFpQjtBQUFBO0FBQUEsVUFHN0IsS0FBSyxJ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