"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
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 __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/umi.ts
var umi_exports = {};
__export(umi_exports, {
  createUmiPlugin: () => createUmiPlugin,
  default: () => umi_default
});
module.exports = __toCommonJS(umi_exports);

// src/integrations/umi.ts
var import_node_fs4 = __toESM(require("fs"), 1);
var import_node_path6 = __toESM(require("path"), 1);

// src/config/normalize.ts
var import_node_path = __toESM(require("path"), 1);
function shouldEnableDevTools(enabledEnvironments, mode, command) {
  if (process.env.VITE_REACT_DEVTOOLS_ENABLED !== void 0) {
    return process.env.VITE_REACT_DEVTOOLS_ENABLED === "true";
  }
  if (enabledEnvironments === true) {
    return command === "serve";
  }
  if (enabledEnvironments === false) {
    return false;
  }
  if (Array.isArray(enabledEnvironments)) {
    const nodeEnv = process.env.NODE_ENV || mode;
    return enabledEnvironments.includes(nodeEnv) || enabledEnvironments.includes(mode);
  }
  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 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 (!import_node_path.default.isAbsolute(src)) {
        src = import_node_path.default.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,
    injectSource,
    sourcePathMode,
    projectRoot,
    mode,
    command,
    isEnabled,
    scan,
    clientUrl: options.clientUrl,
    rootSelector: options.rootSelector,
    theme: options.theme,
    assets: options.assets,
    launchEditor: options.launchEditor
  };
}

// src/dir.ts
var import_node_path2 = require("path");
var DIR_DIST = __dirname;
var DIR_OVERLAY = (0, import_node_path2.resolve)(DIR_DIST, "../src/overlay");

// src/middleware/assets.ts
var import_promises = __toESM(require("fs/promises"), 1);
var import_node_path3 = __toESM(require("path"), 1);
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 = import_node_path3.default.isAbsolute(publicDir) ? publicDir : import_node_path3.default.resolve(root, publicDir);
      const relativePublicDir = import_node_path3.default.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 = import_node_path3.default.resolve(root, relativePath);
        const stat = await import_promises.default.lstat(filePath);
        const assetPath = relativePath.replace(new RegExp(`^${relativePublicDir}/`), "");
        return {
          path: assetPath,
          relativePath,
          publicPath: import_node_path3.default.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 import_promises.default.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 import_promises.default.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
var import_sirv = __toESM(require("sirv"), 1);
function serveClient(servePath) {
  return (0, import_sirv.default)(servePath, {
    single: true,
    dev: true
  });
}

// src/middleware/graph.ts
var import_node_fs = __toESM(require("fs"), 1);
var import_node_path4 = __toESM(require("path"), 1);
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 = import_node_path4.default.join(root, ".next", "cache", "react-devtools");
            if (!import_node_fs.default.existsSync(graphDir)) {
              import_node_fs.default.mkdirSync(graphDir, { recursive: true });
            }
            const graphPath = import_node_path4.default.join(graphDir, "module-graph.json");
            import_node_fs.default.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 = import_node_path4.default.join(root, ".next", "cache", "react-devtools");
          if (!import_node_fs.default.existsSync(graphDir)) {
            import_node_fs.default.mkdirSync(graphDir, { recursive: true });
          }
          const graphPath = import_node_path4.default.join(graphDir, "module-graph.json");
          import_node_fs.default.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 path6 = modulePath;
  const loaderIndex = path6.lastIndexOf("!");
  if (loaderIndex !== -1) {
    path6 = path6.substring(loaderIndex + 1);
  }
  const queryIndex = path6.indexOf("?");
  if (queryIndex !== -1) {
    path6 = path6.substring(0, queryIndex);
  }
  path6 = path6.replace(/^\.\//, "");
  path6 = path6.replace(/^!+/, "");
  if (!path6 || !path6.includes("/"))
    return null;
  return path6;
}
function getWebpackModuleGraph() {
  return async () => {
    return webpackModuleGraph;
  };
}

// src/middleware/open-in-editor.ts
var import_node_child_process = require("child_process");

// src/utils/paths.ts
var import_node_fs2 = __toESM(require("fs"), 1);
var import_node_path5 = __toESM(require("path"), 1);
function normalizePath(id) {
  return id.replace(/\\/g, "/");
}
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 = import_node_path5.default.resolve(reactDevtoolsPath, "../../react-devtools-client");
  const oldClientPath = import_node_path5.default.resolve(reactDevtoolsPath, "../client");
  const clientDistPath = import_node_path5.default.resolve(clientPath, "dist");
  return import_node_fs2.default.existsSync(clientDistPath) && import_node_fs2.default.existsSync(import_node_path5.default.resolve(clientDistPath, "index.html")) ? clientDistPath : oldClientPath;
}
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" || import_node_path5.default.isAbsolute(relativePath)) {
    return relativePath;
  }
  const segments = relativePath.split("/");
  const pathFromRoot = segments.length > 1 ? segments.slice(1).join("/") : relativePath;
  return import_node_path5.default.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}"`;
    (0, import_node_child_process.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
var import_node_fs3 = __toESM(require("fs"), 1);
var import_core = require("@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 (!import_node_fs3.default.existsSync(decodedPath)) {
          console.error("[React DevTools] Plugin file middleware: File not found", decodedPath);
          res.statusCode = 404;
          res.end("File not found");
          return;
        }
        const content = import_node_fs3.default.readFileSync(decodedPath, "utf-8");
        const isTs = decodedPath.endsWith(".ts") || decodedPath.endsWith(".tsx");
        const isJsx = decodedPath.endsWith(".jsx") || decodedPath.endsWith(".tsx");
        const result = (0, import_core.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 }]
          ],
          plugins: [
            // Simple plugin to rewrite "import React from 'react'" to "const React = window.React"
            function() {
              return {
                visitor: {
                  ImportDeclaration(path6) {
                    if (path6.node.source.value === "react") {
                      const defaultSpecifier = path6.node.specifiers.find(
                        (s) => s.type === "ImportDefaultSpecifier"
                      );
                      if (defaultSpecifier) {
                        const localName = defaultSpecifier.local.name;
                        path6.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 = path6.node.specifiers.find(
                          (s) => s.type === "ImportNamespaceSpecifier"
                        );
                        if (namespaceSpecifier) {
                          const localName = namespaceSpecifier.local.name;
                          path6.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 {
                          path6.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/umi.ts
function createUmiPlugin(options = {}) {
  return (api) => {
    const mode = api.env || "development";
    const projectRoot = api.cwd;
    const reactDevtoolsPath = getPluginPath();
    const clientPath = getClientPath(reactDevtoolsPath);
    const pluginConfig = resolvePluginConfig(
      options,
      projectRoot,
      mode,
      mode === "development" ? "serve" : "build"
    );
    if (!(pluginConfig == null ? void 0 : pluginConfig.isEnabled)) {
      return;
    }
    api.logger.info("[React DevTools Plus] Plugin enabled");
    api.addBeforeMiddlewares(() => {
      const middlewares = [];
      middlewares.push((req, res, next) => {
        if (req.url === "/__react_devtools__/overlay.mjs") {
          const overlayPath = import_node_path6.default.join(DIR_OVERLAY, "react-devtools-overlay.mjs");
          if (import_node_fs4.default.existsSync(overlayPath)) {
            res.setHeader("Content-Type", "application/javascript; charset=utf-8");
            res.end(import_node_fs4.default.readFileSync(overlayPath, "utf-8"));
            return;
          }
        }
        next();
      });
      middlewares.push(
        createPluginsMiddleware(pluginConfig, (filePath) => {
          return `/__react_devtools__/file?path=${encodeURIComponent(filePath)}`;
        })
      );
      middlewares.push(createPluginFileMiddleware());
      middlewares.push(
        createGraphMiddleware(getWebpackModuleGraph(), "/")
      );
      middlewares.push(
        createOpenInEditorMiddleware(
          pluginConfig.projectRoot,
          pluginConfig.sourcePathMode,
          pluginConfig.launchEditor
        )
      );
      middlewares.push(
        createAssetsMiddleware({
          root: pluginConfig.projectRoot,
          publicDir: "public",
          baseUrl: "/"
        })
      );
      const sirvHandler = serveClient(clientPath);
      middlewares.push((req, res, next) => {
        var _a, _b;
        if (((_a = req.url) == null ? void 0 : _a.startsWith("/__react_devtools__")) && !((_b = req.url) == null ? void 0 : _b.includes("/overlay.mjs"))) {
          const originalUrl = req.url;
          req.url = req.url.replace("/__react_devtools__", "") || "/";
          sirvHandler(req, res, () => {
            req.url = originalUrl;
            next();
          });
        } else {
          next();
        }
      });
      return middlewares;
    });
    api.chainWebpack((memo, { env, webpack }) => {
      memo.plugin("react-devtools-module-graph").use(
        class ReactDevToolsModuleGraphPlugin {
          apply(compiler) {
            setupWebpackModuleGraph(compiler, projectRoot);
          }
        }
      );
      return memo;
    });
    api.addEntryCodeAhead(() => {
      return [
        `
// React DevTools Plus: Auto-expose React and ReactDOM to window
// This allows the overlay to render without manual user configuration
if (typeof window !== 'undefined') {
  try {
    if (!window.React) {
      window.React = require('react');
    }
  } catch (e) {
    // React not available via require, may be loaded via CDN
  }

  try {
    if (!window.ReactDOM) {
      var ReactDOM = require('react-dom');
      // Try to add createRoot support for React 18+
      try {
        var ReactDOMClient = require('react-dom/client');
        if (ReactDOMClient && ReactDOMClient.createRoot) {
          window.ReactDOM = Object.assign({}, ReactDOM, ReactDOMClient);
        } else {
          window.ReactDOM = ReactDOM;
        }
      } catch (e) {
        // react-dom/client not available (React 17 or earlier)
        window.ReactDOM = ReactDOM;
      }
    }
  } catch (e) {
    // ReactDOM not available via require, may be loaded via CDN
  }
}
`
      ];
    });
    api.addHTMLHeadScripts(() => {
      const scripts = [];
      scripts.push({
        content: `
(function() {
  if (typeof window !== 'undefined' && !window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
    window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
      renderers: new Map(),
      supportsFiber: true,
      inject: function(renderer) {
        var id = Math.random();
        this.renderers.set(id, renderer);
        return id;
      },
      onCommitFiberRoot: function() {},
      onCommitFiberUnmount: function() {},
    };
  }
})();
`
      });
      return scripts;
    });
    api.addHTMLScripts(() => {
      const scripts = [];
      const cssPath = import_node_path6.default.join(DIR_OVERLAY, "react-devtools-overlay.css");
      if (import_node_fs4.default.existsSync(cssPath)) {
        const cssContent = import_node_fs4.default.readFileSync(cssPath, "utf-8");
        scripts.push({
          content: `
(function() {
  if (typeof document !== 'undefined' && !document.getElementById('react-devtools-overlay-styles')) {
    var style = document.createElement('style');
    style.id = 'react-devtools-overlay-styles';
    style.textContent = ${JSON.stringify(cssContent)};
    document.head.appendChild(style);
  }
})();
`
        });
      }
      scripts.push({
        content: `
(function() {
  var maxAttempts = 100;
  var attempts = 0;

  function loadOverlay() {
    if (typeof window === 'undefined') return;

    attempts++;

    // Wait for React to be on window (exposed via webpack ProvidePlugin)
    if (!window.React || !window.ReactDOM) {
      if (attempts < maxAttempts) {
        setTimeout(loadOverlay, 50);
      } else {
        console.warn('[React DevTools] React not found on window after ' + maxAttempts + ' attempts');
      }
      return;
    }

    // Dynamically import the overlay module
    var script = document.createElement('script');
    script.type = 'module';
    script.src = '/__react_devtools__/overlay.mjs';
    script.onerror = function() {
      console.warn('[React DevTools] Failed to load overlay script');
    };
    document.body.appendChild(script);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', loadOverlay);
  } else {
    loadOverlay();
  }
})();
`
      });
      return scripts;
    });
    api.onDevCompileDone(() => {
      const panelShortcut = process.platform === "darwin" ? "Option(\u2325)+Shift(\u21E7)+D" : "Alt(\u2325)+Shift(\u21E7)+D";
      api.logger.info(`[React DevTools Plus] Press ${panelShortcut} to toggle DevTools panel`);
    });
  };
}

// src/umi.ts
var umi_default = createUmiPlugin;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createUmiPlugin
});
//# sourceMappingURL=umi.cjs.map