cogsbox-state 0.5.13 → 0.5.14
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.
- package/dist/CogsState.d.ts +8 -6
- package/dist/CogsState.jsx +46 -45
- package/dist/CogsState.jsx.map +1 -1
- package/package.json +1 -1
package/dist/CogsState.d.ts
CHANGED
|
@@ -167,14 +167,15 @@ type CookieType<T> = {
|
|
|
167
167
|
};
|
|
168
168
|
export type CogsCookiesType<T extends string[] = string[]> = CookieType<ArrayToObject<T>>;
|
|
169
169
|
export type ReactivityType = "none" | "component" | "deps" | "all";
|
|
170
|
+
type ValidationOptionsType = {
|
|
171
|
+
key?: string;
|
|
172
|
+
zodSchema?: ZodObject<ZodRawShape> | ZodArray<ZodObject<ZodRawShape>>;
|
|
173
|
+
onBlur?: boolean;
|
|
174
|
+
};
|
|
170
175
|
export type OptionsType<T extends unknown = unknown> = {
|
|
171
176
|
componentId?: string;
|
|
172
177
|
serverSync?: ServerSyncType<T>;
|
|
173
|
-
validation?:
|
|
174
|
-
key?: string;
|
|
175
|
-
zodSchema?: ZodObject<ZodRawShape> | ZodArray<ZodObject<ZodRawShape>>;
|
|
176
|
-
onBlur?: boolean;
|
|
177
|
-
};
|
|
178
|
+
validation?: ValidationOptionsType;
|
|
178
179
|
enableServerState?: boolean;
|
|
179
180
|
middleware?: ({ updateLog, update, }: {
|
|
180
181
|
updateLog: UpdateTypeDetail[] | undefined;
|
|
@@ -261,9 +262,10 @@ export type CogsInitialState<T> = {
|
|
|
261
262
|
export type TransformedStateType<T> = {
|
|
262
263
|
[P in keyof T]: T[P] extends CogsInitialState<infer U> ? U : T[P];
|
|
263
264
|
};
|
|
264
|
-
export declare function addStateOptions<T extends unknown>(initialState: T, { formElements }: OptionsType<T>): T;
|
|
265
|
+
export declare function addStateOptions<T extends unknown>(initialState: T, { formElements, validation }: OptionsType<T>): T;
|
|
265
266
|
export declare const createCogsState: <State extends Record<string, unknown>>(initialState: State, opt?: {
|
|
266
267
|
formElements?: FormsElementsType;
|
|
268
|
+
validation?: ValidationOptionsType;
|
|
267
269
|
}) => {
|
|
268
270
|
useCogsState: <StateKey extends keyof State>(stateKey: StateKey, options?: OptionsType<TransformedStateType<State>[StateKey]>) => StateObject<TransformedStateType<State>[StateKey]>;
|
|
269
271
|
setCogsOptions: <StateKey extends keyof State>(stateKey: StateKey, options: OptionsType<TransformedStateType<State>[StateKey]>) => void;
|
package/dist/CogsState.jsx
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx as at } from "react/jsx-runtime";
|
|
3
3
|
import { useState as Y, useRef as z, useEffect as K, useLayoutEffect as vt, useMemo as It, createElement as H, useSyncExternalStore as Et, startTransition as J } from "react";
|
|
4
|
-
import { transformStateFunc as
|
|
4
|
+
import { transformStateFunc as _t, isFunction as ut, getNestedValue as L, isDeepEqual as k, debounce as pt } from "./utility.js";
|
|
5
5
|
import { pushFunc as it, updateFn as q, cutFunc as st, ValidationWrapper as wt, FormControlComponent as $t } from "./Functions.jsx";
|
|
6
6
|
import "zod";
|
|
7
7
|
import { getGlobalStore as o, formRefStore as ct } from "./store.js";
|
|
@@ -19,29 +19,30 @@ function dt({
|
|
|
19
19
|
options: a,
|
|
20
20
|
initialOptionsPart: g
|
|
21
21
|
}) {
|
|
22
|
-
const S = et(t) || {}, l = g[t] || {}, E = o.getState().setInitialStateOptions,
|
|
22
|
+
const S = et(t) || {}, l = g[t] || {}, E = o.getState().setInitialStateOptions, _ = { ...l, ...S };
|
|
23
23
|
let v = !1;
|
|
24
24
|
if (a)
|
|
25
25
|
for (const m in a)
|
|
26
|
-
|
|
27
|
-
v && E(t,
|
|
26
|
+
_.hasOwnProperty(m) || (v = !0, _[m] = a[m]);
|
|
27
|
+
v && E(t, _);
|
|
28
28
|
}
|
|
29
|
-
function qt(t, { formElements: a }) {
|
|
30
|
-
return { initialState: t, formElements: a };
|
|
29
|
+
function qt(t, { formElements: a, validation: g }) {
|
|
30
|
+
return { initialState: t, formElements: a, validation: g };
|
|
31
31
|
}
|
|
32
32
|
const zt = (t, a) => {
|
|
33
33
|
let g = t;
|
|
34
|
-
const [S, l] =
|
|
35
|
-
a?.formElements && Object.keys(l).forEach((v) => {
|
|
34
|
+
const [S, l] = _t(g);
|
|
35
|
+
(a?.formElements || a?.validation) && Object.keys(l).forEach((v) => {
|
|
36
36
|
l[v] = l[v] || {}, l[v].formElements = {
|
|
37
37
|
...a.formElements,
|
|
38
38
|
// Global defaults first
|
|
39
|
+
...a?.validation,
|
|
39
40
|
...l[v].formElements || {}
|
|
40
41
|
// State-specific overrides
|
|
41
42
|
};
|
|
42
43
|
}), o.getState().setInitialStates(S);
|
|
43
44
|
const E = (v, m) => {
|
|
44
|
-
const [
|
|
45
|
+
const [p] = Y(m?.componentId ?? tt());
|
|
45
46
|
dt({
|
|
46
47
|
stateKey: v,
|
|
47
48
|
options: m,
|
|
@@ -52,7 +53,7 @@ const zt = (t, a) => {
|
|
|
52
53
|
{
|
|
53
54
|
stateKey: v,
|
|
54
55
|
syncUpdate: m?.syncUpdate,
|
|
55
|
-
componentId:
|
|
56
|
+
componentId: p,
|
|
56
57
|
localStorage: m?.localStorage,
|
|
57
58
|
middleware: m?.middleware,
|
|
58
59
|
enabledSync: m?.enabledSync,
|
|
@@ -64,10 +65,10 @@ const zt = (t, a) => {
|
|
|
64
65
|
);
|
|
65
66
|
return h;
|
|
66
67
|
};
|
|
67
|
-
function
|
|
68
|
+
function _(v, m) {
|
|
68
69
|
dt({ stateKey: v, options: m, initialOptionsPart: l });
|
|
69
70
|
}
|
|
70
|
-
return { useCogsState: E, setCogsOptions:
|
|
71
|
+
return { useCogsState: E, setCogsOptions: _ };
|
|
71
72
|
}, {
|
|
72
73
|
setUpdaterState: B,
|
|
73
74
|
setState: x,
|
|
@@ -98,7 +99,7 @@ const zt = (t, a) => {
|
|
|
98
99
|
window.localStorage.setItem(E, JSON.stringify(l));
|
|
99
100
|
}
|
|
100
101
|
}, Ft = (t, a, g, S, l, E) => {
|
|
101
|
-
const
|
|
102
|
+
const _ = {
|
|
102
103
|
initialState: a,
|
|
103
104
|
updaterState: Z(
|
|
104
105
|
t,
|
|
@@ -109,7 +110,7 @@ const zt = (t, a) => {
|
|
|
109
110
|
state: g
|
|
110
111
|
};
|
|
111
112
|
J(() => {
|
|
112
|
-
nt(t,
|
|
113
|
+
nt(t, _.initialState), B(t, _.updaterState), x(t, _.state);
|
|
113
114
|
});
|
|
114
115
|
}, jt = (t) => {
|
|
115
116
|
const a = o.getState().stateComponents.get(t);
|
|
@@ -135,10 +136,10 @@ function Mt(t, {
|
|
|
135
136
|
localStorage: S,
|
|
136
137
|
formElements: l,
|
|
137
138
|
middleware: E,
|
|
138
|
-
reactiveDeps:
|
|
139
|
+
reactiveDeps: _,
|
|
139
140
|
reactiveType: v,
|
|
140
141
|
componentId: m,
|
|
141
|
-
localStorageKey:
|
|
142
|
+
localStorageKey: p,
|
|
142
143
|
initState: d,
|
|
143
144
|
syncUpdate: e
|
|
144
145
|
} = {}) {
|
|
@@ -162,8 +163,8 @@ function Mt(t, {
|
|
|
162
163
|
initState: d
|
|
163
164
|
});
|
|
164
165
|
let c = null;
|
|
165
|
-
|
|
166
|
-
F + "-" + u + "-" +
|
|
166
|
+
p && (c = gt(
|
|
167
|
+
F + "-" + u + "-" + p
|
|
167
168
|
));
|
|
168
169
|
let r = null;
|
|
169
170
|
d?.initialState && (r = d?.initialState, console.log("newState", r), c && c.lastUpdated > (c.lastSyncedWithServer || 0) && (r = c.state), Ft(
|
|
@@ -174,7 +175,7 @@ function Mt(t, {
|
|
|
174
175
|
U.current,
|
|
175
176
|
F
|
|
176
177
|
), console.log("newState222", r), h({}));
|
|
177
|
-
}, [
|
|
178
|
+
}, [p, ...d?.dependencies || []]), vt(() => {
|
|
178
179
|
b && lt(u, {
|
|
179
180
|
serverSync: g,
|
|
180
181
|
formElements: l,
|
|
@@ -189,7 +190,7 @@ function Mt(t, {
|
|
|
189
190
|
forceUpdate: () => h({}),
|
|
190
191
|
paths: /* @__PURE__ */ new Set(),
|
|
191
192
|
deps: [],
|
|
192
|
-
depsFunction:
|
|
193
|
+
depsFunction: _ || void 0,
|
|
193
194
|
reactiveType: v ?? ["component", "deps"]
|
|
194
195
|
}), o.getState().stateComponents.set(u, r), h({}), () => {
|
|
195
196
|
const f = `${u}////${U.current}`;
|
|
@@ -316,7 +317,7 @@ function Mt(t, {
|
|
|
316
317
|
function Z(t, a, g, S) {
|
|
317
318
|
const l = /* @__PURE__ */ new Map();
|
|
318
319
|
let E = 0;
|
|
319
|
-
const
|
|
320
|
+
const _ = (d) => {
|
|
320
321
|
const e = d.join(".");
|
|
321
322
|
for (const [I] of l)
|
|
322
323
|
(I === e || I.startsWith(e + ".")) && l.delete(I);
|
|
@@ -330,7 +331,7 @@ function Z(t, a, g, S) {
|
|
|
330
331
|
e?.key && R(e?.key), d?.validationKey && R(d.validationKey);
|
|
331
332
|
const I = o.getState().initialStateGlobal[t];
|
|
332
333
|
l.clear(), E++;
|
|
333
|
-
const h =
|
|
334
|
+
const h = p(I, []);
|
|
334
335
|
J(() => {
|
|
335
336
|
B(t, h), x(t, I);
|
|
336
337
|
const F = o.getState().stateComponents.get(t);
|
|
@@ -369,7 +370,7 @@ function Z(t, a, g, S) {
|
|
|
369
370
|
return !!(d && k(d, ft(t)));
|
|
370
371
|
}
|
|
371
372
|
};
|
|
372
|
-
function
|
|
373
|
+
function p(d, e = [], I) {
|
|
373
374
|
const h = e.map(String).join(".");
|
|
374
375
|
l.get(h);
|
|
375
376
|
const F = {
|
|
@@ -393,7 +394,7 @@ function Z(t, a, g, S) {
|
|
|
393
394
|
return () => {
|
|
394
395
|
const n = v.get(e.join("."));
|
|
395
396
|
if (n !== void 0)
|
|
396
|
-
return
|
|
397
|
+
return p(
|
|
397
398
|
d[n],
|
|
398
399
|
[...e, n.toString()],
|
|
399
400
|
I
|
|
@@ -405,7 +406,7 @@ function Z(t, a, g, S) {
|
|
|
405
406
|
(r) => r.join(".") === e.join(".")
|
|
406
407
|
), c = s ? d : o.getState().getNestedState(t, e);
|
|
407
408
|
return i !== "stateMapNoRender" && (l.clear(), E++), c.map((r, f) => {
|
|
408
|
-
const w = s && r.__origIndex ? r.__origIndex : f, j =
|
|
409
|
+
const w = s && r.__origIndex ? r.__origIndex : f, j = p(
|
|
409
410
|
r,
|
|
410
411
|
[...e, w.toString()],
|
|
411
412
|
I
|
|
@@ -415,7 +416,7 @@ function Z(t, a, g, S) {
|
|
|
415
416
|
j,
|
|
416
417
|
f,
|
|
417
418
|
d,
|
|
418
|
-
|
|
419
|
+
p(d, e, I)
|
|
419
420
|
);
|
|
420
421
|
});
|
|
421
422
|
};
|
|
@@ -427,7 +428,7 @@ function Z(t, a, g, S) {
|
|
|
427
428
|
_mapFn: n
|
|
428
429
|
// Pass the actual function, not string
|
|
429
430
|
},
|
|
430
|
-
rebuildStateShape:
|
|
431
|
+
rebuildStateShape: p
|
|
431
432
|
});
|
|
432
433
|
if (i === "stateFlattenOn")
|
|
433
434
|
return (n) => {
|
|
@@ -438,7 +439,7 @@ function Z(t, a, g, S) {
|
|
|
438
439
|
const r = c.flatMap(
|
|
439
440
|
(f, w) => f[n] ?? []
|
|
440
441
|
);
|
|
441
|
-
return
|
|
442
|
+
return p(
|
|
442
443
|
r,
|
|
443
444
|
[...e, "[*]", n],
|
|
444
445
|
I
|
|
@@ -451,15 +452,15 @@ function Z(t, a, g, S) {
|
|
|
451
452
|
);
|
|
452
453
|
if (c === -1) return;
|
|
453
454
|
const r = d[c], f = [...e, c.toString()];
|
|
454
|
-
return l.clear(), E++, l.clear(), E++,
|
|
455
|
+
return l.clear(), E++, l.clear(), E++, p(r, f);
|
|
455
456
|
};
|
|
456
457
|
if (i === "index")
|
|
457
458
|
return (n) => {
|
|
458
459
|
const s = d[n];
|
|
459
|
-
return
|
|
460
|
+
return p(s, [...e, n.toString()]);
|
|
460
461
|
};
|
|
461
462
|
if (i === "insert")
|
|
462
|
-
return (n) => (
|
|
463
|
+
return (n) => (_(e), it(a, n, e, t), p(
|
|
463
464
|
o.getState().cogsStateStore[t],
|
|
464
465
|
[]
|
|
465
466
|
));
|
|
@@ -477,17 +478,17 @@ function Z(t, a, g, S) {
|
|
|
477
478
|
const M = k(V, f);
|
|
478
479
|
return M && (w = V), M;
|
|
479
480
|
}))
|
|
480
|
-
|
|
481
|
+
_(e), it(a, f, e, t);
|
|
481
482
|
else if (c && w) {
|
|
482
483
|
const V = c(w), M = r.map(
|
|
483
484
|
(C) => k(C, w) ? V : C
|
|
484
485
|
);
|
|
485
|
-
|
|
486
|
+
_(e), q(a, M, e);
|
|
486
487
|
}
|
|
487
488
|
};
|
|
488
489
|
if (i === "cut")
|
|
489
490
|
return (n, s) => {
|
|
490
|
-
s?.waitForSync || (
|
|
491
|
+
s?.waitForSync || (_(e), st(a, e, t, n));
|
|
491
492
|
};
|
|
492
493
|
if (i === "stateFilter")
|
|
493
494
|
return (n) => {
|
|
@@ -497,7 +498,7 @@ function Z(t, a, g, S) {
|
|
|
497
498
|
})), c = [], r = [];
|
|
498
499
|
for (let f = 0; f < s.length; f++)
|
|
499
500
|
n(s[f], f) && (c.push(f), r.push(s[f]));
|
|
500
|
-
return l.clear(), E++,
|
|
501
|
+
return l.clear(), E++, p(r, e, {
|
|
501
502
|
filtered: [...I?.filtered || [], e],
|
|
502
503
|
validIndices: c
|
|
503
504
|
// Pass through the meta
|
|
@@ -549,7 +550,7 @@ function Z(t, a, g, S) {
|
|
|
549
550
|
const s = e.slice(0, -1), c = Number(e[e.length - 1]), r = s.join(".");
|
|
550
551
|
n ? v.set(r, c) : v.delete(r);
|
|
551
552
|
const f = o.getState().getNestedState(t, [...s]);
|
|
552
|
-
q(a, f, s),
|
|
553
|
+
q(a, f, s), _(s);
|
|
553
554
|
};
|
|
554
555
|
if (e.length == 0) {
|
|
555
556
|
if (i === "validateZodSchema")
|
|
@@ -616,7 +617,7 @@ function Z(t, a, g, S) {
|
|
|
616
617
|
if (i === "update")
|
|
617
618
|
return (n, s) => {
|
|
618
619
|
if (s?.debounce)
|
|
619
|
-
|
|
620
|
+
pt(() => {
|
|
620
621
|
q(a, n, e, "");
|
|
621
622
|
const c = o.getState().getNestedState(t, e);
|
|
622
623
|
s?.afterUpdate && s.afterUpdate(c);
|
|
@@ -626,7 +627,7 @@ function Z(t, a, g, S) {
|
|
|
626
627
|
const c = o.getState().getNestedState(t, e);
|
|
627
628
|
s?.afterUpdate && s.afterUpdate(c);
|
|
628
629
|
}
|
|
629
|
-
|
|
630
|
+
_(e);
|
|
630
631
|
};
|
|
631
632
|
if (i === "formElement")
|
|
632
633
|
return (n, s) => /* @__PURE__ */ at(
|
|
@@ -640,7 +641,7 @@ function Z(t, a, g, S) {
|
|
|
640
641
|
}
|
|
641
642
|
);
|
|
642
643
|
const U = [...e, i], A = o.getState().getNestedState(t, U);
|
|
643
|
-
return
|
|
644
|
+
return p(A, U, I);
|
|
644
645
|
}
|
|
645
646
|
}, b = new Proxy(m, F);
|
|
646
647
|
return l.set(h, {
|
|
@@ -648,7 +649,7 @@ function Z(t, a, g, S) {
|
|
|
648
649
|
stateVersion: E
|
|
649
650
|
}), b;
|
|
650
651
|
}
|
|
651
|
-
return
|
|
652
|
+
return p(
|
|
652
653
|
o.getState().getNestedState(t, [])
|
|
653
654
|
);
|
|
654
655
|
}
|
|
@@ -664,7 +665,7 @@ function Ot({
|
|
|
664
665
|
g,
|
|
665
666
|
t._path
|
|
666
667
|
).stateMapNoRender(
|
|
667
|
-
(l, E,
|
|
668
|
+
(l, E, _, v, m) => t._mapFn(l, E, _, v, m)
|
|
668
669
|
) : null;
|
|
669
670
|
}
|
|
670
671
|
function bt({
|
|
@@ -674,16 +675,16 @@ function bt({
|
|
|
674
675
|
return K(() => {
|
|
675
676
|
const S = a.current;
|
|
676
677
|
if (!S || !S.parentElement) return;
|
|
677
|
-
const l = S.parentElement,
|
|
678
|
+
const l = S.parentElement, _ = Array.from(l.childNodes).indexOf(S);
|
|
678
679
|
let v = l.getAttribute("data-parent-id");
|
|
679
680
|
v || (v = `parent-${crypto.randomUUID()}`, l.setAttribute("data-parent-id", v));
|
|
680
|
-
const
|
|
681
|
+
const p = {
|
|
681
682
|
instanceId: `instance-${crypto.randomUUID()}`,
|
|
682
683
|
parentId: v,
|
|
683
|
-
position:
|
|
684
|
+
position: _,
|
|
684
685
|
effect: t._effect
|
|
685
686
|
};
|
|
686
|
-
o.getState().addSignalElement(g,
|
|
687
|
+
o.getState().addSignalElement(g, p);
|
|
687
688
|
const d = o.getState().getNestedState(t._stateKey, t._path);
|
|
688
689
|
let e;
|
|
689
690
|
if (t._effect)
|
package/dist/CogsState.jsx.map
CHANGED
|
@@ -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 getNestedValue,\r\n isFunction,\r\n updateNestedProperty,\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 { boolean, 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 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 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 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 }) => void;\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\nexport type OptionsType<T extends unknown = unknown> = {\r\n componentId?: string;\r\n serverSync?: ServerSyncType<T>;\r\n validation?: {\r\n key?: string;\r\n zodSchema?: ZodObject<ZodRawShape> | ZodArray<ZodObject<ZodRawShape>>;\r\n onBlur?: boolean;\r\n };\r\n\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 localStorageKey?: string;\r\n initState?: {\r\n ctx?: Record<string, any>;\r\n initialState: T;\r\n dependencies?: any[]; // Just like useEffect dependencies\r\n };\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?: Opt;\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 mergedOptions[key] = options[key as keyof typeof options];\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 }: OptionsType<T>\r\n) {\r\n return { initialState: initialState, formElements } as T;\r\n}\r\n\r\nexport const createCogsState = <State extends Record<string, unknown>>(\r\n initialState: State,\r\n opt?: { formElements?: FormsElementsType }\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) {\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 // Apply form elements with global as defaults\r\n initialOptionsPart[key].formElements = {\r\n ...opt.formElements, // Global defaults first\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 initState: options?.initState,\r\n localStorageKey: options?.localStorageKey,\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.localStorageKey) {\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 = currentInitialOptions.initState\r\n ? `${sessionId}-${thisKey}-${currentInitialOptions.localStorageKey}`\r\n : thisKey;\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 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 localStorageKey,\r\n initState,\r\n syncUpdate,\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 initState,\r\n });\r\n let localData = null;\r\n if (localStorageKey) {\r\n localData = loadFromLocalStorage(\r\n sessionId + \"-\" + thisKey + \"-\" + localStorageKey\r\n );\r\n }\r\n let newState = null;\r\n if (initState?.initialState) {\r\n newState = initState?.initialState;\r\n console.log(\"newState\", newState);\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 initState?.initialState,\r\n newState,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n console.log(\"newState222\", newState);\r\n forceUpdate({});\r\n }\r\n }, [localStorageKey, ...(initState?.dependencies || [])]);\r\n\r\n useLayoutEffect(() => {\r\n if (noStateKey) {\r\n setAndMergeOptions(thisKey as string, {\r\n serverSync,\r\n formElements,\r\n initState,\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 if (stateKey == \"cart\") {\r\n console.log(\"thisKey\", thisKey);\r\n console.log(\"stateEntry\", stateEntry);\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 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 console.log(\"Initializing state for\", thisKey, stateObject); // Debug log\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 selectedIndexMap = new Map<string, number>();\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\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 const initalOptionsGet = getInitialOptions(stateKey as string);\r\n if (initalOptionsGet?.localStorageKey) {\r\n localStorage.removeItem(\r\n initalOptionsGet?.initState\r\n ? sessionId +\r\n \"-\" +\r\n stateKey +\r\n \"-\" +\r\n initalOptionsGet?.localStorageKey\r\n : stateKey\r\n );\r\n }\r\n localStorage.removeItem(stateKey);\r\n });\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 localStorage.removeItem(stateKey);\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\r\n const handler = {\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 === \"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 = selectedIndexMap.get(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\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\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 return rebuildStateShape(filteredArray as any, path, {\r\n filtered: [...(meta?.filtered || []), path],\r\n validIndices, // Pass through the meta\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 === \"_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 currentIndex === selectedIndexMap.get(parentKey);\r\n }\r\n return undefined;\r\n }\r\n if (prop == \"getLocalStorage\") {\r\n return (key: string) =>\r\n loadFromLocalStorage(sessionId + \"-\" + stateKey + \"-\" + key);\r\n }\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 if (value) {\r\n selectedIndexMap.set(parentKey, thisIndex);\r\n } else {\r\n // Optional: clear selection if false\r\n selectedIndexMap.delete(parentKey);\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 // ADDED: Invalidate cache for parent path\r\n invalidateCachePath(parentPath);\r\n };\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 console.log(\r\n `Validation error at ${fullErrorPath}: ${errorMessage}`\r\n );\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(baseObj as StateObject<T>, 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 console.log(\"value\", value);\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","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","data","storageKey","updateGlobalState","newState","effectiveSetState","updates","createProxyHandler","startTransition","notifyComponents","stateEntry","component","update","notifyComponent","fullComponentId","stateObject","serverSync","localStorage","middleware","reactiveDeps","reactiveType","initState","syncUpdate","reactiveForce","forceUpdate","useCogsConfig","noStateKey","stateLog","componentUpdatesRef","useRef","componentIdRef","latestInitialOptionsRef","useEffect","prevState","syncKey","localData","useLayoutEffect","depsKey","newStateOrFunction","path","updateObj","validationKey","pathKey","prevValue","payload","isFunction","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","selectedIndexMap","baseObj","obj","init","newProxy","rebuildStateShape","initalOptionsGet","newUpdaterState","field","serverState","currentState","meta","cacheKey","handler","target","prop","currentPath","selectedIndex","callbackfn","isFiltered","p","arrayToMap","val","index","thisIndex","elementProxy","createElement","SignalMapRenderer","fieldName","flattenedResults","thisValue","foundIndex","foundValue","newPath","indexValue","pushFunc","fields","onMatch","currentArray","matchedItem","item","isMatch","updatedItem","updatedArray","updateFn","cutFunc","newVal","i","validIndices","filteredArray","lastPathElement","parentPath","parentValue","fn","$cogsSignal","parentKey","value","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":";;;;;;;;;AA6XA,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,GAAkBF,CAAkB,KAAK,CAAC,GAC3DS,IAA0BD,EAAmBR,CAAkB,KAAK,CAAC,GACrEI,IACJD,EAAe,SAAA,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A,eACA6B,GAAK;AACJ,gBAAA,MAAM,kDAAkDA,CAAG,GACpD9G,IAAAiF;AAAA,MAAA;AAAA;AAGF,MAAAjF,IAAAiF;AAGjB,IAAIjF,MAAiB,QAAQ,OAAOA,KAAiB,aACpCA,IAAA,KAAK,UAAUA,CAAY;AAG5C,UAAM+G,IAAW,SAAS,eAAe,OAAO/G,CAAY,CAAC;AAC7D,IAAA2G,EAAQ,YAAYI,CAAQ;AAAA,EAAA,GAC3B,CAACT,EAAM,WAAWA,EAAM,MAAM,KAAK,GAAG,GAAGA,EAAM,OAAO,CAAC,GAEnDnD,EAAc,QAAQ;AAAA,IAC3B,KAAKuD;AAAA,IACL,OAAO,EAAE,SAAS,OAAO;AAAA,IACzB,kBAAkBvH;AAAA,EAAA,CACnB;AACH;AACO,SAAS6H,GAAiBV,GAG9B;AACD,QAAMrB,IAAQgC;AAAA,IACZ,CAACC,MAAW;AACJ,YAAAnK,IAAatD,EAChB,SAAS,EACT,gBAAgB,IAAI6M,EAAM,SAAS,KAAK;AAAA,QACzC,gCAAgB,IAAI;AAAA,MACtB;AACW,aAAAvJ,EAAA,WAAW,IAAIuJ,EAAM,WAAW;AAAA,QACzC,aAAaY;AAAA,QACb,2BAAW,IAAI,CAACZ,EAAM,MAAM,KAAK,GAAG,CAAC,CAAC;AAAA,MAAA,CACvC,GACM,MAAMvJ,EAAW,WAAW,OAAOuJ,EAAM,SAAS;AAAA,IAC3D;AAAA,IACA,MAAM7M,EAAe,WAAW,eAAe6M,EAAM,WAAWA,EAAM,KAAK;AAAA,EAC7E;AACA,SAAOnD,EAAc,QAAQ,CAAI,GAAA,OAAO8B,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 getNestedValue,\r\n isFunction,\r\n updateNestedProperty,\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 { boolean, 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 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 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 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 }) => void;\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 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 localStorageKey?: string;\r\n initState?: {\r\n ctx?: Record<string, any>;\r\n initialState: T;\r\n dependencies?: any[]; // Just like useEffect dependencies\r\n };\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?: Opt;\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 mergedOptions[key] = options[key as keyof typeof options];\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 // Apply form elements with global as defaults\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 initState: options?.initState,\r\n localStorageKey: options?.localStorageKey,\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.localStorageKey) {\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 = currentInitialOptions.initState\r\n ? `${sessionId}-${thisKey}-${currentInitialOptions.localStorageKey}`\r\n : thisKey;\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 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 localStorageKey,\r\n initState,\r\n syncUpdate,\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 initState,\r\n });\r\n let localData = null;\r\n if (localStorageKey) {\r\n localData = loadFromLocalStorage(\r\n sessionId + \"-\" + thisKey + \"-\" + localStorageKey\r\n );\r\n }\r\n let newState = null;\r\n if (initState?.initialState) {\r\n newState = initState?.initialState;\r\n console.log(\"newState\", newState);\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 initState?.initialState,\r\n newState,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n console.log(\"newState222\", newState);\r\n forceUpdate({});\r\n }\r\n }, [localStorageKey, ...(initState?.dependencies || [])]);\r\n\r\n useLayoutEffect(() => {\r\n if (noStateKey) {\r\n setAndMergeOptions(thisKey as string, {\r\n serverSync,\r\n formElements,\r\n initState,\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 if (stateKey == \"cart\") {\r\n console.log(\"thisKey\", thisKey);\r\n console.log(\"stateEntry\", stateEntry);\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 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 console.log(\"Initializing state for\", thisKey, stateObject); // Debug log\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 selectedIndexMap = new Map<string, number>();\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\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 const initalOptionsGet = getInitialOptions(stateKey as string);\r\n if (initalOptionsGet?.localStorageKey) {\r\n localStorage.removeItem(\r\n initalOptionsGet?.initState\r\n ? sessionId +\r\n \"-\" +\r\n stateKey +\r\n \"-\" +\r\n initalOptionsGet?.localStorageKey\r\n : stateKey\r\n );\r\n }\r\n localStorage.removeItem(stateKey);\r\n });\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 localStorage.removeItem(stateKey);\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\r\n const handler = {\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 === \"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 = selectedIndexMap.get(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\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\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 return rebuildStateShape(filteredArray as any, path, {\r\n filtered: [...(meta?.filtered || []), path],\r\n validIndices, // Pass through the meta\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 === \"_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 currentIndex === selectedIndexMap.get(parentKey);\r\n }\r\n return undefined;\r\n }\r\n if (prop == \"getLocalStorage\") {\r\n return (key: string) =>\r\n loadFromLocalStorage(sessionId + \"-\" + stateKey + \"-\" + key);\r\n }\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 if (value) {\r\n selectedIndexMap.set(parentKey, thisIndex);\r\n } else {\r\n // Optional: clear selection if false\r\n selectedIndexMap.delete(parentKey);\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 // ADDED: Invalidate cache for parent path\r\n invalidateCachePath(parentPath);\r\n };\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 console.log(\r\n `Validation error at ${fullErrorPath}: ${errorMessage}`\r\n );\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(baseObj as StateObject<T>, 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 console.log(\"value\", value);\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","data","storageKey","updateGlobalState","newState","effectiveSetState","updates","createProxyHandler","startTransition","notifyComponents","stateEntry","component","update","notifyComponent","fullComponentId","stateObject","serverSync","localStorage","middleware","reactiveDeps","reactiveType","initState","syncUpdate","reactiveForce","forceUpdate","useCogsConfig","noStateKey","stateLog","componentUpdatesRef","useRef","componentIdRef","latestInitialOptionsRef","useEffect","prevState","syncKey","localData","useLayoutEffect","depsKey","newStateOrFunction","path","updateObj","validationKey","pathKey","prevValue","payload","isFunction","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","selectedIndexMap","baseObj","obj","init","newProxy","rebuildStateShape","initalOptionsGet","newUpdaterState","field","serverState","currentState","meta","cacheKey","handler","target","prop","currentPath","selectedIndex","callbackfn","isFiltered","p","arrayToMap","val","index","thisIndex","elementProxy","createElement","SignalMapRenderer","fieldName","flattenedResults","thisValue","foundIndex","foundValue","newPath","indexValue","pushFunc","fields","onMatch","currentArray","matchedItem","item","isMatch","updatedItem","updatedArray","updateFn","cutFunc","newVal","i","validIndices","filteredArray","lastPathElement","parentPath","parentValue","fn","$cogsSignal","parentKey","value","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":";;;;;;;;;AA8XA,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,GAAkBF,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,MACvBD,IAAA,IACED,EAAAE,CAAG,IAAIL,EAAQK,CAA2B;AAI9D,EAAID,KACFP,EAAuBJ,GAAoBU,CAAa;AAE5D;AACO,SAASG,GACdC,GACA,EAAE,cAAAC,GAAc,YAAAC,KAChB;AACO,SAAA,EAAE,cAAAF,GAA4B,cAAAC,GAAc,YAAAC,EAAW;AAChE;AAEa,MAAAC,KAAkB,CAC7BH,GACAI,MACG;AACH,MAAIC,IAAkBL;AAGtB,QAAM,CAACM,GAAWZ,CAAkB,IAClCa,GAA0BF,CAAe;AAGvC,GAAAD,GAAK,gBAAgBA,GAAK,eAC5B,OAAO,KAAKV,CAAkB,EAAE,QAAQ,CAACI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