cogsbox-state 0.5.212 → 0.5.214

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,18 @@
1
1
  "use client";
2
- import { jsx as me } from "react/jsx-runtime";
3
- import { useState as le, useRef as Q, useEffect as de, useLayoutEffect as $e, useMemo as ke, createElement as te, useSyncExternalStore as Te, startTransition as Ae } from "react";
4
- import { transformStateFunc as Ne, isDeepEqual as G, isFunction as J, getNestedValue as W, getDifferences as ue, debounce as Ve } from "./utility.js";
5
- import { pushFunc as se, updateFn as Y, cutFunc as X, ValidationWrapper as _e, FormControlComponent as be } from "./Functions.jsx";
6
- import Ce from "superjson";
2
+ import { jsx as ye } from "react/jsx-runtime";
3
+ import { useState as de, useRef as te, useEffect as ue, useLayoutEffect as $e, useMemo as Ne, createElement as ae, useSyncExternalStore as Te, startTransition as Ae } from "react";
4
+ import { transformStateFunc as be, isDeepEqual as G, isFunction as B, getNestedValue as W, getDifferences as fe, debounce as Ve } from "./utility.js";
5
+ import { pushFunc as ce, updateFn as K, cutFunc as ee, ValidationWrapper as _e, FormControlComponent as Pe } from "./Functions.jsx";
6
+ import xe from "superjson";
7
7
  import { v4 as ge } from "uuid";
8
8
  import "zod";
9
- import { getGlobalStore as n, formRefStore as ye } from "./store.js";
9
+ import { getGlobalStore as r, formRefStore as ve } from "./store.js";
10
10
  import { useCogsConfig as we } from "./CogsStateClient.jsx";
11
- import { applyPatch as Pe } from "fast-json-patch";
12
- function ve(e, i) {
13
- const y = n.getState().getInitialOptions, u = n.getState().setInitialStateOptions, f = y(e) || {};
11
+ import { applyPatch as Ce } from "fast-json-patch";
12
+ function he(e, i) {
13
+ const y = r.getState().getInitialOptions, u = r.getState().setInitialStateOptions, g = y(e) || {};
14
14
  u(e, {
15
- ...f,
15
+ ...g,
16
16
  ...i
17
17
  });
18
18
  }
@@ -21,40 +21,40 @@ function Ie({
21
21
  options: i,
22
22
  initialOptionsPart: y
23
23
  }) {
24
- const u = Z(e) || {}, f = y[e] || {}, T = n.getState().setInitialStateOptions, h = { ...f, ...u };
25
- let I = !1;
24
+ const u = Y(e) || {}, g = y[e] || {}, $ = r.getState().setInitialStateOptions, p = { ...g, ...u };
25
+ let v = !1;
26
26
  if (i)
27
27
  for (const s in i)
28
- h.hasOwnProperty(s) ? (s == "localStorage" && i[s] && h[s].key !== i[s]?.key && (I = !0, h[s] = i[s]), s == "initialState" && i[s] && h[s] !== i[s] && // Different references
29
- !G(h[s], i[s]) && (I = !0, h[s] = i[s])) : (I = !0, h[s] = i[s]);
30
- I && T(e, h);
28
+ p.hasOwnProperty(s) ? (s == "localStorage" && i[s] && p[s].key !== i[s]?.key && (v = !0, p[s] = i[s]), s == "initialState" && i[s] && p[s] !== i[s] && // Different references
29
+ !G(p[s], i[s]) && (v = !0, p[s] = i[s])) : (v = !0, p[s] = i[s]);
30
+ v && $(e, p);
31
31
  }
32
- function Qe(e, { formElements: i, validation: y }) {
32
+ function Ke(e, { formElements: i, validation: y }) {
33
33
  return { initialState: e, formElements: i, validation: y };
34
34
  }
35
- const Ke = (e, i) => {
35
+ const et = (e, i) => {
36
36
  let y = e;
37
- const [u, f] = Ne(y);
38
- (Object.keys(f).length > 0 || i && Object.keys(i).length > 0) && Object.keys(f).forEach((I) => {
39
- f[I] = f[I] || {}, f[I].formElements = {
37
+ const [u, g] = be(y);
38
+ (Object.keys(g).length > 0 || i && Object.keys(i).length > 0) && Object.keys(g).forEach((v) => {
39
+ g[v] = g[v] || {}, g[v].formElements = {
40
40
  ...i?.formElements,
41
41
  // Global defaults first
42
42
  ...i?.validation,
43
- ...f[I].formElements || {}
43
+ ...g[v].formElements || {}
44
44
  // State-specific overrides
45
- }, Z(I) || n.getState().setInitialStateOptions(I, f[I]);
46
- }), n.getState().setInitialStates(u), n.getState().setCreatedState(u);
47
- const T = (I, s) => {
48
- const [S] = le(s?.componentId ?? ge());
45
+ }, Y(v) || r.getState().setInitialStateOptions(v, g[v]);
46
+ }), r.getState().setInitialStates(u), r.getState().setCreatedState(u);
47
+ const $ = (v, s) => {
48
+ const [S] = de(s?.componentId ?? ge());
49
49
  Ie({
50
- stateKey: I,
50
+ stateKey: v,
51
51
  options: s,
52
- initialOptionsPart: f
52
+ initialOptionsPart: g
53
53
  });
54
- const t = n.getState().cogsStateStore[I] || u[I], m = s?.modifyState ? s.modifyState(t) : t, [M, N] = Ue(
54
+ const t = r.getState().cogsStateStore[v] || u[v], m = s?.modifyState ? s.modifyState(t) : t, [U, V] = Me(
55
55
  m,
56
56
  {
57
- stateKey: I,
57
+ stateKey: v,
58
58
  syncUpdate: s?.syncUpdate,
59
59
  componentId: S,
60
60
  localStorage: s?.localStorage,
@@ -67,49 +67,49 @@ const Ke = (e, i) => {
67
67
  serverState: s?.serverState
68
68
  }
69
69
  );
70
- return N;
70
+ return V;
71
71
  };
72
- function h(I, s) {
73
- Ie({ stateKey: I, options: s, initialOptionsPart: f }), s.localStorage && Me(I, s), re(I);
72
+ function p(v, s) {
73
+ Ie({ stateKey: v, options: s, initialOptionsPart: g }), s.localStorage && Ue(v, s), ie(v);
74
74
  }
75
- return { useCogsState: T, setCogsOptions: h };
75
+ return { useCogsState: $, setCogsOptions: p };
76
76
  }, {
77
- setUpdaterState: K,
78
- setState: B,
79
- getInitialOptions: Z,
77
+ setUpdaterState: ne,
78
+ setState: H,
79
+ getInitialOptions: Y,
80
80
  getKeyState: Ee,
81
- getValidationErrors: xe,
82
- setStateLog: Oe,
83
- updateInitialStateGlobal: fe,
84
- addValidationError: Fe,
85
- removeValidationError: z,
86
- setServerSyncActions: Re
87
- } = n.getState(), he = (e, i, y, u, f) => {
81
+ getValidationErrors: Oe,
82
+ setStateLog: Fe,
83
+ updateInitialStateGlobal: Se,
84
+ addValidationError: Re,
85
+ removeValidationError: J,
86
+ setServerSyncActions: je
87
+ } = r.getState(), pe = (e, i, y, u, g) => {
88
88
  y?.log && console.log(
89
89
  "saving to localstorage",
90
90
  i,
91
91
  y.localStorage?.key,
92
92
  u
93
93
  );
94
- const T = J(y?.localStorage?.key) ? y.localStorage?.key(e) : y?.localStorage?.key;
95
- if (T && u) {
96
- const h = `${u}-${i}-${T}`;
97
- let I;
94
+ const $ = B(y?.localStorage?.key) ? y.localStorage?.key(e) : y?.localStorage?.key;
95
+ if ($ && u) {
96
+ const p = `${u}-${i}-${$}`;
97
+ let v;
98
98
  try {
99
- I = ne(h)?.lastSyncedWithServer;
99
+ v = oe(p)?.lastSyncedWithServer;
100
100
  } catch {
101
101
  }
102
102
  const s = {
103
103
  state: e,
104
104
  lastUpdated: Date.now(),
105
- lastSyncedWithServer: f ?? I
106
- }, S = Ce.serialize(s);
105
+ lastSyncedWithServer: g ?? v
106
+ }, S = xe.serialize(s);
107
107
  window.localStorage.setItem(
108
- h,
108
+ p,
109
109
  JSON.stringify(S.json)
110
110
  );
111
111
  }
112
- }, ne = (e) => {
112
+ }, oe = (e) => {
113
113
  if (!e) return null;
114
114
  try {
115
115
  const i = window.localStorage.getItem(e);
@@ -117,30 +117,30 @@ const Ke = (e, i) => {
117
117
  } catch (i) {
118
118
  return console.error("Error loading from localStorage:", i), null;
119
119
  }
120
- }, Me = (e, i) => {
121
- const y = n.getState().cogsStateStore[e], { sessionId: u } = we(), f = J(i?.localStorage?.key) ? i.localStorage.key(y) : i?.localStorage?.key;
122
- if (f && u) {
123
- const T = ne(
124
- `${u}-${e}-${f}`
120
+ }, Ue = (e, i) => {
121
+ const y = r.getState().cogsStateStore[e], { sessionId: u } = we(), g = B(i?.localStorage?.key) ? i.localStorage.key(y) : i?.localStorage?.key;
122
+ if (g && u) {
123
+ const $ = oe(
124
+ `${u}-${e}-${g}`
125
125
  );
126
- if (T && T.lastUpdated > (T.lastSyncedWithServer || 0))
127
- return B(e, T.state), re(e), !0;
126
+ if ($ && $.lastUpdated > ($.lastSyncedWithServer || 0))
127
+ return H(e, $.state), ie(e), !0;
128
128
  }
129
129
  return !1;
130
- }, pe = (e, i, y, u, f, T) => {
131
- const h = {
130
+ }, ke = (e, i, y, u, g, $) => {
131
+ const p = {
132
132
  initialState: i,
133
- updaterState: ee(
133
+ updaterState: re(
134
134
  e,
135
135
  u,
136
- f,
137
- T
136
+ g,
137
+ $
138
138
  ),
139
139
  state: y
140
140
  };
141
- fe(e, h.initialState), K(e, h.updaterState), B(e, h.state);
142
- }, re = (e) => {
143
- const i = n.getState().stateComponents.get(e);
141
+ Se(e, p.initialState), ne(e, p.updaterState), H(e, p.state);
142
+ }, ie = (e) => {
143
+ const i = r.getState().stateComponents.get(e);
144
144
  if (!i) return;
145
145
  const y = /* @__PURE__ */ new Set();
146
146
  i.components.forEach((u) => {
@@ -148,15 +148,15 @@ const Ke = (e, i) => {
148
148
  }), queueMicrotask(() => {
149
149
  y.forEach((u) => u());
150
150
  });
151
- }, et = (e, i) => {
152
- const y = n.getState().stateComponents.get(e);
151
+ }, tt = (e, i) => {
152
+ const y = r.getState().stateComponents.get(e);
153
153
  if (y) {
154
- const u = `${e}////${i}`, f = y.components.get(u);
155
- if ((f ? Array.isArray(f.reactiveType) ? f.reactiveType : [f.reactiveType || "component"] : null)?.includes("none"))
154
+ const u = `${e}////${i}`, g = y.components.get(u);
155
+ if ((g ? Array.isArray(g.reactiveType) ? g.reactiveType : [g.reactiveType || "component"] : null)?.includes("none"))
156
156
  return;
157
- f && f.forceUpdate();
157
+ g && g.forceUpdate();
158
158
  }
159
- }, je = (e, i, y, u) => {
159
+ }, De = (e, i, y, u) => {
160
160
  switch (e) {
161
161
  case "update":
162
162
  return {
@@ -179,57 +179,57 @@ const Ke = (e, i) => {
179
179
  return { oldValue: null, newValue: null };
180
180
  }
181
181
  };
182
- function Ue(e, {
182
+ function Me(e, {
183
183
  stateKey: i,
184
184
  serverSync: y,
185
185
  localStorage: u,
186
- formElements: f,
187
- reactiveDeps: T,
188
- reactiveType: h,
189
- componentId: I,
186
+ formElements: g,
187
+ reactiveDeps: $,
188
+ reactiveType: p,
189
+ componentId: v,
190
190
  initialState: s,
191
191
  syncUpdate: S,
192
192
  dependencies: t,
193
193
  serverState: m
194
194
  } = {}) {
195
- const [M, N] = le({}), { sessionId: V } = we();
196
- let j = !i;
197
- const [g] = le(i ?? ge()), c = n.getState().stateLog[g], H = Q(/* @__PURE__ */ new Set()), q = Q(I ?? ge()), _ = Q(
195
+ const [U, V] = de({}), { sessionId: _ } = we();
196
+ let D = !i;
197
+ const [f] = de(i ?? ge()), l = r.getState().stateLog[f], X = te(/* @__PURE__ */ new Set()), L = te(v ?? ge()), P = te(
198
198
  null
199
199
  );
200
- _.current = Z(g) ?? null, de(() => {
201
- if (S && S.stateKey === g && S.path?.[0]) {
202
- B(g, (a) => ({
200
+ P.current = Y(f) ?? null, ue(() => {
201
+ if (S && S.stateKey === f && S.path?.[0]) {
202
+ H(f, (a) => ({
203
203
  ...a,
204
204
  [S.path[0]]: S.newValue
205
205
  }));
206
206
  const o = `${S.stateKey}:${S.path.join(".")}`;
207
- n.getState().setSyncInfo(o, {
207
+ r.getState().setSyncInfo(o, {
208
208
  timeStamp: S.timeStamp,
209
209
  userId: S.userId
210
210
  });
211
211
  }
212
- }, [S]), de(() => {
212
+ }, [S]), ue(() => {
213
213
  if (s) {
214
- ve(g, {
214
+ he(f, {
215
215
  initialState: s
216
216
  });
217
- const o = _.current, l = o?.serverState?.id !== void 0 && o?.serverState?.status === "success" && o?.serverState?.data, w = n.getState().initialStateGlobal[g];
218
- if (!(w && !G(w, s) || !w) && !l)
217
+ const o = P.current, c = o?.serverState?.id !== void 0 && o?.serverState?.status === "success" && o?.serverState?.data, I = r.getState().initialStateGlobal[f];
218
+ if (!(I && !G(I, s) || !I) && !c)
219
219
  return;
220
220
  let E = null;
221
- const p = J(o?.localStorage?.key) ? o?.localStorage?.key(s) : o?.localStorage?.key;
222
- p && V && (E = ne(`${V}-${g}-${p}`));
223
- let k = s, b = !1;
224
- const P = l ? Date.now() : 0, x = E?.lastUpdated || 0, ae = E?.lastSyncedWithServer || 0;
225
- l && P > x ? (k = o.serverState.data, b = !0) : E && x > ae && (k = E.state, o?.localStorage?.onChange && o?.localStorage?.onChange(k)), pe(
226
- g,
221
+ const w = B(o?.localStorage?.key) ? o?.localStorage?.key(s) : o?.localStorage?.key;
222
+ w && _ && (E = oe(`${_}-${f}-${w}`));
223
+ let k = s, x = !1;
224
+ const C = c ? Date.now() : 0, R = E?.lastUpdated || 0, q = E?.lastSyncedWithServer || 0;
225
+ c && C > R ? (k = o.serverState.data, x = !0) : E && R > q && (k = E.state, o?.localStorage?.onChange && o?.localStorage?.onChange(k)), ke(
226
+ f,
227
227
  s,
228
228
  k,
229
229
  d,
230
- q.current,
231
- V
232
- ), b && p && V && he(k, g, o, V, Date.now()), re(g), (Array.isArray(h) ? h : [h || "component"]).includes("none") || N({});
230
+ L.current,
231
+ _
232
+ ), x && w && _ && pe(k, f, o, _, Date.now()), ie(f), (Array.isArray(p) ? p : [p || "component"]).includes("none") || V({});
233
233
  }
234
234
  }, [
235
235
  s,
@@ -237,723 +237,757 @@ function Ue(e, {
237
237
  m?.data,
238
238
  ...t || []
239
239
  ]), $e(() => {
240
- j && ve(g, {
240
+ D && he(f, {
241
241
  serverSync: y,
242
- formElements: f,
242
+ formElements: g,
243
243
  initialState: s,
244
244
  localStorage: u,
245
- middleware: _.current?.middleware
245
+ middleware: P.current?.middleware
246
246
  });
247
- const o = `${g}////${q.current}`, a = n.getState().stateComponents.get(g) || {
247
+ const o = `${f}////${L.current}`, a = r.getState().stateComponents.get(f) || {
248
248
  components: /* @__PURE__ */ new Map()
249
249
  };
250
250
  return a.components.set(o, {
251
- forceUpdate: () => N({}),
251
+ forceUpdate: () => V({}),
252
252
  paths: /* @__PURE__ */ new Set(),
253
253
  deps: [],
254
- depsFunction: T || void 0,
255
- reactiveType: h ?? ["component", "deps"]
256
- }), n.getState().stateComponents.set(g, a), N({}), () => {
257
- const l = `${g}////${q.current}`;
258
- a && (a.components.delete(l), a.components.size === 0 && n.getState().stateComponents.delete(g));
254
+ depsFunction: $ || void 0,
255
+ reactiveType: p ?? ["component", "deps"]
256
+ }), r.getState().stateComponents.set(f, a), V({}), () => {
257
+ const c = `${f}////${L.current}`;
258
+ a && (a.components.delete(c), a.components.size === 0 && r.getState().stateComponents.delete(f));
259
259
  };
260
260
  }, []);
261
- const d = (o, a, l, w) => {
261
+ const d = (o, a, c, I) => {
262
262
  if (Array.isArray(a)) {
263
- const v = `${g}-${a.join(".")}`;
264
- H.current.add(v);
263
+ const h = `${f}-${a.join(".")}`;
264
+ X.current.add(h);
265
265
  }
266
- B(g, (v) => {
267
- const E = J(o) ? o(v) : o, p = `${g}-${a.join(".")}`;
268
- if (p) {
269
- let D = !1, A = n.getState().signalDomElements.get(p);
270
- if ((!A || A.size === 0) && (l.updateType === "insert" || l.updateType === "cut")) {
271
- const F = a.slice(0, -1), U = W(E, F);
272
- if (Array.isArray(U)) {
273
- D = !0;
274
- const $ = `${g}-${F.join(".")}`;
275
- A = n.getState().signalDomElements.get($);
266
+ H(f, (h) => {
267
+ const E = B(o) ? o(h) : o, w = `${f}-${a.join(".")}`;
268
+ if (w) {
269
+ let F = !1, N = r.getState().signalDomElements.get(w);
270
+ if ((!N || N.size === 0) && (c.updateType === "insert" || c.updateType === "cut")) {
271
+ const j = a.slice(0, -1), O = W(E, j);
272
+ if (Array.isArray(O)) {
273
+ F = !0;
274
+ const b = `${f}-${j.join(".")}`;
275
+ N = r.getState().signalDomElements.get(b);
276
276
  }
277
277
  }
278
- if (A) {
279
- const F = D ? W(E, a.slice(0, -1)) : W(E, a);
280
- A.forEach(({ parentId: U, position: $, effect: O }) => {
281
- const C = document.querySelector(
282
- `[data-parent-id="${U}"]`
278
+ if (N) {
279
+ const j = F ? W(E, a.slice(0, -1)) : W(E, a);
280
+ N.forEach(({ parentId: O, position: b, effect: T }) => {
281
+ const A = document.querySelector(
282
+ `[data-parent-id="${O}"]`
283
283
  );
284
- if (C) {
285
- const L = Array.from(C.childNodes);
286
- if (L[$]) {
287
- const R = O ? new Function("state", `return (${O})(state)`)(F) : F;
288
- L[$].textContent = String(R);
284
+ if (A) {
285
+ const Z = Array.from(A.childNodes);
286
+ if (Z[b]) {
287
+ const z = T ? new Function("state", `return (${T})(state)`)(j) : j;
288
+ Z[b].textContent = String(z);
289
289
  }
290
290
  }
291
291
  });
292
292
  }
293
293
  }
294
- l.updateType === "update" && (w || _.current?.validation?.key) && a && z(
295
- (w || _.current?.validation?.key) + "." + a.join(".")
294
+ c.updateType === "update" && (I || P.current?.validation?.key) && a && J(
295
+ (I || P.current?.validation?.key) + "." + a.join(".")
296
296
  );
297
297
  const k = a.slice(0, a.length - 1);
298
- l.updateType === "cut" && _.current?.validation?.key && z(
299
- _.current?.validation?.key + "." + k.join(".")
300
- ), l.updateType === "insert" && _.current?.validation?.key && xe(
301
- _.current?.validation?.key + "." + k.join(".")
302
- ).filter(([A, F]) => {
303
- let U = A?.split(".").length;
304
- if (A == k.join(".") && U == k.length - 1) {
305
- let $ = A + "." + k;
306
- z(A), Fe($, F);
298
+ c.updateType === "cut" && P.current?.validation?.key && J(
299
+ P.current?.validation?.key + "." + k.join(".")
300
+ ), c.updateType === "insert" && P.current?.validation?.key && Oe(
301
+ P.current?.validation?.key + "." + k.join(".")
302
+ ).filter(([N, j]) => {
303
+ let O = N?.split(".").length;
304
+ if (N == k.join(".") && O == k.length - 1) {
305
+ let b = N + "." + k;
306
+ J(N), Re(b, j);
307
307
  }
308
308
  });
309
- const b = n.getState().stateComponents.get(g);
310
- if (b) {
311
- const D = ue(v, E), A = new Set(D), F = l.updateType === "update" ? a.join(".") : a.slice(0, -1).join(".") || "";
309
+ const x = r.getState().stateComponents.get(f);
310
+ if (x) {
311
+ const F = fe(h, E), N = new Set(F), j = c.updateType === "update" ? a.join(".") : a.slice(0, -1).join(".") || "", O = [];
312
312
  for (const [
313
- U,
314
- $
315
- ] of b.components.entries()) {
316
- let O = !1;
317
- const C = Array.isArray($.reactiveType) ? $.reactiveType : [$.reactiveType || "component"];
318
- if (!C.includes("none")) {
319
- if (C.includes("all")) {
320
- $.forceUpdate();
313
+ b,
314
+ T
315
+ ] of x.components.entries()) {
316
+ let A = !1;
317
+ const Z = Array.isArray(T.reactiveType) ? T.reactiveType : [T.reactiveType || "component"];
318
+ if (!Z.includes("none")) {
319
+ if (Z.includes("all")) {
320
+ O.push(T.forceUpdate);
321
321
  continue;
322
322
  }
323
- if (C.includes("component") && (($.paths.has(F) || $.paths.has("")) && (O = !0), !O))
324
- for (const L of A) {
325
- let R = L;
323
+ if (Z.includes("component") && ((T.paths.has(j) || T.paths.has("")) && (A = !0), !A))
324
+ for (const z of N) {
325
+ let M = z;
326
326
  for (; ; ) {
327
- if ($.paths.has(R)) {
328
- O = !0;
327
+ if (T.paths.has(M)) {
328
+ A = !0;
329
329
  break;
330
330
  }
331
- const ie = R.lastIndexOf(".");
332
- if (ie !== -1) {
333
- const Se = R.substring(
331
+ const se = M.lastIndexOf(".");
332
+ if (se !== -1) {
333
+ const me = M.substring(
334
334
  0,
335
- ie
335
+ se
336
336
  );
337
337
  if (!isNaN(
338
- Number(R.substring(ie + 1))
339
- ) && $.paths.has(Se)) {
340
- O = !0;
338
+ Number(M.substring(se + 1))
339
+ ) && T.paths.has(me)) {
340
+ A = !0;
341
341
  break;
342
342
  }
343
- R = Se;
343
+ M = me;
344
344
  } else
345
- R = "";
346
- if (R === "")
345
+ M = "";
346
+ if (M === "")
347
347
  break;
348
348
  }
349
- if (O) break;
349
+ if (A) break;
350
350
  }
351
- if (!O && C.includes("deps") && $.depsFunction) {
352
- const L = $.depsFunction(E);
353
- let R = !1;
354
- typeof L == "boolean" ? L && (R = !0) : G($.deps, L) || ($.deps = L, R = !0), R && (O = !0);
351
+ if (!A && Z.includes("deps") && T.depsFunction) {
352
+ const z = T.depsFunction(E);
353
+ let M = !1;
354
+ typeof z == "boolean" ? z && (M = !0) : G(T.deps, z) || (T.deps = z, M = !0), M && (A = !0);
355
355
  }
356
- O && $.forceUpdate();
356
+ A && O.push(T.forceUpdate);
357
357
  }
358
358
  }
359
+ O.length > 0 && queueMicrotask(() => {
360
+ O.forEach((b) => b());
361
+ });
359
362
  }
360
- const P = Date.now();
361
- a = a.map((D, A) => {
362
- const F = a.slice(0, -1), U = W(E, F);
363
- return A === a.length - 1 && ["insert", "cut"].includes(l.updateType) ? (U.length - 1).toString() : D;
364
- }), console.log(
365
- "mmmmmmmmmmmmmmmmm22222222222222",
366
- l.updateType,
367
- v,
368
- E,
369
- a
370
- );
371
- const { oldValue: x, newValue: ae } = je(
372
- l.updateType,
373
- v,
363
+ const C = Date.now();
364
+ a = a.map((F, N) => {
365
+ const j = a.slice(0, -1), O = W(E, j);
366
+ return N === a.length - 1 && ["insert", "cut"].includes(c.updateType) ? (O.length - 1).toString() : F;
367
+ });
368
+ const { oldValue: R, newValue: q } = De(
369
+ c.updateType,
370
+ h,
374
371
  E,
375
372
  a
376
- ), oe = {
377
- timeStamp: P,
378
- stateKey: g,
373
+ ), Q = {
374
+ timeStamp: C,
375
+ stateKey: f,
379
376
  path: a,
380
- updateType: l.updateType,
377
+ updateType: c.updateType,
381
378
  status: "new",
382
- oldValue: x,
383
- newValue: ae
379
+ oldValue: R,
380
+ newValue: q
384
381
  };
385
- if (Oe(g, (D) => {
386
- const F = [...D ?? [], oe].reduce((U, $) => {
387
- const O = `${$.stateKey}:${JSON.stringify($.path)}`, C = U.get(O);
388
- return C ? (C.timeStamp = Math.max(C.timeStamp, $.timeStamp), C.newValue = $.newValue, C.oldValue = C.oldValue ?? $.oldValue, C.updateType = $.updateType) : U.set(O, { ...$ }), U;
382
+ if (Fe(f, (F) => {
383
+ const j = [...F ?? [], Q].reduce((O, b) => {
384
+ const T = `${b.stateKey}:${JSON.stringify(b.path)}`, A = O.get(T);
385
+ return A ? (A.timeStamp = Math.max(A.timeStamp, b.timeStamp), A.newValue = b.newValue, A.oldValue = A.oldValue ?? b.oldValue, A.updateType = b.updateType) : O.set(T, { ...b }), O;
389
386
  }, /* @__PURE__ */ new Map());
390
- return Array.from(F.values());
391
- }), he(
387
+ return Array.from(j.values());
388
+ }), pe(
392
389
  E,
393
- g,
394
- _.current,
395
- V
396
- ), _.current?.middleware && _.current.middleware({
397
- updateLog: c,
398
- update: oe
399
- }), _.current?.serverSync) {
400
- const D = n.getState().serverState[g], A = _.current?.serverSync;
401
- Re(g, {
402
- syncKey: typeof A.syncKey == "string" ? A.syncKey : A.syncKey({ state: E }),
403
- rollBackState: D,
404
- actionTimeStamp: Date.now() + (A.debounce ?? 3e3),
390
+ f,
391
+ P.current,
392
+ _
393
+ ), P.current?.middleware && P.current.middleware({
394
+ updateLog: l,
395
+ update: Q
396
+ }), P.current?.serverSync) {
397
+ const F = r.getState().serverState[f], N = P.current?.serverSync;
398
+ je(f, {
399
+ syncKey: typeof N.syncKey == "string" ? N.syncKey : N.syncKey({ state: E }),
400
+ rollBackState: F,
401
+ actionTimeStamp: Date.now() + (N.debounce ?? 3e3),
405
402
  status: "waiting"
406
403
  });
407
404
  }
408
405
  return E;
409
406
  });
410
407
  };
411
- n.getState().updaterState[g] || (K(
412
- g,
413
- ee(
414
- g,
408
+ r.getState().updaterState[f] || (ne(
409
+ f,
410
+ re(
411
+ f,
415
412
  d,
416
- q.current,
417
- V
413
+ L.current,
414
+ _
418
415
  )
419
- ), n.getState().cogsStateStore[g] || B(g, e), n.getState().initialStateGlobal[g] || fe(g, e));
420
- const r = ke(() => ee(
421
- g,
416
+ ), r.getState().cogsStateStore[f] || H(f, e), r.getState().initialStateGlobal[f] || Se(f, e));
417
+ const n = Ne(() => re(
418
+ f,
422
419
  d,
423
- q.current,
424
- V
425
- ), [g]);
426
- return [Ee(g), r];
420
+ L.current,
421
+ _
422
+ ), [f, _]);
423
+ return [Ee(f), n];
427
424
  }
428
- function ee(e, i, y, u) {
429
- const f = /* @__PURE__ */ new Map();
430
- let T = 0;
431
- const h = (S) => {
425
+ function re(e, i, y, u) {
426
+ const g = /* @__PURE__ */ new Map();
427
+ let $ = 0;
428
+ const p = (S) => {
432
429
  const t = S.join(".");
433
- for (const [m] of f)
434
- (m === t || m.startsWith(t + ".")) && f.delete(m);
435
- T++;
436
- }, I = {
430
+ for (const [m] of g)
431
+ (m === t || m.startsWith(t + ".")) && g.delete(m);
432
+ $++;
433
+ }, v = {
437
434
  removeValidation: (S) => {
438
- S?.validationKey && z(S.validationKey);
435
+ S?.validationKey && J(S.validationKey);
439
436
  },
440
437
  revertToInitialState: (S) => {
441
- const t = n.getState().getInitialOptions(e)?.validation;
442
- t?.key && z(t?.key), S?.validationKey && z(S.validationKey);
443
- const m = n.getState().initialStateGlobal[e];
444
- n.getState().clearSelectedIndexesForState(e), f.clear(), T++;
445
- const M = s(m, []), N = Z(e), V = J(N?.localStorage?.key) ? N?.localStorage?.key(m) : N?.localStorage?.key, j = `${u}-${e}-${V}`;
446
- j && localStorage.removeItem(j), K(e, M), B(e, m);
447
- const g = n.getState().stateComponents.get(e);
448
- return g && g.components.forEach((c) => {
449
- c.forceUpdate();
438
+ const t = r.getState().getInitialOptions(e)?.validation;
439
+ t?.key && J(t?.key), S?.validationKey && J(S.validationKey);
440
+ const m = r.getState().initialStateGlobal[e];
441
+ r.getState().clearSelectedIndexesForState(e), g.clear(), $++;
442
+ const U = s(m, []), V = Y(e), _ = B(V?.localStorage?.key) ? V?.localStorage?.key(m) : V?.localStorage?.key, D = `${u}-${e}-${_}`;
443
+ D && localStorage.removeItem(D), ne(e, U), H(e, m);
444
+ const f = r.getState().stateComponents.get(e);
445
+ return f && f.components.forEach((l) => {
446
+ l.forceUpdate();
450
447
  }), m;
451
448
  },
452
449
  updateInitialState: (S) => {
453
- f.clear(), T++;
454
- const t = ee(
450
+ g.clear(), $++;
451
+ const t = re(
455
452
  e,
456
453
  i,
457
454
  y,
458
455
  u
459
- ), m = n.getState().initialStateGlobal[e], M = Z(e), N = J(M?.localStorage?.key) ? M?.localStorage?.key(m) : M?.localStorage?.key, V = `${u}-${e}-${N}`;
460
- return console.log("removing storage", V), localStorage.getItem(V) && localStorage.removeItem(V), Ae(() => {
461
- fe(e, S), K(e, t), B(e, S);
462
- const j = n.getState().stateComponents.get(e);
463
- j && j.components.forEach((g) => {
464
- g.forceUpdate();
456
+ ), m = r.getState().initialStateGlobal[e], U = Y(e), V = B(U?.localStorage?.key) ? U?.localStorage?.key(m) : U?.localStorage?.key, _ = `${u}-${e}-${V}`;
457
+ return localStorage.getItem(_) && localStorage.removeItem(_), Ae(() => {
458
+ Se(e, S), ne(e, t), H(e, S);
459
+ const D = r.getState().stateComponents.get(e);
460
+ D && D.components.forEach((f) => {
461
+ f.forceUpdate();
465
462
  });
466
463
  }), {
467
- fetchId: (j) => t.get()[j]
464
+ fetchId: (D) => t.get()[D]
468
465
  };
469
466
  },
470
- _initialState: n.getState().initialStateGlobal[e],
471
- _serverState: n.getState().serverState[e],
472
- _isLoading: n.getState().isLoadingGlobal[e],
467
+ _initialState: r.getState().initialStateGlobal[e],
468
+ _serverState: r.getState().serverState[e],
469
+ _isLoading: r.getState().isLoadingGlobal[e],
473
470
  _isServerSynced: () => {
474
- const S = n.getState().serverState[e];
471
+ const S = r.getState().serverState[e];
475
472
  return !!(S && G(S, Ee(e)));
476
473
  }
477
474
  };
478
475
  function s(S, t = [], m) {
479
- const M = t.map(String).join(".");
480
- f.get(M);
481
- const N = function() {
482
- return n().getNestedState(e, t);
476
+ const U = t.map(String).join(".");
477
+ g.get(U);
478
+ const V = function() {
479
+ return r().getNestedState(e, t);
483
480
  };
484
- Object.keys(I).forEach((g) => {
485
- N[g] = I[g];
486
- }), console.log("rebuildStateShapessss", t);
487
- const V = {
488
- apply(g, c, H) {
481
+ Object.keys(v).forEach((f) => {
482
+ V[f] = v[f];
483
+ });
484
+ const _ = {
485
+ apply(f, l, X) {
489
486
  return console.log(
490
487
  `PROXY APPLY TRAP HIT: stateKey=${e}, path=${t.join(".")}`
491
- ), console.trace("Apply trap stack trace"), n().getNestedState(e, t);
488
+ ), console.trace("Apply trap stack trace"), r().getNestedState(e, t);
492
489
  },
493
- get(g, c) {
494
- if (m?.validIndices && !Array.isArray(S) && (m = { ...m, validIndices: void 0 }), c !== "then" && !c.startsWith("$") && c !== "stateMapNoRender") {
495
- const d = t.join("."), r = `${e}////${y}`, o = n.getState().stateComponents.get(e);
496
- if (o) {
497
- const a = o.components.get(r);
498
- a && (t.length > 0 || c === "get") && a.paths.add(d);
490
+ get(f, l) {
491
+ if (m?.validIndices && !Array.isArray(S) && (m = { ...m, validIndices: void 0 }), !(l === "then" || l[0] === "$" || // Faster than startsWith
492
+ l === "stateMapNoRender")) {
493
+ const d = `${e}////${y}`, n = r.getState().stateComponents.get(e);
494
+ if (n) {
495
+ const o = n.components.get(d);
496
+ if (o && !o.paths.has("")) {
497
+ if (t.length === 0 && l === "get")
498
+ o.paths.add("");
499
+ else if (t.length > 0) {
500
+ const a = t.join(".");
501
+ if (o.paths.size === 0)
502
+ o.paths.add(a);
503
+ else {
504
+ let c = !0;
505
+ for (const I of o.paths) {
506
+ if (I === a) {
507
+ c = !1;
508
+ break;
509
+ }
510
+ if (I.length < a.length && a[I.length] === "." && a.substring(0, I.length) === I) {
511
+ c = !1;
512
+ break;
513
+ }
514
+ }
515
+ c && o.paths.add(a);
516
+ }
517
+ }
518
+ }
499
519
  }
500
520
  }
501
- if (c === "getDifferences")
502
- return () => ue(
503
- n.getState().cogsStateStore[e],
504
- n.getState().initialStateGlobal[e]
521
+ if (l === "getDifferences")
522
+ return () => fe(
523
+ r.getState().cogsStateStore[e],
524
+ r.getState().initialStateGlobal[e]
505
525
  );
506
- if (c === "sync" && t.length === 0)
526
+ if (l === "sync" && t.length === 0)
507
527
  return async function() {
508
- const d = n.getState().getInitialOptions(e), r = d?.sync;
509
- if (!r)
528
+ const d = r.getState().getInitialOptions(e), n = d?.sync;
529
+ if (!n)
510
530
  return console.error(`No mutation defined for state key "${e}"`), { success: !1, error: "No mutation defined" };
511
- const o = n.getState().getNestedState(e, []), a = d?.validation?.key;
531
+ const o = r.getState().getNestedState(e, []), a = d?.validation?.key;
512
532
  try {
513
- const l = await r.action(o);
514
- if (l && !l.success && l.errors && a) {
515
- n.getState().removeValidationError(a), l.errors.forEach((v) => {
516
- const E = [a, ...v.path].join(".");
517
- n.getState().addValidationError(E, v.message);
533
+ const c = await n.action(o);
534
+ if (c && !c.success && c.errors && a) {
535
+ r.getState().removeValidationError(a), c.errors.forEach((h) => {
536
+ const E = [a, ...h.path].join(".");
537
+ r.getState().addValidationError(E, h.message);
518
538
  });
519
- const w = n.getState().stateComponents.get(e);
520
- w && w.components.forEach((v) => {
521
- v.forceUpdate();
539
+ const I = r.getState().stateComponents.get(e);
540
+ I && I.components.forEach((h) => {
541
+ h.forceUpdate();
522
542
  });
523
543
  }
524
- return l?.success && r.onSuccess ? r.onSuccess(l.data) : !l?.success && r.onError && r.onError(l.error), l;
525
- } catch (l) {
526
- return r.onError && r.onError(l), { success: !1, error: l };
544
+ return c?.success && n.onSuccess ? n.onSuccess(c.data) : !c?.success && n.onError && n.onError(c.error), c;
545
+ } catch (c) {
546
+ return n.onError && n.onError(c), { success: !1, error: c };
527
547
  }
528
548
  };
529
- if (c === "_status") {
530
- const d = n.getState().getNestedState(e, t), r = n.getState().initialStateGlobal[e], o = W(r, t);
549
+ if (l === "_status") {
550
+ const d = r.getState().getNestedState(e, t), n = r.getState().initialStateGlobal[e], o = W(n, t);
531
551
  return G(d, o) ? "fresh" : "stale";
532
552
  }
533
- if (c === "getStatus")
553
+ if (l === "getStatus")
534
554
  return function() {
535
- const d = n().getNestedState(
555
+ const d = r().getNestedState(
536
556
  e,
537
557
  t
538
- ), r = n.getState().initialStateGlobal[e], o = W(r, t);
558
+ ), n = r.getState().initialStateGlobal[e], o = W(n, t);
539
559
  return G(d, o) ? "fresh" : "stale";
540
560
  };
541
- if (c === "removeStorage")
561
+ if (l === "removeStorage")
542
562
  return () => {
543
- const d = n.getState().initialStateGlobal[e], r = Z(e), o = J(r?.localStorage?.key) ? r?.localStorage?.key(d) : r?.localStorage?.key, a = `${u}-${e}-${o}`;
544
- console.log("removing storage", a), a && localStorage.removeItem(a);
563
+ const d = r.getState().initialStateGlobal[e], n = Y(e), o = B(n?.localStorage?.key) ? n?.localStorage?.key(d) : n?.localStorage?.key, a = `${u}-${e}-${o}`;
564
+ a && localStorage.removeItem(a);
545
565
  };
546
- if (c === "showValidationErrors")
566
+ if (l === "showValidationErrors")
547
567
  return () => {
548
- const d = n.getState().getInitialOptions(e)?.validation;
568
+ const d = r.getState().getInitialOptions(e)?.validation;
549
569
  if (!d?.key)
550
570
  throw new Error("Validation key not found");
551
- return n.getState().getValidationErrors(d.key + "." + t.join("."));
571
+ return r.getState().getValidationErrors(d.key + "." + t.join("."));
552
572
  };
553
573
  if (Array.isArray(S)) {
554
574
  const d = () => m?.validIndices ? S.map((o, a) => ({
555
575
  item: o,
556
576
  originalIndex: m.validIndices[a]
557
- })) : n.getState().getNestedState(e, t).map((o, a) => ({
577
+ })) : r.getState().getNestedState(e, t).map((o, a) => ({
558
578
  item: o,
559
579
  originalIndex: a
560
580
  }));
561
- if (c === "getSelected")
581
+ if (l === "getSelected")
562
582
  return () => {
563
- const r = n.getState().getSelectedIndex(e, t.join("."));
564
- if (r !== void 0)
583
+ const n = r.getState().getSelectedIndex(e, t.join("."));
584
+ if (n !== void 0)
565
585
  return s(
566
- S[r],
567
- [...t, r.toString()],
586
+ S[n],
587
+ [...t, n.toString()],
568
588
  m
569
589
  );
570
590
  };
571
- if (c === "clearSelected")
591
+ if (l === "clearSelected")
572
592
  return () => {
573
- n.getState().clearSelectedIndex({ stateKey: e, path: t });
593
+ r.getState().clearSelectedIndex({ stateKey: e, path: t });
574
594
  };
575
- if (c === "getSelectedIndex")
576
- return () => n.getState().getSelectedIndex(e, t.join(".")) ?? -1;
577
- if (c === "stateSort")
578
- return (r) => {
595
+ if (l === "getSelectedIndex")
596
+ return () => r.getState().getSelectedIndex(e, t.join(".")) ?? -1;
597
+ if (l === "stateSort")
598
+ return (n) => {
579
599
  const a = [...d()].sort(
580
- (v, E) => r(v.item, E.item)
581
- ), l = a.map(({ item: v }) => v), w = {
600
+ (h, E) => n(h.item, E.item)
601
+ ), c = a.map(({ item: h }) => h), I = {
582
602
  ...m,
583
603
  validIndices: a.map(
584
- ({ originalIndex: v }) => v
604
+ ({ originalIndex: h }) => h
585
605
  )
586
606
  };
587
- return s(l, t, w);
607
+ return s(c, t, I);
588
608
  };
589
- if (c === "stateFilter")
590
- return (r) => {
609
+ if (l === "stateFilter")
610
+ return (n) => {
591
611
  const a = d().filter(
592
- ({ item: v }, E) => r(v, E)
593
- ), l = a.map(({ item: v }) => v), w = {
612
+ ({ item: h }, E) => n(h, E)
613
+ ), c = a.map(({ item: h }) => h), I = {
594
614
  ...m,
595
615
  validIndices: a.map(
596
- ({ originalIndex: v }) => v
616
+ ({ originalIndex: h }) => h
597
617
  )
598
618
  };
599
- return s(l, t, w);
619
+ return s(c, t, I);
600
620
  };
601
- if (c === "stateMap" || c === "stateMapNoRender")
602
- return (r) => S.map((a, l) => {
603
- let w;
604
- m?.validIndices && m.validIndices[l] !== void 0 ? w = m.validIndices[l] : w = l;
605
- const v = [...t, w.toString()];
606
- console.log("stateMapstateMapstateMapstateMap", v);
607
- const E = s(a, v, m);
608
- return r(
621
+ if (l === "stateMap" || l === "stateMapNoRender")
622
+ return (n) => S.map((a, c) => {
623
+ let I;
624
+ m?.validIndices && m.validIndices[c] !== void 0 ? I = m.validIndices[c] : I = c;
625
+ const h = [...t, I.toString()], E = s(a, h, m);
626
+ return n(
609
627
  a,
610
628
  E,
611
- l,
629
+ c,
612
630
  S,
613
631
  s(S, t, m)
614
632
  );
615
633
  });
616
- if (c === "$stateMap")
617
- return (r) => te(De, {
634
+ if (l === "$stateMap")
635
+ return (n) => ae(Ge, {
618
636
  proxy: {
619
637
  _stateKey: e,
620
638
  _path: t,
621
- _mapFn: r
639
+ _mapFn: n
622
640
  // Pass the actual function, not string
623
641
  },
624
642
  rebuildStateShape: s
625
643
  });
626
- if (c === "stateFlattenOn")
627
- return (r) => {
644
+ if (l === "stateFlattenOn")
645
+ return (n) => {
628
646
  const o = S;
629
- f.clear(), T++;
647
+ g.clear(), $++;
630
648
  const a = o.flatMap(
631
- (l) => l[r] ?? []
649
+ (c) => c[n] ?? []
632
650
  );
633
651
  return s(
634
652
  a,
635
- [...t, "[*]", r],
653
+ [...t, "[*]", n],
636
654
  m
637
655
  );
638
656
  };
639
- if (c === "index")
640
- return (r) => {
641
- const o = S[r];
642
- return s(o, [...t, r.toString()]);
657
+ if (l === "index")
658
+ return (n) => {
659
+ const o = S[n];
660
+ return s(o, [...t, n.toString()]);
643
661
  };
644
- if (c === "last")
662
+ if (l === "last")
645
663
  return () => {
646
- const r = n.getState().getNestedState(e, t);
647
- if (r.length === 0) return;
648
- const o = r.length - 1, a = r[o], l = [...t, o.toString()];
649
- return s(a, l);
664
+ const n = r.getState().getNestedState(e, t);
665
+ if (n.length === 0) return;
666
+ const o = n.length - 1, a = n[o], c = [...t, o.toString()];
667
+ return s(a, c);
650
668
  };
651
- if (c === "insert")
652
- return (r) => (h(t), se(i, r, t, e), s(
653
- n.getState().getNestedState(e, t),
669
+ if (l === "insert")
670
+ return (n) => (p(t), ce(i, n, t, e), s(
671
+ r.getState().getNestedState(e, t),
654
672
  t
655
673
  ));
656
- if (c === "uniqueInsert")
657
- return (r, o, a) => {
658
- const l = n.getState().getNestedState(e, t), w = J(r) ? r(l) : r;
659
- let v = null;
660
- if (!l.some((p) => {
674
+ if (l === "uniqueInsert")
675
+ return (n, o, a) => {
676
+ const c = r.getState().getNestedState(e, t), I = B(n) ? n(c) : n;
677
+ let h = null;
678
+ if (!c.some((w) => {
661
679
  if (o) {
662
- const b = o.every(
663
- (P) => G(p[P], w[P])
680
+ const x = o.every(
681
+ (C) => G(w[C], I[C])
664
682
  );
665
- return b && (v = p), b;
683
+ return x && (h = w), x;
666
684
  }
667
- const k = G(p, w);
668
- return k && (v = p), k;
685
+ const k = G(w, I);
686
+ return k && (h = w), k;
669
687
  }))
670
- h(t), se(i, w, t, e);
671
- else if (a && v) {
672
- const p = a(v), k = l.map(
673
- (b) => G(b, v) ? p : b
688
+ p(t), ce(i, I, t, e);
689
+ else if (a && h) {
690
+ const w = a(h), k = c.map(
691
+ (x) => G(x, h) ? w : x
674
692
  );
675
- h(t), Y(i, k, t);
693
+ p(t), K(i, k, t);
676
694
  }
677
695
  };
678
- if (c === "cut")
679
- return (r, o) => {
696
+ if (l === "cut")
697
+ return (n, o) => {
680
698
  if (!o?.waitForSync)
681
- return h(t), X(i, t, e, r), s(
682
- n.getState().getNestedState(e, t),
699
+ return p(t), ee(i, t, e, n), s(
700
+ r.getState().getNestedState(e, t),
683
701
  t
684
702
  );
685
703
  };
686
- if (c === "cutByValue")
687
- return (r) => {
704
+ if (l === "cutByValue")
705
+ return (n) => {
688
706
  for (let o = 0; o < S.length; o++)
689
- S[o] === r && X(i, t, e, o);
707
+ S[o] === n && ee(i, t, e, o);
690
708
  };
691
- if (c === "toggleByValue")
692
- return (r) => {
693
- const o = S.findIndex((a) => a === r);
694
- o > -1 ? X(i, t, e, o) : se(i, r, t, e);
709
+ if (l === "toggleByValue")
710
+ return (n) => {
711
+ const o = S.findIndex((a) => a === n);
712
+ o > -1 ? ee(i, t, e, o) : ce(i, n, t, e);
695
713
  };
696
- if (c === "stateFind")
697
- return (r) => {
714
+ if (l === "stateFind")
715
+ return (n) => {
698
716
  const a = d().find(
699
- ({ item: w }, v) => r(w, v)
717
+ ({ item: I }, h) => n(I, h)
700
718
  );
701
719
  if (!a) return;
702
- const l = [...t, a.originalIndex.toString()];
703
- return s(a.item, l, m);
720
+ const c = [...t, a.originalIndex.toString()];
721
+ return s(a.item, c, m);
704
722
  };
705
- if (c === "findWith")
706
- return (r, o) => {
707
- const l = d().find(
708
- ({ item: v }) => v[r] === o
723
+ if (l === "findWith")
724
+ return (n, o) => {
725
+ const c = d().find(
726
+ ({ item: h }) => h[n] === o
709
727
  );
710
- if (!l) return;
711
- const w = [...t, l.originalIndex.toString()];
712
- return s(l.item, w, m);
728
+ if (!c) return;
729
+ const I = [...t, c.originalIndex.toString()];
730
+ return s(c.item, I, m);
713
731
  };
714
732
  }
715
- const H = t[t.length - 1];
716
- if (!isNaN(Number(H))) {
717
- const d = t.slice(0, -1), r = n.getState().getNestedState(e, d);
718
- if (Array.isArray(r) && c === "cut")
719
- return () => X(
733
+ const X = t[t.length - 1];
734
+ if (!isNaN(Number(X))) {
735
+ const d = t.slice(0, -1), n = r.getState().getNestedState(e, d);
736
+ if (Array.isArray(n) && l === "cut")
737
+ return () => ee(
720
738
  i,
721
739
  d,
722
740
  e,
723
- Number(H)
741
+ Number(X)
724
742
  );
725
743
  }
726
- if (c === "get")
727
- return () => n.getState().getNestedState(e, t);
728
- if (c === "$derive")
729
- return (d) => ce({
744
+ if (l === "get")
745
+ return () => r.getState().getNestedState(e, t);
746
+ if (l === "$derive")
747
+ return (d) => le({
730
748
  _stateKey: e,
731
749
  _path: t,
732
750
  _effect: d.toString()
733
751
  });
734
- if (c === "$derive")
735
- return (d) => ce({
752
+ if (l === "$derive")
753
+ return (d) => le({
736
754
  _stateKey: e,
737
755
  _path: t,
738
756
  _effect: d.toString()
739
757
  });
740
- if (c === "$get")
741
- return () => ce({
758
+ if (l === "$get")
759
+ return () => le({
742
760
  _stateKey: e,
743
761
  _path: t
744
762
  });
745
- if (c === "lastSynced") {
763
+ if (l === "lastSynced") {
746
764
  const d = `${e}:${t.join(".")}`;
747
- return n.getState().getSyncInfo(d);
765
+ return r.getState().getSyncInfo(d);
748
766
  }
749
- if (c == "getLocalStorage")
750
- return (d) => ne(u + "-" + e + "-" + d);
751
- if (c === "_selected") {
752
- const d = t.slice(0, -1), r = d.join("."), o = n.getState().getNestedState(e, d);
753
- return Array.isArray(o) ? Number(t[t.length - 1]) === n.getState().getSelectedIndex(e, r) : void 0;
767
+ if (l == "getLocalStorage")
768
+ return (d) => oe(u + "-" + e + "-" + d);
769
+ if (l === "_selected") {
770
+ const d = t.slice(0, -1), n = d.join("."), o = r.getState().getNestedState(e, d);
771
+ return Array.isArray(o) ? Number(t[t.length - 1]) === r.getState().getSelectedIndex(e, n) : void 0;
754
772
  }
755
- if (c === "setSelected")
773
+ if (l === "setSelected")
756
774
  return (d) => {
757
- const r = t.slice(0, -1), o = Number(t[t.length - 1]), a = r.join(".");
758
- d ? n.getState().setSelectedIndex(e, a, o) : n.getState().setSelectedIndex(e, a, void 0);
759
- const l = n.getState().getNestedState(e, [...r]);
760
- Y(i, l, r), h(r);
775
+ const n = t.slice(0, -1), o = Number(t[t.length - 1]), a = n.join(".");
776
+ d ? r.getState().setSelectedIndex(e, a, o) : r.getState().setSelectedIndex(e, a, void 0);
777
+ const c = r.getState().getNestedState(e, [...n]);
778
+ K(i, c, n), p(n);
761
779
  };
762
- if (c === "toggleSelected")
780
+ if (l === "toggleSelected")
763
781
  return () => {
764
- const d = t.slice(0, -1), r = Number(t[t.length - 1]), o = d.join("."), a = n.getState().getSelectedIndex(e, o);
765
- n.getState().setSelectedIndex(
782
+ const d = t.slice(0, -1), n = Number(t[t.length - 1]), o = d.join("."), a = r.getState().getSelectedIndex(e, o);
783
+ r.getState().setSelectedIndex(
766
784
  e,
767
785
  o,
768
- a === r ? void 0 : r
786
+ a === n ? void 0 : n
769
787
  );
770
- const l = n.getState().getNestedState(e, [...d]);
771
- Y(i, l, d), h(d);
788
+ const c = r.getState().getNestedState(e, [...d]);
789
+ K(i, c, d), p(d);
772
790
  };
773
791
  if (t.length == 0) {
774
- if (c === "applyJsonPatch")
792
+ if (l === "applyJsonPatch")
775
793
  return (d) => {
776
- const r = n.getState().cogsStateStore[e], a = Pe(r, d).newDocument;
777
- pe(
794
+ const n = r.getState().cogsStateStore[e], a = Ce(n, d).newDocument;
795
+ ke(
778
796
  e,
779
- n.getState().initialStateGlobal[e],
797
+ r.getState().initialStateGlobal[e],
780
798
  a,
781
799
  i,
782
800
  y,
783
801
  u
784
802
  );
785
- const l = n.getState().stateComponents.get(e);
786
- if (l) {
787
- const w = ue(r, a), v = new Set(w);
803
+ const c = r.getState().stateComponents.get(e);
804
+ if (c) {
805
+ const I = fe(n, a), h = new Set(I);
788
806
  for (const [
789
807
  E,
790
- p
791
- ] of l.components.entries()) {
808
+ w
809
+ ] of c.components.entries()) {
792
810
  let k = !1;
793
- const b = Array.isArray(p.reactiveType) ? p.reactiveType : [p.reactiveType || "component"];
794
- if (!b.includes("none")) {
795
- if (b.includes("all")) {
796
- p.forceUpdate();
811
+ const x = Array.isArray(w.reactiveType) ? w.reactiveType : [w.reactiveType || "component"];
812
+ if (!x.includes("none")) {
813
+ if (x.includes("all")) {
814
+ w.forceUpdate();
797
815
  continue;
798
816
  }
799
- if (b.includes("component") && (p.paths.has("") && (k = !0), !k))
800
- for (const P of v) {
801
- if (p.paths.has(P)) {
817
+ if (x.includes("component") && (w.paths.has("") && (k = !0), !k))
818
+ for (const C of h) {
819
+ if (w.paths.has(C)) {
802
820
  k = !0;
803
821
  break;
804
822
  }
805
- let x = P;
806
- for (; x.includes("."); )
807
- if (x = x.substring(
808
- 0,
809
- x.lastIndexOf(".")
810
- ), p.paths.has(x)) {
823
+ let R = C.lastIndexOf(".");
824
+ for (; R !== -1; ) {
825
+ const q = C.substring(0, R);
826
+ if (w.paths.has(q)) {
811
827
  k = !0;
812
828
  break;
813
829
  }
830
+ const Q = C.substring(
831
+ R + 1
832
+ );
833
+ if (!isNaN(Number(Q))) {
834
+ const F = q.lastIndexOf(".");
835
+ if (F !== -1) {
836
+ const N = q.substring(
837
+ 0,
838
+ F
839
+ );
840
+ if (w.paths.has(N)) {
841
+ k = !0;
842
+ break;
843
+ }
844
+ }
845
+ }
846
+ R = q.lastIndexOf(".");
847
+ }
814
848
  if (k) break;
815
849
  }
816
- if (!k && b.includes("deps") && p.depsFunction) {
817
- const P = p.depsFunction(a);
818
- let x = !1;
819
- typeof P == "boolean" ? P && (x = !0) : G(p.deps, P) || (p.deps = P, x = !0), x && (k = !0);
850
+ if (!k && x.includes("deps") && w.depsFunction) {
851
+ const C = w.depsFunction(a);
852
+ let R = !1;
853
+ typeof C == "boolean" ? C && (R = !0) : G(w.deps, C) || (w.deps = C, R = !0), R && (k = !0);
820
854
  }
821
- k && p.forceUpdate();
855
+ k && w.forceUpdate();
822
856
  }
823
857
  }
824
858
  }
825
859
  };
826
- if (c === "validateZodSchema")
860
+ if (l === "validateZodSchema")
827
861
  return () => {
828
- const d = n.getState().getInitialOptions(e)?.validation, r = n.getState().addValidationError;
862
+ const d = r.getState().getInitialOptions(e)?.validation, n = r.getState().addValidationError;
829
863
  if (!d?.zodSchema)
830
864
  throw new Error("Zod schema not found");
831
865
  if (!d?.key)
832
866
  throw new Error("Validation key not found");
833
- z(d.key);
834
- const o = n.getState().cogsStateStore[e];
867
+ J(d.key);
868
+ const o = r.getState().cogsStateStore[e];
835
869
  try {
836
- const a = n.getState().getValidationErrors(d.key);
837
- a && a.length > 0 && a.forEach(([w]) => {
838
- w && w.startsWith(d.key) && z(w);
870
+ const a = r.getState().getValidationErrors(d.key);
871
+ a && a.length > 0 && a.forEach(([I]) => {
872
+ I && I.startsWith(d.key) && J(I);
839
873
  });
840
- const l = d.zodSchema.safeParse(o);
841
- return l.success ? !0 : (l.error.errors.forEach((v) => {
842
- const E = v.path, p = v.message, k = [d.key, ...E].join(".");
843
- r(k, p);
844
- }), re(e), !1);
874
+ const c = d.zodSchema.safeParse(o);
875
+ return c.success ? !0 : (c.error.errors.forEach((h) => {
876
+ const E = h.path, w = h.message, k = [d.key, ...E].join(".");
877
+ n(k, w);
878
+ }), ie(e), !1);
845
879
  } catch (a) {
846
880
  return console.error("Zod schema validation failed", a), !1;
847
881
  }
848
882
  };
849
- if (c === "_componentId") return y;
850
- if (c === "getComponents")
851
- return () => n().stateComponents.get(e);
852
- if (c === "getAllFormRefs")
853
- return () => ye.getState().getFormRefsByStateKey(e);
854
- if (c === "_initialState")
855
- return n.getState().initialStateGlobal[e];
856
- if (c === "_serverState")
857
- return n.getState().serverState[e];
858
- if (c === "_isLoading")
859
- return n.getState().isLoadingGlobal[e];
860
- if (c === "revertToInitialState")
861
- return I.revertToInitialState;
862
- if (c === "updateInitialState") return I.updateInitialState;
863
- if (c === "removeValidation") return I.removeValidation;
883
+ if (l === "_componentId") return y;
884
+ if (l === "getComponents")
885
+ return () => r().stateComponents.get(e);
886
+ if (l === "getAllFormRefs")
887
+ return () => ve.getState().getFormRefsByStateKey(e);
888
+ if (l === "_initialState")
889
+ return r.getState().initialStateGlobal[e];
890
+ if (l === "_serverState")
891
+ return r.getState().serverState[e];
892
+ if (l === "_isLoading")
893
+ return r.getState().isLoadingGlobal[e];
894
+ if (l === "revertToInitialState")
895
+ return v.revertToInitialState;
896
+ if (l === "updateInitialState") return v.updateInitialState;
897
+ if (l === "removeValidation") return v.removeValidation;
864
898
  }
865
- if (c === "getFormRef")
866
- return () => ye.getState().getFormRef(e + "." + t.join("."));
867
- if (c === "validationWrapper")
899
+ if (l === "getFormRef")
900
+ return () => ve.getState().getFormRef(e + "." + t.join("."));
901
+ if (l === "validationWrapper")
868
902
  return ({
869
903
  children: d,
870
- hideMessage: r
871
- }) => /* @__PURE__ */ me(
904
+ hideMessage: n
905
+ }) => /* @__PURE__ */ ye(
872
906
  _e,
873
907
  {
874
- formOpts: r ? { validation: { message: "" } } : void 0,
908
+ formOpts: n ? { validation: { message: "" } } : void 0,
875
909
  path: t,
876
- validationKey: n.getState().getInitialOptions(e)?.validation?.key || "",
910
+ validationKey: r.getState().getInitialOptions(e)?.validation?.key || "",
877
911
  stateKey: e,
878
912
  validIndices: m?.validIndices,
879
913
  children: d
880
914
  }
881
915
  );
882
- if (c === "_stateKey") return e;
883
- if (c === "_path") return t;
884
- if (c === "_isServerSynced") return I._isServerSynced;
885
- if (c === "update")
886
- return (d, r) => {
887
- if (r?.debounce)
916
+ if (l === "_stateKey") return e;
917
+ if (l === "_path") return t;
918
+ if (l === "_isServerSynced") return v._isServerSynced;
919
+ if (l === "update")
920
+ return (d, n) => {
921
+ if (n?.debounce)
888
922
  Ve(() => {
889
- Y(i, d, t, "");
890
- const o = n.getState().getNestedState(e, t);
891
- r?.afterUpdate && r.afterUpdate(o);
892
- }, r.debounce);
923
+ K(i, d, t, "");
924
+ const o = r.getState().getNestedState(e, t);
925
+ n?.afterUpdate && n.afterUpdate(o);
926
+ }, n.debounce);
893
927
  else {
894
- Y(i, d, t, "");
895
- const o = n.getState().getNestedState(e, t);
896
- r?.afterUpdate && r.afterUpdate(o);
928
+ K(i, d, t, "");
929
+ const o = r.getState().getNestedState(e, t);
930
+ n?.afterUpdate && n.afterUpdate(o);
897
931
  }
898
- h(t);
932
+ p(t);
899
933
  };
900
- if (c === "formElement")
901
- return (d, r) => /* @__PURE__ */ me(
902
- be,
934
+ if (l === "formElement")
935
+ return (d, n) => /* @__PURE__ */ ye(
936
+ Pe,
903
937
  {
904
938
  setState: i,
905
939
  stateKey: e,
906
940
  path: t,
907
941
  child: d,
908
- formOpts: r
942
+ formOpts: n
909
943
  }
910
944
  );
911
- const q = [...t, c], _ = n.getState().getNestedState(e, q);
912
- return s(_, q, m);
945
+ const L = [...t, l], P = r.getState().getNestedState(e, L);
946
+ return s(P, L, m);
913
947
  }
914
- }, j = new Proxy(N, V);
915
- return f.set(M, {
916
- proxy: j,
917
- stateVersion: T
918
- }), j;
948
+ }, D = new Proxy(V, _);
949
+ return g.set(U, {
950
+ proxy: D,
951
+ stateVersion: $
952
+ }), D;
919
953
  }
920
954
  return s(
921
- n.getState().getNestedState(e, [])
955
+ r.getState().getNestedState(e, [])
922
956
  );
923
957
  }
924
- function ce(e) {
925
- return te(Ge, { proxy: e });
958
+ function le(e) {
959
+ return ae(We, { proxy: e });
926
960
  }
927
- function De({
961
+ function Ge({
928
962
  proxy: e,
929
963
  rebuildStateShape: i
930
964
  }) {
931
- const y = n().getNestedState(e._stateKey, e._path);
965
+ const y = r().getNestedState(e._stateKey, e._path);
932
966
  return Array.isArray(y) ? i(
933
967
  y,
934
968
  e._path
935
969
  ).stateMapNoRender(
936
- (f, T, h, I, s) => e._mapFn(f, T, h, I, s)
970
+ (g, $, p, v, s) => e._mapFn(g, $, p, v, s)
937
971
  ) : null;
938
972
  }
939
- function Ge({
973
+ function We({
940
974
  proxy: e
941
975
  }) {
942
- const i = Q(null), y = `${e._stateKey}-${e._path.join(".")}`;
943
- return de(() => {
976
+ const i = te(null), y = `${e._stateKey}-${e._path.join(".")}`;
977
+ return ue(() => {
944
978
  const u = i.current;
945
979
  if (!u || !u.parentElement) return;
946
- const f = u.parentElement, h = Array.from(f.childNodes).indexOf(u);
947
- let I = f.getAttribute("data-parent-id");
948
- I || (I = `parent-${crypto.randomUUID()}`, f.setAttribute("data-parent-id", I));
980
+ const g = u.parentElement, p = Array.from(g.childNodes).indexOf(u);
981
+ let v = g.getAttribute("data-parent-id");
982
+ v || (v = `parent-${crypto.randomUUID()}`, g.setAttribute("data-parent-id", v));
949
983
  const S = {
950
984
  instanceId: `instance-${crypto.randomUUID()}`,
951
- parentId: I,
952
- position: h,
985
+ parentId: v,
986
+ position: p,
953
987
  effect: e._effect
954
988
  };
955
- n.getState().addSignalElement(y, S);
956
- const t = n.getState().getNestedState(e._stateKey, e._path);
989
+ r.getState().addSignalElement(y, S);
990
+ const t = r.getState().getNestedState(e._stateKey, e._path);
957
991
  let m;
958
992
  if (e._effect)
959
993
  try {
@@ -961,24 +995,24 @@ function Ge({
961
995
  "state",
962
996
  `return (${e._effect})(state)`
963
997
  )(t);
964
- } catch (N) {
965
- console.error("Error evaluating effect function during mount:", N), m = t;
998
+ } catch (V) {
999
+ console.error("Error evaluating effect function during mount:", V), m = t;
966
1000
  }
967
1001
  else
968
1002
  m = t;
969
1003
  m !== null && typeof m == "object" && (m = JSON.stringify(m));
970
- const M = document.createTextNode(String(m));
971
- u.replaceWith(M);
972
- }, [e._stateKey, e._path.join("."), e._effect]), te("span", {
1004
+ const U = document.createTextNode(String(m));
1005
+ u.replaceWith(U);
1006
+ }, [e._stateKey, e._path.join("."), e._effect]), ae("span", {
973
1007
  ref: i,
974
1008
  style: { display: "none" },
975
1009
  "data-signal-id": y
976
1010
  });
977
1011
  }
978
- function tt(e) {
1012
+ function nt(e) {
979
1013
  const i = Te(
980
1014
  (y) => {
981
- const u = n.getState().stateComponents.get(e._stateKey) || {
1015
+ const u = r.getState().stateComponents.get(e._stateKey) || {
982
1016
  components: /* @__PURE__ */ new Map()
983
1017
  };
984
1018
  return u.components.set(e._stateKey, {
@@ -986,16 +1020,16 @@ function tt(e) {
986
1020
  paths: /* @__PURE__ */ new Set([e._path.join(".")])
987
1021
  }), () => u.components.delete(e._stateKey);
988
1022
  },
989
- () => n.getState().getNestedState(e._stateKey, e._path)
1023
+ () => r.getState().getNestedState(e._stateKey, e._path)
990
1024
  );
991
- return te("text", {}, String(i));
1025
+ return ae("text", {}, String(i));
992
1026
  }
993
1027
  export {
994
- ce as $cogsSignal,
995
- tt as $cogsSignalStore,
996
- Qe as addStateOptions,
997
- Ke as createCogsState,
998
- et as notifyComponent,
999
- Ue as useCogsStateFn
1028
+ le as $cogsSignal,
1029
+ nt as $cogsSignalStore,
1030
+ Ke as addStateOptions,
1031
+ et as createCogsState,
1032
+ tt as notifyComponent,
1033
+ Me as useCogsStateFn
1000
1034
  };
1001
1035
  //# sourceMappingURL=CogsState.jsx.map