var __defProp = Object.defineProperty;
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 __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined")
    return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});

// src/logger.ts
function isProduction() {
  if (typeof process !== "undefined" && process.env) {
    return false;
  }
  return false;
}
function setLogLevel(level) {
  config.level = level;
}
function getLogLevel() {
  return config.level;
}
function configureLogger(options) {
  config = { ...config, ...options };
}
function enableLogging() {
  config.level = "debug";
}
function disableLogging() {
  config.level = "none";
}
function setDebugMode(enabled) {
  config.level = enabled ? "debug" : "error";
}
function isDebugMode() {
  return config.level === "debug";
}
function shouldLog(level) {
  return LOG_LEVEL_ORDER[level] >= LOG_LEVEL_ORDER[config.level];
}
function formatTag(tag, level) {
  const timestamp = config.timestamps ? `${new Date().toISOString()} ` : "";
  if (config.colors && level !== "none") {
    const color = LOG_LEVEL_COLORS[level];
    return `${timestamp}${color}[${tag}]${RESET_COLOR}`;
  }
  return `${timestamp}[${tag}]`;
}

class Logger {
  tag;
  constructor(tag) {
    this.tag = tag;
  }
  debug(...args) {
    if (!shouldLog("debug"))
      return;
    if (config.handler) {
      config.handler.debug(this.tag, ...args);
    } else {
      console.log(formatTag(this.tag, "debug"), ...args);
    }
  }
  info(...args) {
    if (!shouldLog("info"))
      return;
    if (config.handler) {
      config.handler.info(this.tag, ...args);
    } else {
      console.info(formatTag(this.tag, "info"), ...args);
    }
  }
  warn(...args) {
    if (!shouldLog("warn"))
      return;
    if (config.handler) {
      config.handler.warn(this.tag, ...args);
    } else {
      console.warn(formatTag(this.tag, "warn"), ...args);
    }
  }
  error(...args) {
    if (!shouldLog("error"))
      return;
    if (config.handler) {
      config.handler.error(this.tag, ...args);
    } else {
      console.error(formatTag(this.tag, "error"), ...args);
    }
  }
  time(label, fn) {
    if (!shouldLog("debug")) {
      return fn();
    }
    const start = performance.now();
    try {
      return fn();
    } finally {
      const duration = performance.now() - start;
      this.debug(`${label}: ${duration.toFixed(2)}ms`);
    }
  }
  async timeAsync(label, fn) {
    if (!shouldLog("debug")) {
      return fn();
    }
    const start = performance.now();
    try {
      return await fn();
    } finally {
      const duration = performance.now() - start;
      this.debug(`${label}: ${duration.toFixed(2)}ms`);
    }
  }
  child(subTag) {
    return new Logger(`${this.tag}:${subTag}`);
  }
  debugIf(condition, ...args) {
    if (condition)
      this.debug(...args);
  }
  warnIf(condition, ...args) {
    if (condition)
      this.warn(...args);
  }
  errorIf(condition, ...args) {
    if (condition)
      this.error(...args);
  }
  loggedOnce = new Set;
  warnOnce(key, ...args) {
    if (this.loggedOnce.has(key))
      return;
    this.loggedOnce.add(key);
    this.warn(...args);
  }
  debugOnce(key, ...args) {
    if (this.loggedOnce.has(key))
      return;
    this.loggedOnce.add(key);
    this.debug(...args);
  }
}
function createLogger(tag) {
  return new Logger(tag);
}
var LOG_LEVEL_ORDER, LOG_LEVEL_COLORS, RESET_COLOR = "\x1B[0m", config, logger, log, frameworkLoggers;
var init_logger = __esm(() => {
  LOG_LEVEL_ORDER = {
    debug: 0,
    info: 1,
    warn: 2,
    error: 3,
    none: 4
  };
  LOG_LEVEL_COLORS = {
    debug: "\x1B[36m",
    info: "\x1B[32m",
    warn: "\x1B[33m",
    error: "\x1B[31m"
  };
  config = {
    level: isProduction() ? "error" : "info",
    colors: true,
    timestamps: false
  };
  logger = createLogger("Hypen");
  log = {
    debug: (tag, ...args) => {
      if (!shouldLog("debug"))
        return;
      console.log(formatTag(tag, "debug"), ...args);
    },
    info: (tag, ...args) => {
      if (!shouldLog("info"))
        return;
      console.info(formatTag(tag, "info"), ...args);
    },
    warn: (tag, ...args) => {
      if (!shouldLog("warn"))
        return;
      console.warn(formatTag(tag, "warn"), ...args);
    },
    error: (tag, ...args) => {
      if (!shouldLog("error"))
        return;
      console.error(formatTag(tag, "error"), ...args);
    }
  };
  frameworkLoggers = {
    hypen: createLogger("Hypen"),
    engine: createLogger("Engine"),
    router: createLogger("Router"),
    state: createLogger("State"),
    events: createLogger("Events"),
    remote: createLogger("Remote"),
    renderer: createLogger("Renderer"),
    module: createLogger("Module"),
    lifecycle: createLogger("Lifecycle"),
    loader: createLogger("Loader"),
    context: createLogger("Context"),
    discovery: createLogger("Discovery"),
    plugin: createLogger("Plugin"),
    canvas: createLogger("Canvas"),
    debug: createLogger("Debug")
  };
});

// src/result.ts
function Ok(value) {
  return { ok: true, value };
}
function Err(error) {
  return { ok: false, error };
}
function classifyEngineError(err) {
  const message = err instanceof Error ? err.message : String(err);
  if (message.startsWith("Parse error:")) {
    return new ParseError(message);
  }
  if (message.startsWith("Invalid state:") || message.startsWith("Invalid state patch:")) {
    return new StateError(message);
  }
  if (message.startsWith("Parent node not found:")) {
    return new RenderError(message);
  }
  return new RenderError(message);
}
var HypenError, ActionError, ConnectionError, StateError, ParseError, RenderError;
var init_result = __esm(() => {
  HypenError = class HypenError extends Error {
    code;
    context;
    cause;
    constructor(code, message, options) {
      super(message);
      this.name = "HypenError";
      this.code = code;
      this.context = options?.context;
      this.cause = options?.cause;
      Object.setPrototypeOf(this, new.target.prototype);
    }
  };
  ActionError = class ActionError extends HypenError {
    actionName;
    constructor(actionName, cause) {
      super("ACTION_ERROR", `Action handler "${actionName}" failed: ${cause instanceof Error ? cause.message : String(cause)}`, {
        context: { actionName },
        cause: cause instanceof Error ? cause : undefined
      });
      this.name = "ActionError";
      this.actionName = actionName;
    }
  };
  ConnectionError = class ConnectionError extends HypenError {
    url;
    attempt;
    constructor(url, cause, attempt) {
      super("CONNECTION_ERROR", `Connection to "${url}" failed${attempt ? ` (attempt ${attempt})` : ""}: ${cause instanceof Error ? cause.message : String(cause)}`, {
        context: { url, attempt },
        cause: cause instanceof Error ? cause : undefined
      });
      this.name = "ConnectionError";
      this.url = url;
      this.attempt = attempt;
    }
  };
  StateError = class StateError extends HypenError {
    path;
    constructor(message, path, cause) {
      super("STATE_ERROR", message, {
        context: { path },
        cause: cause instanceof Error ? cause : undefined
      });
      this.name = "StateError";
      this.path = path;
    }
  };
  ParseError = class ParseError extends HypenError {
    source;
    constructor(message, source, cause) {
      super("PARSE_ERROR", message, {
        context: { source },
        cause: cause instanceof Error ? cause : undefined
      });
      this.name = "ParseError";
      this.source = source;
    }
  };
  RenderError = class RenderError extends HypenError {
    constructor(message, cause) {
      super("RENDER_ERROR", message, {
        cause: cause instanceof Error ? cause : undefined
      });
      this.name = "RenderError";
    }
  };
});

// src/engine.browser.ts
init_logger();
init_result();
var log2 = frameworkLoggers.engine;
var wasmInit = null;
var WasmEngineClass = null;
function mapToObject(value) {
  if (value instanceof Map) {
    const obj = {};
    for (const [key, val] of value.entries()) {
      obj[key] = mapToObject(val);
    }
    return obj;
  } else if (Array.isArray(value)) {
    return value.map(mapToObject);
  } else if (value && typeof value === "object" && value.constructor === Object) {
    const obj = {};
    for (const [key, val] of Object.entries(value)) {
      obj[key] = mapToObject(val);
    }
    return obj;
  }
  return value;
}

class Engine {
  wasmEngine = null;
  initialized = false;
  async init(options = {}) {
    if (this.initialized)
      return;
    const cdnBase = "https://unpkg.com/@hypen-space/core@latest/wasm-browser";
    const jsUrl = options.jsUrl ?? `${cdnBase}/hypen_engine.js`;
    const wasmUrl = options.wasmUrl ?? `${cdnBase}/hypen_engine_bg.wasm`;
    try {
      const wasmModule = await import(jsUrl);
      wasmInit = wasmModule.default;
      WasmEngineClass = wasmModule.WasmEngine;
      await wasmInit(wasmUrl);
      this.wasmEngine = new WasmEngineClass;
      this.initialized = true;
    } catch (error) {
      log2.error("Failed to initialize WASM engine:", error);
      throw error;
    }
  }
  ensureInitialized() {
    if (!this.wasmEngine) {
      throw new Error("Engine not initialized. Call init() first.");
    }
    return this.wasmEngine;
  }
  setRenderCallback(callback) {
    const engine = this.ensureInitialized();
    engine.setRenderCallback((patches) => {
      callback(patches);
    });
  }
  setComponentResolver(resolver) {
    const engine = this.ensureInitialized();
    engine.setComponentResolver((componentName, contextPath) => {
      const result = resolver(componentName, contextPath);
      return result;
    });
  }
  renderSource(source) {
    const engine = this.ensureInitialized();
    try {
      engine.renderSource(source);
    } catch (err) {
      throw classifyEngineError(err);
    }
  }
  renderLazyComponent(source) {
    const engine = this.ensureInitialized();
    engine.renderLazyComponent(source);
  }
  renderInto(source, parentNodeId, state) {
    const engine = this.ensureInitialized();
    const safeState = JSON.parse(JSON.stringify(state));
    try {
      engine.renderInto(source, parentNodeId, safeState);
    } catch (err) {
      throw classifyEngineError(err);
    }
  }
  notifyStateChange(paths, values) {
    const engine = this.ensureInitialized();
    if (paths.length === 0) {
      return;
    }
    const plainValues = JSON.parse(JSON.stringify(values));
    try {
      engine.updateStateSparse(paths, plainValues);
    } catch (err) {
      throw classifyEngineError(err);
    }
    log2.debug("State changed (sparse):", paths);
  }
  notifyStateChangeFull(paths, currentState) {
    const engine = this.ensureInitialized();
    const plainObject = JSON.parse(JSON.stringify(currentState));
    engine.updateState(plainObject);
    if (paths.length > 0) {
      log2.debug("State changed (full):", paths);
    }
  }
  updateState(statePatch) {
    const engine = this.ensureInitialized();
    const plainObject = JSON.parse(JSON.stringify(statePatch));
    engine.updateState(plainObject);
  }
  dispatchAction(name, payload) {
    const engine = this.ensureInitialized();
    log2.debug(`Action dispatched: ${name}`);
    try {
      engine.dispatchAction(name, payload ?? null);
    } catch (err) {
      throw classifyEngineError(err);
    }
  }
  onAction(actionName, handler) {
    const engine = this.ensureInitialized();
    engine.onAction(actionName, (action) => {
      const normalizedAction = {
        ...action,
        payload: action.payload ? mapToObject(action.payload) : action.payload
      };
      Promise.resolve(handler(normalizedAction)).catch((err) => log2.error("Action handler error:", err));
    });
  }
  setModule(name, actions, stateKeys, initialState) {
    const engine = this.ensureInitialized();
    engine.setModule(name, actions, stateKeys, initialState);
  }
  getRevision() {
    const engine = this.ensureInitialized();
    return engine.getRevision();
  }
  clearTree() {
    const engine = this.ensureInitialized();
    engine.clearTree();
  }
  debugParseComponent(source) {
    const engine = this.ensureInitialized();
    return engine.debugParseComponent(source);
  }
  setContext(name, data) {
    const engine = this.ensureInitialized();
    const plainData = JSON.parse(JSON.stringify(data));
    try {
      engine.setContext(name, plainData);
    } catch (err) {
      throw classifyEngineError(err);
    }
  }
  removeContext(name) {
    const engine = this.ensureInitialized();
    engine.removeContext(name);
  }
}
export {
  Engine
};

//# debugId=C512B9141446E71964756E2164756E21
