import CJS_COMPAT_NODE_URL_jj04cksboja from 'node:url';
import CJS_COMPAT_NODE_PATH_jj04cksboja from 'node:path';
import CJS_COMPAT_NODE_MODULE_jj04cksboja from "node:module";

var __filename = CJS_COMPAT_NODE_URL_jj04cksboja.fileURLToPath(import.meta.url);
var __dirname = CJS_COMPAT_NODE_PATH_jj04cksboja.dirname(__filename);
var require = CJS_COMPAT_NODE_MODULE_jj04cksboja.createRequire(import.meta.url);

// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
  resolvePackageDir
} from "./chunk-3ML5DUTC.js";
import "./chunk-NU5QOZC6.js";
import {
  require_dist
} from "./chunk-TUFGO7A6.js";
import {
  __name,
  __toESM
} from "./chunk-T7Y6VNG2.js";

// src/core-server/presets/vitePlugins/vite-inject-mocker/plugin.ts
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";

// ../node_modules/@rolldown/pluginutils/dist/index.js
function exactRegex(str, flags) {
  return new RegExp(`^${escapeRegex(str)}$`, flags);
}
__name(exactRegex, "exactRegex");
var escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
function escapeRegex(str) {
  return str.replace(escapeRegexRE, "\\$&");
}
__name(escapeRegex, "escapeRegex");

// src/core-server/presets/vitePlugins/vite-inject-mocker/plugin.ts
var import_ts_dedent = __toESM(require_dist(), 1);
var entryPath = "/vite-inject-mocker-entry.js";
var entryCode = import_ts_dedent.dedent`
    <script type="module" src=".${entryPath}"></script>
  `;
var server;
var viteInjectMockerRuntime = /* @__PURE__ */ __name((options) => {
  let viteConfig;
  return {
    name: "vite:storybook-inject-mocker-runtime",
    buildStart() {
      if (viteConfig.command === "build") {
        this.emitFile({
          type: "chunk",
          id: join(
            resolvePackageDir("storybook"),
            "assets",
            "server",
            "mocker-runtime.template.js"
          ),
          fileName: entryPath.slice(1)
        });
      }
    },
    config() {
      return {
        optimizeDeps: {
          include: ["@vitest/mocker", "@vitest/mocker/browser"]
        },
        resolve: {
          // Aliasing necessary for package managers like pnpm, since resolving modules from a virtual module
          // leads to errors, if the imported module is not a dependency of the project.
          // By resolving the module to the real path, we can avoid this issue.
          alias: {
            "@vitest/mocker/browser": fileURLToPath(import.meta.resolve("@vitest/mocker/browser")),
            "@vitest/mocker": fileURLToPath(import.meta.resolve("@vitest/mocker"))
          }
        }
      };
    },
    configResolved(config) {
      viteConfig = config;
    },
    configureServer(server_) {
      server = server_;
      if (options.previewConfigPath) {
        server.watcher.on("change", (file) => {
          if (file === options.previewConfigPath) {
            server.ws.send({
              type: "custom",
              event: "invalidate-mocker"
            });
          }
        });
      }
    },
    resolveId: {
      filter: {
        id: [exactRegex(entryPath)]
      },
      handler(id) {
        if (exactRegex(id).test(entryPath)) {
          return id;
        }
        return null;
      }
    },
    async load(id) {
      if (exactRegex(id).test(entryPath)) {
        return readFileSync(
          join(resolvePackageDir("storybook"), "assets", "server", "mocker-runtime.template.js"),
          "utf-8"
        );
      }
      return null;
    },
    transformIndexHtml(html) {
      const headTag = html.match(/<head[^>]*>/);
      if (headTag) {
        const headTagIndex = html.indexOf(headTag[0]);
        const newHtml = html.slice(0, headTagIndex + headTag[0].length) + entryCode + html.slice(headTagIndex + headTag[0].length);
        return newHtml;
      }
    }
  };
}, "viteInjectMockerRuntime");
export {
  viteInjectMockerRuntime
};
