// @bun
var __create = Object.create;
var __getProtoOf = Object.getPrototypeOf;
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __hasOwnProp = Object.prototype.hasOwnProperty;
function __accessProp(key) {
  return this[key];
}
var __toESMCache_node;
var __toESMCache_esm;
var __toESM = (mod, isNodeMode, target) => {
  var canCache = mod != null && typeof mod === "object";
  if (canCache) {
    var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
    var cached = cache.get(mod);
    if (cached)
      return cached;
  }
  target = mod != null ? __create(__getProtoOf(mod)) : {};
  const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
  for (let key of __getOwnPropNames(mod))
    if (!__hasOwnProp.call(to, key))
      __defProp(to, key, {
        get: __accessProp.bind(mod, key),
        enumerable: true
      });
  if (canCache)
    cache.set(mod, to);
  return to;
};
var __toCommonJS = (from) => {
  var entry = (__moduleCache ??= new WeakMap).get(from), desc;
  if (entry)
    return entry;
  entry = __defProp({}, "__esModule", { value: true });
  if (from && typeof from === "object" || typeof from === "function") {
    for (var key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(entry, key))
        __defProp(entry, key, {
          get: __accessProp.bind(from, key),
          enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
        });
  }
  __moduleCache.set(from, entry);
  return entry;
};
var __moduleCache;
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __returnValue = (v) => v;
function __exportSetter(name, newValue) {
  this[name] = __returnValue.bind(null, newValue);
}
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, {
      get: all[name],
      enumerable: true,
      configurable: true,
      set: __exportSetter.bind(all, name)
    });
};
var __legacyDecorateClassTS = function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1;i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __legacyMetadataTS = (k, v) => {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
    return Reflect.metadata(k, v);
};
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = import.meta.require;

// src/utils/escapeScriptContent.ts
var ESCAPE_LOOKUP, ESCAPE_REGEX, escapeScriptContent = (content) => content.replace(ESCAPE_REGEX, (char) => {
  const escaped = ESCAPE_LOOKUP[char];
  return escaped !== undefined ? escaped : char;
});
var init_escapeScriptContent = __esm(() => {
  ESCAPE_LOOKUP = {
    "\u2028": "\\u2028",
    "\u2029": "\\u2029",
    "&": "\\u0026",
    "<": "\\u003C"
  };
  ESCAPE_REGEX = /[&<\u2028\u2029]/g;
});

// src/core/islandPageContext.ts
var BOOTSTRAP_MANIFEST_KEY = "BootstrapClient", ISLAND_MARKER = 'data-island="true"', MANIFEST_MARKER = "__ABSOLUTE_MANIFEST__", ISLAND_STATE_MARKER = "__ABS_ISLAND_STATE__", CLOSING_HEAD_TAG2 = "</head>", buildIslandsHeadMarkup = (manifest) => {
  const manifestScript = `<script>window.__ABSOLUTE_MANIFEST__ = ${JSON.stringify(manifest)}</script>`;
  const islandStateScript = `<script>window.__ABS_ISLAND_STATE__ = ${JSON.stringify(globalThis.__ABS_ISLAND_STATE__ ?? {})}</script>`;
  const bootstrapPath = manifest[BOOTSTRAP_MANIFEST_KEY];
  const bootstrapScript = bootstrapPath ? `<script type="module" src="${bootstrapPath}"></script>` : "";
  return `${manifestScript}${islandStateScript}${bootstrapScript}`;
}, injectHeadMarkup = (html, markup) => {
  const closingHeadIndex = html.indexOf("</head>");
  if (closingHeadIndex >= 0) {
    return `${html.slice(0, closingHeadIndex)}${markup}${html.slice(closingHeadIndex)}`;
  }
  const openingBodyIndex = html.indexOf("<body");
  if (openingBodyIndex >= 0) {
    const bodyStart = html.indexOf(">", openingBodyIndex);
    if (bodyStart >= 0) {
      return `${html.slice(0, openingBodyIndex)}<head>${markup}</head>${html.slice(openingBodyIndex)}`;
    }
  }
  return `<!DOCTYPE html><html><head>${markup}</head><body>${html}</body></html>`;
}, streamChunkToString2 = (value, decoder) => typeof value === "string" ? value : decoder.decode(value, { stream: true }), pipeStreamWithHeadInjection = (stream, markup) => {
  const encoder = new TextEncoder;
  const decoder = new TextDecoder;
  const lookbehind = CLOSING_HEAD_TAG2.length - 1;
  return new ReadableStream({
    async start(controller) {
      const reader = stream.getReader();
      let injected = false;
      let pending = "";
      try {
        for (;; ) {
          const { done, value } = await reader.read();
          if (done)
            break;
          if (!value)
            continue;
          pending += streamChunkToString2(value, decoder);
          if (injected) {
            controller.enqueue(encoder.encode(pending));
            pending = "";
            continue;
          }
          const headIndex = pending.indexOf(CLOSING_HEAD_TAG2);
          if (headIndex >= 0) {
            const next = `${pending.slice(0, headIndex)}${markup}${pending.slice(headIndex)}`;
            controller.enqueue(encoder.encode(next));
            pending = "";
            injected = true;
            continue;
          }
          if (pending.length > lookbehind) {
            const safeText = pending.slice(0, pending.length - lookbehind);
            controller.enqueue(encoder.encode(safeText));
            pending = pending.slice(-lookbehind);
          }
        }
        pending += decoder.decode();
        if (!injected) {
          pending = injectHeadMarkup(pending, markup);
        }
        if (pending.length > 0) {
          controller.enqueue(encoder.encode(pending));
        }
        controller.close();
      } catch (error) {
        controller.error(error);
      }
    }
  });
}, pipeStreamWithIslandMarkerDetection = (stream, markup) => {
  const encoder = new TextEncoder;
  const decoder = new TextDecoder;
  const lookbehind = Math.max(ISLAND_MARKER.length, 1024);
  return new ReadableStream({
    async start(controller) {
      const reader = stream.getReader();
      let injected = false;
      let pending = "";
      try {
        for (;; ) {
          const { done, value } = await reader.read();
          if (done)
            break;
          if (!value)
            continue;
          pending += streamChunkToString2(value, decoder);
          if (injected) {
            controller.enqueue(encoder.encode(pending));
            pending = "";
            continue;
          }
          const markerIndex = pending.indexOf(ISLAND_MARKER);
          if (markerIndex >= 0) {
            const tagStart = pending.lastIndexOf("<", markerIndex);
            const injectAt = tagStart >= 0 ? tagStart : markerIndex;
            const next = `${pending.slice(0, injectAt)}${markup}${pending.slice(injectAt)}`;
            controller.enqueue(encoder.encode(next));
            pending = "";
            injected = true;
            continue;
          }
          if (pending.length > lookbehind) {
            const safeText = pending.slice(0, pending.length - lookbehind);
            controller.enqueue(encoder.encode(safeText));
            pending = pending.slice(-lookbehind);
          }
        }
        pending += decoder.decode();
        if (pending.length > 0) {
          controller.enqueue(encoder.encode(pending));
        }
        controller.close();
      } catch (error) {
        controller.error(error);
      }
    }
  });
}, htmlContainsIslands = (html) => html.includes(ISLAND_MARKER), injectIslandPageContext = (html, options) => {
  const manifest = globalThis.__absoluteManifest;
  const hasIslands = options?.hasIslands ?? htmlContainsIslands(html);
  if (!manifest || !hasIslands) {
    return html;
  }
  if (html.includes(MANIFEST_MARKER) || html.includes(ISLAND_STATE_MARKER)) {
    return html;
  }
  return injectHeadMarkup(html, buildIslandsHeadMarkup(manifest));
}, injectIslandPageContextStream = (stream, options) => {
  const manifest = globalThis.__absoluteManifest;
  if (!manifest)
    return stream;
  const markup = buildIslandsHeadMarkup(manifest);
  if (options?.hasIslands === true) {
    return pipeStreamWithHeadInjection(stream, markup);
  }
  if (options?.hasIslands === false) {
    return stream;
  }
  return pipeStreamWithIslandMarkerDetection(stream, markup);
}, setCurrentIslandManifest = (manifest) => {
  globalThis.__absoluteManifest = manifest;
};

// src/utils/ssrErrorPage.ts
var ssrErrorPage = (framework, error) => {
  const frameworkColors = {
    angular: "#dd0031",
    html: "#e34c26",
    htmx: "#1a365d",
    react: "#61dafb",
    svelte: "#ff3e00",
    vue: "#42b883"
  };
  const accent = frameworkColors[framework] ?? "#94a3b8";
  const label = framework.charAt(0).toUpperCase() + framework.slice(1);
  const message = error instanceof Error ? error.message : String(error);
  return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SSR Error - AbsoluteJS</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{min-height:100vh;background:linear-gradient(135deg,rgba(15,23,42,0.98) 0%,rgba(30,41,59,0.98) 100%);color:#e2e8f0;font-family:"JetBrains Mono","Fira Code",ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;font-size:14px;line-height:1.6;display:flex;align-items:flex-start;justify-content:center;padding:32px}
.card{max-width:720px;width:100%;background:rgba(30,41,59,0.6);border:1px solid rgba(71,85,105,0.5);border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,0.5),0 0 0 1px rgba(255,255,255,0.05);overflow:hidden}
.header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:20px 24px;background:rgba(15,23,42,0.5);border-bottom:1px solid rgba(71,85,105,0.4)}
.brand{font-weight:700;font-size:20px;color:#fff;letter-spacing:-0.02em}
.badge{padding:5px 10px;border-radius:8px;font-size:12px;font-weight:600;background:${accent};color:#fff;opacity:0.95;box-shadow:0 2px 4px rgba(0,0,0,0.2)}
.kind{color:#94a3b8;font-size:13px;font-weight:500}
.content{padding:24px}
.label{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.08em;color:#94a3b8;margin-bottom:8px}
.message{margin:0;padding:16px 20px;background:rgba(239,68,68,0.12);border:1px solid rgba(239,68,68,0.25);border-radius:10px;overflow-x:auto;white-space:pre-wrap;word-break:break-word;color:#fca5a5;font-size:13px;line-height:1.5}
.hint{margin-top:20px;padding:12px 20px;background:rgba(71,85,105,0.3);border-radius:10px;border:1px solid rgba(71,85,105,0.4);color:#cbd5e1;font-size:13px}
</style>
</head>
<body>
<div class="card">
<div class="header">
<div style="display:flex;align-items:center;gap:12px">
<span class="brand">AbsoluteJS</span>
<span class="badge">${label}</span>
</div>
<span class="kind">Server Render Error</span>
</div>
<div class="content">
<div class="label">What went wrong</div>
<pre class="message">${message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</pre>
<div class="hint">A component threw during server-side rendering. Check the terminal for the full stack trace.</div>
</div>
</div>
</body>
</html>`;
};

// src/utils/stringModifiers.ts
var normalizeSlug = (str) => str.trim().replace(/\s+/g, "-").replace(/[^A-Za-z0-9\-_]+/g, "").replace(/[-_]{2,}/g, "-"), toKebab = (str) => normalizeSlug(str).replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase(), toPascal = (str) => {
  if (!str.includes("-") && !str.includes("_")) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }
  return normalizeSlug(str).split(/[-_]/).filter(Boolean).map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1).toLowerCase()).join("");
}, toScreamingSnake = (str) => str.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();

// src/utils/resolveConvention.ts
import { basename } from "path";
var CONVENTIONS_KEY = "__absoluteConventions", isConventionsMap = (value) => Boolean(value) && typeof value === "object", getMap = () => {
  const value = Reflect.get(globalThis, CONVENTIONS_KEY);
  if (isConventionsMap(value))
    return value;
  const empty = {};
  return empty;
}, derivePageName = (pagePath) => {
  const base = basename(pagePath);
  const dotIndex = base.indexOf(".");
  const name = dotIndex > 0 ? base.slice(0, dotIndex) : base;
  return toPascal(name);
}, resolveErrorConventionPath = (framework, pageName) => {
  const conventions = getMap()[framework];
  if (!conventions)
    return;
  return conventions.pages?.[pageName]?.error ?? conventions.defaults?.error;
}, resolveNotFoundConventionPath = (framework) => getMap()[framework]?.defaults?.notFound, setConventions = (map) => {
  Reflect.set(globalThis, CONVENTIONS_KEY, map);
}, isDev = () => true, buildErrorProps = (error) => {
  const message = error instanceof Error ? error.message : String(error);
  const stack = isDev() && error instanceof Error ? error.stack : undefined;
  return { error: { message, stack } };
}, renderReactError = async (conventionPath, errorProps) => {
  const { createElement } = await import("react");
  const { renderToReadableStream } = await import("react-dom/server");
  const mod = await import(conventionPath);
  const [firstKey] = Object.keys(mod);
  const ErrorComponent = mod.default ?? (firstKey ? mod[firstKey] : undefined);
  const element = createElement(ErrorComponent, errorProps);
  const stream = await renderToReadableStream(element);
  return new Response(stream, {
    headers: { "Content-Type": "text/html" },
    status: 500
  });
}, renderSvelteError = async (conventionPath, errorProps) => {
  const { render } = await import("svelte/server");
  const mod = await import(conventionPath);
  const ErrorComponent = mod.default;
  const { head, body } = render(ErrorComponent, {
    props: errorProps
  });
  const html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
  return new Response(html, {
    headers: { "Content-Type": "text/html" },
    status: 500
  });
}, unescapeVueStyles = (ssrBody) => {
  let styles = "";
  const body = ssrBody.replace(/<style>([\s\S]*?)<\/style>/g, (_, css) => {
    styles += `<style>${css.replace(/&quot;/g, '"').replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">")}</style>`;
    return "";
  });
  return { body, styles };
}, renderVueError = async (conventionPath, errorProps) => {
  const { createSSRApp, h } = await import("vue");
  const { renderToString } = await import("vue/server-renderer");
  const mod = await import(conventionPath);
  const ErrorComponent = mod.default;
  const app = createSSRApp({
    render: () => h(ErrorComponent, errorProps)
  });
  const rawBody = await renderToString(app);
  const { styles, body } = unescapeVueStyles(rawBody);
  const html = `<!DOCTYPE html><html><head>${styles}</head><body><div id="root">${body}</div></body></html>`;
  return new Response(html, {
    headers: { "Content-Type": "text/html" },
    status: 500
  });
}, renderAngularError = async (conventionPath, errorProps) => {
  const mod = await import(conventionPath);
  const renderError = mod.default ?? mod.renderError;
  if (typeof renderError !== "function")
    return null;
  const html = renderError(errorProps);
  return new Response(html, {
    headers: { "Content-Type": "text/html" },
    status: 500
  });
}, logConventionRenderError = (framework, label, renderError) => {
  const message = renderError instanceof Error ? renderError.message : "";
  if (message.includes("Cannot find module") || message.includes("Cannot find package") || message.includes("not found in module")) {
    console.error(`[SSR] Convention ${label} page for ${framework} failed: missing framework package. Ensure the ${framework} runtime is installed (e.g. bun add ${framework === "react" ? "react react-dom" : framework}).`);
    return;
  }
  console.error(`[SSR] Failed to render ${framework} convention ${label} page:`, renderError);
}, ERROR_RENDERERS, renderConventionError = async (framework, pageName, error) => {
  const conventionPath = resolveErrorConventionPath(framework, pageName);
  if (!conventionPath)
    return null;
  const errorProps = buildErrorProps(error);
  const renderer = ERROR_RENDERERS[framework];
  if (!renderer)
    return null;
  try {
    return await renderer(conventionPath, errorProps);
  } catch (renderError) {
    logConventionRenderError(framework, "error", renderError);
  }
  return null;
}, renderReactNotFound = async (conventionPath) => {
  const { createElement } = await import("react");
  const { renderToReadableStream } = await import("react-dom/server");
  const mod = await import(conventionPath);
  const [nfKey] = Object.keys(mod);
  const NotFoundComponent = mod.default ?? (nfKey ? mod[nfKey] : undefined);
  const element = createElement(NotFoundComponent);
  const stream = await renderToReadableStream(element);
  return new Response(stream, {
    headers: { "Content-Type": "text/html" },
    status: 404
  });
}, renderSvelteNotFound = async (conventionPath) => {
  const { render } = await import("svelte/server");
  const mod = await import(conventionPath);
  const NotFoundComponent = mod.default;
  const { head, body } = render(NotFoundComponent);
  const html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
  return new Response(html, {
    headers: { "Content-Type": "text/html" },
    status: 404
  });
}, renderVueNotFound = async (conventionPath) => {
  const { createSSRApp, h } = await import("vue");
  const { renderToString } = await import("vue/server-renderer");
  const mod = await import(conventionPath);
  const NotFoundComponent = mod.default;
  const app = createSSRApp({
    render: () => h(NotFoundComponent)
  });
  const rawBody = await renderToString(app);
  const { styles, body } = unescapeVueStyles(rawBody);
  const html = `<!DOCTYPE html><html><head>${styles}</head><body><div id="root">${body}</div></body></html>`;
  return new Response(html, {
    headers: { "Content-Type": "text/html" },
    status: 404
  });
}, renderAngularNotFound = async (conventionPath) => {
  const mod = await import(conventionPath);
  const renderNotFound = mod.default ?? mod.renderNotFound;
  if (typeof renderNotFound !== "function")
    return null;
  const html = renderNotFound();
  return new Response(html, {
    headers: { "Content-Type": "text/html" },
    status: 404
  });
}, NOT_FOUND_RENDERERS, renderConventionNotFound = async (framework) => {
  const conventionPath = resolveNotFoundConventionPath(framework);
  if (!conventionPath)
    return null;
  const renderer = NOT_FOUND_RENDERERS[framework];
  if (!renderer)
    return null;
  try {
    return await renderer(conventionPath);
  } catch (renderError) {
    logConventionRenderError(framework, "not-found", renderError);
  }
  return null;
}, NOT_FOUND_PRIORITY, renderFirstNotFound = async () => {
  for (const framework of NOT_FOUND_PRIORITY) {
    if (!getMap()[framework]?.defaults?.notFound)
      continue;
    const response = await renderConventionNotFound(framework);
    if (response)
      return response;
  }
  return null;
};
var init_resolveConvention = __esm(() => {
  ERROR_RENDERERS = {
    angular: renderAngularError,
    react: renderReactError,
    svelte: renderSvelteError,
    vue: renderVueError
  };
  NOT_FOUND_RENDERERS = {
    angular: renderAngularNotFound,
    react: renderReactNotFound,
    svelte: renderSvelteNotFound,
    vue: renderVueNotFound
  };
  NOT_FOUND_PRIORITY = [
    "react",
    "svelte",
    "vue",
    "angular"
  ];
});

// src/react/pageHandler.ts
var ssrDirty = false, buildDirtyResponse = (index, maybeProps) => {
  const propsScript = maybeProps ? `window.__INITIAL_PROPS__=${JSON.stringify(maybeProps)};` : "";
  const dirtyFlag = "window.__SSR_DIRTY__=true;";
  const refreshSetup = "window.__REFRESH_BUFFER__=[];" + "window.$RefreshReg$=function(t,i){window.__REFRESH_BUFFER__.push([t,i])};" + "window.$RefreshSig$=function(){return function(t){return t}};";
  const inlineScript = `${propsScript}${dirtyFlag}${refreshSetup}`;
  const html = `<!DOCTYPE html><html><head></head><body>` + `<script>${inlineScript}</script>` + `<script type="module" src="${index}"></script>` + `</body></html>`;
  return new Response(html, {
    headers: { "Content-Type": "text/html" }
  });
}, handleReactPageRequest = async (PageComponent, index, ...props) => {
  const [maybeProps] = props;
  if (ssrDirty) {
    return buildDirtyResponse(index, maybeProps);
  }
  try {
    const { createElement } = await import("react");
    const { renderToReadableStream } = await import("react-dom/server");
    const element = maybeProps !== undefined ? createElement(PageComponent, maybeProps) : createElement(PageComponent);
    const propsScript = maybeProps ? `window.__INITIAL_PROPS__=${JSON.stringify(maybeProps)};` : "";
    const refreshSetup = "window.__REFRESH_BUFFER__=[];window.$RefreshReg$=function(t,i){window.__REFRESH_BUFFER__.push([t,i])};window.$RefreshSig$=function(){return function(t){return t}};";
    const stream = await renderToReadableStream(element, {
      bootstrapModules: [index],
      bootstrapScriptContent: propsScript + refreshSetup || undefined,
      onError(error) {
        console.error("[SSR] React streaming error:", error);
      }
    });
    if ("allReady" in stream && stream.allReady instanceof Promise) {
      await stream.allReady;
    }
    const htmlStream = injectIslandPageContextStream(stream);
    return new Response(htmlStream, {
      headers: { "Content-Type": "text/html" }
    });
  } catch (error) {
    console.error("[SSR] React render error:", error);
    const pageName = PageComponent.name || PageComponent.displayName || "";
    const conventionResponse = await renderConventionError("react", pageName, error);
    if (conventionResponse)
      return conventionResponse;
    return new Response(ssrErrorPage("react", error), {
      headers: { "Content-Type": "text/html" },
      status: 500
    });
  }
}, invalidateReactSsrCache = () => {
  ssrDirty = true;
};
var init_pageHandler = __esm(() => {
  init_resolveConvention();
});

// src/core/islandManifest.ts
var toIslandFrameworkSegment = (framework) => framework[0]?.toUpperCase() + framework.slice(1), collectFrameworkIslands = (manifest, prefix) => {
  const entries = {};
  let found = false;
  for (const [key, value] of Object.entries(manifest)) {
    if (!key.startsWith(prefix))
      continue;
    const component = key.slice(prefix.length);
    if (!component)
      continue;
    entries[component] = value;
    found = true;
  }
  return found ? entries : undefined;
}, getIslandManifestEntries = (manifest) => {
  const islands = {};
  const frameworks = ["react", "svelte", "vue", "angular"];
  for (const framework of frameworks) {
    const prefix = `Island${toIslandFrameworkSegment(framework)}`;
    const entries = collectFrameworkIslands(manifest, prefix);
    if (entries)
      islands[framework] = entries;
  }
  return islands;
}, getIslandManifestKey = (framework, component) => `Island${toIslandFrameworkSegment(framework)}${component}`;

// src/core/islands.ts
function getIslandComponent(component) {
  if (isIslandComponentDefinition(component)) {
    return component.component;
  }
  return component;
}
var defineIslandComponent = (component, options) => ({
  component,
  export: options.export,
  source: options.source
}), defineIslandRegistry = (registry) => registry, isRecord = (value) => typeof value === "object" && value !== null, getIslandBuildReference = (component) => {
  if (!isIslandComponentDefinition(component))
    return null;
  return {
    export: component.export,
    source: component.source
  };
}, isIslandComponentDefinition = (value) => isRecord(value) && ("component" in value) && ("source" in value) && typeof value.source === "string", parseIslandProps = (rawProps) => {
  if (!rawProps)
    return {};
  return JSON.parse(rawProps);
}, serializeIslandProps = (props) => JSON.stringify(props ?? {});
var init_islands = () => {};

// src/core/islandMarkupAttributes.ts
var getIslandMarkerAttributes = (props, islandId) => ({
  "data-component": props.component,
  "data-framework": props.framework,
  "data-hydrate": props.hydrate ?? "load",
  "data-island": "true",
  ...islandId ? { "data-island-id": islandId } : {},
  "data-props": serializeIslandProps(props.props)
}), escapeHtmlAttribute = (value) => value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"), serializeIslandAttributes = (attributes) => Object.entries(attributes).map(([key, value]) => `${key}="${escapeHtmlAttribute(value)}"`).join(" ");
var init_islandMarkupAttributes = __esm(() => {
  init_islands();
});

// src/core/currentIslandRegistry.ts
var requireCurrentIslandRegistry = () => {
  const registry = globalThis.__absoluteIslandRegistry;
  if (!registry) {
    throw new Error("No island registry is active. Configure `islands.registry` in absolute.config.ts before rendering <Island />.");
  }
  return registry;
}, setCurrentIslandRegistry = (registry) => {
  globalThis.__absoluteIslandRegistry = registry;
};

// src/angular/injectorPatch.ts
import { existsSync, readFileSync, writeFileSync } from "fs";
import { dirname, join, resolve } from "path";
var applyInjectorPatch = (chunkPath, content) => {
  if (content.includes('Symbol.for("angular.currentInjector")')) {
    return;
  }
  const original = [
    "let _currentInjector = undefined;",
    "function getCurrentInjector() {",
    "  return _currentInjector;",
    "}",
    "function setCurrentInjector(injector) {",
    "  const former = _currentInjector;",
    "  _currentInjector = injector;",
    "  return former;",
    "}"
  ].join(`
`);
  const replacement = [
    'const _injSym = Symbol.for("angular.currentInjector");',
    "if (!globalThis[_injSym]) globalThis[_injSym] = { v: undefined };",
    "function getCurrentInjector() {",
    "  return globalThis[_injSym].v;",
    "}",
    "function setCurrentInjector(injector) {",
    "  const former = globalThis[_injSym].v;",
    "  globalThis[_injSym].v = injector;",
    "  return former;",
    "}"
  ].join(`
`);
  const patched = content.replace(original, replacement);
  if (patched === content) {
    return;
  }
  writeFileSync(chunkPath, patched, "utf-8");
}, resolveAngularCoreDir = () => {
  const fromProject = resolve(process.cwd(), "node_modules/@angular/core");
  if (existsSync(join(fromProject, "package.json"))) {
    return fromProject;
  }
  return dirname(__require.resolve("@angular/core/package.json"));
}, patchAngularInjectorSingleton = () => {
  try {
    const coreDir = resolveAngularCoreDir();
    const chunkPath = join(coreDir, "fesm2022", "_not_found-chunk.mjs");
    const content = readFileSync(chunkPath, "utf-8");
    applyInjectorPatch(chunkPath, content);
  } catch {}
};
var init_injectorPatch = __esm(() => {
  patchAngularInjectorSingleton();
});

// src/angular/resolveAngularPackage.ts
import { existsSync as existsSync2 } from "fs";
import { resolve as resolve2 } from "path";
var resolveAngularPackage = (specifier) => {
  const fromProject = resolve2(process.cwd(), "node_modules", specifier);
  if (existsSync2(fromProject)) {
    return fromProject;
  }
  return specifier;
};
var init_resolveAngularPackage = () => {};

// src/angular/angularPatch.ts
var exports_angularPatch = {};
__export(exports_angularPatch, {
  applyPatches: () => applyPatches
});
var ensureHead = (doc) => {
  if (!doc || doc.head || !doc.documentElement) {
    return;
  }
  const head = doc.createElement("head");
  doc.documentElement.insertBefore(head, doc.documentElement.firstChild);
}, applyPatches = async () => {
  const { \u{275}DominoAdapter } = await import(resolveAngularPackage("@angular/platform-server"));
  if (!\u{275}DominoAdapter?.prototype) {
    console.warn("[Angular Patch] \u0275DominoAdapter not found, skipping patches");
    return false;
  }
  const proto = \u{275}DominoAdapter.prototype;
  const origGetBaseHref = proto.getBaseHref;
  proto.getBaseHref = function(doc) {
    if (!doc || !doc.head || typeof doc.head.children === "undefined") {
      return "";
    }
    return origGetBaseHref.call(this, doc);
  };
  const origCreateHtmlDocument = proto.createHtmlDocument;
  proto.createHtmlDocument = function() {
    const doc = origCreateHtmlDocument.call(this);
    ensureHead(doc);
    return doc;
  };
  const origGetDefaultDocument = proto.getDefaultDocument;
  proto.getDefaultDocument = function() {
    const doc = origGetDefaultDocument.call(this);
    ensureHead(doc);
    return doc;
  };
  return true;
};
var init_angularPatch = __esm(() => {
  init_resolveAngularPackage();
});

// src/angular/angularDeps.ts
var initDominoAdapter = (platformServer) => {
  try {
    const DominoAdapter = platformServer.\u{275}DominoAdapter;
    DominoAdapter?.makeCurrent?.();
  } catch (err) {
    console.error("Failed to initialize DominoAdapter:", err);
  }
}, loadAngularDeps = async () => {
  patchAngularInjectorSingleton();
  await import(resolveAngularPackage("@angular/compiler"));
  const { applyPatches: applyPatches2 } = await Promise.resolve().then(() => (init_angularPatch(), exports_angularPatch));
  await applyPatches2();
  const [platformBrowser, platformServer, common, core] = await Promise.all([
    import(resolveAngularPackage("@angular/platform-browser")),
    import(resolveAngularPackage("@angular/platform-server")),
    import(resolveAngularPackage("@angular/common")),
    import(resolveAngularPackage("@angular/core"))
  ]);
  if (false) {}
  initDominoAdapter(platformServer);
  return {
    APP_BASE_HREF: common.APP_BASE_HREF,
    bootstrapApplication: platformBrowser.bootstrapApplication,
    DomSanitizer: platformBrowser.DomSanitizer,
    provideClientHydration: platformBrowser.provideClientHydration,
    provideServerRendering: platformServer.provideServerRendering,
    provideZonelessChangeDetection: core.provideZonelessChangeDetection,
    reflectComponentType: core.reflectComponentType,
    renderApplication: platformServer.renderApplication,
    Sanitizer: core.Sanitizer,
    SecurityContext: core.SecurityContext
  };
}, angularDeps = null, getAngularDeps = () => {
  if (!angularDeps) {
    angularDeps = loadAngularDeps();
  }
  return angularDeps;
};
var init_angularDeps = __esm(() => {
  init_injectorPatch();
  init_resolveAngularPackage();
});

// src/utils/registerClientScript.ts
var scriptRegistry, requestCounter = 0, getRequestId = () => `req_${Date.now()}_${++requestCounter}`, ssrContextGetter = null, getSsrContextId = () => ssrContextGetter?.() || Object.getOwnPropertyDescriptor(globalThis, "__absolutejs_requestId")?.value, registerClientScript = (script, requestId) => {
  const id = requestId || getSsrContextId() || getRequestId();
  if (!scriptRegistry.has(id)) {
    scriptRegistry.set(id, new Set);
  }
  scriptRegistry.get(id)?.add(script);
  return id;
}, setSsrContextGetter = (getter) => {
  ssrContextGetter = getter;
}, clearAllClientScripts = () => {
  scriptRegistry.clear();
}, generateClientScriptCode = (scripts) => {
  if (scripts.length === 0) {
    return "";
  }
  const scriptCode = scripts.map((script, index) => {
    const funcString = script.toString();
    const bodyMatch = funcString.match(/\{([\s\S]*)\}/);
    if (!bodyMatch || !bodyMatch[1]) {
      return "";
    }
    const body = bodyMatch[1].trim();
    return `
	(function() {
		var executed = false;
		function executeScript_${index}() {
			if (executed) return;
			executed = true;
			${body}
		}

		if (document.readyState === 'complete' || document.readyState === 'interactive') {
			executeScript_${index}();
		} else {
			document.addEventListener('DOMContentLoaded', executeScript_${index});
		}

		// Watch for hydration-added elements
		var observer = new MutationObserver(function() {
			executeScript_${index}();
			if (executed) observer.disconnect();
		});
		if (!executed) {
			observer.observe(document.body || document.documentElement, { childList: true, subtree: true });
		}

		// Single fallback timeout
		setTimeout(function() {
			executeScript_${index}();
			observer.disconnect();
		}, 1000);
	})();`;
  }).join(`
`);
  return `<script>
(function() {
${scriptCode}
})();
</script>`;
}, getAndClearClientScripts = (requestId) => {
  const id = requestId || ssrContextGetter?.();
  if (!id)
    return [];
  const scripts = scriptRegistry.get(id);
  if (!scripts) {
    return [];
  }
  const scriptArray = Array.from(scripts);
  scriptRegistry.delete(id);
  return scriptArray;
};
var init_registerClientScript = __esm(() => {
  scriptRegistry = new Map;
  if (typeof globalThis !== "undefined") {
    Object.assign(globalThis, { registerClientScript });
  }
});

// src/angular/ssrRender.ts
var routePropsCache, cacheRouteData = (pagePath, data) => {
  const cacheKey = pagePath.split("?")[0] ?? pagePath;
  routePropsCache.set(cacheKey, data);
}, getCachedRouteData = (pagePath) => routePropsCache.get(pagePath), selectorCache, buildDeps = (ssrResult, baseDeps) => {
  if (!ssrResult?.core) {
    return baseDeps;
  }
  const { common, core, platformBrowser, platformServer } = ssrResult;
  return {
    APP_BASE_HREF: common?.APP_BASE_HREF ?? baseDeps.APP_BASE_HREF,
    bootstrapApplication: platformBrowser?.bootstrapApplication ?? baseDeps.bootstrapApplication,
    DomSanitizer: platformBrowser?.DomSanitizer ?? baseDeps.DomSanitizer,
    provideClientHydration: platformBrowser?.provideClientHydration ?? baseDeps.provideClientHydration,
    provideServerRendering: platformServer?.provideServerRendering ?? baseDeps.provideServerRendering,
    provideZonelessChangeDetection: core.provideZonelessChangeDetection,
    reflectComponentType: core.reflectComponentType,
    renderApplication: platformServer?.renderApplication ?? baseDeps.renderApplication,
    Sanitizer: core.Sanitizer,
    SecurityContext: core.SecurityContext
  };
}, buildProviders = (deps, sanitizer, maybeProps, tokenMap) => {
  const providers = [
    deps.provideServerRendering(),
    deps.provideClientHydration(),
    deps.provideZonelessChangeDetection(),
    { provide: deps.APP_BASE_HREF, useValue: "/" },
    {
      provide: deps.DomSanitizer,
      useValue: sanitizer
    },
    { provide: deps.Sanitizer, useValue: sanitizer }
  ];
  if (!maybeProps) {
    return providers;
  }
  const propProviders = Object.entries(maybeProps).map(([propName, propValue]) => ({
    token: tokenMap.get(toScreamingSnake(propName)),
    value: propValue
  })).filter((entry) => entry.token).map((entry) => ({ provide: entry.token, useValue: entry.value }));
  return [...providers, ...propProviders];
}, clearSelectorCache = () => selectorCache.clear(), isInjectionToken = (value) => {
  if (!value || typeof value !== "object") {
    return false;
  }
  return "ngMetadataName" in value && value.ngMetadataName === "InjectionToken";
}, discoverTokens = (pageModule) => new Map(Object.entries(pageModule).filter(([, value]) => isInjectionToken(value))), loadSsrDeps = async (pagePath) => {
  const ssrDepsPath = (pagePath.split("?")[0] ?? pagePath).replace(/\.js$/, ".ssr-deps.js");
  try {
    const ssrDeps = await import(ssrDepsPath);
    const result = {
      common: ssrDeps.__angularCommon,
      core: ssrDeps.__angularCore,
      platformBrowser: ssrDeps.__angularPlatformBrowser,
      platformServer: ssrDeps.__angularPlatformServer
    };
    return result;
  } catch {
    return null;
  }
}, resolveSelector = (deps, pagePath, PageComponent) => {
  const cached = selectorCache.get(pagePath);
  if (cached) {
    return cached;
  }
  const selector = deps.reflectComponentType(PageComponent)?.selector ?? "ng-app";
  selectorCache.set(pagePath, selector);
  return selector;
}, injectBeforeClose = (html, snippet) => {
  if (html.includes("</body>")) {
    return html.replace("</body>", `${snippet}</body>`);
  }
  if (html.includes("</html>")) {
    return html.replace("</html>", `${snippet}</html>`);
  }
  return html + snippet;
}, injectSsrScripts = (html, requestId, indexPath, props) => {
  let result = html;
  const registeredScripts = getAndClearClientScripts(requestId);
  if (registeredScripts.length > 0) {
    result = injectBeforeClose(result, generateClientScriptCode(registeredScripts));
  }
  if (props) {
    result = injectBeforeClose(result, `<script>window.__ABS_ANGULAR_PAGE_PROPS__ = ${JSON.stringify(props)};</script>`);
  }
  if (indexPath) {
    result = injectBeforeClose(result, `<script type="module" src="${indexPath}"></script>`);
  }
  return result;
}, renderAngularApp = async (deps, PageComponent, providers, document2) => {
  const bootstrap = (context) => deps.bootstrapApplication(PageComponent, { providers }, context);
  return withSuppressedAngularDevLogs(() => deps.renderApplication(bootstrap, {
    document: document2,
    platformProviders: [],
    url: "/"
  }));
}, withSuppressedAngularDevLogs = async (render) => {
  const origLog = console.log;
  console.log = (...args) => {
    if (typeof args[0] === "string" && args[0].includes("development mode")) {
      return;
    }
    origLog.apply(console, args);
  };
  try {
    return await render();
  } finally {
    console.log = origLog;
  }
};
var init_ssrRender = __esm(() => {
  init_registerClientScript();
  routePropsCache = new Map;
  selectorCache = new Map;
});

// src/angular/islands.ts
var angularIslandSelector = "abs-angular-island", getAngularIslandSelector = (_islandId) => angularIslandSelector, getSelectorFromRenderedIsland = (rootElement) => {
  const firstChild = rootElement.firstElementChild;
  if (!(firstChild instanceof HTMLElement)) {
    return null;
  }
  const selector = firstChild.tagName.toLowerCase();
  return selector.length > 0 ? selector : null;
}, getClientAngularComponentSelector = (component) => {
  const maybeDef = Reflect.get(component, "\u0275cmp");
  if (typeof maybeDef !== "object" || maybeDef === null) {
    return null;
  }
  const maybeSelectors = Reflect.get(maybeDef, "selectors");
  if (!Array.isArray(maybeSelectors)) {
    return null;
  }
  const [firstSelectorGroup] = maybeSelectors;
  if (!Array.isArray(firstSelectorGroup)) {
    return null;
  }
  const [selector] = firstSelectorGroup;
  return typeof selector === "string" && selector.length > 0 ? selector : null;
}, createAngularIslandApp = async () => {
  const { EnvironmentInjector, provideZonelessChangeDetection } = await import("@angular/core");
  const { createApplication } = await import("@angular/platform-browser");
  const app = await createApplication({
    providers: [provideZonelessChangeDetection()]
  });
  const environmentInjector = app.injector.get(EnvironmentInjector);
  return { app, environmentInjector };
}, angularIslandAppPromise = null, getAngularIslandApp = async () => {
  if (!angularIslandAppPromise) {
    angularIslandAppPromise = createAngularIslandApp();
  }
  return angularIslandAppPromise;
}, wrapperMetadataCache, requestRenderCache, getRequestRenderCache = () => {
  const requestId = getSsrContextId();
  if (!requestId) {
    return null;
  }
  const cached = requestRenderCache.get(requestId);
  if (cached) {
    return cached;
  }
  const renderCache = new Map;
  requestRenderCache.set(requestId, renderCache);
  return renderCache;
}, getAngularIslandWrapperKey = (component, _islandId) => {
  const componentName = typeof component.name === "string" && component.name.length > 0 ? component.name : "AngularIsland";
  return `${componentName}:${angularIslandSelector}`;
}, getIslandRenderCacheKey = (component, props) => {
  const componentName = typeof component.name === "string" && component.name.length > 0 ? component.name : "AngularIsland";
  return `${componentName}:${JSON.stringify(props)}`;
}, buildAngularIslandWrapperMetadata = async (component, islandId, wrapperKey) => {
  const { Component, InjectionToken, inject } = await import("@angular/core");
  const { NgComponentOutlet } = await import("@angular/common");
  const deps = await getAngularDeps();
  const selector = getAngularIslandSelector(islandId);
  const propsToken = new InjectionToken(`${wrapperKey}:props`);

  class AngularIslandWrapperComponent {
    component = component;
    props = inject(propsToken);
  }
  return {
    deps,
    propsToken,
    selector,
    WrapperComponent: Component({
      imports: [NgComponentOutlet, component],
      selector,
      standalone: true,
      template: '<ng-container *ngComponentOutlet="component; inputs: props"></ng-container>'
    })(AngularIslandWrapperComponent)
  };
}, createAngularIslandWrapper = async (component, islandId) => {
  const wrapperKey = getAngularIslandWrapperKey(component, islandId);
  const cached = wrapperMetadataCache.get(wrapperKey);
  if (cached) {
    return cached;
  }
  const metadataPromise = buildAngularIslandWrapperMetadata(component, islandId, wrapperKey);
  wrapperMetadataCache.set(wrapperKey, metadataPromise);
  return metadataPromise;
}, extractAngularIslandRoot = (html, selector) => {
  const openTag = `<${selector}`;
  const start = html.indexOf(openTag);
  if (start < 0) {
    throw new Error(`Could not find Angular island root "${selector}".`);
  }
  const endTag = `</${selector}>`;
  const end = html.indexOf(endTag, start);
  if (end < 0) {
    throw new Error(`Could not close Angular island root "${selector}".`);
  }
  return html.slice(start, end + endTag.length);
}, mountAngularIsland = async (component, element, props, islandId) => {
  await import("@angular/compiler");
  const { createComponent, inputBinding } = await import("@angular/core");
  const selector = getAngularIslandSelector(islandId);
  const { app, environmentInjector } = await getAngularIslandApp();
  let rootElement = element.querySelector(selector);
  if (!(rootElement instanceof HTMLElement)) {
    element.innerHTML = `<${selector}></${selector}>`;
    rootElement = element.querySelector(selector);
  }
  if (!(rootElement instanceof HTMLElement))
    return app;
  const componentSelector = getClientAngularComponentSelector(component) ?? getSelectorFromRenderedIsland(rootElement);
  if (!componentSelector)
    return app;
  rootElement.innerHTML = `<${componentSelector}></${componentSelector}>`;
  const hostElement = rootElement.querySelector(componentSelector);
  if (!(hostElement instanceof HTMLElement))
    return app;
  const bindings = Object.entries(props).map(([key, value]) => inputBinding(key, () => value));
  const componentRef = createComponent(component, {
    bindings,
    environmentInjector,
    hostElement
  });
  app.attachView(componentRef.hostView);
  componentRef.changeDetectorRef.detectChanges();
  window.__ABS_ANGULAR_ISLAND_APPS__ ??= [];
  window.__ABS_ANGULAR_ISLAND_APPS__.push(app);
  return app;
}, renderAngularIslandToHtml = async (component, props, islandId) => {
  const requestCache = getRequestRenderCache();
  const renderCacheKey = getIslandRenderCacheKey(component, props);
  const cachedHtml = requestCache?.get(renderCacheKey);
  if (cachedHtml) {
    return cachedHtml;
  }
  const { deps, propsToken, selector, WrapperComponent } = await createAngularIslandWrapper(component, islandId);
  const providers = [
    deps.provideServerRendering(),
    deps.provideZonelessChangeDetection(),
    { provide: deps.APP_BASE_HREF, useValue: "/" },
    { provide: propsToken, useValue: props }
  ];
  const document2 = `<!DOCTYPE html><html><body><${selector}></${selector}></body></html>`;
  const html = await withSuppressedAngularDevLogs(() => deps.renderApplication((context) => deps.bootstrapApplication(WrapperComponent, { providers }, context), {
    document: document2,
    platformProviders: [],
    url: "/"
  }));
  const islandHtml = extractAngularIslandRoot(html, selector);
  requestCache?.set(renderCacheKey, islandHtml);
  return islandHtml;
};
var init_islands2 = __esm(() => {
  init_angularDeps();
  init_ssrRender();
  init_registerClientScript();
  wrapperMetadataCache = new Map;
  requestRenderCache = new Map;
});

// src/core/islandSsr.ts
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { render as renderSvelte } from "svelte/server";
import { createSSRApp, h } from "vue";
import { renderToString as renderVueToString } from "vue/server-renderer";
var renderReactIslandToHtml = (component, props) => renderToStaticMarkup(createElement(component, props)), renderSvelteIslandToHtml = (component, props) => {
  const { body } = renderSvelte(component, { props });
  return body;
}, renderVueIslandToHtml = (component, props) => {
  const app = createSSRApp({
    render: () => h(component, props)
  });
  return renderVueToString(app);
};
var init_islandSsr = __esm(() => {
  init_islands2();
});

// src/build/resolvePackageImport.ts
import { resolve as resolve3, join as join2 } from "path";
import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
var resolveExportPath = (entry, conditions) => {
  if (typeof entry === "string")
    return entry;
  if (!entry || typeof entry !== "object")
    return null;
  for (const condition of conditions) {
    const target = Reflect.get(entry, condition);
    if (typeof target === "string") {
      return target;
    }
  }
  return null;
}, resolvePackageImport = (specifier, conditions = ["import"]) => {
  if (specifier.startsWith(".") || specifier.startsWith("/"))
    return null;
  const parts = specifier.split("/");
  const isScoped = specifier.startsWith("@");
  const packageName = isScoped ? `${parts[0]}/${parts[1]}` : parts[0];
  const subpath = isScoped ? parts.slice(2).join("/") : parts.slice(1).join("/");
  const exportKey = subpath ? `./${subpath}` : ".";
  const currentPackageJsonPath = resolve3(process.cwd(), "package.json");
  const currentPackageJson = existsSync3(currentPackageJsonPath) ? JSON.parse(readFileSync2(currentPackageJsonPath, "utf-8")) : null;
  const currentPackageDir = currentPackageJson?.name === packageName ? process.cwd() : null;
  const packageDir = currentPackageDir ?? resolve3(process.cwd(), "node_modules", packageName ?? "");
  const packageJsonPath = join2(packageDir, "package.json");
  if (!existsSync3(packageJsonPath))
    return null;
  try {
    const packageJson = currentPackageDir && currentPackageJson ? currentPackageJson : JSON.parse(readFileSync2(packageJsonPath, "utf-8"));
    const { exports } = packageJson;
    if (!exports)
      return null;
    const entry = exports[exportKey];
    if (!entry)
      return null;
    const importPath = resolveExportPath(entry, conditions);
    if (!importPath)
      return null;
    if (currentPackageDir && importPath.startsWith("./dist/")) {
      const sourceCandidate = resolve3(packageDir, importPath.replace(/^\.\/dist\//, "./src/"));
      if (existsSync3(sourceCandidate)) {
        return sourceCandidate;
      }
    }
    const resolved = resolve3(packageDir, importPath);
    return existsSync3(resolved) ? resolved : null;
  } catch {
    return null;
  }
};
var init_resolvePackageImport = () => {};

// src/constants.ts
var ANGULAR_INIT_TIMEOUT_MS = 500, ANSI_ESCAPE_LENGTH = 3, ASCII_SPACE = 32, BASE_36_RADIX = 36, BUN_BUILD_WARNING_SUPPRESSION = "wildcard sideEffects are not supported yet", BODY_SLICE_LENGTH = 2000, BYTES_PER_KILOBYTE = 1024, CLI_ARGS_OFFSET = 3, CSS_ERROR_RESOLVE_DELAY_MS = 50, CSS_MAX_CHECK_ATTEMPTS = 10, CSS_MAX_PARSE_TIMEOUT_MS = 500, CSS_SHEET_READY_TIMEOUT_MS = 100, DEFAULT_CHUNK_SIZE = 16384, DEFAULT_DEBOUNCE_MS = 15, DEFAULT_PORT = 3000, DEV_SERVER_RESTART_DEBOUNCE_MS = 100, DOM_UPDATE_DELAY_MS = 50, FILE_PROTOCOL_PREFIX_LENGTH = 7, FOCUS_ID_PREFIX_LENGTH = 3, FOCUS_IDX_PREFIX_LENGTH = 4, FOCUS_NAME_PREFIX_LENGTH = 5, HMR_UPDATE_TIMEOUT_MS = 2000, HOOK_SIGNATURE_LENGTH = 12, EXCLUDE_LAST_OFFSET = -1, HOURS_IN_DAY = 24, HOURS_IN_HALF_DAY = 12, MAX_ERROR_LENGTH = 200, MAX_RECONNECT_ATTEMPTS = 60, MILLISECONDS_IN_A_SECOND = 1000, MINUTES_IN_AN_HOUR = 60, SECONDS_IN_A_MINUTE = 60, MILLISECONDS_IN_A_MINUTE, MILLISECONDS_IN_A_DAY, OVERLAY_FADE_DURATION_MS = 150, PING_INTERVAL_MS = 30000, RAF_BATCH_COUNT = 3, RANDOM_ID_END_INDEX = 11, REBUILD_BATCH_DELAY_MS = 10, REBUILD_RELOAD_DELAY_MS = 200, RECONNECT_INITIAL_DELAY_MS = 500, RECONNECT_POLL_INTERVAL_MS = 300, SIGINT_EXIT_CODE = 130, SIGTERM_EXIT_CODE = 143, SVELTE_CSS_LOAD_TIMEOUT_MS = 500, TIME_PRECISION = 2, TWO_THIRDS, UNFOUND_INDEX = -1, WEBSOCKET_NORMAL_CLOSURE = 1000;
var init_constants = __esm(() => {
  MILLISECONDS_IN_A_MINUTE = MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE;
  MILLISECONDS_IN_A_DAY = MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE * MINUTES_IN_AN_HOUR * HOURS_IN_DAY;
  TWO_THIRDS = 2 / 3;
});

// src/svelte/lowerIslandSyntax.ts
var ISLAND_TAG_RE, extractBracedExpression = (text, braceStart) => {
  let depth = 0;
  for (let index = braceStart;index < text.length; index += 1) {
    const char = text[index];
    if (char === "{")
      depth += 1;
    if (char === "}")
      depth -= 1;
    if (depth === 0) {
      return text.slice(braceStart + 1, index).trim();
    }
  }
  return null;
}, extractIslandAttribute = (attributeString, name) => {
  const quotedMatch = attributeString.match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']+)["']`));
  if (quotedMatch?.[1]) {
    return { expression: JSON.stringify(quotedMatch[1]), found: true };
  }
  const attributeIndex = attributeString.search(new RegExp(`\\b${name}\\s*=\\s*\\{`));
  if (attributeIndex < 0) {
    return { expression: "", found: false };
  }
  const braceStart = attributeString.indexOf("{", attributeIndex);
  if (braceStart < 0) {
    return { expression: "", found: false };
  }
  const expression = extractBracedExpression(attributeString, braceStart);
  if (expression === null) {
    return { expression: "", found: false };
  }
  return { expression, found: true };
}, lowerSvelteIslandSyntax = (source, _mode = "server") => {
  if (!source.includes("<Island")) {
    return { code: source, transformed: false };
  }
  let islandIndex = 0;
  const transformedMarkup = source.replace(ISLAND_TAG_RE, (fullMatch, attributeString) => {
    const framework = extractIslandAttribute(attributeString, "framework");
    const component = extractIslandAttribute(attributeString, "component");
    if (!framework.found || !component.found) {
      return fullMatch;
    }
    const hydrate = extractIslandAttribute(attributeString, "hydrate");
    const props = extractIslandAttribute(attributeString, "props");
    const slotId = `absolute-svelte-island-${islandIndex.toString(BASE_36_RADIX)}`;
    islandIndex += 1;
    const resolveExpression = `await __absoluteResolveIslandHtml(${JSON.stringify(slotId)}, { component: ${component.expression}, framework: ${framework.expression}, hydrate: ${hydrate.found ? hydrate.expression : JSON.stringify("load")}, props: ${props.found ? props.expression : "{}"} })`;
    return `<div data-absolute-island-slot="${slotId}" style="display: contents">{@html ${resolveExpression}}</div>`;
  });
  const importLine = 'import { resolveIslandHtml as __absoluteResolveIslandHtml } from "@absolutejs/absolute/svelte";';
  if (transformedMarkup.includes("<script")) {
    return {
      code: transformedMarkup.replace(/<script(\s[^>]*)?>/, (match) => `${match}
${importLine}
`),
      transformed: true
    };
  }
  return {
    code: `<script lang="ts">
${importLine}
</script>
${transformedMarkup}`,
    transformed: true
  };
};
var init_lowerIslandSyntax = __esm(() => {
  init_constants();
  ISLAND_TAG_RE = /<Island\b([\s\S]*?)\/>/g;
});

// src/svelte/lowerAwaitSlotSyntax.ts
var AWAIT_BLOCK_RE, escapeTemplateLiteral = (value) => value.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${"), markupToTemplateLiteral = (markup) => {
  const escaped = escapeTemplateLiteral(markup.trim());
  const withExpressions = escaped.replace(/\{([^{}]+)\}/g, (_, expression) => `\${${String(expression).trim()}}`);
  return `\`${withExpressions}\``;
}, lowerSvelteAwaitSlotSyntax = (source) => {
  if (!source.includes("{#await")) {
    return { code: source, transformed: false };
  }
  let awaitIndex = 0;
  let transformed = false;
  const lowered = source.replace(AWAIT_BLOCK_RE, (fullMatch, awaitExpression, pendingMarkup, thenIdentifier, thenMarkup, catchIdentifier, catchMarkup) => {
    const trimmedAwaitExpression = awaitExpression.trim();
    if (!trimmedAwaitExpression) {
      return fullMatch;
    }
    const slotId = `absolute-svelte-await-${awaitIndex.toString(BASE_36_RADIX)}`;
    awaitIndex += 1;
    transformed = true;
    const thenValueIdentifier = thenIdentifier?.trim() || "__awaitValue";
    const catchValueIdentifier = catchIdentifier?.trim() || "__awaitError";
    const fallbackHtml = markupToTemplateLiteral(pendingMarkup);
    const resolvedHtml = markupToTemplateLiteral(thenMarkup);
    const rejectedHtml = typeof catchMarkup === "string" ? markupToTemplateLiteral(catchMarkup) : null;
    const catchBranch = rejectedHtml ? `catch (${catchValueIdentifier}) { return ${rejectedHtml}; }` : "catch (_absoluteAwaitError) { throw _absoluteAwaitError; }";
    return `<AbsoluteAwaitSlot id="${slotId}" fallbackHtml={${fallbackHtml}} resolve={async () => { try { const ${thenValueIdentifier} = await (${trimmedAwaitExpression}); return ${resolvedHtml}; } ${catchBranch} }} />`;
  });
  if (!transformed) {
    return { code: source, transformed: false };
  }
  const importLine = 'import AbsoluteAwaitSlot from "@absolutejs/absolute/svelte/components/AwaitSlot.svelte";';
  if (lowered.includes("<script")) {
    return {
      code: lowered.replace(/<script(\s[^>]*)?>/, (match) => `${match}
${importLine}
`),
      transformed: true
    };
  }
  return {
    code: `<script lang="ts">
${importLine}
</script>
${lowered}`,
    transformed: true
  };
};
var init_lowerAwaitSlotSyntax = __esm(() => {
  init_constants();
  AWAIT_BLOCK_RE = /\{#await\s+([^}]+)\}([\s\S]*?)\{:then(?:\s+([A-Za-z_$][\w$]*))?\}([\s\S]*?)(?:\{:catch(?:\s+([A-Za-z_$][\w$]*))?\}([\s\S]*?))?\{\/await\}/g;
});

// src/core/svelteServerModule.ts
import { mkdir, readdir } from "fs/promises";
import { basename as basename2, dirname as dirname2, extname, join as join3, relative, resolve as resolve4 } from "path";
var serverCacheRoot, compiledModuleCache, originalSourcePathCache, transpiler, ensureRelativeImportPath = (from, target) => {
  const importPath = relative(dirname2(from), target).replace(/\\/g, "/");
  return importPath.startsWith(".") ? importPath : `./${importPath}`;
}, processDirectoryEntries = (entries, dir, targetFileName, stack) => {
  for (const entry of entries) {
    const entryPath = join3(dir, entry.name);
    if (entry.isDirectory())
      stack.push(entryPath);
    if (entry.isFile() && entry.name === targetFileName) {
      return entryPath;
    }
  }
  return null;
}, searchDirectoryLevel = async (dirs, targetFileName) => {
  if (dirs.length === 0)
    return null;
  const nextStack = [];
  const dirEntries = await Promise.all(dirs.map(async (dir) => ({
    dir,
    entries: await readdir(dir, {
      encoding: "utf-8",
      withFileTypes: true
    })
  })));
  for (const { dir, entries } of dirEntries) {
    const found = processDirectoryEntries(entries, dir, targetFileName, nextStack);
    if (found)
      return found;
  }
  return searchDirectoryLevel(nextStack, targetFileName);
}, findSourceFileByBasename = async (searchRoot, targetFileName) => searchDirectoryLevel([searchRoot], targetFileName), normalizeBuiltSvelteFileName = (sourcePath) => basename2(sourcePath).replace(/-[a-z0-9]{6,}(?=\.svelte$)/i, ""), resolveOriginalSourcePath = async (sourcePath) => {
  const cachedPath = originalSourcePathCache.get(sourcePath);
  if (cachedPath !== undefined) {
    return cachedPath;
  }
  if (!sourcePath.includes(`${join3(process.cwd(), "build")}${process.platform === "win32" ? "" : "/"}`) && !sourcePath.includes("/build/")) {
    originalSourcePathCache.set(sourcePath, sourcePath);
    return sourcePath;
  }
  const resolvedSourcePath = await findSourceFileByBasename(join3(process.cwd(), "src"), normalizeBuiltSvelteFileName(sourcePath));
  const nextPath = resolvedSourcePath ?? sourcePath;
  originalSourcePathCache.set(sourcePath, nextPath);
  return nextPath;
}, resolveRelativeModule = async (spec, from) => {
  if (!spec.startsWith(".")) {
    return null;
  }
  const basePath = resolve4(dirname2(from), spec);
  const candidates = [
    basePath,
    `${basePath}.ts`,
    `${basePath}.js`,
    `${basePath}.mjs`,
    `${basePath}.cjs`,
    `${basePath}.json`,
    join3(basePath, "index.ts"),
    join3(basePath, "index.js"),
    join3(basePath, "index.mjs"),
    join3(basePath, "index.cjs"),
    join3(basePath, "index.json")
  ];
  const existResults = await Promise.all(candidates.map((candidate) => Bun.file(candidate).exists()));
  const foundIndex = existResults.indexOf(true);
  return foundIndex >= 0 ? candidates[foundIndex] ?? null : null;
}, getCachedModulePath = (sourcePath) => {
  const relativeSourcePath = relative(process.cwd(), sourcePath).replace(/\\/g, "/");
  const normalizedSourcePath = relativeSourcePath.startsWith("..") ? sourcePath.replace(/[:\\/]/g, "_") : relativeSourcePath;
  return join3(serverCacheRoot, `${normalizedSourcePath}.server.js`);
}, resolveSvelteImport = async (spec, from) => {
  if (!spec.startsWith(".") && !spec.startsWith("/")) {
    const resolved = resolvePackageImport(spec);
    return resolved && resolved.endsWith(".svelte") ? resolved : null;
  }
  if (spec.startsWith("/")) {
    return spec;
  }
  if (!spec.startsWith(".")) {
    return null;
  }
  const explicitPath = resolve4(dirname2(from), spec);
  if (extname(explicitPath) === ".svelte") {
    return explicitPath;
  }
  const candidate = `${explicitPath}.svelte`;
  if (await Bun.file(candidate).exists() === true) {
    return candidate;
  }
  return null;
}, writeIfChanged = async (path, content) => {
  const targetFile = Bun.file(path);
  const exists = await targetFile.exists();
  if (exists) {
    const currentContent = await targetFile.text();
    if (currentContent === content) {
      return;
    }
  }
  await Bun.write(path, content);
}, compileSvelteServerModule = async (sourcePath) => {
  const cachedModulePath = compiledModuleCache.get(sourcePath);
  if (cachedModulePath) {
    return cachedModulePath;
  }
  const resolutionSourcePath = await resolveOriginalSourcePath(sourcePath);
  const source = await Bun.file(sourcePath).text();
  const { compile, preprocess } = await import("svelte/compiler");
  const loweredAwaitSource = lowerSvelteAwaitSlotSyntax(source);
  const loweredSource = lowerSvelteIslandSyntax(loweredAwaitSource.code, "server");
  const preprocessed = await preprocess(loweredSource.code, {});
  let transpiled = sourcePath.endsWith(".ts") || sourcePath.endsWith(".svelte.ts") ? transpiler.transformSync(preprocessed.code) : preprocessed.code;
  const childImportSpecs = Array.from(transpiled.matchAll(/from\s+['"]([^'"]+)['"]/g)).map((match) => match[1]).filter((value) => value !== undefined);
  const resolvedChildModules = await Promise.all(childImportSpecs.map((spec) => resolveSvelteImport(spec, resolutionSourcePath)));
  const resolvedModuleImports = await Promise.all(childImportSpecs.map((spec) => resolveRelativeModule(spec, resolutionSourcePath)));
  const childModulePaths = new Map;
  const rewrittenModulePaths = new Map;
  const compiledChildren = await Promise.all(childImportSpecs.map(async (spec, index) => {
    const resolvedChild = resolvedChildModules[index];
    if (!spec || !resolvedChild)
      return null;
    return {
      compiledPath: await compileSvelteServerModule(resolvedChild),
      resolvedChild,
      spec
    };
  }));
  for (const result of compiledChildren) {
    if (!result)
      continue;
    childModulePaths.set(result.spec, result.compiledPath);
    childModulePaths.set(result.resolvedChild, result.compiledPath);
  }
  for (let index = 0;index < childImportSpecs.length; index += 1) {
    const spec = childImportSpecs[index];
    const resolvedModuleImport = resolvedModuleImports[index];
    if (!spec || !resolvedModuleImport)
      continue;
    if (resolvedChildModules[index])
      continue;
    rewrittenModulePaths.set(spec, ensureRelativeImportPath(getCachedModulePath(sourcePath), resolvedModuleImport));
  }
  for (const [spec, resolvedModuleImport] of rewrittenModulePaths) {
    transpiled = transpiled.replaceAll(spec, resolvedModuleImport);
  }
  let compiledCode = compile(transpiled, {
    css: "injected",
    experimental: {
      async: loweredAwaitSource.transformed || loweredSource.transformed
    },
    filename: resolutionSourcePath,
    generate: "server"
  }).js.code;
  for (const [spec, compiledChildPath] of childModulePaths) {
    compiledCode = compiledCode.replaceAll(spec, ensureRelativeImportPath(getCachedModulePath(sourcePath), compiledChildPath));
  }
  for (const [spec, resolvedModuleImport] of rewrittenModulePaths) {
    compiledCode = compiledCode.replaceAll(spec, resolvedModuleImport);
  }
  const compiledModulePath = getCachedModulePath(sourcePath);
  await mkdir(dirname2(compiledModulePath), { recursive: true });
  await writeIfChanged(compiledModulePath, compiledCode);
  compiledModuleCache.set(sourcePath, compiledModulePath);
  return compiledModulePath;
};
var init_svelteServerModule = __esm(() => {
  init_resolvePackageImport();
  init_lowerIslandSyntax();
  init_lowerAwaitSlotSyntax();
  serverCacheRoot = join3(process.cwd(), ".absolutejs", "islands", "svelte");
  compiledModuleCache = new Map;
  originalSourcePathCache = new Map;
  transpiler = new Bun.Transpiler({
    loader: "ts",
    target: "browser"
  });
});

// src/core/renderIslandMarkup.ts
var islandSequence = 0, resolvedServerComponentCache, resolvedServerBuildComponentCache, nextIslandId = () => {
  islandSequence += 1;
  return `island-${islandSequence}`;
}, isRecord2 = (value) => typeof value === "object" && value !== null, isReactServerIslandComponent = (value) => typeof value === "function", isSvelteServerIslandComponent = (value) => typeof value === "function", isVueServerIslandComponent = (value) => typeof value === "function" || isRecord2(value), isAngularServerIslandComponent = (value) => typeof value === "function", resolveBuildReferencePath = (source, registryPath) => {
  if (source.startsWith("file://"))
    return new URL(source).pathname;
  if (source.startsWith("."))
    return new URL(source, registryPath).pathname;
  return source;
}, loadAndCompileServerBuildComponent = async (buildReferencePath) => {
  const compiledModulePath = await compileSvelteServerModule(buildReferencePath);
  const loadedModule = await import(compiledModulePath);
  return "default" in loadedModule ? loadedModule.default : loadedModule;
}, loadServerBuildComponent = async (buildReferencePath) => {
  const cachedBuildComponent = resolvedServerBuildComponentCache.get(buildReferencePath);
  if (cachedBuildComponent) {
    return cachedBuildComponent;
  }
  const loadPromise = loadAndCompileServerBuildComponent(buildReferencePath);
  resolvedServerBuildComponentCache.set(buildReferencePath, loadPromise);
  return loadPromise;
}, loadServerImportComponent = async (resolvedComponent) => {
  const resolvedModulePath = resolvedComponent.startsWith(".") ? new URL(resolvedComponent, import.meta.url).pathname : resolvedComponent;
  const importTarget = resolvedModulePath.endsWith(".svelte") ? await compileSvelteServerModule(resolvedModulePath) : resolvedModulePath;
  const loadedModule = await import(importTarget);
  return "default" in loadedModule ? loadedModule.default : loadedModule;
}, resolveIslandComponent = async (component) => {
  const buildReference = getIslandBuildReference(component);
  const buildReferencePath = buildReference?.source ? resolveBuildReferencePath(buildReference.source, import.meta.url) : null;
  if (buildReferencePath?.endsWith(".svelte")) {
    return loadServerBuildComponent(buildReferencePath);
  }
  const resolvedComponent = getIslandComponent(component);
  if (typeof resolvedComponent !== "string") {
    return resolvedComponent;
  }
  return loadServerImportComponent(resolvedComponent);
}, resolveServerIslandComponent = async (component) => {
  const cachedResolvedComponent = resolvedServerComponentCache.get(component);
  if (cachedResolvedComponent) {
    return cachedResolvedComponent;
  }
  const resolutionPromise = resolveIslandComponent(component);
  resolvedServerComponentCache.set(component, resolutionPromise);
  return resolutionPromise;
}, resolveReactServerIslandComponent = async (component) => {
  const resolvedComponent = await resolveServerIslandComponent(component);
  if (!isReactServerIslandComponent(resolvedComponent)) {
    throw new Error("Resolved React island is not a valid React component.");
  }
  return resolvedComponent;
}, resolveSvelteServerIslandComponent = async (component) => {
  const resolvedComponent = await resolveServerIslandComponent(component);
  if (!isSvelteServerIslandComponent(resolvedComponent)) {
    throw new Error("Resolved Svelte island is not a valid Svelte component.");
  }
  return resolvedComponent;
}, resolveVueServerIslandComponent = async (component) => {
  const resolvedComponent = await resolveServerIslandComponent(component);
  if (!isVueServerIslandComponent(resolvedComponent)) {
    throw new Error("Resolved Vue island is not a valid Vue component.");
  }
  return resolvedComponent;
}, resolveAngularServerIslandComponent = async (component) => {
  const resolvedComponent = await resolveServerIslandComponent(component);
  if (!isAngularServerIslandComponent(resolvedComponent)) {
    throw new Error("Resolved Angular island is not a valid Angular component.");
  }
  return resolvedComponent;
}, renderIslandMarkup = async (registry, props) => {
  const result = await renderIslandResult(registry, props);
  return `<div ${serializeIslandAttributes(result.attributes)}>${result.html}</div>`;
}, renderIslandResult = async (registry, props) => {
  const islandId = nextIslandId();
  const attributes = getIslandMarkerAttributes(props);
  if (props.framework === "react") {
    const entry = registry.react?.[props.component];
    if (!entry) {
      throw new Error(`Island component "${props.component}" is not registered for framework "react".`);
    }
    const component = await resolveReactServerIslandComponent(entry);
    const html = renderReactIslandToHtml(component, props.props);
    return { attributes, html };
  }
  if (props.framework === "svelte") {
    const entry = registry.svelte?.[props.component];
    if (!entry) {
      throw new Error(`Island component "${props.component}" is not registered for framework "svelte".`);
    }
    const component = await resolveSvelteServerIslandComponent(entry);
    const html = renderSvelteIslandToHtml(component, props.props);
    return { attributes, html };
  }
  if (props.framework === "vue") {
    const entry = registry.vue?.[props.component];
    if (!entry) {
      throw new Error(`Island component "${props.component}" is not registered for framework "vue".`);
    }
    const component = await resolveVueServerIslandComponent(entry);
    const html = await renderVueIslandToHtml(component, props.props);
    return { attributes, html };
  }
  if (props.framework === "angular") {
    const entry = registry.angular?.[props.component];
    if (!entry) {
      throw new Error(`Island component "${props.component}" is not registered for framework "angular".`);
    }
    const component = await resolveAngularServerIslandComponent(entry);
    const html = await renderAngularIslandToHtml(component, props.props, islandId);
    return {
      attributes: {
        ...getIslandMarkerAttributes(props, islandId)
      },
      html
    };
  }
  throw new Error(`Framework "${props.framework}" is not implemented in this prototype.`);
};
var init_renderIslandMarkup = __esm(() => {
  init_islandSsr();
  init_svelteServerModule();
  init_islandMarkupAttributes();
  init_islands();
  resolvedServerComponentCache = new Map;
  resolvedServerBuildComponentCache = new Map;
});

// src/core/streamingSlotRegistrar.ts
var STREAMING_SLOT_REGISTRAR_KEY = Symbol.for("absolutejs.streamingSlotRegistrar");
var getRegistrarGlobal = () => globalThis;
var setStreamingSlotRegistrar = (nextRegistrar) => {
  getRegistrarGlobal()[STREAMING_SLOT_REGISTRAR_KEY] = nextRegistrar;
};
var registerStreamingSlot = (slot) => {
  getRegistrarGlobal()[STREAMING_SLOT_REGISTRAR_KEY]?.(slot);
};

// src/core/streamingSlotRegistry.ts
var STREAMING_SLOT_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotAsyncLocalStorage");
var getStorageGlobal = () => globalThis;
var isServerRuntime = () => typeof process !== "undefined" && typeof process.versions?.node === "string";
var ensureAsyncLocalStorage = async () => {
  const storageGlobal = getStorageGlobal();
  if (typeof storageGlobal[STREAMING_SLOT_STORAGE_KEY] !== "undefined") {
    return storageGlobal[STREAMING_SLOT_STORAGE_KEY];
  }
  if (!isServerRuntime()) {
    storageGlobal[STREAMING_SLOT_STORAGE_KEY] = null;
    return storageGlobal[STREAMING_SLOT_STORAGE_KEY];
  }
  const mod = await import("async_hooks");
  storageGlobal[STREAMING_SLOT_STORAGE_KEY] = new mod.AsyncLocalStorage;
  return storageGlobal[STREAMING_SLOT_STORAGE_KEY];
};
var registerStreamingSlot2 = (slot) => {
  const storage = getStorageGlobal()[STREAMING_SLOT_STORAGE_KEY];
  if (!storage)
    return;
  const store = storage.getStore();
  if (!store)
    return;
  store.set(slot.id, slot);
};
setStreamingSlotRegistrar(registerStreamingSlot2);
var runWithStreamingSlotRegistry = async (task) => {
  const storage = await ensureAsyncLocalStorage();
  if (!storage) {
    return {
      result: await task(),
      slots: []
    };
  }
  return storage.run(new Map, async () => {
    const result = await task();
    const store = storage.getStore();
    return {
      result,
      slots: store ? [...store.values()] : []
    };
  });
};

// src/client/streamSwap.ts
var streamSwapRuntime = () => {
  const SLOT_PATCH_EVENT = "absolutejs:slot-patch";
  if (window.__ABS_SLOT_RUNTIME__ === true)
    return;
  window.__ABS_SLOT_RUNTIME__ = true;
  window.__ABS_SLOT_CONSUMERS__ = window.__ABS_SLOT_CONSUMERS__ ?? {};
  window.__ABS_SLOT_PENDING__ = window.__ABS_SLOT_PENDING__ ?? {};
  const consumers = window.__ABS_SLOT_CONSUMERS__;
  const pending = window.__ABS_SLOT_PENDING__;
  const canApplyImmediately = () => window.__ABS_SLOT_HYDRATION_PENDING__ !== true;
  const apply = (id, html) => {
    if (!canApplyImmediately()) {
      pending[id] = html;
      return;
    }
    const consumer = consumers[id];
    if (typeof consumer === "function") {
      const handled = consumer(html);
      if (handled !== false) {
        delete pending[id];
        return;
      }
    }
    const node = document.getElementById(`slot-${id}`);
    if (!node) {
      pending[id] = html;
      return;
    }
    node.innerHTML = html;
    window.dispatchEvent(new CustomEvent(SLOT_PATCH_EVENT, {
      detail: { html, id }
    }));
    delete pending[id];
  };
  const flush = () => {
    for (const id in pending) {
      if (!Object.prototype.hasOwnProperty.call(pending, id))
        continue;
      apply(id, pending[id] ?? "");
    }
  };
  window.__ABS_SLOT_FLUSH__ = flush;
  window.__ABS_SLOT_ENQUEUE__ = (id, html) => {
    apply(id, html);
  };
  if (typeof MutationObserver === "function") {
    const observer = new MutationObserver(flush);
    const root = document.documentElement ?? document.body ?? document;
    observer.observe(root, { childList: true, subtree: true });
  }
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", flush, { once: true });
  }
  flush();
};
var stripFunctionWrapper = (value) => {
  const start = value.indexOf("{");
  const end = value.lastIndexOf("}");
  if (start < 0 || end <= start)
    return "";
  return value.slice(start + 1, end);
};
var getStreamSwapRuntimeScript = () => `(function(){${stripFunctionWrapper(streamSwapRuntime.toString())}})();`;

// src/utils/streamingSlots.ts
init_escapeScriptContent();
var SLOT_ID_PREFIX = "abs-slot-";
var SLOT_PLACEHOLDER_PREFIX = "slot-";
var CLOSING_BODY_TAG = "</body>";
var CLOSING_HEAD_TAG = "</head>";
var CLOSING_BODY_TAG_LENGTH = CLOSING_BODY_TAG.length;
var CLOSING_HEAD_TAG_LENGTH = CLOSING_HEAD_TAG.length;
var CLOSING_PAGE_TAG_REGEX = /<\/body>\s*<\/html>\s*$/i;
var STREAMING_RUNTIME_GLOBAL = "__ABS_SLOT_ENQUEUE__";
var STREAMING_PENDING_GLOBAL = "__ABS_SLOT_PENDING__";
var STREAM_TAIL_LOOKBEHIND = 128;
var STREAMING_SLOT_TIMEOUT_MS = 5000;
var STREAMING_SLOT_MAX_PER_RESPONSE = 128;
var STREAMING_SLOT_MAX_HTML_BYTES = 64000;
var createSlotPlaceholderId = (id) => `${SLOT_PLACEHOLDER_PREFIX}${id}`;
var createSlotPatchStatement = (id, html) => `(window.${STREAMING_RUNTIME_GLOBAL}||function(i,h){window.${STREAMING_PENDING_GLOBAL}=window.${STREAMING_PENDING_GLOBAL}||{};window.${STREAMING_PENDING_GLOBAL}[i]=h;})(${JSON.stringify(id)},${JSON.stringify(html)});`;
var createNonceAttr = (nonce) => nonce ? ` nonce="${nonce}"` : "";
var createStreamingSlotId = () => `${SLOT_ID_PREFIX}${Math.random().toString(36).slice(2, 10)}`;
var getStreamingSlotsRuntimeScript = () => getStreamSwapRuntimeScript();
var renderStreamingSlotsRuntimeTag = (nonce) => `<script${createNonceAttr(nonce)}>${escapeScriptContent(getStreamingSlotsRuntimeScript())}</script>`;
var renderStreamingSlotPlaceholder = (id, fallbackHtml = "") => `<div id="${createSlotPlaceholderId(id)}" data-absolute-slot="true">${fallbackHtml}</div>`;
var renderStreamingSlotPatchTag = (id, html, nonce) => `<script${createNonceAttr(nonce)}>${escapeScriptContent(createSlotPatchStatement(id, html))}</script>`;
var injectHtmlIntoHead = (html, injection) => {
  const closingHeadIndex = html.indexOf(CLOSING_HEAD_TAG);
  if (closingHeadIndex >= 0) {
    return `${html.slice(0, closingHeadIndex)}${injection}${html.slice(closingHeadIndex)}`;
  }
  return `${html}${injection}`;
};
var injectHtmlIntoBody = (html, injection) => {
  const closingBodyIndex = html.indexOf(CLOSING_BODY_TAG);
  if (closingBodyIndex >= 0) {
    return `${html.slice(0, closingBodyIndex)}${injection}${html.slice(closingBodyIndex)}`;
  }
  return `${html}${injection}`;
};
var toUint8 = (value, encoder) => encoder.encode(value);
var normalizeSafeHtml = (value) => {
  const candidate = value;
  if (candidate && typeof candidate.changingThisBreaksApplicationSecurity === "string") {
    return candidate.changingThisBreaksApplicationSecurity;
  }
  return value;
};
var currentStreamingSlotPolicy = {
  timeoutMs: STREAMING_SLOT_TIMEOUT_MS,
  fallbackHtml: "",
  errorHtml: undefined,
  maxSlotsPerResponse: STREAMING_SLOT_MAX_PER_RESPONSE,
  maxSlotHtmlSizeBytes: STREAMING_SLOT_MAX_HTML_BYTES
};
var clonePolicy = (policy) => ({
  ...policy
});
var normalizeSlotBytes = (value, fallback) => {
  if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
    return Math.floor(value);
  }
  return fallback;
};
var normalizeSlotText = (value, fallback) => typeof normalizeSafeHtml(value) === "string" ? normalizeSafeHtml(value) : fallback;
var normalizeSlotError = (value, fallback = undefined) => {
  const safeValue = normalizeSafeHtml(value);
  if (typeof safeValue === "string")
    return safeValue;
  return fallback;
};
var hasPolicyValue = (policy, key) => Object.prototype.hasOwnProperty.call(policy, key);
var applyStreamingSlotPolicyOverrides = (base, overridePolicy = {}) => ({
  timeoutMs: hasPolicyValue(overridePolicy, "timeoutMs") ? normalizeSlotBytes(overridePolicy.timeoutMs, base.timeoutMs) : base.timeoutMs,
  fallbackHtml: hasPolicyValue(overridePolicy, "fallbackHtml") ? normalizeSlotText(overridePolicy.fallbackHtml, "") : base.fallbackHtml,
  errorHtml: hasPolicyValue(overridePolicy, "errorHtml") ? normalizeSlotError(overridePolicy.errorHtml) : base.errorHtml,
  maxSlotsPerResponse: hasPolicyValue(overridePolicy, "maxSlotsPerResponse") ? normalizeSlotBytes(overridePolicy.maxSlotsPerResponse, base.maxSlotsPerResponse) : base.maxSlotsPerResponse,
  maxSlotHtmlSizeBytes: hasPolicyValue(overridePolicy, "maxSlotHtmlSizeBytes") ? normalizeSlotBytes(overridePolicy.maxSlotHtmlSizeBytes, base.maxSlotHtmlSizeBytes) : base.maxSlotHtmlSizeBytes,
  onError: hasPolicyValue(overridePolicy, "onError") ? overridePolicy.onError : base.onError,
  onSlotMetric: hasPolicyValue(overridePolicy, "onSlotMetric") ? overridePolicy.onSlotMetric : base.onSlotMetric
});
var createCombinedSlotErrorHandler = (policyOnError, enhancerOnError) => {
  if (!policyOnError && !enhancerOnError)
    return;
  return (error, slot) => {
    policyOnError?.(error, slot);
    enhancerOnError?.(error, slot);
  };
};
var createCombinedSlotMetricHandler = (policyOnSlotMetric, callOnSlotMetric) => {
  if (!policyOnSlotMetric && !callOnSlotMetric)
    return;
  return (metric) => {
    policyOnSlotMetric?.(metric);
    callOnSlotMetric?.(metric);
  };
};
var resolveStreamingSlotPolicy = (overridePolicy = {}) => {
  const base = getStreamingSlotPolicy();
  return applyStreamingSlotPolicyOverrides(base, overridePolicy);
};
var getStreamingSlotPolicy = () => clonePolicy(currentStreamingSlotPolicy);
var setStreamingSlotPolicy = (policy = {}) => {
  const base = getStreamingSlotPolicy();
  currentStreamingSlotPolicy = applyStreamingSlotPolicyOverrides(base, policy);
};
var withStreamingSlotPolicy = async (policy, callback) => {
  const previous = getStreamingSlotPolicy();
  setStreamingSlotPolicy(policy);
  try {
    return await callback();
  } finally {
    currentStreamingSlotPolicy = previous;
  }
};
var emitSlotMetric = (metric, onSlotMetric) => {
  onSlotMetric?.(metric);
};
var createTimeoutError = (slot, timeoutMs) => {
  const error = new Error(`Streaming slot "${slot.id}" timed out after ${timeoutMs}ms`);
  error.__absTimeout = true;
  return error;
};
var toStreamingSlot = (slot, policy) => ({
  errorHtml: slot.errorHtml === undefined ? policy.errorHtml : slot.errorHtml,
  fallbackHtml: normalizeSlotText(slot.fallbackHtml, policy.fallbackHtml),
  id: slot.id ?? createStreamingSlotId(),
  timeoutMs: normalizeSlotBytes(slot.timeoutMs, policy.timeoutMs),
  resolve: slot.resolve
});
var prepareSlots = ({
  policy,
  slots,
  onError,
  onSlotMetric
}) => {
  const preparedSlots = slots.map((slot) => toStreamingSlot(slot, policy));
  const maxSlotsPerResponse = policy.maxSlotsPerResponse;
  if (maxSlotsPerResponse === 0) {
    const error = new Error("Streaming slot limit is set to 0");
    for (const slot of preparedSlots) {
      onError?.(error, slot);
      emitSlotMetric({
        type: "dropped",
        slotId: slot.id,
        reason: "maxSlotsPerResponse is 0"
      }, onSlotMetric);
    }
    return [];
  }
  if (preparedSlots.length <= maxSlotsPerResponse) {
    preparedSlots.forEach((slot) => emitSlotMetric({
      type: "prepared",
      slotId: slot.id
    }, onSlotMetric));
    return preparedSlots;
  }
  const keptSlots = preparedSlots.slice(0, maxSlotsPerResponse);
  const droppedSlots = preparedSlots.slice(maxSlotsPerResponse);
  droppedSlots.forEach((slot) => {
    onError?.(new Error(`Streaming slot "${slot.id}" dropped because ${maxSlotsPerResponse} slots is the configured maximum`), slot);
    emitSlotMetric({
      type: "dropped",
      slotId: slot.id,
      reason: `maxSlotsPerResponse is ${maxSlotsPerResponse}`
    }, onSlotMetric);
  });
  keptSlots.forEach((slot) => emitSlotMetric({
    type: "prepared",
    slotId: slot.id
  }, onSlotMetric));
  return keptSlots;
};
var htmlByteLength = (value, encoder) => encoder.encode(value).length;
var resolveSlot = async (slot, onError, policy, onSlotMetric) => {
  const safePolicy = policy ?? getStreamingSlotPolicy();
  const encoder = new TextEncoder;
  const start = Date.now();
  try {
    const maybeAsyncValue = Promise.resolve(slot.resolve());
    const resolved = typeof slot.timeoutMs === "number" && slot.timeoutMs > 0 ? await Promise.race([
      maybeAsyncValue,
      new Promise((_, reject) => setTimeout(() => {
        reject(createTimeoutError(slot, slot.timeoutMs ?? 0));
      }, slot.timeoutMs))
    ]) : await maybeAsyncValue;
    const safeResolved = normalizeSafeHtml(resolved);
    const html = typeof safeResolved === "string" ? safeResolved : `${safeResolved}`;
    if (safePolicy.maxSlotHtmlSizeBytes > 0 && htmlByteLength(html, encoder) > safePolicy.maxSlotHtmlSizeBytes) {
      const bytes2 = htmlByteLength(html, encoder);
      const error = new Error(`Streaming slot "${slot.id}" exceeded max payload size of ${safePolicy.maxSlotHtmlSizeBytes} bytes`);
      const durationMs2 = Date.now() - start;
      onError?.(error, slot);
      emitSlotMetric({
        type: "size_exceeded",
        slotId: slot.id,
        durationMs: durationMs2,
        bytes: bytes2,
        error
      }, onSlotMetric);
      const fallbackHtml = normalizeSlotError(slot.errorHtml, undefined);
      return {
        html: fallbackHtml === undefined ? null : fallbackHtml,
        id: slot.id,
        durationMs: durationMs2,
        bytes: fallbackHtml === undefined ? 0 : htmlByteLength(fallbackHtml, encoder)
      };
    }
    const durationMs = Date.now() - start;
    const bytes = htmlByteLength(html, encoder);
    emitSlotMetric({
      type: "resolved",
      slotId: slot.id,
      durationMs,
      bytes
    }, onSlotMetric);
    return {
      html,
      id: slot.id,
      durationMs,
      bytes
    };
  } catch (error) {
    const durationMs = Date.now() - start;
    onError?.(error, slot);
    emitSlotMetric({
      type: error?.__absTimeout === true ? "timeout" : "error",
      slotId: slot.id,
      durationMs,
      error
    }, onSlotMetric);
    const html = normalizeSlotError(slot.errorHtml, undefined);
    if (html) {
      return {
        html,
        id: slot.id,
        durationMs,
        bytes: htmlByteLength(html, encoder)
      };
    }
    return {
      html: null,
      id: slot.id,
      durationMs,
      bytes: 0
    };
  }
};
var nextResolvedSlot = async (pending) => {
  const wrapped = pending.map((promise) => promise.then((result) => ({
    original: promise,
    result
  })));
  return Promise.race(wrapped);
};
var streamChunkToString = (value, decoder) => typeof value === "string" ? value : decoder.decode(value, { stream: true });
var streamOutOfOrderSlots = ({
  footerHtml = "",
  headerHtml = "",
  nonce,
  policy,
  onSlotMetric,
  onError,
  slots
}) => {
  const resolvedPolicy = resolveStreamingSlotPolicy(policy);
  const combinedOnError = createCombinedSlotErrorHandler(resolvedPolicy.onError, onError);
  const combinedOnSlotMetric = createCombinedSlotMetricHandler(resolvedPolicy.onSlotMetric, onSlotMetric);
  const effectivePolicy = {
    ...resolvedPolicy,
    onSlotMetric: combinedOnSlotMetric
  };
  const preparedSlots = prepareSlots({
    policy: effectivePolicy,
    slots,
    onError: combinedOnError,
    onSlotMetric: combinedOnSlotMetric
  });
  const encoder = new TextEncoder;
  return new ReadableStream({
    async start(controller) {
      try {
        let header = headerHtml;
        if (preparedSlots.length > 0 && !header.includes(STREAMING_RUNTIME_GLOBAL)) {
          header = injectHtmlIntoHead(header, renderStreamingSlotsRuntimeTag(nonce));
        }
        controller.enqueue(toUint8(header, encoder));
        const pending = preparedSlots.map((slot) => {
          const fallback = renderStreamingSlotPlaceholder(slot.id, slot.fallbackHtml ?? "");
          controller.enqueue(toUint8(fallback, encoder));
          return resolveSlot(slot, combinedOnError, effectivePolicy, combinedOnSlotMetric);
        });
        while (pending.length > 0) {
          const { original, result } = await nextResolvedSlot(pending);
          const index = pending.indexOf(original);
          if (index >= 0)
            pending.splice(index, 1);
          if (result.html === null)
            continue;
          emitSlotMetric({
            type: "patched",
            slotId: result.id,
            durationMs: result.durationMs,
            bytes: result.bytes
          }, combinedOnSlotMetric);
          controller.enqueue(toUint8(renderStreamingSlotPatchTag(result.id, result.html, nonce), encoder));
        }
        if (footerHtml.length > 0) {
          controller.enqueue(toUint8(footerHtml, encoder));
        }
        controller.close();
      } catch (error) {
        controller.error(error);
      }
    }
  });
};
var injectStreamingRuntimeIntoStream = (stream, nonce, runtimePlacement = "head") => {
  const runtimeTag = renderStreamingSlotsRuntimeTag(nonce);
  const encoder = new TextEncoder;
  const decoder = new TextDecoder;
  const closingTag = runtimePlacement === "body" ? CLOSING_BODY_TAG : CLOSING_HEAD_TAG;
  const lookbehind = (runtimePlacement === "body" ? CLOSING_BODY_TAG_LENGTH : CLOSING_HEAD_TAG_LENGTH) - 1;
  return new ReadableStream({
    async start(controller) {
      const reader = stream.getReader();
      let injected = false;
      let pending = "";
      try {
        for (;; ) {
          const { done, value } = await reader.read();
          if (done)
            break;
          if (!value)
            continue;
          pending += streamChunkToString(value, decoder);
          if (injected) {
            controller.enqueue(encoder.encode(pending));
            pending = "";
            continue;
          }
          const closingTagIndex = pending.indexOf(closingTag);
          if (closingTagIndex >= 0) {
            const withRuntime = `${pending.slice(0, closingTagIndex)}${runtimeTag}${pending.slice(closingTagIndex)}`;
            controller.enqueue(encoder.encode(withRuntime));
            pending = "";
            injected = true;
            continue;
          }
          if (pending.length > lookbehind) {
            const safeText = pending.slice(0, pending.length - lookbehind);
            controller.enqueue(encoder.encode(safeText));
            pending = pending.slice(-lookbehind);
          }
        }
        pending += decoder.decode();
        if (!injected) {
          pending = runtimePlacement === "body" ? injectHtmlIntoBody(pending, runtimeTag) : injectHtmlIntoHead(pending, runtimeTag);
        }
        if (pending.length > 0) {
          controller.enqueue(encoder.encode(pending));
        }
        controller.close();
      } catch (error) {
        controller.error(error);
      }
    }
  });
};
var appendStreamingSlotPatchesToStream = (stream, slots = [], {
  injectRuntime = true,
  nonce,
  onError,
  onSlotMetric,
  policy,
  runtimePlacement = "head"
} = {}) => {
  const resolvedPolicy = resolveStreamingSlotPolicy(policy);
  const combinedOnError = createCombinedSlotErrorHandler(resolvedPolicy.onError, onError);
  const combinedOnSlotMetric = createCombinedSlotMetricHandler(resolvedPolicy.onSlotMetric, onSlotMetric);
  const effectivePolicy = {
    ...resolvedPolicy,
    onSlotMetric: combinedOnSlotMetric
  };
  const preparedSlots = prepareSlots({
    policy: effectivePolicy,
    slots,
    onError: combinedOnError,
    onSlotMetric: combinedOnSlotMetric
  });
  if (preparedSlots.length === 0)
    return stream;
  const source = injectRuntime ? injectStreamingRuntimeIntoStream(stream, nonce, runtimePlacement) : stream;
  const encoder = new TextEncoder;
  const decoder = new TextDecoder;
  const reader = source.getReader();
  const pending = preparedSlots.map((slot) => resolveSlot(slot, combinedOnError, effectivePolicy, combinedOnSlotMetric));
  return new ReadableStream({
    async start(controller) {
      let baseDone = false;
      let baseRead = reader.read();
      let tail = "";
      let footer = "";
      try {
        while (!baseDone || pending.length > 0) {
          const racers = [];
          if (!baseDone) {
            racers.push(baseRead.then(({ done, value }) => ({
              done,
              kind: "base",
              value
            })));
          }
          if (pending.length > 0) {
            racers.push(nextResolvedSlot(pending).then((resolved) => ({
              kind: "slot",
              ...resolved
            })));
          }
          if (racers.length === 0)
            break;
          const winner = await Promise.race(racers);
          if (winner.kind === "base") {
            if (winner.done) {
              baseDone = true;
              tail += decoder.decode();
              const footerStart = tail.search(CLOSING_PAGE_TAG_REGEX);
              if (footerStart >= 0) {
                const content = tail.slice(0, footerStart);
                footer = tail.slice(footerStart);
                if (content.length > 0) {
                  controller.enqueue(encoder.encode(content));
                }
              } else if (tail.length > 0) {
                controller.enqueue(encoder.encode(tail));
              }
              tail = "";
            } else if (winner.value) {
              tail += streamChunkToString(winner.value, decoder);
              if (tail.length > STREAM_TAIL_LOOKBEHIND) {
                const content = tail.slice(0, tail.length - STREAM_TAIL_LOOKBEHIND);
                controller.enqueue(encoder.encode(content));
                tail = tail.slice(-STREAM_TAIL_LOOKBEHIND);
              }
              baseRead = reader.read();
            }
            continue;
          }
          const index = pending.indexOf(winner.original);
          if (index >= 0)
            pending.splice(index, 1);
          if (winner.result.html === null)
            continue;
          emitSlotMetric({
            type: "patched",
            slotId: winner.result.id,
            durationMs: winner.result.durationMs,
            bytes: winner.result.bytes
          }, combinedOnSlotMetric);
          controller.enqueue(encoder.encode(renderStreamingSlotPatchTag(winner.result.id, winner.result.html, nonce)));
        }
        if (footer.length > 0)
          controller.enqueue(encoder.encode(footer));
        controller.close();
      } catch (error) {
        controller.error(error);
      }
    }
  });
};

// src/core/responseEnhancers.ts
var toResponse = async (responseLike) => await responseLike;
var cloneHeaders = (response) => {
  const headers = new Headers(response.headers);
  return headers;
};
var enhanceHtmlResponseWithStreamingSlots = (response, {
  nonce,
  onError,
  runtimePlacement,
  streamingSlots = [],
  policy
} = {}) => {
  if (!response.body || streamingSlots.length === 0) {
    return response;
  }
  const body = appendStreamingSlotPatchesToStream(response.body, streamingSlots, {
    nonce,
    onError,
    policy,
    runtimePlacement
  });
  return new Response(body, {
    headers: cloneHeaders(response),
    status: response.status,
    statusText: response.statusText
  });
};
var withStreamingSlots = async (responseLike, options = {}) => enhanceHtmlResponseWithStreamingSlots(await toResponse(responseLike), options);
var mergeStreamingSlots = (registered, explicit) => {
  const merged = new Map;
  for (const slot of registered)
    merged.set(slot.id, slot);
  for (const slot of explicit)
    merged.set(slot.id, slot);
  return [...merged.values()];
};
var withRegisteredStreamingSlots = async (renderResponse, options = {}) => {
  const { result, slots } = await runWithStreamingSlotRegistry(renderResponse);
  const explicit = options.streamingSlots ?? [];
  return withStreamingSlots(result, {
    ...options,
    streamingSlots: mergeStreamingSlots(slots, explicit)
  });
};

// src/core/wrapPageHandlerWithStreamingSlots.ts
var wrapPageHandlerWithStreamingSlots = (handler, options) => (...args) => withRegisteredStreamingSlots(() => handler(...args), options);

// src/react/index.ts
init_pageHandler();

// src/react/Island.tsx
init_islandMarkupAttributes();
init_renderIslandMarkup();
import { jsxDEV } from "react/jsx-dev-runtime";
var Island = async (props) => {
  if (typeof window !== "undefined") {
    return /* @__PURE__ */ jsxDEV("div", {
      ...getIslandMarkerAttributes(props),
      suppressHydrationWarning: true
    }, undefined, false, undefined, this);
  }
  const result = await renderIslandResult(requireCurrentIslandRegistry(), props);
  return /* @__PURE__ */ jsxDEV("div", {
    ...result.attributes,
    dangerouslySetInnerHTML: { __html: result.html }
  }, undefined, false, undefined, this);
};
// src/react/createIsland.tsx
init_islandMarkupAttributes();
init_renderIslandMarkup();
import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
var createTypedIsland = (registry) => {
  const Island2 = async (props) => {
    if (typeof window !== "undefined") {
      return /* @__PURE__ */ jsxDEV2("div", {
        ...getIslandMarkerAttributes(props),
        suppressHydrationWarning: true
      }, undefined, false, undefined, this);
    }
    const result = await renderIslandResult(registry, props);
    return /* @__PURE__ */ jsxDEV2("div", {
      ...result.attributes,
      dangerouslySetInnerHTML: { __html: result.html }
    }, undefined, false, undefined, this);
  };
  return Island2;
};
// src/react/hooks/useIslandStore.ts
import { useSyncExternalStore } from "react";

// node_modules/zustand/esm/vanilla.mjs
var createStoreImpl = (createState) => {
  let state;
  const listeners = /* @__PURE__ */ new Set;
  const setState = (partial, replace) => {
    const nextState = typeof partial === "function" ? partial(state) : partial;
    if (!Object.is(nextState, state)) {
      const previousState = state;
      state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
      listeners.forEach((listener) => listener(state, previousState));
    }
  };
  const getState = () => state;
  const getInitialState = () => initialState;
  const subscribe = (listener) => {
    listeners.add(listener);
    return () => listeners.delete(listener);
  };
  const api = { setState, getState, getInitialState, subscribe };
  const initialState = state = createState(setState, getState, api);
  return api;
};
var createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl;

// node_modules/zustand/esm/middleware.mjs
function combine(initialState, create) {
  return (...args) => Object.assign({}, initialState, create(...args));
}

// src/client/islandStore.ts
var getIslandStoreSnapshot = () => {
  globalThis.__ABS_ISLAND_STATE__ ??= {};
  return globalThis.__ABS_ISLAND_STATE__;
};
var getIslandStores = () => {
  globalThis.__ABS_ISLAND_STORES__ ??= new Map;
  return globalThis.__ABS_ISLAND_STORES__;
};
var isSerializableValue = (value) => typeof value !== "function" && value !== undefined;
var toSerializableState = (state) => Object.fromEntries(Object.entries(state).filter(([, value]) => isSerializableValue(value)));
var applySnapshot = (store, snapshot) => {
  if (!snapshot) {
    return;
  }
  store.setState({
    ...store.getState(),
    ...snapshot
  });
};
var getPeerStores = (storeInstances, ownerStore) => [...storeInstances].filter((peer) => peer.store !== ownerStore);
var syncIslandSnapshot = (storeId, state, storeInstances, ownerStore) => {
  const nextSnapshot = toSerializableState(state);
  getIslandStoreSnapshot()[storeId] = nextSnapshot;
  for (const peerStore of getPeerStores(storeInstances, ownerStore)) {
    peerStore.applyExternalSnapshot(nextSnapshot);
  }
};
var createIslandStore = (storeId, initialState, createState) => {
  const store = createStore(combine(initialState, createState));
  const stores = getIslandStores();
  const storeInstances = stores.get(storeId) ?? new Set;
  const initialSnapshot = getIslandStoreSnapshot()[storeId];
  applySnapshot(store, initialSnapshot);
  let isApplyingExternalSnapshot = false;
  const applyExternalSnapshot = (snapshot) => {
    isApplyingExternalSnapshot = true;
    applySnapshot(store, snapshot);
  };
  storeInstances.add({
    applyExternalSnapshot,
    store
  });
  stores.set(storeId, storeInstances);
  syncIslandSnapshot(storeId, store.getState(), storeInstances, store);
  store.subscribe((state) => {
    if (isApplyingExternalSnapshot) {
      isApplyingExternalSnapshot = false;
      return;
    }
    syncIslandSnapshot(storeId, state, storeInstances, store);
  });
  return store;
};
var getIslandStoreServerSnapshot = (store, selector) => selector(store.getInitialState());
var applySnapshotToStoreInstances = (storeId, instances, snapshot) => {
  for (const instance of instances) {
    instance.applyExternalSnapshot(snapshot[storeId] ?? {});
  }
};
var initializeIslandStores = (state) => {
  const currentSnapshot = getIslandStoreSnapshot();
  const nextSnapshot = {
    ...state,
    ...currentSnapshot
  };
  globalThis.__ABS_ISLAND_STATE__ = nextSnapshot;
  for (const [storeId, store] of getIslandStores()) {
    applySnapshotToStoreInstances(storeId, store, nextSnapshot);
  }
};
var readIslandStore = (store, selector) => selector(store.getState());
var subscribeIslandStore = (store, selector, listener) => {
  let currentSelection = selector(store.getState());
  return store.subscribe((state) => {
    const nextSelection = selector(state);
    if (Object.is(nextSelection, currentSelection)) {
      return;
    }
    currentSelection = nextSelection;
    listener(nextSelection);
  });
};

// src/react/hooks/useIslandStore.ts
var useIslandStore = (store, selector) => useSyncExternalStore((listener) => subscribeIslandStore(store, selector, () => {
  listener();
}), () => readIslandStore(store, selector), () => getIslandStoreServerSnapshot(store, selector));

// src/react/index.ts
var handleReactPageRequest2 = wrapPageHandlerWithStreamingSlots(handleReactPageRequest);
export {
  useIslandStore,
  handleReactPageRequest2 as handleReactPageRequest,
  createTypedIsland,
  Island
};

//# debugId=64717BD1B5CB5A6264756E2164756E21
//# sourceMappingURL=index.js.map
