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 __getOwnPropNames = Object.getOwnPropertyNames;
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');
});
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 });
};

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

// src/utils/paths.ts
import fs from "fs";
import path from "path";
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" || path.isAbsolute(relativePath)) {
    return relativePath;
  }
  const segments = relativePath.split("/");
  const pathFromRoot = segments.length > 1 ? segments.slice(1).join("/") : relativePath;
  return path.resolve(projectRoot, pathFromRoot);
}
var DEVTOOLS_OPTIONS_ID, RESOLVED_OPTIONS_ID;
var init_paths = __esm({
  "src/utils/paths.ts"() {
    "use strict";
    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
});
import { exec } from "child_process";
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");
    }
  };
}
var init_open_in_editor = __esm({
  "src/middleware/open-in-editor.ts"() {
    "use strict";
    init_paths();
  }
});

// src/next-api.ts
import fs2 from "fs";
import path2 from "path";
import { NextResponse } from "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 = path2.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 (!fs2.existsSync(dir)) {
    return assets;
  }
  const entries = fs2.readdirSync(dir, { withFileTypes: true });
  for (const entry of entries) {
    const fullPath = path2.join(dir, entry.name);
    const relativePath = path2.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 = path2.extname(entry.name).toLowerCase();
      if (ASSET_EXTENSIONS.includes(ext)) {
        try {
          const stats = fs2.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(path2.join(projectRoot, "public"), "public", projectRoot);
      const srcAssets = scanAssets(path2.join(projectRoot, "src"), "src", projectRoot);
      const appAssets = scanAssets(path2.join(projectRoot, "app"), "app", projectRoot);
      const assets = [...publicAssets, ...srcAssets, ...appAssets];
      return new NextResponse(JSON.stringify(assets), {
        headers: {
          "Content-Type": "application/json",
          "Cache-Control": "no-cache",
          "Access-Control-Allow-Origin": "*"
        }
      });
    } catch (e) {
      return new NextResponse(JSON.stringify({ error: "Failed to scan assets" }), {
        status: 500,
        headers: { "Content-Type": "application/json" }
      });
    }
  }
  if (requestPath === "api/assets/refresh") {
    try {
      const publicAssets = scanAssets(path2.join(projectRoot, "public"), "public", projectRoot);
      const srcAssets = scanAssets(path2.join(projectRoot, "src"), "src", projectRoot);
      const appAssets = scanAssets(path2.join(projectRoot, "app"), "app", projectRoot);
      const assets = [...publicAssets, ...srcAssets, ...appAssets];
      return new NextResponse(JSON.stringify(assets), {
        headers: {
          "Content-Type": "application/json",
          "Cache-Control": "no-cache",
          "Access-Control-Allow-Origin": "*"
        }
      });
    } catch (e) {
      return new 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 NextResponse(JSON.stringify({ error: "Missing path parameter" }), {
        status: 400,
        headers: { "Content-Type": "application/json" }
      });
    }
    try {
      const fullPath = path2.join(projectRoot, filepath);
      if (fs2.existsSync(fullPath)) {
        const stats = fs2.statSync(fullPath);
        return new NextResponse(JSON.stringify({
          size: stats.size,
          mtime: stats.mtime.toISOString()
        }), {
          headers: {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*"
          }
        });
      }
      return new NextResponse(JSON.stringify(null), {
        headers: { "Content-Type": "application/json" }
      });
    } catch (e) {
      return new 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 NextResponse(JSON.stringify({ error: "Missing path parameter" }), {
        status: 400,
        headers: { "Content-Type": "application/json" }
      });
    }
    try {
      const fullPath = path2.join(projectRoot, filepath);
      if (fs2.existsSync(fullPath)) {
        const content = fs2.readFileSync(fullPath, "utf-8").slice(0, limit);
        return new NextResponse(JSON.stringify({ content }), {
          headers: {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*"
          }
        });
      }
      return new NextResponse(JSON.stringify({ content: null }), {
        headers: { "Content-Type": "application/json" }
      });
    } catch (e) {
      return new NextResponse(JSON.stringify({ error: "Failed to get text content" }), {
        status: 500,
        headers: { "Content-Type": "application/json" }
      });
    }
  }
  return new NextResponse("Not found", { status: 404 });
}
function findPackageDir() {
  const possiblePaths = [
    path2.join(process.cwd(), "node_modules", "react-devtools-plus")
  ];
  try {
    const pkgPath = __require.resolve("react-devtools-plus/package.json");
    possiblePaths.unshift(path2.dirname(pkgPath));
  } catch (e) {
  }
  for (const p of possiblePaths) {
    if (fs2.existsSync(p)) {
      const pkgJsonPath = path2.join(p, "package.json");
      if (fs2.existsSync(pkgJsonPath)) {
        try {
          const pkg = JSON.parse(fs2.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 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 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 NextResponse("Failed to open editor", { status: 500 });
      }
    }
    if (requestPath === "plugins-manifest.json") {
      return new 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 = path2.join(projectRoot, ".next", "cache", "react-devtools", "module-graph.json");
      try {
        if (fs2.existsSync(graphPath)) {
          const graphData = JSON.parse(fs2.readFileSync(graphPath, "utf-8"));
          return new NextResponse(JSON.stringify(graphData), {
            headers: {
              "Content-Type": "application/json",
              "Cache-Control": "no-cache",
              "Access-Control-Allow-Origin": "*"
            }
          });
        }
      } catch (e) {
      }
      return new 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 NextResponse("react-devtools-plus package not found", {
        status: 404,
        headers: { "Content-Type": "text/plain" }
      });
    }
    if (requestPath === "overlay.mjs") {
      const overlayPaths = [
        path2.join(packageDir, "src", "overlay", "react-devtools-overlay.mjs"),
        path2.join(packageDir, "dist", "overlay", "react-devtools-overlay.mjs")
      ];
      for (const overlayPath of overlayPaths) {
        if (fs2.existsSync(overlayPath)) {
          const content2 = fs2.readFileSync(overlayPath, "utf-8");
          return new NextResponse(content2, {
            headers: {
              "Content-Type": "application/javascript; charset=utf-8",
              "Cache-Control": "no-cache"
            }
          });
        }
      }
      return new NextResponse("Overlay not found", { status: 404 });
    }
    if (requestPath === "overlay.css") {
      const cssPaths = [
        path2.join(packageDir, "src", "overlay", "react-devtools-overlay.css"),
        path2.join(packageDir, "dist", "overlay", "react-devtools-overlay.css")
      ];
      for (const cssPath of cssPaths) {
        if (fs2.existsSync(cssPath)) {
          const content2 = fs2.readFileSync(cssPath, "utf-8");
          return new NextResponse(content2, {
            headers: {
              "Content-Type": "text/css; charset=utf-8",
              "Cache-Control": "no-cache"
            }
          });
        }
      }
    }
    const clientDir = path2.join(packageDir, "client");
    if (!fs2.existsSync(clientDir)) {
      return new NextResponse("DevTools client not found", { status: 404 });
    }
    let filePath = path2.join(clientDir, requestPath || "index.html");
    if (!requestPath || !fs2.existsSync(filePath) || fs2.statSync(filePath).isDirectory()) {
      filePath = path2.join(clientDir, "index.html");
    }
    if (!fs2.existsSync(filePath)) {
      return new NextResponse("File not found", { status: 404 });
    }
    const mimeType = getMimeType(filePath);
    if (filePath.endsWith(".html")) {
      let htmlContent = fs2.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 NextResponse(htmlContent, {
        headers: {
          "Content-Type": mimeType,
          "Cache-Control": "no-cache"
        }
      });
    }
    const content = new Uint8Array(fs2.readFileSync(filePath));
    return new NextResponse(content, {
      headers: {
        "Content-Type": mimeType,
        "Cache-Control": "no-cache"
      }
    });
  } catch (error) {
    console.error("[React DevTools] API error:", error);
    return new NextResponse("Internal error", { status: 500 });
  }
}
export {
  GET
};
//# sourceMappingURL=next-api-handler.js.map