// @bun
var{defineProperty:G,getOwnPropertyNames:Q,getOwnPropertyDescriptor:T}=Object,U=Object.prototype.hasOwnProperty;function V(j){return this[j]}var $=(j)=>{var k=(J??=new WeakMap).get(j),u;if(k)return k;if(k=G({},"__esModule",{value:!0}),j&&typeof j==="object"||typeof j==="function"){for(var z of Q(j))if(!U.call(k,z))G(k,z,{get:V.bind(j,z),enumerable:!(u=T(j,z))||u.enumerable})}return J.set(j,k),k},J;var W=(j)=>j;function X(j,k){this[j]=W.bind(null,k)}var M=(j,k)=>{for(var u in k)G(j,u,{get:k[u],enumerable:!0,configurable:!0,set:X.bind(k,u)})};var O=(j,k)=>()=>(j&&(k=j(j=0)),k);var q=import.meta.require;class K{clients=new Set;server=null;options;constructor(j={}){this.options={wsPort:j.wsPort??3001,showOverlay:j.showOverlay??!0,reconnectInterval:j.reconnectInterval??1000,maxReconnectAttempts:j.maxReconnectAttempts??10,verbose:j.verbose??!1}}start(j){let k=j??this.options.wsPort,u=20;for(let z=0;z<u;z++)try{if(this.server=Bun.serve({port:k,fetch(B,C){if(C.upgrade(B,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(B)=>{if(this.clients.add(B),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);B.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(B)=>{if(this.clients.delete(B),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(B,C)=>{let F=typeof C==="string"?C:C.toString();if(F==="ping")return;try{let D=JSON.parse(F);if(D.type==="console"&&Array.isArray(D.args)){let L=D.args.join(" "),N={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[D.level]??"\x1B[36m";console.log(`${N}[browser]${D.level!=="log"?` ${D.level}`:""}\x1B[0m ${L}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${k}`);return k}catch(B){if(B?.code==="EADDRINUSE"){k++;continue}throw B}throw Error(`Could not find an available port after ${u} attempts starting from ${j??this.options.wsPort}`)}stop(){for(let j of this.clients)try{j.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(j){let k=JSON.stringify(j),u=0;for(let z of this.clients)try{if(z.readyState===1)z.send(k),u++}catch{this.clients.delete(z)}if(this.options.verbose&&u>0)console.log(`[HMR] Broadcast ${j.type} to ${u} client(s)`)}reload(j){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${j||"all"}`);this.broadcast({type:"reload",path:j,timestamp:Date.now()})}updateCss(j,k){this.broadcast({type:"css-update",path:j,content:k,timestamp:Date.now()})}error(j){this.broadcast({type:"error",content:j,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function Z(j,k={}){let{showOverlay:u=!0,reconnectInterval:z=1000,maxReconnectAttempts:B=10}=k;return`
<script>
(function() {
  // stx Hot Reload Client
  var wsUrl = 'ws://' + window.location.hostname + ':${j}';
  var reconnectAttempts = 0;
  var maxAttempts = ${B};
  var reconnectInterval = ${z};
  var socket = null;
  var overlay = null;
  var wasConnected = false; // Track if we ever connected successfully

  ${u?`
  // Create connection status overlay
  function createOverlay() {
    overlay = document.createElement('div');
    overlay.id = 'stx-hmr-overlay';
    overlay.style.cssText = 'position:fixed;top:0;left:0;right:0;padding:8px 16px;background:#f59e0b;color:#000;font-family:system-ui,sans-serif;font-size:14px;text-align:center;z-index:999999;display:none;';
    document.body.appendChild(overlay);
  }

  function showOverlay(message, isError) {
    // Only show overlay if we were previously connected (don't show during initial connection)
    if (!wasConnected && !isError) return;
    if (!overlay) createOverlay();
    overlay.textContent = message;
    overlay.style.background = isError ? '#ef4444' : '#f59e0b';
    overlay.style.color = isError ? '#fff' : '#000';
    overlay.style.display = 'block';
  }

  function hideOverlay() {
    if (overlay) overlay.style.display = 'none';
  }
  `:`
  function showOverlay() {}
  function hideOverlay() {}
  `}

  function connect() {
    try {
      socket = new WebSocket(wsUrl);
    }
catch (e) {
      // Silent fail for initial connection attempts
      if (wasConnected) {
        scheduleReconnect();
      }
      return;
    }

    socket.onopen = function() {
      // connected silently
      wasConnected = true;
      reconnectAttempts = 0;
      hideOverlay();
    };

    socket.onmessage = function(event) {
      try {
        var msg = JSON.parse(event.data);

        switch (msg.type) {
          case 'reload':
            console.log('[stx] Reloading...', msg.path || '');
            // Use SPA router for progressive update instead of full page reload.
            // Falls back to hard reload only when the router isn't available.
            if (typeof window.navigate === 'function') {
              window.navigate(window.location.pathname + window.location.search, false, true);
            } else {
              window.location.reload();
            }
            break;

          case 'css-update':
            console.log('[stx] CSS update:', msg.path);
            updateCss(msg.path, msg.content);
            break;

          case 'error':
            console.error('[stx] Error:', msg.content);
            showOverlay('Build Error: ' + msg.content, true);
            break;

          case 'connected':
            break;
        }
      }
catch (e) {
        console.error('[stx] Invalid message:', e);
      }
    };

    socket.onclose = function() {
      socket = null;
      // Only log and show overlay if we were previously connected
      if (wasConnected) {
        console.log('[stx] Connection closed, reconnecting...');
        scheduleReconnect();
      }
else {
        // Silently retry initial connection
        setTimeout(connect, reconnectInterval);
      }
    };

    socket.onerror = function() {
      // Errors are handled in onclose
    };
  }

  function scheduleReconnect() {
    if (reconnectAttempts < maxAttempts) {
      reconnectAttempts++;
      showOverlay('Reconnecting... (' + reconnectAttempts + '/' + maxAttempts + ')');
      setTimeout(connect, reconnectInterval);
    }
else {
      showOverlay('Connection lost. Refresh to reconnect.', true);
    }
  }

  // CSS hot update without full reload
  function updateCss(path, content) {
    // Try to find and update existing stylesheet
    var links = document.querySelectorAll('link[rel="stylesheet"]');
    for (var i = 0; i < links.length; i++) {
      var href = links[i].getAttribute('href');
      if (href && href.indexOf(path) !== -1) {
        // Add cache-busting query param
        var newHref = href.split('?')[0] + '?t=' + Date.now();
        links[i].setAttribute('href', newHref);
        return;
      }
    }

    // If content provided, inject as style tag
    if (content) {
      var style = document.createElement('style');
      style.setAttribute('data-stx-hmr', path);
      style.textContent = content;

      // Remove old injected style
      var old = document.querySelector('style[data-stx-hmr="' + path + '"]');
      if (old) old.remove();

      document.head.appendChild(style);
    }
  }

  // Start connection when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', connect);
  }
else {
    connect();
  }

  // Forward browser console to the dev server terminal
  var _origLog = console.log;
  var _origError = console.error;
  var _origWarn = console.warn;
  var _origInfo = console.info;

  function _fwd(level, args) {
    if (socket && socket.readyState === 1) {
      try {
        socket.send(JSON.stringify({
          type: 'console',
          level: level,
          args: Array.prototype.slice.call(args).map(function(a) {
            if (a === null) return 'null';
            if (a === undefined) return 'undefined';
            if (typeof a === 'object') { try { return JSON.stringify(a); } catch(e) { return String(a); } }
            return String(a);
          })
        }));
      } catch(e) {}
    }
  }

  console.log = function() { _origLog.apply(console, arguments); _fwd('log', arguments); };
  console.error = function() { _origError.apply(console, arguments); _fwd('error', arguments); };
  console.warn = function() { _origWarn.apply(console, arguments); _fwd('warn', arguments); };
  console.info = function() { _origInfo.apply(console, arguments); _fwd('info', arguments); };

  // Expose for debugging
  window.__stxHmr = {
    reconnect: connect,
    status: function() { return socket ? socket.readyState : -1; }
  };
})();
</script>
`}function y(j,k,u={}){let z=Z(k,u),B=j.lastIndexOf("</body>");if(B!==-1)return j.slice(0,B)+z+j.slice(B);if(j.includes("</html>"))return j.replace("</html>",`${z}</html>`);return j+z}function I(j){let k=j.toLowerCase();return k.endsWith(".css")||k.endsWith(".scss")||k.endsWith(".sass")||k.endsWith(".less")}function R(j){let k=j.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((z)=>k.endsWith(z))}function b(j){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((u)=>u.test(j))}function H(j){if(!E)E=new K(j);return E}function S(){if(E)E.stop(),E=null}var E=null;export{S as stopHmrServer,R as shouldReloadOnChange,b as shouldIgnoreFile,I as isCssOnlyChange,y as injectHotReload,H as getHmrServer,Z as generateHotReloadScript,K as HotReloadServer};
