"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
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/dir.ts
var import_node_path, DIR_DIST, DIR_OVERLAY;
var init_dir = __esm({
  "src/dir.ts"() {
    "use strict";
    import_node_path = require("path");
    DIR_DIST = __dirname;
    DIR_OVERLAY = (0, import_node_path.resolve)(DIR_DIST, "../src/overlay");
  }
});

// src/utils/paths.ts
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_path2.default.isAbsolute(relativePath)) {
    return relativePath;
  }
  const segments = relativePath.split("/");
  const pathFromRoot = segments.length > 1 ? segments.slice(1).join("/") : relativePath;
  return import_node_path2.default.resolve(projectRoot, pathFromRoot);
}
var import_node_fs, import_node_path2, DEVTOOLS_OPTIONS_ID, RESOLVED_OPTIONS_ID;
var init_paths = __esm({
  "src/utils/paths.ts"() {
    "use strict";
    import_node_fs = __toESM(require("fs"), 1);
    import_node_path2 = __toESM(require("path"), 1);
    init_dir();
    DEVTOOLS_OPTIONS_ID = "virtual:react-devtools-options";
    RESOLVED_OPTIONS_ID = `\0${DEVTOOLS_OPTIONS_ID}`;
  }
});

// src/middleware/open-in-editor.ts
var open_in_editor_exports = {};
__export(open_in_editor_exports, {
  createOpenInEditorMiddleware: () => createOpenInEditorMiddleware,
  openFileInEditor: () => openFileInEditor
});
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");
    }
  };
}
var import_node_child_process;
var init_open_in_editor = __esm({
  "src/middleware/open-in-editor.ts"() {
    "use strict";
    import_node_child_process = require("child_process");
    init_paths();
  }
});

// src/next-api.ts
var next_api_exports = {};
__export(next_api_exports, {
  GET: () => GET
});
module.exports = __toCommonJS(next_api_exports);
var import_node_fs2 = __toESM(require("fs"), 1);
var import_node_path3 = __toESM(require("path"), 1);
var import_server = require("next/server");
var mimeTypes = {
  ".html": "text/html",
  ".js": "application/javascript",
  ".mjs": "application/javascript",
  ".css": "text/css",
  ".json": "application/json",
  ".svg": "image/svg+xml",
  ".png": "image/png",
  ".ico": "image/x-icon",
  ".woff": "font/woff",
  ".woff2": "font/woff2"
};
function getMimeType(filePath) {
  const ext = import_node_path3.default.extname(filePath).toLowerCase();
  return mimeTypes[ext] || "application/octet-stream";
}
var ASSET_EXTENSIONS = [
  ".png",
  ".jpg",
  ".jpeg",
  ".gif",
  ".webp",
  ".svg",
  ".ico",
  ".bmp",
  ".mp4",
  ".webm",
  ".ogg",
  ".mp3",
  ".wav",
  ".woff",
  ".woff2",
  ".ttf",
  ".eot",
  ".otf",
  ".pdf",
  ".txt",
  ".md",
  ".json"
];
function scanAssets(dir, basePath = "", projectRoot = process.cwd()) {
  const assets = [];
  if (!import_node_fs2.default.existsSync(dir)) {
    return assets;
  }
  const entries = import_node_fs2.default.readdirSync(dir, { withFileTypes: true });
  for (const entry of entries) {
    const fullPath = import_node_path3.default.join(dir, entry.name);
    const relativePath = import_node_path3.default.join(basePath, entry.name);
    if (entry.isDirectory()) {
      if (entry.name === "node_modules" || entry.name.startsWith(".") || entry.name === ".next") {
        continue;
      }
      assets.push(...scanAssets(fullPath, relativePath, projectRoot));
    } else if (entry.isFile()) {
      const ext = import_node_path3.default.extname(entry.name).toLowerCase();
      if (ASSET_EXTENSIONS.includes(ext)) {
        try {
          const stats = import_node_fs2.default.statSync(fullPath);
          const isPublic = basePath.startsWith("public");
          const publicPath = isPublic ? `/${relativePath.replace(/^public[/\\]/, "")}` : "";
          assets.push({
            path: relativePath,
            type: getAssetType(ext),
            publicPath,
            relativePath,
            filePath: fullPath,
            size: stats.size,
            mtime: stats.mtime.getTime()
          });
        } catch (e) {
        }
      }
    }
  }
  return assets;
}
function getAssetType(ext) {
  if ([".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".ico", ".bmp"].includes(ext)) {
    return "image";
  }
  if ([".mp4", ".webm", ".ogg"].includes(ext)) {
    return "video";
  }
  if ([".mp3", ".wav"].includes(ext)) {
    return "audio";
  }
  if ([".woff", ".woff2", ".ttf", ".eot", ".otf"].includes(ext)) {
    return "font";
  }
  return "other";
}
function handleAssetsApi(requestPath, url) {
  const projectRoot = process.cwd();
  if (requestPath === "api/assets") {
    try {
      const publicAssets = scanAssets(import_node_path3.default.join(projectRoot, "public"), "public", projectRoot);
      const srcAssets = scanAssets(import_node_path3.default.join(projectRoot, "src"), "src", projectRoot);
      const appAssets = scanAssets(import_node_path3.default.join(projectRoot, "app"), "app", projectRoot);
      const assets = [...publicAssets, ...srcAssets, ...appAssets];
      return new import_server.NextResponse(JSON.stringify(assets), {
        headers: {
          "Content-Type": "application/json",
          "Cache-Control": "no-cache",
          "Access-Control-Allow-Origin": "*"
        }
      });
    } catch (e) {
      return new import_server.NextResponse(JSON.stringify({ error: "Failed to scan assets" }), {
        status: 500,
        headers: { "Content-Type": "application/json" }
      });
    }
  }
  if (requestPath === "api/assets/refresh") {
    try {
      const publicAssets = scanAssets(import_node_path3.default.join(projectRoot, "public"), "public", projectRoot);
      const srcAssets = scanAssets(import_node_path3.default.join(projectRoot, "src"), "src", projectRoot);
      const appAssets = scanAssets(import_node_path3.default.join(projectRoot, "app"), "app", projectRoot);
      const assets = [...publicAssets, ...srcAssets, ...appAssets];
      return new import_server.NextResponse(JSON.stringify(assets), {
        headers: {
          "Content-Type": "application/json",
          "Cache-Control": "no-cache",
          "Access-Control-Allow-Origin": "*"
        }
      });
    } catch (e) {
      return new import_server.NextResponse(JSON.stringify({ error: "Failed to refresh assets" }), {
        status: 500,
        headers: { "Content-Type": "application/json" }
      });
    }
  }
  if (requestPath === "api/assets/image-meta") {
    const filepath = url.searchParams.get("path");
    if (!filepath) {
      return new import_server.NextResponse(JSON.stringify({ error: "Missing path parameter" }), {
        status: 400,
        headers: { "Content-Type": "application/json" }
      });
    }
    try {
      const fullPath = import_node_path3.default.join(projectRoot, filepath);
      if (import_node_fs2.default.existsSync(fullPath)) {
        const stats = import_node_fs2.default.statSync(fullPath);
        return new import_server.NextResponse(JSON.stringify({
          size: stats.size,
          mtime: stats.mtime.toISOString()
        }), {
          headers: {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*"
          }
        });
      }
      return new import_server.NextResponse(JSON.stringify(null), {
        headers: { "Content-Type": "application/json" }
      });
    } catch (e) {
      return new import_server.NextResponse(JSON.stringify({ error: "Failed to get image meta" }), {
        status: 500,
        headers: { "Content-Type": "application/json" }
      });
    }
  }
  if (requestPath === "api/assets/text-content") {
    const filepath = url.searchParams.get("path");
    const limit = Number.parseInt(url.searchParams.get("limit") || "500", 10);
    if (!filepath) {
      return new import_server.NextResponse(JSON.stringify({ error: "Missing path parameter" }), {
        status: 400,
        headers: { "Content-Type": "application/json" }
      });
    }
    try {
      const fullPath = import_node_path3.default.join(projectRoot, filepath);
      if (import_node_fs2.default.existsSync(fullPath)) {
        const content = import_node_fs2.default.readFileSync(fullPath, "utf-8").slice(0, limit);
        return new import_server.NextResponse(JSON.stringify({ content }), {
          headers: {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*"
          }
        });
      }
      return new import_server.NextResponse(JSON.stringify({ content: null }), {
        headers: { "Content-Type": "application/json" }
      });
    } catch (e) {
      return new import_server.NextResponse(JSON.stringify({ error: "Failed to get text content" }), {
        status: 500,
        headers: { "Content-Type": "application/json" }
      });
    }
  }
  return new import_server.NextResponse("Not found", { status: 404 });
}
function findPackageDir() {
  const possiblePaths = [
    import_node_path3.default.join(process.cwd(), "node_modules", "react-devtools-plus")
  ];
  try {
    const pkgPath = require.resolve("react-devtools-plus/package.json");
    possiblePaths.unshift(import_node_path3.default.dirname(pkgPath));
  } catch (e) {
  }
  for (const p of possiblePaths) {
    if (import_node_fs2.default.existsSync(p)) {
      const pkgJsonPath = import_node_path3.default.join(p, "package.json");
      if (import_node_fs2.default.existsSync(pkgJsonPath)) {
        try {
          const pkg = JSON.parse(import_node_fs2.default.readFileSync(pkgJsonPath, "utf-8"));
          if (pkg.name === "react-devtools-plus") {
            return p;
          }
        } catch (e) {
        }
      }
    }
  }
  return null;
}
async function GET(request, context) {
  try {
    const params = await context.params;
    const pathSegments = params.path || [];
    const requestPath = pathSegments.join("/");
    const url = new URL(request.url);
    const fullPath = url.pathname;
    const basePath = requestPath ? fullPath.replace(`/${requestPath}`, "") : fullPath.replace(/\/$/, "");
    if (requestPath === "api/open-in-editor" || requestPath.startsWith("__open-in-editor")) {
      const projectRoot = process.cwd();
      const url2 = new URL(request.url);
      const file = url2.searchParams.get("file");
      if (!file) {
        return new import_server.NextResponse("Missing file parameter", { status: 400 });
      }
      try {
        const { openFileInEditor: openFileInEditor2 } = await Promise.resolve().then(() => (init_open_in_editor(), open_in_editor_exports));
        await openFileInEditor2(file, projectRoot, "relative");
        return new import_server.NextResponse("OK", {
          headers: {
            "Content-Type": "text/plain",
            "Access-Control-Allow-Origin": "*"
          }
        });
      } catch (error) {
        console.error("[React DevTools] Failed to open editor:", error.message);
        return new import_server.NextResponse("Failed to open editor", { status: 500 });
      }
    }
    if (requestPath === "plugins-manifest.json") {
      return new import_server.NextResponse(JSON.stringify([]), {
        headers: {
          "Content-Type": "application/json",
          "Cache-Control": "no-cache",
          "Access-Control-Allow-Origin": "*"
        }
      });
    }
    if (requestPath === "__react_devtools_api__/graph" || requestPath === "api/graph") {
      const projectRoot = process.cwd();
      const graphPath = import_node_path3.default.join(projectRoot, ".next", "cache", "react-devtools", "module-graph.json");
      try {
        if (import_node_fs2.default.existsSync(graphPath)) {
          const graphData = JSON.parse(import_node_fs2.default.readFileSync(graphPath, "utf-8"));
          return new import_server.NextResponse(JSON.stringify(graphData), {
            headers: {
              "Content-Type": "application/json",
              "Cache-Control": "no-cache",
              "Access-Control-Allow-Origin": "*"
            }
          });
        }
      } catch (e) {
      }
      return new import_server.NextResponse(JSON.stringify({
        modules: [],
        root: projectRoot,
        message: "Module graph data not yet available. Please wait for webpack compilation to complete."
      }), {
        headers: {
          "Content-Type": "application/json",
          "Cache-Control": "no-cache",
          "Access-Control-Allow-Origin": "*"
        }
      });
    }
    if (requestPath === "api/assets" || requestPath.startsWith("api/assets/")) {
      return handleAssetsApi(requestPath, url);
    }
    const packageDir = findPackageDir();
    if (!packageDir) {
      return new import_server.NextResponse("react-devtools-plus package not found", {
        status: 404,
        headers: { "Content-Type": "text/plain" }
      });
    }
    if (requestPath === "overlay.mjs") {
      const overlayPaths = [
        import_node_path3.default.join(packageDir, "src", "overlay", "react-devtools-overlay.mjs"),
        import_node_path3.default.join(packageDir, "dist", "overlay", "react-devtools-overlay.mjs")
      ];
      for (const overlayPath of overlayPaths) {
        if (import_node_fs2.default.existsSync(overlayPath)) {
          const content2 = import_node_fs2.default.readFileSync(overlayPath, "utf-8");
          return new import_server.NextResponse(content2, {
            headers: {
              "Content-Type": "application/javascript; charset=utf-8",
              "Cache-Control": "no-cache"
            }
          });
        }
      }
      return new import_server.NextResponse("Overlay not found", { status: 404 });
    }
    if (requestPath === "overlay.css") {
      const cssPaths = [
        import_node_path3.default.join(packageDir, "src", "overlay", "react-devtools-overlay.css"),
        import_node_path3.default.join(packageDir, "dist", "overlay", "react-devtools-overlay.css")
      ];
      for (const cssPath of cssPaths) {
        if (import_node_fs2.default.existsSync(cssPath)) {
          const content2 = import_node_fs2.default.readFileSync(cssPath, "utf-8");
          return new import_server.NextResponse(content2, {
            headers: {
              "Content-Type": "text/css; charset=utf-8",
              "Cache-Control": "no-cache"
            }
          });
        }
      }
    }
    const clientDir = import_node_path3.default.join(packageDir, "client");
    if (!import_node_fs2.default.existsSync(clientDir)) {
      return new import_server.NextResponse("DevTools client not found", { status: 404 });
    }
    let filePath = import_node_path3.default.join(clientDir, requestPath || "index.html");
    if (!requestPath || !import_node_fs2.default.existsSync(filePath) || import_node_fs2.default.statSync(filePath).isDirectory()) {
      filePath = import_node_path3.default.join(clientDir, "index.html");
    }
    if (!import_node_fs2.default.existsSync(filePath)) {
      return new import_server.NextResponse("File not found", { status: 404 });
    }
    const mimeType = getMimeType(filePath);
    if (filePath.endsWith(".html")) {
      let htmlContent = import_node_fs2.default.readFileSync(filePath, "utf-8");
      htmlContent = htmlContent.replace(/src="\.\/assets\//g, `src="${basePath}/assets/`);
      htmlContent = htmlContent.replace(/href="\.\/assets\//g, `href="${basePath}/assets/`);
      htmlContent = htmlContent.replace(/src="\/__react_devtools__\/assets\//g, `src="${basePath}/assets/`);
      htmlContent = htmlContent.replace(/href="\/__react_devtools__\/assets\//g, `href="${basePath}/assets/`);
      return new import_server.NextResponse(htmlContent, {
        headers: {
          "Content-Type": mimeType,
          "Cache-Control": "no-cache"
        }
      });
    }
    const content = new Uint8Array(import_node_fs2.default.readFileSync(filePath));
    return new import_server.NextResponse(content, {
      headers: {
        "Content-Type": mimeType,
        "Cache-Control": "no-cache"
      }
    });
  } catch (error) {
    console.error("[React DevTools] API error:", error);
    return new import_server.NextResponse("Internal error", { status: 500 });
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  GET
});
//# sourceMappingURL=next-api.cjs.map