// @bun
var{defineProperty:G,getOwnPropertyNames:P,getOwnPropertyDescriptor:Q}=Object,T=Object.prototype.hasOwnProperty;function W(f){return this[f]}var S=(f)=>{var j=(J??=new WeakMap).get(f),q;if(j)return j;if(j=G({},"__esModule",{value:!0}),f&&typeof f==="object"||typeof f==="function"){for(var z of P(f))if(!T.call(j,z))G(j,z,{get:W.bind(f,z),enumerable:!(q=Q(f,z))||q.enumerable})}return J.set(f,j),j},J;var X=(f)=>f;function Y(f,j){this[f]=X.bind(null,j)}var Z=(f,j)=>{for(var q in j)G(f,q,{get:j[q],enumerable:!0,configurable:!0,set:Y.bind(j,q)})};var g=(f,j)=>()=>(f&&(j=f(f=0)),j);var x=import.meta.require;var N={};Z(N,{shouldCacheComponent:()=>y,processKeepAliveDirectives:()=>w,onDeactivated:()=>K,onActivated:()=>b,generateKeepAliveRuntime:()=>R,generateKeepAliveCSS:()=>H,createKeepAliveCache:()=>U});function L(){return`keep-alive-${++$}-${Date.now().toString(36)}`}function w(f,j={},q){let z=/@keepAlive(?:\s*\(([^)]*)\))?\s*([\s\S]*?)@endkeepAlive/gi;return f.replace(z,(E,B,D)=>{let F=L(),M=C(B||"");return O(F,D.trim(),M)})}function C(f){let j={max:10},q=/(\w+)\s*:\s*(?:'([^']*)'|"([^"]*)"|(\d+)|(\w+))/g,z;while((z=q.exec(f))!==null){let E=z[1],B=z[2]||z[3],D=z[4];switch(E){case"max":j.max=D?parseInt(D,10):10;break;case"include":j.include=B;break;case"exclude":j.exclude=B;break;case"id":j.id=B;break}}return j}function O(f,j,q){let{max:z,include:E,exclude:B}=q,D=q.id||f;return`
<div class="stx-keep-alive" data-keep-alive-id="${f}" data-custom-id="${D}">
  <div class="stx-keep-alive-content" data-keep-alive-content="${f}">
    ${j}
  </div>
  <div class="stx-keep-alive-cache" data-keep-alive-cache="${f}" style="display: none;">
  </div>
</div>
<script>
(function() {
  const keepAliveId = '${f}';
  const customId = '${D}';
  const maxCache = ${z||10};
  const includeFilter = ${E?JSON.stringify(E.split(",").map((F)=>F.trim())):"null"};
  const excludeFilter = ${B?JSON.stringify(B.split(",").map((F)=>F.trim())):"null"};

  const container = document.querySelector('[data-keep-alive-id="' + keepAliveId + '"]');
  const contentEl = document.querySelector('[data-keep-alive-content="' + keepAliveId + '"]');
  const cacheEl = document.querySelector('[data-keep-alive-cache="' + keepAliveId + '"]');

  if (!container || !contentEl || !cacheEl) return;

  // LRU Cache
  const cache = new Map();
  const cacheOrder = [];

  // Check if component should be cached
  function shouldCache(componentName) {
    if (excludeFilter && excludeFilter.includes(componentName)) {
      return false;
    }
    if (includeFilter && !includeFilter.includes(componentName)) {
      return false;
    }
    return true;
  }

  // Get component key from element
  function getComponentKey(element) {
    // Try various ways to identify the component
    return element.getAttribute('data-component') ||
           element.getAttribute('data-key') ||
           element.id ||
           element.className.split(' ')[0] ||
           element.tagName.toLowerCase();
  }

  // Save scroll positions
  function saveScrollPositions(element) {
    const positions = new Map();
    // eslint-disable-next-line pickier/no-unused-vars
    element.querySelectorAll('[data-keep-scroll]').forEach(function(el) {
      const key = el.getAttribute('data-keep-scroll') || el.id || 'default';
      positions.set(key, { top: el.scrollTop, left: el.scrollLeft });
    });
    // Also save the element's own scroll if scrollable
    if (element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth) {
      positions.set('__self__', { top: element.scrollTop, left: element.scrollLeft });
    }
    return positions;
  }

  // Restore scroll positions
  function restoreScrollPositions(element, positions) {
    if (!positions) return;

    positions.forEach(function(pos, key) {
      if (key === '__self__') {
        element.scrollTop = pos.top;
        element.scrollLeft = pos.left;
      }
else {
        const el = element.querySelector('[data-keep-scroll="' + key + '"]') ||
                   document.getElementById(key);
        if (el) {
          el.scrollTop = pos.top;
          el.scrollLeft = pos.left;
        }
      }
    });
  }

  // Save component state (form values, etc.)
  function saveComponentState(element) {
    const state = {};

    // Save form inputs
    // eslint-disable-next-line pickier/no-unused-vars
    element.querySelectorAll('input, textarea, select').forEach(function(input, index) {
      const key = input.name || input.id || 'input_' + index;
      if (input.type === 'checkbox' || input.type === 'radio') {
        state[key] = input.checked;
      }
else {
        state[key] = input.value;
      }
    });

    // Save data attributes marked for keeping
    // eslint-disable-next-line pickier/no-unused-vars
    element.querySelectorAll('[data-keep-state]').forEach(function(el) {
      const key = el.getAttribute('data-keep-state');
      const value = el.getAttribute('data-state-value') || el.textContent;
      state['__data__' + key] = value;
    });

    return state;
  }

  // Restore component state
  function restoreComponentState(element, state) {
    if (!state) return;

    // Restore form inputs
    // eslint-disable-next-line pickier/no-unused-vars
    element.querySelectorAll('input, textarea, select').forEach(function(input, index) {
      const key = input.name || input.id || 'input_' + index;
      if (state[key] !== undefined) {
        if (input.type === 'checkbox' || input.type === 'radio') {
          input.checked = state[key];
        }
else {
          input.value = state[key];
        }
      }
    });
  }

  // Cache a component
  function cacheComponent(key, element) {
    if (!shouldCache(key)) return;

    // Remove from cache order if exists (for LRU)
    const existingIndex = cacheOrder.indexOf(key);
    if (existingIndex > -1) {
      cacheOrder.splice(existingIndex, 1);
    }

    // Evict oldest if at max capacity
    while (cacheOrder.length >= maxCache) {
      const oldestKey = cacheOrder.shift();
      const oldCached = cache.get(oldestKey);
      if (oldCached && oldCached.element) {
        oldCached.element.remove();
      }
      cache.delete(oldestKey);
    }

    // Clone and cache
    const clone = element.cloneNode(true);
    clone.style.display = 'none';
    clone.setAttribute('data-cached-key', key);

    const cached = {
      key: key,
      element: clone,
      state: saveComponentState(element),
      scrollPositions: saveScrollPositions(element),
      cachedAt: Date.now()
    };

    cache.set(key, cached);
    cacheOrder.push(key);
    cacheEl.appendChild(clone);

    // Dispatch deactivated event
    element.dispatchEvent(new CustomEvent('stx:deactivated', {
      detail: { key: key, keepAliveId: keepAliveId },
      bubbles: true
    }));
  }

  // Restore a component from cache
  function restoreComponent(key) {
    const cached = cache.get(key);
    if (!cached) return null;

    // Move to end of cache order (most recently used)
    const index = cacheOrder.indexOf(key);
    if (index > -1) {
      cacheOrder.splice(index, 1);
      cacheOrder.push(key);
    }

    // Clone the cached element
    const restored = cached.element.cloneNode(true);
    restored.style.display = '';
    restored.removeAttribute('data-cached-key');

    // Restore state after a tick (to let DOM settle)
    setTimeout(function() {
      restoreComponentState(restored, cached.state);
      restoreScrollPositions(restored, cached.scrollPositions);

      // Dispatch activated event
      restored.dispatchEvent(new CustomEvent('stx:activated', {
        detail: { key: key, keepAliveId: keepAliveId, cachedAt: cached.cachedAt },
        bubbles: true
      }));
    }, 0);

    return restored;
  }

  // Check if component is cached
  function isCached(key) {
    return cache.has(key);
  }

  // Clear cache
  function clearCache(key) {
    if (key) {
      const cached = cache.get(key);
      if (cached && cached.element) {
        cached.element.remove();
      }
      cache.delete(key);
      const index = cacheOrder.indexOf(key);
      if (index > -1) {
        cacheOrder.splice(index, 1);
      }
    }
else {
      cache.forEach(function(cached) {
        if (cached.element) {
          cached.element.remove();
        }
      });
      cache.clear();
      cacheOrder.length = 0;
    }
  }

  // Expose API
  window.STX = window.STX || {};
  window.STX.keepAlive = window.STX.keepAlive || { instances: {} };
  window.STX.keepAlive.instances[keepAliveId] = {
    id: keepAliveId,
    customId: customId,
    cache: cacheComponent,
    restore: restoreComponent,
    isCached: isCached,
    clear: clearCache,
    getCacheKeys: function() { return Array.from(cache.keys()); },
    getCacheSize: function() { return cache.size; }
  };

  // Observe for component changes
  const observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      // Handle removed nodes (cache them)
      mutation.removedNodes.forEach(function(node) {
        if (node.nodeType === Node.ELEMENT_NODE && node.hasAttribute && !node.hasAttribute('data-cached-key')) {
          const key = getComponentKey(node);
          if (key && shouldCache(key)) {
            // Check if this removal is intentional (not just DOM restructuring)
            if (!contentEl.contains(node)) {
              cacheComponent(key, node);
            }
          }
        }
      });

      // Handle added nodes (check if we should restore from cache)
      mutation.addedNodes.forEach(function(node) {
        if (node.nodeType === Node.ELEMENT_NODE && node.hasAttribute) {
          const key = getComponentKey(node);
          if (key && isCached(key)) {
            const restored = restoreComponent(key);
            if (restored) {
              node.replaceWith(restored);
            }
          }
        }
      });
    });
  });

  observer.observe(contentEl, { childList: true, subtree: true });

  // Cleanup on removal
  container.addEventListener('stx:destroy', function() {
    observer.disconnect();
    clearCache();
  });
})();
</script>
`}function U(f={}){return{id:f.id||L(),cache:new Map,max:f.max||10,include:f.include?f.include.split(",").map((q)=>q.trim()):null,exclude:f.exclude?f.exclude.split(",").map((q)=>q.trim()):null}}function y(f,j){if(j.exclude&&j.exclude.includes(f))return!1;if(j.include&&!j.include.includes(f))return!1;return!0}function H(){return`
/* STX Keep-Alive Styles */
.stx-keep-alive {
  position: relative;
}

.stx-keep-alive-cache {
  display: none !important;
  visibility: hidden;
  position: absolute;
  pointer-events: none;
}

/* Activation transition */
.stx-keep-alive-content > * {
  transition: opacity 0.15s ease;
}

.stx-keep-alive-content > [data-activating] {
  opacity: 0;
}

.stx-keep-alive-content > [data-activated] {
  opacity: 1;
}
`}function R(){return`
// STX Keep-Alive Runtime
(function() {
  if (typeof window === 'undefined') return;

  window.STX = window.STX || {};
  window.STX.keepAlive = window.STX.keepAlive || { instances: {} };

  // Global keep-alive utilities
  window.STX.keepAlive.clearAll = function() {
    Object.values(window.STX.keepAlive.instances).forEach(function(instance) {
      instance.clear();
    });
  };

  window.STX.keepAlive.getTotalCached = function() {
    return Object.values(window.STX.keepAlive.instances).reduce(function(total, instance) {
      return total + instance.getCacheSize();
    }, 0);
  };

  // Lifecycle hooks for keep-alive
  window.STX.onActivated = function(callback) {
    document.addEventListener('stx:activated', function(e) {
      callback(e.detail);
    });
  };

  window.STX.onDeactivated = function(callback) {
    document.addEventListener('stx:deactivated', function(e) {
      callback(e.detail);
    });
  };

  console.log('[stx] Keep-alive runtime initialized');
})();
`}function b(f){if(typeof document<"u")document.addEventListener("stx:activated",(j)=>{f(j.detail)})}function K(f){if(typeof document<"u")document.addEventListener("stx:deactivated",(j)=>{f(j.detail)})}var $=0;export{y as shouldCacheComponent,w as processKeepAliveDirectives,K as onDeactivated,b as onActivated,R as generateKeepAliveRuntime,H as generateKeepAliveCSS,U as createKeepAliveCache};
