import esbuild from "esbuild";
import fs from "fs";
import {fileURLToPath} from "url";
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 viteTransform;
  return {
    name: "@astrojs/vite-plugin-astro",
    enforce: "pre",
    configResolved(resolvedConfig) {
      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)) || id.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) => {
            if (!attrs || !attrs.lang)
              return null;
            const result = await transformWithVite({value, attrs, 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};
          }
        });
        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];
          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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