cogsbox-state 0.5.74 → 0.5.76

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.
@@ -60,6 +60,7 @@ export type ArrayEndType<TShape extends unknown> = {
60
60
  uniqueInsert: (payload: UpdateArg<InferArrayElement<TShape>>, fields?: (keyof InferArrayElement<TShape>)[], onMatch?: (existingItem: any) => any) => void;
61
61
  stateFilter: (callbackfn: (value: InferArrayElement<TShape>, index: number) => void) => ArrayEndType<TShape>;
62
62
  getSelected: () => StateObject<InferArrayElement<TShape>> | undefined;
63
+ getSelectedIndex: () => number | undefined;
63
64
  } & EndType<TShape> & {
64
65
  [K in keyof (any[] extends infer T ? T : never)]: never;
65
66
  };
@@ -48,7 +48,7 @@ const zt = (t, i) => {
48
48
  options: l,
49
49
  initialOptionsPart: g
50
50
  });
51
- const e = r.getState().cogsStateStore[v] || y[v], S = l?.modifyState ? l.modifyState(e) : e, [T, A] = bt(
51
+ const e = r.getState().cogsStateStore[v] || y[v], S = l?.modifyState ? l.modifyState(e) : e, [h, A] = jt(
52
52
  S,
53
53
  {
54
54
  stateKey: v,
@@ -75,11 +75,11 @@ const zt = (t, i) => {
75
75
  getInitialOptions: Y,
76
76
  getKeyState: gt,
77
77
  getValidationErrors: kt,
78
- setStateLog: pt,
78
+ setStateLog: Ct,
79
79
  updateInitialStateGlobal: ot,
80
- addValidationError: Ct,
80
+ addValidationError: Tt,
81
81
  removeValidationError: P,
82
- setServerSyncActions: Tt
82
+ setServerSyncActions: ht
83
83
  } = r.getState(), ft = (t) => {
84
84
  if (!t) return null;
85
85
  try {
@@ -88,7 +88,7 @@ const zt = (t, i) => {
88
88
  } catch (i) {
89
89
  return console.error("Error loading from localStorage:", i), null;
90
90
  }
91
- }, ht = (t, i, m, y) => {
91
+ }, pt = (t, i, m, y) => {
92
92
  m.log && console.log(
93
93
  "saving to localstorage",
94
94
  i,
@@ -105,7 +105,7 @@ const zt = (t, i) => {
105
105
  }, _ = `${y}-${i}-${g}`;
106
106
  window.localStorage.setItem(_, JSON.stringify($));
107
107
  }
108
- }, Ft = (t, i, m, y, g, $) => {
108
+ }, xt = (t, i, m, y, g, $) => {
109
109
  const _ = {
110
110
  initialState: i,
111
111
  updaterState: X(
@@ -137,7 +137,7 @@ const zt = (t, i) => {
137
137
  g && g.forceUpdate();
138
138
  }
139
139
  };
140
- function bt(t, {
140
+ function jt(t, {
141
141
  stateKey: i,
142
142
  serverSync: m,
143
143
  localStorage: y,
@@ -150,10 +150,10 @@ function bt(t, {
150
150
  syncUpdate: e,
151
151
  dependencies: S
152
152
  } = {}) {
153
- const [T, A] = et({}), { sessionId: h } = At();
153
+ const [h, A] = et({}), { sessionId: p } = At();
154
154
  let R = !i;
155
- const [u] = et(i ?? rt()), s = r.getState().stateLog[u], G = J(/* @__PURE__ */ new Set()), x = J(l ?? rt()), p = J(null);
156
- p.current = Y(u), nt(() => {
155
+ const [u] = et(i ?? rt()), s = r.getState().stateLog[u], G = J(/* @__PURE__ */ new Set()), b = J(l ?? rt()), C = J(null);
156
+ C.current = Y(u), nt(() => {
157
157
  if (e && e.stateKey === u && e.path?.[0]) {
158
158
  D(u, (o) => ({
159
159
  ...o,
@@ -169,21 +169,21 @@ function bt(t, {
169
169
  dt(u, {
170
170
  initialState: f
171
171
  });
172
- const c = p.current;
172
+ const c = C.current;
173
173
  let o = null;
174
174
  c.log && console.log("newoptions", c);
175
175
  const d = L(c.localStorage?.key) ? c.localStorage?.key(f) : c.localStorage?.key;
176
- d && h && (o = ft(
177
- h + "-" + u + "-" + d
176
+ d && p && (o = ft(
177
+ p + "-" + u + "-" + d
178
178
  ));
179
179
  let E = null;
180
- f && (E = f, o && o.lastUpdated > (o.lastSyncedWithServer || 0) && (E = o.state), Ft(
180
+ f && (E = f, o && o.lastUpdated > (o.lastSyncedWithServer || 0) && (E = o.state), xt(
181
181
  u,
182
182
  f,
183
183
  E,
184
184
  n,
185
- x.current,
186
- h
185
+ b.current,
186
+ p
187
187
  ), St(u), A({}));
188
188
  }, [f, ...S || []]), It(() => {
189
189
  R && dt(u, {
@@ -193,7 +193,7 @@ function bt(t, {
193
193
  localStorage: y,
194
194
  middleware: $
195
195
  });
196
- const c = `${u}////${x.current}`, o = r.getState().stateComponents.get(u) || {
196
+ const c = `${u}////${b.current}`, o = r.getState().stateComponents.get(u) || {
197
197
  components: /* @__PURE__ */ new Map()
198
198
  };
199
199
  return o.components.set(c, {
@@ -203,19 +203,19 @@ function bt(t, {
203
203
  depsFunction: _ || void 0,
204
204
  reactiveType: v ?? ["component", "deps"]
205
205
  }), r.getState().stateComponents.set(u, o), A({}), () => {
206
- const d = `${u}////${x.current}`;
206
+ const d = `${u}////${b.current}`;
207
207
  o && (o.components.delete(d), o.components.size === 0 && r.getState().stateComponents.delete(u));
208
208
  };
209
209
  }, []);
210
210
  const n = (c, o, d, E) => {
211
211
  if (Array.isArray(o)) {
212
- const F = `${u}-${o.join(".")}`;
213
- G.current.add(F);
212
+ const x = `${u}-${o.join(".")}`;
213
+ G.current.add(x);
214
214
  }
215
- D(u, (F) => {
216
- const N = L(c) ? c(F) : c, j = `${u}-${o.join(".")}`;
217
- if (j) {
218
- let O = !1, I = r.getState().signalDomElements.get(j);
215
+ D(u, (x) => {
216
+ const N = L(c) ? c(x) : c, F = `${u}-${o.join(".")}`;
217
+ if (F) {
218
+ let O = !1, I = r.getState().signalDomElements.get(F);
219
219
  if ((!I || I.size === 0) && (d.updateType === "insert" || d.updateType === "cut")) {
220
220
  const V = o.slice(0, -1), k = U(N, V);
221
221
  if (Array.isArray(k)) {
@@ -227,11 +227,11 @@ function bt(t, {
227
227
  if (I) {
228
228
  const V = O ? U(N, o.slice(0, -1)) : U(N, o);
229
229
  I.forEach(({ parentId: k, position: w, effect: W }) => {
230
- const b = document.querySelector(
230
+ const j = document.querySelector(
231
231
  `[data-parent-id="${k}"]`
232
232
  );
233
- if (b) {
234
- const st = Array.from(b.childNodes);
233
+ if (j) {
234
+ const st = Array.from(j.childNodes);
235
235
  if (st[w]) {
236
236
  const vt = W ? new Function("state", `return (${W})(state)`)(V) : V;
237
237
  st[w].textContent = String(vt);
@@ -240,22 +240,22 @@ function bt(t, {
240
240
  });
241
241
  }
242
242
  }
243
- d.updateType === "update" && (E || p.current?.validationKey) && o && P(
244
- (E || p.current?.validationKey) + "." + o.join(".")
243
+ d.updateType === "update" && (E || C.current?.validationKey) && o && P(
244
+ (E || C.current?.validationKey) + "." + o.join(".")
245
245
  );
246
- const C = o.slice(0, o.length - 1);
247
- d.updateType === "cut" && p.current?.validationKey && P(
248
- p.current?.validationKey + "." + C.join(".")
249
- ), d.updateType === "insert" && p.current?.validationKey && kt(
250
- p.current?.validationKey + "." + C.join(".")
246
+ const T = o.slice(0, o.length - 1);
247
+ d.updateType === "cut" && C.current?.validationKey && P(
248
+ C.current?.validationKey + "." + T.join(".")
249
+ ), d.updateType === "insert" && C.current?.validationKey && kt(
250
+ C.current?.validationKey + "." + T.join(".")
251
251
  ).filter(([I, V]) => {
252
252
  let k = I?.split(".").length;
253
- if (I == C.join(".") && k == C.length - 1) {
254
- let w = I + "." + C;
255
- P(I), Ct(w, V);
253
+ if (I == T.join(".") && k == T.length - 1) {
254
+ let w = I + "." + T;
255
+ P(I), Tt(w, V);
256
256
  }
257
257
  });
258
- const q = U(F, o), mt = U(N, o), yt = d.updateType === "update" ? o.join(".") : [...o].slice(0, -1).join("."), at = r.getState().stateComponents.get(u);
258
+ const q = U(x, o), mt = U(N, o), yt = d.updateType === "update" ? o.join(".") : [...o].slice(0, -1).join("."), at = r.getState().stateComponents.get(u);
259
259
  if (at)
260
260
  for (const [O, I] of at.components.entries()) {
261
261
  let V = !1;
@@ -281,23 +281,23 @@ function bt(t, {
281
281
  oldValue: q,
282
282
  newValue: mt
283
283
  };
284
- if (pt(u, (O) => {
284
+ if (Ct(u, (O) => {
285
285
  const V = [...O ?? [], it].reduce((k, w) => {
286
- const W = `${w.stateKey}:${JSON.stringify(w.path)}`, b = k.get(W);
287
- return b ? (b.timeStamp = Math.max(b.timeStamp, w.timeStamp), b.newValue = w.newValue, b.oldValue = b.oldValue ?? w.oldValue, b.updateType = w.updateType) : k.set(W, { ...w }), k;
286
+ const W = `${w.stateKey}:${JSON.stringify(w.path)}`, j = k.get(W);
287
+ return j ? (j.timeStamp = Math.max(j.timeStamp, w.timeStamp), j.newValue = w.newValue, j.oldValue = j.oldValue ?? w.oldValue, j.updateType = w.updateType) : k.set(W, { ...w }), k;
288
288
  }, /* @__PURE__ */ new Map());
289
289
  return Array.from(V.values());
290
- }), ht(
290
+ }), pt(
291
291
  N,
292
292
  u,
293
- p.current,
294
- h
293
+ C.current,
294
+ p
295
295
  ), $ && $({
296
296
  updateLog: s,
297
297
  update: it
298
- }), p.current?.serverSync) {
299
- const O = r.getState().serverState[u], I = p.current?.serverSync;
300
- Tt(u, {
298
+ }), C.current?.serverSync) {
299
+ const O = r.getState().serverState[u], I = C.current?.serverSync;
300
+ ht(u, {
301
301
  syncKey: typeof I.syncKey == "string" ? I.syncKey : I.syncKey({ state: N }),
302
302
  rollBackState: O,
303
303
  actionTimeStamp: Date.now() + (I.debounce ?? 3e3),
@@ -312,15 +312,15 @@ function bt(t, {
312
312
  X(
313
313
  u,
314
314
  n,
315
- x.current,
316
- h
315
+ b.current,
316
+ p
317
317
  )
318
318
  ), r.getState().cogsStateStore[u] || D(u, t), r.getState().initialStateGlobal[u] || ot(u, t));
319
319
  const a = _t(() => X(
320
320
  u,
321
321
  n,
322
- x.current,
323
- h
322
+ b.current,
323
+ p
324
324
  ), [u]);
325
325
  return [gt(u), a];
326
326
  }
@@ -341,9 +341,9 @@ function X(t, i, m, y) {
341
341
  e?.key && P(e?.key), f?.validationKey && P(f.validationKey);
342
342
  const S = r.getState().initialStateGlobal[t];
343
343
  g.clear(), $++;
344
- const T = l(S, []), A = Y(t), h = L(A?.localStorage?.key) ? A?.localStorage?.key(S) : A?.localStorage?.key, R = `${y}-${t}-${h}`;
344
+ const h = l(S, []), A = Y(t), p = L(A?.localStorage?.key) ? A?.localStorage?.key(S) : A?.localStorage?.key, R = `${y}-${t}-${p}`;
345
345
  return R && localStorage.removeItem(R), Z(() => {
346
- H(t, T), D(t, S);
346
+ H(t, h), D(t, S);
347
347
  const u = r.getState().stateComponents.get(t);
348
348
  u && u.components.forEach((s) => {
349
349
  s.forceUpdate();
@@ -361,8 +361,8 @@ function X(t, i, m, y) {
361
361
  return Z(() => {
362
362
  ot(t, f), H(t, e), D(t, f);
363
363
  const S = r.getState().stateComponents.get(t);
364
- S && S.components.forEach((T) => {
365
- T.forceUpdate();
364
+ S && S.components.forEach((h) => {
365
+ h.forceUpdate();
366
366
  });
367
367
  }), {
368
368
  fetchId: (S) => e.get()[S]
@@ -377,15 +377,15 @@ function X(t, i, m, y) {
377
377
  }
378
378
  };
379
379
  function l(f, e = [], S) {
380
- const T = e.map(String).join(".");
381
- g.get(T);
380
+ const h = e.map(String).join(".");
381
+ g.get(h);
382
382
  const A = function() {
383
383
  return r().getNestedState(t, e);
384
384
  };
385
385
  Object.keys(v).forEach((u) => {
386
386
  A[u] = v[u];
387
387
  });
388
- const h = {
388
+ const p = {
389
389
  apply(u, s, G) {
390
390
  return console.log(
391
391
  `PROXY APPLY TRAP HIT: stateKey=${t}, path=${e.join(".")}`
@@ -434,6 +434,12 @@ function X(t, i, m, y) {
434
434
  S
435
435
  );
436
436
  };
437
+ if (s === "getSelectedIndex")
438
+ return () => {
439
+ const n = r.getState().getSelectedIndex(t, e.join("."));
440
+ if (n !== void 0)
441
+ return n;
442
+ };
437
443
  if (s === "stateSort")
438
444
  return (n) => {
439
445
  const o = [...r.getState().getNestedState(t, e).map((d, E) => ({
@@ -453,14 +459,14 @@ function X(t, i, m, y) {
453
459
  (o) => o.join(".") === e.join(".")
454
460
  ), c = a ? f : r.getState().getNestedState(t, e);
455
461
  return s !== "stateMapNoRender" && (g.clear(), $++), c.map((o, d) => {
456
- const E = a && o.__origIndex ? o.__origIndex : d, F = l(
462
+ const E = a && o.__origIndex ? o.__origIndex : d, x = l(
457
463
  o,
458
464
  [...e, E.toString()],
459
465
  S
460
466
  );
461
467
  return n(
462
468
  o,
463
- F,
469
+ x,
464
470
  d,
465
471
  f,
466
472
  l(f, e, S)
@@ -468,7 +474,7 @@ function X(t, i, m, y) {
468
474
  });
469
475
  };
470
476
  if (s === "$stateMap")
471
- return (n) => Q(jt, {
477
+ return (n) => Q(Ft, {
472
478
  proxy: {
473
479
  _stateKey: t,
474
480
  _path: e,
@@ -517,20 +523,20 @@ function X(t, i, m, y) {
517
523
  let E = null;
518
524
  if (!o.some((N) => {
519
525
  if (a) {
520
- const C = a.every(
526
+ const T = a.every(
521
527
  (q) => M(N[q], d[q])
522
528
  );
523
- return C && (E = N), C;
529
+ return T && (E = N), T;
524
530
  }
525
- const j = M(N, d);
526
- return j && (E = N), j;
531
+ const F = M(N, d);
532
+ return F && (E = N), F;
527
533
  }))
528
534
  _(e), K(i, d, e, t);
529
535
  else if (c && E) {
530
- const N = c(E), j = o.map(
531
- (C) => M(C, E) ? N : C
536
+ const N = c(E), F = o.map(
537
+ (T) => M(T, E) ? N : T
532
538
  );
533
- _(e), z(i, j, e);
539
+ _(e), z(i, F, e);
534
540
  }
535
541
  };
536
542
  if (s === "cut")
@@ -625,9 +631,9 @@ function X(t, i, m, y) {
625
631
  E && E.startsWith(n.key) && P(E);
626
632
  });
627
633
  const d = n.zodSchema.safeParse(c);
628
- return d.success ? !0 : (d.error.errors.forEach((F) => {
629
- const N = F.path, j = F.message, C = [n.key, ...N].join(".");
630
- a(C, j);
634
+ return d.success ? !0 : (d.error.errors.forEach((x) => {
635
+ const N = x.path, F = x.message, T = [n.key, ...N].join(".");
636
+ a(T, F);
631
637
  }), St(t), !1);
632
638
  } catch (o) {
633
639
  return console.error("Zod schema validation failed", o), !1;
@@ -695,11 +701,11 @@ function X(t, i, m, y) {
695
701
  formOpts: a
696
702
  }
697
703
  );
698
- const x = [...e, s], p = r.getState().getNestedState(t, x);
699
- return l(p, x, S);
704
+ const b = [...e, s], C = r.getState().getNestedState(t, b);
705
+ return l(C, b, S);
700
706
  }
701
- }, R = new Proxy(A, h);
702
- return g.set(T, {
707
+ }, R = new Proxy(A, p);
708
+ return g.set(h, {
703
709
  proxy: R,
704
710
  stateVersion: $
705
711
  }), R;
@@ -709,9 +715,9 @@ function X(t, i, m, y) {
709
715
  );
710
716
  }
711
717
  function tt(t) {
712
- return Q(xt, { proxy: t });
718
+ return Q(bt, { proxy: t });
713
719
  }
714
- function jt({
720
+ function Ft({
715
721
  proxy: t,
716
722
  rebuildStateShape: i
717
723
  }) {
@@ -723,7 +729,7 @@ function jt({
723
729
  (g, $, _, v, l) => t._mapFn(g, $, _, v, l)
724
730
  ) : null;
725
731
  }
726
- function xt({
732
+ function bt({
727
733
  proxy: t
728
734
  }) {
729
735
  const i = J(null), m = `${t._stateKey}-${t._path.join(".")}`;
@@ -754,8 +760,8 @@ function xt({
754
760
  else
755
761
  S = e;
756
762
  S !== null && typeof S == "object" && (S = JSON.stringify(S));
757
- const T = document.createTextNode(String(S));
758
- y.replaceWith(T);
763
+ const h = document.createTextNode(String(S));
764
+ y.replaceWith(h);
759
765
  }, [t._stateKey, t._path.join("."), t._effect]), Q("span", {
760
766
  ref: i,
761
767
  style: { display: "none" },
@@ -783,6 +789,6 @@ export {
783
789
  qt as addStateOptions,
784
790
  zt as createCogsState,
785
791
  Bt as notifyComponent,
786
- bt as useCogsStateFn
792
+ jt as useCogsStateFn
787
793
  };
788
794
  //# sourceMappingURL=CogsState.jsx.map
@@ -1 +1 @@
1
- {"version":3,"file":"CogsState.jsx","sources":["../src/CogsState.tsx"],"sourcesContent":["\"use client\";\r\nimport {\r\n createElement,\r\n startTransition,\r\n useEffect,\r\n useLayoutEffect,\r\n useMemo,\r\n useRef,\r\n useState,\r\n useSyncExternalStore,\r\n type ReactNode,\r\n} from \"react\";\r\n\r\nimport {\r\n debounce,\r\n getDifferences,\r\n getNestedValue,\r\n isFunction,\r\n type GenericObject,\r\n} from \"./utility.js\";\r\nimport {\r\n cutFunc,\r\n FormControlComponent,\r\n pushFunc,\r\n updateFn,\r\n ValidationWrapper,\r\n} from \"./Functions.js\";\r\nimport { isDeepEqual, transformStateFunc } from \"./utility.js\";\r\nimport type { UseMutationResult } from \"@tanstack/react-query\";\r\nimport { v4 as uuidv4 } from \"uuid\";\r\nimport { ZodArray, ZodObject, type ZodRawShape } from \"zod\";\r\n\r\nimport { formRefStore, getGlobalStore, type ComponentsType } from \"./store.js\";\r\nimport { useCogsConfig } from \"./CogsStateClient.js\";\r\n\r\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\r\n\r\nexport type ServerSyncStatus = {\r\n isFresh: boolean;\r\n isFreshTime: number;\r\n isStale: boolean;\r\n isStaleTime: number;\r\n isSyncing: boolean;\r\n isSyncingTime: number;\r\n};\r\n\r\nexport type SyncInfo = {\r\n timeStamp: number;\r\n userId: number;\r\n};\r\n\r\nexport type FormElementParams<T> = {\r\n get: () => T;\r\n\r\n set: UpdateType<T>;\r\n syncStatus: (SyncInfo & { date: Date }) | null;\r\n path: string[];\r\n validationErrors: () => string[];\r\n addValidationError: (message?: string) => void;\r\n\r\n inputProps: {\r\n ref?: React.RefObject<any>;\r\n value?: T extends boolean ? never : T;\r\n onChange?: (\r\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\r\n ) => void;\r\n onBlur?: () => void;\r\n };\r\n};\r\n\r\nexport type StateKeys = string;\r\n\r\ntype findWithFuncType<U> = (\r\n thisKey: keyof U,\r\n thisValue: U[keyof U]\r\n) => EndType<U> & StateObject<U>;\r\nexport type PushArgs<U> = (\r\n update:\r\n | Prettify<U>\r\n | ((prevState: NonNullable<Prettify<U>>[]) => NonNullable<Prettify<U>>),\r\n opts?: UpdateOpts<U>\r\n) => void;\r\n\r\ntype CutFunctionType = (\r\n index?: number,\r\n options?: { waitForSync?: boolean }\r\n) => void;\r\n\r\nexport type InferArrayElement<T> = T extends (infer U)[] ? U : never;\r\n\r\nexport type ArrayEndType<TShape extends unknown> = {\r\n findWith: findWithFuncType<InferArrayElement<TShape>>;\r\n index: (index: number) => StateObject<InferArrayElement<TShape>> & {\r\n insert: PushArgs<InferArrayElement<TShape>>;\r\n cut: CutFunctionType;\r\n _index: number;\r\n } & EndType<InferArrayElement<TShape>>;\r\n insert: PushArgs<InferArrayElement<TShape>>;\r\n cut: CutFunctionType;\r\n cutByValue: (value: string | number | boolean) => void;\r\n toggleByValue: (value: string | number | boolean) => void;\r\n stateSort: (\r\n compareFn: (\r\n a: InferArrayElement<TShape>,\r\n b: InferArrayElement<TShape>\r\n ) => number\r\n ) => ArrayEndType<TShape>;\r\n\r\n stateMapNoRender: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n $stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateFlattenOn: <K extends keyof InferArrayElement<TShape>>(\r\n field: K\r\n ) => StateObject<InferArrayElement<InferArrayElement<TShape>[K]>[]>;\r\n uniqueInsert: (\r\n payload: UpdateArg<InferArrayElement<TShape>>,\r\n fields?: (keyof InferArrayElement<TShape>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => void;\r\n stateFilter: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => void\r\n ) => ArrayEndType<TShape>;\r\n getSelected: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n} & EndType<TShape> & {\r\n [K in keyof (any[] extends infer T ? T : never)]: never;\r\n };\r\n\r\nexport type UpdateType<T> = (\r\n payload: UpdateArg<Prettify<T>>,\r\n opts?: UpdateOpts<T>\r\n) => void;\r\nexport type FormOptsType = {\r\n key?: string;\r\n validation?: {\r\n hideMessage?: boolean;\r\n message?: string;\r\n stretch?: boolean;\r\n props?: GenericObject;\r\n disable?: boolean;\r\n };\r\n formElements?: boolean;\r\n debounceTime?: number;\r\n stateServerDifferences?: string[][];\r\n};\r\n\r\nexport type FormControl<T> = (obj: FormElementParams<T>) => JSX.Element;\r\n\r\nexport type UpdateArg<S> = S | ((prevState: S) => S);\r\nexport type UpdateOpts<T> = {\r\n afterUpdate?: (state: T) => void;\r\n debounce?: number;\r\n};\r\nexport type ObjectEndType<T> = EndType<T> & {\r\n [K in keyof T]-?: ObjectEndType<T[K]>;\r\n} & {\r\n stateObject: (callbackfn: (value: T, setter: StateObject<T>) => void) => any;\r\n delete: () => void;\r\n};\r\ntype EffectFunction<T, R> = (state: T) => R;\r\nexport type EndType<T, IsArrayElement = false> = {\r\n update: UpdateType<T>;\r\n _path: string[];\r\n _stateKey: string;\r\n formElement: (control: FormControl<T>, opts?: FormOptsType) => JSX.Element;\r\n get: () => T;\r\n $get: () => T;\r\n $derive: <R>(fn: EffectFunction<T, R>) => R;\r\n _status: \"fresh\" | \"stale\" | \"synced\";\r\n getStatus: () => \"fresh\" | \"stale\";\r\n showValidationErrors: () => string[];\r\n setValidation: (ctx: string) => void;\r\n removeValidation: (ctx: string) => void;\r\n ignoreFields: (fields: string[]) => StateObject<T>;\r\n _selected: boolean;\r\n setSelected: (value: boolean) => void;\r\n getFormRef: () => React.RefObject<any> | undefined;\r\n removeStorage: () => void;\r\n validationWrapper: ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => JSX.Element;\r\n lastSynced?: SyncInfo;\r\n} & (IsArrayElement extends true ? { cut: () => void } : {}) & {\r\n [K in keyof (any extends infer T ? T : never)]: never;\r\n };\r\n\r\nexport type StateObject<T> = (T extends any[]\r\n ? ArrayEndType<T>\r\n : T extends Record<string, unknown> | object\r\n ? { [K in keyof T]-?: StateObject<T[K]> } & ObjectEndType<T>\r\n : T extends string | number | boolean | null\r\n ? T\r\n : never) &\r\n EndType<T, true> & {\r\n getAllFormRefs: () => Map<string, React.RefObject<any>>;\r\n _componentId: string | null;\r\n getComponents: () => ComponentsType;\r\n validateZodSchema: () => void;\r\n _initialState: T;\r\n updateInitialState: (newState: T | null) => {\r\n fetchId: (field: keyof T) => string | number;\r\n };\r\n _isLoading: boolean;\r\n _serverState: T;\r\n revertToInitialState: (obj?: { validationKey?: string }) => T;\r\n middleware: (\r\n middles: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void\r\n ) => void;\r\n _isServerSynced: () => boolean;\r\n getLocalStorage: (key: string) => LocalStorageData<T> | null;\r\n };\r\n\r\nexport type CogsUpdate<T extends unknown> = UpdateType<T>;\r\n\r\nexport type EffectiveSetState<TStateObject> = (\r\n newStateOrFunction:\r\n | TStateObject\r\n | ((prevState: TStateObject) => TStateObject),\r\n path: string[],\r\n updateObj: { updateType: \"update\" | \"insert\" | \"cut\" },\r\n validationKey?: string,\r\n opts?: UpdateOpts<TStateObject>\r\n) => void;\r\n\r\nexport type UpdateTypeDetail = {\r\n timeStamp: number;\r\n stateKey: string;\r\n updateType: \"update\" | \"insert\" | \"cut\";\r\n path: string[];\r\n status: \"new\" | \"sent\" | \"synced\";\r\n oldValue: any;\r\n newValue: any;\r\n userId?: number;\r\n};\r\n\r\nexport type ActionsType<T> = {\r\n type: \"onChange\";\r\n action: ({ state, actionType }: { state: T; actionType: string }) => void;\r\n debounce?: number;\r\n}[];\r\n\r\ntype ArrayToObject<T extends string[]> = Record<T[number], string>;\r\ntype CookieType<T> = {\r\n timeStamp: number;\r\n value: T;\r\n cookieName: string;\r\n OnUnMountCookie?: Boolean;\r\n};\r\nexport type CogsCookiesType<T extends string[] = string[]> = CookieType<\r\n ArrayToObject<T>\r\n>;\r\nexport type ReactivityType = \"none\" | \"component\" | \"deps\" | \"all\";\r\n\r\ntype ValidationOptionsType = {\r\n key?: string;\r\n zodSchema?: ZodObject<ZodRawShape> | ZodArray<ZodObject<ZodRawShape>>;\r\n onBlur?: boolean;\r\n};\r\n\r\nexport type OptionsType<T extends unknown = unknown> = {\r\n log?: boolean;\r\n componentId?: string;\r\n serverSync?: ServerSyncType<T>;\r\n validation?: ValidationOptionsType;\r\n enableServerState?: boolean;\r\n middleware?: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void;\r\n\r\n modifyState?: (state: T) => T;\r\n localStorage?: { key: string | ((state: T) => string) };\r\n formElements?: FormsElementsType;\r\n enabledSync?: (state: T) => boolean;\r\n reactiveDeps?: (state: T) => any[] | true;\r\n reactiveType?: ReactivityType[] | ReactivityType;\r\n syncUpdate?: Partial<UpdateTypeDetail>;\r\n\r\n initialState?: T;\r\n dependencies?: any[]; // Just like useEffect dependencies\r\n};\r\nexport type ServerSyncType<T> = {\r\n testKey?: string;\r\n syncKey: (({ state }: { state: T }) => string) | string;\r\n syncFunction: ({ state }: { state: T }) => void;\r\n debounce?: number;\r\n mutation: UseMutationResult<any, unknown, any, unknown>;\r\n snapshot?: {\r\n name: (({ state }: { state: T }) => string) | string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\nexport type SyncActionsType<T> = {\r\n syncKey: string;\r\n\r\n rollBackState?: T;\r\n actionTimeStamp: number;\r\n retryCount?: number;\r\n status:\r\n | \"success\"\r\n | \"waiting\"\r\n | \"rolledBack\"\r\n | \"error\"\r\n | \"cancelled\"\r\n | \"failed\";\r\n snapshot?: {\r\n name: string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\n\r\nexport type ValidationWrapperOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n active: boolean;\r\n stretch?: boolean;\r\n path: string[];\r\n message?: string;\r\n data?: T;\r\n key?: string;\r\n};\r\nexport type SyncRenderOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n time: number;\r\n data?: T;\r\n key?: string;\r\n};\r\n\r\ntype FormsElementsType<T extends unknown = unknown> = {\r\n validation?: (options: ValidationWrapperOptions<T>) => React.ReactNode;\r\n syncRender?: (options: SyncRenderOptions<T>) => React.ReactNode;\r\n};\r\n\r\nexport type InitialStateInnerType<T extends unknown = unknown> = {\r\n initialState: T;\r\n} & OptionsType<T>;\r\n\r\nexport type InitialStateType<T> = {\r\n [key: string]: InitialStateInnerType<T>;\r\n};\r\n\r\nexport type AllStateTypes<T extends unknown> = Record<string, T>;\r\n\r\nexport type CogsInitialState<T> = {\r\n initialState: T;\r\n formElements?: FormsElementsType<T>;\r\n};\r\n\r\nexport type TransformedStateType<T> = {\r\n [P in keyof T]: T[P] extends CogsInitialState<infer U> ? U : T[P];\r\n};\r\n\r\nfunction setAndMergeOptions(stateKey: string, newOptions: OptionsType<any>) {\r\n const getInitialOptions = getGlobalStore.getState().getInitialOptions;\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n\r\n setInitialStateOptions(stateKey as string, {\r\n ...initialOptions,\r\n ...newOptions,\r\n });\r\n}\r\n\r\nfunction setOptions<StateKey, Opt>({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n}: {\r\n stateKey: StateKey;\r\n options?: OptionsType<any>;\r\n initialOptionsPart: Record<string, any>;\r\n}) {\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n const initialOptionsPartState = initialOptionsPart[stateKey as string] || {};\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n const mergedOptions = { ...initialOptionsPartState, ...initialOptions };\r\n\r\n let needToAdd = false;\r\n if (options) {\r\n for (const key in options) {\r\n if (!mergedOptions.hasOwnProperty(key)) {\r\n needToAdd = true;\r\n\r\n mergedOptions[key] = options[key as keyof typeof options];\r\n } else {\r\n if (\r\n key == \"localStorage\" &&\r\n options[key] &&\r\n mergedOptions[key].key !== options[key]?.key\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n }\r\n }\r\n }\r\n if (needToAdd) {\r\n setInitialStateOptions(stateKey as string, mergedOptions);\r\n }\r\n}\r\nexport function addStateOptions<T extends unknown>(\r\n initialState: T,\r\n { formElements, validation }: OptionsType<T>\r\n) {\r\n return { initialState: initialState, formElements, validation } as T;\r\n}\r\n\r\nexport const createCogsState = <State extends Record<string, unknown>>(\r\n initialState: State,\r\n opt?: { formElements?: FormsElementsType; validation?: ValidationOptionsType }\r\n) => {\r\n let newInitialState = initialState;\r\n\r\n // Extract state parts and options using transformStateFunc\r\n const [statePart, initialOptionsPart] =\r\n transformStateFunc<State>(newInitialState);\r\n\r\n // Apply global formElements as defaults to each state key's options\r\n if (opt?.formElements || opt?.validation) {\r\n Object.keys(initialOptionsPart).forEach((key) => {\r\n // Get the existing options for this state key\r\n initialOptionsPart[key] = initialOptionsPart[key] || {};\r\n\r\n initialOptionsPart[key].formElements = {\r\n ...opt.formElements, // Global defaults first\r\n ...opt?.validation,\r\n ...(initialOptionsPart[key].formElements || {}), // State-specific overrides\r\n };\r\n });\r\n }\r\n\r\n getGlobalStore.getState().setInitialStates(statePart);\r\n type StateKeys = keyof typeof statePart;\r\n\r\n const useCogsState = <StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options?: OptionsType<(typeof statePart)[StateKey]>\r\n ) => {\r\n const [componentId] = useState(options?.componentId ?? uuidv4());\r\n setOptions({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n });\r\n\r\n const thiState =\r\n getGlobalStore.getState().cogsStateStore[stateKey as string] ||\r\n statePart[stateKey as string];\r\n const partialState = options?.modifyState\r\n ? options.modifyState(thiState)\r\n : thiState;\r\n\r\n const [state, updater] = useCogsStateFn<(typeof statePart)[StateKey]>(\r\n partialState,\r\n {\r\n stateKey: stateKey as string,\r\n syncUpdate: options?.syncUpdate,\r\n componentId,\r\n localStorage: options?.localStorage,\r\n middleware: options?.middleware,\r\n enabledSync: options?.enabledSync,\r\n reactiveType: options?.reactiveType,\r\n reactiveDeps: options?.reactiveDeps,\r\n initialState: options?.initialState,\r\n dependencies: options?.dependencies,\r\n }\r\n );\r\n\r\n return updater;\r\n };\r\n\r\n function setCogsOptions<StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options: OptionsType<(typeof statePart)[StateKey]>\r\n ) {\r\n setOptions({ stateKey, options, initialOptionsPart });\r\n }\r\n\r\n return { useCogsState, setCogsOptions };\r\n};\r\n\r\nconst {\r\n setUpdaterState,\r\n setState,\r\n getInitialOptions,\r\n getKeyState,\r\n getValidationErrors,\r\n setStateLog,\r\n updateInitialStateGlobal,\r\n addValidationError,\r\n removeValidationError,\r\n setServerSyncActions,\r\n} = getGlobalStore.getState();\r\n\r\nconst loadFromLocalStorage = (localStorageKey: string) => {\r\n if (!localStorageKey) return null;\r\n\r\n try {\r\n const storedData = window.localStorage.getItem(localStorageKey);\r\n if (!storedData) return null;\r\n\r\n const parsedData = JSON.parse(storedData);\r\n\r\n return parsedData;\r\n } catch (error) {\r\n console.error(\"Error loading from localStorage:\", error);\r\n return null;\r\n }\r\n};\r\n\r\nconst saveToLocalStorage = <T,>(\r\n state: T,\r\n thisKey: string,\r\n currentInitialOptions: any,\r\n sessionId?: string\r\n) => {\r\n if (currentInitialOptions.log) {\r\n console.log(\r\n \"saving to localstorage\",\r\n thisKey,\r\n currentInitialOptions.localStorage?.key,\r\n sessionId\r\n );\r\n }\r\n const key = isFunction(currentInitialOptions.localStorage?.key)\r\n ? currentInitialOptions.localStorage?.key(state)\r\n : currentInitialOptions.localStorage?.key;\r\n if (key && sessionId) {\r\n const data: LocalStorageData<T> = {\r\n state,\r\n lastUpdated: Date.now(),\r\n lastSyncedWithServer:\r\n getGlobalStore.getState().serverSyncLog[thisKey]?.[0]?.timeStamp,\r\n baseServerState: getGlobalStore.getState().serverState[thisKey],\r\n };\r\n\r\n const storageKey = `${sessionId}-${thisKey}-${key}`;\r\n\r\n window.localStorage.setItem(storageKey, JSON.stringify(data));\r\n }\r\n};\r\n\r\ntype LocalStorageData<T> = {\r\n state: T;\r\n lastUpdated: number;\r\n lastSyncedWithServer?: number;\r\n baseServerState?: T; // Add this to track what server state our changes are based on\r\n};\r\n\r\nconst updateGlobalState = (\r\n thisKey: string,\r\n initialState: any,\r\n newState: any,\r\n effectiveSetState: EffectiveSetState<any>,\r\n componentId: string,\r\n sessionId?: string\r\n) => {\r\n // Update all global state at once\r\n const updates = {\r\n initialState: initialState,\r\n updaterState: createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n ),\r\n state: newState,\r\n };\r\n\r\n startTransition(() => {\r\n updateInitialStateGlobal(thisKey, updates.initialState);\r\n setUpdaterState(thisKey, updates.updaterState);\r\n setState(thisKey, updates.state);\r\n });\r\n};\r\n\r\nconst notifyComponents = (thisKey: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n if (!stateEntry) return;\r\n\r\n // Batch component updates\r\n const updates = new Set<() => void>();\r\n stateEntry.components.forEach((component) => {\r\n updates.add(() => component.forceUpdate());\r\n });\r\n\r\n // Schedule updates in the next tick to allow batching\r\n queueMicrotask(() => {\r\n startTransition(() => {\r\n updates.forEach((update) => update());\r\n });\r\n });\r\n};\r\n\r\nexport const notifyComponent = (stateKey: string, componentId: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // Force an update to ensure the current value is saved\r\n\r\n component.forceUpdate();\r\n }\r\n }\r\n};\r\n\r\nexport function useCogsStateFn<TStateObject extends unknown>(\r\n stateObject: TStateObject,\r\n {\r\n stateKey,\r\n serverSync,\r\n localStorage,\r\n formElements,\r\n middleware,\r\n reactiveDeps,\r\n reactiveType,\r\n componentId,\r\n initialState,\r\n syncUpdate,\r\n dependencies,\r\n }: {\r\n stateKey?: string;\r\n componentId?: string;\r\n } & OptionsType<TStateObject> = {}\r\n) {\r\n const [reactiveForce, forceUpdate] = useState({}); //this is the key to reactivity\r\n const { sessionId } = useCogsConfig();\r\n\r\n let noStateKey = stateKey ? false : true;\r\n const [thisKey] = useState(stateKey ?? uuidv4());\r\n const stateLog = getGlobalStore.getState().stateLog[thisKey];\r\n const componentUpdatesRef = useRef(new Set<string>());\r\n const componentIdRef = useRef(componentId ?? uuidv4());\r\n const latestInitialOptionsRef = useRef<any>(null);\r\n latestInitialOptionsRef.current = getInitialOptions(thisKey as string);\r\n\r\n useEffect(() => {\r\n if (syncUpdate && syncUpdate.stateKey === thisKey && syncUpdate.path?.[0]) {\r\n // Update the actual state value\r\n setState(thisKey, (prevState: any) => ({\r\n ...prevState,\r\n [syncUpdate.path![0]!]: syncUpdate.newValue,\r\n }));\r\n\r\n // Create combined key and update sync info\r\n const syncKey = `${syncUpdate.stateKey}:${syncUpdate.path.join(\".\")}`;\r\n getGlobalStore.getState().setSyncInfo(syncKey, {\r\n timeStamp: syncUpdate.timeStamp!,\r\n userId: syncUpdate.userId!,\r\n });\r\n }\r\n }, [syncUpdate]);\r\n\r\n useEffect(() => {\r\n setAndMergeOptions(thisKey as string, {\r\n initialState,\r\n });\r\n const options = latestInitialOptionsRef.current;\r\n let localData = null;\r\n if (options.log) {\r\n console.log(\"newoptions\", options);\r\n }\r\n const localkey = isFunction(options.localStorage?.key)\r\n ? options.localStorage?.key(initialState)\r\n : options.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n localData = loadFromLocalStorage(\r\n sessionId + \"-\" + thisKey + \"-\" + localkey\r\n );\r\n }\r\n\r\n let newState = null;\r\n if (initialState) {\r\n newState = initialState;\r\n\r\n if (localData) {\r\n if (localData.lastUpdated > (localData.lastSyncedWithServer || 0)) {\r\n newState = localData.state;\r\n }\r\n }\r\n updateGlobalState(\r\n thisKey,\r\n initialState,\r\n newState,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n\r\n notifyComponents(thisKey);\r\n forceUpdate({});\r\n }\r\n }, [initialState, ...(dependencies || [])]);\r\n\r\n useLayoutEffect(() => {\r\n if (noStateKey) {\r\n setAndMergeOptions(thisKey as string, {\r\n serverSync,\r\n formElements,\r\n initialState,\r\n localStorage,\r\n middleware,\r\n });\r\n }\r\n\r\n const depsKey = `${thisKey}////${componentIdRef.current}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(thisKey) || {\r\n components: new Map(),\r\n };\r\n\r\n stateEntry.components.set(depsKey, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set(),\r\n deps: [],\r\n depsFunction: reactiveDeps || undefined,\r\n reactiveType: reactiveType ?? [\"component\", \"deps\"],\r\n });\r\n\r\n getGlobalStore.getState().stateComponents.set(thisKey, stateEntry);\r\n //need to force update to create the stateUpdates references\r\n forceUpdate({});\r\n return () => {\r\n const depsKey = `${thisKey}////${componentIdRef.current}`;\r\n\r\n if (stateEntry) {\r\n stateEntry.components.delete(depsKey);\r\n if (stateEntry.components.size === 0) {\r\n getGlobalStore.getState().stateComponents.delete(thisKey);\r\n }\r\n }\r\n };\r\n }, []);\r\n\r\n const effectiveSetState = (\r\n newStateOrFunction:\r\n | TStateObject\r\n | ((prevState: TStateObject) => TStateObject),\r\n path: string[],\r\n updateObj: { updateType: \"insert\" | \"cut\" | \"update\" },\r\n validationKey?: string\r\n ) => {\r\n if (Array.isArray(path)) {\r\n const pathKey = `${thisKey}-${path.join(\".\")}`;\r\n componentUpdatesRef.current.add(pathKey);\r\n }\r\n setState(thisKey, (prevValue: TStateObject) => {\r\n const payload = isFunction<TStateObject>(newStateOrFunction)\r\n ? newStateOrFunction(prevValue as TStateObject)\r\n : newStateOrFunction;\r\n\r\n const signalId = `${thisKey}-${path.join(\".\")}`;\r\n if (signalId) {\r\n let isArrayOperation = false;\r\n let elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(signalId);\r\n\r\n if (\r\n (!elements || elements.size === 0) &&\r\n (updateObj.updateType === \"insert\" || updateObj.updateType === \"cut\")\r\n ) {\r\n // Remove last segment (index) from path\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n // If it's an array, use that path for signal\r\n if (Array.isArray(arrayValue)) {\r\n isArrayOperation = true;\r\n const arraySignalId = `${thisKey}-${arrayPath.join(\".\")}`;\r\n elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(arraySignalId);\r\n }\r\n }\r\n\r\n if (elements) {\r\n const newValue = isArrayOperation\r\n ? getNestedValue(payload, path.slice(0, -1))\r\n : getNestedValue(payload, path);\r\n elements.forEach(({ parentId, position, effect }) => {\r\n const parent = document.querySelector(\r\n `[data-parent-id=\"${parentId}\"]`\r\n );\r\n if (parent) {\r\n const childNodes = Array.from(parent.childNodes);\r\n if (childNodes[position]) {\r\n const displayValue = effect\r\n ? new Function(\"state\", `return (${effect})(state)`)(newValue)\r\n : newValue;\r\n childNodes[position].textContent = String(displayValue);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n if (\r\n updateObj.updateType === \"update\" &&\r\n (validationKey || latestInitialOptionsRef.current?.validationKey) &&\r\n path\r\n ) {\r\n removeValidationError(\r\n (validationKey || latestInitialOptionsRef.current?.validationKey) +\r\n \".\" +\r\n path.join(\".\")\r\n );\r\n }\r\n const arrayWithoutIndex = path.slice(0, path.length - 1);\r\n if (\r\n updateObj.updateType === \"cut\" &&\r\n latestInitialOptionsRef.current?.validationKey\r\n ) {\r\n removeValidationError(\r\n latestInitialOptionsRef.current?.validationKey +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n }\r\n if (\r\n updateObj.updateType === \"insert\" &&\r\n latestInitialOptionsRef.current?.validationKey\r\n ) {\r\n let getValidation = getValidationErrors(\r\n latestInitialOptionsRef.current?.validationKey +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n\r\n //TODO this is untested its supposed to cahnge teh validation errors alreaady stored when a new entry is push\r\n\r\n getValidation.filter(([k, v]) => {\r\n let length = k?.split(\".\").length;\r\n\r\n if (\r\n k == arrayWithoutIndex.join(\".\") &&\r\n length == arrayWithoutIndex.length - 1\r\n ) {\r\n // console.log(length, pathWithoutIndex.length);\r\n let newKey = k + \".\" + arrayWithoutIndex;\r\n removeValidationError(k!);\r\n addValidationError(newKey, v!);\r\n }\r\n });\r\n }\r\n\r\n const oldValue = getNestedValue(prevValue, path);\r\n const newValue = getNestedValue(payload, path);\r\n const pathToCheck =\r\n updateObj.updateType === \"update\"\r\n ? path.join(\".\")\r\n : [...path].slice(0, -1).join(\".\");\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n\r\n if (stateEntry) {\r\n for (const [key, component] of stateEntry.components.entries()) {\r\n let shouldUpdate = false;\r\n const reactiveTypes = Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"];\r\n\r\n // Skip if reactivity is disabled\r\n if (reactiveTypes.includes(\"none\")) {\r\n continue;\r\n }\r\n\r\n // Force update if \"all\" is specified\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n\r\n continue;\r\n }\r\n\r\n // Check component-level path reactivity\r\n if (reactiveTypes.includes(\"component\")) {\r\n if (\r\n component.paths &&\r\n (component.paths.has(pathToCheck) || component.paths.has(\"\"))\r\n ) {\r\n shouldUpdate = true;\r\n }\r\n }\r\n\r\n // Check dependency-based reactivity\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(payload);\r\n\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) {\r\n shouldUpdate = true;\r\n }\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n shouldUpdate = true;\r\n }\r\n }\r\n }\r\n\r\n if (shouldUpdate) {\r\n component.forceUpdate();\r\n }\r\n }\r\n }\r\n const timeStamp = Date.now();\r\n\r\n const newUpdate = {\r\n timeStamp,\r\n stateKey: thisKey,\r\n path,\r\n updateType: updateObj.updateType,\r\n status: \"new\" as const,\r\n oldValue,\r\n newValue,\r\n } satisfies UpdateTypeDetail;\r\n\r\n setStateLog(thisKey, (prevLogs) => {\r\n const logs = [...(prevLogs ?? []), newUpdate];\r\n\r\n // Aggregate the updates by stateKey and path\r\n const aggregatedLogs = logs.reduce((acc, log) => {\r\n const uniqueKey = `${log.stateKey}:${JSON.stringify(log.path)}`;\r\n const existing = acc.get(uniqueKey);\r\n\r\n if (existing) {\r\n // Update the existing entry with the most recent details\r\n existing.timeStamp = Math.max(existing.timeStamp, log.timeStamp);\r\n existing.newValue = log.newValue; // Overwrite with the latest value\r\n existing.oldValue = existing.oldValue ?? log.oldValue; // Retain the initial oldValue\r\n existing.updateType = log.updateType; // Update to the most recent type\r\n } else {\r\n // Add the log if no existing match is found\r\n acc.set(uniqueKey, { ...(log as any) });\r\n }\r\n\r\n return acc;\r\n }, new Map<string, typeof newUpdate>());\r\n\r\n // Convert the aggregated map back to an array\r\n return Array.from(aggregatedLogs.values());\r\n });\r\n\r\n saveToLocalStorage(\r\n payload,\r\n thisKey,\r\n latestInitialOptionsRef.current,\r\n sessionId\r\n );\r\n\r\n if (middleware) {\r\n middleware({\r\n updateLog: stateLog,\r\n update: newUpdate,\r\n });\r\n }\r\n if (latestInitialOptionsRef.current?.serverSync) {\r\n const serverStateStore = getGlobalStore.getState().serverState[thisKey];\r\n const serverSync = latestInitialOptionsRef.current?.serverSync;\r\n setServerSyncActions(thisKey, {\r\n syncKey:\r\n typeof serverSync.syncKey == \"string\"\r\n ? serverSync.syncKey\r\n : serverSync.syncKey({ state: payload }),\r\n rollBackState: serverStateStore,\r\n actionTimeStamp: Date.now() + (serverSync.debounce ?? 3000),\r\n status: \"waiting\",\r\n });\r\n }\r\n\r\n return payload;\r\n });\r\n };\r\n if (!getGlobalStore.getState().updaterState[thisKey]) {\r\n setUpdaterState(\r\n thisKey,\r\n createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n )\r\n );\r\n if (!getGlobalStore.getState().cogsStateStore[thisKey]) {\r\n setState(thisKey, stateObject);\r\n }\r\n if (!getGlobalStore.getState().initialStateGlobal[thisKey]) {\r\n updateInitialStateGlobal(thisKey, stateObject);\r\n }\r\n }\r\n\r\n const updaterFinal = useMemo(() => {\r\n // Create proxy with baseObject as target\r\n return createProxyHandler<TStateObject>(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n }, [thisKey]);\r\n\r\n return [getKeyState(thisKey), updaterFinal] as [\r\n TStateObject,\r\n StateObject<TStateObject>,\r\n ];\r\n}\r\n\r\nfunction createProxyHandler<T>(\r\n stateKey: string,\r\n effectiveSetState: EffectiveSetState<T>,\r\n componentId: string,\r\n sessionId?: string\r\n): StateObject<T> {\r\n // ADDED: Enhanced cache with versioning\r\n type CacheEntry = {\r\n proxy: any;\r\n stateVersion: number;\r\n };\r\n const shapeCache = new Map<string, CacheEntry>();\r\n let stateVersion = 0;\r\n\r\n // ADDED: Cache invalidation helper\r\n const invalidateCachePath = (path: string[]) => {\r\n const pathKey = path.join(\".\");\r\n for (const [key] of shapeCache) {\r\n if (key === pathKey || key.startsWith(pathKey + \".\")) {\r\n shapeCache.delete(key);\r\n }\r\n }\r\n stateVersion++;\r\n };\r\n\r\n const baseObj = {\r\n removeValidation: (obj?: { validationKey?: string }) => {\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n },\r\n\r\n revertToInitialState: (obj?: { validationKey?: string }) => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n if (init?.key) {\r\n removeValidationError(init?.key);\r\n }\r\n\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n\r\n // ADDED: Clear cache on revert\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newProxy = rebuildStateShape(initialState, []);\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n startTransition(() => {\r\n setUpdaterState(stateKey, newProxy);\r\n setState(stateKey, initialState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return initialState;\r\n },\r\n updateInitialState: (newState: T) => {\r\n // ADDED: Clear cache on initial state update\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newUpdaterState = createProxyHandler(\r\n stateKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n startTransition(() => {\r\n updateInitialStateGlobal(stateKey, newState);\r\n setUpdaterState(stateKey, newUpdaterState);\r\n setState(stateKey, newState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return {\r\n fetchId: (field: keyof T) => newUpdaterState.get()[field],\r\n };\r\n },\r\n _initialState: getGlobalStore.getState().initialStateGlobal[stateKey],\r\n _serverState: getGlobalStore.getState().serverState[stateKey],\r\n _isLoading: getGlobalStore.getState().isLoadingGlobal[stateKey],\r\n _isServerSynced: () => {\r\n const serverState = getGlobalStore.getState().serverState[stateKey];\r\n return Boolean(\r\n serverState && isDeepEqual(serverState, getKeyState(stateKey))\r\n );\r\n },\r\n };\r\n\r\n function rebuildStateShape(\r\n currentState: T,\r\n path: string[] = [],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ): any {\r\n const cacheKey = path.map(String).join(\".\");\r\n\r\n // MODIFIED: Cache check with version\r\n const cachedEntry = shapeCache.get(cacheKey);\r\n // if (cachedEntry?.stateVersion === stateVersion) {\r\n // return cachedEntry.proxy;\r\n // }\r\n type CallableStateObject<T> = {\r\n (): T;\r\n } & {\r\n [key: string]: any;\r\n };\r\n\r\n const baseFunction = function () {\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n } as unknown as CallableStateObject<T>;\r\n\r\n // Copy properties from baseObj to the function with type assertion\r\n Object.keys(baseObj).forEach((key) => {\r\n (baseFunction as any)[key] = (baseObj as any)[key];\r\n });\r\n\r\n const handler = {\r\n apply(target: any, thisArg: any, args: any[]) {\r\n console.log(\r\n `PROXY APPLY TRAP HIT: stateKey=${stateKey}, path=${path.join(\".\")}`\r\n ); // <--- ADD LOGGING\r\n console.trace(\"Apply trap stack trace\");\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n },\r\n\r\n get(target: any, prop: string) {\r\n if (\r\n prop !== \"then\" &&\r\n !prop.startsWith(\"$\") &&\r\n prop !== \"stateMapNoRender\"\r\n ) {\r\n const currentPath = path.join(\".\");\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n\r\n if (stateEntry) {\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // Only add paths for non-root or specifically for get() at root\r\n if (path.length > 0 || prop === \"get\") {\r\n component.paths.add(currentPath);\r\n }\r\n } else {\r\n }\r\n }\r\n }\r\n if (prop === \"_status\") {\r\n // Get current state at this path (non-reactive version)\r\n const thisReactiveState = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n }\r\n if (prop === \"getStatus\") {\r\n return function () {\r\n // Get current state at this path (reactive version)\r\n const thisReactiveState = getGlobalStore().getNestedState(\r\n stateKey,\r\n path\r\n );\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n };\r\n }\r\n if (prop === \"removeStorage\") {\r\n return () => {\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n console.log(\"removing storage\", storageKey);\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n };\r\n }\r\n if (prop === \"showValidationErrors\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n const errors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key + \".\" + path.join(\".\"));\r\n\r\n return errors;\r\n };\r\n }\r\n if (Array.isArray(currentState)) {\r\n if (prop === \"getSelected\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n if (selectedIndex === undefined) return undefined;\r\n return rebuildStateShape(\r\n currentState[selectedIndex],\r\n [...path, selectedIndex.toString()],\r\n meta\r\n );\r\n };\r\n }\r\n if (prop === \"stateSort\") {\r\n return (\r\n compareFn: (\r\n a: InferArrayElement<T>,\r\n b: InferArrayElement<T>\r\n ) => number\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n\r\n // Create a shallow copy with original indices\r\n const arrayCopy = currentArray.map((v: any, i: number) => ({\r\n ...v,\r\n __origIndex: i.toString(),\r\n }));\r\n\r\n // Sort the copy using the provided compare function\r\n const sortedArray = [...arrayCopy].sort(compareFn);\r\n\r\n // ADDED: Clear cache for sort operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // Return the sorted array with state objects\r\n return rebuildStateShape(sortedArray as any, path, {\r\n filtered: [...(meta?.filtered || []), path],\r\n validIndices: sortedArray.map((item) =>\r\n parseInt(item.__origIndex as string)\r\n ),\r\n });\r\n };\r\n }\r\n if (prop === \"stateMap\" || prop === \"stateMapNoRender\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n const isFiltered = meta?.filtered?.some(\r\n (p) => p.join(\".\") === path.join(\".\")\r\n );\r\n const arrayToMap = isFiltered\r\n ? currentState\r\n : getGlobalStore.getState().getNestedState(stateKey, path);\r\n\r\n if (prop !== \"stateMapNoRender\") {\r\n shapeCache.clear();\r\n stateVersion++;\r\n }\r\n\r\n return arrayToMap.map((val: any, index: number) => {\r\n const thisIndex =\r\n isFiltered && val.__origIndex ? val.__origIndex : index;\r\n const elementProxy = rebuildStateShape(\r\n val,\r\n [...path, thisIndex.toString()],\r\n meta\r\n );\r\n return callbackfn(\r\n val,\r\n elementProxy,\r\n index,\r\n currentState as any,\r\n rebuildStateShape(currentState as any, path, meta)\r\n );\r\n });\r\n };\r\n }\r\n if (prop === \"$stateMap\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n return createElement(SignalMapRenderer, {\r\n proxy: {\r\n _stateKey: stateKey,\r\n _path: path,\r\n _mapFn: callbackfn as any, // Pass the actual function, not string\r\n },\r\n\r\n rebuildStateShape,\r\n });\r\n };\r\n }\r\n if (prop === \"stateFlattenOn\") {\r\n return (fieldName: string) => {\r\n const isFiltered = meta?.filtered?.some(\r\n (p) => p.join(\".\") === path.join(\".\")\r\n );\r\n const arrayToMap = isFiltered\r\n ? currentState\r\n : getGlobalStore.getState().getNestedState(stateKey, path);\r\n\r\n // ADDED: Clear shape cache for flattening operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const flattenedResults = arrayToMap.flatMap(\r\n (val: any, index: number) => {\r\n return val[fieldName] ?? [];\r\n }\r\n );\r\n\r\n return rebuildStateShape(\r\n flattenedResults,\r\n [...path, \"[*]\", fieldName],\r\n meta\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"findWith\") {\r\n return (\r\n thisKey: keyof InferArrayElement<T>,\r\n thisValue: InferArrayElement<T>[keyof InferArrayElement<T>]\r\n ) => {\r\n const foundIndex = currentState.findIndex(\r\n (obj: any) => obj[thisKey] === thisValue\r\n );\r\n if (foundIndex === -1) return undefined;\r\n const foundValue = currentState[foundIndex];\r\n const newPath = [...path, foundIndex.toString()];\r\n // console.log(\r\n // \"findWithfindWithfindWithfindWith\",\r\n // stateKey,\r\n // foundValue,\r\n // newPath,\r\n // );\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // ADDED: Clear cache for find operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n // Try returning without spread\r\n return rebuildStateShape(foundValue, newPath);\r\n };\r\n }\r\n\r\n if (prop === \"index\") {\r\n return (index: number) => {\r\n const indexValue = currentState[index];\r\n return rebuildStateShape(indexValue, [...path, index.toString()]);\r\n };\r\n }\r\n\r\n if (prop === \"insert\") {\r\n return (payload: UpdateArg<T>) => {\r\n // ADDED: Invalidate cache on insert\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, payload, path, stateKey);\r\n return rebuildStateShape(\r\n getGlobalStore.getState().cogsStateStore[stateKey],\r\n []\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"uniqueInsert\") {\r\n return (\r\n payload: UpdateArg<T>,\r\n fields?: (keyof InferArrayElement<T>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n const newValue = isFunction<T>(payload)\r\n ? payload(currentArray as any)\r\n : (payload as any);\r\n\r\n let matchedItem: any = null;\r\n const isUnique = !currentArray.some((item) => {\r\n if (fields) {\r\n const isMatch = fields.every((field) =>\r\n isDeepEqual(item[field], newValue[field])\r\n );\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n }\r\n const isMatch = isDeepEqual(item, newValue);\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n });\r\n\r\n if (isUnique) {\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, newValue, path, stateKey);\r\n } else if (onMatch && matchedItem) {\r\n const updatedItem = onMatch(matchedItem);\r\n const updatedArray = currentArray.map((item) =>\r\n isDeepEqual(item, matchedItem) ? updatedItem : item\r\n );\r\n invalidateCachePath(path);\r\n updateFn(effectiveSetState, updatedArray as any, path);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"cut\") {\r\n return (index: number, options?: { waitForSync?: boolean }) => {\r\n if (options?.waitForSync) return;\r\n // ADDED: Invalidate cache on cut\r\n invalidateCachePath(path);\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n };\r\n }\r\n if (prop === \"cutByValue\") {\r\n return (value: string | number | boolean) => {\r\n for (let index = 0; index < currentState.length; index++) {\r\n if (currentState[index] === value) {\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n }\r\n }\r\n };\r\n }\r\n if (prop === \"toggleByValue\") {\r\n return (value: string | number | boolean) => {\r\n const index = currentState.findIndex((item) => item === value);\r\n if (index > -1) {\r\n // Value exists, so cut it\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n } else {\r\n // Value doesn't exist, so insert it\r\n pushFunc(effectiveSetState, value as any, path, stateKey);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"stateFilter\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const newVal = currentState.map((v: any, i: number) => ({\r\n ...v,\r\n __origIndex: i.toString(),\r\n }));\r\n\r\n const validIndices: number[] = [];\r\n const filteredArray: Array<InferArrayElement<T>> = [];\r\n\r\n for (let i = 0; i < newVal.length; i++) {\r\n if (callbackfn(newVal[i], i)) {\r\n validIndices.push(i);\r\n filteredArray.push(newVal[i]);\r\n }\r\n }\r\n\r\n // ADDED: Clear cache for filter operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // Always include validIndices, even if it's an empty array\r\n return rebuildStateShape(filteredArray as any, path, {\r\n filtered: [...(meta?.filtered || []), path],\r\n validIndices: validIndices, // Always pass validIndices, even if empty\r\n });\r\n };\r\n }\r\n }\r\n const lastPathElement = path[path.length - 1];\r\n if (!isNaN(Number(lastPathElement))) {\r\n const parentPath = path.slice(0, -1);\r\n const parentValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n\r\n if (Array.isArray(parentValue) && prop === \"cut\") {\r\n return () =>\r\n cutFunc(\r\n effectiveSetState,\r\n parentPath,\r\n stateKey,\r\n Number(lastPathElement)\r\n );\r\n }\r\n }\r\n\r\n if (prop === \"get\") {\r\n return () => getGlobalStore.getState().getNestedState(stateKey, path);\r\n }\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$get\") {\r\n return () =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n });\r\n }\r\n if (prop === \"lastSynced\") {\r\n const syncKey = `${stateKey}:${path.join(\".\")}`;\r\n return getGlobalStore.getState().getSyncInfo(syncKey);\r\n }\r\n\r\n if (prop == \"getLocalStorage\") {\r\n return (key: string) =>\r\n loadFromLocalStorage(sessionId + \"-\" + stateKey + \"-\" + key);\r\n }\r\n if (prop === \"_selected\") {\r\n const parentPath = path.slice(0, -1);\r\n const parentKey = parentPath.join(\".\");\r\n const parent = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n if (Array.isArray(parent)) {\r\n const currentIndex = Number(path[path.length - 1]);\r\n return (\r\n currentIndex ===\r\n getGlobalStore.getState().getSelectedIndex(stateKey, parentKey)\r\n );\r\n }\r\n return undefined;\r\n }\r\n if (prop === \"setSelected\") {\r\n return (value: boolean) => {\r\n const parentPath = path.slice(0, -1);\r\n const thisIndex = Number(path[path.length - 1]);\r\n const parentKey = parentPath.join(\".\");\r\n\r\n if (value) {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, thisIndex);\r\n } else {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, undefined);\r\n }\r\n\r\n const nested = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, [...parentPath]);\r\n updateFn(effectiveSetState, nested, parentPath);\r\n\r\n // Invalidate cache for this path\r\n invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (path.length == 0) {\r\n if (prop === \"validateZodSchema\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n const addValidationError =\r\n getGlobalStore.getState().addValidationError;\r\n\r\n if (!init?.zodSchema) {\r\n throw new Error(\"Zod schema not found\");\r\n }\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n removeValidationError(init.key);\r\n const thisObject =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n\r\n try {\r\n // First clear any existing validation errors for this schema\r\n // This ensures we don't have stale errors\r\n const existingErrors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key);\r\n if (existingErrors && existingErrors.length > 0) {\r\n existingErrors.forEach(([errorPath]) => {\r\n if (errorPath && errorPath.startsWith(init.key!)) {\r\n removeValidationError(errorPath);\r\n }\r\n });\r\n }\r\n\r\n // Attempt to validate with Zod\r\n const result = init.zodSchema.safeParse(thisObject);\r\n\r\n if (!result.success) {\r\n // Process Zod errors and add them to the validation store\r\n const zodErrors = result.error.errors;\r\n\r\n zodErrors.forEach((error) => {\r\n const errorPath = error.path;\r\n const errorMessage = error.message;\r\n\r\n // Build the full path for the validation error\r\n // Format: validationKey.path.to.field\r\n const fullErrorPath = [init.key, ...errorPath].join(\".\");\r\n\r\n // Add the error to the store\r\n addValidationError(fullErrorPath, errorMessage);\r\n });\r\n\r\n notifyComponents(stateKey);\r\n\r\n return false;\r\n }\r\n\r\n return true;\r\n } catch (error) {\r\n console.error(\"Zod schema validation failed\", error);\r\n return false;\r\n }\r\n };\r\n }\r\n if (prop === \"_componentId\") return componentId;\r\n if (prop === \"getComponents\") {\r\n return () => getGlobalStore().stateComponents.get(stateKey);\r\n }\r\n if (prop === \"getAllFormRefs\") {\r\n return () => {\r\n return formRefStore.getState().getFormRefsByStateKey(stateKey);\r\n };\r\n }\r\n\r\n if (prop === \"_initialState\")\r\n return getGlobalStore.getState().initialStateGlobal[stateKey];\r\n if (prop === \"_serverState\")\r\n return getGlobalStore.getState().serverState[stateKey];\r\n if (prop === \"_isLoading\")\r\n return getGlobalStore.getState().isLoadingGlobal[stateKey];\r\n if (prop === \"revertToInitialState\")\r\n return baseObj.revertToInitialState;\r\n if (prop === \"updateInitialState\") return baseObj.updateInitialState;\r\n if (prop === \"removeValidation\") return baseObj.removeValidation;\r\n }\r\n if (prop === \"getFormRef\") {\r\n return () => {\r\n return formRefStore\r\n .getState()\r\n .getFormRef(stateKey + \".\" + path.join(\".\"));\r\n };\r\n }\r\n\r\n if (prop === \"validationWrapper\") {\r\n return ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => (\r\n <ValidationWrapper\r\n formOpts={\r\n hideMessage ? { validation: { message: \"\" } } : undefined\r\n }\r\n path={path}\r\n validationKey={\r\n getGlobalStore.getState().getInitialOptions(stateKey)\r\n ?.validation?.key || \"\"\r\n }\r\n stateKey={stateKey}\r\n validIndices={meta?.validIndices}\r\n >\r\n {children}\r\n </ValidationWrapper>\r\n );\r\n }\r\n\r\n if (prop === \"_stateKey\") return stateKey;\r\n if (prop === \"_path\") return path;\r\n if (prop === \"_isServerSynced\") return baseObj._isServerSynced;\r\n\r\n if (prop === \"update\") {\r\n return (payload: UpdateArg<T>, opts?: UpdateOpts<T>) => {\r\n // ADDED: Invalidate cache on update\r\n if (opts?.debounce) {\r\n debounce(() => {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }, opts.debounce);\r\n } else {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }\r\n invalidateCachePath(path);\r\n };\r\n }\r\n\r\n if (prop === \"formElement\") {\r\n return (child: FormControl<T>, formOpts?: FormOptsType) => {\r\n return (\r\n <FormControlComponent<T>\r\n setState={effectiveSetState}\r\n stateKey={stateKey}\r\n path={path}\r\n child={child}\r\n formOpts={formOpts}\r\n />\r\n );\r\n };\r\n }\r\n\r\n const nextPath = [...path, prop];\r\n const nextValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, nextPath);\r\n return rebuildStateShape(nextValue, nextPath, meta);\r\n },\r\n };\r\n\r\n const proxyInstance = new Proxy(baseFunction, handler);\r\n\r\n shapeCache.set(cacheKey, {\r\n proxy: proxyInstance,\r\n stateVersion: stateVersion,\r\n });\r\n\r\n return proxyInstance;\r\n }\r\n\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, [])\r\n );\r\n}\r\n\r\nexport function $cogsSignal(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n}) {\r\n return createElement(SignalRenderer, { proxy });\r\n}\r\n\r\nfunction SignalMapRenderer({\r\n proxy,\r\n\r\n rebuildStateShape,\r\n}: {\r\n proxy: {\r\n _stateKey: string;\r\n _path: string[];\r\n _mapFn: (\r\n value: any,\r\n setter: any,\r\n index: number,\r\n array: any[],\r\n arraySetter: any\r\n ) => ReactNode;\r\n };\r\n\r\n rebuildStateShape: (\r\n currentState: any,\r\n path: string[],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ) => any;\r\n}) {\r\n const value = getGlobalStore().getNestedState(proxy._stateKey, proxy._path);\r\n\r\n if (!Array.isArray(value)) {\r\n return null;\r\n }\r\n const arraySetter = rebuildStateShape(\r\n value,\r\n proxy._path\r\n ) as ArrayEndType<any>;\r\n // Use existing global state management\r\n return arraySetter.stateMapNoRender(\r\n (item, setter, index, value, arraysetter) => {\r\n // Execute map function in React context with existing state/proxies\r\n return proxy._mapFn(item, setter, index, value, arraysetter);\r\n }\r\n );\r\n}\r\nfunction SignalRenderer({\r\n proxy,\r\n}: {\r\n proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n };\r\n}) {\r\n const elementRef = useRef<HTMLSpanElement>(null);\r\n const signalId = `${proxy._stateKey}-${proxy._path.join(\".\")}`;\r\n\r\n useEffect(() => {\r\n const element = elementRef.current;\r\n if (!element || !element.parentElement) return;\r\n\r\n const parentElement = element.parentElement;\r\n const childNodes = Array.from(parentElement.childNodes);\r\n const position = childNodes.indexOf(element);\r\n\r\n let parentId = parentElement.getAttribute(\"data-parent-id\");\r\n if (!parentId) {\r\n parentId = `parent-${crypto.randomUUID()}`;\r\n parentElement.setAttribute(\"data-parent-id\", parentId);\r\n }\r\n\r\n const instanceId = `instance-${crypto.randomUUID()}`;\r\n const elementInfo = {\r\n instanceId,\r\n parentId,\r\n position,\r\n effect: proxy._effect,\r\n };\r\n\r\n getGlobalStore.getState().addSignalElement(signalId, elementInfo);\r\n\r\n // Get the raw value from the store\r\n const value = getGlobalStore\r\n .getState()\r\n .getNestedState(proxy._stateKey, proxy._path);\r\n\r\n let displayValue;\r\n if (proxy._effect) {\r\n try {\r\n displayValue = new Function(\r\n \"state\",\r\n `return (${proxy._effect})(state)`\r\n )(value);\r\n } catch (err) {\r\n console.error(\"Error evaluating effect function during mount:\", err);\r\n displayValue = value; // Fallback to raw value\r\n }\r\n } else {\r\n displayValue = value;\r\n }\r\n\r\n if (displayValue !== null && typeof displayValue === \"object\") {\r\n displayValue = JSON.stringify(displayValue);\r\n }\r\n\r\n const textNode = document.createTextNode(String(displayValue));\r\n element.replaceWith(textNode);\r\n }, [proxy._stateKey, proxy._path.join(\".\"), proxy._effect]);\r\n\r\n return createElement(\"span\", {\r\n ref: elementRef,\r\n style: { display: \"none\" },\r\n \"data-signal-id\": signalId,\r\n });\r\n}\r\nexport function $cogsSignalStore(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n}) {\r\n const value = useSyncExternalStore(\r\n (notify) => {\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(proxy._stateKey) || {\r\n components: new Map(),\r\n };\r\n stateEntry.components.set(proxy._stateKey, {\r\n forceUpdate: notify,\r\n paths: new Set([proxy._path.join(\".\")]),\r\n });\r\n return () => stateEntry.components.delete(proxy._stateKey);\r\n },\r\n () => getGlobalStore.getState().getNestedState(proxy._stateKey, proxy._path)\r\n );\r\n return createElement(\"text\", {}, String(value));\r\n}\r\n"],"names":["setAndMergeOptions","stateKey","newOptions","getInitialOptions","getGlobalStore","setInitialStateOptions","initialOptions","setOptions","options","initialOptionsPart","initialOptionsPartState","mergedOptions","needToAdd","key","addStateOptions","initialState","formElements","validation","createCogsState","opt","newInitialState","statePart","transformStateFunc","useCogsState","componentId","useState","uuidv4","thiState","partialState","state","updater","useCogsStateFn","setCogsOptions","setUpdaterState","setState","getKeyState","getValidationErrors","setStateLog","updateInitialStateGlobal","addValidationError","removeValidationError","setServerSyncActions","loadFromLocalStorage","localStorageKey","storedData","error","saveToLocalStorage","thisKey","currentInitialOptions","sessionId","isFunction","data","storageKey","updateGlobalState","newState","effectiveSetState","updates","createProxyHandler","startTransition","notifyComponents","stateEntry","component","update","notifyComponent","fullComponentId","stateObject","serverSync","localStorage","middleware","reactiveDeps","reactiveType","syncUpdate","dependencies","reactiveForce","forceUpdate","useCogsConfig","noStateKey","stateLog","componentUpdatesRef","useRef","componentIdRef","latestInitialOptionsRef","useEffect","prevState","syncKey","localData","localkey","useLayoutEffect","depsKey","newStateOrFunction","path","updateObj","validationKey","pathKey","prevValue","payload","signalId","isArrayOperation","elements","arrayPath","arrayValue","getNestedValue","arraySignalId","newValue","parentId","position","effect","parent","childNodes","displayValue","arrayWithoutIndex","k","v","length","newKey","oldValue","pathToCheck","shouldUpdate","reactiveTypes","depsResult","isDeepEqual","newUpdate","prevLogs","aggregatedLogs","acc","log","uniqueKey","existing","serverStateStore","updaterFinal","useMemo","shapeCache","stateVersion","invalidateCachePath","baseObj","obj","init","newProxy","rebuildStateShape","initalOptionsGet","localKey","newUpdaterState","field","serverState","currentState","meta","cacheKey","baseFunction","handler","target","thisArg","args","prop","currentPath","thisReactiveState","initialStateAtPath","selectedIndex","compareFn","sortedArray","i","item","callbackfn","isFiltered","p","arrayToMap","val","index","thisIndex","elementProxy","createElement","SignalMapRenderer","fieldName","flattenedResults","thisValue","foundIndex","foundValue","newPath","indexValue","pushFunc","fields","onMatch","currentArray","matchedItem","isMatch","updatedItem","updatedArray","updateFn","cutFunc","value","newVal","validIndices","filteredArray","lastPathElement","parentPath","parentValue","fn","$cogsSignal","parentKey","nested","thisObject","existingErrors","errorPath","result","errorMessage","fullErrorPath","formRefStore","children","hideMessage","jsx","ValidationWrapper","opts","debounce","child","formOpts","FormControlComponent","nextPath","nextValue","proxyInstance","proxy","SignalRenderer","setter","arraysetter","elementRef","element","parentElement","elementInfo","err","textNode","$cogsSignalStore","useSyncExternalStore","notify"],"mappings":";;;;;;;;;AAuYA,SAASA,GAAmBC,GAAkBC,GAA8B;AACpEC,QAAAA,IAAoBC,EAAe,SAAA,EAAW,mBAC9CC,IACJD,EAAe,SAAA,EAAW,wBAEtBE,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC;AAEjE,EAAAI,EAAuBJ,GAAoB;AAAA,IACzC,GAAGK;AAAA,IACH,GAAGJ;AAAA,EAAA,CACJ;AACH;AAEA,SAASK,GAA0B;AAAA,EACjC,UAAAN;AAAA,EACA,SAAAO;AAAA,EACA,oBAAAC;AACF,GAIG;AACD,QAAMH,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC,GAC3DS,IAA0BD,EAAmBR,CAAkB,KAAK,CAAC,GACrEI,IACJD,EAAe,SAAA,EAAW,wBACtBO,IAAgB,EAAE,GAAGD,GAAyB,GAAGJ,EAAe;AAEtE,MAAIM,IAAY;AAChB,MAAIJ;AACF,eAAWK,KAAOL;AAChB,MAAKG,EAAc,eAAeE,CAAG,IAMjCA,KAAO,kBACPL,EAAQK,CAAG,KACXF,EAAcE,CAAG,EAAE,QAAQL,EAAQK,CAAG,GAAG,QAE7BD,IAAA,IACED,EAAAE,CAAG,IAAIL,EAAQK,CAA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AA+E;AAAA,MAAA;AAAA;AAGF,MAAA/E,IAAA+E;AAGjB,IAAI/E,MAAiB,QAAQ,OAAOA,KAAiB,aACpCA,IAAA,KAAK,UAAUA,CAAY;AAG5C,UAAMsH,IAAW,SAAS,eAAe,OAAOtH,CAAY,CAAC;AAC7D,IAAAkH,EAAQ,YAAYI,CAAQ;AAAA,EAAA,GAC3B,CAACT,EAAM,WAAWA,EAAM,MAAM,KAAK,GAAG,GAAGA,EAAM,OAAO,CAAC,GAEnDjD,EAAc,QAAQ;AAAA,IAC3B,KAAKqD;AAAA,IACL,OAAO,EAAE,SAAS,OAAO;AAAA,IACzB,kBAAkB9H;AAAA,EAAA,CACnB;AACH;AACO,SAASoI,GAAiBV,GAG9B;AACD,QAAM9B,IAAQyC;AAAA,IACZ,CAACC,MAAW;AACJ,YAAA1K,IAAaxD,EAChB,SAAS,EACT,gBAAgB,IAAIsN,EAAM,SAAS,KAAK;AAAA,QACzC,gCAAgB,IAAI;AAAA,MACtB;AACW,aAAA9J,EAAA,WAAW,IAAI8J,EAAM,WAAW;AAAA,QACzC,aAAaY;AAAA,QACb,2BAAW,IAAI,CAACZ,EAAM,MAAM,KAAK,GAAG,CAAC,CAAC;AAAA,MAAA,CACvC,GACM,MAAM9J,EAAW,WAAW,OAAO8J,EAAM,SAAS;AAAA,IAC3D;AAAA,IACA,MAAMtN,EAAe,WAAW,eAAesN,EAAM,WAAWA,EAAM,KAAK;AAAA,EAC7E;AACA,SAAOjD,EAAc,QAAQ,CAAI,GAAA,OAAOmB,CAAK,CAAC;AAChD;"}
1
+ {"version":3,"file":"CogsState.jsx","sources":["../src/CogsState.tsx"],"sourcesContent":["\"use client\";\r\nimport {\r\n createElement,\r\n startTransition,\r\n useEffect,\r\n useLayoutEffect,\r\n useMemo,\r\n useRef,\r\n useState,\r\n useSyncExternalStore,\r\n type ReactNode,\r\n} from \"react\";\r\n\r\nimport {\r\n debounce,\r\n getDifferences,\r\n getNestedValue,\r\n isFunction,\r\n type GenericObject,\r\n} from \"./utility.js\";\r\nimport {\r\n cutFunc,\r\n FormControlComponent,\r\n pushFunc,\r\n updateFn,\r\n ValidationWrapper,\r\n} from \"./Functions.js\";\r\nimport { isDeepEqual, transformStateFunc } from \"./utility.js\";\r\nimport type { UseMutationResult } from \"@tanstack/react-query\";\r\nimport { v4 as uuidv4 } from \"uuid\";\r\nimport { ZodArray, ZodObject, type ZodRawShape } from \"zod\";\r\n\r\nimport { formRefStore, getGlobalStore, type ComponentsType } from \"./store.js\";\r\nimport { useCogsConfig } from \"./CogsStateClient.js\";\r\n\r\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\r\n\r\nexport type ServerSyncStatus = {\r\n isFresh: boolean;\r\n isFreshTime: number;\r\n isStale: boolean;\r\n isStaleTime: number;\r\n isSyncing: boolean;\r\n isSyncingTime: number;\r\n};\r\n\r\nexport type SyncInfo = {\r\n timeStamp: number;\r\n userId: number;\r\n};\r\n\r\nexport type FormElementParams<T> = {\r\n get: () => T;\r\n\r\n set: UpdateType<T>;\r\n syncStatus: (SyncInfo & { date: Date }) | null;\r\n path: string[];\r\n validationErrors: () => string[];\r\n addValidationError: (message?: string) => void;\r\n\r\n inputProps: {\r\n ref?: React.RefObject<any>;\r\n value?: T extends boolean ? never : T;\r\n onChange?: (\r\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\r\n ) => void;\r\n onBlur?: () => void;\r\n };\r\n};\r\n\r\nexport type StateKeys = string;\r\n\r\ntype findWithFuncType<U> = (\r\n thisKey: keyof U,\r\n thisValue: U[keyof U]\r\n) => EndType<U> & StateObject<U>;\r\nexport type PushArgs<U> = (\r\n update:\r\n | Prettify<U>\r\n | ((prevState: NonNullable<Prettify<U>>[]) => NonNullable<Prettify<U>>),\r\n opts?: UpdateOpts<U>\r\n) => void;\r\n\r\ntype CutFunctionType = (\r\n index?: number,\r\n options?: { waitForSync?: boolean }\r\n) => void;\r\n\r\nexport type InferArrayElement<T> = T extends (infer U)[] ? U : never;\r\n\r\nexport type ArrayEndType<TShape extends unknown> = {\r\n findWith: findWithFuncType<InferArrayElement<TShape>>;\r\n index: (index: number) => StateObject<InferArrayElement<TShape>> & {\r\n insert: PushArgs<InferArrayElement<TShape>>;\r\n cut: CutFunctionType;\r\n _index: number;\r\n } & EndType<InferArrayElement<TShape>>;\r\n insert: PushArgs<InferArrayElement<TShape>>;\r\n cut: CutFunctionType;\r\n cutByValue: (value: string | number | boolean) => void;\r\n toggleByValue: (value: string | number | boolean) => void;\r\n stateSort: (\r\n compareFn: (\r\n a: InferArrayElement<TShape>,\r\n b: InferArrayElement<TShape>\r\n ) => number\r\n ) => ArrayEndType<TShape>;\r\n\r\n stateMapNoRender: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n $stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateFlattenOn: <K extends keyof InferArrayElement<TShape>>(\r\n field: K\r\n ) => StateObject<InferArrayElement<InferArrayElement<TShape>[K]>[]>;\r\n uniqueInsert: (\r\n payload: UpdateArg<InferArrayElement<TShape>>,\r\n fields?: (keyof InferArrayElement<TShape>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => void;\r\n stateFilter: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => void\r\n ) => ArrayEndType<TShape>;\r\n getSelected: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n getSelectedIndex: () => number | undefined;\r\n} & EndType<TShape> & {\r\n [K in keyof (any[] extends infer T ? T : never)]: never;\r\n };\r\n\r\nexport type UpdateType<T> = (\r\n payload: UpdateArg<Prettify<T>>,\r\n opts?: UpdateOpts<T>\r\n) => void;\r\nexport type FormOptsType = {\r\n key?: string;\r\n validation?: {\r\n hideMessage?: boolean;\r\n message?: string;\r\n stretch?: boolean;\r\n props?: GenericObject;\r\n disable?: boolean;\r\n };\r\n formElements?: boolean;\r\n debounceTime?: number;\r\n stateServerDifferences?: string[][];\r\n};\r\n\r\nexport type FormControl<T> = (obj: FormElementParams<T>) => JSX.Element;\r\n\r\nexport type UpdateArg<S> = S | ((prevState: S) => S);\r\nexport type UpdateOpts<T> = {\r\n afterUpdate?: (state: T) => void;\r\n debounce?: number;\r\n};\r\nexport type ObjectEndType<T> = EndType<T> & {\r\n [K in keyof T]-?: ObjectEndType<T[K]>;\r\n} & {\r\n stateObject: (callbackfn: (value: T, setter: StateObject<T>) => void) => any;\r\n delete: () => void;\r\n};\r\ntype EffectFunction<T, R> = (state: T) => R;\r\nexport type EndType<T, IsArrayElement = false> = {\r\n update: UpdateType<T>;\r\n _path: string[];\r\n _stateKey: string;\r\n formElement: (control: FormControl<T>, opts?: FormOptsType) => JSX.Element;\r\n get: () => T;\r\n $get: () => T;\r\n $derive: <R>(fn: EffectFunction<T, R>) => R;\r\n _status: \"fresh\" | \"stale\" | \"synced\";\r\n getStatus: () => \"fresh\" | \"stale\";\r\n showValidationErrors: () => string[];\r\n setValidation: (ctx: string) => void;\r\n removeValidation: (ctx: string) => void;\r\n ignoreFields: (fields: string[]) => StateObject<T>;\r\n _selected: boolean;\r\n setSelected: (value: boolean) => void;\r\n getFormRef: () => React.RefObject<any> | undefined;\r\n removeStorage: () => void;\r\n validationWrapper: ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => JSX.Element;\r\n lastSynced?: SyncInfo;\r\n} & (IsArrayElement extends true ? { cut: () => void } : {}) & {\r\n [K in keyof (any extends infer T ? T : never)]: never;\r\n };\r\n\r\nexport type StateObject<T> = (T extends any[]\r\n ? ArrayEndType<T>\r\n : T extends Record<string, unknown> | object\r\n ? { [K in keyof T]-?: StateObject<T[K]> } & ObjectEndType<T>\r\n : T extends string | number | boolean | null\r\n ? T\r\n : never) &\r\n EndType<T, true> & {\r\n getAllFormRefs: () => Map<string, React.RefObject<any>>;\r\n _componentId: string | null;\r\n getComponents: () => ComponentsType;\r\n validateZodSchema: () => void;\r\n _initialState: T;\r\n updateInitialState: (newState: T | null) => {\r\n fetchId: (field: keyof T) => string | number;\r\n };\r\n _isLoading: boolean;\r\n _serverState: T;\r\n revertToInitialState: (obj?: { validationKey?: string }) => T;\r\n middleware: (\r\n middles: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void\r\n ) => void;\r\n _isServerSynced: () => boolean;\r\n getLocalStorage: (key: string) => LocalStorageData<T> | null;\r\n };\r\n\r\nexport type CogsUpdate<T extends unknown> = UpdateType<T>;\r\n\r\nexport type EffectiveSetState<TStateObject> = (\r\n newStateOrFunction:\r\n | TStateObject\r\n | ((prevState: TStateObject) => TStateObject),\r\n path: string[],\r\n updateObj: { updateType: \"update\" | \"insert\" | \"cut\" },\r\n validationKey?: string,\r\n opts?: UpdateOpts<TStateObject>\r\n) => void;\r\n\r\nexport type UpdateTypeDetail = {\r\n timeStamp: number;\r\n stateKey: string;\r\n updateType: \"update\" | \"insert\" | \"cut\";\r\n path: string[];\r\n status: \"new\" | \"sent\" | \"synced\";\r\n oldValue: any;\r\n newValue: any;\r\n userId?: number;\r\n};\r\n\r\nexport type ActionsType<T> = {\r\n type: \"onChange\";\r\n action: ({ state, actionType }: { state: T; actionType: string }) => void;\r\n debounce?: number;\r\n}[];\r\n\r\ntype ArrayToObject<T extends string[]> = Record<T[number], string>;\r\ntype CookieType<T> = {\r\n timeStamp: number;\r\n value: T;\r\n cookieName: string;\r\n OnUnMountCookie?: Boolean;\r\n};\r\nexport type CogsCookiesType<T extends string[] = string[]> = CookieType<\r\n ArrayToObject<T>\r\n>;\r\nexport type ReactivityType = \"none\" | \"component\" | \"deps\" | \"all\";\r\n\r\ntype ValidationOptionsType = {\r\n key?: string;\r\n zodSchema?: ZodObject<ZodRawShape> | ZodArray<ZodObject<ZodRawShape>>;\r\n onBlur?: boolean;\r\n};\r\n\r\nexport type OptionsType<T extends unknown = unknown> = {\r\n log?: boolean;\r\n componentId?: string;\r\n serverSync?: ServerSyncType<T>;\r\n validation?: ValidationOptionsType;\r\n enableServerState?: boolean;\r\n middleware?: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void;\r\n\r\n modifyState?: (state: T) => T;\r\n localStorage?: { key: string | ((state: T) => string) };\r\n formElements?: FormsElementsType;\r\n enabledSync?: (state: T) => boolean;\r\n reactiveDeps?: (state: T) => any[] | true;\r\n reactiveType?: ReactivityType[] | ReactivityType;\r\n syncUpdate?: Partial<UpdateTypeDetail>;\r\n\r\n initialState?: T;\r\n dependencies?: any[]; // Just like useEffect dependencies\r\n};\r\nexport type ServerSyncType<T> = {\r\n testKey?: string;\r\n syncKey: (({ state }: { state: T }) => string) | string;\r\n syncFunction: ({ state }: { state: T }) => void;\r\n debounce?: number;\r\n mutation: UseMutationResult<any, unknown, any, unknown>;\r\n snapshot?: {\r\n name: (({ state }: { state: T }) => string) | string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\nexport type SyncActionsType<T> = {\r\n syncKey: string;\r\n\r\n rollBackState?: T;\r\n actionTimeStamp: number;\r\n retryCount?: number;\r\n status:\r\n | \"success\"\r\n | \"waiting\"\r\n | \"rolledBack\"\r\n | \"error\"\r\n | \"cancelled\"\r\n | \"failed\";\r\n snapshot?: {\r\n name: string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\n\r\nexport type ValidationWrapperOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n active: boolean;\r\n stretch?: boolean;\r\n path: string[];\r\n message?: string;\r\n data?: T;\r\n key?: string;\r\n};\r\nexport type SyncRenderOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n time: number;\r\n data?: T;\r\n key?: string;\r\n};\r\n\r\ntype FormsElementsType<T extends unknown = unknown> = {\r\n validation?: (options: ValidationWrapperOptions<T>) => React.ReactNode;\r\n syncRender?: (options: SyncRenderOptions<T>) => React.ReactNode;\r\n};\r\n\r\nexport type InitialStateInnerType<T extends unknown = unknown> = {\r\n initialState: T;\r\n} & OptionsType<T>;\r\n\r\nexport type InitialStateType<T> = {\r\n [key: string]: InitialStateInnerType<T>;\r\n};\r\n\r\nexport type AllStateTypes<T extends unknown> = Record<string, T>;\r\n\r\nexport type CogsInitialState<T> = {\r\n initialState: T;\r\n formElements?: FormsElementsType<T>;\r\n};\r\n\r\nexport type TransformedStateType<T> = {\r\n [P in keyof T]: T[P] extends CogsInitialState<infer U> ? U : T[P];\r\n};\r\n\r\nfunction setAndMergeOptions(stateKey: string, newOptions: OptionsType<any>) {\r\n const getInitialOptions = getGlobalStore.getState().getInitialOptions;\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n\r\n setInitialStateOptions(stateKey as string, {\r\n ...initialOptions,\r\n ...newOptions,\r\n });\r\n}\r\n\r\nfunction setOptions<StateKey, Opt>({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n}: {\r\n stateKey: StateKey;\r\n options?: OptionsType<any>;\r\n initialOptionsPart: Record<string, any>;\r\n}) {\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n const initialOptionsPartState = initialOptionsPart[stateKey as string] || {};\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n const mergedOptions = { ...initialOptionsPartState, ...initialOptions };\r\n\r\n let needToAdd = false;\r\n if (options) {\r\n for (const key in options) {\r\n if (!mergedOptions.hasOwnProperty(key)) {\r\n needToAdd = true;\r\n\r\n mergedOptions[key] = options[key as keyof typeof options];\r\n } else {\r\n if (\r\n key == \"localStorage\" &&\r\n options[key] &&\r\n mergedOptions[key].key !== options[key]?.key\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n }\r\n }\r\n }\r\n if (needToAdd) {\r\n setInitialStateOptions(stateKey as string, mergedOptions);\r\n }\r\n}\r\nexport function addStateOptions<T extends unknown>(\r\n initialState: T,\r\n { formElements, validation }: OptionsType<T>\r\n) {\r\n return { initialState: initialState, formElements, validation } as T;\r\n}\r\n\r\nexport const createCogsState = <State extends Record<string, unknown>>(\r\n initialState: State,\r\n opt?: { formElements?: FormsElementsType; validation?: ValidationOptionsType }\r\n) => {\r\n let newInitialState = initialState;\r\n\r\n // Extract state parts and options using transformStateFunc\r\n const [statePart, initialOptionsPart] =\r\n transformStateFunc<State>(newInitialState);\r\n\r\n // Apply global formElements as defaults to each state key's options\r\n if (opt?.formElements || opt?.validation) {\r\n Object.keys(initialOptionsPart).forEach((key) => {\r\n // Get the existing options for this state key\r\n initialOptionsPart[key] = initialOptionsPart[key] || {};\r\n\r\n initialOptionsPart[key].formElements = {\r\n ...opt.formElements, // Global defaults first\r\n ...opt?.validation,\r\n ...(initialOptionsPart[key].formElements || {}), // State-specific overrides\r\n };\r\n });\r\n }\r\n\r\n getGlobalStore.getState().setInitialStates(statePart);\r\n type StateKeys = keyof typeof statePart;\r\n\r\n const useCogsState = <StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options?: OptionsType<(typeof statePart)[StateKey]>\r\n ) => {\r\n const [componentId] = useState(options?.componentId ?? uuidv4());\r\n setOptions({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n });\r\n\r\n const thiState =\r\n getGlobalStore.getState().cogsStateStore[stateKey as string] ||\r\n statePart[stateKey as string];\r\n const partialState = options?.modifyState\r\n ? options.modifyState(thiState)\r\n : thiState;\r\n\r\n const [state, updater] = useCogsStateFn<(typeof statePart)[StateKey]>(\r\n partialState,\r\n {\r\n stateKey: stateKey as string,\r\n syncUpdate: options?.syncUpdate,\r\n componentId,\r\n localStorage: options?.localStorage,\r\n middleware: options?.middleware,\r\n enabledSync: options?.enabledSync,\r\n reactiveType: options?.reactiveType,\r\n reactiveDeps: options?.reactiveDeps,\r\n initialState: options?.initialState,\r\n dependencies: options?.dependencies,\r\n }\r\n );\r\n\r\n return updater;\r\n };\r\n\r\n function setCogsOptions<StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options: OptionsType<(typeof statePart)[StateKey]>\r\n ) {\r\n setOptions({ stateKey, options, initialOptionsPart });\r\n }\r\n\r\n return { useCogsState, setCogsOptions };\r\n};\r\n\r\nconst {\r\n setUpdaterState,\r\n setState,\r\n getInitialOptions,\r\n getKeyState,\r\n getValidationErrors,\r\n setStateLog,\r\n updateInitialStateGlobal,\r\n addValidationError,\r\n removeValidationError,\r\n setServerSyncActions,\r\n} = getGlobalStore.getState();\r\n\r\nconst loadFromLocalStorage = (localStorageKey: string) => {\r\n if (!localStorageKey) return null;\r\n\r\n try {\r\n const storedData = window.localStorage.getItem(localStorageKey);\r\n if (!storedData) return null;\r\n\r\n const parsedData = JSON.parse(storedData);\r\n\r\n return parsedData;\r\n } catch (error) {\r\n console.error(\"Error loading from localStorage:\", error);\r\n return null;\r\n }\r\n};\r\n\r\nconst saveToLocalStorage = <T,>(\r\n state: T,\r\n thisKey: string,\r\n currentInitialOptions: any,\r\n sessionId?: string\r\n) => {\r\n if (currentInitialOptions.log) {\r\n console.log(\r\n \"saving to localstorage\",\r\n thisKey,\r\n currentInitialOptions.localStorage?.key,\r\n sessionId\r\n );\r\n }\r\n const key = isFunction(currentInitialOptions.localStorage?.key)\r\n ? currentInitialOptions.localStorage?.key(state)\r\n : currentInitialOptions.localStorage?.key;\r\n if (key && sessionId) {\r\n const data: LocalStorageData<T> = {\r\n state,\r\n lastUpdated: Date.now(),\r\n lastSyncedWithServer:\r\n getGlobalStore.getState().serverSyncLog[thisKey]?.[0]?.timeStamp,\r\n baseServerState: getGlobalStore.getState().serverState[thisKey],\r\n };\r\n\r\n const storageKey = `${sessionId}-${thisKey}-${key}`;\r\n\r\n window.localStorage.setItem(storageKey, JSON.stringify(data));\r\n }\r\n};\r\n\r\ntype LocalStorageData<T> = {\r\n state: T;\r\n lastUpdated: number;\r\n lastSyncedWithServer?: number;\r\n baseServerState?: T; // Add this to track what server state our changes are based on\r\n};\r\n\r\nconst updateGlobalState = (\r\n thisKey: string,\r\n initialState: any,\r\n newState: any,\r\n effectiveSetState: EffectiveSetState<any>,\r\n componentId: string,\r\n sessionId?: string\r\n) => {\r\n // Update all global state at once\r\n const updates = {\r\n initialState: initialState,\r\n updaterState: createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n ),\r\n state: newState,\r\n };\r\n\r\n startTransition(() => {\r\n updateInitialStateGlobal(thisKey, updates.initialState);\r\n setUpdaterState(thisKey, updates.updaterState);\r\n setState(thisKey, updates.state);\r\n });\r\n};\r\n\r\nconst notifyComponents = (thisKey: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n if (!stateEntry) return;\r\n\r\n // Batch component updates\r\n const updates = new Set<() => void>();\r\n stateEntry.components.forEach((component) => {\r\n updates.add(() => component.forceUpdate());\r\n });\r\n\r\n // Schedule updates in the next tick to allow batching\r\n queueMicrotask(() => {\r\n startTransition(() => {\r\n updates.forEach((update) => update());\r\n });\r\n });\r\n};\r\n\r\nexport const notifyComponent = (stateKey: string, componentId: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // Force an update to ensure the current value is saved\r\n\r\n component.forceUpdate();\r\n }\r\n }\r\n};\r\n\r\nexport function useCogsStateFn<TStateObject extends unknown>(\r\n stateObject: TStateObject,\r\n {\r\n stateKey,\r\n serverSync,\r\n localStorage,\r\n formElements,\r\n middleware,\r\n reactiveDeps,\r\n reactiveType,\r\n componentId,\r\n initialState,\r\n syncUpdate,\r\n dependencies,\r\n }: {\r\n stateKey?: string;\r\n componentId?: string;\r\n } & OptionsType<TStateObject> = {}\r\n) {\r\n const [reactiveForce, forceUpdate] = useState({}); //this is the key to reactivity\r\n const { sessionId } = useCogsConfig();\r\n\r\n let noStateKey = stateKey ? false : true;\r\n const [thisKey] = useState(stateKey ?? uuidv4());\r\n const stateLog = getGlobalStore.getState().stateLog[thisKey];\r\n const componentUpdatesRef = useRef(new Set<string>());\r\n const componentIdRef = useRef(componentId ?? uuidv4());\r\n const latestInitialOptionsRef = useRef<any>(null);\r\n latestInitialOptionsRef.current = getInitialOptions(thisKey as string);\r\n\r\n useEffect(() => {\r\n if (syncUpdate && syncUpdate.stateKey === thisKey && syncUpdate.path?.[0]) {\r\n // Update the actual state value\r\n setState(thisKey, (prevState: any) => ({\r\n ...prevState,\r\n [syncUpdate.path![0]!]: syncUpdate.newValue,\r\n }));\r\n\r\n // Create combined key and update sync info\r\n const syncKey = `${syncUpdate.stateKey}:${syncUpdate.path.join(\".\")}`;\r\n getGlobalStore.getState().setSyncInfo(syncKey, {\r\n timeStamp: syncUpdate.timeStamp!,\r\n userId: syncUpdate.userId!,\r\n });\r\n }\r\n }, [syncUpdate]);\r\n\r\n useEffect(() => {\r\n setAndMergeOptions(thisKey as string, {\r\n initialState,\r\n });\r\n const options = latestInitialOptionsRef.current;\r\n let localData = null;\r\n if (options.log) {\r\n console.log(\"newoptions\", options);\r\n }\r\n const localkey = isFunction(options.localStorage?.key)\r\n ? options.localStorage?.key(initialState)\r\n : options.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n localData = loadFromLocalStorage(\r\n sessionId + \"-\" + thisKey + \"-\" + localkey\r\n );\r\n }\r\n\r\n let newState = null;\r\n if (initialState) {\r\n newState = initialState;\r\n\r\n if (localData) {\r\n if (localData.lastUpdated > (localData.lastSyncedWithServer || 0)) {\r\n newState = localData.state;\r\n }\r\n }\r\n updateGlobalState(\r\n thisKey,\r\n initialState,\r\n newState,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n\r\n notifyComponents(thisKey);\r\n forceUpdate({});\r\n }\r\n }, [initialState, ...(dependencies || [])]);\r\n\r\n useLayoutEffect(() => {\r\n if (noStateKey) {\r\n setAndMergeOptions(thisKey as string, {\r\n serverSync,\r\n formElements,\r\n initialState,\r\n localStorage,\r\n middleware,\r\n });\r\n }\r\n\r\n const depsKey = `${thisKey}////${componentIdRef.current}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(thisKey) || {\r\n components: new Map(),\r\n };\r\n\r\n stateEntry.components.set(depsKey, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set(),\r\n deps: [],\r\n depsFunction: reactiveDeps || undefined,\r\n reactiveType: reactiveType ?? [\"component\", \"deps\"],\r\n });\r\n\r\n getGlobalStore.getState().stateComponents.set(thisKey, stateEntry);\r\n //need to force update to create the stateUpdates references\r\n forceUpdate({});\r\n return () => {\r\n const depsKey = `${thisKey}////${componentIdRef.current}`;\r\n\r\n if (stateEntry) {\r\n stateEntry.components.delete(depsKey);\r\n if (stateEntry.components.size === 0) {\r\n getGlobalStore.getState().stateComponents.delete(thisKey);\r\n }\r\n }\r\n };\r\n }, []);\r\n\r\n const effectiveSetState = (\r\n newStateOrFunction:\r\n | TStateObject\r\n | ((prevState: TStateObject) => TStateObject),\r\n path: string[],\r\n updateObj: { updateType: \"insert\" | \"cut\" | \"update\" },\r\n validationKey?: string\r\n ) => {\r\n if (Array.isArray(path)) {\r\n const pathKey = `${thisKey}-${path.join(\".\")}`;\r\n componentUpdatesRef.current.add(pathKey);\r\n }\r\n setState(thisKey, (prevValue: TStateObject) => {\r\n const payload = isFunction<TStateObject>(newStateOrFunction)\r\n ? newStateOrFunction(prevValue as TStateObject)\r\n : newStateOrFunction;\r\n\r\n const signalId = `${thisKey}-${path.join(\".\")}`;\r\n if (signalId) {\r\n let isArrayOperation = false;\r\n let elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(signalId);\r\n\r\n if (\r\n (!elements || elements.size === 0) &&\r\n (updateObj.updateType === \"insert\" || updateObj.updateType === \"cut\")\r\n ) {\r\n // Remove last segment (index) from path\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n // If it's an array, use that path for signal\r\n if (Array.isArray(arrayValue)) {\r\n isArrayOperation = true;\r\n const arraySignalId = `${thisKey}-${arrayPath.join(\".\")}`;\r\n elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(arraySignalId);\r\n }\r\n }\r\n\r\n if (elements) {\r\n const newValue = isArrayOperation\r\n ? getNestedValue(payload, path.slice(0, -1))\r\n : getNestedValue(payload, path);\r\n elements.forEach(({ parentId, position, effect }) => {\r\n const parent = document.querySelector(\r\n `[data-parent-id=\"${parentId}\"]`\r\n );\r\n if (parent) {\r\n const childNodes = Array.from(parent.childNodes);\r\n if (childNodes[position]) {\r\n const displayValue = effect\r\n ? new Function(\"state\", `return (${effect})(state)`)(newValue)\r\n : newValue;\r\n childNodes[position].textContent = String(displayValue);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n if (\r\n updateObj.updateType === \"update\" &&\r\n (validationKey || latestInitialOptionsRef.current?.validationKey) &&\r\n path\r\n ) {\r\n removeValidationError(\r\n (validationKey || latestInitialOptionsRef.current?.validationKey) +\r\n \".\" +\r\n path.join(\".\")\r\n );\r\n }\r\n const arrayWithoutIndex = path.slice(0, path.length - 1);\r\n if (\r\n updateObj.updateType === \"cut\" &&\r\n latestInitialOptionsRef.current?.validationKey\r\n ) {\r\n removeValidationError(\r\n latestInitialOptionsRef.current?.validationKey +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n }\r\n if (\r\n updateObj.updateType === \"insert\" &&\r\n latestInitialOptionsRef.current?.validationKey\r\n ) {\r\n let getValidation = getValidationErrors(\r\n latestInitialOptionsRef.current?.validationKey +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n\r\n //TODO this is untested its supposed to cahnge teh validation errors alreaady stored when a new entry is push\r\n\r\n getValidation.filter(([k, v]) => {\r\n let length = k?.split(\".\").length;\r\n\r\n if (\r\n k == arrayWithoutIndex.join(\".\") &&\r\n length == arrayWithoutIndex.length - 1\r\n ) {\r\n // console.log(length, pathWithoutIndex.length);\r\n let newKey = k + \".\" + arrayWithoutIndex;\r\n removeValidationError(k!);\r\n addValidationError(newKey, v!);\r\n }\r\n });\r\n }\r\n\r\n const oldValue = getNestedValue(prevValue, path);\r\n const newValue = getNestedValue(payload, path);\r\n const pathToCheck =\r\n updateObj.updateType === \"update\"\r\n ? path.join(\".\")\r\n : [...path].slice(0, -1).join(\".\");\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n\r\n if (stateEntry) {\r\n for (const [key, component] of stateEntry.components.entries()) {\r\n let shouldUpdate = false;\r\n const reactiveTypes = Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"];\r\n\r\n // Skip if reactivity is disabled\r\n if (reactiveTypes.includes(\"none\")) {\r\n continue;\r\n }\r\n\r\n // Force update if \"all\" is specified\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n\r\n continue;\r\n }\r\n\r\n // Check component-level path reactivity\r\n if (reactiveTypes.includes(\"component\")) {\r\n if (\r\n component.paths &&\r\n (component.paths.has(pathToCheck) || component.paths.has(\"\"))\r\n ) {\r\n shouldUpdate = true;\r\n }\r\n }\r\n\r\n // Check dependency-based reactivity\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(payload);\r\n\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) {\r\n shouldUpdate = true;\r\n }\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n shouldUpdate = true;\r\n }\r\n }\r\n }\r\n\r\n if (shouldUpdate) {\r\n component.forceUpdate();\r\n }\r\n }\r\n }\r\n const timeStamp = Date.now();\r\n\r\n const newUpdate = {\r\n timeStamp,\r\n stateKey: thisKey,\r\n path,\r\n updateType: updateObj.updateType,\r\n status: \"new\" as const,\r\n oldValue,\r\n newValue,\r\n } satisfies UpdateTypeDetail;\r\n\r\n setStateLog(thisKey, (prevLogs) => {\r\n const logs = [...(prevLogs ?? []), newUpdate];\r\n\r\n // Aggregate the updates by stateKey and path\r\n const aggregatedLogs = logs.reduce((acc, log) => {\r\n const uniqueKey = `${log.stateKey}:${JSON.stringify(log.path)}`;\r\n const existing = acc.get(uniqueKey);\r\n\r\n if (existing) {\r\n // Update the existing entry with the most recent details\r\n existing.timeStamp = Math.max(existing.timeStamp, log.timeStamp);\r\n existing.newValue = log.newValue; // Overwrite with the latest value\r\n existing.oldValue = existing.oldValue ?? log.oldValue; // Retain the initial oldValue\r\n existing.updateType = log.updateType; // Update to the most recent type\r\n } else {\r\n // Add the log if no existing match is found\r\n acc.set(uniqueKey, { ...(log as any) });\r\n }\r\n\r\n return acc;\r\n }, new Map<string, typeof newUpdate>());\r\n\r\n // Convert the aggregated map back to an array\r\n return Array.from(aggregatedLogs.values());\r\n });\r\n\r\n saveToLocalStorage(\r\n payload,\r\n thisKey,\r\n latestInitialOptionsRef.current,\r\n sessionId\r\n );\r\n\r\n if (middleware) {\r\n middleware({\r\n updateLog: stateLog,\r\n update: newUpdate,\r\n });\r\n }\r\n if (latestInitialOptionsRef.current?.serverSync) {\r\n const serverStateStore = getGlobalStore.getState().serverState[thisKey];\r\n const serverSync = latestInitialOptionsRef.current?.serverSync;\r\n setServerSyncActions(thisKey, {\r\n syncKey:\r\n typeof serverSync.syncKey == \"string\"\r\n ? serverSync.syncKey\r\n : serverSync.syncKey({ state: payload }),\r\n rollBackState: serverStateStore,\r\n actionTimeStamp: Date.now() + (serverSync.debounce ?? 3000),\r\n status: \"waiting\",\r\n });\r\n }\r\n\r\n return payload;\r\n });\r\n };\r\n if (!getGlobalStore.getState().updaterState[thisKey]) {\r\n setUpdaterState(\r\n thisKey,\r\n createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n )\r\n );\r\n if (!getGlobalStore.getState().cogsStateStore[thisKey]) {\r\n setState(thisKey, stateObject);\r\n }\r\n if (!getGlobalStore.getState().initialStateGlobal[thisKey]) {\r\n updateInitialStateGlobal(thisKey, stateObject);\r\n }\r\n }\r\n\r\n const updaterFinal = useMemo(() => {\r\n // Create proxy with baseObject as target\r\n return createProxyHandler<TStateObject>(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n }, [thisKey]);\r\n\r\n return [getKeyState(thisKey), updaterFinal] as [\r\n TStateObject,\r\n StateObject<TStateObject>,\r\n ];\r\n}\r\n\r\nfunction createProxyHandler<T>(\r\n stateKey: string,\r\n effectiveSetState: EffectiveSetState<T>,\r\n componentId: string,\r\n sessionId?: string\r\n): StateObject<T> {\r\n // ADDED: Enhanced cache with versioning\r\n type CacheEntry = {\r\n proxy: any;\r\n stateVersion: number;\r\n };\r\n const shapeCache = new Map<string, CacheEntry>();\r\n let stateVersion = 0;\r\n\r\n // ADDED: Cache invalidation helper\r\n const invalidateCachePath = (path: string[]) => {\r\n const pathKey = path.join(\".\");\r\n for (const [key] of shapeCache) {\r\n if (key === pathKey || key.startsWith(pathKey + \".\")) {\r\n shapeCache.delete(key);\r\n }\r\n }\r\n stateVersion++;\r\n };\r\n\r\n const baseObj = {\r\n removeValidation: (obj?: { validationKey?: string }) => {\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n },\r\n\r\n revertToInitialState: (obj?: { validationKey?: string }) => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n if (init?.key) {\r\n removeValidationError(init?.key);\r\n }\r\n\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n\r\n // ADDED: Clear cache on revert\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newProxy = rebuildStateShape(initialState, []);\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n startTransition(() => {\r\n setUpdaterState(stateKey, newProxy);\r\n setState(stateKey, initialState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return initialState;\r\n },\r\n updateInitialState: (newState: T) => {\r\n // ADDED: Clear cache on initial state update\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newUpdaterState = createProxyHandler(\r\n stateKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n startTransition(() => {\r\n updateInitialStateGlobal(stateKey, newState);\r\n setUpdaterState(stateKey, newUpdaterState);\r\n setState(stateKey, newState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return {\r\n fetchId: (field: keyof T) => newUpdaterState.get()[field],\r\n };\r\n },\r\n _initialState: getGlobalStore.getState().initialStateGlobal[stateKey],\r\n _serverState: getGlobalStore.getState().serverState[stateKey],\r\n _isLoading: getGlobalStore.getState().isLoadingGlobal[stateKey],\r\n _isServerSynced: () => {\r\n const serverState = getGlobalStore.getState().serverState[stateKey];\r\n return Boolean(\r\n serverState && isDeepEqual(serverState, getKeyState(stateKey))\r\n );\r\n },\r\n };\r\n\r\n function rebuildStateShape(\r\n currentState: T,\r\n path: string[] = [],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ): any {\r\n const cacheKey = path.map(String).join(\".\");\r\n\r\n // MODIFIED: Cache check with version\r\n const cachedEntry = shapeCache.get(cacheKey);\r\n // if (cachedEntry?.stateVersion === stateVersion) {\r\n // return cachedEntry.proxy;\r\n // }\r\n type CallableStateObject<T> = {\r\n (): T;\r\n } & {\r\n [key: string]: any;\r\n };\r\n\r\n const baseFunction = function () {\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n } as unknown as CallableStateObject<T>;\r\n\r\n // Copy properties from baseObj to the function with type assertion\r\n Object.keys(baseObj).forEach((key) => {\r\n (baseFunction as any)[key] = (baseObj as any)[key];\r\n });\r\n\r\n const handler = {\r\n apply(target: any, thisArg: any, args: any[]) {\r\n console.log(\r\n `PROXY APPLY TRAP HIT: stateKey=${stateKey}, path=${path.join(\".\")}`\r\n ); // <--- ADD LOGGING\r\n console.trace(\"Apply trap stack trace\");\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n },\r\n\r\n get(target: any, prop: string) {\r\n if (\r\n prop !== \"then\" &&\r\n !prop.startsWith(\"$\") &&\r\n prop !== \"stateMapNoRender\"\r\n ) {\r\n const currentPath = path.join(\".\");\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n\r\n if (stateEntry) {\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // Only add paths for non-root or specifically for get() at root\r\n if (path.length > 0 || prop === \"get\") {\r\n component.paths.add(currentPath);\r\n }\r\n } else {\r\n }\r\n }\r\n }\r\n if (prop === \"_status\") {\r\n // Get current state at this path (non-reactive version)\r\n const thisReactiveState = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n }\r\n if (prop === \"getStatus\") {\r\n return function () {\r\n // Get current state at this path (reactive version)\r\n const thisReactiveState = getGlobalStore().getNestedState(\r\n stateKey,\r\n path\r\n );\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n };\r\n }\r\n if (prop === \"removeStorage\") {\r\n return () => {\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n console.log(\"removing storage\", storageKey);\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n };\r\n }\r\n if (prop === \"showValidationErrors\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n const errors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key + \".\" + path.join(\".\"));\r\n\r\n return errors;\r\n };\r\n }\r\n if (Array.isArray(currentState)) {\r\n if (prop === \"getSelected\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n if (selectedIndex === undefined) return undefined;\r\n return rebuildStateShape(\r\n currentState[selectedIndex],\r\n [...path, selectedIndex.toString()],\r\n meta\r\n );\r\n };\r\n }\r\n if (prop === \"getSelectedIndex\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n if (selectedIndex === undefined) return undefined;\r\n return selectedIndex;\r\n };\r\n }\r\n if (prop === \"stateSort\") {\r\n return (\r\n compareFn: (\r\n a: InferArrayElement<T>,\r\n b: InferArrayElement<T>\r\n ) => number\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n\r\n // Create a shallow copy with original indices\r\n const arrayCopy = currentArray.map((v: any, i: number) => ({\r\n ...v,\r\n __origIndex: i.toString(),\r\n }));\r\n\r\n // Sort the copy using the provided compare function\r\n const sortedArray = [...arrayCopy].sort(compareFn);\r\n\r\n // ADDED: Clear cache for sort operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // Return the sorted array with state objects\r\n return rebuildStateShape(sortedArray as any, path, {\r\n filtered: [...(meta?.filtered || []), path],\r\n validIndices: sortedArray.map((item) =>\r\n parseInt(item.__origIndex as string)\r\n ),\r\n });\r\n };\r\n }\r\n if (prop === \"stateMap\" || prop === \"stateMapNoRender\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n const isFiltered = meta?.filtered?.some(\r\n (p) => p.join(\".\") === path.join(\".\")\r\n );\r\n const arrayToMap = isFiltered\r\n ? currentState\r\n : getGlobalStore.getState().getNestedState(stateKey, path);\r\n\r\n if (prop !== \"stateMapNoRender\") {\r\n shapeCache.clear();\r\n stateVersion++;\r\n }\r\n\r\n return arrayToMap.map((val: any, index: number) => {\r\n const thisIndex =\r\n isFiltered && val.__origIndex ? val.__origIndex : index;\r\n const elementProxy = rebuildStateShape(\r\n val,\r\n [...path, thisIndex.toString()],\r\n meta\r\n );\r\n return callbackfn(\r\n val,\r\n elementProxy,\r\n index,\r\n currentState as any,\r\n rebuildStateShape(currentState as any, path, meta)\r\n );\r\n });\r\n };\r\n }\r\n if (prop === \"$stateMap\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n return createElement(SignalMapRenderer, {\r\n proxy: {\r\n _stateKey: stateKey,\r\n _path: path,\r\n _mapFn: callbackfn as any, // Pass the actual function, not string\r\n },\r\n\r\n rebuildStateShape,\r\n });\r\n };\r\n }\r\n if (prop === \"stateFlattenOn\") {\r\n return (fieldName: string) => {\r\n const isFiltered = meta?.filtered?.some(\r\n (p) => p.join(\".\") === path.join(\".\")\r\n );\r\n const arrayToMap = isFiltered\r\n ? currentState\r\n : getGlobalStore.getState().getNestedState(stateKey, path);\r\n\r\n // ADDED: Clear shape cache for flattening operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const flattenedResults = arrayToMap.flatMap(\r\n (val: any, index: number) => {\r\n return val[fieldName] ?? [];\r\n }\r\n );\r\n\r\n return rebuildStateShape(\r\n flattenedResults,\r\n [...path, \"[*]\", fieldName],\r\n meta\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"findWith\") {\r\n return (\r\n thisKey: keyof InferArrayElement<T>,\r\n thisValue: InferArrayElement<T>[keyof InferArrayElement<T>]\r\n ) => {\r\n const foundIndex = currentState.findIndex(\r\n (obj: any) => obj[thisKey] === thisValue\r\n );\r\n if (foundIndex === -1) return undefined;\r\n const foundValue = currentState[foundIndex];\r\n const newPath = [...path, foundIndex.toString()];\r\n // console.log(\r\n // \"findWithfindWithfindWithfindWith\",\r\n // stateKey,\r\n // foundValue,\r\n // newPath,\r\n // );\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // ADDED: Clear cache for find operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n // Try returning without spread\r\n return rebuildStateShape(foundValue, newPath);\r\n };\r\n }\r\n\r\n if (prop === \"index\") {\r\n return (index: number) => {\r\n const indexValue = currentState[index];\r\n return rebuildStateShape(indexValue, [...path, index.toString()]);\r\n };\r\n }\r\n\r\n if (prop === \"insert\") {\r\n return (payload: UpdateArg<T>) => {\r\n // ADDED: Invalidate cache on insert\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, payload, path, stateKey);\r\n return rebuildStateShape(\r\n getGlobalStore.getState().cogsStateStore[stateKey],\r\n []\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"uniqueInsert\") {\r\n return (\r\n payload: UpdateArg<T>,\r\n fields?: (keyof InferArrayElement<T>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n const newValue = isFunction<T>(payload)\r\n ? payload(currentArray as any)\r\n : (payload as any);\r\n\r\n let matchedItem: any = null;\r\n const isUnique = !currentArray.some((item) => {\r\n if (fields) {\r\n const isMatch = fields.every((field) =>\r\n isDeepEqual(item[field], newValue[field])\r\n );\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n }\r\n const isMatch = isDeepEqual(item, newValue);\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n });\r\n\r\n if (isUnique) {\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, newValue, path, stateKey);\r\n } else if (onMatch && matchedItem) {\r\n const updatedItem = onMatch(matchedItem);\r\n const updatedArray = currentArray.map((item) =>\r\n isDeepEqual(item, matchedItem) ? updatedItem : item\r\n );\r\n invalidateCachePath(path);\r\n updateFn(effectiveSetState, updatedArray as any, path);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"cut\") {\r\n return (index: number, options?: { waitForSync?: boolean }) => {\r\n if (options?.waitForSync) return;\r\n // ADDED: Invalidate cache on cut\r\n invalidateCachePath(path);\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n };\r\n }\r\n if (prop === \"cutByValue\") {\r\n return (value: string | number | boolean) => {\r\n for (let index = 0; index < currentState.length; index++) {\r\n if (currentState[index] === value) {\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n }\r\n }\r\n };\r\n }\r\n if (prop === \"toggleByValue\") {\r\n return (value: string | number | boolean) => {\r\n const index = currentState.findIndex((item) => item === value);\r\n if (index > -1) {\r\n // Value exists, so cut it\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n } else {\r\n // Value doesn't exist, so insert it\r\n pushFunc(effectiveSetState, value as any, path, stateKey);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"stateFilter\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const newVal = currentState.map((v: any, i: number) => ({\r\n ...v,\r\n __origIndex: i.toString(),\r\n }));\r\n\r\n const validIndices: number[] = [];\r\n const filteredArray: Array<InferArrayElement<T>> = [];\r\n\r\n for (let i = 0; i < newVal.length; i++) {\r\n if (callbackfn(newVal[i], i)) {\r\n validIndices.push(i);\r\n filteredArray.push(newVal[i]);\r\n }\r\n }\r\n\r\n // ADDED: Clear cache for filter operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // Always include validIndices, even if it's an empty array\r\n return rebuildStateShape(filteredArray as any, path, {\r\n filtered: [...(meta?.filtered || []), path],\r\n validIndices: validIndices, // Always pass validIndices, even if empty\r\n });\r\n };\r\n }\r\n }\r\n const lastPathElement = path[path.length - 1];\r\n if (!isNaN(Number(lastPathElement))) {\r\n const parentPath = path.slice(0, -1);\r\n const parentValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n\r\n if (Array.isArray(parentValue) && prop === \"cut\") {\r\n return () =>\r\n cutFunc(\r\n effectiveSetState,\r\n parentPath,\r\n stateKey,\r\n Number(lastPathElement)\r\n );\r\n }\r\n }\r\n\r\n if (prop === \"get\") {\r\n return () => getGlobalStore.getState().getNestedState(stateKey, path);\r\n }\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$get\") {\r\n return () =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n });\r\n }\r\n if (prop === \"lastSynced\") {\r\n const syncKey = `${stateKey}:${path.join(\".\")}`;\r\n return getGlobalStore.getState().getSyncInfo(syncKey);\r\n }\r\n\r\n if (prop == \"getLocalStorage\") {\r\n return (key: string) =>\r\n loadFromLocalStorage(sessionId + \"-\" + stateKey + \"-\" + key);\r\n }\r\n if (prop === \"_selected\") {\r\n const parentPath = path.slice(0, -1);\r\n const parentKey = parentPath.join(\".\");\r\n const parent = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n if (Array.isArray(parent)) {\r\n const currentIndex = Number(path[path.length - 1]);\r\n return (\r\n currentIndex ===\r\n getGlobalStore.getState().getSelectedIndex(stateKey, parentKey)\r\n );\r\n }\r\n return undefined;\r\n }\r\n if (prop === \"setSelected\") {\r\n return (value: boolean) => {\r\n const parentPath = path.slice(0, -1);\r\n const thisIndex = Number(path[path.length - 1]);\r\n const parentKey = parentPath.join(\".\");\r\n\r\n if (value) {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, thisIndex);\r\n } else {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, undefined);\r\n }\r\n\r\n const nested = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, [...parentPath]);\r\n updateFn(effectiveSetState, nested, parentPath);\r\n\r\n // Invalidate cache for this path\r\n invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (path.length == 0) {\r\n if (prop === \"validateZodSchema\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n const addValidationError =\r\n getGlobalStore.getState().addValidationError;\r\n\r\n if (!init?.zodSchema) {\r\n throw new Error(\"Zod schema not found\");\r\n }\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n removeValidationError(init.key);\r\n const thisObject =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n\r\n try {\r\n // First clear any existing validation errors for this schema\r\n // This ensures we don't have stale errors\r\n const existingErrors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key);\r\n if (existingErrors && existingErrors.length > 0) {\r\n existingErrors.forEach(([errorPath]) => {\r\n if (errorPath && errorPath.startsWith(init.key!)) {\r\n removeValidationError(errorPath);\r\n }\r\n });\r\n }\r\n\r\n // Attempt to validate with Zod\r\n const result = init.zodSchema.safeParse(thisObject);\r\n\r\n if (!result.success) {\r\n // Process Zod errors and add them to the validation store\r\n const zodErrors = result.error.errors;\r\n\r\n zodErrors.forEach((error) => {\r\n const errorPath = error.path;\r\n const errorMessage = error.message;\r\n\r\n // Build the full path for the validation error\r\n // Format: validationKey.path.to.field\r\n const fullErrorPath = [init.key, ...errorPath].join(\".\");\r\n\r\n // Add the error to the store\r\n addValidationError(fullErrorPath, errorMessage);\r\n });\r\n\r\n notifyComponents(stateKey);\r\n\r\n return false;\r\n }\r\n\r\n return true;\r\n } catch (error) {\r\n console.error(\"Zod schema validation failed\", error);\r\n return false;\r\n }\r\n };\r\n }\r\n if (prop === \"_componentId\") return componentId;\r\n if (prop === \"getComponents\") {\r\n return () => getGlobalStore().stateComponents.get(stateKey);\r\n }\r\n if (prop === \"getAllFormRefs\") {\r\n return () => {\r\n return formRefStore.getState().getFormRefsByStateKey(stateKey);\r\n };\r\n }\r\n\r\n if (prop === \"_initialState\")\r\n return getGlobalStore.getState().initialStateGlobal[stateKey];\r\n if (prop === \"_serverState\")\r\n return getGlobalStore.getState().serverState[stateKey];\r\n if (prop === \"_isLoading\")\r\n return getGlobalStore.getState().isLoadingGlobal[stateKey];\r\n if (prop === \"revertToInitialState\")\r\n return baseObj.revertToInitialState;\r\n if (prop === \"updateInitialState\") return baseObj.updateInitialState;\r\n if (prop === \"removeValidation\") return baseObj.removeValidation;\r\n }\r\n if (prop === \"getFormRef\") {\r\n return () => {\r\n return formRefStore\r\n .getState()\r\n .getFormRef(stateKey + \".\" + path.join(\".\"));\r\n };\r\n }\r\n\r\n if (prop === \"validationWrapper\") {\r\n return ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => (\r\n <ValidationWrapper\r\n formOpts={\r\n hideMessage ? { validation: { message: \"\" } } : undefined\r\n }\r\n path={path}\r\n validationKey={\r\n getGlobalStore.getState().getInitialOptions(stateKey)\r\n ?.validation?.key || \"\"\r\n }\r\n stateKey={stateKey}\r\n validIndices={meta?.validIndices}\r\n >\r\n {children}\r\n </ValidationWrapper>\r\n );\r\n }\r\n\r\n if (prop === \"_stateKey\") return stateKey;\r\n if (prop === \"_path\") return path;\r\n if (prop === \"_isServerSynced\") return baseObj._isServerSynced;\r\n\r\n if (prop === \"update\") {\r\n return (payload: UpdateArg<T>, opts?: UpdateOpts<T>) => {\r\n // ADDED: Invalidate cache on update\r\n if (opts?.debounce) {\r\n debounce(() => {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }, opts.debounce);\r\n } else {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }\r\n invalidateCachePath(path);\r\n };\r\n }\r\n\r\n if (prop === \"formElement\") {\r\n return (child: FormControl<T>, formOpts?: FormOptsType) => {\r\n return (\r\n <FormControlComponent<T>\r\n setState={effectiveSetState}\r\n stateKey={stateKey}\r\n path={path}\r\n child={child}\r\n formOpts={formOpts}\r\n />\r\n );\r\n };\r\n }\r\n\r\n const nextPath = [...path, prop];\r\n const nextValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, nextPath);\r\n return rebuildStateShape(nextValue, nextPath, meta);\r\n },\r\n };\r\n\r\n const proxyInstance = new Proxy(baseFunction, handler);\r\n\r\n shapeCache.set(cacheKey, {\r\n proxy: proxyInstance,\r\n stateVersion: stateVersion,\r\n });\r\n\r\n return proxyInstance;\r\n }\r\n\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, [])\r\n );\r\n}\r\n\r\nexport function $cogsSignal(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n}) {\r\n return createElement(SignalRenderer, { proxy });\r\n}\r\n\r\nfunction SignalMapRenderer({\r\n proxy,\r\n\r\n rebuildStateShape,\r\n}: {\r\n proxy: {\r\n _stateKey: string;\r\n _path: string[];\r\n _mapFn: (\r\n value: any,\r\n setter: any,\r\n index: number,\r\n array: any[],\r\n arraySetter: any\r\n ) => ReactNode;\r\n };\r\n\r\n rebuildStateShape: (\r\n currentState: any,\r\n path: string[],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ) => any;\r\n}) {\r\n const value = getGlobalStore().getNestedState(proxy._stateKey, proxy._path);\r\n\r\n if (!Array.isArray(value)) {\r\n return null;\r\n }\r\n const arraySetter = rebuildStateShape(\r\n value,\r\n proxy._path\r\n ) as ArrayEndType<any>;\r\n // Use existing global state management\r\n return arraySetter.stateMapNoRender(\r\n (item, setter, index, value, arraysetter) => {\r\n // Execute map function in React context with existing state/proxies\r\n return proxy._mapFn(item, setter, index, value, arraysetter);\r\n }\r\n );\r\n}\r\nfunction SignalRenderer({\r\n proxy,\r\n}: {\r\n proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n };\r\n}) {\r\n const elementRef = useRef<HTMLSpanElement>(null);\r\n const signalId = `${proxy._stateKey}-${proxy._path.join(\".\")}`;\r\n\r\n useEffect(() => {\r\n const element = elementRef.current;\r\n if (!element || !element.parentElement) return;\r\n\r\n const parentElement = element.parentElement;\r\n const childNodes = Array.from(parentElement.childNodes);\r\n const position = childNodes.indexOf(element);\r\n\r\n let parentId = parentElement.getAttribute(\"data-parent-id\");\r\n if (!parentId) {\r\n parentId = `parent-${crypto.randomUUID()}`;\r\n parentElement.setAttribute(\"data-parent-id\", parentId);\r\n }\r\n\r\n const instanceId = `instance-${crypto.randomUUID()}`;\r\n const elementInfo = {\r\n instanceId,\r\n parentId,\r\n position,\r\n effect: proxy._effect,\r\n };\r\n\r\n getGlobalStore.getState().addSignalElement(signalId, elementInfo);\r\n\r\n // Get the raw value from the store\r\n const value = getGlobalStore\r\n .getState()\r\n .getNestedState(proxy._stateKey, proxy._path);\r\n\r\n let displayValue;\r\n if (proxy._effect) {\r\n try {\r\n displayValue = new Function(\r\n \"state\",\r\n `return (${proxy._effect})(state)`\r\n )(value);\r\n } catch (err) {\r\n console.error(\"Error evaluating effect function during mount:\", err);\r\n displayValue = value; // Fallback to raw value\r\n }\r\n } else {\r\n displayValue = value;\r\n }\r\n\r\n if (displayValue !== null && typeof displayValue === \"object\") {\r\n displayValue = JSON.stringify(displayValue);\r\n }\r\n\r\n const textNode = document.createTextNode(String(displayValue));\r\n element.replaceWith(textNode);\r\n }, [proxy._stateKey, proxy._path.join(\".\"), proxy._effect]);\r\n\r\n return createElement(\"span\", {\r\n ref: elementRef,\r\n style: { display: \"none\" },\r\n \"data-signal-id\": signalId,\r\n });\r\n}\r\nexport function $cogsSignalStore(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n}) {\r\n const value = useSyncExternalStore(\r\n (notify) => {\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(proxy._stateKey) || {\r\n components: new Map(),\r\n };\r\n stateEntry.components.set(proxy._stateKey, {\r\n forceUpdate: notify,\r\n paths: new Set([proxy._path.join(\".\")]),\r\n });\r\n return () => stateEntry.components.delete(proxy._stateKey);\r\n },\r\n () => getGlobalStore.getState().getNestedState(proxy._stateKey, proxy._path)\r\n );\r\n return createElement(\"text\", {}, String(value));\r\n}\r\n"],"names":["setAndMergeOptions","stateKey","newOptions","getInitialOptions","getGlobalStore","setInitialStateOptions","initialOptions","setOptions","options","initialOptionsPart","initialOptionsPartState","mergedOptions","needToAdd","key","addStateOptions","initialState","formElements","validation","createCogsState","opt","newInitialState","statePart","transformStateFunc","useCogsState","componentId","useState","uuidv4","thiState","partialState","state","updater","useCogsStateFn","setCogsOptions","setUpdaterState","setState","getKeyState","getValidationErrors","setStateLog","updateInitialStateGlobal","addValidationError","removeValidationError","setServerSyncActions","loadFromLocalStorage","localStorageKey","storedData","error","saveToLocalStorage","thisKey","currentInitialOptions","sessionId","isFunction","data","storageKey","updateGlobalState","newState","effectiveSetState","updates","createProxyHandler","startTransition","notifyComponents","stateEntry","component","update","notifyComponent","fullComponentId","stateObject","serverSync","localStorage","middleware","reactiveDeps","reactiveType","syncUpdate","dependencies","reactiveForce","forceUpdate","useCogsConfig","noStateKey","stateLog","componentUpdatesRef","useRef","componentIdRef","latestInitialOptionsRef","useEffect","prevState","syncKey","localData","localkey","useLayoutEffect","depsKey","newStateOrFunction","path","updateObj","validationKey","pathKey","prevValue","payload","signalId","isArrayOperation","elements","arrayPath","arrayValue","getNestedValue","arraySignalId","newValue","parentId","position","effect","parent","childNodes","displayValue","arrayWithoutIndex","k","v","length","newKey","oldValue","pathToCheck","shouldUpdate","reactiveTypes","depsResult","isDeepEqual","newUpdate","prevLogs","aggregatedLogs","acc","log","uniqueKey","existing","serverStateStore","updaterFinal","useMemo","shapeCache","stateVersion","invalidateCachePath","baseObj","obj","init","newProxy","rebuildStateShape","initalOptionsGet","localKey","newUpdaterState","field","serverState","currentState","meta","cacheKey","baseFunction","handler","target","thisArg","args","prop","currentPath","thisReactiveState","initialStateAtPath","selectedIndex","compareFn","sortedArray","i","item","callbackfn","isFiltered","p","arrayToMap","val","index","thisIndex","elementProxy","createElement","SignalMapRenderer","fieldName","flattenedResults","thisValue","foundIndex","foundValue","newPath","indexValue","pushFunc","fields","onMatch","currentArray","matchedItem","isMatch","updatedItem","updatedArray","updateFn","cutFunc","value","newVal","validIndices","filteredArray","lastPathElement","parentPath","parentValue","fn","$cogsSignal","parentKey","nested","thisObject","existingErrors","errorPath","result","errorMessage","fullErrorPath","formRefStore","children","hideMessage","jsx","ValidationWrapper","opts","debounce","child","formOpts","FormControlComponent","nextPath","nextValue","proxyInstance","proxy","SignalRenderer","setter","arraysetter","elementRef","element","parentElement","elementInfo","err","textNode","$cogsSignalStore","useSyncExternalStore","notify"],"mappings":";;;;;;;;;AAwYA,SAASA,GAAmBC,GAAkBC,GAA8B;AACpEC,QAAAA,IAAoBC,EAAe,SAAA,EAAW,mBAC9CC,IACJD,EAAe,SAAA,EAAW,wBAEtBE,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC;AAEjE,EAAAI,EAAuBJ,GAAoB;AAAA,IACzC,GAAGK;AAAA,IACH,GAAGJ;AAAA,EAAA,CACJ;AACH;AAEA,SAASK,GAA0B;AAAA,EACjC,UAAAN;AAAA,EACA,SAAAO;AAAA,EACA,oBAAAC;AACF,GAIG;AACD,QAAMH,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC,GAC3DS,IAA0BD,EAAmBR,CAAkB,KAAK,CAAC,GACrEI,IACJD,EAAe,SAAA,EAAW,wBACtBO,IAAgB,EAAE,GAAGD,GAAyB,GAAGJ,EAAe;AAEtE,MAAIM,IAAY;AAChB,MAAIJ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M,KAAK;AAAA,EAC7E;AACA,SAAOjD,EAAc,QAAQ,CAAI,GAAA,OAAOmB,CAAK,CAAC;AAChD;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cogsbox-state",
3
- "version": "0.5.74",
3
+ "version": "0.5.76",
4
4
  "description": "React state management library with form controls and server sync",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -37,6 +37,20 @@
37
37
  "react": "^18.2.0",
38
38
  "react-dom": "^18.2.0"
39
39
  },
40
+ "peerDependenciesMeta": {
41
+ "@trpc/next": {
42
+ "optional": true
43
+ },
44
+ "@types/react": {
45
+ "optional": true
46
+ },
47
+ "react": {
48
+ "optional": false
49
+ },
50
+ "react-dom": {
51
+ "optional": false
52
+ }
53
+ },
40
54
  "devDependencies": {
41
55
  "@types/node": "^22.14.0",
42
56
  "@types/react": "^18.2.0",