var __defProp = Object.defineProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, {
      get: all[name],
      enumerable: true,
      configurable: true,
      set: (newValue) => all[name] = () => newValue
    });
};
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);

// src/state.ts
function deepClone(obj) {
  if (obj === null || typeof obj !== "object") {
    return obj;
  }
  if (typeof obj === "function") {
    return obj;
  }
  if (typeof obj.__getSnapshot === "function") {
    return obj.__getSnapshot();
  }
  if (obj instanceof WeakMap || obj instanceof WeakSet) {
    return obj;
  }
  const visited = new WeakMap;
  function cloneInternal(value) {
    if (value === null || typeof value !== "object") {
      return value;
    }
    if (typeof value === "function") {
      return value;
    }
    if (visited.has(value)) {
      return visited.get(value);
    }
    if (value instanceof WeakMap || value instanceof WeakSet) {
      return value;
    }
    if (value instanceof Date || value instanceof RegExp || value instanceof Map || value instanceof Set || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
      try {
        return structuredClone(value);
      } catch {}
    }
    if (Array.isArray(value)) {
      const arrClone = [];
      visited.set(value, arrClone);
      for (let i = 0;i < value.length; i++) {
        arrClone[i] = cloneInternal(value[i]);
      }
      return arrClone;
    }
    const objClone = {};
    visited.set(value, objClone);
    for (const key in value) {
      if (Object.prototype.hasOwnProperty.call(value, key)) {
        objClone[key] = cloneInternal(value[key]);
      }
    }
    const symbolKeys = Object.getOwnPropertySymbols(value);
    for (const sym of symbolKeys) {
      objClone[sym] = cloneInternal(value[sym]);
    }
    return objClone;
  }
  return cloneInternal(obj);
}
function diffState(oldState, newState, basePath = "") {
  const paths = [];
  const newValues = {};
  function diff(oldVal, newVal, path) {
    if (oldVal === newVal)
      return;
    if (typeof oldVal !== "object" || typeof newVal !== "object" || oldVal === null || newVal === null) {
      if (oldVal !== newVal) {
        paths.push(path);
        newValues[path] = newVal;
      }
      return;
    }
    if (Array.isArray(oldVal) || Array.isArray(newVal)) {
      if (!Array.isArray(oldVal) || !Array.isArray(newVal) || oldVal.length !== newVal.length) {
        paths.push(path);
        newValues[path] = newVal;
        return;
      }
      for (let i = 0;i < newVal.length; i++) {
        const itemPath = path ? `${path}.${i}` : `${i}`;
        diff(oldVal[i], newVal[i], itemPath);
      }
      return;
    }
    const oldKeys = new Set(Object.keys(oldVal));
    const newKeys = new Set(Object.keys(newVal));
    for (const key of newKeys) {
      const propPath = path ? `${path}.${key}` : key;
      if (!oldKeys.has(key)) {
        paths.push(propPath);
        newValues[propPath] = newVal[key];
      } else {
        diff(oldVal[key], newVal[key], propPath);
      }
    }
    for (const key of oldKeys) {
      if (!newKeys.has(key)) {
        const propPath = path ? `${path}.${key}` : key;
        paths.push(propPath);
        newValues[propPath] = undefined;
      }
    }
  }
  diff(oldState, newState, basePath);
  return { paths, newValues };
}
function createObservableState(initialState, options) {
  const opts = options || { onChange: () => {} };
  if (initialState === null || initialState === undefined) {
    initialState = {};
  }
  if (initialState instanceof Number || initialState instanceof String || initialState instanceof Boolean) {
    throw new TypeError("Cannot create observable state from primitive wrapper objects (Number, String, Boolean). " + "Use plain primitives or regular objects instead.");
  }
  initialState = deepClone(initialState);
  let lastSnapshot = deepClone(initialState);
  const pathPrefix = opts.pathPrefix || "";
  let batchDepth = 0;
  let pendingChange = null;
  function notifyChange() {
    if (batchDepth > 0)
      return;
    const change = diffState(lastSnapshot, state, pathPrefix);
    if (change.paths.length > 0) {
      lastSnapshot = deepClone(state);
      if (pendingChange) {
        change.paths.push(...pendingChange.paths);
        Object.assign(change.newValues, pendingChange.newValues);
        pendingChange = null;
      }
      opts.onChange(change);
    }
  }
  let notificationPending = false;
  function scheduleBatch() {
    if (batchDepth === 0) {
      if (!notificationPending) {
        notificationPending = true;
        queueMicrotask(() => {
          notificationPending = false;
          if (batchDepth === 0) {
            notifyChange();
          }
        });
      }
    }
  }
  const proxyCache = new WeakMap;
  function createProxy(target, basePath) {
    const cached = proxyCache.get(target);
    if (cached)
      return cached;
    const proxy = new Proxy(target, {
      get(obj, prop) {
        if (prop === IS_PROXY)
          return true;
        if (prop === RAW_TARGET)
          return obj;
        if (prop === "__beginBatch") {
          return () => {
            batchDepth++;
          };
        }
        if (prop === "__endBatch") {
          return () => {
            batchDepth--;
            if (batchDepth === 0) {
              notifyChange();
            }
          };
        }
        if (prop === "__getSnapshot") {
          return () => deepClone(obj);
        }
        const value = obj[prop];
        if (value && typeof value === "object") {
          if (value[IS_PROXY]) {
            return value;
          }
          if (value instanceof Date || value instanceof RegExp || value instanceof Map || value instanceof Set || value instanceof WeakMap || value instanceof WeakSet) {
            return value;
          }
          const cachedNested = proxyCache.get(value);
          if (cachedNested) {
            return cachedNested;
          }
          const nestedProxy = createProxy(value, basePath ? `${basePath}.${String(prop)}` : String(prop));
          return nestedProxy;
        }
        return value;
      },
      set(obj, prop, value) {
        const oldValue = obj[prop];
        if (value && typeof value === "object" && value[IS_PROXY]) {
          value = value[RAW_TARGET];
        }
        obj[prop] = value;
        if (oldValue !== value) {
          scheduleBatch();
        }
        return true;
      },
      deleteProperty(obj, prop) {
        if (prop in obj) {
          delete obj[prop];
          scheduleBatch();
        }
        return true;
      }
    });
    proxyCache.set(target, proxy);
    return proxy;
  }
  const state = createProxy(initialState, pathPrefix);
  return state;
}
function batchStateUpdates(state, fn) {
  const s = state;
  if (s.__beginBatch && s.__endBatch) {
    s.__beginBatch();
    try {
      fn();
    } finally {
      s.__endBatch();
    }
  } else {
    fn();
  }
}
function getStateSnapshot(state) {
  const s = state;
  if (s.__getSnapshot) {
    return s.__getSnapshot();
  }
  return deepClone(state);
}
function isStateProxy(value) {
  return value !== null && typeof value === "object" && value[IS_PROXY] === true;
}
function unwrapProxy(value) {
  if (value !== null && typeof value === "object" && value[IS_PROXY]) {
    return value[RAW_TARGET];
  }
  return value;
}
var IS_PROXY, RAW_TARGET;
var init_state = __esm(() => {
  IS_PROXY = Symbol.for("hypen.isProxy");
  RAW_TARGET = Symbol.for("hypen.rawTarget");
});

// src/result.ts
function Ok(value) {
  return { ok: true, value };
}
function Err(error) {
  return { ok: false, error };
}
function isOk(result) {
  return result.ok;
}
function isErr(result) {
  return !result.ok;
}
async function fromPromise(promise, mapError) {
  try {
    const value = await promise;
    return Ok(value);
  } catch (e) {
    if (mapError) {
      return Err(mapError(e));
    }
    return Err(e);
  }
}
function fromTry(fn, mapError) {
  try {
    return Ok(fn());
  } catch (e) {
    if (mapError) {
      return Err(mapError(e));
    }
    return Err(e);
  }
}
function map(result, fn) {
  if (result.ok) {
    return Ok(fn(result.value));
  }
  return result;
}
function mapErr(result, fn) {
  if (!result.ok) {
    return Err(fn(result.error));
  }
  return result;
}
function flatMap(result, fn) {
  if (result.ok) {
    return fn(result.value);
  }
  return result;
}
function unwrap(result) {
  if (result.ok) {
    return result.value;
  }
  throw result.error;
}
function unwrapOr(result, defaultValue) {
  if (result.ok) {
    return result.value;
  }
  return defaultValue;
}
function unwrapOrElse(result, fn) {
  if (result.ok) {
    return result.value;
  }
  return fn(result.error);
}
function match(result, handlers) {
  if (result.ok) {
    return handlers.ok(result.value);
  }
  return handlers.err(result.error);
}
function all(results) {
  const values = [];
  for (const result of results) {
    if (!result.ok) {
      return result;
    }
    values.push(result.value);
  }
  return Ok(values);
}
var HypenError, ActionError, ConnectionError, StateError;
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;
    }
  };
});

// 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 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" : "debug",
    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 = {
    engine: createLogger("Engine"),
    router: createLogger("Router"),
    state: createLogger("State"),
    events: createLogger("Events"),
    remote: createLogger("Remote"),
    renderer: createLogger("Renderer"),
    module: createLogger("Module"),
    lifecycle: createLogger("Lifecycle")
  };
});

// src/app.ts
var exports_app = {};
__export(exports_app, {
  app: () => app,
  HypenModuleInstance: () => HypenModuleInstance,
  HypenAppBuilder: () => HypenAppBuilder,
  HypenApp: () => HypenApp
});

class HypenAppBuilder {
  initialState;
  options;
  createdHandler;
  actionHandlers = new Map;
  destroyedHandler;
  disconnectHandler;
  reconnectHandler;
  expireHandler;
  errorHandler;
  template;
  constructor(initialState, options) {
    this.initialState = initialState;
    this.options = options || {};
  }
  onCreated(fn) {
    this.createdHandler = fn;
    return this;
  }
  onAction(name, fn) {
    this.actionHandlers.set(name, fn);
    return this;
  }
  onDestroyed(fn) {
    this.destroyedHandler = fn;
    return this;
  }
  onDisconnect(fn) {
    this.disconnectHandler = fn;
    return this;
  }
  onReconnect(fn) {
    this.reconnectHandler = fn;
    return this;
  }
  onExpire(fn) {
    this.expireHandler = fn;
    return this;
  }
  onError(fn) {
    this.errorHandler = fn;
    return this;
  }
  ui(template) {
    this.template = template;
    return this.build();
  }
  build() {
    const stateKeys = this.initialState !== null && typeof this.initialState === "object" ? Object.keys(this.initialState) : [];
    return {
      name: this.options.name,
      actions: Array.from(this.actionHandlers.keys()),
      stateKeys,
      persist: this.options.persist,
      version: this.options.version,
      initialState: this.initialState,
      template: this.template,
      handlers: {
        onCreated: this.createdHandler,
        onAction: this.actionHandlers,
        onDestroyed: this.destroyedHandler,
        onDisconnect: this.disconnectHandler,
        onReconnect: this.reconnectHandler,
        onExpire: this.expireHandler,
        onError: this.errorHandler
      }
    };
  }
}

class HypenApp {
  defineState(initial, options) {
    return new HypenAppBuilder(initial, options);
  }
}

class HypenModuleInstance {
  engine;
  definition;
  state;
  isDestroyed = false;
  routerContext;
  globalContext;
  stateChangeCallbacks = [];
  constructor(engine, definition, routerContext, globalContext) {
    this.engine = engine;
    this.definition = definition;
    this.routerContext = routerContext;
    this.globalContext = globalContext;
    this.state = createObservableState(definition.initialState, {
      onChange: (change) => {
        this.engine.notifyStateChange(change.paths, change.newValues);
        this.stateChangeCallbacks.forEach((cb) => cb());
      }
    });
    this.engine.setModule(definition.name || "AnonymousModule", definition.actions, definition.stateKeys, getStateSnapshot(this.state));
    for (const [actionName, handler] of definition.handlers.onAction) {
      log2.debug(`Registering action handler: ${actionName} for module ${definition.name}`);
      this.engine.onAction(actionName, async (action) => {
        log2.debug(`Action handler fired: ${actionName}`, action);
        const actionCtx = {
          name: action.name,
          payload: action.payload,
          sender: action.sender
        };
        const next = {
          router: this.routerContext?.root || null
        };
        const context = this.globalContext ? this.createGlobalContextAPI() : undefined;
        const result = await this.executeAction(actionName, handler, {
          action: actionCtx,
          state: this.state,
          next,
          context
        });
        if (!result.ok) {
          const shouldRethrow = await this.handleError(result.error, { actionName });
          if (shouldRethrow) {
            throw result.error;
          }
        } else {
          log2.debug(`Action handler completed: ${actionName}`);
        }
      });
    }
    this.callCreatedHandler();
  }
  createGlobalContextAPI() {
    if (!this.globalContext) {
      throw new Error("Global context not available");
    }
    const ctx = this.globalContext;
    const api = {
      getModule: (id) => ctx.getModule(id),
      hasModule: (id) => ctx.hasModule(id),
      getModuleIds: () => ctx.getModuleIds(),
      getGlobalState: () => ctx.getGlobalState(),
      emit: (event, payload) => ctx.emit(event, payload),
      on: (event, handler) => ctx.on(event, handler)
    };
    if (ctx.__router) {
      api.__router = ctx.__router;
    }
    if (ctx.__hypenEngine) {
      api.__hypenEngine = ctx.__hypenEngine;
    }
    return api;
  }
  async executeAction(actionName, handler, ctx) {
    try {
      const result = handler(ctx);
      await result;
      return Ok(undefined);
    } catch (e) {
      return Err(new ActionError(actionName, e));
    }
  }
  async handleError(error, context) {
    const errorCtx = {
      error,
      state: this.state,
      actionName: context.actionName,
      lifecycle: context.lifecycle
    };
    if (this.definition.handlers.onError) {
      try {
        const result = await this.definition.handlers.onError(errorCtx);
        if (result && typeof result === "object") {
          if ("handled" in result && result.handled) {
            return false;
          }
          if ("rethrow" in result && result.rethrow) {
            return true;
          }
        }
      } catch (handlerError) {
        log2.error("Error in onError handler:", handlerError);
      }
    }
    if (this.globalContext) {
      const eventContext = context.actionName ? `action:${context.actionName}` : context.lifecycle ? `lifecycle:${context.lifecycle}` : "unknown";
      this.globalContext.emit("error", {
        message: error.message,
        error,
        context: eventContext
      });
    }
    log2.error(`${context.actionName ? `Action "${context.actionName}"` : `Lifecycle "${context.lifecycle}"`} error:`, error);
    return false;
  }
  async callCreatedHandler() {
    if (this.definition.handlers.onCreated) {
      const context = this.globalContext ? this.createGlobalContextAPI() : undefined;
      await this.definition.handlers.onCreated(this.state, context);
    }
  }
  onStateChange(callback) {
    this.stateChangeCallbacks.push(callback);
  }
  async destroy() {
    if (this.isDestroyed)
      return;
    if (this.definition.handlers.onDestroyed) {
      await this.definition.handlers.onDestroyed(this.state);
    }
    this.isDestroyed = true;
  }
  getState() {
    return getStateSnapshot(this.state);
  }
  getLiveState() {
    return this.state;
  }
  updateState(patch) {
    Object.assign(this.state, patch);
  }
}
var log2, app;
var init_app = __esm(() => {
  init_result();
  init_state();
  init_logger();
  log2 = createLogger("ModuleInstance");
  app = new HypenApp;
});
init_app();

export {
  app,
  HypenModuleInstance,
  HypenAppBuilder,
  HypenApp
};

//# debugId=F0743B5CC3E9E8A564756E2164756E21
