import CJS_COMPAT_NODE_URL_e2uwcrjkoh from 'node:url';
import CJS_COMPAT_NODE_PATH_e2uwcrjkoh from 'node:path';
import CJS_COMPAT_NODE_MODULE_e2uwcrjkoh from "node:module";

var __filename = CJS_COMPAT_NODE_URL_e2uwcrjkoh.fileURLToPath(import.meta.url);
var __dirname = CJS_COMPAT_NODE_PATH_e2uwcrjkoh.dirname(__filename);
var require = CJS_COMPAT_NODE_MODULE_e2uwcrjkoh.createRequire(import.meta.url);

// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
  babelParser,
  extractMockCalls,
  getIsExternal,
  resolveExternalModule,
  resolveWithExtensions
} from "./chunk-UNAHBFTN.js";
import "./chunk-WUDNZFSJ.js";
import {
  __name
} from "./chunk-4HUD73B3.js";

// src/core-server/presets/webpack/plugins/webpack-mock-plugin.ts
import { createRequire } from "node:module";
import { dirname, isAbsolute } from "node:path";
import { fileURLToPath } from "node:url";
var require2 = createRequire(import.meta.url);
var PLUGIN_NAME = "storybook-mock-plugin";
var WebpackMockPlugin = class {
  constructor(options) {
    this.mockMap = /* @__PURE__ */ new Map();
    if (!options.previewConfigPath) {
      throw new Error(`[${PLUGIN_NAME}] \`previewConfigPath\` is required.`);
    }
    this.options = options;
  }
  static {
    __name(this, "WebpackMockPlugin");
  }
  /**
   * The main entry point for the Webpack plugin.
   *
   * @param {Compiler} compiler The Webpack compiler instance.
   */
  apply(compiler) {
    const logger = compiler.getInfrastructureLogger(PLUGIN_NAME);
    const updateMocks = /* @__PURE__ */ __name(() => {
      this.mockMap = new Map(
        this.extractAndResolveMocks(compiler).flatMap((mock) => [
          // first one, full path
          [mock.absolutePath, mock],
          // second one, without the extension
          [mock.absolutePath.replace(/\.[^.]+$/, ""), mock]
        ])
      );
      logger.info(`Mock map updated with ${this.mockMap.size / 2} mocks.`);
    }, "updateMocks");
    compiler.hooks.beforeRun.tap(PLUGIN_NAME, updateMocks);
    compiler.hooks.watchRun.tap(PLUGIN_NAME, updateMocks);
    new compiler.webpack.NormalModuleReplacementPlugin(/.*/, (resource) => {
      try {
        const path = resource.request;
        const importer = resource.context;
        const isExternal = getIsExternal(path, importer);
        const absolutePath = isExternal ? resolveExternalModule(path, importer) : resolveWithExtensions(path, importer);
        if (this.mockMap.has(absolutePath)) {
          resource.request = this.mockMap.get(absolutePath).replacementResource;
        }
      } catch (e) {
        logger.debug(`Could not resolve mock for "${resource.request}".`);
      }
    }).apply(compiler);
    compiler.hooks.afterCompile.tap(PLUGIN_NAME, (compilation) => {
      compilation.fileDependencies.add(this.options.previewConfigPath);
      for (const mock of this.mockMap.values()) {
        if (isAbsolute(mock.replacementResource) && mock.replacementResource.includes("__mocks__")) {
          compilation.contextDependencies.add(dirname(mock.replacementResource));
        }
      }
    });
  }
  /**
   * Reads the preview config, parses it to find all `sb.mock()` calls, and resolves their
   * corresponding mock implementations.
   *
   * @param {Compiler} compiler The Webpack compiler instance.
   * @returns {ResolvedMock[]} An array of fully processed mocks.
   */
  extractAndResolveMocks(compiler) {
    const { previewConfigPath } = this.options;
    const logger = compiler.getInfrastructureLogger(PLUGIN_NAME);
    const mocks = extractMockCalls(
      { previewConfigPath, configDir: dirname(previewConfigPath) },
      babelParser,
      compiler.context
    );
    const resolvedMocks = [];
    for (const mock of mocks) {
      try {
        const { absolutePath, redirectPath } = mock;
        let replacementResource;
        if (redirectPath) {
          replacementResource = redirectPath;
        } else {
          const loaderPath = fileURLToPath(
            import.meta.resolve("storybook/webpack/loaders/webpack-automock-loader")
          );
          replacementResource = `${loaderPath}?spy=${mock.spy}!${absolutePath}`;
        }
        resolvedMocks.push({
          ...mock,
          replacementResource
        });
      } catch (e) {
        logger.warn(`Could not resolve mock for "${mock.path}". It will be ignored.`);
      }
    }
    return resolvedMocks;
  }
};
export {
  WebpackMockPlugin
};
