import MagicString from "magic-string";
import { walk } from "estree-walker";
function isSSR(options) {
  if (options === void 0) {
    return false;
  }
  if (typeof options === "boolean") {
    return options;
  }
  if (typeof options == "object") {
    return !!options.ssr;
  }
  return false;
}
const SUPPORTED_FILES = /\.(astro|svelte|vue|[cm]?js|jsx|[cm]?ts|tsx)$/;
const IGNORED_MODULES = [/astro\/dist\/runtime\/server/, /\/node-fetch\//];
const DEFINE_FETCH = `import fetch from 'node-fetch';
`;
function isIdentifier(node) {
  return node.type === "Identifier";
}
function pluginFetch() {
  return {
    name: "@astrojs/vite-plugin-fetch",
    enforce: "post",
    async transform(code, id, opts) {
      const ssr = isSSR(opts);
      if (!ssr) {
        return null;
      }
      if (!id.match(SUPPORTED_FILES)) {
        return null;
      }
      if (!code.includes("fetch")) {
        return null;
      }
      const ast = this.parse(code);
      let fetchDeclared = false;
      walk(ast, {
        enter(node, parent) {
          if (fetchDeclared)
            return this.skip();
          if (isIdentifier(node)) {
            if (node.name === "fetch" && !parent.type.endsWith("Expression")) {
              fetchDeclared = true;
            }
          }
        }
      });
      if (fetchDeclared) {
        return null;
      }
      for (const ignored of IGNORED_MODULES) {
        if (id.match(ignored)) {
          return null;
        }
      }
      const s = new MagicString(code);
      s.prepend(DEFINE_FETCH);
      const result = s.toString();
      const map = s.generateMap({
        source: id,
        includeContent: true
      });
      return { code: result, map };
    }
  };
}
export {
  pluginFetch as default
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vc3JjL3ZpdGUtcGx1Z2luLWZldGNoL2luZGV4LnRzIl0sCiAgIm1hcHBpbmdzIjogIkFBRUE7QUFDQTtBQUdBLGVBQWUsU0FBMEQ7QUFDeEUsTUFBSSxZQUFZLFFBQVc7QUFDMUIsV0FBTztBQUFBO0FBRVIsTUFBSSxPQUFPLFlBQVksV0FBVztBQUNqQyxXQUFPO0FBQUE7QUFFUixNQUFJLE9BQU8sV0FBVyxVQUFVO0FBQy9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