import { dirname as __pathDirname } from 'path';
import { fileURLToPath as __fileURLToPath } from 'url';
var __dirname = (function() {
  try {
    var url = import.meta?.url;
    if (url) return __pathDirname(__fileURLToPath(url));
  } catch (e) {}
  try {
    if (typeof __filename !== 'undefined') return __pathDirname(__filename);
  } catch (e) {}
  return process.cwd();
})();
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});

// src/unplugin.ts
import fs8 from "fs";
import path11 from "path";
import { bold, cyan, green } from "kolorist";
import { createUnplugin } from "unplugin";

// src/codegen/config-injector.ts
function generateConfigInjectionCode(config) {
  if (!config.clientUrl && !config.rootSelector && !config.theme && !config.assets && !config.launchEditor) {
    return "";
  }
  const configParts = [];
  if (config.clientUrl) {
    configParts.push(`window.__REACT_DEVTOOLS_CONFIG__.clientUrl = ${JSON.stringify(config.clientUrl)};`);
  }
  if (config.rootSelector) {
    configParts.push(`window.__REACT_DEVTOOLS_CONFIG__.rootSelector = ${JSON.stringify(config.rootSelector)};`);
  }
  if (config.theme) {
    configParts.push(`window.__REACT_DEVTOOLS_CONFIG__.theme = ${JSON.stringify(config.theme)};`);
  }
  if (config.assets) {
    configParts.push(`window.__REACT_DEVTOOLS_CONFIG__.assets = ${JSON.stringify(config.assets)};`);
  }
  if (config.launchEditor) {
    configParts.push(`window.__REACT_DEVTOOLS_CONFIG__.launchEditor = ${JSON.stringify(config.launchEditor)};`);
  }
  return `
if (typeof window !== 'undefined') {
  window.__REACT_DEVTOOLS_CONFIG__ = window.__REACT_DEVTOOLS_CONFIG__ || {};
  ${configParts.join("\n  ")}
}
`.trim();
}
function generateConfigScriptTag(config) {
  const code = generateConfigInjectionCode(config);
  if (!code) {
    return null;
  }
  return {
    tag: "script",
    attrs: {},
    children: code,
    injectTo: "head-prepend"
  };
}

// src/codegen/css-injector.ts
import fs from "fs";
import path from "path";
function readAndEscapeCSSContent(cssPath) {
  if (!fs.existsSync(cssPath)) {
    return "";
  }
  return fs.readFileSync(cssPath, "utf-8").replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
}
function generateGlobalsWithCSSCode(overlayDir) {
  const cssPath = path.join(overlayDir, "react-devtools-overlay.css");
  const cssContent = readAndEscapeCSSContent(cssPath);
  let code = `
// React DevTools: Setup React globals and CSS for overlay
// SUpport both npm-installed React and CDN-loaded React (like singleSpa)

if (typeof window !== 'undefined') {
  // Check if React is already available on window (CDN scenario)
  var React = window.React;
  var ReactDOM = window.ReactDOM;

  // if not found, try to require from node_modules
  if (!React) {
    try {
      React = require('react');
      window.React = React;
    } catch (e) {
      // React not available via require, must be loaded via CDN
    }
  }

  if (!ReactDOM) {
    try {
      ReactDOM = require('react-dom');
      window.ReactDOM = ReactDOM;
    } catch (e) {
      // ReactDOM not available via require, must be loaded via CDN
    }
  }

  // Try to add createRoot support for React 18+ (optional)
  if (ReactDOM && !ReactDOM.createRoot) {
    try {
      var ReactDOMClient = require('react-dom/client');
      if (ReactDOMClient && ReactDOMClient.createRoot) {
        window.ReactDOM = Object.assign({}, ReactDOM, ReactDOMClient);
      }
    } catch (e) {
      // react-dom/client not available, which is fine for React 17 or CDN
    }
  }
`;
  if (cssContent) {
    code += `
  // Inject CSS styles for React DevTools overlay
  if (!document.querySelector('style[data-react-devtools]')) {
    var style = document.createElement('style');
    style.setAttribute('data-react-devtools', 'true');
    style.textContent = \`${cssContent}\`;
    document.head.appendChild(style);
  }
`;
  }
  code += `}
`;
  return code.trim();
}
function generateCSSScriptTags(overlayDir, base, isProduction) {
  if (isProduction) {
    return [{
      tag: "link",
      attrs: {
        rel: "stylesheet",
        href: `${base}assets/react-devtools-overlay.css`
      },
      injectTo: "head"
    }];
  }
  const cssPath = path.join(overlayDir, "react-devtools-overlay.css");
  if (!fs.existsSync(cssPath)) {
    return [];
  }
  const cssContent = fs.readFileSync(cssPath, "utf-8");
  return [{
    tag: "style",
    attrs: {
      "data-react-devtools": "true"
    },
    children: cssContent,
    injectTo: "head"
  }];
}

// src/codegen/devtools-hook.ts
function generateDevToolsHookCode() {
  return `
if (typeof window !== 'undefined' && !window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
  (function() {
    var renderers = new Map();
    window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
      __IS_OUR_MOCK__: true,
      checkDCE: function() {},
      supportsFiber: true,
      renderers: renderers,
      onScheduleFiberRoot: function() {},
      onCommitFiberRoot: function(rendererID, root, priorityLevel) {
        // This might be overwritten by bippy
      },
      onCommitFiberUnmount: function() {},
      inject: function(renderer) {
        var id = Math.random().toString(36).slice(2);
        renderers.set(id, renderer);
        return id;
      }
    };
  })();
}
`.trim();
}
function generateDevToolsHookScriptTag() {
  return {
    tag: "script",
    attrs: {},
    children: generateDevToolsHookCode(),
    injectTo: "head-prepend"
  };
}

// src/codegen/react-globals.ts
function generateReactGlobalsESMCode(options = {}) {
  const { dispatchReadyEvent = true } = options;
  let code = `
// React DevTools: Setup React globals for overlay
// Supports both npm-installed React and CDN-loaded React (like singleSpa)
(async function() {
  if (typeof window === 'undefined') return;

  // Check if React is already available on window (CDN scenario)
  let React = window.React;
  let ReactDOM = window.ReactDOM;

  // If not found, try to import from node_modules
  if (!React) {
    try {
      const reactModule = await import('react');
      React = reactModule.default || reactModule;
      window.React = React;
    } catch (e) {
      // React not available via import, must be loaded via CDN
      console.debug('[React DevTools] React not found in node_modules, using window.React');
    }
  }

  if (!ReactDOM) {
    try {
      const reactDomModule = await import('react-dom');
      // In React 19, the module exports are at the top level, not under .default
      ReactDOM = reactDomModule.default || reactDomModule;
      window.ReactDOM = ReactDOM;
    } catch (e) {
      // ReactDOM not available via import, must be loaded via CDN
    }
  }

  // Try to add createRoot support for React 18+ (optional)
  // IMPORTANT: For React 18, createRoot is in react-dom/client
  // For React 19, createRoot is exported from both react-dom and react-dom/client
  if (ReactDOM && !ReactDOM.createRoot) {
    try {
      // Import react-dom/client - Vite will transform this to the correct URL
      const reactDomClientModule = await import('react-dom/client');
      // Get createRoot from the module - it's a named export, not default
      const createRoot = reactDomClientModule.createRoot;
      const hydrateRoot = reactDomClientModule.hydrateRoot;
      if (createRoot) {
        // Merge createRoot and hydrateRoot into ReactDOM
        window.ReactDOM = { ...ReactDOM, createRoot, hydrateRoot };
      }
    } catch (e) {
      // react-dom/client not available, which is fine for React 17 or CDN
    }
  }
`;
  if (dispatchReadyEvent) {
    code += `
  // Signal that React globals are ready
  window.__REACT_DEVTOOLS_GLOBALS_READY__ = true;
  // Dispatch event for waiting scripts
  window.dispatchEvent(new CustomEvent('react-devtools-globals-ready'));
`;
  }
  code += `})();
`;
  return code.trim();
}
function generateOverlayLoaderCode(scriptSrc) {
  return `
function loadOverlay() {
  import('${scriptSrc}').catch(err => {
    console.warn('[React DevTools] Failed to load overlay:', err);
  });
}
if (window.__REACT_DEVTOOLS_GLOBALS_READY__) {
  loadOverlay();
} else {
  window.addEventListener('react-devtools-globals-ready', loadOverlay, { once: true });
  // Fallback timeout in case event was missed
  setTimeout(() => {
    if (!window.__REACT_DEVTOOLS_OVERLAY_LOADED__) {
      window.__REACT_DEVTOOLS_OVERLAY_LOADED__ = true;
      loadOverlay();
    }
  }, 1000);
}
`.trim();
}

// src/codegen/scan-init.ts
import path2 from "path";
var DEFAULT_SCAN_OPTIONS = {
  enabled: true,
  showToolbar: false,
  log: false,
  animationSpeed: "fast",
  showOutlines: true
};
function normalizeScanOptions(options) {
  return __spreadValues(__spreadValues({}, DEFAULT_SCAN_OPTIONS), options);
}
function generateScanInitESMCode(options) {
  const normalizedOptions = normalizeScanOptions(options);
  return `
import { initScan, ReactScanInternals, setOptions, getOptions, scan } from 'react-devtools-plus/scan';

if (typeof window !== 'undefined') {
  window.__REACT_SCAN_INTERNALS__ = ReactScanInternals;
  window.__REACT_SCAN_SET_OPTIONS__ = setOptions;
  window.__REACT_SCAN_GET_OPTIONS__ = getOptions;
  window.__REACT_SCAN_SCAN__ = scan;
}

if (ReactScanInternals) {
  ReactScanInternals.runInAllEnvironments = true;
}

scan(${JSON.stringify(normalizedOptions)});
`.trim();
}
function generateScanInitCJSCode(options) {
  const normalizedOptions = __spreadProps(__spreadValues({}, normalizeScanOptions(options)), {
    showOutlines: true
    // Force show outlines for Webpack
  });
  const scanPackagePath = path2.dirname(__require.resolve("react-devtools-plus/package.json"));
  const scanModulePath = path2.join(scanPackagePath, "dist", "scan.cjs").replace(/\\/g, "/");
  return `
var scanModule = require('${scanModulePath}');
var initScan = scanModule.initScan;
var ReactScanInternals = scanModule.ReactScanInternals;
var setOptions = scanModule.setOptions;
var getOptions = scanModule.getOptions;
var scan = scanModule.scan;

if (typeof window !== 'undefined') {
  window.__REACT_SCAN_INTERNALS__ = ReactScanInternals;
  window.__REACT_SCAN_SET_OPTIONS__ = setOptions;
  window.__REACT_SCAN_GET_OPTIONS__ = getOptions;
  window.__REACT_SCAN_SCAN__ = scan;
}

// Ensure we run in all environments
if (ReactScanInternals) {
  ReactScanInternals.runInAllEnvironments = true;
}

initScan(${JSON.stringify(normalizedOptions)});
`.trim();
}
function generateScanScriptTag(base, options) {
  return {
    tag: "script",
    attrs: { type: "module" },
    children: `import '${base}@id/__react-devtools-scan__';`,
    injectTo: "head-prepend"
  };
}

// src/config/normalize.ts
import path3 from "path";
function normalizeBasePath(base) {
  if (!base || base === "auto") {
    return "/";
  }
  let normalized = base;
  if (!normalized.startsWith("/")) {
    normalized = `/${normalized}`;
  }
  if (normalized !== "/" && normalized.endsWith("/")) {
    normalized = normalized.slice(0, -1);
  }
  return normalized;
}
function detectEnvironment(mode) {
  if (mode && mode !== "undefined") {
    return mode;
  }
  const nodeEnv = process.env.NODE_ENV;
  if (nodeEnv && nodeEnv !== "undefined") {
    return nodeEnv;
  }
  return "development";
}
function shouldEnableDevTools(enabledEnvironments, mode, command) {
  if (process.env.VITE_REACT_DEVTOOLS_ENABLED !== void 0) {
    return process.env.VITE_REACT_DEVTOOLS_ENABLED === "true";
  }
  const detectedEnv = detectEnvironment(mode);
  if (enabledEnvironments === false) {
    return false;
  }
  if (Array.isArray(enabledEnvironments)) {
    const isInList = enabledEnvironments.includes(detectedEnv);
    return isInList;
  }
  return command === "serve";
}
function shouldInjectSource(injectSourceOption, mode, command) {
  if (injectSourceOption !== void 0) {
    return injectSourceOption;
  }
  const nodeEnv = process.env.NODE_ENV || mode;
  const isProduction = nodeEnv === "production" || command === "build" && mode === "production";
  return !isProduction;
}
function normalizeScanConfig(scan, command) {
  var _a, _b;
  if (!scan) {
    return void 0;
  }
  if (scan === true) {
    return {
      enabled: command === "serve",
      // Only enable in dev mode by default
      showToolbar: true
    };
  }
  return __spreadValues({
    enabled: (_a = scan.enabled) != null ? _a : command === "serve",
    showToolbar: (_b = scan.showToolbar) != null ? _b : true
  }, scan);
}
function resolvePluginConfig(options, projectRoot, mode, command) {
  const enabledEnvironments = options.enabledEnvironments;
  const injectSourceOption = options.injectSource;
  const sourcePathMode = options.sourcePathMode || "absolute";
  const detectedEnvironment = detectEnvironment(mode);
  const isEnabled = shouldEnableDevTools(enabledEnvironments, mode, command);
  const injectSource = shouldInjectSource(injectSourceOption, mode, command);
  const scan = normalizeScanConfig(options.scan, command);
  const plugins = (options.plugins || []).map((plugin) => {
    if (plugin.view && plugin.view.src) {
      let src = plugin.view.src;
      if (!path3.isAbsolute(src)) {
        src = path3.resolve(projectRoot, src);
      }
      return __spreadProps(__spreadValues({}, plugin), {
        view: __spreadProps(__spreadValues({}, plugin.view), {
          src
          // Resolved absolute path
        })
      });
    }
    return plugin;
  });
  return {
    plugins,
    appendTo: options.appendTo,
    enabledEnvironments: enabledEnvironments != null ? enabledEnvironments : true,
    detectedEnvironment,
    injectSource,
    sourcePathMode,
    projectRoot,
    mode,
    command,
    isEnabled,
    scan,
    clientUrl: options.clientUrl,
    rootSelector: options.rootSelector,
    theme: options.theme,
    assets: options.assets,
    launchEditor: options.launchEditor
  };
}
function validatePluginOptions(options) {
  if (options.sourcePathMode && !["absolute", "relative"].includes(options.sourcePathMode)) {
    throw new Error(`[React DevTools] Invalid sourcePathMode: ${options.sourcePathMode}. Must be 'absolute' or 'relative'.`);
  }
  if (options.enabledEnvironments !== void 0) {
    const { enabledEnvironments } = options;
    if (typeof enabledEnvironments !== "boolean" && !Array.isArray(enabledEnvironments)) {
      throw new TypeError("[React DevTools] enabledEnvironments must be a boolean or an array of strings.");
    }
  }
  if (options.appendTo !== void 0) {
    if (typeof options.appendTo !== "string" && !(options.appendTo instanceof RegExp)) {
      throw new TypeError("[React DevTools] appendTo must be a string or RegExp.");
    }
  }
  if (options.scan !== void 0 && typeof options.scan !== "boolean" && typeof options.scan !== "object") {
    throw new TypeError("[React DevTools] scan must be a boolean or an object.");
  }
}

// src/dir.ts
import { resolve } from "path";
var DIR_DIST = __dirname;
var DIR_OVERLAY = resolve(DIR_DIST, "../src/overlay");

// src/integrations/vite.ts
import fs5 from "fs";
import path7 from "path";

// src/middleware/assets.ts
import fsp from "fs/promises";
import path4 from "path";
function guessType(filePath) {
  if (/\.(?:png|jpe?g|jxl|gif|svg|webp|avif|ico|bmp|tiff?)$/i.test(filePath))
    return "image";
  if (/\.(?:json[5c]?|te?xt|[mc]?[jt]sx?|md[cx]?|markdown|ya?ml|toml)$/i.test(filePath))
    return "text";
  if (/\.(?:mp4|webm|ogv|mov|avi|flv|wmv|mpg|mpeg|mkv|3gp|3g2|mts|m2ts|vob|ogm|ogx|rm|rmvb|asf|amv|divx|m4v|svi|viv|f4v|f4p|f4a|f4b)$/i.test(filePath))
    return "video";
  if (/\.(?:mp3|wav|ogg|flac|aac|wma|alac|ape|ac3|dts|tta|opus|amr|aiff|au|mid|midi|ra|rm|wv|weba|dss|spx|vox|tak|dsf|dff|dsd|cda)$/i.test(filePath))
    return "audio";
  if (/\.(?:woff2?|eot|ttf|otf|ttc|pfa|pfb|pfm|afm)$/i.test(filePath))
    return "font";
  if (/\.wasm$/i.test(filePath))
    return "wasm";
  return "other";
}
var FILE_PATTERNS = [
  // image
  "**/*.{png,jpg,jpeg,gif,svg,webp,avif,ico,bmp,tiff}",
  // video
  "**/*.{mp4,webm,ogv,mov,avi,flv,wmv,mpg,mpeg,mkv,3gp,3g2,m2ts,vob,ogm,ogx,rm,rmvb,asf,amv,divx,m4v,svi,viv,f4v,f4p,f4a,f4b}",
  // audio
  "**/*.{mp3,wav,ogg,flac,aac,wma,alac,ape,ac3,dts,tta,opus,amr,aiff,au,mid,midi,ra,rm,wv,weba,dss,spx,vox,tak,dsf,dff,dsd,cda}",
  // font
  "**/*.{woff,woff2,eot,ttf,otf,ttc,pfa,pfb,pfm,afm}",
  // text
  "**/*.{json,json5,jsonc,txt,text,tsx,jsx,ts,js,md,mdx,mdc,markdown,yaml,yml,toml}",
  // wasm
  "**/*.wasm"
];
var IGNORE_DIRS = [
  "**/node_modules/**",
  "**/dist/**",
  "**/build/**",
  "**/.git/**",
  "**/package-lock.*",
  "**/pnpm-lock.*",
  "**/yarn.lock",
  "**/pnpm-workspace.*"
];
var AssetsScanner = class {
  constructor(config) {
    this.cache = null;
    this.imageMetaCache = /* @__PURE__ */ new Map();
    this.config = {
      root: config.root,
      publicDir: config.publicDir || "public",
      baseUrl: config.baseUrl || "/"
    };
  }
  async scan() {
    const { root, publicDir, baseUrl } = this.config;
    try {
      const fg = await import("fast-glob").then((m) => m.default || m);
      const resolvedPublicDir = path4.isAbsolute(publicDir) ? publicDir : path4.resolve(root, publicDir);
      const relativePublicDir = path4.relative(root, resolvedPublicDir);
      const files = await fg(FILE_PATTERNS, {
        cwd: root,
        onlyFiles: true,
        caseSensitiveMatch: false,
        ignore: IGNORE_DIRS
      });
      this.cache = await Promise.all(files.map(async (relativePath) => {
        const filePath = path4.resolve(root, relativePath);
        const stat = await fsp.lstat(filePath);
        const assetPath = relativePath.replace(new RegExp(`^${relativePublicDir}/`), "");
        return {
          path: assetPath,
          relativePath,
          publicPath: path4.posix.join(baseUrl, assetPath),
          filePath,
          type: guessType(relativePath),
          size: stat.size,
          mtime: stat.mtimeMs
        };
      }));
      return this.cache;
    } catch (error) {
      console.error("[React DevTools] Failed to scan assets:", error);
      return [];
    }
  }
  async getAssets() {
    if (this.cache)
      return this.cache;
    return this.scan();
  }
  clearCache() {
    this.cache = null;
  }
  async getImageMeta(filepath) {
    if (this.imageMetaCache.has(filepath))
      return this.imageMetaCache.get(filepath);
    try {
      const { imageMeta } = await import("image-meta");
      const buffer = await fsp.readFile(filepath);
      const meta = imageMeta(buffer);
      this.imageMetaCache.set(filepath, meta);
      return meta;
    } catch (e) {
      this.imageMetaCache.set(filepath, void 0);
      return void 0;
    }
  }
  async getTextContent(filepath, limit = 500) {
    try {
      const content = await fsp.readFile(filepath, "utf-8");
      return content.slice(0, limit);
    } catch (e) {
      return void 0;
    }
  }
};
var globalScanner = null;
function createAssetsScanner(config) {
  globalScanner = new AssetsScanner(config);
  return globalScanner;
}
function createAssetsMiddleware(config) {
  const scanner = createAssetsScanner(config);
  return async (req, res, next) => {
    const rawUrl = req.url || "";
    const url = new URL(rawUrl, "http://localhost");
    if (url.pathname === "/__react_devtools__/api/assets") {
      try {
        const assets = await scanner.getAssets();
        res.setHeader("Content-Type", "application/json");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.end(JSON.stringify(assets));
        return;
      } catch (e) {
        res.statusCode = 500;
        res.end(JSON.stringify({ error: "Failed to scan assets" }));
        return;
      }
    }
    if (url.pathname === "/__react_devtools__/api/assets/refresh") {
      try {
        scanner.clearCache();
        const assets = await scanner.scan();
        res.setHeader("Content-Type", "application/json");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.end(JSON.stringify(assets));
        return;
      } catch (e) {
        res.statusCode = 500;
        res.end(JSON.stringify({ error: "Failed to refresh assets" }));
        return;
      }
    }
    if (url.pathname === "/__react_devtools__/api/assets/image-meta") {
      const filepath = url.searchParams.get("path");
      if (!filepath) {
        res.statusCode = 400;
        res.end(JSON.stringify({ error: "Missing path parameter" }));
        return;
      }
      try {
        const meta = await scanner.getImageMeta(filepath);
        res.setHeader("Content-Type", "application/json");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.end(JSON.stringify(meta || null));
        return;
      } catch (e) {
        res.statusCode = 500;
        res.end(JSON.stringify({ error: "Failed to get image meta" }));
        return;
      }
    }
    if (url.pathname === "/__react_devtools__/api/assets/text-content") {
      const filepath = url.searchParams.get("path");
      const limit = Number.parseInt(url.searchParams.get("limit") || "500", 10);
      if (!filepath) {
        res.statusCode = 400;
        res.end(JSON.stringify({ error: "Missing path parameter" }));
        return;
      }
      try {
        const content = await scanner.getTextContent(filepath, limit);
        res.setHeader("Content-Type", "application/json");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.end(JSON.stringify({ content: content || null }));
        return;
      } catch (e) {
        res.statusCode = 500;
        res.end(JSON.stringify({ error: "Failed to get text content" }));
        return;
      }
    }
    next();
  };
}

// src/middleware/client-server.ts
import sirv from "sirv";
function serveClient(servePath) {
  return sirv(servePath, {
    single: true,
    dev: true
  });
}

// src/middleware/graph.ts
import fs2 from "fs";
import path5 from "path";
function createGraphMiddleware(getModuleGraph, base = "/") {
  const apiPath = `${base}__react_devtools_api__/graph`.replace(/\/+/g, "/");
  return async (req, res, next) => {
    const url = req.url || "";
    if (url === apiPath || url.startsWith(`${apiPath}?`)) {
      try {
        const data = await getModuleGraph();
        res.setHeader("Content-Type", "application/json");
        res.setHeader("Cache-Control", "no-cache");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.end(JSON.stringify(data));
      } catch (error) {
        console.error("[React DevTools] Failed to get module graph:", error);
        res.statusCode = 500;
        res.end(JSON.stringify({ error: "Failed to get module graph" }));
      }
    } else {
      next();
    }
  };
}
var webpackModuleGraph = { modules: [], root: "" };
function processModules(statsModules, modules, fileExtPattern) {
  const moduleMap = /* @__PURE__ */ new Map();
  statsModules.forEach((mod) => {
    const id = mod.name || mod.identifier || "";
    if (!id)
      return;
    if (!fileExtPattern.test(id))
      return;
    if (id.startsWith("webpack/") || id.startsWith("(webpack)"))
      return;
    const normalizedId = normalizeWebpackModulePath(id);
    if (!normalizedId)
      return;
    const isVirtual = !mod.resource || id.includes("\0") || id.includes("virtual:");
    if (!moduleMap.has(normalizedId)) {
      moduleMap.set(normalizedId, {
        id: normalizedId,
        deps: [],
        virtual: isVirtual
      });
    }
    if (mod.reasons && Array.isArray(mod.reasons)) {
      mod.reasons.forEach((reason) => {
        const depId = reason.moduleName || reason.moduleIdentifier || "";
        if (!depId)
          return;
        if (!fileExtPattern.test(depId))
          return;
        if (depId.startsWith("webpack/") || depId.startsWith("(webpack)"))
          return;
        const normalizedDepId = normalizeWebpackModulePath(depId);
        if (normalizedDepId && normalizedDepId !== normalizedId) {
          if (!moduleMap.has(normalizedDepId)) {
            moduleMap.set(normalizedDepId, {
              id: normalizedDepId,
              deps: [],
              virtual: false
            });
          }
          const depModule = moduleMap.get(normalizedDepId);
          if (!depModule.deps.includes(normalizedId)) {
            depModule.deps.push(normalizedId);
          }
        }
      });
    }
    if (mod.issuer) {
      const issuerId = normalizeWebpackModulePath(mod.issuer);
      if (issuerId && issuerId !== normalizedId && fileExtPattern.test(mod.issuer)) {
        if (!moduleMap.has(issuerId)) {
          moduleMap.set(issuerId, {
            id: issuerId,
            deps: [],
            virtual: false
          });
        }
        const issuerModule = moduleMap.get(issuerId);
        if (!issuerModule.deps.includes(normalizedId)) {
          issuerModule.deps.push(normalizedId);
        }
      }
    }
  });
  moduleMap.forEach((mod) => {
    const existing = modules.find((m) => m.id === mod.id);
    if (existing) {
      mod.deps.forEach((dep) => {
        if (!existing.deps.includes(dep)) {
          existing.deps.push(dep);
        }
      });
    } else {
      modules.push(mod);
    }
  });
}
function setupWebpackModuleGraph(compiler, root) {
  const fileExtPattern = /\.(?:tsx?|jsx?|vue|json|css|scss|less|html)(?:$|\?)/;
  compiler.hooks.compilation.tap("react-devtools-graph", (compilation) => {
    var _a;
    (_a = compilation.hooks.afterOptimizeModules) == null ? void 0 : _a.tap("react-devtools-graph", (compilationModules) => {
      var _a2, _b;
      try {
        const modules = [];
        const moduleMap = /* @__PURE__ */ new Map();
        for (const mod of compilationModules) {
          const resource = mod.resource || mod.userRequest || "";
          if (!resource)
            continue;
          if (!fileExtPattern.test(resource))
            continue;
          const normalizedPath = resource.replace(/\\/g, "/");
          const id = normalizedPath;
          if (!moduleMap.has(id)) {
            moduleMap.set(id, {
              id,
              deps: [],
              virtual: !mod.resource
            });
          }
          if (mod.dependencies) {
            for (const dep of mod.dependencies) {
              const depModule = (_b = (_a2 = compilation.moduleGraph) == null ? void 0 : _a2.getModule) == null ? void 0 : _b.call(_a2, dep);
              if (depModule) {
                const depResource = depModule.resource || depModule.userRequest || "";
                if (depResource && fileExtPattern.test(depResource)) {
                  const depId = depResource.replace(/\\/g, "/");
                  const currentModule = moduleMap.get(id);
                  if (!currentModule.deps.includes(depId)) {
                    currentModule.deps.push(depId);
                  }
                }
              }
            }
          }
        }
        moduleMap.forEach((mod) => {
          modules.push(mod);
        });
        if (modules.length > 0) {
          webpackModuleGraph = { modules, root };
          try {
            const graphDir = path5.join(root, ".next", "cache", "react-devtools");
            if (!fs2.existsSync(graphDir)) {
              fs2.mkdirSync(graphDir, { recursive: true });
            }
            const graphPath = path5.join(graphDir, "module-graph.json");
            fs2.writeFileSync(graphPath, JSON.stringify(webpackModuleGraph, null, 2));
          } catch (e) {
          }
        }
      } catch (error) {
        console.error("[React DevTools] Failed to collect module graph from compilation:", error);
      }
    });
  });
  compiler.hooks.done.tap("react-devtools-graph", (stats) => {
    if (webpackModuleGraph.modules.length > 0) {
      return;
    }
    try {
      const modules = [];
      const statsArray = stats.stats || [stats];
      for (const singleStats of statsArray) {
        if (typeof singleStats.toJson !== "function") {
          continue;
        }
        const statsData = singleStats.toJson({
          all: false,
          modules: true,
          reasons: true,
          children: true,
          nestedModules: true,
          dependentModules: true
        });
        if (statsData.children && Array.isArray(statsData.children) && statsData.children.length > 0) {
          for (const child of statsData.children) {
            if (child.modules && child.modules.length > 0) {
              processModules(child.modules, modules, fileExtPattern);
            }
          }
        }
        if (statsData.modules && statsData.modules.length > 0) {
          processModules(statsData.modules, modules, fileExtPattern);
        }
      }
      if (modules.length > 0) {
        webpackModuleGraph = { modules, root };
        try {
          const graphDir = path5.join(root, ".next", "cache", "react-devtools");
          if (!fs2.existsSync(graphDir)) {
            fs2.mkdirSync(graphDir, { recursive: true });
          }
          const graphPath = path5.join(graphDir, "module-graph.json");
          fs2.writeFileSync(graphPath, JSON.stringify(webpackModuleGraph, null, 2));
        } catch (e) {
        }
      }
    } catch (error) {
      console.error("[React DevTools] Failed to collect module graph:", error);
    }
  });
}
function normalizeWebpackModulePath(modulePath) {
  if (!modulePath)
    return null;
  let path12 = modulePath;
  const loaderIndex = path12.lastIndexOf("!");
  if (loaderIndex !== -1) {
    path12 = path12.substring(loaderIndex + 1);
  }
  const queryIndex = path12.indexOf("?");
  if (queryIndex !== -1) {
    path12 = path12.substring(0, queryIndex);
  }
  path12 = path12.replace(/^\.\//, "");
  path12 = path12.replace(/^!+/, "");
  if (!path12 || !path12.includes("/"))
    return null;
  return path12;
}
function getWebpackModuleGraph() {
  return async () => {
    return webpackModuleGraph;
  };
}
function getViteModuleGraph(server, root) {
  return async () => {
    var _a, _b;
    const moduleGraph = server.moduleGraph;
    if (!moduleGraph) {
      return { modules: [], root };
    }
    const modules = [];
    const fileExtPattern = /\.(?:tsx?|jsx?|vue|json|css|scss|less|html)(?:$|\?)/;
    for (const [, mod] of moduleGraph.idToModuleMap) {
      if (!mod.file && !mod.url)
        continue;
      const id = mod.file || mod.url;
      if (!id)
        continue;
      if (!fileExtPattern.test(id))
        continue;
      const deps = [];
      for (const importedMod of mod.importedModules) {
        const depId = importedMod.file || importedMod.url;
        if (depId && fileExtPattern.test(depId)) {
          deps.push(depId);
        }
      }
      modules.push({
        id,
        deps,
        virtual: !mod.file || ((_a = mod.url) == null ? void 0 : _a.startsWith("\0")) || ((_b = mod.url) == null ? void 0 : _b.includes("virtual:"))
      });
    }
    return { modules, root };
  };
}

// src/middleware/open-in-editor.ts
import { exec } from "child_process";

// src/utils/paths.ts
import fs3 from "fs";
import path6 from "path";
function normalizePath(id) {
  return id.replace(/\\/g, "/");
}
var OVERLAY_ENTRY_ID = "\0react-devtools-overlay-entry";
var OVERLAY_CHUNK_NAME = "react-devtools-overlay";
var VIRTUAL_PATH_PREFIX = "virtual:react-devtools-path:";
var DEVTOOLS_OPTIONS_ID = "virtual:react-devtools-options";
var RESOLVED_OPTIONS_ID = `\0${DEVTOOLS_OPTIONS_ID}`;
function getPluginPath() {
  return normalizePath(DIR_DIST.replace(/\/dist$/, "/src"));
}
function getClientPath(reactDevtoolsPath) {
  const clientPath = path6.resolve(reactDevtoolsPath, "../../react-devtools-client");
  const oldClientPath = path6.resolve(reactDevtoolsPath, "../client");
  const clientDistPath = path6.resolve(clientPath, "dist");
  return fs3.existsSync(clientDistPath) && fs3.existsSync(path6.resolve(clientDistPath, "index.html")) ? clientDistPath : oldClientPath;
}
function resolveOverlayPath(normalizedId, overlayDir, reactDevtoolsPath) {
  if (!normalizedId.startsWith(VIRTUAL_PATH_PREFIX)) {
    return null;
  }
  const pathPart = normalizedId.replace(VIRTUAL_PATH_PREFIX, "");
  const bundledOverlayPath = path6.join(overlayDir, "react-devtools-overlay.mjs");
  if (fs3.existsSync(bundledOverlayPath)) {
    return normalizePath(bundledOverlayPath);
  }
  const basePath = pathPart.replace(/\.mjs$/, "");
  const hasExtension = /\.(?:tsx?|jsx?)$/.test(basePath);
  const paths = [
    hasExtension ? path6.join(overlayDir, basePath) : path6.join(overlayDir, `${basePath}.tsx`),
    path6.join(overlayDir, hasExtension ? basePath.replace(/\.tsx$/, ".ts") : `${basePath}.ts`),
    path6.join(reactDevtoolsPath, "overlay", pathPart)
  ];
  for (const p of paths) {
    if (fs3.existsSync(p)) {
      return normalizePath(p);
    }
  }
  return normalizePath(bundledOverlayPath);
}
function convertToEditorPath(filePath, line, column) {
  const parts = [filePath];
  if (line !== void 0)
    parts.push(String(line));
  if (column !== void 0 && line !== void 0)
    parts.push(String(column));
  return parts.join(":");
}
function parseEditorPath(editorPath) {
  const parts = editorPath.split(":");
  const filePath = parts[0];
  const line = parts[1] ? Number.parseInt(parts[1], 10) : void 0;
  const column = parts[2] ? Number.parseInt(parts[2], 10) : void 0;
  return { filePath, line, column };
}
function resolveRelativeToAbsolute(relativePath, projectRoot, sourcePathMode) {
  if (sourcePathMode === "absolute" || path6.isAbsolute(relativePath)) {
    return relativePath;
  }
  const segments = relativePath.split("/");
  const pathFromRoot = segments.length > 1 ? segments.slice(1).join("/") : relativePath;
  return path6.resolve(projectRoot, pathFromRoot);
}

// src/middleware/open-in-editor.ts
async function openFileInEditor(filePath, projectRoot, sourcePathMode, launchEditor) {
  return new Promise((resolve2, reject) => {
    const { filePath: file, line, column } = parseEditorPath(filePath);
    const absolutePath = resolveRelativeToAbsolute(file, projectRoot, sourcePathMode);
    const editorPath = convertToEditorPath(absolutePath, line, column);
    const editorCmd = launchEditor || process.env.EDITOR || "code";
    const cmd = `${editorCmd} -g "${editorPath}"`;
    exec(cmd, (error) => {
      if (error) {
        console.error("[React DevTools] Failed to open editor:", error);
        reject(error);
      } else {
        resolve2();
      }
    });
  });
}
function createOpenInEditorMiddleware(projectRoot, sourcePathMode, launchEditor) {
  return async (req, res, next) => {
    var _a;
    if (!((_a = req.url) == null ? void 0 : _a.startsWith("/__open-in-editor"))) {
      next == null ? void 0 : next();
      return;
    }
    const url = new URL(req.url, `http://${req.headers.host}`);
    const file = url.searchParams.get("file");
    if (!file) {
      res.statusCode = 400;
      res.setHeader("Content-Type", "text/plain");
      res.end("Missing file parameter");
      return;
    }
    const editorFromClient = url.searchParams.get("editor");
    const effectiveEditor = launchEditor || editorFromClient || void 0;
    try {
      await openFileInEditor(file, projectRoot, sourcePathMode, effectiveEditor);
      res.statusCode = 200;
      res.setHeader("Content-Type", "text/plain");
      res.end("OK");
    } catch (error) {
      console.error("[React DevTools] Failed to execute editor command:", error.message);
      res.statusCode = 500;
      res.setHeader("Content-Type", "text/plain");
      res.end("Failed to open editor");
    }
  };
}

// src/middleware/plugin-file.ts
import fs4 from "fs";
import { transformSync } from "@babel/core";
function createPluginFileMiddleware() {
  return (req, res, next) => {
    const rawUrl = req.url || "";
    const url = new URL(rawUrl, "http://localhost");
    if (rawUrl.includes("__react_devtools__")) {
    }
    if (url.pathname === "/__react_devtools__/file") {
      const filePath = url.searchParams.get("path");
      if (!filePath) {
        console.error("[React DevTools] Plugin file middleware: Missing path parameter", req.url);
        res.statusCode = 400;
        res.end("Missing path parameter");
        return;
      }
      try {
        const decodedPath = decodeURIComponent(filePath);
        if (!fs4.existsSync(decodedPath)) {
          console.error("[React DevTools] Plugin file middleware: File not found", decodedPath);
          res.statusCode = 404;
          res.end("File not found");
          return;
        }
        const content = fs4.readFileSync(decodedPath, "utf-8");
        const isTs = decodedPath.endsWith(".ts") || decodedPath.endsWith(".tsx");
        const isJsx = decodedPath.endsWith(".jsx") || decodedPath.endsWith(".tsx");
        const result = transformSync(content, {
          filename: decodedPath,
          presets: [
            ["@babel/preset-react", {
              runtime: "classic",
              // Switch to classic runtime to avoid jsx-dev-runtime imports
              development: true
            }],
            ["@babel/preset-typescript", { isTSX: isJsx, allExtensions: true, allowDeclareFields: true }]
          ],
          plugins: [
            // Simple plugin to rewrite "import React from 'react'" to "const React = window.React"
            function() {
              return {
                visitor: {
                  ImportDeclaration(path12) {
                    if (path12.node.source.value === "react") {
                      const defaultSpecifier = path12.node.specifiers.find(
                        (s) => s.type === "ImportDefaultSpecifier"
                      );
                      if (defaultSpecifier) {
                        const localName = defaultSpecifier.local.name;
                        path12.replaceWith({
                          type: "VariableDeclaration",
                          kind: "const",
                          declarations: [
                            {
                              type: "VariableDeclarator",
                              id: { type: "Identifier", name: localName },
                              init: {
                                type: "MemberExpression",
                                object: { type: "Identifier", name: "window" },
                                property: { type: "Identifier", name: "React" }
                              }
                            }
                          ]
                        });
                      } else {
                        const namespaceSpecifier = path12.node.specifiers.find(
                          (s) => s.type === "ImportNamespaceSpecifier"
                        );
                        if (namespaceSpecifier) {
                          const localName = namespaceSpecifier.local.name;
                          path12.replaceWith({
                            type: "VariableDeclaration",
                            kind: "const",
                            declarations: [
                              {
                                type: "VariableDeclarator",
                                id: { type: "Identifier", name: localName },
                                init: {
                                  type: "MemberExpression",
                                  object: { type: "Identifier", name: "window" },
                                  property: { type: "Identifier", name: "React" }
                                }
                              }
                            ]
                          });
                        } else {
                          path12.remove();
                        }
                      }
                    }
                  }
                }
              };
            }
          ]
        });
        res.setHeader("Content-Type", "application/javascript");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.end((result == null ? void 0 : result.code) || "");
        return;
      } catch (e) {
        console.error("[React DevTools] Failed to transform plugin file:", e);
        res.statusCode = 500;
        res.end(JSON.stringify({ error: e.message }));
        return;
      }
    }
    next();
  };
}

// src/middleware/plugins.ts
function createPluginsMiddleware(config, transformPath) {
  return (req, res, next) => {
    const rawUrl = req.url || "";
    const url = new URL(rawUrl, "http://localhost");
    const isMatch = url.pathname === "/__react_devtools__/plugins-manifest.json";
    if (isMatch) {
      res.setHeader("Content-Type", "application/json");
      res.setHeader("Access-Control-Allow-Origin", "*");
      const plugins = (config.plugins || []).map((plugin) => {
        if (plugin.view && plugin.view.src && transformPath) {
          return __spreadProps(__spreadValues({}, plugin), {
            view: __spreadProps(__spreadValues({}, plugin.view), {
              src: transformPath(plugin.view.src)
            })
          });
        }
        return plugin;
      });
      res.end(JSON.stringify(plugins));
      return;
    }
    next();
  };
}

// src/integrations/vite.ts
function createOutputConfig(baseConfig) {
  return __spreadProps(__spreadValues({}, baseConfig), {
    manualChunks: (id, options, getModuleInfo) => {
      if (id.includes(OVERLAY_CHUNK_NAME) || id.includes("overlay")) {
        return OVERLAY_CHUNK_NAME;
      }
      if (typeof (baseConfig == null ? void 0 : baseConfig.manualChunks) === "function") {
        return baseConfig.manualChunks(id, options, getModuleInfo);
      }
      return null;
    }
  });
}
function createRollupInput(existingInput, overlayInput, root) {
  if (existingInput) {
    if (Array.isArray(existingInput)) {
      return [...existingInput, overlayInput];
    }
    if (typeof existingInput === "object") {
      return __spreadProps(__spreadValues({}, existingInput), {
        [OVERLAY_CHUNK_NAME]: overlayInput
      });
    }
  }
  const indexHtmlPath = path7.resolve(root, "index.html");
  if (fs5.existsSync(indexHtmlPath)) {
    return {
      main: indexHtmlPath,
      [OVERLAY_CHUNK_NAME]: overlayInput
    };
  }
  return overlayInput;
}
function findOverlayBundle(bundle) {
  for (const [key, chunk] of Object.entries(bundle)) {
    if ((chunk == null ? void 0 : chunk.type) === "chunk" && (key === OVERLAY_CHUNK_NAME || chunk.name === OVERLAY_CHUNK_NAME)) {
      return chunk.fileName;
    }
  }
  return null;
}
function updateHtmlWithOverlayPath(htmlPath, overlayBundleName, base) {
  let htmlContent = fs5.readFileSync(htmlPath, "utf-8");
  const placeholderPath = `${base}assets/react-devtools-overlay.js`;
  const virtualPath = `${base}@id/virtual:react-devtools-path:main.tsx`;
  const actualPath = `${base}${overlayBundleName}`;
  const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  htmlContent = htmlContent.replace(new RegExp(escapeRegex(placeholderPath), "g"), actualPath);
  htmlContent = htmlContent.replace(new RegExp(escapeRegex(virtualPath), "g"), actualPath);
  fs5.writeFileSync(htmlPath, htmlContent, "utf-8");
}
function setupDevServerMiddlewares(server, config, clientPath) {
  const base = server.config.base || "/";
  server.middlewares.use(createOpenInEditorMiddleware(
    config.projectRoot,
    config.sourcePathMode,
    config.launchEditor
  ));
  server.middlewares.use(createGraphMiddleware(
    getViteModuleGraph(server, config.projectRoot),
    base
  ));
  server.middlewares.use(createAssetsMiddleware({
    root: config.projectRoot,
    publicDir: server.config.publicDir || "public",
    baseUrl: base
  }));
  server.middlewares.use(`${base}__react_devtools__`, serveClient(clientPath));
}
function setupPreviewServerMiddlewares(server, config, clientPath) {
  server.middlewares.use(createOpenInEditorMiddleware(
    config.projectRoot,
    config.sourcePathMode,
    config.launchEditor
  ));
  const base = server.config.base || "/";
  server.middlewares.use(`${base}__react_devtools__`, serveClient(clientPath));
}
function getViteModeAndCommand(viteConfig) {
  return {
    // Consider both Vite mode and NODE_ENV for environment detection
    mode: viteConfig.mode || process.env.NODE_ENV || "development",
    command: viteConfig.command
  };
}

// src/integrations/webpack.ts
import fs7 from "fs";
import path10 from "path";

// src/compat/webpack-dev-server-version.ts
import fs6 from "fs";
import path8 from "path";
function detectDevServerVersion(devServerOptions, compiler) {
  const detectedVersion = detectFromPackageJson(compiler);
  if (detectedVersion) {
    return detectedVersion;
  }
  if (hasV4PlusOptions(devServerOptions)) {
    return { major: 4, version: "4.x+", isV3: false, isV4Plus: true };
  }
  if (hasV3Options(devServerOptions)) {
    return { major: 3, version: "3.x", isV3: true, isV4Plus: false };
  }
  return { major: 4, version: "4.x+ (assumed)", isV3: false, isV4Plus: true };
}
function hasV3Options(devServerOptions) {
  return devServerOptions.contentBase !== void 0 || typeof devServerOptions.before === "function" || typeof devServerOptions.after === "function";
}
function hasV4PlusOptions(devServerOptions) {
  return devServerOptions.static !== void 0 || typeof devServerOptions.setupMiddlewares === "function";
}
function detectFromPackageJson(compiler) {
  const contextPath = compiler.context || process.cwd();
  const possiblePaths = [
    path8.join(contextPath, "node_modules", "webpack-dev-server", "package.json"),
    path8.join(contextPath, "..", "node_modules", "webpack-dev-server", "package.json"),
    path8.join(contextPath, "..", "..", "node_modules", "webpack-dev-server", "package.json")
  ];
  for (const pkgPath of possiblePaths) {
    try {
      if (fs6.existsSync(pkgPath)) {
        const pkgJson = JSON.parse(fs6.readFileSync(pkgPath, "utf-8"));
        const version = pkgJson.version || "";
        const major = Number.parseInt(version.split(".")[0], 10) || 4;
        return {
          major,
          version,
          isV3: major === 3,
          isV4Plus: major >= 4
        };
      }
    } catch (e) {
      continue;
    }
  }
  return null;
}
function isDevServerV3(devServerOptions, compiler) {
  return detectDevServerVersion(devServerOptions, compiler).isV3;
}
var DevServerMiddlewareAdapter = {
  /**
   * Apply middleware for webpack-dev-server v3
   */
  applyV3(devServerOptions, middlewares) {
    const originalBefore = devServerOptions.before;
    devServerOptions.before = (app, server, compiler) => {
      for (const { path: pathPrefix, middleware } of middlewares) {
        if (pathPrefix) {
          app.use(pathPrefix, middleware);
        } else {
          app.use(middleware);
        }
      }
      if (originalBefore) {
        originalBefore(app, server, compiler);
      }
    };
  },
  /**
   * Apply middleware for webpack-dev-server v4+
   */
  applyV4Plus(devServerOptions, middlewares) {
    const originalSetupMiddlewares = devServerOptions.setupMiddlewares;
    devServerOptions.setupMiddlewares = (existingMiddlewares, devServer) => {
      let result = existingMiddlewares;
      if (originalSetupMiddlewares) {
        result = originalSetupMiddlewares(existingMiddlewares, devServer);
      }
      for (const setup of [...middlewares].reverse()) {
        result.unshift({
          name: setup.name,
          path: setup.path,
          middleware: setup.middleware
        });
      }
      return result;
    };
  },
  /**
   * Apply middleware based on detected version
   */
  apply(devServerOptions, compiler, middlewares) {
    if (isDevServerV3(devServerOptions, compiler)) {
      this.applyV3(devServerOptions, middlewares);
    } else {
      this.applyV4Plus(devServerOptions, middlewares);
    }
  }
};

// src/compat/webpack-version.ts
function detectWebpackVersion(compiler) {
  var _a;
  let version = "";
  let major = 4;
  const webpackVersion = ((_a = compiler.webpack) == null ? void 0 : _a.version) || "";
  if (webpackVersion) {
    version = webpackVersion;
    major = Number.parseInt(version.split(".")[0], 10) || 4;
  } else if (compiler.webpack === void 0) {
    major = 4;
    version = "4.x (detected by missing compiler.webpack)";
  } else if (compiler.webpack) {
    major = 5;
    version = "5.x";
  } else {
    major = 4;
    version = "4.x (assumed)";
  }
  return {
    major,
    version,
    isWebpack4: major === 4,
    isWebpack5: major >= 5
  };
}
function isWebpack4(compiler) {
  return detectWebpackVersion(compiler).isWebpack4;
}

// src/utils/babel-transform.ts
import path9 from "path";
import { transformSync as transformSync2, types } from "@babel/core";
function createSourceAttributePlugin(projectRoot, pathMode) {
  return function sourceAttributePlugin() {
    return {
      name: "react-devtools-source-attribute",
      visitor: {
        JSXOpeningElement(nodePath) {
          var _a, _b;
          const loc = nodePath.node.loc;
          if (!loc)
            return;
          const filename = ((_b = (_a = this.file) == null ? void 0 : _a.opts) == null ? void 0 : _b.filename) || "";
          if (!filename)
            return;
          let finalPath = filename;
          if (pathMode === "relative" && path9.isAbsolute(filename) && projectRoot) {
            const parentDir = path9.dirname(projectRoot);
            finalPath = path9.relative(parentDir, filename);
            finalPath = finalPath.split(path9.sep).join("/");
          }
          nodePath.node.attributes.push(
            types.jsxAttribute(
              types.jsxIdentifier("data-source-path"),
              types.stringLiteral(`${finalPath}:${loc.start.line}:${loc.start.column}`)
            )
          );
        }
      }
    };
  };
}
function transformSourceCode(code, id, enableInjection, projectRoot, sourcePathMode) {
  if (!id.match(/\.[jt]sx$/))
    return null;
  if (!enableInjection)
    return null;
  try {
    const result = transformSync2(code, {
      filename: id,
      presets: [
        ["@babel/preset-react", { runtime: "automatic" }],
        ["@babel/preset-typescript", { allowDeclareFields: true }]
      ],
      plugins: [createSourceAttributePlugin(projectRoot, sourcePathMode)],
      ast: true,
      sourceMaps: true,
      configFile: false,
      babelrc: false
    });
    return (result == null ? void 0 : result.code) ? { code: result.code, map: result.map } : null;
  } catch (error) {
    console.error("[React DevTools] Babel transform error:", error);
    return null;
  }
}
function shouldProcessFile(id) {
  if (id.includes("node_modules"))
    return false;
  if (id.endsWith(".html") || id.endsWith(".htm")) {
    return false;
  }
  if (/\.(?:css|scss|sass|less|styl|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$/i.test(id)) {
    return false;
  }
  return true;
}

// src/integrations/webpack.ts
function setupWebpackDevServerMiddlewares(compiler, config, clientPath) {
  if (!compiler.options.devServer) {
    compiler.options.devServer = {};
  }
  const devServerOptions = compiler.options.devServer;
  setupWebpackModuleGraph(compiler, config.projectRoot);
  const middlewares = [
    {
      name: "react-devtools-plugins-manifest",
      // Mount globally so middleware handles path matching (same as Vite)
      middleware: createPluginsMiddleware(config, (filePath) => {
        return `/__react_devtools__/file?path=${encodeURIComponent(filePath)}`;
      })
    },
    {
      name: "react-devtools-plugin-file",
      // Mount globally to debug why path matching fails.
      // The middleware itself handles path checking.
      middleware: createPluginFileMiddleware()
    },
    {
      name: "react-devtools-graph",
      // Graph middleware for module dependency visualization (must be before client serving)
      middleware: createGraphMiddleware(
        getWebpackModuleGraph(),
        "/"
      )
    },
    {
      name: "react-devtools-open-in-editor",
      // Mount globally so middleware handles path matching for /__open-in-editor
      middleware: createOpenInEditorMiddleware(
        config.projectRoot,
        config.sourcePathMode,
        config.launchEditor
      )
    },
    {
      name: "react-devtools-assets",
      // Mount globally for assets API
      middleware: createAssetsMiddleware({
        root: config.projectRoot,
        publicDir: "public",
        baseUrl: "/"
      })
    },
    {
      name: "react-devtools-client",
      path: "/__react_devtools__",
      middleware: serveClient(clientPath)
    }
  ];
  DevServerMiddlewareAdapter.apply(devServerOptions, compiler, middlewares);
}
function getWebpackModeAndCommand(compiler) {
  const mode = compiler.options.mode || process.env.NODE_ENV || "development";
  const isServeMode = process.env.WEBPACK_SERVE === "true" || compiler.options.devServer && mode === "development";
  const command = isServeMode ? "serve" : "build";
  return { mode, command };
}
function getWebpackContext(compiler) {
  return compiler.context || process.cwd();
}
function ensureCacheDir(projectRoot) {
  const cacheDir = path10.join(projectRoot, "node_modules", ".cache", "react-devtools-plus");
  if (!fs7.existsSync(cacheDir)) {
    fs7.mkdirSync(cacheDir, { recursive: true });
  }
  return cacheDir;
}
function writeInitFile(cacheDir, filename, content) {
  const filePath = path10.join(cacheDir, filename);
  fs7.writeFileSync(filePath, content, "utf-8");
  return filePath;
}
function injectDevToolsEntries(compiler, overlayPath, projectRoot, overlayDir, scanInitCode, clientUrl, rootSelector, theme, assets, launchEditor) {
  const cacheDir = ensureCacheDir(projectRoot);
  const filesToInject = [];
  const configCode = generateConfigInjectionCode({ clientUrl, rootSelector, theme, assets, launchEditor });
  if (configCode) {
    const configPath = writeInitFile(cacheDir, "devtools-config.js", configCode);
    filesToInject.push(configPath);
  }
  if (scanInitCode) {
    const scanInitPath = writeInitFile(cacheDir, "scan-init.js", scanInitCode);
    filesToInject.push(scanInitPath);
  }
  const globalsInitCode = generateGlobalsWithCSSCode(overlayDir);
  const globalsInitPath = writeInitFile(cacheDir, "react-globals-init.js", globalsInitCode);
  filesToInject.push(globalsInitPath);
  filesToInject.push(overlayPath);
  const originalEntry = compiler.options.entry;
  const useWebpack4Format = isWebpack4(compiler);
  if (useWebpack4Format) {
    if (typeof originalEntry === "function") {
      compiler.options.entry = () => {
        const result = originalEntry();
        if (result && typeof result.then === "function") {
          return result.then((entries) => {
            return transformEntries(entries, filesToInject, true);
          });
        }
        return transformEntries(result, filesToInject, true);
      };
    } else {
      compiler.options.entry = transformEntries(originalEntry, filesToInject, true);
    }
  } else {
    compiler.options.entry = async () => {
      const entries = typeof originalEntry === "function" ? await originalEntry() : originalEntry;
      return transformEntries(entries, filesToInject, false);
    };
  }
}
function transformEntries(entries, filesToInject, useWebpack4Format) {
  if (typeof entries === "string") {
    if (useWebpack4Format) {
      return [...filesToInject, entries];
    } else {
      return {
        main: { import: [...filesToInject, entries] }
      };
    }
  }
  if (Array.isArray(entries)) {
    if (useWebpack4Format) {
      return [...filesToInject, ...entries];
    } else {
      return {
        main: { import: [...filesToInject, ...entries] }
      };
    }
  }
  if (typeof entries === "object" && entries !== null) {
    return transformObjectEntries(entries, filesToInject, useWebpack4Format);
  }
  return entries;
}
function transformObjectEntries(entries, filesToInject, useWebpack4Format) {
  const newEntries = __spreadValues({}, entries);
  const keys = Object.keys(newEntries);
  const mainKey = keys.find((k) => k === "main" || k === "app" || k === "index") || keys[0];
  if (!mainKey) {
    return newEntries;
  }
  const currentEntry = newEntries[mainKey];
  if (useWebpack4Format) {
    newEntries[mainKey] = transformWebpack4Entry(currentEntry, filesToInject);
  } else {
    newEntries[mainKey] = transformWebpack5Entry(currentEntry, filesToInject);
  }
  return newEntries;
}
function transformWebpack4Entry(currentEntry, filesToInject) {
  if (typeof currentEntry === "string") {
    return [...filesToInject, currentEntry];
  }
  if (Array.isArray(currentEntry)) {
    return [...filesToInject, ...currentEntry];
  }
  return filesToInject;
}
function transformWebpack5Entry(currentEntry, filesToInject) {
  let importFiles = [];
  let descriptor = {};
  if (typeof currentEntry === "string") {
    importFiles = [currentEntry];
  } else if (Array.isArray(currentEntry)) {
    importFiles = [...currentEntry];
  } else if (typeof currentEntry === "object" && (currentEntry == null ? void 0 : currentEntry.import)) {
    importFiles = Array.isArray(currentEntry.import) ? [...currentEntry.import] : [currentEntry.import];
    descriptor = currentEntry;
  }
  importFiles.unshift(...filesToInject);
  return __spreadProps(__spreadValues({}, descriptor), {
    import: importFiles
  });
}
function injectBabelPlugin(compiler, projectRoot, sourcePathMode) {
  var _a;
  const rules = (_a = compiler.options.module) == null ? void 0 : _a.rules;
  if (!rules) {
    return;
  }
  const plugin = createSourceAttributePlugin(projectRoot, sourcePathMode);
  rules.forEach((rule) => visitRuleAndInjectPlugin(rule, plugin));
}
function visitRuleAndInjectPlugin(rule, plugin) {
  if (rule.oneOf) {
    rule.oneOf.forEach((r) => visitRuleAndInjectPlugin(r, plugin));
    return;
  }
  if (rule.use) {
    const uses = Array.isArray(rule.use) ? rule.use : [rule.use];
    uses.forEach((use) => injectPluginToLoader(use, plugin));
  }
  if (rule.loader && rule.loader.includes("babel-loader")) {
    injectPluginToOptions(rule, plugin);
  }
}
function injectPluginToLoader(use, plugin) {
  const loaderName = typeof use === "string" ? use : use.loader;
  if (loaderName && loaderName.includes("babel-loader") && typeof use !== "string") {
    injectPluginToOptions(use, plugin);
  }
}
function injectPluginToOptions(config, plugin) {
  if (!config.options) {
    config.options = {};
  }
  if (!config.options.plugins) {
    config.options.plugins = [];
  }
  config.options.plugins.push(plugin);
}

// src/unplugin.ts
function printEnvironmentInfo(detectedEnv, isEnabled, enabledEnvironments) {
  const envInfo = `${bold("React DevTools")}: Environment detected as "${cyan(detectedEnv)}"`;
  const statusInfo = isEnabled ? `${green("\u2713")} DevTools enabled` : `${cyan("\u25CB")} DevTools disabled`;
  let reasonInfo = "";
  if (Array.isArray(enabledEnvironments)) {
    const envList = enabledEnvironments.map((e) => `"${e}"`).join(", ");
    reasonInfo = isEnabled ? ` (matched enabledEnvironments: [${envList}])` : ` (not in enabledEnvironments: [${envList}])`;
  } else if (enabledEnvironments === false) {
    reasonInfo = " (enabledEnvironments: false)";
  } else {
    reasonInfo = isEnabled ? " (serve mode)" : " (build mode)";
  }
  console.log(`  ${green("\u279C")}  ${envInfo}`);
  console.log(`  ${green("\u279C")}  ${statusInfo}${reasonInfo}`);
}
function printDevToolsUrls(urls) {
  const panelShortcut = process.platform === "darwin" ? "Option(\u2325)+Shift(\u21E7)+D" : "Alt(\u2325)+Shift(\u21E7)+D";
  const visibilityShortcut = process.platform === "darwin" ? "Option(\u2325)+Shift(\u21E7)+R" : "Alt(\u2325)+Shift(\u21E7)+R";
  const colorUrl = (value) => cyan(value.replace(/:(\d+)\//, (_, port) => `:${bold(port)}/`));
  for (const url of urls) {
    const devtoolsUrl = url.endsWith("/") ? `${url}__react_devtools__/` : `${url}/__react_devtools__/`;
    console.log(`  ${green("\u279C")}  ${bold("React DevTools")}: Open ${colorUrl(devtoolsUrl)} to view component tree`);
    console.log(`  ${green("\u279C")}  ${bold("React DevTools")}: Press ${cyan(panelShortcut)} to toggle panel, ${cyan(visibilityShortcut)} to show/hide overlay`);
  }
}
function wrapPrintUrls(server) {
  const originalPrintUrls = server.printUrls;
  server.printUrls = () => {
    originalPrintUrls();
    const urls = server.resolvedUrls;
    if (urls) {
      printDevToolsUrls(urls.local);
    }
  };
}
function excludeHtmlFromUnplugin(compiler) {
  compiler.hooks.normalModuleFactory.tap("unplugin-react-devtools", (nmf) => {
    nmf.hooks.afterResolve.tap("unplugin-react-devtools", (data) => {
      if (data.resource && (data.resource.endsWith(".html") || data.resource.endsWith(".htm"))) {
        if (data.loaders && Array.isArray(data.loaders)) {
          data.loaders = data.loaders.filter((loader) => {
            const loaderPath = typeof loader === "string" ? loader : loader.loader || loader.path || loader.request || "";
            return !loaderPath.includes("unplugin");
          });
        }
      }
    });
  });
}
var unpluginFactory = (options = {}) => {
  validatePluginOptions(options);
  const reactDevtoolsPath = getPluginPath();
  let viteConfig;
  let pluginConfig;
  let isWebpackContext = false;
  return {
    name: "unplugin-react-devtools",
    enforce: "pre",
    // Include JSX/TSX files for transformation
    transformInclude(id) {
      if (id.endsWith(".html") || id.endsWith(".htm"))
        return false;
      if (id.match(/\.[jt]sx$/))
        return true;
      return false;
    },
    loadInclude(id) {
      if (isWebpackContext)
        return false;
      return true;
    },
    // ============================================================
    // Vite Hooks
    // ============================================================
    vite: {
      apply(config, env) {
        const mode = env.mode || config.mode || process.env.NODE_ENV || "development";
        const command = env.command;
        const tempConfig = resolvePluginConfig(options, process.cwd(), mode, command);
        return tempConfig.isEnabled;
      },
      configResolved(resolved) {
        viteConfig = resolved;
        const { mode, command } = getViteModeAndCommand(resolved);
        pluginConfig = resolvePluginConfig(
          options,
          resolved.root || process.cwd(),
          mode,
          command
        );
        if (resolved.server) {
          resolved.server.fs.allow = [
            ...resolved.server.fs.allow || [],
            DIR_OVERLAY,
            path11.resolve(DIR_OVERLAY, "..")
          ];
        }
      },
      config(config, env) {
        var _a, _b, _c, _d, _e;
        if (env.command !== "build") {
          return {};
        }
        const mode = env.mode || config.mode || process.env.NODE_ENV || "development";
        const command = env.command;
        const tempConfig = resolvePluginConfig(options, config.root || process.cwd(), mode, command);
        if (!tempConfig.isEnabled) {
          return {};
        }
        const overlayMainPath = path11.join(DIR_OVERLAY, "react-devtools-overlay.mjs");
        if (!fs8.existsSync(overlayMainPath)) {
          return {};
        }
        const existingInput = (_b = (_a = config.build) == null ? void 0 : _a.rollupOptions) == null ? void 0 : _b.input;
        const existingOutput = (_d = (_c = config.build) == null ? void 0 : _c.rollupOptions) == null ? void 0 : _d.output;
        const outputConfig = Array.isArray(existingOutput) ? existingOutput.map(createOutputConfig) : existingOutput ? createOutputConfig(existingOutput) : createOutputConfig({});
        const input = createRollupInput(
          existingInput,
          OVERLAY_ENTRY_ID,
          config.root || process.cwd()
        );
        return {
          build: __spreadProps(__spreadValues({}, config.build), {
            rollupOptions: __spreadProps(__spreadValues({}, (_e = config.build) == null ? void 0 : _e.rollupOptions), {
              input,
              output: outputConfig
            })
          })
        };
      },
      configureServer(server) {
        if (!pluginConfig)
          return;
        printEnvironmentInfo(
          pluginConfig.detectedEnvironment,
          pluginConfig.isEnabled,
          pluginConfig.enabledEnvironments
        );
        const servePath = getClientPath(reactDevtoolsPath);
        setupDevServerMiddlewares(server, pluginConfig, servePath);
        server.middlewares.use(createPluginsMiddleware(pluginConfig, (filePath) => {
          if (process.platform === "win32") {
            return `/@fs/${filePath.replace(/\\/g, "/")}`;
          }
          return `/@fs${filePath}`;
        }));
        wrapPrintUrls(server);
      },
      configurePreviewServer(server) {
        if (!pluginConfig)
          return;
        const servePath = getClientPath(reactDevtoolsPath);
        setupPreviewServerMiddlewares(server, pluginConfig, servePath);
        wrapPrintUrls(server);
      },
      async resolveId(id, importer) {
        if (id === DEVTOOLS_OPTIONS_ID) {
          return RESOLVED_OPTIONS_ID;
        }
        if (id === OVERLAY_ENTRY_ID) {
          const overlayMainPath = path11.join(DIR_OVERLAY, "react-devtools-overlay.mjs");
          return fs8.existsSync(overlayMainPath) ? overlayMainPath : null;
        }
        if (id === "__react-devtools-scan__") {
          return "\0__react-devtools-scan__";
        }
        if (id === "__react-devtools-globals__") {
          return "\0__react-devtools-globals__";
        }
        if (id === "react-dom/client" && (importer == null ? void 0 : importer.includes("__react-devtools-globals__"))) {
          try {
            const projectRoot = (viteConfig == null ? void 0 : viteConfig.root) || process.cwd();
            const reactDomPath = path11.join(projectRoot, "node_modules", "react-dom", "client.js");
            if (fs8.existsSync(reactDomPath)) {
              return null;
            }
          } catch (e) {
          }
          return "\0__react-devtools-react-dom-client-fallback__";
        }
        const normalizedId = id.startsWith("@id/") ? id.replace("@id/", "") : id;
        return resolveOverlayPath(normalizedId, DIR_OVERLAY, reactDevtoolsPath);
      },
      async load(id) {
        if (id === RESOLVED_OPTIONS_ID) {
          if (!viteConfig || !pluginConfig) {
            return null;
          }
          return `export default ${JSON.stringify({
            base: viteConfig.base || "/",
            enabled: pluginConfig.isEnabled
          })}`;
        }
        if (id === "\0__react-devtools-scan__") {
          if (!(pluginConfig == null ? void 0 : pluginConfig.scan)) {
            return "export const initScan = () => {};";
          }
          return generateScanInitESMCode(pluginConfig.scan);
        }
        if (id === "\0__react-devtools-globals__") {
          return generateReactGlobalsESMCode({
            tryReactDOMClient: true,
            dispatchReadyEvent: true
          });
        }
        if (id === "\0__react-devtools-react-dom-client-fallback__") {
          return `
// Fallback module for react-dom/client (React 16/17)
// createRoot doesn't exist in React 16/17
export const createRoot = undefined;
export const hydrateRoot = undefined;
`;
        }
        return null;
      },
      transform(code, id, transformOptions) {
        if (transformOptions == null ? void 0 : transformOptions.ssr)
          return null;
        if (!isWebpackContext && !viteConfig)
          return null;
        if (!pluginConfig)
          return null;
        const filename = id.split("?", 2)[0];
        if (!shouldProcessFile(filename))
          return null;
        return transformSourceCode(
          code,
          filename,
          pluginConfig.injectSource,
          pluginConfig.projectRoot,
          pluginConfig.sourcePathMode
        );
      },
      transformIndexHtml(html, ctx) {
        if (!pluginConfig)
          return html;
        const base = normalizeBasePath(viteConfig == null ? void 0 : viteConfig.base);
        const isProduction = !!ctx.bundle;
        const scriptSrc = isProduction ? (() => {
          const overlayBundleName = findOverlayBundle(ctx.bundle);
          if (!overlayBundleName) {
            return `${base}@id/${VIRTUAL_PATH_PREFIX}main.tsx`;
          }
          const assetPath = `${base}${overlayBundleName}`;
          return assetPath;
        })() : `${base}@id/${VIRTUAL_PATH_PREFIX}main.tsx`;
        if (!scriptSrc) {
          return html;
        }
        const tags = [];
        const configTag = generateConfigScriptTag({
          clientUrl: pluginConfig.clientUrl,
          rootSelector: pluginConfig.rootSelector,
          theme: pluginConfig.theme,
          assets: pluginConfig.assets,
          launchEditor: pluginConfig.launchEditor
        });
        if (configTag) {
          tags.push(configTag);
        }
        tags.push(...generateCSSScriptTags(DIR_OVERLAY, base, isProduction));
        tags.push(generateDevToolsHookScriptTag());
        if (pluginConfig.scan) {
          tags.push(generateScanScriptTag(base, pluginConfig.scan));
        }
        tags.push({
          tag: "script",
          attrs: {
            type: "module",
            src: `${base}@id/__react-devtools-globals__`
          },
          injectTo: "head"
        });
        tags.push({
          tag: "script",
          attrs: {
            type: "module"
          },
          children: generateOverlayLoaderCode(scriptSrc),
          injectTo: "body"
        });
        return {
          html,
          tags
        };
      },
      async closeBundle() {
        if (!viteConfig || !pluginConfig || viteConfig.command !== "build")
          return;
        const outputDir = viteConfig.build.outDir || "dist";
        const htmlPath = path11.resolve(viteConfig.root, outputDir, "index.html");
        if (!fs8.existsSync(htmlPath)) {
          return;
        }
        const overlayBundleName = await (async () => {
          const assetsDir = path11.resolve(viteConfig.root, outputDir);
          const files = fs8.readdirSync(assetsDir);
          for (const file of files) {
            if (file.includes(OVERLAY_CHUNK_NAME) && file.endsWith(".js")) {
              return file;
            }
          }
          return null;
        })();
        if (!overlayBundleName) {
          return;
        }
        const base = normalizeBasePath(viteConfig.base);
        updateHtmlWithOverlayPath(htmlPath, overlayBundleName, base);
      }
    },
    // ============================================================
    // Webpack Hooks
    // ============================================================
    webpack(compiler) {
      isWebpackContext = true;
      excludeHtmlFromUnplugin(compiler);
      const { mode, command } = getWebpackModeAndCommand(compiler);
      const projectRoot = getWebpackContext(compiler);
      pluginConfig = resolvePluginConfig(options, projectRoot, mode, command);
      printEnvironmentInfo(
        pluginConfig.detectedEnvironment,
        pluginConfig.isEnabled,
        pluginConfig.enabledEnvironments
      );
      if (!(pluginConfig == null ? void 0 : pluginConfig.isEnabled)) {
        return;
      }
      if (command === "serve" && pluginConfig) {
        const servePath = getClientPath(reactDevtoolsPath);
        setupWebpackDevServerMiddlewares(compiler, pluginConfig, servePath);
        let scanInitCode;
        if (pluginConfig.scan) {
          scanInitCode = generateScanInitCJSCode(pluginConfig.scan);
        }
        const overlayPath = path11.join(DIR_OVERLAY, "react-devtools-overlay.mjs");
        injectDevToolsEntries(
          compiler,
          overlayPath,
          projectRoot,
          DIR_OVERLAY,
          scanInitCode,
          pluginConfig.clientUrl,
          pluginConfig.rootSelector,
          pluginConfig.theme,
          pluginConfig.assets,
          pluginConfig.launchEditor
        );
        if (pluginConfig.injectSource) {
          injectBabelPlugin(
            compiler,
            pluginConfig.projectRoot,
            pluginConfig.sourcePathMode
          );
        }
      }
    }
  };
};
var unplugin = createUnplugin(unpluginFactory);
var unplugin_default = unplugin;
var vite = unplugin.vite;
var webpack = unplugin.webpack;
export {
  unplugin_default as default,
  vite,
  webpack
};
//# sourceMappingURL=index.js.map