import "@seamless/logger";
import { a as E } from "./initialize-logger.mjs";
import { g as A, S as w } from "./shared-logger.mjs";
import { b as se, c as ae, d as B, a as Q } from "./deep-merge.mjs";
import "@seamless/store";
import { w as ce } from "./with-usage-tracking.mjs";
const ie = A();
function b(t, r, n) {
  const e = n?.events?.[t];
  if (typeof e == "function")
    try {
      e(r);
    } catch (a) {
      try {
        n?.events?.onError?.({ error: a, context: { type: t, message: "Error in event hook", ...r } });
      } catch (o) {
        ie("Error in onError event hook", {
          args: [o],
          group: w.STORE,
          level: E.ERROR
        });
      }
    }
}
function le({
  options: t,
  prevBaseState: r,
  nextBaseState: n,
  action: e,
  args: a,
  meta: o,
  skipMiddleware: u
}) {
  if (!t?.middleware || u)
    return n;
  const s = Array.isArray(t.middleware) ? t.middleware : [t.middleware];
  let i = n;
  for (const f of s)
    try {
      const S = f({ prevState: r, nextState: i, action: e, args: a, meta: o });
      if (S instanceof Promise)
        throw new TypeError("Async (Promise-returning) middleware is not supported. Middleware must be synchronous.");
      if (S === !1)
        return !1;
      S && typeof S == "object" && (i = S);
    } catch (S) {
      return b("onError", { error: S, action: e, args: a, meta: o }, t), !1;
    }
  return i;
}
function P({ channel: t, baseState: r, shallow: n, sourceId: e }) {
  if (t)
    try {
      t.postMessage({
        type: "setState",
        sourceId: e,
        payload: r,
        shallow: n
      });
    } catch (a) {
      if (!(a instanceof Error) || a.name !== "InvalidStateError")
        throw a;
    }
}
const ue = A();
function W({
  baseState: t,
  derivedFunctions: r
}) {
  const n = {}, e = {};
  for (const [a, o] of Object.entries(r)) {
    const u = /* @__PURE__ */ new Set(), s = new Proxy(t, {
      get(i, f) {
        if (typeof f == "string") {
          if (f in r)
            throw new Error(
              `Derived function "${String(a)}" attempted to access another derived key "${f}". This is not allowed.`
            );
          if (f in i)
            return u.add(f), i[f];
        }
      }
    });
    try {
      n[a] = o(s), e[a] = u;
    } catch (i) {
      ue(`Error computing derived key "${String(a)}":`, {
        args: [i],
        group: w.STORE,
        level: E.ERROR
      });
    }
  }
  return { derivedState: n, derivedDependencies: e };
}
const de = A();
function fe(t, r) {
  const n = {};
  for (const e of Reflect.ownKeys(t)) {
    if (Object.hasOwn(r, e)) {
      de(
        `Attempted to set derived key "${String(e)}" via setState. Derived values are read-only and cannot be set directly.`,
        {
          group: w.STORE,
          level: E.WARN
        }
      );
      continue;
    }
    n[e] = t[e];
  }
  return n;
}
function Se({
  baseState: t,
  derivedFunctions: r,
  update: n,
  shallow: e
}) {
  const a = typeof n == "function" ? n(t) : n, o = fe(a, r);
  return e ? { ...t, ...o } : se(t, o);
}
const ve = Object.freeze([
  "getState",
  "setState",
  "subscribe",
  "subscribeTo",
  "resetState",
  "batch",
  "destroy",
  "unsubscribeAll"
]), ge = A();
function be(t = {}) {
  return Object.fromEntries(
    Object.entries(t).filter(([r]) => {
      const n = ve.includes(r);
      return n && ge(`User-defined API method "${r}" conflicts with core store method and was ignored.`, {
        args: [r],
        group: w.STORE,
        level: E.WARN
      }), !n;
    })
  );
}
function he(t, r) {
  const n = /* @__PURE__ */ new Set(), e = /* @__PURE__ */ new Set([...Reflect.ownKeys(t), ...Reflect.ownKeys(r)]);
  for (const a of e)
    r[a] !== t[a] && n.add(a);
  return n;
}
function C(t, r) {
  return { ...t, ...r };
}
function X({
  baseState: t,
  derivedFunctions: r,
  changedKeys: n,
  prevDerivedState: e,
  prevDerivedDependencies: a
}) {
  const o = { ...e }, u = { ...a };
  for (const [s, i] of Object.entries(r)) {
    const f = a[s];
    if (f && [...f].some((S) => n.has(S))) {
      const { derivedState: S, derivedDependencies: g } = W({
        baseState: t,
        derivedFunctions: { [s]: i }
      }), R = S[s], y = e[s];
      if (Object.is(R, y))
        continue;
      o[s] = S[s], u[s] = g[s];
    }
  }
  return { derivedState: o, derivedDependencies: u };
}
const Y = A();
function ye(t, r) {
  try {
    if (typeof r == "object" && r.enable && r.key)
      return new BroadcastChannel(r.key);
    if (r === !0 && t)
      return new BroadcastChannel(`store-sync:${t}`);
    r === !0 && Y(
      'Tab sync requires an "owner" to be defined when no custom key is provided. Set the "owner" option or provide a custom tabSync.key.',
      {
        group: w.STORE,
        level: E.WARN
      }
    );
  } catch (n) {
    Y("BroadcastChannel not available or failed to initialize:", {
      args: [n],
      group: w.STORE,
      level: E.WARN
    });
  }
  return null;
}
function me(t, r) {
  const n = {};
  for (const e in r) {
    const a = r[e];
    typeof a == "function" && (n[e] = ((...o) => {
      const u = t.setState, i = { ...t, setState: (f, S = {}) => u.call(t, f, { ...S, action: e, args: o }), ...n };
      return a(i, ...o);
    }));
  }
  return n;
}
const pe = A();
function Ee({
  owner: t,
  enableUsageTracking: r = !1,
  stateCoreMethods: n,
  userDefinedApi: e,
  subscriptionMethods: a,
  untrackedMethods: o = {}
}) {
  const u = new Set(Object.keys(o)), s = me(n, e);
  if (!t)
    return r && pe('Tracking requires an "owner" to be defined. Set the "owner" option to use this feature.', {
      group: w.STORE,
      level: E.WARN
    }), {
      ...n,
      ...a,
      ...s,
      ...o
    };
  const i = Object.fromEntries(
    Object.entries(n).filter(([g]) => !u.has(g))
  ), f = Object.fromEntries(
    Object.entries(a).filter(([g]) => !u.has(g))
  );
  return {
    ...ce(t, {
      ...i,
      ...f,
      ...s
    }),
    ...o
  };
}
function we({
  channel: t,
  sourceId: r,
  setState: n,
  getBaseState: e,
  tabCounterKey: a,
  isStateBroadcasted: o
}) {
  Number(localStorage.getItem(a)) <= 1 && Re(a), t.addEventListener("message", (s) => {
    const { type: i, payload: f, sourceId: S, shallow: g } = s.data || {};
    if (S === r)
      return;
    if (i === "requestState") {
      t.postMessage({ type: "setState", payload: e(), sourceId: r, shallow: !1 });
      return;
    }
    const R = ae(f, e());
    if (!(!f || i !== "setState" || R)) {
      o.value = !0;
      try {
        n(() => f, { shallow: g, skipMiddleware: !0 });
      } finally {
        o.value = !1;
      }
    }
  });
}
function Re(t) {
  const r = Number(localStorage.getItem(t) ?? "0") + 1;
  return localStorage.setItem(t, String(r)), r;
}
function Oe(t) {
  const r = Math.max(0, Number(localStorage.getItem(t) ?? "1") - 1);
  return localStorage.setItem(t, String(r)), r;
}
const Te = A();
function Ae(t, r, n) {
  for (const e of Reflect.ownKeys(n)) {
    const a = n[e];
    if (!a || a.size === 0)
      continue;
    const o = t[e], u = r[e];
    o !== u && Array.from(a).forEach((s) => {
      try {
        s(o, { prevValue: u, state: t });
      } catch (i) {
        Te(`Error in subscriber for key "${String(e)}":`, {
          args: [i],
          group: w.STORE,
          level: E.ERROR
        });
      }
    });
  }
}
const De = A();
function V({
  nextState: t,
  prevState: r,
  subscriptions: n,
  keySubscriptions: e,
  isReady: a
}) {
  a.value && (n.forEach((o) => {
    try {
      o(t);
    } catch (u) {
      De("Error in global subscription:", {
        args: [u],
        group: w.STORE,
        level: E.ERROR
      });
    }
  }), Ae(t, r, e));
}
function Ce(t, r, n) {
  let e = B(t);
  if (n?.persistence) {
    const { key: a, storage: o = localStorage, deserialize: u = JSON.parse } = n.persistence;
    try {
      const s = o.getItem(a);
      s && (e = u(s), r.value = !0);
    } catch (s) {
      b("onError", { error: s, context: { type: "hydrate", state: t } }, n);
    }
  }
  return e;
}
function F(t, r) {
  if (!r?.persistence)
    return;
  const { key: n, storage: e = localStorage, serialize: a = JSON.stringify } = r.persistence;
  try {
    const o = a(t);
    e.getItem(n) !== o && e.setItem(n, o);
  } catch (o) {
    b("onError", { error: o, context: { type: "persist", state: t } }, r);
  }
}
function $e({ channel: t, sourceId: r, isHydrated: n, tabCounterKey: e }) {
  return Number(localStorage.getItem(e)) <= 1 || n.value ? (n.value = !0, Promise.resolve()) : (t.postMessage({ type: "requestState", sourceId: r }), new Promise((o) => {
    const u = (s) => {
      const { type: i } = s.data || {};
      i === "setState" && (n.value = !0, t.removeEventListener("message", u), o());
    };
    t.addEventListener("message", u), setTimeout(() => {
      t.removeEventListener("message", u), n.value = !0, o();
    }, 1e3);
  }));
}
function Z({
  nextBaseState: t,
  changedKeys: r,
  batchDepth: n,
  batchScheduled: e,
  pendingBaseState: a,
  pendingChangedKeys: o
}) {
  return n.value > 0 ? (a.value = t, o.value ? r.forEach((u) => o.value?.add(u)) : o.value = new Set(r), e.value = !0, !0) : !1;
}
const je = A();
function ze({ owner: t, initialState: r, derived: n = {}, options: e, api: a }) {
  const o = { value: !e?.controlledReady }, u = { value: !1 };
  let s = Ce(r, u, e), { derivedState: i, derivedDependencies: f } = W({ baseState: s, derivedFunctions: n });
  const S = be(a), g = /* @__PURE__ */ new Set(), R = /* @__PURE__ */ new Set(), y = {}, D = {}, $ = { value: 0 }, K = { value: !1 }, j = { value: null }, L = { value: null }, x = crypto.randomUUID(), O = ye(t, e?.tabSync), _ = { value: !1 };
  let I = null;
  const U = `${O?.name}_tabCounter`;
  function q(c, {
    shallow: l = e?.defaultShallow ?? !1,
    action: d = "setState",
    args: h = [],
    meta: m,
    skipMiddleware: z = !1
  } = {}) {
    const p = C(s, i), T = { action: d, args: h, meta: m, options: e };
    try {
      let v = Se({
        baseState: $.value > 0 && j.value ? j.value : s,
        derivedFunctions: n,
        update: c,
        shallow: l
      });
      const M = he(s, v);
      if (M.size === 0 || (v = le({
        prevBaseState: s,
        nextBaseState: Q(v),
        skipMiddleware: z,
        ...T
      }), v === !1) || Z({ batchDepth: $, batchScheduled: K, pendingBaseState: j, pendingChangedKeys: L, changedKeys: M, nextBaseState: v }))
        return;
      s = v, { derivedState: i, derivedDependencies: f } = X({
        baseState: s,
        derivedFunctions: n,
        changedKeys: M,
        prevDerivedState: i,
        prevDerivedDependencies: f
      });
      const k = C(s, i);
      b("onAction", { action: d, args: h, prevState: p, nextState: k, meta: m }, e), b("onState", { prevState: p, nextState: k, action: d, meta: m }, e), F(v, e), V({ keySubscriptions: y, subscriptions: g, nextState: k, prevState: p, isReady: o }), _.value || P({ channel: O, baseState: v, shallow: l, sourceId: x });
    } catch (v) {
      b("onError", { error: v, context: { type: "setState", action: d, args: h, prevState: p, meta: m } }, e);
    }
  }
  function N() {
    let c = C(s, i);
    return e?.cloneState !== !1 && (c = B(c)), e?.freezeState !== !1 && (c = Q(c)), c;
  }
  function ee() {
    if (Z({
      batchDepth: $,
      batchScheduled: K,
      pendingBaseState: j,
      pendingChangedKeys: L,
      changedKeys: new Set(Object.keys(r)),
      nextBaseState: B(r)
    }))
      return;
    const c = C(s, i);
    s = B(r), { derivedState: i, derivedDependencies: f } = W({ baseState: s, derivedFunctions: n });
    const l = C(s, i);
    V({ nextState: l, subscriptions: g, prevState: c, keySubscriptions: y, isReady: o }), P({ channel: O, baseState: s, shallow: !0, sourceId: x }), b("onAction", { action: "resetState", args: [], prevState: c, nextState: l }, e), b("onState", { prevState: c, nextState: l, action: "resetState" }, e), F(s, e);
  }
  function te(c, l) {
    let d = c;
    if (l?.once && (d = (h) => {
      c(h), g.delete(d);
    }), g.add(d), l?.emitImmediately !== !1 && o.value)
      try {
        d(N());
      } catch (h) {
        b(
          "onError",
          {
            error: h,
            context: {
              type: "subscribe",
              message: "Error in initial subscriber callback"
            }
          },
          e
        );
      }
    else l?.emitImmediately !== !1 && !o.value && R.add(d);
    return () => {
      g.delete(d), R.delete(d);
    };
  }
  function re(c, l, d) {
    const h = d?.emitImmediately !== !1, m = h && !o.value;
    function z() {
      return m ? (D[c] ??= /* @__PURE__ */ new Set(), D[c]) : (y[c] ??= /* @__PURE__ */ new Set(), y[c]);
    }
    const p = z();
    if (p.has(l))
      return je(`Duplicate subscription to key "${String(c)}"`, {
        group: w.STORE,
        level: E.WARN
      }), () => {
        p.delete(l), D[c]?.delete(l), y[c]?.delete(l);
      };
    let T = l;
    if (d?.once && (T = (v, M) => {
      l(v, M), D[c]?.delete(T), y[c]?.delete(T);
    }), p.add(T), h && !m && o.value)
      try {
        const v = N();
        T(v[c], { prevValue: void 0, state: v });
      } catch (v) {
        b(
          "onError",
          {
            error: v,
            context: {
              type: "subscribeTo",
              key: c,
              message: `Error in immediate subscription callback for "${String(c)}"`
            }
          },
          e
        );
      }
    return () => {
      D[c]?.delete(T), y[c]?.delete(T);
    };
  }
  function G() {
    g.clear(), R.clear(), Object.entries(y).forEach(([c, l]) => {
      l.clear(), delete y[c];
    }), Object.entries(D).forEach(([c, l]) => {
      l.clear(), delete D[c];
    });
  }
  async function ne() {
    O && (we({
      getBaseState: () => s,
      setState: q,
      channel: O,
      sourceId: x,
      tabCounterKey: U,
      isStateBroadcasted: _
    }), await $e({ channel: O, sourceId: x, isHydrated: u, tabCounterKey: U }), I || (I = (c) => {
      c.persisted || J();
    }, globalThis.window?.addEventListener?.("pagehide", I)));
  }
  function H(c) {
    if (c.constructor.name === "AsyncFunction")
      throw new Error("Async batch functions are not supported.");
    const l = C(s, i);
    $.value++;
    try {
      c();
    } finally {
      if ($.value--, $.value === 0 && K.value) {
        s = j.value, { derivedState: i, derivedDependencies: f } = X({
          baseState: s,
          derivedFunctions: n,
          changedKeys: L.value,
          prevDerivedState: i,
          prevDerivedDependencies: f
        }), j.value = null, L.value = null;
        const d = C(s, i);
        b("onAction", { action: "resetState", args: [], prevState: l, nextState: d }, e), b("onState", { prevState: l, nextState: d, action: "resetState" }, e), F(s, e), V({ nextState: d, subscriptions: g, prevState: l, keySubscriptions: y, isReady: o }), P({ channel: O, baseState: s, shallow: !1, sourceId: x }), K.value = !1;
      }
    }
  }
  function J() {
    G(), I && (globalThis.window?.removeEventListener?.("pagehide", I), I = null), O?.close(), O && Oe(U);
  }
  function oe() {
    o.value = !0;
    const c = N();
    R.forEach((l) => {
      try {
        l(c);
      } catch (d) {
        b(
          "onError",
          {
            error: d,
            context: {
              type: "subscribe",
              message: "Error in deferred subscriber callback"
            }
          },
          e
        );
      }
    }), R.clear(), Object.entries(D).forEach(([l, d]) => {
      d.forEach(
        (h) => {
          try {
            h(c[l], { prevValue: void 0, state: c });
          } catch (m) {
            b(
              "onError",
              {
                error: m,
                context: {
                  type: "subscribeTo",
                  key: l,
                  message: `Error in deferred subscription callback for "${String(l)}"`
                }
              },
              e
            );
          }
        }
      ), d.clear();
    });
  }
  return Ee({
    owner: t,
    stateCoreMethods: {
      getState: N,
      setState: q,
      batch: H,
      resetState: ee
    },
    userDefinedApi: S,
    subscriptionMethods: {
      subscribe: te,
      subscribeTo: re,
      unsubscribeAll: G
    },
    untrackedMethods: {
      batch: H,
      destroy: J,
      setupTabSync: ne,
      setReady: oe
    },
    enableUsageTracking: e?.enableUsageTracking
  });
}
export {
  ze as c
};
//# sourceMappingURL=create-store.mjs.map
