import esbuild from "esbuild";
import fs from "fs";
import {transform} from "@astrojs/compiler";
import {decode} from "sourcemap-codec";
function astro({config, devServer}) {
  return {
    name: "@astrojs/vite-plugin-astro",
    enforce: "pre",
    async load(id) {
      if (!id.endsWith(".astro")) {
        return null;
      }
      let source = await fs.promises.readFile(id, "utf8");
      let tsResult;
      try {
        tsResult = await transform(source, {
          site: config.buildOptions.site,
          sourcefile: id,
          sourcemap: "both",
          internalURL: "astro/internal"
        });
        const {code, map} = await esbuild.transform(tsResult.code, {loader: "ts", sourcemap: "external", sourcefile: id});
        return {
          code,
          map
        };
      } catch (err) {
        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];
          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,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vc3JjL3ZpdGUtcGx1Z2luLWFzdHJvL2luZGV4LnRzIl0sCiAgIm1hcHBpbmdzIjogIkFBSUE7QUFDQTtBQUNBO0FBQ0E7QUFTZSxlQUFlLENBQUUsUUFBUSxZQUF5QztBQUMvRSxTQUFPO0FBQUEsSUFDTCxNQUFNO0FBQUEsSUFDTixTQUFTO0FBQUEsVUFFSCxLQUFLLElBQUk7QUFDYixVQUFJLENBQUMsR0FBRyxTQUFTLFdBQVc7QUFDMUIsZUFBTztBQUFBO0FBR1QsVUFBSSxTQUFTLE1BQU0sR0FBRyxTQUFTLFNBQVMsSUFBSTtBQUM1QyxVQUFJO0FBRUosVUFBSTtBQUdGLG1CQUFXLE1BQU0sVUFBVSxRQUFRO0FBQUEsVUFDakMsTUFBTSxPQUFPLGFBQWE7QUF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