// @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/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/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/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/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_islands = __esm(() => {
  init_angularDeps();
  init_ssrRender();
  init_registerClientScript();
  wrapperMetadataCache = new Map;
  requestRenderCache = new Map;
});

// 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_islands2 = () => {};

// 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_islands2();
});

// src/client/islandResolver.ts
var createIslandManifestResolver = (manifest) => {
  const islandManifest = getIslandManifestEntries(manifest);
  return async (framework, component) => {
    const modulePath = islandManifest[framework]?.[component] ?? manifest[getIslandManifestKey(framework, component)];
    if (!modulePath)
      return;
    const loadedModule = await import(modulePath);
    return loadedModule.default;
  };
};
// src/client/streamSwap.ts
var streamSwapRuntime = () => {
  if (window.__ABS_SLOT_RUNTIME__ === true)
    return;
  window.__ABS_SLOT_RUNTIME__ = true;
  window.__ABS_SLOT_PENDING__ = window.__ABS_SLOT_PENDING__ ?? {};
  const pending = window.__ABS_SLOT_PENDING__;
  const apply = (id, html) => {
    const node = document.getElementById(`slot-${id}`);
    if (!node) {
      pending[id] = html;
      return;
    }
    node.innerHTML = html;
    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_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())}})();`;
// 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/client/islandRuntime.ts
init_islands();
init_islands2();
import { createElement } from "react";
import { hydrateRoot } from "react-dom/client";
import { hydrate as hydrateSvelte } from "svelte";
import { createSSRApp, h } from "vue";

// src/client/preserveIslandMarkup.ts
init_islandMarkupAttributes();
var getClaimMap = () => {
  if (typeof window === "undefined") {
    return null;
  }
  window.__ABS_CLAIMED_ISLAND_MARKUP__ ??= new Map;
  return window.__ABS_CLAIMED_ISLAND_MARKUP__;
};
var getSnapshotMap = () => {
  if (typeof window === "undefined") {
    return null;
  }
  window.__ABS_SERVER_ISLAND_HTML__ ??= new Map;
  return window.__ABS_SERVER_ISLAND_HTML__;
};
var getIslandSignature = (props) => {
  const attributes = getIslandMarkerAttributes(props);
  return [
    attributes["data-component"],
    attributes["data-framework"],
    attributes["data-hydrate"],
    attributes["data-props"]
  ].join("::");
};
var isMatchingIslandElement = (element, props) => {
  if (!(element instanceof HTMLElement)) {
    return false;
  }
  const attributes = getIslandMarkerAttributes(props);
  return element.dataset.island === "true" && element.dataset.component === attributes["data-component"] && element.dataset.framework === attributes["data-framework"] && (element.dataset.hydrate ?? "load") === attributes["data-hydrate"] && (element.dataset.props ?? "{}") === attributes["data-props"];
};
var snapshotIslandElement = (element, snapshotMap) => {
  const signature = [
    element.dataset.component,
    element.dataset.framework,
    element.dataset.hydrate ?? "load",
    element.dataset.props ?? "{}"
  ].join("::");
  const existing = snapshotMap.get(signature) ?? [];
  const attributes = Object.fromEntries(element.getAttributeNames().map((name) => [name, element.getAttribute(name) ?? ""]));
  existing.push({
    attributes,
    innerHTML: element.innerHTML
  });
  snapshotMap.set(signature, existing);
};
var initializeIslandMarkupSnapshot = () => {
  if (typeof document === "undefined") {
    return;
  }
  const snapshotMap = getSnapshotMap();
  if (!snapshotMap || snapshotMap.size > 0) {
    return;
  }
  const elements = Array.from(document.querySelectorAll('[data-island="true"]'));
  for (const element of elements) {
    snapshotIslandElement(element, snapshotMap);
  }
};
var preserveIslandMarkup = (props) => {
  if (typeof document === "undefined") {
    return {
      attributes: getIslandMarkerAttributes(props),
      innerHTML: ""
    };
  }
  const claimMap = getClaimMap();
  const snapshotMap = getSnapshotMap();
  const signature = getIslandSignature(props);
  const claimedCount = claimMap?.get(signature) ?? 0;
  const snapshotCandidate = snapshotMap?.get(signature)?.[claimedCount];
  const candidates = Array.from(document.querySelectorAll('[data-island="true"]')).filter((element) => isMatchingIslandElement(element, props));
  const candidate = candidates[claimedCount];
  if (claimMap) {
    claimMap.set(signature, claimedCount + 1);
  }
  return {
    attributes: snapshotCandidate?.attributes ?? getIslandMarkerAttributes(props),
    innerHTML: snapshotCandidate?.innerHTML ?? candidate?.innerHTML ?? ""
  };
};

// src/client/islandRuntime.ts
initializeIslandMarkupSnapshot();
var idleDeadline = {
  didTimeout: false,
  timeRemaining: () => 0
};
var requestIdle = typeof window !== "undefined" && "requestIdleCallback" in window ? window.requestIdleCallback.bind(window) : (callback) => window.setTimeout(() => callback(idleDeadline), 1);
var hydrateReactIsland = (component, element, props) => {
  const existingRoot = reactIslandRoots.get(element);
  if (existingRoot) {
    existingRoot.render(isPropsRecord(props) ? createElement(component, props) : createElement(component));
    return;
  }
  if (!isPropsRecord(props)) {
    reactIslandRoots.set(element, hydrateRoot(element, createElement(component)));
    return;
  }
  reactIslandRoots.set(element, hydrateRoot(element, createElement(component, props)));
};
var hydrateSvelteIsland = (component, element, props) => {
  hydrateSvelte(component, {
    props: isPropsRecord(props) ? props : undefined,
    target: element
  });
};
var hydrateVueIsland = (component, element, props) => {
  if (vueIslandApps.has(element)) {
    return;
  }
  const app = createSSRApp({
    render: () => h(component, isPropsRecord(props) ? props : undefined)
  });
  app.mount(element);
  vueIslandApps.set(element, app);
};
var isIslandElement = (value) => value instanceof HTMLElement && value.dataset.island === "true";
var isPropsRecord = (value) => typeof value === "object" && value !== null;
var isReactComponent = (value) => typeof value === "function";
var isSvelteComponent = (value) => typeof value === "function";
var isVueComponent = (value) => typeof value === "function" || isPropsRecord(value);
var isAngularComponent = (value) => typeof value === "function";
var observedRoots = new WeakSet;
var hydratingIslands = new WeakSet;
var reactIslandRoots = new WeakMap;
var vueIslandApps = new WeakMap;
var hydrateByFramework = async (registry, framework, componentName, element, props, resolveComponent) => {
  if (framework === "react") {
    const resolvedComponent = await resolveComponent?.(framework, componentName) ?? getIslandComponent(registry.react?.[componentName]);
    if (!isReactComponent(resolvedComponent))
      return;
    hydrateReactIsland(resolvedComponent, element, isPropsRecord(props) ? props : undefined);
    element.dataset.hydrated = "true";
    return;
  }
  if (framework === "svelte") {
    const resolvedComponent = await resolveComponent?.(framework, componentName) ?? getIslandComponent(registry.svelte?.[componentName]);
    if (!isSvelteComponent(resolvedComponent))
      return;
    hydrateSvelteIsland(resolvedComponent, element, isPropsRecord(props) ? props : undefined);
    element.dataset.hydrated = "true";
    return;
  }
  if (framework === "vue") {
    const resolvedComponent = await resolveComponent?.(framework, componentName) ?? getIslandComponent(registry.vue?.[componentName]);
    if (!isVueComponent(resolvedComponent))
      return;
    hydrateVueIsland(resolvedComponent, element, isPropsRecord(props) ? props : undefined);
    element.dataset.hydrated = "true";
    return;
  }
  if (framework === "angular") {
    const resolvedComponent = await resolveComponent?.(framework, componentName) ?? getIslandComponent(registry.angular?.[componentName]);
    const { islandId } = element.dataset;
    if (!isAngularComponent(resolvedComponent) || !islandId)
      return;
    await mountAngularIsland(resolvedComponent, element, isPropsRecord(props) ? props : {}, islandId);
    element.dataset.hydrated = "true";
  }
};
var hydrateIsland = async (registry, element, resolveComponent) => {
  if (element.dataset.hydrated === "true" || hydratingIslands.has(element)) {
    return;
  }
  const { framework } = element.dataset;
  const componentName = element.dataset.component;
  if (!framework || !componentName)
    return;
  const props = parseIslandProps(element.getAttribute("data-props"));
  hydratingIslands.add(element);
  try {
    await hydrateByFramework(registry, framework, componentName, element, props, resolveComponent);
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown island error";
    element.dataset.error = message;
    console.error(`[islands] Failed to hydrate ${framework}:${componentName}`, error);
  } finally {
    hydratingIslands.delete(element);
  }
};
var scheduleIsland = (registry, element, observer, resolveComponent) => {
  const mode = element.dataset.hydrate ?? "load";
  if (mode === "none")
    return;
  if (mode === "load") {
    hydrateIsland(registry, element, resolveComponent);
    return;
  }
  if (mode === "idle") {
    requestIdle(() => void hydrateIsland(registry, element, resolveComponent));
    return;
  }
  if (mode === "visible" && observer) {
    observer.observe(element);
    return;
  }
  hydrateIsland(registry, element, resolveComponent);
};
var collectIslandElements = (node) => {
  const islands = [];
  if (isIslandElement(node))
    islands.push(node);
  if (!(node instanceof Element))
    return islands;
  const nested = node.querySelectorAll('[data-island="true"]');
  for (const island of nested) {
    islands.push(island);
  }
  return islands;
};
var startIslands = ({
  registry,
  resolveComponent,
  root = document.documentElement
}) => {
  const targetRoot = root instanceof Document ? root.documentElement : root;
  const observer = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver((entries) => {
    for (const entry of entries) {
      if (!entry.isIntersecting)
        continue;
      if (!isIslandElement(entry.target))
        continue;
      observer?.unobserve(entry.target);
      hydrateIsland(registry, entry.target, resolveComponent);
    }
  });
  const islands = targetRoot.querySelectorAll('[data-island="true"]');
  for (const island of islands) {
    scheduleIsland(registry, island, observer, resolveComponent);
  }
  if (typeof MutationObserver === "undefined")
    return;
  if (observedRoots.has(targetRoot))
    return;
  const mutationObserver = new MutationObserver((records) => {
    const addedIslands = records.flatMap((record) => Array.from(record.addedNodes).flatMap(collectIslandElements));
    for (const island of addedIslands) {
      scheduleIsland(registry, island, observer, resolveComponent);
    }
  });
  observedRoots.add(targetRoot);
  mutationObserver.observe(targetRoot, {
    childList: true,
    subtree: true
  });
};
export {
  subscribeIslandStore,
  startIslands,
  readIslandStore,
  initializeIslandStores,
  getStreamSwapRuntimeScript,
  getIslandStoreServerSnapshot,
  createIslandStore,
  createIslandManifestResolver
};

//# debugId=88DDA8682BB7927F64756E2164756E21
//# sourceMappingURL=index.js.map
