cogsbox-state 0.5.37 → 0.5.39

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.
@@ -2,73 +2,75 @@
2
2
  import { jsx as it } from "react/jsx-runtime";
3
3
  import { useState as Y, useRef as z, useEffect as K, useLayoutEffect as vt, useMemo as It, createElement as H, useSyncExternalStore as Et, startTransition as J } from "react";
4
4
  import { transformStateFunc as _t, isFunction as ft, getNestedValue as L, isDeepEqual as G, debounce as pt } from "./utility.js";
5
- import { pushFunc as st, updateFn as q, cutFunc as ct, ValidationWrapper as wt, FormControlComponent as Nt } from "./Functions.jsx";
5
+ import { pushFunc as st, updateFn as q, cutFunc as ct, ValidationWrapper as wt, FormControlComponent as Vt } from "./Functions.jsx";
6
6
  import "zod";
7
- import { getGlobalStore as a, formRefStore as lt } from "./store.js";
8
- import { useCogsConfig as Vt } from "./CogsStateClient.jsx";
7
+ import { getGlobalStore as o, formRefStore as lt } from "./store.js";
8
+ import { useCogsConfig as Nt } from "./CogsStateClient.jsx";
9
9
  import tt from "./node_modules/uuid/dist/esm-browser/v4.js";
10
- function dt(t, o) {
11
- const f = a.getState().getInitialOptions, u = a.getState().setInitialStateOptions, d = f(t) || {};
12
- return u(t, {
13
- ...d,
14
- ...o
10
+ function dt(t, a) {
11
+ const f = o.getState().getInitialOptions, u = o.getState().setInitialStateOptions, c = f(t) || {};
12
+ return a.log && (console.log("setAndMergeOptions", t, a), console.log("setAndMergeOptions oldValue", c)), u(t, {
13
+ ...c,
14
+ ...a
15
15
  }), {
16
- ...d,
17
- ...o
16
+ ...c,
17
+ ...a
18
18
  };
19
19
  }
20
20
  function ut({
21
21
  stateKey: t,
22
- options: o,
22
+ options: a,
23
23
  initialOptionsPart: f
24
24
  }) {
25
- const u = et(t) || {}, d = f[t] || {}, _ = a.getState().setInitialStateOptions, w = { ...d, ...u };
26
- let v = !1;
27
- if (o)
28
- for (const m in o)
29
- w.hasOwnProperty(m) || (v = !0, w[m] = o[m]);
30
- v && _(t, w);
25
+ const u = et(t) || {}, c = f[t] || {}, _ = o.getState().setInitialStateOptions, w = { ...c, ...u };
26
+ let y = !1;
27
+ if (a)
28
+ for (const S in a)
29
+ w.hasOwnProperty(S) || (y = !0, w[S] = a[S]);
30
+ y && _(t, w);
31
31
  }
32
- function Wt(t, { formElements: o, validation: f }) {
33
- return { initialState: t, formElements: o, validation: f };
32
+ function Wt(t, { formElements: a, validation: f }) {
33
+ return { initialState: t, formElements: a, validation: f };
34
34
  }
35
- const qt = (t, o) => {
35
+ const qt = (t, a) => {
36
36
  let f = t;
37
- const [u, d] = _t(f);
38
- (o?.formElements || o?.validation) && Object.keys(d).forEach((v) => {
39
- d[v] = d[v] || {}, d[v].formElements = {
40
- ...o.formElements,
37
+ const [u, c] = _t(f);
38
+ (a?.formElements || a?.validation) && Object.keys(c).forEach((y) => {
39
+ c[y] = c[y] || {}, c[y].formElements = {
40
+ ...a.formElements,
41
41
  // Global defaults first
42
- ...o?.validation,
43
- ...d[v].formElements || {}
42
+ ...a?.validation,
43
+ ...c[y].formElements || {}
44
44
  // State-specific overrides
45
45
  };
46
- }), a.getState().setInitialStates(u);
47
- const _ = (v, m) => {
48
- const [p] = Y(m?.componentId ?? tt());
46
+ }), o.getState().setInitialStates(u);
47
+ const _ = (y, S) => {
48
+ const [p] = Y(S?.componentId ?? tt());
49
49
  ut({
50
- stateKey: v,
51
- options: m,
52
- initialOptionsPart: d
50
+ stateKey: y,
51
+ options: S,
52
+ initialOptionsPart: c
53
53
  });
54
- const s = a.getState().cogsStateStore[v] || u[v], e = m?.modifyState ? m.modifyState(s) : s, [I, V] = jt(
54
+ const s = o.getState().cogsStateStore[y] || u[y], e = S?.modifyState ? S.modifyState(s) : s;
55
+ S?.log && console.log("useCogsState", y, S);
56
+ const [I, N] = Ot(
55
57
  e,
56
58
  {
57
- stateKey: v,
58
- syncUpdate: m?.syncUpdate,
59
+ stateKey: y,
60
+ syncUpdate: S?.syncUpdate,
59
61
  componentId: p,
60
- localStorage: m?.localStorage,
61
- middleware: m?.middleware,
62
- enabledSync: m?.enabledSync,
63
- reactiveType: m?.reactiveType,
64
- reactiveDeps: m?.reactiveDeps,
65
- initState: m?.initState
62
+ localStorage: S?.localStorage,
63
+ middleware: S?.middleware,
64
+ enabledSync: S?.enabledSync,
65
+ reactiveType: S?.reactiveType,
66
+ reactiveDeps: S?.reactiveDeps,
67
+ initState: S?.initState
66
68
  }
67
69
  );
68
- return V;
70
+ return N;
69
71
  };
70
- function w(v, m) {
71
- ut({ stateKey: v, options: m, initialOptionsPart: d });
72
+ function w(y, S) {
73
+ ut({ stateKey: y, options: S, initialOptionsPart: c });
72
74
  }
73
75
  return { useCogsState: _, setCogsOptions: w };
74
76
  }, {
@@ -80,38 +82,38 @@ const qt = (t, o) => {
80
82
  setStateLog: ht,
81
83
  updateInitialStateGlobal: nt,
82
84
  addValidationError: At,
83
- removeValidationError: M,
85
+ removeValidationError: b,
84
86
  setServerSyncActions: Ct
85
- } = a.getState(), St = (t) => {
87
+ } = o.getState(), St = (t) => {
86
88
  if (!t) return null;
87
89
  try {
88
- const o = window.localStorage.getItem(t);
89
- return o ? JSON.parse(o) : null;
90
- } catch (o) {
91
- return console.error("Error loading from localStorage:", o), null;
90
+ const a = window.localStorage.getItem(t);
91
+ return a ? JSON.parse(a) : null;
92
+ } catch (a) {
93
+ return console.error("Error loading from localStorage:", a), null;
92
94
  }
93
- }, Tt = (t, o, f, u) => {
95
+ }, Tt = (t, a, f, u) => {
94
96
  if (f.log && console.log(
95
97
  "saving to localstorage",
96
- o,
98
+ a,
97
99
  f.localStorage?.key,
98
100
  u
99
101
  ), f.localStorage?.key && u) {
100
- const d = {
102
+ const c = {
101
103
  state: t,
102
104
  lastUpdated: Date.now(),
103
- lastSyncedWithServer: a.getState().serverSyncLog[o]?.[0]?.timeStamp,
104
- baseServerState: a.getState().serverState[o]
105
- }, _ = `${u}-${o}-${f.localStorage?.key}`;
106
- window.localStorage.setItem(_, JSON.stringify(d));
105
+ lastSyncedWithServer: o.getState().serverSyncLog[a]?.[0]?.timeStamp,
106
+ baseServerState: o.getState().serverState[a]
107
+ }, _ = `${u}-${a}-${f.localStorage?.key}`;
108
+ window.localStorage.setItem(_, JSON.stringify(c));
107
109
  }
108
- }, Ft = (t, o, f, u, d, _) => {
110
+ }, Ft = (t, a, f, u, c, _) => {
109
111
  const w = {
110
- initialState: o,
112
+ initialState: a,
111
113
  updaterState: Z(
112
114
  t,
113
115
  u,
114
- d,
116
+ c,
115
117
  _
116
118
  ),
117
119
  state: f
@@ -120,77 +122,81 @@ const qt = (t, o) => {
120
122
  nt(t, w.initialState), B(t, w.updaterState), x(t, w.state);
121
123
  });
122
124
  }, mt = (t) => {
123
- const o = a.getState().stateComponents.get(t);
124
- if (!o) return;
125
+ const a = o.getState().stateComponents.get(t);
126
+ if (!a) return;
125
127
  const f = /* @__PURE__ */ new Set();
126
- o.components.forEach((u) => {
128
+ a.components.forEach((u) => {
127
129
  f.add(() => u.forceUpdate());
128
130
  }), queueMicrotask(() => {
129
131
  J(() => {
130
132
  f.forEach((u) => u());
131
133
  });
132
134
  });
133
- }, zt = (t, o) => {
134
- const f = a.getState().stateComponents.get(t);
135
+ }, zt = (t, a) => {
136
+ const f = o.getState().stateComponents.get(t);
135
137
  if (f) {
136
- const u = `${t}////${o}`, d = f.components.get(u);
137
- d && d.forceUpdate();
138
+ const u = `${t}////${a}`, c = f.components.get(u);
139
+ c && c.forceUpdate();
138
140
  }
139
141
  };
140
- function jt(t, {
141
- stateKey: o,
142
+ function Ot(t, {
143
+ stateKey: a,
142
144
  serverSync: f,
143
145
  localStorage: u,
144
- formElements: d,
146
+ formElements: c,
145
147
  middleware: _,
146
148
  reactiveDeps: w,
147
- reactiveType: v,
148
- componentId: m,
149
+ reactiveType: y,
150
+ componentId: S,
149
151
  initState: p,
150
152
  syncUpdate: s
151
153
  } = {}) {
152
- const [e, I] = Y({}), { sessionId: V } = Vt();
153
- let k = !o;
154
- const [c] = Y(o ?? tt()), U = a.getState().stateLog[c], P = z(/* @__PURE__ */ new Set()), i = z(m ?? tt()), h = z(null);
155
- h.current = et(c), K(() => {
156
- if (s && s.stateKey === c && s.path?.[0]) {
157
- x(c, (r) => ({
154
+ const [e, I] = Y({}), { sessionId: N } = Nt();
155
+ let k = !a;
156
+ const [l] = Y(a ?? tt()), R = o.getState().stateLog[l], U = z(/* @__PURE__ */ new Set()), i = z(S ?? tt()), $ = z(null);
157
+ $.current = et(l), K(() => {
158
+ if (s && s.stateKey === l && s.path?.[0]) {
159
+ x(l, (r) => ({
158
160
  ...r,
159
161
  [s.path[0]]: s.newValue
160
162
  }));
161
163
  const n = `${s.stateKey}:${s.path.join(".")}`;
162
- a.getState().setSyncInfo(n, {
164
+ o.getState().setSyncInfo(n, {
163
165
  timeStamp: s.timeStamp,
164
166
  userId: s.userId
165
167
  });
166
168
  }
167
- }, [s]), K(() => {
168
- const n = dt(c, {
169
+ }, [s]), $.current.log && (console.log(
170
+ "latestInitialOptionsRef.current ",
171
+ $.current
172
+ ), console.log("latestInitialOptionsRef.current localStorage", u)), K(() => {
173
+ const n = dt(l, {
169
174
  initState: p,
170
175
  localStorage: u
171
176
  });
177
+ $.current = n;
172
178
  let r = null;
173
- n.log && console.log("newoptions", n), n.localStorage?.key && V && (r = St(
174
- V + "-" + c + "-" + n.localStorage?.key
179
+ n.log && console.log("newoptions", n), n.localStorage?.key && N && (r = St(
180
+ N + "-" + l + "-" + n.localStorage?.key
175
181
  ));
176
- let l = null;
177
- p?.initialState && (l = p?.initialState, r && r.lastUpdated > (r.lastSyncedWithServer || 0) && (l = r.state), Ft(
178
- c,
179
- p?.initialState,
182
+ let d = null;
183
+ p?.initialState && (d = p?.initialState, r && r.lastUpdated > (r.lastSyncedWithServer || 0) && (d = r.state), Ft(
180
184
  l,
181
- R,
185
+ p?.initialState,
186
+ d,
187
+ P,
182
188
  i.current,
183
- V
184
- ), mt(c), I({}));
189
+ N
190
+ ), mt(l), I({}));
185
191
  }, [u?.key, ...p?.dependencies || []]), vt(() => {
186
- k && dt(c, {
192
+ k && dt(l, {
187
193
  serverSync: f,
188
- formElements: d,
194
+ formElements: c,
189
195
  initState: p,
190
196
  localStorage: u,
191
197
  middleware: _
192
198
  });
193
- const n = `${c}////${i.current}`, r = a.getState().stateComponents.get(c) || {
199
+ const n = `${l}////${i.current}`, r = o.getState().stateComponents.get(l) || {
194
200
  components: /* @__PURE__ */ new Map()
195
201
  };
196
202
  return r.components.set(n, {
@@ -198,217 +204,217 @@ function jt(t, {
198
204
  paths: /* @__PURE__ */ new Set(),
199
205
  deps: [],
200
206
  depsFunction: w || void 0,
201
- reactiveType: v ?? ["component", "deps"]
202
- }), a.getState().stateComponents.set(c, r), I({}), () => {
203
- const l = `${c}////${i.current}`;
204
- r && (r.components.delete(l), r.components.size === 0 && a.getState().stateComponents.delete(c));
207
+ reactiveType: y ?? ["component", "deps"]
208
+ }), o.getState().stateComponents.set(l, r), I({}), () => {
209
+ const d = `${l}////${i.current}`;
210
+ r && (r.components.delete(d), r.components.size === 0 && o.getState().stateComponents.delete(l));
205
211
  };
206
212
  }, []);
207
- const R = (n, r, l, g) => {
213
+ const P = (n, r, d, g) => {
208
214
  if (Array.isArray(r)) {
209
- const S = `${c}-${r.join(".")}`;
210
- P.current.add(S);
215
+ const m = `${l}-${r.join(".")}`;
216
+ U.current.add(m);
211
217
  }
212
- x(c, (S) => {
213
- const E = ft(n) ? n(S) : n, j = `${c}-${r.join(".")}`;
214
- if (j) {
215
- let b = !1, y = a.getState().signalDomElements.get(j);
216
- if ((!y || y.size === 0) && (l.updateType === "insert" || l.updateType === "cut")) {
217
- const $ = r.slice(0, -1), C = L(E, $);
218
+ x(l, (m) => {
219
+ const E = ft(n) ? n(m) : n, O = `${l}-${r.join(".")}`;
220
+ if (O) {
221
+ let M = !1, v = o.getState().signalDomElements.get(O);
222
+ if ((!v || v.size === 0) && (d.updateType === "insert" || d.updateType === "cut")) {
223
+ const h = r.slice(0, -1), C = L(E, h);
218
224
  if (Array.isArray(C)) {
219
- b = !0;
220
- const N = `${c}-${$.join(".")}`;
221
- y = a.getState().signalDomElements.get(N);
225
+ M = !0;
226
+ const V = `${l}-${h.join(".")}`;
227
+ v = o.getState().signalDomElements.get(V);
222
228
  }
223
229
  }
224
- if (y) {
225
- const $ = b ? L(E, r.slice(0, -1)) : L(E, r);
226
- y.forEach(({ parentId: C, position: N, effect: D }) => {
230
+ if (v) {
231
+ const h = M ? L(E, r.slice(0, -1)) : L(E, r);
232
+ v.forEach(({ parentId: C, position: V, effect: D }) => {
227
233
  const T = document.querySelector(
228
234
  `[data-parent-id="${C}"]`
229
235
  );
230
236
  if (T) {
231
- const ot = Array.from(T.childNodes);
232
- if (ot[N]) {
233
- const yt = D ? new Function("state", `return (${D})(state)`)($) : $;
234
- ot[N].textContent = String(yt);
237
+ const at = Array.from(T.childNodes);
238
+ if (at[V]) {
239
+ const yt = D ? new Function("state", `return (${D})(state)`)(h) : h;
240
+ at[V].textContent = String(yt);
235
241
  }
236
242
  }
237
243
  });
238
244
  }
239
245
  }
240
- l.updateType === "update" && (g || h.current?.validationKey) && r && M(
241
- (g || h.current?.validationKey) + "." + r.join(".")
246
+ d.updateType === "update" && (g || $.current?.validationKey) && r && b(
247
+ (g || $.current?.validationKey) + "." + r.join(".")
242
248
  );
243
249
  const A = r.slice(0, r.length - 1);
244
- l.updateType === "cut" && h.current?.validationKey && M(
245
- h.current?.validationKey + "." + A.join(".")
246
- ), l.updateType === "insert" && h.current?.validationKey && $t(
247
- h.current?.validationKey + "." + A.join(".")
248
- ).filter(([y, $]) => {
249
- let C = y?.split(".").length;
250
- if (y == A.join(".") && C == A.length - 1) {
251
- let N = y + "." + A;
252
- M(y), At(N, $);
250
+ d.updateType === "cut" && $.current?.validationKey && b(
251
+ $.current?.validationKey + "." + A.join(".")
252
+ ), d.updateType === "insert" && $.current?.validationKey && $t(
253
+ $.current?.validationKey + "." + A.join(".")
254
+ ).filter(([v, h]) => {
255
+ let C = v?.split(".").length;
256
+ if (v == A.join(".") && C == A.length - 1) {
257
+ let V = v + "." + A;
258
+ b(v), At(V, h);
253
259
  }
254
260
  });
255
- const O = L(S, r), F = L(E, r), W = l.updateType === "update" ? r.join(".") : [...r].slice(0, -1).join("."), rt = a.getState().stateComponents.get(c);
261
+ const j = L(m, r), F = L(E, r), W = d.updateType === "update" ? r.join(".") : [...r].slice(0, -1).join("."), rt = o.getState().stateComponents.get(l);
256
262
  if (rt)
257
- for (const [b, y] of rt.components.entries()) {
258
- let $ = !1;
259
- const C = Array.isArray(y.reactiveType) ? y.reactiveType : [y.reactiveType || "component"];
263
+ for (const [M, v] of rt.components.entries()) {
264
+ let h = !1;
265
+ const C = Array.isArray(v.reactiveType) ? v.reactiveType : [v.reactiveType || "component"];
260
266
  if (!C.includes("none")) {
261
267
  if (C.includes("all")) {
262
- y.forceUpdate();
268
+ v.forceUpdate();
263
269
  continue;
264
270
  }
265
- if (C.includes("component") && y.paths && (y.paths.has(W) || y.paths.has("")) && ($ = !0), !$ && C.includes("deps") && y.depsFunction) {
266
- const N = y.depsFunction(E);
267
- typeof N == "boolean" ? N && ($ = !0) : G(y.deps, N) || (y.deps = N, $ = !0);
271
+ if (C.includes("component") && v.paths && (v.paths.has(W) || v.paths.has("")) && (h = !0), !h && C.includes("deps") && v.depsFunction) {
272
+ const V = v.depsFunction(E);
273
+ typeof V == "boolean" ? V && (h = !0) : G(v.deps, V) || (v.deps = V, h = !0);
268
274
  }
269
- $ && y.forceUpdate();
275
+ h && v.forceUpdate();
270
276
  }
271
277
  }
272
- const at = {
278
+ const ot = {
273
279
  timeStamp: Date.now(),
274
- stateKey: c,
280
+ stateKey: l,
275
281
  path: r,
276
- updateType: l.updateType,
282
+ updateType: d.updateType,
277
283
  status: "new",
278
- oldValue: O,
284
+ oldValue: j,
279
285
  newValue: F
280
286
  };
281
- if (ht(c, (b) => {
282
- const $ = [...b ?? [], at].reduce((C, N) => {
283
- const D = `${N.stateKey}:${JSON.stringify(N.path)}`, T = C.get(D);
284
- return T ? (T.timeStamp = Math.max(T.timeStamp, N.timeStamp), T.newValue = N.newValue, T.oldValue = T.oldValue ?? N.oldValue, T.updateType = N.updateType) : C.set(D, { ...N }), C;
287
+ if (ht(l, (M) => {
288
+ const h = [...M ?? [], ot].reduce((C, V) => {
289
+ const D = `${V.stateKey}:${JSON.stringify(V.path)}`, T = C.get(D);
290
+ return T ? (T.timeStamp = Math.max(T.timeStamp, V.timeStamp), T.newValue = V.newValue, T.oldValue = T.oldValue ?? V.oldValue, T.updateType = V.updateType) : C.set(D, { ...V }), C;
285
291
  }, /* @__PURE__ */ new Map());
286
- return Array.from($.values());
292
+ return Array.from(h.values());
287
293
  }), Tt(
288
294
  E,
289
- c,
290
- h.current,
291
- V
295
+ l,
296
+ $.current,
297
+ N
292
298
  ), _ && _({
293
- updateLog: U,
294
- update: at
295
- }), h.current?.serverSync) {
296
- const b = a.getState().serverState[c], y = h.current?.serverSync;
297
- Ct(c, {
298
- syncKey: typeof y.syncKey == "string" ? y.syncKey : y.syncKey({ state: E }),
299
- rollBackState: b,
300
- actionTimeStamp: Date.now() + (y.debounce ?? 3e3),
299
+ updateLog: R,
300
+ update: ot
301
+ }), $.current?.serverSync) {
302
+ const M = o.getState().serverState[l], v = $.current?.serverSync;
303
+ Ct(l, {
304
+ syncKey: typeof v.syncKey == "string" ? v.syncKey : v.syncKey({ state: E }),
305
+ rollBackState: M,
306
+ actionTimeStamp: Date.now() + (v.debounce ?? 3e3),
301
307
  status: "waiting"
302
308
  });
303
309
  }
304
310
  return E;
305
311
  });
306
312
  };
307
- a.getState().updaterState[c] || (B(
308
- c,
313
+ o.getState().updaterState[l] || (B(
314
+ l,
309
315
  Z(
310
- c,
311
- R,
316
+ l,
317
+ P,
312
318
  i.current,
313
- V
319
+ N
314
320
  )
315
- ), a.getState().cogsStateStore[c] || x(c, t), a.getState().initialStateGlobal[c] || nt(c, t));
321
+ ), o.getState().cogsStateStore[l] || x(l, t), o.getState().initialStateGlobal[l] || nt(l, t));
316
322
  const Q = It(() => Z(
317
- c,
318
- R,
323
+ l,
324
+ P,
319
325
  i.current,
320
- V
321
- ), [c]);
322
- return [gt(c), Q];
326
+ N
327
+ ), [l]);
328
+ return [gt(l), Q];
323
329
  }
324
- function Z(t, o, f, u) {
325
- const d = /* @__PURE__ */ new Map();
330
+ function Z(t, a, f, u) {
331
+ const c = /* @__PURE__ */ new Map();
326
332
  let _ = 0;
327
333
  const w = (s) => {
328
334
  const e = s.join(".");
329
- for (const [I] of d)
330
- (I === e || I.startsWith(e + ".")) && d.delete(I);
335
+ for (const [I] of c)
336
+ (I === e || I.startsWith(e + ".")) && c.delete(I);
331
337
  _++;
332
- }, v = /* @__PURE__ */ new Map(), m = {
338
+ }, y = /* @__PURE__ */ new Map(), S = {
333
339
  removeValidation: (s) => {
334
- s?.validationKey && M(s.validationKey);
340
+ s?.validationKey && b(s.validationKey);
335
341
  },
336
342
  revertToInitialState: (s) => {
337
- const e = a.getState().getInitialOptions(t)?.validation;
338
- e?.key && M(e?.key), s?.validationKey && M(s.validationKey);
339
- const I = a.getState().initialStateGlobal[t];
340
- d.clear(), _++;
341
- const V = p(I, []);
343
+ const e = o.getState().getInitialOptions(t)?.validation;
344
+ e?.key && b(e?.key), s?.validationKey && b(s.validationKey);
345
+ const I = o.getState().initialStateGlobal[t];
346
+ c.clear(), _++;
347
+ const N = p(I, []);
342
348
  J(() => {
343
- B(t, V), x(t, I);
344
- const k = a.getState().stateComponents.get(t);
345
- k && k.components.forEach((U) => {
346
- U.forceUpdate();
349
+ B(t, N), x(t, I);
350
+ const k = o.getState().stateComponents.get(t);
351
+ k && k.components.forEach((R) => {
352
+ R.forceUpdate();
347
353
  });
348
- const c = et(t);
349
- c?.localStorage?.key && localStorage.removeItem(
350
- c?.initState ? u + "-" + t + "-" + c?.localStorage?.key : t
354
+ const l = et(t);
355
+ l?.localStorage?.key && localStorage.removeItem(
356
+ l?.initState ? u + "-" + t + "-" + l?.localStorage?.key : t
351
357
  ), localStorage.removeItem(t);
352
358
  });
353
359
  },
354
360
  updateInitialState: (s) => {
355
- d.clear(), _++;
361
+ c.clear(), _++;
356
362
  const e = Z(
357
363
  t,
358
- o,
364
+ a,
359
365
  f,
360
366
  u
361
367
  );
362
368
  return J(() => {
363
369
  nt(t, s), B(t, e), x(t, s);
364
- const I = a.getState().stateComponents.get(t);
365
- I && I.components.forEach((V) => {
366
- V.forceUpdate();
370
+ const I = o.getState().stateComponents.get(t);
371
+ I && I.components.forEach((N) => {
372
+ N.forceUpdate();
367
373
  }), localStorage.removeItem(t);
368
374
  }), {
369
375
  fetchId: (I) => e.get()[I]
370
376
  };
371
377
  },
372
- _initialState: a.getState().initialStateGlobal[t],
373
- _serverState: a.getState().serverState[t],
374
- _isLoading: a.getState().isLoadingGlobal[t],
378
+ _initialState: o.getState().initialStateGlobal[t],
379
+ _serverState: o.getState().serverState[t],
380
+ _isLoading: o.getState().isLoadingGlobal[t],
375
381
  _isServerSynced: () => {
376
- const s = a.getState().serverState[t];
382
+ const s = o.getState().serverState[t];
377
383
  return !!(s && G(s, gt(t)));
378
384
  }
379
385
  };
380
386
  function p(s, e = [], I) {
381
- const V = e.map(String).join(".");
382
- d.get(V);
387
+ const N = e.map(String).join(".");
388
+ c.get(N);
383
389
  const k = function() {
384
- return a().getNestedState(t, e);
390
+ return o().getNestedState(t, e);
385
391
  };
386
- Object.keys(m).forEach((P) => {
387
- k[P] = m[P];
392
+ Object.keys(S).forEach((U) => {
393
+ k[U] = S[U];
388
394
  });
389
- const c = {
390
- apply(P, i, h) {
391
- return a().getNestedState(t, e);
395
+ const l = {
396
+ apply(U, i, $) {
397
+ return o().getNestedState(t, e);
392
398
  },
393
- get(P, i) {
399
+ get(U, i) {
394
400
  if (i !== "then" && !i.startsWith("$") && i !== "stateMapNoRender") {
395
- const n = e.join("."), r = `${t}////${f}`, l = a.getState().stateComponents.get(t);
396
- if (l) {
397
- const g = l.components.get(r);
401
+ const n = e.join("."), r = `${t}////${f}`, d = o.getState().stateComponents.get(t);
402
+ if (d) {
403
+ const g = d.components.get(r);
398
404
  g && (e.length > 0 || i === "get") && g.paths.add(n);
399
405
  }
400
406
  }
401
407
  if (i === "showValidationErrors")
402
408
  return () => {
403
- const n = a.getState().getInitialOptions(t)?.validation;
409
+ const n = o.getState().getInitialOptions(t)?.validation;
404
410
  if (!n?.key)
405
411
  throw new Error("Validation key not found");
406
- return a.getState().getValidationErrors(n.key + "." + e.join("."));
412
+ return o.getState().getValidationErrors(n.key + "." + e.join("."));
407
413
  };
408
414
  if (Array.isArray(s)) {
409
415
  if (i === "getSelected")
410
416
  return () => {
411
- const n = v.get(e.join("."));
417
+ const n = y.get(e.join("."));
412
418
  if (n !== void 0)
413
419
  return p(
414
420
  s[n],
@@ -420,24 +426,24 @@ function Z(t, o, f, u) {
420
426
  return (n) => {
421
427
  const r = I?.filtered?.some(
422
428
  (g) => g.join(".") === e.join(".")
423
- ), l = r ? s : a.getState().getNestedState(t, e);
424
- return i !== "stateMapNoRender" && (d.clear(), _++), l.map((g, S) => {
425
- const E = r && g.__origIndex ? g.__origIndex : S, j = p(
429
+ ), d = r ? s : o.getState().getNestedState(t, e);
430
+ return i !== "stateMapNoRender" && (c.clear(), _++), d.map((g, m) => {
431
+ const E = r && g.__origIndex ? g.__origIndex : m, O = p(
426
432
  g,
427
433
  [...e, E.toString()],
428
434
  I
429
435
  );
430
436
  return n(
431
437
  g,
432
- j,
433
- S,
438
+ O,
439
+ m,
434
440
  s,
435
441
  p(s, e, I)
436
442
  );
437
443
  });
438
444
  };
439
445
  if (i === "$stateMap")
440
- return (n) => H(Ot, {
446
+ return (n) => H(jt, {
441
447
  proxy: {
442
448
  _stateKey: t,
443
449
  _path: e,
@@ -448,12 +454,12 @@ function Z(t, o, f, u) {
448
454
  });
449
455
  if (i === "stateFlattenOn")
450
456
  return (n) => {
451
- const l = I?.filtered?.some(
452
- (S) => S.join(".") === e.join(".")
453
- ) ? s : a.getState().getNestedState(t, e);
454
- d.clear(), _++;
455
- const g = l.flatMap(
456
- (S, E) => S[n] ?? []
457
+ const d = I?.filtered?.some(
458
+ (m) => m.join(".") === e.join(".")
459
+ ) ? s : o.getState().getNestedState(t, e);
460
+ c.clear(), _++;
461
+ const g = d.flatMap(
462
+ (m, E) => m[n] ?? []
457
463
  );
458
464
  return p(
459
465
  g,
@@ -463,12 +469,12 @@ function Z(t, o, f, u) {
463
469
  };
464
470
  if (i === "findWith")
465
471
  return (n, r) => {
466
- const l = s.findIndex(
472
+ const d = s.findIndex(
467
473
  (E) => E[n] === r
468
474
  );
469
- if (l === -1) return;
470
- const g = s[l], S = [...e, l.toString()];
471
- return d.clear(), _++, d.clear(), _++, p(g, S);
475
+ if (d === -1) return;
476
+ const g = s[d], m = [...e, d.toString()];
477
+ return c.clear(), _++, c.clear(), _++, p(g, m);
472
478
  };
473
479
  if (i === "index")
474
480
  return (n) => {
@@ -476,64 +482,64 @@ function Z(t, o, f, u) {
476
482
  return p(r, [...e, n.toString()]);
477
483
  };
478
484
  if (i === "insert")
479
- return (n) => (w(e), st(o, n, e, t), p(
480
- a.getState().cogsStateStore[t],
485
+ return (n) => (w(e), st(a, n, e, t), p(
486
+ o.getState().cogsStateStore[t],
481
487
  []
482
488
  ));
483
489
  if (i === "uniqueInsert")
484
- return (n, r, l) => {
485
- const g = a.getState().getNestedState(t, e), S = ft(n) ? n(g) : n;
490
+ return (n, r, d) => {
491
+ const g = o.getState().getNestedState(t, e), m = ft(n) ? n(g) : n;
486
492
  let E = null;
487
493
  if (!g.some((A) => {
488
494
  if (r) {
489
495
  const F = r.every(
490
- (W) => G(A[W], S[W])
496
+ (W) => G(A[W], m[W])
491
497
  );
492
498
  return F && (E = A), F;
493
499
  }
494
- const O = G(A, S);
495
- return O && (E = A), O;
500
+ const j = G(A, m);
501
+ return j && (E = A), j;
496
502
  }))
497
- w(e), st(o, S, e, t);
498
- else if (l && E) {
499
- const A = l(E), O = g.map(
503
+ w(e), st(a, m, e, t);
504
+ else if (d && E) {
505
+ const A = d(E), j = g.map(
500
506
  (F) => G(F, E) ? A : F
501
507
  );
502
- w(e), q(o, O, e);
508
+ w(e), q(a, j, e);
503
509
  }
504
510
  };
505
511
  if (i === "cut")
506
512
  return (n, r) => {
507
- r?.waitForSync || (w(e), ct(o, e, t, n));
513
+ r?.waitForSync || (w(e), ct(a, e, t, n));
508
514
  };
509
515
  if (i === "stateFilter")
510
516
  return (n) => {
511
- const r = s.map((S, E) => ({
512
- ...S,
517
+ const r = s.map((m, E) => ({
518
+ ...m,
513
519
  __origIndex: E.toString()
514
- })), l = [], g = [];
515
- for (let S = 0; S < r.length; S++)
516
- n(r[S], S) && (l.push(S), g.push(r[S]));
517
- return d.clear(), _++, p(g, e, {
520
+ })), d = [], g = [];
521
+ for (let m = 0; m < r.length; m++)
522
+ n(r[m], m) && (d.push(m), g.push(r[m]));
523
+ return c.clear(), _++, p(g, e, {
518
524
  filtered: [...I?.filtered || [], e],
519
- validIndices: l
525
+ validIndices: d
520
526
  // Always pass validIndices, even if empty
521
527
  });
522
528
  };
523
529
  }
524
- const h = e[e.length - 1];
525
- if (!isNaN(Number(h))) {
526
- const n = e.slice(0, -1), r = a.getState().getNestedState(t, n);
530
+ const $ = e[e.length - 1];
531
+ if (!isNaN(Number($))) {
532
+ const n = e.slice(0, -1), r = o.getState().getNestedState(t, n);
527
533
  if (Array.isArray(r) && i === "cut")
528
534
  return () => ct(
529
- o,
535
+ a,
530
536
  n,
531
537
  t,
532
- Number(h)
538
+ Number($)
533
539
  );
534
540
  }
535
541
  if (i === "get")
536
- return () => a.getState().getNestedState(t, e);
542
+ return () => o.getState().getNestedState(t, e);
537
543
  if (i === "$derive")
538
544
  return (n) => X({
539
545
  _stateKey: t,
@@ -553,40 +559,40 @@ function Z(t, o, f, u) {
553
559
  });
554
560
  if (i === "lastSynced") {
555
561
  const n = `${t}:${e.join(".")}`;
556
- return a.getState().getSyncInfo(n);
562
+ return o.getState().getSyncInfo(n);
557
563
  }
558
564
  if (i === "_selected") {
559
- const n = e.slice(0, -1), r = n.join("."), l = a.getState().getNestedState(t, n);
560
- return Array.isArray(l) ? Number(e[e.length - 1]) === v.get(r) : void 0;
565
+ const n = e.slice(0, -1), r = n.join("."), d = o.getState().getNestedState(t, n);
566
+ return Array.isArray(d) ? Number(e[e.length - 1]) === y.get(r) : void 0;
561
567
  }
562
568
  if (i == "getLocalStorage")
563
569
  return (n) => St(u + "-" + t + "-" + n);
564
570
  if (i === "setSelected")
565
571
  return (n) => {
566
- const r = e.slice(0, -1), l = Number(e[e.length - 1]), g = r.join(".");
567
- n ? v.set(g, l) : v.delete(g);
568
- const S = a.getState().getNestedState(t, [...r]);
569
- q(o, S, r), w(r);
572
+ const r = e.slice(0, -1), d = Number(e[e.length - 1]), g = r.join(".");
573
+ n ? y.set(g, d) : y.delete(g);
574
+ const m = o.getState().getNestedState(t, [...r]);
575
+ q(a, m, r), w(r);
570
576
  };
571
577
  if (e.length == 0) {
572
578
  if (i === "validateZodSchema")
573
579
  return () => {
574
- const n = a.getState().getInitialOptions(t)?.validation, r = a.getState().addValidationError;
580
+ const n = o.getState().getInitialOptions(t)?.validation, r = o.getState().addValidationError;
575
581
  if (!n?.zodSchema)
576
582
  throw new Error("Zod schema not found");
577
583
  if (!n?.key)
578
584
  throw new Error("Validation key not found");
579
- M(n.key);
580
- const l = a.getState().cogsStateStore[t];
585
+ b(n.key);
586
+ const d = o.getState().cogsStateStore[t];
581
587
  try {
582
- const g = a.getState().getValidationErrors(n.key);
588
+ const g = o.getState().getValidationErrors(n.key);
583
589
  g && g.length > 0 && g.forEach(([E]) => {
584
- E && E.startsWith(n.key) && M(E);
590
+ E && E.startsWith(n.key) && b(E);
585
591
  });
586
- const S = n.zodSchema.safeParse(l);
587
- return S.success ? !0 : (S.error.errors.forEach((j) => {
588
- const A = j.path, O = j.message, F = [n.key, ...A].join(".");
589
- r(F, O);
592
+ const m = n.zodSchema.safeParse(d);
593
+ return m.success ? !0 : (m.error.errors.forEach((O) => {
594
+ const A = O.path, j = O.message, F = [n.key, ...A].join(".");
595
+ r(F, j);
590
596
  }), mt(t), !1);
591
597
  } catch (g) {
592
598
  return console.error("Zod schema validation failed", g), !1;
@@ -594,19 +600,19 @@ function Z(t, o, f, u) {
594
600
  };
595
601
  if (i === "_componentId") return f;
596
602
  if (i === "getComponents")
597
- return () => a().stateComponents.get(t);
603
+ return () => o().stateComponents.get(t);
598
604
  if (i === "getAllFormRefs")
599
605
  return () => lt.getState().getFormRefsByStateKey(t);
600
606
  if (i === "_initialState")
601
- return a.getState().initialStateGlobal[t];
607
+ return o.getState().initialStateGlobal[t];
602
608
  if (i === "_serverState")
603
- return a.getState().serverState[t];
609
+ return o.getState().serverState[t];
604
610
  if (i === "_isLoading")
605
- return a.getState().isLoadingGlobal[t];
611
+ return o.getState().isLoadingGlobal[t];
606
612
  if (i === "revertToInitialState")
607
- return m.revertToInitialState;
608
- if (i === "updateInitialState") return m.updateInitialState;
609
- if (i === "removeValidation") return m.removeValidation;
613
+ return S.revertToInitialState;
614
+ if (i === "updateInitialState") return S.updateInitialState;
615
+ if (i === "removeValidation") return S.removeValidation;
610
616
  }
611
617
  if (i === "getFormRef")
612
618
  return () => lt.getState().getFormRef(t + "." + e.join("."));
@@ -619,7 +625,7 @@ function Z(t, o, f, u) {
619
625
  {
620
626
  formOpts: r ? { validation: { message: "" } } : void 0,
621
627
  path: e,
622
- validationKey: a.getState().getInitialOptions(t)?.validation?.key || "",
628
+ validationKey: o.getState().getInitialOptions(t)?.validation?.key || "",
623
629
  stateKey: t,
624
630
  validIndices: I?.validIndices,
625
631
  children: n
@@ -627,79 +633,79 @@ function Z(t, o, f, u) {
627
633
  );
628
634
  if (i === "_stateKey") return t;
629
635
  if (i === "_path") return e;
630
- if (i === "_isServerSynced") return m._isServerSynced;
636
+ if (i === "_isServerSynced") return S._isServerSynced;
631
637
  if (i === "update")
632
638
  return (n, r) => {
633
639
  if (r?.debounce)
634
640
  pt(() => {
635
- q(o, n, e, "");
636
- const l = a.getState().getNestedState(t, e);
637
- r?.afterUpdate && r.afterUpdate(l);
641
+ q(a, n, e, "");
642
+ const d = o.getState().getNestedState(t, e);
643
+ r?.afterUpdate && r.afterUpdate(d);
638
644
  }, r.debounce);
639
645
  else {
640
- q(o, n, e, "");
641
- const l = a.getState().getNestedState(t, e);
642
- r?.afterUpdate && r.afterUpdate(l);
646
+ q(a, n, e, "");
647
+ const d = o.getState().getNestedState(t, e);
648
+ r?.afterUpdate && r.afterUpdate(d);
643
649
  }
644
650
  w(e);
645
651
  };
646
652
  if (i === "formElement")
647
653
  return (n, r) => /* @__PURE__ */ it(
648
- Nt,
654
+ Vt,
649
655
  {
650
- setState: o,
656
+ setState: a,
651
657
  stateKey: t,
652
658
  path: e,
653
659
  child: n,
654
660
  formOpts: r
655
661
  }
656
662
  );
657
- const R = [...e, i], Q = a.getState().getNestedState(t, R);
658
- return p(Q, R, I);
663
+ const P = [...e, i], Q = o.getState().getNestedState(t, P);
664
+ return p(Q, P, I);
659
665
  }
660
- }, U = new Proxy(k, c);
661
- return d.set(V, {
662
- proxy: U,
666
+ }, R = new Proxy(k, l);
667
+ return c.set(N, {
668
+ proxy: R,
663
669
  stateVersion: _
664
- }), U;
670
+ }), R;
665
671
  }
666
672
  return p(
667
- a.getState().getNestedState(t, [])
673
+ o.getState().getNestedState(t, [])
668
674
  );
669
675
  }
670
676
  function X(t) {
671
- return H(bt, { proxy: t });
677
+ return H(Mt, { proxy: t });
672
678
  }
673
- function Ot({
679
+ function jt({
674
680
  proxy: t,
675
- rebuildStateShape: o
681
+ rebuildStateShape: a
676
682
  }) {
677
- const f = a().getNestedState(t._stateKey, t._path);
678
- return Array.isArray(f) ? o(
683
+ const f = o().getNestedState(t._stateKey, t._path);
684
+ return Array.isArray(f) ? a(
679
685
  f,
680
686
  t._path
681
687
  ).stateMapNoRender(
682
- (d, _, w, v, m) => t._mapFn(d, _, w, v, m)
688
+ (c, _, w, y, S) => t._mapFn(c, _, w, y, S)
683
689
  ) : null;
684
690
  }
685
- function bt({
691
+ function Mt({
686
692
  proxy: t
687
693
  }) {
688
- const o = z(null), f = `${t._stateKey}-${t._path.join(".")}`;
694
+ const a = z(null), f = `${t._stateKey}-${t._path.join(".")}`;
689
695
  return K(() => {
690
- const u = o.current;
696
+ const u = a.current;
691
697
  if (!u || !u.parentElement) return;
692
- const d = u.parentElement, w = Array.from(d.childNodes).indexOf(u);
693
- let v = d.getAttribute("data-parent-id");
694
- v || (v = `parent-${crypto.randomUUID()}`, d.setAttribute("data-parent-id", v));
698
+ const c = u.parentElement, w = Array.from(c.childNodes).indexOf(u);
699
+ let y = c.getAttribute("data-parent-id");
700
+ y || (y = `parent-${crypto.randomUUID()}`, c.setAttribute("data-parent-id", y));
695
701
  const p = {
696
702
  instanceId: `instance-${crypto.randomUUID()}`,
697
- parentId: v,
703
+ parentId: y,
698
704
  position: w,
699
705
  effect: t._effect
700
706
  };
701
- a.getState().addSignalElement(f, p);
702
- const s = a.getState().getNestedState(t._stateKey, t._path);
707
+ o.getState().addSignalElement(f, p);
708
+ const s = o.getState().getNestedState(t._stateKey, t._path);
703
709
  let e;
704
710
  if (t._effect)
705
711
  try {
@@ -707,8 +713,8 @@ function bt({
707
713
  "state",
708
714
  `return (${t._effect})(state)`
709
715
  )(s);
710
- } catch (V) {
711
- console.error("Error evaluating effect function during mount:", V), e = s;
716
+ } catch (N) {
717
+ console.error("Error evaluating effect function during mount:", N), e = s;
712
718
  }
713
719
  else
714
720
  e = s;
@@ -716,15 +722,15 @@ function bt({
716
722
  const I = document.createTextNode(String(e));
717
723
  u.replaceWith(I);
718
724
  }, [t._stateKey, t._path.join("."), t._effect]), H("span", {
719
- ref: o,
725
+ ref: a,
720
726
  style: { display: "none" },
721
727
  "data-signal-id": f
722
728
  });
723
729
  }
724
730
  function Jt(t) {
725
- const o = Et(
731
+ const a = Et(
726
732
  (f) => {
727
- const u = a.getState().stateComponents.get(t._stateKey) || {
733
+ const u = o.getState().stateComponents.get(t._stateKey) || {
728
734
  components: /* @__PURE__ */ new Map()
729
735
  };
730
736
  return u.components.set(t._stateKey, {
@@ -732,9 +738,9 @@ function Jt(t) {
732
738
  paths: /* @__PURE__ */ new Set([t._path.join(".")])
733
739
  }), () => u.components.delete(t._stateKey);
734
740
  },
735
- () => a.getState().getNestedState(t._stateKey, t._path)
741
+ () => o.getState().getNestedState(t._stateKey, t._path)
736
742
  );
737
- return H("text", {}, String(o));
743
+ return H("text", {}, String(a));
738
744
  }
739
745
  export {
740
746
  X as $cogsSignal,
@@ -742,6 +748,6 @@ export {
742
748
  Wt as addStateOptions,
743
749
  qt as createCogsState,
744
750
  zt as notifyComponent,
745
- jt as useCogsStateFn
751
+ Ot as useCogsStateFn
746
752
  };
747
753
  //# sourceMappingURL=CogsState.jsx.map