var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { D as DevServer } from "./dev-server-nWWQHf5q.js";
import { C as BufferPolyfill, as as almostnodeDebugWarn, at as simpleHash, ao as almostnodeDebugError, H as almostnodeDebugLog, au as REACT_CDN, av as REACT_DOM_CDN, aw as REACT_REFRESH_CDN, ax as TAILWIND_CDN_URL, ap as ESBUILD_WASM_ESM_CDN, aq as ESBUILD_WASM_BINARY_CDN } from "./fetch-virtual-server-BZi6n2Qk.js";
import { c as clearNpmBundleCache, a as addReactRefresh, r as redirectNpmImports, b as bundleNpmModuleForBrowser, l as loadTailwindConfig } from "./tailwind-config-loader-DYrGqMY-.js";
import { generateAndWriteRouteTree } from "./tanstack-route-tree-Cb1t32So.js";
const dynamicImport = new Function(
  "specifier",
  "return import(specifier)"
);
const isBrowser = typeof window !== "undefined" && typeof window.navigator !== "undefined" && "serviceWorker" in window.navigator;
async function initEsbuild() {
  if (!isBrowser) return;
  if (window.__esbuild) {
    return;
  }
  if (window.__esbuildInitPromise) {
    return window.__esbuildInitPromise;
  }
  if (window.__esbuildInitFailed) {
    throw new Error("esbuild initialization previously failed permanently");
  }
  window.__esbuildInitPromise = (async () => {
    try {
      const mod = await dynamicImport(ESBUILD_WASM_ESM_CDN);
      const esbuildMod = mod.default || mod;
      try {
        await esbuildMod.initialize({
          wasmURL: ESBUILD_WASM_BINARY_CDN
        });
        almostnodeDebugLog("vite", "[ViteDevServer] esbuild-wasm initialized");
      } catch (initError) {
        if (initError instanceof Error && initError.message.includes('Cannot call "initialize" more than once')) {
          almostnodeDebugLog("vite", "[ViteDevServer] esbuild-wasm already initialized, reusing");
        } else {
          throw initError;
        }
      }
      window.__esbuild = esbuildMod;
    } catch (error) {
      almostnodeDebugError("vite", "[ViteDevServer] Failed to initialize esbuild:", error);
      window.__esbuildInitFailed = true;
      window.__esbuildInitPromise = void 0;
      throw error;
    }
  })();
  return window.__esbuildInitPromise;
}
function getEsbuild() {
  return isBrowser ? window.__esbuild : void 0;
}
const REACT_REFRESH_PREAMBLE = `
<script type="module">
// Block until React Refresh is loaded and initialized
// This MUST happen before React is imported
const RefreshRuntime = await import('${REACT_REFRESH_CDN}').then(m => m.default || m);

// Hook into React BEFORE it's loaded
RefreshRuntime.injectIntoGlobalHook(window);
window.$RefreshRuntime$ = RefreshRuntime;

// Track registrations for debugging
window.$RefreshRegCount$ = 0;

// Register function called by transformed modules
window.$RefreshReg$ = (type, id) => {
  window.$RefreshRegCount$++;
  RefreshRuntime.register(type, id);
};

// Signature function (simplified - always returns identity)
window.$RefreshSig$ = () => (type) => type;

console.log('[HMR] React Refresh initialized');
<\/script>
`;
const HMR_CLIENT_SCRIPT = `
<script type="module">
(function() {
  // Track hot modules and their callbacks
  const hotModules = new Map();
  const pendingUpdates = new Map();

  // Implement import.meta.hot API (Vite-compatible)
  window.__vite_hot_context__ = function createHotContext(ownerPath) {
    // Return existing context if already created
    if (hotModules.has(ownerPath)) {
      return hotModules.get(ownerPath);
    }

    const hot = {
      // Persisted data between updates
      data: {},

      // Accept self-updates
      accept(callback) {
        hot._acceptCallback = callback;
      },

      // Cleanup before update
      dispose(callback) {
        hot._disposeCallback = callback;
      },

      // Force full reload
      invalidate() {
        location.reload();
      },

      // Prune callback (called when module is no longer imported)
      prune(callback) {
        hot._pruneCallback = callback;
      },

      // Event handlers (not implemented)
      on(event, cb) {},
      off(event, cb) {},
      send(event, data) {},

      // Internal callbacks
      _acceptCallback: null,
      _disposeCallback: null,
      _pruneCallback: null,
    };

    hotModules.set(ownerPath, hot);
    return hot;
  };

  // This preview's own virtual port: with several sandboxes live, updates
  // from another sandbox's dev server must be ignored even if a stale HMR
  // target still points at this window.
  var __hmrBaseMatch = location.pathname.match(/^(.*\\/__virtual__\\/(\\d+))(?:\\/|$)/);
  var __hmrVirtualBase = __hmrBaseMatch ? __hmrBaseMatch[1] : '';
  var __hmrOwnPort = __hmrBaseMatch ? Number(__hmrBaseMatch[2]) : null;

  function __hmrModuleUrl(modulePath, timestamp) {
    var normalizedPath = modulePath.startsWith('/') ? modulePath : '/' + modulePath;
    var pathWithBase = __hmrVirtualBase ? __hmrVirtualBase + normalizedPath : normalizedPath;
    return pathWithBase + '?t=' + timestamp;
  }

  // Listen for HMR updates via postMessage (works with sandboxed iframes)
  window.addEventListener('message', async (event) => {
    // Filter for HMR messages only
    if (!event.data || event.data.channel !== 'vite-hmr') return;
    if (
      __hmrOwnPort !== null &&
      typeof event.data.port === 'number' &&
      event.data.port !== __hmrOwnPort
    ) return;
    const { type, path, timestamp } = event.data;

    if (type === 'update') {
      console.log('[HMR] Update:', path);

      if (path.endsWith('.css')) {
        // CSS hot reload - update stylesheet href
        const links = document.querySelectorAll('link[rel="stylesheet"]');
        links.forEach(link => {
          const href = link.getAttribute('href');
          if (href && href.includes(path.replace(/^\\//, ''))) {
            link.href = href.split('?')[0] + '?t=' + timestamp;
          }
        });

        // Also update any injected style tags
        const styles = document.querySelectorAll('style[data-vite-dev-id]');
        styles.forEach(style => {
          const id = style.getAttribute('data-vite-dev-id');
          if (id && id.includes(path.replace(/^\\//, ''))) {
            // Re-import the CSS module to get updated styles
            import(__hmrModuleUrl(path, timestamp)).catch(() => {});
          }
        });
      } else if (path.match(/\\.(jsx?|tsx?)$/)) {
        // JS/JSX hot reload with React Refresh
        await handleJSUpdate(path, timestamp);
      }
    } else if (type === 'full-reload') {
      console.log('[HMR] Full reload');
      location.reload();
    }
  });

  // Handle JS/JSX module updates
  async function handleJSUpdate(path, timestamp) {
    // Normalize path to match module keys
    const normalizedPath = path.startsWith('/') ? path : '/' + path;
    const hot = hotModules.get(normalizedPath);

    try {
      // Call dispose callback if registered
      if (hot && hot._disposeCallback) {
        hot._disposeCallback(hot.data);
      }

      // Enqueue React Refresh (batches multiple updates)
      if (window.$RefreshRuntime$) {
        pendingUpdates.set(normalizedPath, timestamp);

        // Schedule refresh after a short delay to batch updates
        if (pendingUpdates.size === 1) {
          setTimeout(async () => {
            try {
              // Re-import all pending modules
              for (const [modulePath, ts] of pendingUpdates) {
                const moduleUrl = __hmrModuleUrl(modulePath, ts);
                await import(moduleUrl);
              }

              // Perform React Refresh
              window.$RefreshRuntime$.performReactRefresh();
              console.log('[HMR] Updated', pendingUpdates.size, 'module(s)');

              pendingUpdates.clear();
            } catch (error) {
              console.error('[HMR] Failed to apply update:', error);
              pendingUpdates.clear();
              location.reload();
            }
          }, 30);
        }
      } else {
        // No React Refresh available, fall back to page reload
        console.log('[HMR] React Refresh not available, reloading page');
        location.reload();
      }
    } catch (error) {
      console.error('[HMR] Update failed:', error);
      location.reload();
    }
  }

  console.log('[HMR] Client ready with React Refresh support');
})();
<\/script>
`;
const REPLAY_CAPTURE_SCRIPT = `
<script>
(function() {
  var simulationData = [];
  var startTime = Date.now();
  var nextRequestIndex = 0;

  function ts() { return new Date().toISOString(); }
  function relMs() { return Date.now() - startTime; }

  // ── Initial packets (matching simulationState.ts:initSimulationState) ──
  simulationData.push({ kind: 'version', version: '0.2.0', time: ts() });
  simulationData.push({ kind: 'viewport', size: { width: window.innerWidth, height: window.innerHeight }, time: ts() });
  simulationData.push({ kind: 'locationHref', href: location.href, time: ts() });
  simulationData.push({ kind: 'documentURL', url: location.href, time: ts() });
  simulationData.push({ kind: 'colorScheme', scheme: window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light', time: ts() });

  // ── rrweb DOM recording (loaded from CDN) ──
  import('https://esm.sh/rrweb@2.0.0-alpha.4').then(function(mod) {
    var record = mod.record || (mod.default && mod.default.record);
    if (!record) { console.warn('[Replay] rrweb record() not found in module'); return; }
    record({
      emit: function(event) {
        simulationData.push({ kind: 'rrweb', event: event, time: ts() });
      },
      checkoutEveryNms: 10000,
    });
    console.log('[Replay] rrweb recording started');
  }).catch(function(err) {
    console.warn('[Replay] Failed to load rrweb:', err.message || err);
  });

  // ── Selector builder ──
  function buildSelector(el) {
    if (!el || !el.tagName) return '';
    var parts = [];
    var cur = el;
    for (var i = 0; i < 5 && cur && cur.tagName; i++) {
      var s = cur.tagName.toLowerCase();
      if (cur.id) { parts.unshift(s + '#' + cur.id); break; }
      if (cur.className && typeof cur.className === 'string') {
        s += '.' + cur.className.trim().split(/\\s+/).join('.');
      }
      parts.unshift(s);
      cur = cur.parentElement;
    }
    return parts.join(' > ');
  }

  // ── Interaction capture (matching eventListeners.ts format) ──
  document.addEventListener('click', function(e) {
    var target = e.target;
    var rect = target && target.getBoundingClientRect ? target.getBoundingClientRect() : null;
    simulationData.push({
      kind: 'interaction',
      interaction: {
        kind: 'click',
        time: relMs(),
        selector: buildSelector(target),
        width: rect ? rect.width : 0,
        height: rect ? rect.height : 0,
        x: rect ? e.clientX - rect.x : e.clientX,
        y: rect ? e.clientY - rect.y : e.clientY,
      },
      time: ts(),
    });
  }, { capture: true, passive: true });

  document.addEventListener('keydown', function(e) {
    simulationData.push({
      kind: 'interaction',
      interaction: { kind: 'keydown', time: relMs(), key: e.key, selector: buildSelector(e.target) },
      time: ts(),
    });
  }, { capture: true, passive: true });

  document.addEventListener('scroll', function() {
    simulationData.push({
      kind: 'interaction',
      interaction: {
        kind: 'scroll',
        time: relMs(),
        windowScrollX: window.scrollX,
        windowScrollY: window.scrollY,
      },
      time: ts(),
    });
  }, { capture: true, passive: true });

  document.addEventListener('input', function(e) {
    var target = e.target;
    simulationData.push({
      kind: 'interaction',
      interaction: {
        kind: 'input',
        time: relMs(),
        selector: buildSelector(target),
        value: target && target.value ? target.value.slice(0, 200) : '',
      },
      time: ts(),
    });
  }, { capture: true, passive: true });

  // ── Network capture (matching networkCapture.ts format) ──
  var origFetch = window.fetch;
  window.fetch = function(input, init) {
    var url = typeof input === 'string' ? input : (input && input.url ? input.url : String(input));
    var idx = nextRequestIndex++;
    var reqTime = ts();

    simulationData.push({
      kind: 'networkRequest',
      request: { requestIndex: idx, url: url, time: reqTime },
      time: reqTime,
    });

    return origFetch.apply(this, arguments).then(function(response) {
      simulationData.push({
        kind: 'networkResponse',
        response: { requestIndex: idx, responseStatus: response.status },
        time: ts(),
      });
      return response;
    }).catch(function(err) {
      simulationData.push({
        kind: 'networkResponse',
        response: { requestIndex: idx, error: err.message || String(err) },
        time: ts(),
      });
      throw err;
    });
  };

  // ── Error capture (matching detectedError.ts format) ──
  window.addEventListener('error', function(e) {
    simulationData.push({
      kind: 'detectedError',
      detectedError: {
        time: ts(),
        message: e.message || String(e),
        details: (e.filename || '') + ':' + (e.lineno || 0) + ':' + (e.colno || 0),
      },
      time: ts(),
    });
  });

  window.addEventListener('unhandledrejection', function(e) {
    simulationData.push({
      kind: 'detectedError',
      detectedError: {
        time: ts(),
        message: e.reason ? (e.reason.message || String(e.reason)) : 'Unhandled rejection',
      },
      time: ts(),
    });
  });

  // ── @@replay-nut message handler (matching messageHandler.ts) ──
  window.addEventListener('message', function(event) {
    if (!event.data || event.data.source !== '@@replay-nut' || !event.data.request) return;

    var request = event.data.request;
    if (request.request === 'recording-data') {
      var json = JSON.stringify(simulationData);
      var buffer = new TextEncoder().encode(json).buffer;
      window.parent.postMessage(
        { id: event.data.id, response: buffer, source: '@@replay-nut' },
        '*',
        [buffer]
      );
    }
  });

  console.log('[Replay] Recording capture initialized (' + simulationData.length + ' initial packets)');
})();
<\/script>
`;
const _ViteDevServer = class _ViteDevServer extends DevServer {
  constructor(vfs, options) {
    super(vfs, options);
    __publicField(this, "watcherCleanup", null);
    __publicField(this, "options");
    __publicField(this, "hmrTargetWindow", null);
    __publicField(this, "transformCache", /* @__PURE__ */ new Map());
    __publicField(this, "pendingInstalledPackagesCacheClear", null);
    __publicField(this, "pendingRouteTreeRegen", null);
    __publicField(this, "tailwindConfigScript", "");
    __publicField(this, "tailwindConfigLoaded", false);
    __publicField(this, "_dependencies");
    __publicField(this, "_installedPackages");
    __publicField(this, "publicDir", null);
    this.options = {
      jsx: true,
      jsxFactory: "React.createElement",
      jsxFragment: "React.Fragment",
      jsxAutoImport: true,
      ...options
    };
    this.publicDir = this.options.publicDir === false ? null : this.resolvePath(this.options.publicDir ?? "/public");
  }
  /**
   * Set the target window for HMR updates (typically iframe.contentWindow).
   * This enables HMR to work with sandboxed iframes via postMessage.
   * Pass null when the workspace detaches: the iframe element (and its
   * contentWindow identity) is shared across sandboxes, so a stale target
   * would deliver this server's updates into another sandbox's preview.
   */
  setHMRTarget(targetWindow) {
    this.hmrTargetWindow = targetWindow;
  }
  clearInstalledPackagesCache() {
    this.transformCache.clear();
    this._installedPackages = void 0;
    this._dependencies = void 0;
    clearNpmBundleCache(this.vfs);
  }
  scheduleInstalledPackagesCacheClear() {
    if (this.pendingInstalledPackagesCacheClear) {
      clearTimeout(this.pendingInstalledPackagesCacheClear);
    }
    this.pendingInstalledPackagesCacheClear = setTimeout(() => {
      this.pendingInstalledPackagesCacheClear = null;
      this.clearInstalledPackagesCache();
    }, 48);
  }
  /**
   * Handle an incoming HTTP request
   */
  async handleRequest(method, url, headers, body) {
    const urlObj = new URL(url, "http://localhost");
    let pathname = urlObj.pathname;
    const npmMatch = pathname.match(/^(?:\/__virtual__\/\d+)?(\/_npm\/.*)$/);
    if (npmMatch) {
      return this.serveNpmModule(npmMatch[1]);
    }
    if (urlObj.searchParams.has("url")) {
      const resolvedPath = this.resolveModulePath(pathname);
      if (this.exists(resolvedPath)) {
        const js = `export default ${JSON.stringify(pathname)};`;
        return {
          statusCode: 200,
          statusMessage: "OK",
          headers: { "Content-Type": "application/javascript; charset=utf-8", "Cache-Control": "no-cache" },
          body: BufferPolyfill.from(js)
        };
      }
    }
    if (urlObj.searchParams.has("raw")) {
      const resolvedPath = this.resolveModulePath(pathname);
      if (this.exists(resolvedPath)) {
        try {
          const content = this.vfs.readFileSync(resolvedPath, "utf8");
          const js = `export default ${JSON.stringify(content)};`;
          return {
            statusCode: 200,
            statusMessage: "OK",
            headers: { "Content-Type": "application/javascript; charset=utf-8", "Cache-Control": "no-cache" },
            body: BufferPolyfill.from(js)
          };
        } catch {
        }
      }
    }
    const publicResponse = this.servePublicFile(pathname);
    if (publicResponse) {
      return publicResponse;
    }
    if (pathname === "/") {
      pathname = "/index.html";
    }
    const filePath = this.resolveModulePath(pathname);
    if (!pathname.endsWith("/") && filePath !== this.resolvePath(pathname)) {
      const basePath = this.resolvePath(pathname);
      if (this.isDirectory(basePath) && filePath.startsWith(basePath + "/index.")) {
        const lastSegment = pathname.split("/").pop() || "";
        return {
          statusCode: 301,
          statusMessage: "Moved Permanently",
          headers: { Location: lastSegment + "/" },
          body: BufferPolyfill.from("")
        };
      }
    }
    if (!this.exists(filePath)) {
      if (this.exists(filePath + ".html")) {
        return this.serveFile(filePath + ".html");
      }
      if (this.isDirectory(filePath) && this.exists(filePath + "/index.html")) {
        return this.serveFile(filePath + "/index.html");
      }
      if (this.options.spaFallback && !pathname.includes(".")) {
        return this.handleRequest(method, "/", headers, body);
      }
      return this.notFound(pathname);
    }
    if (this.isDirectory(filePath)) {
      if (this.exists(filePath + "/index.html")) {
        return this.serveFile(filePath + "/index.html");
      }
      return this.notFound(pathname);
    }
    if (this.needsTransform(filePath)) {
      return this.transformAndServe(filePath, pathname);
    }
    if (pathname.endsWith(".css")) {
      const secFetchDest = headers["sec-fetch-dest"] || headers["Sec-Fetch-Dest"] || headers["SEC-FETCH-DEST"] || "";
      const isModuleImport = secFetchDest === "script" || secFetchDest === "empty" || isBrowser && secFetchDest === "";
      if (isModuleImport) {
        return this.serveCssAsModule(filePath);
      }
      return this.serveFile(filePath);
    }
    if (pathname.endsWith(".html")) {
      return this.serveHtmlWithHMR(filePath);
    }
    if (pathname.endsWith(".json")) {
      const secFetchDest = headers["sec-fetch-dest"] || headers["Sec-Fetch-Dest"] || headers["SEC-FETCH-DEST"] || "";
      const isModuleImport = secFetchDest === "script" || secFetchDest === "empty" || isBrowser && secFetchDest === "";
      if (isModuleImport) {
        try {
          const content = this.vfs.readFileSync(filePath, "utf8");
          const js = `export default ${content};`;
          const buf = BufferPolyfill.from(js);
          return {
            statusCode: 200,
            statusMessage: "OK",
            headers: {
              "Content-Type": "application/javascript; charset=utf-8",
              "Content-Length": String(buf.length),
              "Cache-Control": "no-cache"
            },
            body: buf
          };
        } catch {
        }
      }
    }
    return this.serveFile(filePath);
  }
  /**
   * Start file watching for HMR
   */
  startWatching() {
    try {
      const watcher = this.vfs.watch(this.root, { recursive: true }, (eventType, filename) => {
        if (!filename) return;
        const fullPath = filename.startsWith("/") ? filename : this.root === "/" ? `/${filename}` : `${this.root}/${filename}`;
        const relativePath = this.root !== "/" && fullPath.startsWith(this.root + "/") ? fullPath.slice(this.root.length + 1) : fullPath.replace(/^\//, "");
        const isNodeModulesChange = relativePath === "node_modules" || relativePath.startsWith("node_modules/");
        if (relativePath === "package.json" || isNodeModulesChange) {
          this.scheduleInstalledPackagesCacheClear();
        }
        if (isNodeModulesChange) {
          return;
        }
        if (eventType === "change") {
          this.handleFileChange(fullPath);
        } else if (eventType === "rename" && this.vfs.existsSync(fullPath)) {
          if (this.isDirectory(fullPath)) return;
          this.handleFileChange(fullPath);
        }
        if (this.options.tanstackRouter) {
          const srcPath = this.root === "/" ? "/src" : `${this.root}/src`;
          const routesPrefix = srcPath + "/routes";
          const checkPath = fullPath;
          if (checkPath.startsWith(routesPrefix) && /\.(tsx?|jsx?)$/.test(checkPath)) {
            this.scheduleRouteTreeRegen();
          }
        }
      });
      this.watcherCleanup = () => {
        watcher.close();
      };
    } catch (error) {
      almostnodeDebugWarn("vite", "[ViteDevServer] Could not watch project root:", error);
    }
    try {
      const nodeModulesPath = this.root === "/" ? "/node_modules" : `${this.root}/node_modules`;
      const nodeModulesWatcher = this.vfs.watch(nodeModulesPath, { recursive: true }, () => {
        this.scheduleInstalledPackagesCacheClear();
      });
      const originalCleanup = this.watcherCleanup;
      this.watcherCleanup = () => {
        originalCleanup == null ? void 0 : originalCleanup();
        nodeModulesWatcher.close();
      };
    } catch {
    }
  }
  /**
   * Handle file change event
   */
  handleFileChange(path) {
    if (/\/tailwind\.config\.(ts|js|mjs)$/.test(path)) {
      this.tailwindConfigLoaded = false;
      this.tailwindConfigScript = "";
    }
    const isCSS = path.endsWith(".css");
    const isJS = /\.(jsx?|tsx?)$/.test(path);
    const updateType = isCSS || isJS ? "update" : "full-reload";
    const hmrPath = this.root !== "/" && path.startsWith(this.root + "/") ? path.slice(this.root.length) : path;
    const update = {
      type: updateType,
      path: hmrPath,
      timestamp: Date.now()
    };
    this.emitHMRUpdate(update);
    if (this.hmrTargetWindow) {
      try {
        this.hmrTargetWindow.postMessage({ ...update, channel: "vite-hmr", port: this.port }, "*");
      } catch (e) {
      }
    }
  }
  /**
   * Stop the server
   */
  stop() {
    if (this.watcherCleanup) {
      this.watcherCleanup();
      this.watcherCleanup = null;
    }
    if (this.pendingInstalledPackagesCacheClear) {
      clearTimeout(this.pendingInstalledPackagesCacheClear);
      this.pendingInstalledPackagesCacheClear = null;
    }
    if (this.pendingRouteTreeRegen) {
      clearTimeout(this.pendingRouteTreeRegen);
      this.pendingRouteTreeRegen = null;
    }
    this.hmrTargetWindow = null;
    super.stop();
  }
  /**
   * Check if a file needs transformation
   */
  needsTransform(path) {
    return /\.(jsx|tsx|ts)$/.test(path);
  }
  resolveModulePath(urlPath) {
    const filePath = this.resolvePath(urlPath);
    if (this.exists(filePath) && !this.isDirectory(filePath)) {
      return filePath;
    }
    const extensionCandidates = [".tsx", ".ts", ".jsx", ".js", ".mjs", ".css", ".json"];
    for (const extension of extensionCandidates) {
      if (this.exists(filePath + extension)) {
        return filePath + extension;
      }
    }
    const indexCandidates = extensionCandidates.map((extension) => `${filePath}/index${extension}`);
    for (const candidate of indexCandidates) {
      if (this.exists(candidate)) {
        return candidate;
      }
    }
    return filePath;
  }
  servePublicFile(pathname) {
    if (!this.publicDir || !pathname.startsWith("/")) {
      return null;
    }
    const publicDir = this.publicDir === "/" ? "" : this.publicDir.replace(/\/+$/, "");
    const publicPath = `${publicDir}${pathname}`;
    if (this.exists(publicPath) && !this.isDirectory(publicPath)) {
      return this.serveFile(publicPath);
    }
    return null;
  }
  /**
   * Transform and serve a JSX/TS file
   */
  async transformAndServe(filePath, urlPath) {
    try {
      const content = this.vfs.readFileSync(filePath, "utf8");
      const hash = simpleHash(content);
      const cached = this.transformCache.get(filePath);
      if (cached && cached.hash === hash) {
        const buffer2 = BufferPolyfill.from(cached.code);
        return {
          statusCode: 200,
          statusMessage: "OK",
          headers: {
            "Content-Type": "application/javascript; charset=utf-8",
            "Content-Length": String(buffer2.length),
            "Cache-Control": "no-cache",
            "X-Transformed": "true",
            "X-Cache": "hit"
          },
          body: buffer2
        };
      }
      const transformed = await this.transformCode(content, filePath);
      this.transformCache.set(filePath, { code: transformed, hash });
      const buffer = BufferPolyfill.from(transformed);
      return {
        statusCode: 200,
        statusMessage: "OK",
        headers: {
          "Content-Type": "application/javascript; charset=utf-8",
          "Content-Length": String(buffer.length),
          "Cache-Control": "no-cache",
          "X-Transformed": "true"
        },
        body: buffer
      };
    } catch (error) {
      almostnodeDebugError("vite", "[ViteDevServer] Transform error:", error);
      const message = error instanceof Error ? error.message : "Transform failed";
      const body = `// Transform Error: ${message}
console.error(${JSON.stringify(message)});`;
      return {
        statusCode: 200,
        // Return 200 with error in code to show in browser console
        statusMessage: "OK",
        headers: {
          "Content-Type": "application/javascript; charset=utf-8",
          "X-Transform-Error": "true"
        },
        body: BufferPolyfill.from(body)
      };
    }
  }
  /**
   * Transform JSX/TS code to browser-compatible JavaScript
   */
  async transformCode(code, filename) {
    if (!isBrowser) {
      return code;
    }
    await initEsbuild();
    const esbuild = getEsbuild();
    if (!esbuild) {
      throw new Error("esbuild not available");
    }
    let loader = "js";
    if (filename.endsWith(".jsx")) loader = "jsx";
    else if (filename.endsWith(".tsx")) loader = "tsx";
    else if (filename.endsWith(".ts")) loader = "ts";
    const result = await esbuild.transform(code, {
      loader,
      format: "esm",
      // Keep as ES modules for browser
      target: "esnext",
      jsx: "automatic",
      // Use React 17+ automatic runtime
      jsxDev: loader === "jsx" || loader === "tsx",
      jsxImportSource: "react",
      sourcemap: "inline",
      sourcefile: filename
    });
    let transformed = result.code;
    transformed = this.redirectNpmImports(transformed);
    if (this.options.aliases && Object.keys(this.options.aliases).length > 0) {
      transformed = this.rewriteAliases(transformed, filename);
    }
    if (/\.(jsx|tsx)$/.test(filename)) {
      return this.addReactRefresh(transformed, filename);
    }
    return transformed;
  }
  addReactRefresh(code, filename) {
    return addReactRefresh(code, filename);
  }
  /**
   * Rewrite path alias prefixes in import/export specifiers to relative paths
   */
  rewriteAliases(code, filename) {
    const aliases = this.options.aliases;
    if (!aliases) return code;
    return code.replace(
      /((?:import|export)\s+.*?\s+from\s+['"])([^'"]+)(['"])|(\bimport\s*\(\s*['"])([^'"]+)(['"]\s*\))/g,
      (match, pre1, spec1, post1, pre2, spec2, post2) => {
        const specifier = spec1 || spec2;
        const pre = pre1 || pre2;
        const post = post1 || post2;
        for (const [alias, target] of Object.entries(aliases)) {
          if (specifier.startsWith(alias)) {
            let resolved = specifier.replace(alias, target);
            const fromDir = filename.replace(/\/[^/]+$/, "");
            const rootPrefix = this.root === "/" ? "" : this.root;
            const fromDirRel = rootPrefix && fromDir.startsWith(rootPrefix) ? fromDir.slice(rootPrefix.length) : fromDir;
            const resolvedFsPath = this.root + "/" + resolved;
            const indexExts = [".tsx", ".ts", ".jsx", ".js", ".mjs"];
            for (const ext of indexExts) {
              if (this.exists(resolvedFsPath + "/index" + ext)) {
                resolved = resolved + "/index" + ext;
                break;
              }
            }
            const targetFull = "/" + resolved;
            const fromParts = fromDirRel.split("/").filter(Boolean);
            const toParts = targetFull.split("/").filter(Boolean);
            let common = 0;
            while (common < fromParts.length && common < toParts.length && fromParts[common] === toParts[common]) {
              common++;
            }
            const ups = fromParts.length - common;
            const remainder = toParts.slice(common);
            let rel = ups > 0 ? "../".repeat(ups) + remainder.join("/") : "./" + remainder.join("/");
            return pre + rel + post;
          }
        }
        return match;
      }
    );
  }
  /**
   * Schedule route tree regeneration (debounced)
   */
  scheduleRouteTreeRegen() {
    if (!this.options.tanstackRouter) return;
    if (this.pendingRouteTreeRegen) {
      clearTimeout(this.pendingRouteTreeRegen);
    }
    this.pendingRouteTreeRegen = setTimeout(() => {
      this.pendingRouteTreeRegen = null;
      try {
        const changed = generateAndWriteRouteTree(this.vfs, this.root);
        if (changed) {
          almostnodeDebugLog("vite", "[ViteDevServer] Regenerated routeTree.gen.ts");
        }
      } catch (error) {
        almostnodeDebugWarn("vite", "[ViteDevServer] Failed to regenerate route tree:", error);
      }
    }, 100);
  }
  getDependencies() {
    if (this._dependencies) return this._dependencies;
    let deps = {};
    try {
      const pkgPath = `${this.root}/package.json`;
      if (this.vfs.existsSync(pkgPath)) {
        const pkg = JSON.parse(this.vfs.readFileSync(pkgPath, "utf-8"));
        deps = { ...pkg.dependencies, ...pkg.devDependencies };
      }
    } catch {
    }
    this._dependencies = deps;
    return deps;
  }
  getInstalledPackages() {
    if (this._installedPackages) return this._installedPackages;
    const pkgs = /* @__PURE__ */ new Set();
    const nmDir = this.root === "/" ? "/node_modules" : `${this.root}/node_modules`;
    try {
      if (!this.vfs.existsSync(nmDir)) {
        this._installedPackages = pkgs;
        return pkgs;
      }
      const entries = this.vfs.readdirSync(nmDir);
      for (const entry of entries) {
        if (entry.startsWith(".")) continue;
        if (entry.startsWith("@")) {
          const scopeDir = nmDir + "/" + entry;
          try {
            const scopeEntries = this.vfs.readdirSync(scopeDir);
            for (const sub of scopeEntries) {
              pkgs.add(entry + "/" + sub);
            }
          } catch {
          }
        } else {
          pkgs.add(entry);
        }
      }
    } catch {
    }
    this._installedPackages = pkgs;
    return pkgs;
  }
  redirectNpmImports(code) {
    const npmUrlPrefix = `${this.options.deploymentBasePath || ""}/__virtual__/${this.port}`;
    return redirectNpmImports(code, _ViteDevServer.IMPORT_MAP_PACKAGES, this.getDependencies(), void 0, this.getInstalledPackages(), npmUrlPrefix);
  }
  async serveNpmModule(pathname) {
    const specifier = pathname.slice("/_npm/".length);
    if (!specifier) {
      return this.notFound(pathname);
    }
    try {
      let code = await bundleNpmModuleForBrowser(specifier, [this.root, "/"], this.vfs);
      code = this.redirectNpmImports(code);
      return {
        statusCode: 200,
        statusMessage: "OK",
        headers: {
          "Content-Type": "application/javascript; charset=utf-8",
          "Cache-Control": "public, max-age=31536000, immutable"
        },
        body: BufferPolyfill.from(code)
      };
    } catch (error) {
      const msg = error instanceof Error ? error.message : String(error);
      almostnodeDebugError("vite", `[ViteDevServer] Failed to bundle npm module '${specifier}':`, msg);
      const errorJs = `console.error(${JSON.stringify(`[almostnode] Failed to bundle '${specifier}': ${msg}`)});
throw new Error(${JSON.stringify(`Failed to bundle '${specifier}': ${msg}`)});
export default undefined;
`;
      return {
        statusCode: 200,
        statusMessage: "OK",
        headers: { "Content-Type": "application/javascript; charset=utf-8" },
        body: BufferPolyfill.from(errorJs)
      };
    }
  }
  /**
   * Serve CSS file as a JavaScript module that injects styles
   * This is needed because ES module imports of CSS files need to return JS
   */
  serveCssAsModule(filePath) {
    try {
      const css = this.vfs.readFileSync(filePath, "utf8");
      const js = `
// CSS Module: ${filePath}
const css = ${JSON.stringify(css)};
const style = document.createElement('style');
style.setAttribute('data-vite-dev-id', ${JSON.stringify(filePath)});
style.textContent = css;
document.head.appendChild(style);
export default css;
`;
      const buffer = BufferPolyfill.from(js);
      return {
        statusCode: 200,
        statusMessage: "OK",
        headers: {
          "Content-Type": "application/javascript; charset=utf-8",
          "Content-Length": String(buffer.length),
          "Cache-Control": "no-cache"
        },
        body: buffer
      };
    } catch (error) {
      return this.serverError(error);
    }
  }
  /**
   * Serve HTML file with HMR client script injected
   *
   * IMPORTANT: React Refresh preamble MUST be injected before any module scripts.
   * The preamble uses top-level await to block until React Refresh is loaded
   * and injectIntoGlobalHook is called. This ensures React Refresh hooks into
   * React BEFORE React is imported by any module.
   */
  async serveHtmlWithHMR(filePath) {
    try {
      let content = this.vfs.readFileSync(filePath, "utf8");
      const tailwindInjection = await this.getTailwindInjection(content);
      content = this.rewriteHtmlModuleScriptSources(content);
      if (this.options.injectHead) {
        if (content.includes("<head>")) {
          content = content.replace("<head>", `<head>
${this.options.injectHead}`);
        } else if (content.includes("<html")) {
          content = content.replace(/<html[^>]*>/, `$&${this.options.injectHead}`);
        } else {
          content = this.options.injectHead + content;
        }
      }
      if (!content.includes('"importmap"')) {
        const importMap = `<script type="importmap">
{
  "imports": {
    "react": "${REACT_CDN}?dev",
    "react/": "${REACT_CDN}&dev/",
    "react-dom": "${REACT_DOM_CDN}?dev",
    "react-dom/": "${REACT_DOM_CDN}&dev/"
  }
}
<\/script>`;
        if (content.includes("</head>")) {
          content = content.replace("</head>", `${importMap}
</head>`);
        } else if (content.includes("<head>")) {
          content = content.replace("<head>", `<head>
${importMap}`);
        }
      }
      const importMapRegex = /<script\b[^>]*\btype\s*=\s*["']importmap["'][^>]*>[\s\S]*?<\/script>/gi;
      let lastImportMapEnd = -1;
      let match;
      while ((match = importMapRegex.exec(content)) !== null) {
        lastImportMapEnd = match.index + match[0].length;
      }
      if (tailwindInjection) {
        if (lastImportMapEnd !== -1) {
          content = content.slice(0, lastImportMapEnd) + tailwindInjection + content.slice(lastImportMapEnd);
        } else if (content.includes("<head>")) {
          content = content.replace("<head>", `<head>
${tailwindInjection}`);
        } else if (content.includes("<html")) {
          content = content.replace(/<html[^>]*>/, `$&${tailwindInjection}`);
        } else {
          content = tailwindInjection + content;
        }
      }
      if (lastImportMapEnd !== -1) {
        content = content.slice(0, lastImportMapEnd) + REACT_REFRESH_PREAMBLE + content.slice(lastImportMapEnd);
      } else if (content.includes("<head>")) {
        content = content.replace("<head>", `<head>${REACT_REFRESH_PREAMBLE}`);
      } else if (content.includes("<html")) {
        content = content.replace(/<html[^>]*>/, `$&${REACT_REFRESH_PREAMBLE}`);
      } else {
        content = REACT_REFRESH_PREAMBLE + content;
      }
      if (content.includes("</head>")) {
        content = content.replace("</head>", `${HMR_CLIENT_SCRIPT}</head>`);
      } else if (content.includes("</body>")) {
        content = content.replace("</body>", `${HMR_CLIENT_SCRIPT}</body>`);
      } else {
        content += HMR_CLIENT_SCRIPT;
      }
      if (content.includes("</body>")) {
        content = content.replace("</body>", `${REPLAY_CAPTURE_SCRIPT}</body>`);
      } else {
        content += REPLAY_CAPTURE_SCRIPT;
      }
      const buffer = BufferPolyfill.from(content);
      return {
        statusCode: 200,
        statusMessage: "OK",
        headers: {
          "Content-Type": "text/html; charset=utf-8",
          "Content-Length": String(buffer.length),
          "Cache-Control": "no-cache"
        },
        body: buffer
      };
    } catch (error) {
      return this.serverError(error);
    }
  }
  rewriteHtmlModuleScriptSources(html) {
    const virtualBase = `${this.options.deploymentBasePath || ""}/__virtual__/${this.port}`;
    return html.replace(
      /<script\b[^>]*\bsrc=(["'])(\/(?!\/)[^"']*)\1[^>]*>/gi,
      (tag, quote, path) => {
        if (!/\btype\s*=\s*["']module["']/i.test(tag)) {
          return tag;
        }
        if (path === virtualBase || path.startsWith(`${virtualBase}/`)) {
          return tag;
        }
        return tag.replace(`${quote}${path}${quote}`, `${quote}${virtualBase}${path}${quote}`);
      }
    );
  }
  async loadTailwindConfigIfNeeded() {
    if (this.tailwindConfigLoaded) {
      return this.tailwindConfigScript;
    }
    try {
      const result = await loadTailwindConfig(this.vfs, this.root);
      if (result.success) {
        this.tailwindConfigScript = result.configScript;
      } else if (result.error) {
        almostnodeDebugWarn("vite", "[ViteDevServer] Tailwind config warning:", result.error);
        this.tailwindConfigScript = "";
      }
    } catch (error) {
      almostnodeDebugWarn("vite", "[ViteDevServer] Failed to load tailwind.config:", error);
      this.tailwindConfigScript = "";
    }
    this.tailwindConfigLoaded = true;
    return this.tailwindConfigScript;
  }
  hasTailwindProjectMarker() {
    const root = this.root === "/" ? "" : this.root;
    return this.vfs.existsSync(`${root}/components.json`) || this.vfs.existsSync(`${root}/tailwind.config.ts`) || this.vfs.existsSync(`${root}/tailwind.config.js`) || this.vfs.existsSync(`${root}/tailwind.config.mjs`);
  }
  async getTailwindInjection(html) {
    if (html.includes("cdn.tailwindcss.com")) {
      return "";
    }
    if (!this.hasTailwindProjectMarker()) {
      return "";
    }
    const configScript = await this.loadTailwindConfigIfNeeded();
    return `<script src="${TAILWIND_CDN_URL}"><\/script>
${configScript}`;
  }
};
/**
 * Packages handled by the import map injected into index.html.
 * These must NOT be rewritten by redirectNpmImports — the import map
 * already maps the bare specifiers to the correct CDN URLs.
 */
__publicField(_ViteDevServer, "IMPORT_MAP_PACKAGES", [
  "react",
  "react-dom"
]);
let ViteDevServer = _ViteDevServer;
export {
  ViteDevServer,
  ViteDevServer as default
};
//# sourceMappingURL=vite-dev-server-CQ-84Km_.js.map
