import CJS_COMPAT_NODE_URL_bqgqh4d46dd from 'node:url';
import CJS_COMPAT_NODE_PATH_bqgqh4d46dd from 'node:path';
import CJS_COMPAT_NODE_MODULE_bqgqh4d46dd from "node:module";

var __filename = CJS_COMPAT_NODE_URL_bqgqh4d46dd.fileURLToPath(import.meta.url);
var __dirname = CJS_COMPAT_NODE_PATH_bqgqh4d46dd.dirname(__filename);
var require = CJS_COMPAT_NODE_MODULE_bqgqh4d46dd.createRequire(import.meta.url);

// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
  getAutomockCode
} from "./chunk-APKZWRTX.js";
import {
  babelParser,
  extractMockCalls,
  getRealPath,
  rewriteSbMockImportCalls
} from "./chunk-BNO5FB6B.js";
import {
  normalize
} from "./chunk-6U2QTN2E.js";
import {
  __name
} from "./chunk-T7KB265F.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, "/");
}
__name(getCleanId, "getCleanId");
function invalidateAllRelatedModules(server, absPath, pkgName) {
  for (const mod of server.moduleGraph.idToModuleMap.values()) {
    if (mod.id === absPath || mod.id && getCleanId(mod.id) === pkgName) {
      server.moduleGraph.invalidateModule(mod);
    }
  }
}
__name(invalidateAllRelatedModules, "invalidateAllRelatedModules");

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