import CJS_COMPAT_NODE_URL_fkaa0x0zihe from 'node:url';
import CJS_COMPAT_NODE_PATH_fkaa0x0zihe from 'node:path';
import CJS_COMPAT_NODE_MODULE_fkaa0x0zihe from "node:module";

var __filename = CJS_COMPAT_NODE_URL_fkaa0x0zihe.fileURLToPath(import.meta.url);
var __dirname = CJS_COMPAT_NODE_PATH_fkaa0x0zihe.dirname(__filename);
var require = CJS_COMPAT_NODE_MODULE_fkaa0x0zihe.createRequire(import.meta.url);

// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
  getAutomockCode
} from "./chunk-EKSZE67Q.js";
import {
  babelParser,
  extractMockCalls,
  getRealPath,
  rewriteSbMockImportCalls
} from "./chunk-S3OHEWCH.js";
import {
  normalize
} from "./chunk-QUBI53SI.js";
import "./chunk-4ILNNMLG.js";

// src/core-server/presets/vitePlugins/vite-mock/plugin.ts
import { readFileSync } from "node:fs";
import { logger } from "storybook/internal/node-logger";

// src/core-server/presets/vitePlugins/vite-mock/utils.ts
function getCleanId(id) {
  return id.replace(/^.*\/deps\//, "").replace(/\.js.*$/, "").replace(/_/g, "/");
}
function invalidateAllRelatedModules(server, absPath, pkgName) {
  for (let mod of server.moduleGraph.idToModuleMap.values())
    (mod.id === absPath || mod.id && getCleanId(mod.id) === pkgName) && server.moduleGraph.invalidateModule(mod);
}

// src/core-server/presets/vitePlugins/vite-mock/plugin.ts
function viteMockPlugin(options) {
  let viteConfig, mockCalls = [], normalizedPreviewConfigPath = normalize(options.previewConfigPath);
  return [
    {
      name: "storybook:mock-loader",
      configResolved(config) {
        viteConfig = config;
      },
      buildStart() {
        mockCalls = extractMockCalls(options, babelParser, viteConfig.root);
      },
      configureServer(server) {
        async function invalidateAffectedFiles(file) {
          if (file === options.previewConfigPath || file.includes("__mocks__")) {
            let oldMockCalls = mockCalls;
            mockCalls = extractMockCalls(options, babelParser, viteConfig.root);
            let previewMod = server.moduleGraph.getModuleById(options.previewConfigPath);
            previewMod && server.moduleGraph.invalidateModule(previewMod);
            for (let call of mockCalls)
              invalidateAllRelatedModules(server, call.absolutePath, call.path);
            let newAbsPaths = new Set(mockCalls.map((c) => c.absolutePath));
            for (let oldCall of oldMockCalls)
              newAbsPaths.has(oldCall.absolutePath) || invalidateAllRelatedModules(server, oldCall.absolutePath, oldCall.path);
            return server.ws.send({ type: "full-reload" }), [];
          }
        }
        server.watcher.on("change", invalidateAffectedFiles), server.watcher.on("add", invalidateAffectedFiles), server.watcher.on("unlink", invalidateAffectedFiles);
      },
      load: {
        order: "pre",
        handler(id) {
          let preserveSymlinks = viteConfig.resolve.preserveSymlinks, idNorm = getRealPath(id, preserveSymlinks), cleanId = getCleanId(idNorm);
          for (let call of mockCalls)
            if (!(getRealPath(call.absolutePath, preserveSymlinks) !== idNorm && call.path !== cleanId) && call.redirectPath)
              return this.addWatchFile(call.redirectPath), readFileSync(call.redirectPath, "utf-8");
          return null;
        }
      },
      transform: {
        order: "pre",
        handler(code, id) {
          for (let call of mockCalls) {
            let preserveSymlinks = viteConfig.resolve.preserveSymlinks, idNorm = getRealPath(id, preserveSymlinks), callNorm = getRealPath(call.absolutePath, preserveSymlinks);
            if (viteConfig.command !== "serve") {
              if (callNorm !== idNorm)
                continue;
            } else {
              let cleanId = getCleanId(idNorm);
              if (call.path !== cleanId && callNorm !== idNorm)
                continue;
            }
            try {
              if (!call.redirectPath) {
                let automockedCode = getAutomockCode(code, call.spy, babelParser);
                return {
                  code: automockedCode.toString(),
                  map: automockedCode.generateMap()
                };
              }
            } catch (e) {
              return logger.error(`Error automocking ${id}: ${e}`), null;
            }
          }
          return null;
        }
      }
    },
    {
      name: "storybook:mock-loader-preview",
      transform(code, id) {
        if (id === normalizedPreviewConfigPath)
          try {
            return rewriteSbMockImportCalls(code);
          } catch (e) {
            return logger.debug(`Could not transform sb.mock(import(...)) calls in ${id}: ${e}`), null;
          }
        return null;
      }
    }
  ];
}
export {
  viteMockPlugin
};
