cogsbox-state 0.5.87 → 0.5.89
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.jsx +199 -188
- package/dist/CogsState.jsx.map +1 -1
- package/package.json +1 -1
package/dist/CogsState.jsx
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { jsx as
|
|
3
|
-
import { useState as et, useRef as Z, useEffect as nt, useLayoutEffect as
|
|
4
|
-
import { transformStateFunc as
|
|
5
|
-
import { pushFunc as K, updateFn as B, cutFunc as J, ValidationWrapper as
|
|
2
|
+
import { jsx as lt } from "react/jsx-runtime";
|
|
3
|
+
import { useState as et, useRef as Z, useEffect as nt, useLayoutEffect as _t, useMemo as Et, createElement as Q, useSyncExternalStore as $t, startTransition as H } from "react";
|
|
4
|
+
import { transformStateFunc as wt, isFunction as D, getNestedValue as U, isDeepEqual as M, debounce as Nt } from "./utility.js";
|
|
5
|
+
import { pushFunc as K, updateFn as B, cutFunc as J, ValidationWrapper as Vt, FormControlComponent as At } from "./Functions.jsx";
|
|
6
6
|
import "zod";
|
|
7
|
-
import { getGlobalStore as r, formRefStore as
|
|
8
|
-
import { useCogsConfig as
|
|
7
|
+
import { getGlobalStore as r, formRefStore as dt } from "./store.js";
|
|
8
|
+
import { useCogsConfig as pt } from "./CogsStateClient.jsx";
|
|
9
9
|
import rt from "./node_modules/uuid/dist/esm-browser/v4.js";
|
|
10
|
-
function
|
|
11
|
-
const m = r.getState().getInitialOptions, y = r.getState().setInitialStateOptions,
|
|
10
|
+
function ut(t, i) {
|
|
11
|
+
const m = r.getState().getInitialOptions, y = r.getState().setInitialStateOptions, g = m(t) || {};
|
|
12
12
|
y(t, {
|
|
13
|
-
...
|
|
13
|
+
...g,
|
|
14
14
|
...i
|
|
15
15
|
});
|
|
16
16
|
}
|
|
17
|
-
function
|
|
17
|
+
function gt({
|
|
18
18
|
stateKey: t,
|
|
19
19
|
options: i,
|
|
20
20
|
initialOptionsPart: m
|
|
21
21
|
}) {
|
|
22
|
-
const y = q(t) || {},
|
|
22
|
+
const y = q(t) || {}, g = m[t] || {}, $ = r.getState().setInitialStateOptions, _ = { ...g, ...y };
|
|
23
23
|
let v = !1;
|
|
24
24
|
if (i)
|
|
25
25
|
for (const l in i)
|
|
@@ -31,26 +31,26 @@ function qt(t, { formElements: i, validation: m }) {
|
|
|
31
31
|
}
|
|
32
32
|
const zt = (t, i) => {
|
|
33
33
|
let m = t;
|
|
34
|
-
const [y,
|
|
35
|
-
(Object.keys(
|
|
36
|
-
|
|
34
|
+
const [y, g] = wt(m);
|
|
35
|
+
(Object.keys(g).length > 0 || i && Object.keys(i).length > 0) && Object.keys(g).forEach((v) => {
|
|
36
|
+
g[v] = g[v] || {}, g[v].formElements = {
|
|
37
37
|
...i?.formElements,
|
|
38
38
|
// Global defaults first
|
|
39
39
|
...i?.validation,
|
|
40
|
-
...
|
|
40
|
+
...g[v].formElements || {}
|
|
41
41
|
// State-specific overrides
|
|
42
42
|
};
|
|
43
43
|
const l = q(v);
|
|
44
|
-
console.log("existingOptions", l,
|
|
44
|
+
console.log("existingOptions", l, g[v]), l || r.getState().setInitialStateOptions(v, g[v]);
|
|
45
45
|
}), r.getState().setInitialStates(y);
|
|
46
46
|
const $ = (v, l) => {
|
|
47
47
|
const [f] = et(l?.componentId ?? rt());
|
|
48
|
-
|
|
48
|
+
gt({
|
|
49
49
|
stateKey: v,
|
|
50
50
|
options: l,
|
|
51
|
-
initialOptionsPart:
|
|
51
|
+
initialOptionsPart: g
|
|
52
52
|
});
|
|
53
|
-
const e = r.getState().cogsStateStore[v] || y[v], S = l?.modifyState ? l.modifyState(e) : e, [
|
|
53
|
+
const e = r.getState().cogsStateStore[v] || y[v], S = l?.modifyState ? l.modifyState(e) : e, [C, V] = Tt(
|
|
54
54
|
S,
|
|
55
55
|
{
|
|
56
56
|
stateKey: v,
|
|
@@ -65,24 +65,24 @@ const zt = (t, i) => {
|
|
|
65
65
|
dependencies: l?.dependencies
|
|
66
66
|
}
|
|
67
67
|
);
|
|
68
|
-
return
|
|
68
|
+
return V;
|
|
69
69
|
};
|
|
70
70
|
function _(v, l) {
|
|
71
|
-
|
|
71
|
+
gt({ stateKey: v, options: l, initialOptionsPart: g });
|
|
72
72
|
}
|
|
73
73
|
return { useCogsState: $, setCogsOptions: _ };
|
|
74
74
|
}, {
|
|
75
75
|
setUpdaterState: Y,
|
|
76
|
-
setState:
|
|
76
|
+
setState: L,
|
|
77
77
|
getInitialOptions: q,
|
|
78
|
-
getKeyState:
|
|
79
|
-
getValidationErrors:
|
|
80
|
-
setStateLog:
|
|
81
|
-
updateInitialStateGlobal:
|
|
82
|
-
addValidationError:
|
|
78
|
+
getKeyState: St,
|
|
79
|
+
getValidationErrors: xt,
|
|
80
|
+
setStateLog: ht,
|
|
81
|
+
updateInitialStateGlobal: at,
|
|
82
|
+
addValidationError: kt,
|
|
83
83
|
removeValidationError: P,
|
|
84
|
-
setServerSyncActions:
|
|
85
|
-
} = r.getState(),
|
|
84
|
+
setServerSyncActions: Ct
|
|
85
|
+
} = r.getState(), mt = (t) => {
|
|
86
86
|
if (!t) return null;
|
|
87
87
|
try {
|
|
88
88
|
const i = window.localStorage.getItem(t);
|
|
@@ -90,38 +90,38 @@ const zt = (t, i) => {
|
|
|
90
90
|
} catch (i) {
|
|
91
91
|
return console.error("Error loading from localStorage:", i), null;
|
|
92
92
|
}
|
|
93
|
-
},
|
|
93
|
+
}, Ot = (t, i, m, y) => {
|
|
94
94
|
m?.log && console.log(
|
|
95
95
|
"saving to localstorage",
|
|
96
96
|
i,
|
|
97
97
|
m.localStorage?.key,
|
|
98
98
|
y
|
|
99
99
|
);
|
|
100
|
-
const
|
|
101
|
-
if (
|
|
100
|
+
const g = D(m?.localStorage?.key) ? m.localStorage?.key(t) : m?.localStorage?.key;
|
|
101
|
+
if (g && y) {
|
|
102
102
|
const $ = {
|
|
103
103
|
state: t,
|
|
104
104
|
lastUpdated: Date.now(),
|
|
105
105
|
lastSyncedWithServer: r.getState().serverSyncLog[i]?.[0]?.timeStamp,
|
|
106
106
|
baseServerState: r.getState().serverState[i]
|
|
107
|
-
}, _ = `${y}-${i}-${
|
|
107
|
+
}, _ = `${y}-${i}-${g}`;
|
|
108
108
|
window.localStorage.setItem(_, JSON.stringify($));
|
|
109
109
|
}
|
|
110
|
-
},
|
|
110
|
+
}, ft = (t, i, m, y, g, $) => {
|
|
111
111
|
const _ = {
|
|
112
112
|
initialState: i,
|
|
113
113
|
updaterState: X(
|
|
114
114
|
t,
|
|
115
115
|
y,
|
|
116
|
-
|
|
116
|
+
g,
|
|
117
117
|
$
|
|
118
118
|
),
|
|
119
119
|
state: m
|
|
120
120
|
};
|
|
121
121
|
H(() => {
|
|
122
|
-
|
|
122
|
+
at(t, _.initialState), Y(t, _.updaterState), L(t, _.state);
|
|
123
123
|
});
|
|
124
|
-
},
|
|
124
|
+
}, ot = (t) => {
|
|
125
125
|
const i = r.getState().stateComponents.get(t);
|
|
126
126
|
if (!i) return;
|
|
127
127
|
const m = /* @__PURE__ */ new Set();
|
|
@@ -135,15 +135,15 @@ const zt = (t, i) => {
|
|
|
135
135
|
}, Bt = (t, i) => {
|
|
136
136
|
const m = r.getState().stateComponents.get(t);
|
|
137
137
|
if (m) {
|
|
138
|
-
const y = `${t}////${i}`,
|
|
139
|
-
|
|
138
|
+
const y = `${t}////${i}`, g = m.components.get(y);
|
|
139
|
+
g && g.forceUpdate();
|
|
140
140
|
}
|
|
141
141
|
};
|
|
142
142
|
function Tt(t, {
|
|
143
143
|
stateKey: i,
|
|
144
144
|
serverSync: m,
|
|
145
145
|
localStorage: y,
|
|
146
|
-
formElements:
|
|
146
|
+
formElements: g,
|
|
147
147
|
middleware: $,
|
|
148
148
|
reactiveDeps: _,
|
|
149
149
|
reactiveType: v,
|
|
@@ -152,12 +152,12 @@ function Tt(t, {
|
|
|
152
152
|
syncUpdate: e,
|
|
153
153
|
dependencies: S
|
|
154
154
|
} = {}) {
|
|
155
|
-
const [
|
|
155
|
+
const [C, V] = et({}), { sessionId: k } = pt();
|
|
156
156
|
let R = !i;
|
|
157
|
-
const [
|
|
158
|
-
x.current = q(
|
|
159
|
-
if (e && e.stateKey ===
|
|
160
|
-
|
|
157
|
+
const [d] = et(i ?? rt()), s = r.getState().stateLog[d], G = Z(/* @__PURE__ */ new Set()), j = Z(l ?? rt()), x = Z(null);
|
|
158
|
+
x.current = q(d), nt(() => {
|
|
159
|
+
if (e && e.stateKey === d && e.path?.[0]) {
|
|
160
|
+
L(d, (o) => ({
|
|
161
161
|
...o,
|
|
162
162
|
[e.path[0]]: e.newValue
|
|
163
163
|
}));
|
|
@@ -168,137 +168,148 @@ function Tt(t, {
|
|
|
168
168
|
});
|
|
169
169
|
}
|
|
170
170
|
}, [e]), nt(() => {
|
|
171
|
-
|
|
171
|
+
ut(d, {
|
|
172
172
|
initialState: f
|
|
173
173
|
});
|
|
174
174
|
const c = x.current;
|
|
175
175
|
let o = null;
|
|
176
|
-
const
|
|
177
|
-
c?.log && (console.log("newoptions", c), console.log("localkey",
|
|
178
|
-
|
|
179
|
-
)
|
|
176
|
+
const u = D(c?.localStorage?.key) ? c?.localStorage?.key(f) : c?.localStorage?.key;
|
|
177
|
+
c?.log && (console.log("newoptions", c), console.log("localkey", u), console.log("initialState", f)), u && k && (o = mt(
|
|
178
|
+
k + "-" + d + "-" + u
|
|
179
|
+
), f || (c?.log && console.log(
|
|
180
|
+
"localData",
|
|
181
|
+
o,
|
|
182
|
+
k + "-" + d + "-" + u
|
|
183
|
+
), ft(
|
|
184
|
+
d,
|
|
185
|
+
f,
|
|
186
|
+
o,
|
|
187
|
+
n,
|
|
188
|
+
j.current,
|
|
189
|
+
k
|
|
190
|
+
), ot(d), V({})));
|
|
180
191
|
let E = null;
|
|
181
|
-
f && (E = f, o && o.lastUpdated > (o.lastSyncedWithServer || 0) && (E = o.state),
|
|
182
|
-
|
|
192
|
+
f && (E = f, o && o.lastUpdated > (o.lastSyncedWithServer || 0) && (E = o.state), ft(
|
|
193
|
+
d,
|
|
183
194
|
f,
|
|
184
195
|
E,
|
|
185
196
|
n,
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
),
|
|
189
|
-
}, [f, ...S || []]),
|
|
190
|
-
R &&
|
|
197
|
+
j.current,
|
|
198
|
+
k
|
|
199
|
+
), ot(d), V({}));
|
|
200
|
+
}, [f, ...S || []]), _t(() => {
|
|
201
|
+
R && ut(d, {
|
|
191
202
|
serverSync: m,
|
|
192
|
-
formElements:
|
|
203
|
+
formElements: g,
|
|
193
204
|
initialState: f,
|
|
194
205
|
localStorage: y,
|
|
195
206
|
middleware: $
|
|
196
207
|
});
|
|
197
|
-
const c = `${
|
|
208
|
+
const c = `${d}////${j.current}`, o = r.getState().stateComponents.get(d) || {
|
|
198
209
|
components: /* @__PURE__ */ new Map()
|
|
199
210
|
};
|
|
200
211
|
return o.components.set(c, {
|
|
201
|
-
forceUpdate: () =>
|
|
212
|
+
forceUpdate: () => V({}),
|
|
202
213
|
paths: /* @__PURE__ */ new Set(),
|
|
203
214
|
deps: [],
|
|
204
215
|
depsFunction: _ || void 0,
|
|
205
216
|
reactiveType: v ?? ["component", "deps"]
|
|
206
|
-
}), r.getState().stateComponents.set(
|
|
207
|
-
const
|
|
208
|
-
o && (o.components.delete(
|
|
217
|
+
}), r.getState().stateComponents.set(d, o), V({}), () => {
|
|
218
|
+
const u = `${d}////${j.current}`;
|
|
219
|
+
o && (o.components.delete(u), o.components.size === 0 && r.getState().stateComponents.delete(d));
|
|
209
220
|
};
|
|
210
221
|
}, []);
|
|
211
|
-
const n = (c, o,
|
|
222
|
+
const n = (c, o, u, E) => {
|
|
212
223
|
if (Array.isArray(o)) {
|
|
213
|
-
const O = `${
|
|
224
|
+
const O = `${d}-${o.join(".")}`;
|
|
214
225
|
G.current.add(O);
|
|
215
226
|
}
|
|
216
|
-
|
|
217
|
-
const N =
|
|
218
|
-
if (
|
|
219
|
-
let F = !1, I = r.getState().signalDomElements.get(
|
|
220
|
-
if ((!I || I.size === 0) && (
|
|
221
|
-
const
|
|
227
|
+
L(d, (O) => {
|
|
228
|
+
const N = D(c) ? c(O) : c, b = `${d}-${o.join(".")}`;
|
|
229
|
+
if (b) {
|
|
230
|
+
let F = !1, I = r.getState().signalDomElements.get(b);
|
|
231
|
+
if ((!I || I.size === 0) && (u.updateType === "insert" || u.updateType === "cut")) {
|
|
232
|
+
const A = o.slice(0, -1), p = U(N, A);
|
|
222
233
|
if (Array.isArray(p)) {
|
|
223
234
|
F = !0;
|
|
224
|
-
const w = `${
|
|
235
|
+
const w = `${d}-${A.join(".")}`;
|
|
225
236
|
I = r.getState().signalDomElements.get(w);
|
|
226
237
|
}
|
|
227
238
|
}
|
|
228
239
|
if (I) {
|
|
229
|
-
const
|
|
240
|
+
const A = F ? U(N, o.slice(0, -1)) : U(N, o);
|
|
230
241
|
I.forEach(({ parentId: p, position: w, effect: W }) => {
|
|
231
242
|
const T = document.querySelector(
|
|
232
243
|
`[data-parent-id="${p}"]`
|
|
233
244
|
);
|
|
234
245
|
if (T) {
|
|
235
|
-
const
|
|
236
|
-
if (
|
|
237
|
-
const
|
|
238
|
-
|
|
246
|
+
const ct = Array.from(T.childNodes);
|
|
247
|
+
if (ct[w]) {
|
|
248
|
+
const It = W ? new Function("state", `return (${W})(state)`)(A) : A;
|
|
249
|
+
ct[w].textContent = String(It);
|
|
239
250
|
}
|
|
240
251
|
}
|
|
241
252
|
});
|
|
242
253
|
}
|
|
243
254
|
}
|
|
244
|
-
|
|
255
|
+
u.updateType === "update" && (E || x.current?.validationKey) && o && P(
|
|
245
256
|
(E || x.current?.validationKey) + "." + o.join(".")
|
|
246
257
|
);
|
|
247
258
|
const h = o.slice(0, o.length - 1);
|
|
248
|
-
|
|
259
|
+
u.updateType === "cut" && x.current?.validationKey && P(
|
|
249
260
|
x.current?.validationKey + "." + h.join(".")
|
|
250
|
-
),
|
|
261
|
+
), u.updateType === "insert" && x.current?.validationKey && xt(
|
|
251
262
|
x.current?.validationKey + "." + h.join(".")
|
|
252
|
-
).filter(([I,
|
|
263
|
+
).filter(([I, A]) => {
|
|
253
264
|
let p = I?.split(".").length;
|
|
254
265
|
if (I == h.join(".") && p == h.length - 1) {
|
|
255
266
|
let w = I + "." + h;
|
|
256
|
-
P(I),
|
|
267
|
+
P(I), kt(w, A);
|
|
257
268
|
}
|
|
258
269
|
});
|
|
259
|
-
const z = U(O, o),
|
|
260
|
-
if (
|
|
261
|
-
for (const [F, I] of
|
|
262
|
-
let
|
|
270
|
+
const z = U(O, o), yt = U(N, o), vt = u.updateType === "update" ? o.join(".") : [...o].slice(0, -1).join("."), it = r.getState().stateComponents.get(d);
|
|
271
|
+
if (it)
|
|
272
|
+
for (const [F, I] of it.components.entries()) {
|
|
273
|
+
let A = !1;
|
|
263
274
|
const p = Array.isArray(I.reactiveType) ? I.reactiveType : [I.reactiveType || "component"];
|
|
264
275
|
if (!p.includes("none")) {
|
|
265
276
|
if (p.includes("all")) {
|
|
266
277
|
I.forceUpdate();
|
|
267
278
|
continue;
|
|
268
279
|
}
|
|
269
|
-
if (p.includes("component") && I.paths && (I.paths.has(
|
|
280
|
+
if (p.includes("component") && I.paths && (I.paths.has(vt) || I.paths.has("")) && (A = !0), !A && p.includes("deps") && I.depsFunction) {
|
|
270
281
|
const w = I.depsFunction(N);
|
|
271
|
-
typeof w == "boolean" ? w && (
|
|
282
|
+
typeof w == "boolean" ? w && (A = !0) : M(I.deps, w) || (I.deps = w, A = !0);
|
|
272
283
|
}
|
|
273
|
-
|
|
284
|
+
A && I.forceUpdate();
|
|
274
285
|
}
|
|
275
286
|
}
|
|
276
|
-
const
|
|
287
|
+
const st = {
|
|
277
288
|
timeStamp: Date.now(),
|
|
278
|
-
stateKey:
|
|
289
|
+
stateKey: d,
|
|
279
290
|
path: o,
|
|
280
|
-
updateType:
|
|
291
|
+
updateType: u.updateType,
|
|
281
292
|
status: "new",
|
|
282
293
|
oldValue: z,
|
|
283
|
-
newValue:
|
|
294
|
+
newValue: yt
|
|
284
295
|
};
|
|
285
|
-
if (
|
|
286
|
-
const
|
|
296
|
+
if (ht(d, (F) => {
|
|
297
|
+
const A = [...F ?? [], st].reduce((p, w) => {
|
|
287
298
|
const W = `${w.stateKey}:${JSON.stringify(w.path)}`, T = p.get(W);
|
|
288
299
|
return T ? (T.timeStamp = Math.max(T.timeStamp, w.timeStamp), T.newValue = w.newValue, T.oldValue = T.oldValue ?? w.oldValue, T.updateType = w.updateType) : p.set(W, { ...w }), p;
|
|
289
300
|
}, /* @__PURE__ */ new Map());
|
|
290
|
-
return Array.from(
|
|
291
|
-
}),
|
|
301
|
+
return Array.from(A.values());
|
|
302
|
+
}), Ot(
|
|
292
303
|
N,
|
|
293
|
-
|
|
304
|
+
d,
|
|
294
305
|
x.current,
|
|
295
|
-
|
|
306
|
+
k
|
|
296
307
|
), $ && $({
|
|
297
308
|
updateLog: s,
|
|
298
|
-
update:
|
|
309
|
+
update: st
|
|
299
310
|
}), x.current?.serverSync) {
|
|
300
|
-
const F = r.getState().serverState[
|
|
301
|
-
|
|
311
|
+
const F = r.getState().serverState[d], I = x.current?.serverSync;
|
|
312
|
+
Ct(d, {
|
|
302
313
|
syncKey: typeof I.syncKey == "string" ? I.syncKey : I.syncKey({ state: N }),
|
|
303
314
|
rollBackState: F,
|
|
304
315
|
actionTimeStamp: Date.now() + (I.debounce ?? 3e3),
|
|
@@ -308,30 +319,30 @@ function Tt(t, {
|
|
|
308
319
|
return N;
|
|
309
320
|
});
|
|
310
321
|
};
|
|
311
|
-
r.getState().updaterState[
|
|
312
|
-
|
|
322
|
+
r.getState().updaterState[d] || (Y(
|
|
323
|
+
d,
|
|
313
324
|
X(
|
|
314
|
-
|
|
325
|
+
d,
|
|
315
326
|
n,
|
|
316
|
-
|
|
317
|
-
|
|
327
|
+
j.current,
|
|
328
|
+
k
|
|
318
329
|
)
|
|
319
|
-
), r.getState().cogsStateStore[
|
|
320
|
-
const a =
|
|
321
|
-
|
|
330
|
+
), r.getState().cogsStateStore[d] || L(d, t), r.getState().initialStateGlobal[d] || at(d, t));
|
|
331
|
+
const a = Et(() => X(
|
|
332
|
+
d,
|
|
322
333
|
n,
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
), [
|
|
326
|
-
return [
|
|
334
|
+
j.current,
|
|
335
|
+
k
|
|
336
|
+
), [d]);
|
|
337
|
+
return [St(d), a];
|
|
327
338
|
}
|
|
328
339
|
function X(t, i, m, y) {
|
|
329
|
-
const
|
|
340
|
+
const g = /* @__PURE__ */ new Map();
|
|
330
341
|
let $ = 0;
|
|
331
342
|
const _ = (f) => {
|
|
332
343
|
const e = f.join(".");
|
|
333
|
-
for (const [S] of
|
|
334
|
-
(S === e || S.startsWith(e + ".")) &&
|
|
344
|
+
for (const [S] of g)
|
|
345
|
+
(S === e || S.startsWith(e + ".")) && g.delete(S);
|
|
335
346
|
$++;
|
|
336
347
|
}, v = {
|
|
337
348
|
removeValidation: (f) => {
|
|
@@ -341,18 +352,18 @@ function X(t, i, m, y) {
|
|
|
341
352
|
const e = r.getState().getInitialOptions(t)?.validation;
|
|
342
353
|
e?.key && P(e?.key), f?.validationKey && P(f.validationKey);
|
|
343
354
|
const S = r.getState().initialStateGlobal[t];
|
|
344
|
-
|
|
345
|
-
const
|
|
355
|
+
g.clear(), $++;
|
|
356
|
+
const C = l(S, []), V = q(t), k = D(V?.localStorage?.key) ? V?.localStorage?.key(S) : V?.localStorage?.key, R = `${y}-${t}-${k}`;
|
|
346
357
|
return R && localStorage.removeItem(R), H(() => {
|
|
347
|
-
Y(t,
|
|
348
|
-
const
|
|
349
|
-
|
|
358
|
+
Y(t, C), L(t, S);
|
|
359
|
+
const d = r.getState().stateComponents.get(t);
|
|
360
|
+
d && d.components.forEach((s) => {
|
|
350
361
|
s.forceUpdate();
|
|
351
362
|
});
|
|
352
363
|
}), S;
|
|
353
364
|
},
|
|
354
365
|
updateInitialState: (f) => {
|
|
355
|
-
|
|
366
|
+
g.clear(), $++;
|
|
356
367
|
const e = X(
|
|
357
368
|
t,
|
|
358
369
|
i,
|
|
@@ -360,10 +371,10 @@ function X(t, i, m, y) {
|
|
|
360
371
|
y
|
|
361
372
|
);
|
|
362
373
|
return H(() => {
|
|
363
|
-
|
|
374
|
+
at(t, f), Y(t, e), L(t, f);
|
|
364
375
|
const S = r.getState().stateComponents.get(t);
|
|
365
|
-
S && S.components.forEach((
|
|
366
|
-
|
|
376
|
+
S && S.components.forEach((C) => {
|
|
377
|
+
C.forceUpdate();
|
|
367
378
|
});
|
|
368
379
|
}), {
|
|
369
380
|
fetchId: (S) => e.get()[S]
|
|
@@ -374,25 +385,25 @@ function X(t, i, m, y) {
|
|
|
374
385
|
_isLoading: r.getState().isLoadingGlobal[t],
|
|
375
386
|
_isServerSynced: () => {
|
|
376
387
|
const f = r.getState().serverState[t];
|
|
377
|
-
return !!(f && M(f,
|
|
388
|
+
return !!(f && M(f, St(t)));
|
|
378
389
|
}
|
|
379
390
|
};
|
|
380
391
|
function l(f, e = [], S) {
|
|
381
|
-
const
|
|
382
|
-
|
|
383
|
-
const
|
|
392
|
+
const C = e.map(String).join(".");
|
|
393
|
+
g.get(C);
|
|
394
|
+
const V = function() {
|
|
384
395
|
return r().getNestedState(t, e);
|
|
385
396
|
};
|
|
386
|
-
Object.keys(v).forEach((
|
|
387
|
-
|
|
397
|
+
Object.keys(v).forEach((d) => {
|
|
398
|
+
V[d] = v[d];
|
|
388
399
|
});
|
|
389
|
-
const
|
|
390
|
-
apply(
|
|
400
|
+
const k = {
|
|
401
|
+
apply(d, s, G) {
|
|
391
402
|
return console.log(
|
|
392
403
|
`PROXY APPLY TRAP HIT: stateKey=${t}, path=${e.join(".")}`
|
|
393
404
|
), console.trace("Apply trap stack trace"), r().getNestedState(t, e);
|
|
394
405
|
},
|
|
395
|
-
get(
|
|
406
|
+
get(d, s) {
|
|
396
407
|
if (s !== "then" && !s.startsWith("$") && s !== "stateMapNoRender") {
|
|
397
408
|
const n = e.join("."), a = `${t}////${m}`, c = r.getState().stateComponents.get(t);
|
|
398
409
|
if (c) {
|
|
@@ -414,7 +425,7 @@ function X(t, i, m, y) {
|
|
|
414
425
|
};
|
|
415
426
|
if (s === "removeStorage")
|
|
416
427
|
return () => {
|
|
417
|
-
const n = r.getState().initialStateGlobal[t], a = q(t), c =
|
|
428
|
+
const n = r.getState().initialStateGlobal[t], a = q(t), c = D(a?.localStorage?.key) ? a?.localStorage?.key(n) : a?.localStorage?.key, o = `${y}-${t}-${c}`;
|
|
418
429
|
console.log("removing storage", o), o && localStorage.removeItem(o);
|
|
419
430
|
};
|
|
420
431
|
if (s === "showValidationErrors")
|
|
@@ -439,14 +450,14 @@ function X(t, i, m, y) {
|
|
|
439
450
|
return () => r.getState().getSelectedIndex(t, e.join(".")) ?? -1;
|
|
440
451
|
if (s === "stateSort")
|
|
441
452
|
return (n) => {
|
|
442
|
-
const o = [...r.getState().getNestedState(t, e).map((
|
|
443
|
-
...
|
|
453
|
+
const o = [...r.getState().getNestedState(t, e).map((u, E) => ({
|
|
454
|
+
...u,
|
|
444
455
|
__origIndex: E.toString()
|
|
445
456
|
}))].sort(n);
|
|
446
|
-
return
|
|
457
|
+
return g.clear(), $++, l(o, e, {
|
|
447
458
|
filtered: [...S?.filtered || [], e],
|
|
448
459
|
validIndices: o.map(
|
|
449
|
-
(
|
|
460
|
+
(u) => parseInt(u.__origIndex)
|
|
450
461
|
)
|
|
451
462
|
});
|
|
452
463
|
};
|
|
@@ -455,8 +466,8 @@ function X(t, i, m, y) {
|
|
|
455
466
|
const a = S?.filtered?.some(
|
|
456
467
|
(o) => o.join(".") === e.join(".")
|
|
457
468
|
), c = a ? f : r.getState().getNestedState(t, e);
|
|
458
|
-
return s !== "stateMapNoRender" && (
|
|
459
|
-
const E = a && o.__origIndex ? o.__origIndex :
|
|
469
|
+
return s !== "stateMapNoRender" && (g.clear(), $++), c.map((o, u) => {
|
|
470
|
+
const E = a && o.__origIndex ? o.__origIndex : u, O = l(
|
|
460
471
|
o,
|
|
461
472
|
[...e, E.toString()],
|
|
462
473
|
S
|
|
@@ -464,7 +475,7 @@ function X(t, i, m, y) {
|
|
|
464
475
|
return n(
|
|
465
476
|
o,
|
|
466
477
|
O,
|
|
467
|
-
|
|
478
|
+
u,
|
|
468
479
|
f,
|
|
469
480
|
l(f, e, S)
|
|
470
481
|
);
|
|
@@ -483,11 +494,11 @@ function X(t, i, m, y) {
|
|
|
483
494
|
if (s === "stateFlattenOn")
|
|
484
495
|
return (n) => {
|
|
485
496
|
const c = S?.filtered?.some(
|
|
486
|
-
(
|
|
497
|
+
(u) => u.join(".") === e.join(".")
|
|
487
498
|
) ? f : r.getState().getNestedState(t, e);
|
|
488
|
-
|
|
499
|
+
g.clear(), $++;
|
|
489
500
|
const o = c.flatMap(
|
|
490
|
-
(
|
|
501
|
+
(u, E) => u[n] ?? []
|
|
491
502
|
);
|
|
492
503
|
return l(
|
|
493
504
|
o,
|
|
@@ -501,8 +512,8 @@ function X(t, i, m, y) {
|
|
|
501
512
|
(E) => E[n] === a
|
|
502
513
|
);
|
|
503
514
|
if (c === -1) return;
|
|
504
|
-
const o = f[c],
|
|
505
|
-
return
|
|
515
|
+
const o = f[c], u = [...e, c.toString()];
|
|
516
|
+
return g.clear(), $++, g.clear(), $++, l(o, u);
|
|
506
517
|
};
|
|
507
518
|
if (s === "index")
|
|
508
519
|
return (n) => {
|
|
@@ -516,24 +527,24 @@ function X(t, i, m, y) {
|
|
|
516
527
|
));
|
|
517
528
|
if (s === "uniqueInsert")
|
|
518
529
|
return (n, a, c) => {
|
|
519
|
-
const o = r.getState().getNestedState(t, e),
|
|
530
|
+
const o = r.getState().getNestedState(t, e), u = D(n) ? n(o) : n;
|
|
520
531
|
let E = null;
|
|
521
532
|
if (!o.some((N) => {
|
|
522
533
|
if (a) {
|
|
523
534
|
const h = a.every(
|
|
524
|
-
(z) => M(N[z],
|
|
535
|
+
(z) => M(N[z], u[z])
|
|
525
536
|
);
|
|
526
537
|
return h && (E = N), h;
|
|
527
538
|
}
|
|
528
|
-
const
|
|
529
|
-
return
|
|
539
|
+
const b = M(N, u);
|
|
540
|
+
return b && (E = N), b;
|
|
530
541
|
}))
|
|
531
|
-
_(e), K(i,
|
|
542
|
+
_(e), K(i, u, e, t);
|
|
532
543
|
else if (c && E) {
|
|
533
|
-
const N = c(E),
|
|
544
|
+
const N = c(E), b = o.map(
|
|
534
545
|
(h) => M(h, E) ? N : h
|
|
535
546
|
);
|
|
536
|
-
_(e), B(i,
|
|
547
|
+
_(e), B(i, b, e);
|
|
537
548
|
}
|
|
538
549
|
};
|
|
539
550
|
if (s === "cut")
|
|
@@ -552,13 +563,13 @@ function X(t, i, m, y) {
|
|
|
552
563
|
};
|
|
553
564
|
if (s === "stateFilter")
|
|
554
565
|
return (n) => {
|
|
555
|
-
const a = f.map((
|
|
556
|
-
...
|
|
566
|
+
const a = f.map((u, E) => ({
|
|
567
|
+
...u,
|
|
557
568
|
__origIndex: E.toString()
|
|
558
569
|
})), c = [], o = [];
|
|
559
|
-
for (let
|
|
560
|
-
n(a[
|
|
561
|
-
return
|
|
570
|
+
for (let u = 0; u < a.length; u++)
|
|
571
|
+
n(a[u], u) && (c.push(u), o.push(a[u]));
|
|
572
|
+
return g.clear(), $++, l(o, e, {
|
|
562
573
|
filtered: [...S?.filtered || [], e],
|
|
563
574
|
validIndices: c
|
|
564
575
|
// Always pass validIndices, even if empty
|
|
@@ -600,7 +611,7 @@ function X(t, i, m, y) {
|
|
|
600
611
|
return r.getState().getSyncInfo(n);
|
|
601
612
|
}
|
|
602
613
|
if (s == "getLocalStorage")
|
|
603
|
-
return (n) =>
|
|
614
|
+
return (n) => mt(y + "-" + t + "-" + n);
|
|
604
615
|
if (s === "_selected") {
|
|
605
616
|
const n = e.slice(0, -1), a = n.join("."), c = r.getState().getNestedState(t, n);
|
|
606
617
|
return Array.isArray(c) ? Number(e[e.length - 1]) === r.getState().getSelectedIndex(t, a) : void 0;
|
|
@@ -609,8 +620,8 @@ function X(t, i, m, y) {
|
|
|
609
620
|
return (n) => {
|
|
610
621
|
const a = e.slice(0, -1), c = Number(e[e.length - 1]), o = a.join(".");
|
|
611
622
|
n ? r.getState().setSelectedIndex(t, o, c) : r.getState().setSelectedIndex(t, o, void 0);
|
|
612
|
-
const
|
|
613
|
-
B(i,
|
|
623
|
+
const u = r.getState().getNestedState(t, [...a]);
|
|
624
|
+
B(i, u, a), _(a);
|
|
614
625
|
};
|
|
615
626
|
if (e.length == 0) {
|
|
616
627
|
if (s === "validateZodSchema")
|
|
@@ -627,11 +638,11 @@ function X(t, i, m, y) {
|
|
|
627
638
|
o && o.length > 0 && o.forEach(([E]) => {
|
|
628
639
|
E && E.startsWith(n.key) && P(E);
|
|
629
640
|
});
|
|
630
|
-
const
|
|
631
|
-
return
|
|
632
|
-
const N = O.path,
|
|
633
|
-
a(h,
|
|
634
|
-
}),
|
|
641
|
+
const u = n.zodSchema.safeParse(c);
|
|
642
|
+
return u.success ? !0 : (u.error.errors.forEach((O) => {
|
|
643
|
+
const N = O.path, b = O.message, h = [n.key, ...N].join(".");
|
|
644
|
+
a(h, b);
|
|
645
|
+
}), ot(t), !1);
|
|
635
646
|
} catch (o) {
|
|
636
647
|
return console.error("Zod schema validation failed", o), !1;
|
|
637
648
|
}
|
|
@@ -640,7 +651,7 @@ function X(t, i, m, y) {
|
|
|
640
651
|
if (s === "getComponents")
|
|
641
652
|
return () => r().stateComponents.get(t);
|
|
642
653
|
if (s === "getAllFormRefs")
|
|
643
|
-
return () =>
|
|
654
|
+
return () => dt.getState().getFormRefsByStateKey(t);
|
|
644
655
|
if (s === "_initialState")
|
|
645
656
|
return r.getState().initialStateGlobal[t];
|
|
646
657
|
if (s === "_serverState")
|
|
@@ -653,13 +664,13 @@ function X(t, i, m, y) {
|
|
|
653
664
|
if (s === "removeValidation") return v.removeValidation;
|
|
654
665
|
}
|
|
655
666
|
if (s === "getFormRef")
|
|
656
|
-
return () =>
|
|
667
|
+
return () => dt.getState().getFormRef(t + "." + e.join("."));
|
|
657
668
|
if (s === "validationWrapper")
|
|
658
669
|
return ({
|
|
659
670
|
children: n,
|
|
660
671
|
hideMessage: a
|
|
661
|
-
}) => /* @__PURE__ */
|
|
662
|
-
|
|
672
|
+
}) => /* @__PURE__ */ lt(
|
|
673
|
+
Vt,
|
|
663
674
|
{
|
|
664
675
|
formOpts: a ? { validation: { message: "" } } : void 0,
|
|
665
676
|
path: e,
|
|
@@ -675,7 +686,7 @@ function X(t, i, m, y) {
|
|
|
675
686
|
if (s === "update")
|
|
676
687
|
return (n, a) => {
|
|
677
688
|
if (a?.debounce)
|
|
678
|
-
|
|
689
|
+
Nt(() => {
|
|
679
690
|
B(i, n, e, "");
|
|
680
691
|
const c = r.getState().getNestedState(t, e);
|
|
681
692
|
a?.afterUpdate && a.afterUpdate(c);
|
|
@@ -688,8 +699,8 @@ function X(t, i, m, y) {
|
|
|
688
699
|
_(e);
|
|
689
700
|
};
|
|
690
701
|
if (s === "formElement")
|
|
691
|
-
return (n, a) => /* @__PURE__ */
|
|
692
|
-
|
|
702
|
+
return (n, a) => /* @__PURE__ */ lt(
|
|
703
|
+
At,
|
|
693
704
|
{
|
|
694
705
|
setState: i,
|
|
695
706
|
stateKey: t,
|
|
@@ -698,11 +709,11 @@ function X(t, i, m, y) {
|
|
|
698
709
|
formOpts: a
|
|
699
710
|
}
|
|
700
711
|
);
|
|
701
|
-
const
|
|
702
|
-
return l(x,
|
|
712
|
+
const j = [...e, s], x = r.getState().getNestedState(t, j);
|
|
713
|
+
return l(x, j, S);
|
|
703
714
|
}
|
|
704
|
-
}, R = new Proxy(
|
|
705
|
-
return
|
|
715
|
+
}, R = new Proxy(V, k);
|
|
716
|
+
return g.set(C, {
|
|
706
717
|
proxy: R,
|
|
707
718
|
stateVersion: $
|
|
708
719
|
}), R;
|
|
@@ -723,7 +734,7 @@ function jt({
|
|
|
723
734
|
m,
|
|
724
735
|
t._path
|
|
725
736
|
).stateMapNoRender(
|
|
726
|
-
(
|
|
737
|
+
(g, $, _, v, l) => t._mapFn(g, $, _, v, l)
|
|
727
738
|
) : null;
|
|
728
739
|
}
|
|
729
740
|
function bt({
|
|
@@ -733,9 +744,9 @@ function bt({
|
|
|
733
744
|
return nt(() => {
|
|
734
745
|
const y = i.current;
|
|
735
746
|
if (!y || !y.parentElement) return;
|
|
736
|
-
const
|
|
737
|
-
let v =
|
|
738
|
-
v || (v = `parent-${crypto.randomUUID()}`,
|
|
747
|
+
const g = y.parentElement, _ = Array.from(g.childNodes).indexOf(y);
|
|
748
|
+
let v = g.getAttribute("data-parent-id");
|
|
749
|
+
v || (v = `parent-${crypto.randomUUID()}`, g.setAttribute("data-parent-id", v));
|
|
739
750
|
const f = {
|
|
740
751
|
instanceId: `instance-${crypto.randomUUID()}`,
|
|
741
752
|
parentId: v,
|
|
@@ -751,14 +762,14 @@ function bt({
|
|
|
751
762
|
"state",
|
|
752
763
|
`return (${t._effect})(state)`
|
|
753
764
|
)(e);
|
|
754
|
-
} catch (
|
|
755
|
-
console.error("Error evaluating effect function during mount:",
|
|
765
|
+
} catch (V) {
|
|
766
|
+
console.error("Error evaluating effect function during mount:", V), S = e;
|
|
756
767
|
}
|
|
757
768
|
else
|
|
758
769
|
S = e;
|
|
759
770
|
S !== null && typeof S == "object" && (S = JSON.stringify(S));
|
|
760
|
-
const
|
|
761
|
-
y.replaceWith(
|
|
771
|
+
const C = document.createTextNode(String(S));
|
|
772
|
+
y.replaceWith(C);
|
|
762
773
|
}, [t._stateKey, t._path.join("."), t._effect]), Q("span", {
|
|
763
774
|
ref: i,
|
|
764
775
|
style: { display: "none" },
|
|
@@ -766,7 +777,7 @@ function bt({
|
|
|
766
777
|
});
|
|
767
778
|
}
|
|
768
779
|
function Jt(t) {
|
|
769
|
-
const i =
|
|
780
|
+
const i = $t(
|
|
770
781
|
(m) => {
|
|
771
782
|
const y = r.getState().stateComponents.get(t._stateKey) || {
|
|
772
783
|
components: /* @__PURE__ */ new Map()
|
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 getDifferences,\r\n getNestedValue,\r\n isFunction,\r\n type GenericObject,\r\n} from \"./utility.js\";\r\nimport {\r\n cutFunc,\r\n FormControlComponent,\r\n pushFunc,\r\n updateFn,\r\n ValidationWrapper,\r\n} from \"./Functions.js\";\r\nimport { isDeepEqual, transformStateFunc } from \"./utility.js\";\r\nimport type { UseMutationResult } from \"@tanstack/react-query\";\r\nimport { v4 as uuidv4 } from \"uuid\";\r\nimport { ZodArray, ZodObject, type ZodRawShape } from \"zod\";\r\n\r\nimport { formRefStore, getGlobalStore, type ComponentsType } from \"./store.js\";\r\nimport { useCogsConfig } from \"./CogsStateClient.js\";\r\n\r\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\r\n\r\nexport type ServerSyncStatus = {\r\n isFresh: boolean;\r\n isFreshTime: number;\r\n isStale: boolean;\r\n isStaleTime: number;\r\n isSyncing: boolean;\r\n isSyncingTime: number;\r\n};\r\n\r\nexport type SyncInfo = {\r\n timeStamp: number;\r\n userId: number;\r\n};\r\n\r\nexport type FormElementParams<T> = {\r\n get: () => T;\r\n\r\n set: UpdateType<T>;\r\n syncStatus: (SyncInfo & { date: Date }) | null;\r\n path: string[];\r\n validationErrors: () => string[];\r\n addValidationError: (message?: string) => void;\r\n\r\n inputProps: {\r\n ref?: React.RefObject<any>;\r\n value?: T extends boolean ? never : T;\r\n onChange?: (\r\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\r\n ) => void;\r\n onBlur?: () => void;\r\n };\r\n};\r\n\r\nexport type StateKeys = string;\r\n\r\ntype findWithFuncType<U> = (\r\n thisKey: keyof U,\r\n thisValue: U[keyof U]\r\n) => EndType<U> & StateObject<U>;\r\nexport type PushArgs<U> = (\r\n update:\r\n | Prettify<U>\r\n | ((prevState: NonNullable<Prettify<U>>[]) => NonNullable<Prettify<U>>),\r\n opts?: UpdateOpts<U>\r\n) => void;\r\n\r\ntype CutFunctionType = (\r\n index?: number,\r\n options?: { waitForSync?: boolean }\r\n) => void;\r\n\r\nexport type InferArrayElement<T> = T extends (infer U)[] ? U : never;\r\n\r\nexport type ArrayEndType<TShape extends unknown> = {\r\n findWith: findWithFuncType<InferArrayElement<TShape>>;\r\n index: (index: number) => StateObject<InferArrayElement<TShape>> & {\r\n insert: PushArgs<InferArrayElement<TShape>>;\r\n cut: CutFunctionType;\r\n _index: number;\r\n } & EndType<InferArrayElement<TShape>>;\r\n insert: PushArgs<InferArrayElement<TShape>>;\r\n cut: CutFunctionType;\r\n cutByValue: (value: string | number | boolean) => void;\r\n toggleByValue: (value: string | number | boolean) => void;\r\n stateSort: (\r\n compareFn: (\r\n a: InferArrayElement<TShape>,\r\n b: InferArrayElement<TShape>\r\n ) => number\r\n ) => ArrayEndType<TShape>;\r\n\r\n stateMapNoRender: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n $stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateFlattenOn: <K extends keyof InferArrayElement<TShape>>(\r\n field: K\r\n ) => StateObject<InferArrayElement<InferArrayElement<TShape>[K]>[]>;\r\n uniqueInsert: (\r\n payload: UpdateArg<InferArrayElement<TShape>>,\r\n fields?: (keyof InferArrayElement<TShape>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => void;\r\n stateFilter: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => void\r\n ) => ArrayEndType<TShape>;\r\n getSelected: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n getSelectedIndex: () => number;\r\n} & EndType<TShape> & {\r\n [K in keyof (any[] extends infer T ? T : never)]: never;\r\n };\r\n\r\nexport type UpdateType<T> = (\r\n payload: UpdateArg<Prettify<T>>,\r\n opts?: UpdateOpts<T>\r\n) => void;\r\nexport type FormOptsType = {\r\n key?: string;\r\n validation?: {\r\n hideMessage?: boolean;\r\n message?: string;\r\n stretch?: boolean;\r\n props?: GenericObject;\r\n disable?: boolean;\r\n };\r\n formElements?: boolean;\r\n debounceTime?: number;\r\n stateServerDifferences?: string[][];\r\n};\r\n\r\nexport type FormControl<T> = (obj: FormElementParams<T>) => JSX.Element;\r\n\r\nexport type UpdateArg<S> = S | ((prevState: S) => S);\r\nexport type UpdateOpts<T> = {\r\n afterUpdate?: (state: T) => void;\r\n debounce?: number;\r\n};\r\nexport type ObjectEndType<T> = EndType<T> & {\r\n [K in keyof T]-?: ObjectEndType<T[K]>;\r\n} & {\r\n stateObject: (callbackfn: (value: T, setter: StateObject<T>) => void) => any;\r\n delete: () => void;\r\n};\r\ntype EffectFunction<T, R> = (state: T) => R;\r\nexport type EndType<T, IsArrayElement = false> = {\r\n update: UpdateType<T>;\r\n _path: string[];\r\n _stateKey: string;\r\n formElement: (control: FormControl<T>, opts?: FormOptsType) => JSX.Element;\r\n get: () => T;\r\n $get: () => T;\r\n $derive: <R>(fn: EffectFunction<T, R>) => R;\r\n _status: \"fresh\" | \"stale\" | \"synced\";\r\n getStatus: () => \"fresh\" | \"stale\";\r\n showValidationErrors: () => string[];\r\n setValidation: (ctx: string) => void;\r\n removeValidation: (ctx: string) => void;\r\n ignoreFields: (fields: string[]) => StateObject<T>;\r\n _selected: boolean;\r\n setSelected: (value: boolean) => void;\r\n getFormRef: () => React.RefObject<any> | undefined;\r\n removeStorage: () => void;\r\n validationWrapper: ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => JSX.Element;\r\n lastSynced?: SyncInfo;\r\n} & (IsArrayElement extends true ? { cut: () => void } : {}) & {\r\n [K in keyof (any extends infer T ? T : never)]: never;\r\n };\r\n\r\nexport type StateObject<T> = (T extends any[]\r\n ? ArrayEndType<T>\r\n : T extends Record<string, unknown> | object\r\n ? { [K in keyof T]-?: StateObject<T[K]> } & ObjectEndType<T>\r\n : T extends string | number | boolean | null\r\n ? T\r\n : never) &\r\n EndType<T, true> & {\r\n getAllFormRefs: () => Map<string, React.RefObject<any>>;\r\n _componentId: string | null;\r\n getComponents: () => ComponentsType;\r\n validateZodSchema: () => void;\r\n _initialState: T;\r\n updateInitialState: (newState: T | null) => {\r\n fetchId: (field: keyof T) => string | number;\r\n };\r\n _isLoading: boolean;\r\n _serverState: T;\r\n revertToInitialState: (obj?: { validationKey?: string }) => T;\r\n middleware: (\r\n middles: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void\r\n ) => void;\r\n _isServerSynced: () => boolean;\r\n getLocalStorage: (key: string) => LocalStorageData<T> | null;\r\n };\r\n\r\nexport type CogsUpdate<T extends unknown> = UpdateType<T>;\r\n\r\nexport type EffectiveSetState<TStateObject> = (\r\n newStateOrFunction:\r\n | TStateObject\r\n | ((prevState: TStateObject) => TStateObject),\r\n path: string[],\r\n updateObj: { updateType: \"update\" | \"insert\" | \"cut\" },\r\n validationKey?: string,\r\n opts?: UpdateOpts<TStateObject>\r\n) => void;\r\n\r\nexport type UpdateTypeDetail = {\r\n timeStamp: number;\r\n stateKey: string;\r\n updateType: \"update\" | \"insert\" | \"cut\";\r\n path: string[];\r\n status: \"new\" | \"sent\" | \"synced\";\r\n oldValue: any;\r\n newValue: any;\r\n userId?: number;\r\n};\r\n\r\nexport type ActionsType<T> = {\r\n type: \"onChange\";\r\n action: ({ state, actionType }: { state: T; actionType: string }) => void;\r\n debounce?: number;\r\n}[];\r\n\r\ntype ArrayToObject<T extends string[]> = Record<T[number], string>;\r\ntype CookieType<T> = {\r\n timeStamp: number;\r\n value: T;\r\n cookieName: string;\r\n OnUnMountCookie?: Boolean;\r\n};\r\nexport type CogsCookiesType<T extends string[] = string[]> = CookieType<\r\n ArrayToObject<T>\r\n>;\r\nexport type ReactivityType = \"none\" | \"component\" | \"deps\" | \"all\";\r\n\r\ntype ValidationOptionsType = {\r\n key?: string;\r\n zodSchema?: ZodObject<ZodRawShape> | ZodArray<ZodObject<ZodRawShape>>;\r\n onBlur?: boolean;\r\n};\r\n\r\nexport type OptionsType<T extends unknown = unknown> = {\r\n log?: boolean;\r\n componentId?: string;\r\n serverSync?: ServerSyncType<T>;\r\n validation?: ValidationOptionsType;\r\n enableServerState?: boolean;\r\n middleware?: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void;\r\n\r\n modifyState?: (state: T) => T;\r\n localStorage?: { key: string | ((state: T) => string) };\r\n formElements?: FormsElementsType;\r\n enabledSync?: (state: T) => boolean;\r\n reactiveDeps?: (state: T) => any[] | true;\r\n reactiveType?: ReactivityType[] | ReactivityType;\r\n syncUpdate?: Partial<UpdateTypeDetail>;\r\n\r\n initialState?: T;\r\n dependencies?: any[]; // Just like useEffect dependencies\r\n};\r\nexport type ServerSyncType<T> = {\r\n testKey?: string;\r\n syncKey: (({ state }: { state: T }) => string) | string;\r\n syncFunction: ({ state }: { state: T }) => void;\r\n debounce?: number;\r\n mutation: UseMutationResult<any, unknown, any, unknown>;\r\n snapshot?: {\r\n name: (({ state }: { state: T }) => string) | string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\nexport type SyncActionsType<T> = {\r\n syncKey: string;\r\n\r\n rollBackState?: T;\r\n actionTimeStamp: number;\r\n retryCount?: number;\r\n status:\r\n | \"success\"\r\n | \"waiting\"\r\n | \"rolledBack\"\r\n | \"error\"\r\n | \"cancelled\"\r\n | \"failed\";\r\n snapshot?: {\r\n name: string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\n\r\nexport type ValidationWrapperOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n active: boolean;\r\n stretch?: boolean;\r\n path: string[];\r\n message?: string;\r\n data?: T;\r\n key?: string;\r\n};\r\nexport type SyncRenderOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n time: number;\r\n data?: T;\r\n key?: string;\r\n};\r\n\r\ntype FormsElementsType<T extends unknown = unknown> = {\r\n validation?: (options: ValidationWrapperOptions<T>) => React.ReactNode;\r\n syncRender?: (options: SyncRenderOptions<T>) => React.ReactNode;\r\n};\r\n\r\nexport type InitialStateInnerType<T extends unknown = unknown> = {\r\n initialState: T;\r\n} & OptionsType<T>;\r\n\r\nexport type InitialStateType<T> = {\r\n [key: string]: InitialStateInnerType<T>;\r\n};\r\n\r\nexport type AllStateTypes<T extends unknown> = Record<string, T>;\r\n\r\nexport type CogsInitialState<T> = {\r\n initialState: T;\r\n formElements?: FormsElementsType<T>;\r\n};\r\n\r\nexport type TransformedStateType<T> = {\r\n [P in keyof T]: T[P] extends CogsInitialState<infer U> ? U : T[P];\r\n};\r\n\r\nfunction setAndMergeOptions(stateKey: string, newOptions: OptionsType<any>) {\r\n const getInitialOptions = getGlobalStore.getState().getInitialOptions;\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n\r\n setInitialStateOptions(stateKey as string, {\r\n ...initialOptions,\r\n ...newOptions,\r\n });\r\n}\r\nfunction setOptions<StateKey, Opt>({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n}: {\r\n stateKey: StateKey;\r\n options?: OptionsType<any>;\r\n initialOptionsPart: Record<string, any>;\r\n}) {\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n const initialOptionsPartState = initialOptionsPart[stateKey as string] || {};\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n const mergedOptions = { ...initialOptionsPartState, ...initialOptions };\r\n\r\n let needToAdd = false;\r\n if (options) {\r\n for (const key in options) {\r\n if (!mergedOptions.hasOwnProperty(key)) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key as keyof typeof options];\r\n } else {\r\n if (\r\n key == \"localStorage\" &&\r\n options[key] &&\r\n mergedOptions[key].key !== options[key]?.key\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n }\r\n }\r\n }\r\n console.log(\"existingOptions-------\", mergedOptions);\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 (\r\n Object.keys(initialOptionsPart).length > 0 ||\r\n (opt && Object.keys(opt).length > 0)\r\n ) {\r\n Object.keys(initialOptionsPart).forEach((key) => {\r\n // Get the existing options for this state key\r\n initialOptionsPart[key] = initialOptionsPart[key] || {};\r\n\r\n initialOptionsPart[key].formElements = {\r\n ...opt?.formElements, // Global defaults first\r\n ...opt?.validation,\r\n ...(initialOptionsPart[key].formElements || {}), // State-specific overrides\r\n };\r\n const existingOptions = getInitialOptions(key);\r\n console.log(\"existingOptions\", existingOptions, initialOptionsPart[key]);\r\n if (!existingOptions) {\r\n getGlobalStore\r\n .getState()\r\n .setInitialStateOptions(key, initialOptionsPart[key]);\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\r\n setOptions({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n });\r\n\r\n const thiState =\r\n getGlobalStore.getState().cogsStateStore[stateKey as string] ||\r\n statePart[stateKey as string];\r\n const partialState = options?.modifyState\r\n ? options.modifyState(thiState)\r\n : thiState;\r\n\r\n const [state, updater] = useCogsStateFn<(typeof statePart)[StateKey]>(\r\n partialState,\r\n {\r\n stateKey: stateKey as string,\r\n syncUpdate: options?.syncUpdate,\r\n componentId,\r\n localStorage: options?.localStorage,\r\n middleware: options?.middleware,\r\n enabledSync: options?.enabledSync,\r\n reactiveType: options?.reactiveType,\r\n reactiveDeps: options?.reactiveDeps,\r\n initialState: options?.initialState,\r\n dependencies: options?.dependencies,\r\n }\r\n );\r\n\r\n return updater;\r\n };\r\n\r\n function setCogsOptions<StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options: OptionsType<(typeof statePart)[StateKey]>\r\n ) {\r\n setOptions({ stateKey, options, initialOptionsPart });\r\n }\r\n\r\n return { useCogsState, setCogsOptions };\r\n};\r\n\r\nconst {\r\n setUpdaterState,\r\n setState,\r\n getInitialOptions,\r\n getKeyState,\r\n getValidationErrors,\r\n setStateLog,\r\n updateInitialStateGlobal,\r\n addValidationError,\r\n removeValidationError,\r\n setServerSyncActions,\r\n} = getGlobalStore.getState();\r\n\r\nconst loadFromLocalStorage = (localStorageKey: string) => {\r\n if (!localStorageKey) return null;\r\n\r\n try {\r\n const storedData = window.localStorage.getItem(localStorageKey);\r\n if (!storedData) return null;\r\n\r\n const parsedData = JSON.parse(storedData);\r\n\r\n return parsedData;\r\n } catch (error) {\r\n console.error(\"Error loading from localStorage:\", error);\r\n return null;\r\n }\r\n};\r\n\r\nconst saveToLocalStorage = <T,>(\r\n state: T,\r\n thisKey: string,\r\n currentInitialOptions: any,\r\n sessionId?: string\r\n) => {\r\n if (currentInitialOptions?.log) {\r\n console.log(\r\n \"saving to localstorage\",\r\n thisKey,\r\n currentInitialOptions.localStorage?.key,\r\n sessionId\r\n );\r\n }\r\n const key = isFunction(currentInitialOptions?.localStorage?.key)\r\n ? currentInitialOptions.localStorage?.key(state)\r\n : currentInitialOptions?.localStorage?.key;\r\n if (key && sessionId) {\r\n const data: LocalStorageData<T> = {\r\n state,\r\n lastUpdated: Date.now(),\r\n lastSyncedWithServer:\r\n getGlobalStore.getState().serverSyncLog[thisKey]?.[0]?.timeStamp,\r\n baseServerState: getGlobalStore.getState().serverState[thisKey],\r\n };\r\n\r\n const storageKey = `${sessionId}-${thisKey}-${key}`;\r\n\r\n window.localStorage.setItem(storageKey, JSON.stringify(data));\r\n }\r\n};\r\n\r\ntype LocalStorageData<T> = {\r\n state: T;\r\n lastUpdated: number;\r\n lastSyncedWithServer?: number;\r\n baseServerState?: T; // Add this to track what server state our changes are based on\r\n};\r\n\r\nconst updateGlobalState = (\r\n thisKey: string,\r\n initialState: any,\r\n newState: any,\r\n effectiveSetState: EffectiveSetState<any>,\r\n componentId: string,\r\n sessionId?: string\r\n) => {\r\n // Update all global state at once\r\n const updates = {\r\n initialState: initialState,\r\n updaterState: createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n ),\r\n state: newState,\r\n };\r\n\r\n startTransition(() => {\r\n updateInitialStateGlobal(thisKey, updates.initialState);\r\n setUpdaterState(thisKey, updates.updaterState);\r\n setState(thisKey, updates.state);\r\n });\r\n};\r\n\r\nconst notifyComponents = (thisKey: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n if (!stateEntry) return;\r\n\r\n // Batch component updates\r\n const updates = new Set<() => void>();\r\n stateEntry.components.forEach((component) => {\r\n updates.add(() => component.forceUpdate());\r\n });\r\n\r\n // Schedule updates in the next tick to allow batching\r\n queueMicrotask(() => {\r\n startTransition(() => {\r\n updates.forEach((update) => update());\r\n });\r\n });\r\n};\r\n\r\nexport const notifyComponent = (stateKey: string, componentId: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // Force an update to ensure the current value is saved\r\n\r\n component.forceUpdate();\r\n }\r\n }\r\n};\r\n\r\nexport function useCogsStateFn<TStateObject extends unknown>(\r\n stateObject: TStateObject,\r\n {\r\n stateKey,\r\n serverSync,\r\n localStorage,\r\n formElements,\r\n middleware,\r\n reactiveDeps,\r\n reactiveType,\r\n componentId,\r\n initialState,\r\n syncUpdate,\r\n dependencies,\r\n }: {\r\n stateKey?: string;\r\n componentId?: string;\r\n } & OptionsType<TStateObject> = {}\r\n) {\r\n const [reactiveForce, forceUpdate] = useState({}); //this is the key to reactivity\r\n const { sessionId } = useCogsConfig();\r\n\r\n let noStateKey = stateKey ? false : true;\r\n const [thisKey] = useState(stateKey ?? uuidv4());\r\n const stateLog = getGlobalStore.getState().stateLog[thisKey];\r\n const componentUpdatesRef = useRef(new Set<string>());\r\n const componentIdRef = useRef(componentId ?? uuidv4());\r\n const latestInitialOptionsRef = useRef<any>(null);\r\n latestInitialOptionsRef.current = getInitialOptions(thisKey as string);\r\n\r\n useEffect(() => {\r\n if (syncUpdate && syncUpdate.stateKey === thisKey && syncUpdate.path?.[0]) {\r\n // Update the actual state value\r\n setState(thisKey, (prevState: any) => ({\r\n ...prevState,\r\n [syncUpdate.path![0]!]: syncUpdate.newValue,\r\n }));\r\n\r\n // Create combined key and update sync info\r\n const syncKey = `${syncUpdate.stateKey}:${syncUpdate.path.join(\".\")}`;\r\n getGlobalStore.getState().setSyncInfo(syncKey, {\r\n timeStamp: syncUpdate.timeStamp!,\r\n userId: syncUpdate.userId!,\r\n });\r\n }\r\n }, [syncUpdate]);\r\n\r\n useEffect(() => {\r\n setAndMergeOptions(thisKey as string, {\r\n initialState,\r\n });\r\n const options = latestInitialOptionsRef.current;\r\n let localData = null;\r\n\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options?.localStorage?.key(initialState)\r\n : options?.localStorage?.key;\r\n if (options?.log) {\r\n console.log(\"newoptions\", options);\r\n console.log(\"localkey\", localkey);\r\n console.log(\"initialState\", initialState);\r\n }\r\n if (localkey && sessionId) {\r\n localData = loadFromLocalStorage(\r\n sessionId + \"-\" + thisKey + \"-\" + localkey\r\n );\r\n }\r\n\r\n let newState = null;\r\n if (initialState) {\r\n newState = initialState;\r\n\r\n if (localData) {\r\n if (localData.lastUpdated > (localData.lastSyncedWithServer || 0)) {\r\n newState = localData.state;\r\n }\r\n }\r\n updateGlobalState(\r\n thisKey,\r\n initialState,\r\n newState,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n\r\n notifyComponents(thisKey);\r\n forceUpdate({});\r\n }\r\n }, [initialState, ...(dependencies || [])]);\r\n\r\n useLayoutEffect(() => {\r\n if (noStateKey) {\r\n setAndMergeOptions(thisKey as string, {\r\n serverSync,\r\n formElements,\r\n initialState,\r\n localStorage,\r\n middleware,\r\n });\r\n }\r\n\r\n const depsKey = `${thisKey}////${componentIdRef.current}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(thisKey) || {\r\n components: new Map(),\r\n };\r\n\r\n stateEntry.components.set(depsKey, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set(),\r\n deps: [],\r\n depsFunction: reactiveDeps || undefined,\r\n reactiveType: reactiveType ?? [\"component\", \"deps\"],\r\n });\r\n\r\n getGlobalStore.getState().stateComponents.set(thisKey, stateEntry);\r\n //need to force update to create the stateUpdates references\r\n forceUpdate({});\r\n return () => {\r\n const depsKey = `${thisKey}////${componentIdRef.current}`;\r\n\r\n if (stateEntry) {\r\n stateEntry.components.delete(depsKey);\r\n if (stateEntry.components.size === 0) {\r\n getGlobalStore.getState().stateComponents.delete(thisKey);\r\n }\r\n }\r\n };\r\n }, []);\r\n\r\n const effectiveSetState = (\r\n newStateOrFunction:\r\n | TStateObject\r\n | ((prevState: TStateObject) => TStateObject),\r\n path: string[],\r\n updateObj: { updateType: \"insert\" | \"cut\" | \"update\" },\r\n validationKey?: string\r\n ) => {\r\n if (Array.isArray(path)) {\r\n const pathKey = `${thisKey}-${path.join(\".\")}`;\r\n componentUpdatesRef.current.add(pathKey);\r\n }\r\n setState(thisKey, (prevValue: TStateObject) => {\r\n const payload = isFunction<TStateObject>(newStateOrFunction)\r\n ? newStateOrFunction(prevValue as TStateObject)\r\n : newStateOrFunction;\r\n\r\n const signalId = `${thisKey}-${path.join(\".\")}`;\r\n if (signalId) {\r\n let isArrayOperation = false;\r\n let elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(signalId);\r\n\r\n if (\r\n (!elements || elements.size === 0) &&\r\n (updateObj.updateType === \"insert\" || updateObj.updateType === \"cut\")\r\n ) {\r\n // Remove last segment (index) from path\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n // If it's an array, use that path for signal\r\n if (Array.isArray(arrayValue)) {\r\n isArrayOperation = true;\r\n const arraySignalId = `${thisKey}-${arrayPath.join(\".\")}`;\r\n elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(arraySignalId);\r\n }\r\n }\r\n\r\n if (elements) {\r\n const newValue = isArrayOperation\r\n ? getNestedValue(payload, path.slice(0, -1))\r\n : getNestedValue(payload, path);\r\n elements.forEach(({ parentId, position, effect }) => {\r\n const parent = document.querySelector(\r\n `[data-parent-id=\"${parentId}\"]`\r\n );\r\n if (parent) {\r\n const childNodes = Array.from(parent.childNodes);\r\n if (childNodes[position]) {\r\n const displayValue = effect\r\n ? new Function(\"state\", `return (${effect})(state)`)(newValue)\r\n : newValue;\r\n childNodes[position].textContent = String(displayValue);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n if (\r\n updateObj.updateType === \"update\" &&\r\n (validationKey || latestInitialOptionsRef.current?.validationKey) &&\r\n path\r\n ) {\r\n removeValidationError(\r\n (validationKey || latestInitialOptionsRef.current?.validationKey) +\r\n \".\" +\r\n path.join(\".\")\r\n );\r\n }\r\n const arrayWithoutIndex = path.slice(0, path.length - 1);\r\n if (\r\n updateObj.updateType === \"cut\" &&\r\n latestInitialOptionsRef.current?.validationKey\r\n ) {\r\n removeValidationError(\r\n latestInitialOptionsRef.current?.validationKey +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n }\r\n if (\r\n updateObj.updateType === \"insert\" &&\r\n latestInitialOptionsRef.current?.validationKey\r\n ) {\r\n let getValidation = getValidationErrors(\r\n latestInitialOptionsRef.current?.validationKey +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n\r\n //TODO this is untested its supposed to cahnge teh validation errors alreaady stored when a new entry is push\r\n\r\n getValidation.filter(([k, v]) => {\r\n let length = k?.split(\".\").length;\r\n\r\n if (\r\n k == arrayWithoutIndex.join(\".\") &&\r\n length == arrayWithoutIndex.length - 1\r\n ) {\r\n // console.log(length, pathWithoutIndex.length);\r\n let newKey = k + \".\" + arrayWithoutIndex;\r\n removeValidationError(k!);\r\n addValidationError(newKey, v!);\r\n }\r\n });\r\n }\r\n\r\n const oldValue = getNestedValue(prevValue, path);\r\n const newValue = getNestedValue(payload, path);\r\n const pathToCheck =\r\n updateObj.updateType === \"update\"\r\n ? path.join(\".\")\r\n : [...path].slice(0, -1).join(\".\");\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n\r\n if (stateEntry) {\r\n for (const [key, component] of stateEntry.components.entries()) {\r\n let shouldUpdate = false;\r\n const reactiveTypes = Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"];\r\n\r\n // Skip if reactivity is disabled\r\n if (reactiveTypes.includes(\"none\")) {\r\n continue;\r\n }\r\n\r\n // Force update if \"all\" is specified\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n\r\n continue;\r\n }\r\n\r\n // Check component-level path reactivity\r\n if (reactiveTypes.includes(\"component\")) {\r\n if (\r\n component.paths &&\r\n (component.paths.has(pathToCheck) || component.paths.has(\"\"))\r\n ) {\r\n shouldUpdate = true;\r\n }\r\n }\r\n\r\n // Check dependency-based reactivity\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(payload);\r\n\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) {\r\n shouldUpdate = true;\r\n }\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n shouldUpdate = true;\r\n }\r\n }\r\n }\r\n\r\n if (shouldUpdate) {\r\n component.forceUpdate();\r\n }\r\n }\r\n }\r\n const timeStamp = Date.now();\r\n\r\n const newUpdate = {\r\n timeStamp,\r\n stateKey: thisKey,\r\n path,\r\n updateType: updateObj.updateType,\r\n status: \"new\" as const,\r\n oldValue,\r\n newValue,\r\n } satisfies UpdateTypeDetail;\r\n\r\n setStateLog(thisKey, (prevLogs) => {\r\n const logs = [...(prevLogs ?? []), newUpdate];\r\n\r\n // Aggregate the updates by stateKey and path\r\n const aggregatedLogs = logs.reduce((acc, log) => {\r\n const uniqueKey = `${log.stateKey}:${JSON.stringify(log.path)}`;\r\n const existing = acc.get(uniqueKey);\r\n\r\n if (existing) {\r\n // Update the existing entry with the most recent details\r\n existing.timeStamp = Math.max(existing.timeStamp, log.timeStamp);\r\n existing.newValue = log.newValue; // Overwrite with the latest value\r\n existing.oldValue = existing.oldValue ?? log.oldValue; // Retain the initial oldValue\r\n existing.updateType = log.updateType; // Update to the most recent type\r\n } else {\r\n // Add the log if no existing match is found\r\n acc.set(uniqueKey, { ...(log as any) });\r\n }\r\n\r\n return acc;\r\n }, new Map<string, typeof newUpdate>());\r\n\r\n // Convert the aggregated map back to an array\r\n return Array.from(aggregatedLogs.values());\r\n });\r\n\r\n saveToLocalStorage(\r\n payload,\r\n thisKey,\r\n latestInitialOptionsRef.current,\r\n sessionId\r\n );\r\n\r\n if (middleware) {\r\n middleware({\r\n updateLog: stateLog,\r\n update: newUpdate,\r\n });\r\n }\r\n if (latestInitialOptionsRef.current?.serverSync) {\r\n const serverStateStore = getGlobalStore.getState().serverState[thisKey];\r\n const serverSync = latestInitialOptionsRef.current?.serverSync;\r\n setServerSyncActions(thisKey, {\r\n syncKey:\r\n typeof serverSync.syncKey == \"string\"\r\n ? serverSync.syncKey\r\n : serverSync.syncKey({ state: payload }),\r\n rollBackState: serverStateStore,\r\n actionTimeStamp: Date.now() + (serverSync.debounce ?? 3000),\r\n status: \"waiting\",\r\n });\r\n }\r\n\r\n return payload;\r\n });\r\n };\r\n if (!getGlobalStore.getState().updaterState[thisKey]) {\r\n setUpdaterState(\r\n thisKey,\r\n createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n )\r\n );\r\n if (!getGlobalStore.getState().cogsStateStore[thisKey]) {\r\n setState(thisKey, stateObject);\r\n }\r\n if (!getGlobalStore.getState().initialStateGlobal[thisKey]) {\r\n updateInitialStateGlobal(thisKey, stateObject);\r\n }\r\n }\r\n\r\n const updaterFinal = useMemo(() => {\r\n // Create proxy with baseObject as target\r\n return createProxyHandler<TStateObject>(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n }, [thisKey]);\r\n\r\n return [getKeyState(thisKey), updaterFinal] as [\r\n TStateObject,\r\n StateObject<TStateObject>,\r\n ];\r\n}\r\n\r\nfunction createProxyHandler<T>(\r\n stateKey: string,\r\n effectiveSetState: EffectiveSetState<T>,\r\n componentId: string,\r\n sessionId?: string\r\n): StateObject<T> {\r\n // ADDED: Enhanced cache with versioning\r\n type CacheEntry = {\r\n proxy: any;\r\n stateVersion: number;\r\n };\r\n const shapeCache = new Map<string, CacheEntry>();\r\n let stateVersion = 0;\r\n\r\n // ADDED: Cache invalidation helper\r\n const invalidateCachePath = (path: string[]) => {\r\n const pathKey = path.join(\".\");\r\n for (const [key] of shapeCache) {\r\n if (key === pathKey || key.startsWith(pathKey + \".\")) {\r\n shapeCache.delete(key);\r\n }\r\n }\r\n stateVersion++;\r\n };\r\n\r\n const baseObj = {\r\n removeValidation: (obj?: { validationKey?: string }) => {\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n },\r\n\r\n revertToInitialState: (obj?: { validationKey?: string }) => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n if (init?.key) {\r\n removeValidationError(init?.key);\r\n }\r\n\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n\r\n // ADDED: Clear cache on revert\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newProxy = rebuildStateShape(initialState, []);\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n startTransition(() => {\r\n setUpdaterState(stateKey, newProxy);\r\n setState(stateKey, initialState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return initialState;\r\n },\r\n updateInitialState: (newState: T) => {\r\n // ADDED: Clear cache on initial state update\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newUpdaterState = createProxyHandler(\r\n stateKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n startTransition(() => {\r\n updateInitialStateGlobal(stateKey, newState);\r\n setUpdaterState(stateKey, newUpdaterState);\r\n setState(stateKey, newState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return {\r\n fetchId: (field: keyof T) => newUpdaterState.get()[field],\r\n };\r\n },\r\n _initialState: getGlobalStore.getState().initialStateGlobal[stateKey],\r\n _serverState: getGlobalStore.getState().serverState[stateKey],\r\n _isLoading: getGlobalStore.getState().isLoadingGlobal[stateKey],\r\n _isServerSynced: () => {\r\n const serverState = getGlobalStore.getState().serverState[stateKey];\r\n return Boolean(\r\n serverState && isDeepEqual(serverState, getKeyState(stateKey))\r\n );\r\n },\r\n };\r\n\r\n function rebuildStateShape(\r\n currentState: T,\r\n path: string[] = [],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ): any {\r\n const cacheKey = path.map(String).join(\".\");\r\n\r\n // MODIFIED: Cache check with version\r\n const cachedEntry = shapeCache.get(cacheKey);\r\n // if (cachedEntry?.stateVersion === stateVersion) {\r\n // return cachedEntry.proxy;\r\n // }\r\n type CallableStateObject<T> = {\r\n (): T;\r\n } & {\r\n [key: string]: any;\r\n };\r\n\r\n const baseFunction = function () {\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n } as unknown as CallableStateObject<T>;\r\n\r\n // Copy properties from baseObj to the function with type assertion\r\n Object.keys(baseObj).forEach((key) => {\r\n (baseFunction as any)[key] = (baseObj as any)[key];\r\n });\r\n\r\n const handler = {\r\n apply(target: any, thisArg: any, args: any[]) {\r\n console.log(\r\n `PROXY APPLY TRAP HIT: stateKey=${stateKey}, path=${path.join(\".\")}`\r\n ); // <--- ADD LOGGING\r\n console.trace(\"Apply trap stack trace\");\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n },\r\n\r\n get(target: any, prop: string) {\r\n if (\r\n prop !== \"then\" &&\r\n !prop.startsWith(\"$\") &&\r\n prop !== \"stateMapNoRender\"\r\n ) {\r\n const currentPath = path.join(\".\");\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n\r\n if (stateEntry) {\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // Only add paths for non-root or specifically for get() at root\r\n if (path.length > 0 || prop === \"get\") {\r\n component.paths.add(currentPath);\r\n }\r\n } else {\r\n }\r\n }\r\n }\r\n if (prop === \"_status\") {\r\n // Get current state at this path (non-reactive version)\r\n const thisReactiveState = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n }\r\n if (prop === \"getStatus\") {\r\n return function () {\r\n // Get current state at this path (reactive version)\r\n const thisReactiveState = getGlobalStore().getNestedState(\r\n stateKey,\r\n path\r\n );\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n };\r\n }\r\n if (prop === \"removeStorage\") {\r\n return () => {\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n console.log(\"removing storage\", storageKey);\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n };\r\n }\r\n if (prop === \"showValidationErrors\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n const errors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key + \".\" + path.join(\".\"));\r\n\r\n return errors;\r\n };\r\n }\r\n if (Array.isArray(currentState)) {\r\n if (prop === \"getSelected\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n if (selectedIndex === undefined) return undefined;\r\n return rebuildStateShape(\r\n currentState[selectedIndex],\r\n [...path, selectedIndex.toString()],\r\n meta\r\n );\r\n };\r\n }\r\n if (prop === \"getSelectedIndex\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n\r\n return selectedIndex ?? -1;\r\n };\r\n }\r\n if (prop === \"stateSort\") {\r\n return (\r\n compareFn: (\r\n a: InferArrayElement<T>,\r\n b: InferArrayElement<T>\r\n ) => number\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n\r\n // Create a shallow copy with original indices\r\n const arrayCopy = currentArray.map((v: any, i: number) => ({\r\n ...v,\r\n __origIndex: i.toString(),\r\n }));\r\n\r\n // Sort the copy using the provided compare function\r\n const sortedArray = [...arrayCopy].sort(compareFn);\r\n\r\n // ADDED: Clear cache for sort operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // Return the sorted array with state objects\r\n return rebuildStateShape(sortedArray as any, path, {\r\n filtered: [...(meta?.filtered || []), path],\r\n validIndices: sortedArray.map((item) =>\r\n parseInt(item.__origIndex as string)\r\n ),\r\n });\r\n };\r\n }\r\n if (prop === \"stateMap\" || prop === \"stateMapNoRender\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n const isFiltered = meta?.filtered?.some(\r\n (p) => p.join(\".\") === path.join(\".\")\r\n );\r\n const arrayToMap = isFiltered\r\n ? currentState\r\n : getGlobalStore.getState().getNestedState(stateKey, path);\r\n\r\n if (prop !== \"stateMapNoRender\") {\r\n shapeCache.clear();\r\n stateVersion++;\r\n }\r\n\r\n return arrayToMap.map((val: any, index: number) => {\r\n const thisIndex =\r\n isFiltered && val.__origIndex ? val.__origIndex : index;\r\n const elementProxy = rebuildStateShape(\r\n val,\r\n [...path, thisIndex.toString()],\r\n meta\r\n );\r\n return callbackfn(\r\n val,\r\n elementProxy,\r\n index,\r\n currentState as any,\r\n rebuildStateShape(currentState as any, path, meta)\r\n );\r\n });\r\n };\r\n }\r\n if (prop === \"$stateMap\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n return createElement(SignalMapRenderer, {\r\n proxy: {\r\n _stateKey: stateKey,\r\n _path: path,\r\n _mapFn: callbackfn as any, // Pass the actual function, not string\r\n },\r\n\r\n rebuildStateShape,\r\n });\r\n };\r\n }\r\n if (prop === \"stateFlattenOn\") {\r\n return (fieldName: string) => {\r\n const isFiltered = meta?.filtered?.some(\r\n (p) => p.join(\".\") === path.join(\".\")\r\n );\r\n const arrayToMap = isFiltered\r\n ? currentState\r\n : getGlobalStore.getState().getNestedState(stateKey, path);\r\n\r\n // ADDED: Clear shape cache for flattening operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const flattenedResults = arrayToMap.flatMap(\r\n (val: any, index: number) => {\r\n return val[fieldName] ?? [];\r\n }\r\n );\r\n\r\n return rebuildStateShape(\r\n flattenedResults,\r\n [...path, \"[*]\", fieldName],\r\n meta\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"findWith\") {\r\n return (\r\n thisKey: keyof InferArrayElement<T>,\r\n thisValue: InferArrayElement<T>[keyof InferArrayElement<T>]\r\n ) => {\r\n const foundIndex = currentState.findIndex(\r\n (obj: any) => obj[thisKey] === thisValue\r\n );\r\n if (foundIndex === -1) return undefined;\r\n const foundValue = currentState[foundIndex];\r\n const newPath = [...path, foundIndex.toString()];\r\n // console.log(\r\n // \"findWithfindWithfindWithfindWith\",\r\n // stateKey,\r\n // foundValue,\r\n // newPath,\r\n // );\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // ADDED: Clear cache for find operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n // Try returning without spread\r\n return rebuildStateShape(foundValue, newPath);\r\n };\r\n }\r\n\r\n if (prop === \"index\") {\r\n return (index: number) => {\r\n const indexValue = currentState[index];\r\n return rebuildStateShape(indexValue, [...path, index.toString()]);\r\n };\r\n }\r\n\r\n if (prop === \"insert\") {\r\n return (payload: UpdateArg<T>) => {\r\n // ADDED: Invalidate cache on insert\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, payload, path, stateKey);\r\n return rebuildStateShape(\r\n getGlobalStore.getState().cogsStateStore[stateKey],\r\n []\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"uniqueInsert\") {\r\n return (\r\n payload: UpdateArg<T>,\r\n fields?: (keyof InferArrayElement<T>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n const newValue = isFunction<T>(payload)\r\n ? payload(currentArray as any)\r\n : (payload as any);\r\n\r\n let matchedItem: any = null;\r\n const isUnique = !currentArray.some((item) => {\r\n if (fields) {\r\n const isMatch = fields.every((field) =>\r\n isDeepEqual(item[field], newValue[field])\r\n );\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n }\r\n const isMatch = isDeepEqual(item, newValue);\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n });\r\n\r\n if (isUnique) {\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, newValue, path, stateKey);\r\n } else if (onMatch && matchedItem) {\r\n const updatedItem = onMatch(matchedItem);\r\n const updatedArray = currentArray.map((item) =>\r\n isDeepEqual(item, matchedItem) ? updatedItem : item\r\n );\r\n invalidateCachePath(path);\r\n updateFn(effectiveSetState, updatedArray as any, path);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"cut\") {\r\n return (index: number, options?: { waitForSync?: boolean }) => {\r\n if (options?.waitForSync) return;\r\n // ADDED: Invalidate cache on cut\r\n invalidateCachePath(path);\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n };\r\n }\r\n if (prop === \"cutByValue\") {\r\n return (value: string | number | boolean) => {\r\n for (let index = 0; index < currentState.length; index++) {\r\n if (currentState[index] === value) {\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n }\r\n }\r\n };\r\n }\r\n if (prop === \"toggleByValue\") {\r\n return (value: string | number | boolean) => {\r\n const index = currentState.findIndex((item) => item === value);\r\n if (index > -1) {\r\n // Value exists, so cut it\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n } else {\r\n // Value doesn't exist, so insert it\r\n pushFunc(effectiveSetState, value as any, path, stateKey);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"stateFilter\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const newVal = currentState.map((v: any, i: number) => ({\r\n ...v,\r\n __origIndex: i.toString(),\r\n }));\r\n\r\n const validIndices: number[] = [];\r\n const filteredArray: Array<InferArrayElement<T>> = [];\r\n\r\n for (let i = 0; i < newVal.length; i++) {\r\n if (callbackfn(newVal[i], i)) {\r\n validIndices.push(i);\r\n filteredArray.push(newVal[i]);\r\n }\r\n }\r\n\r\n // ADDED: Clear cache for filter operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // Always include validIndices, even if it's an empty array\r\n return rebuildStateShape(filteredArray as any, path, {\r\n filtered: [...(meta?.filtered || []), path],\r\n validIndices: validIndices, // Always pass validIndices, even if empty\r\n });\r\n };\r\n }\r\n }\r\n const lastPathElement = path[path.length - 1];\r\n if (!isNaN(Number(lastPathElement))) {\r\n const parentPath = path.slice(0, -1);\r\n const parentValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n\r\n if (Array.isArray(parentValue) && prop === \"cut\") {\r\n return () =>\r\n cutFunc(\r\n effectiveSetState,\r\n parentPath,\r\n stateKey,\r\n Number(lastPathElement)\r\n );\r\n }\r\n }\r\n\r\n if (prop === \"get\") {\r\n return () => getGlobalStore.getState().getNestedState(stateKey, path);\r\n }\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$get\") {\r\n return () =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n });\r\n }\r\n if (prop === \"lastSynced\") {\r\n const syncKey = `${stateKey}:${path.join(\".\")}`;\r\n return getGlobalStore.getState().getSyncInfo(syncKey);\r\n }\r\n\r\n if (prop == \"getLocalStorage\") {\r\n return (key: string) =>\r\n loadFromLocalStorage(sessionId + \"-\" + stateKey + \"-\" + key);\r\n }\r\n if (prop === \"_selected\") {\r\n const parentPath = path.slice(0, -1);\r\n const parentKey = parentPath.join(\".\");\r\n const parent = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n if (Array.isArray(parent)) {\r\n const currentIndex = Number(path[path.length - 1]);\r\n return (\r\n currentIndex ===\r\n getGlobalStore.getState().getSelectedIndex(stateKey, parentKey)\r\n );\r\n }\r\n return undefined;\r\n }\r\n if (prop === \"setSelected\") {\r\n return (value: boolean) => {\r\n const parentPath = path.slice(0, -1);\r\n const thisIndex = Number(path[path.length - 1]);\r\n const parentKey = parentPath.join(\".\");\r\n\r\n if (value) {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, thisIndex);\r\n } else {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, undefined);\r\n }\r\n\r\n const nested = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, [...parentPath]);\r\n updateFn(effectiveSetState, nested, parentPath);\r\n\r\n // Invalidate cache for this path\r\n invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (path.length == 0) {\r\n if (prop === \"validateZodSchema\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n const addValidationError =\r\n getGlobalStore.getState().addValidationError;\r\n\r\n if (!init?.zodSchema) {\r\n throw new Error(\"Zod schema not found\");\r\n }\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n removeValidationError(init.key);\r\n const thisObject =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n\r\n try {\r\n // First clear any existing validation errors for this schema\r\n // This ensures we don't have stale errors\r\n const existingErrors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key);\r\n if (existingErrors && existingErrors.length > 0) {\r\n existingErrors.forEach(([errorPath]) => {\r\n if (errorPath && errorPath.startsWith(init.key!)) {\r\n removeValidationError(errorPath);\r\n }\r\n });\r\n }\r\n\r\n // Attempt to validate with Zod\r\n const result = init.zodSchema.safeParse(thisObject);\r\n\r\n if (!result.success) {\r\n // Process Zod errors and add them to the validation store\r\n const zodErrors = result.error.errors;\r\n\r\n zodErrors.forEach((error) => {\r\n const errorPath = error.path;\r\n const errorMessage = error.message;\r\n\r\n // Build the full path for the validation error\r\n // Format: validationKey.path.to.field\r\n const fullErrorPath = [init.key, ...errorPath].join(\".\");\r\n\r\n // Add the error to the store\r\n addValidationError(fullErrorPath, errorMessage);\r\n });\r\n\r\n notifyComponents(stateKey);\r\n\r\n return false;\r\n }\r\n\r\n return true;\r\n } catch (error) {\r\n console.error(\"Zod schema validation failed\", error);\r\n return false;\r\n }\r\n };\r\n }\r\n if (prop === \"_componentId\") return componentId;\r\n if (prop === \"getComponents\") {\r\n return () => getGlobalStore().stateComponents.get(stateKey);\r\n }\r\n if (prop === \"getAllFormRefs\") {\r\n return () => {\r\n return formRefStore.getState().getFormRefsByStateKey(stateKey);\r\n };\r\n }\r\n\r\n if (prop === \"_initialState\")\r\n return getGlobalStore.getState().initialStateGlobal[stateKey];\r\n if (prop === \"_serverState\")\r\n return getGlobalStore.getState().serverState[stateKey];\r\n if (prop === \"_isLoading\")\r\n return getGlobalStore.getState().isLoadingGlobal[stateKey];\r\n if (prop === \"revertToInitialState\")\r\n return baseObj.revertToInitialState;\r\n if (prop === \"updateInitialState\") return baseObj.updateInitialState;\r\n if (prop === \"removeValidation\") return baseObj.removeValidation;\r\n }\r\n if (prop === \"getFormRef\") {\r\n return () => {\r\n return formRefStore\r\n .getState()\r\n .getFormRef(stateKey + \".\" + path.join(\".\"));\r\n };\r\n }\r\n\r\n if (prop === \"validationWrapper\") {\r\n return ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => (\r\n <ValidationWrapper\r\n formOpts={\r\n hideMessage ? { validation: { message: \"\" } } : undefined\r\n }\r\n path={path}\r\n validationKey={\r\n getGlobalStore.getState().getInitialOptions(stateKey)\r\n ?.validation?.key || \"\"\r\n }\r\n stateKey={stateKey}\r\n validIndices={meta?.validIndices}\r\n >\r\n {children}\r\n </ValidationWrapper>\r\n );\r\n }\r\n\r\n if (prop === \"_stateKey\") return stateKey;\r\n if (prop === \"_path\") return path;\r\n if (prop === \"_isServerSynced\") return baseObj._isServerSynced;\r\n\r\n if (prop === \"update\") {\r\n return (payload: UpdateArg<T>, opts?: UpdateOpts<T>) => {\r\n // ADDED: Invalidate cache on update\r\n if (opts?.debounce) {\r\n debounce(() => {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }, opts.debounce);\r\n } else {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }\r\n invalidateCachePath(path);\r\n };\r\n }\r\n\r\n if (prop === \"formElement\") {\r\n return (child: FormControl<T>, formOpts?: FormOptsType) => {\r\n return (\r\n <FormControlComponent<T>\r\n setState={effectiveSetState}\r\n stateKey={stateKey}\r\n path={path}\r\n child={child}\r\n formOpts={formOpts}\r\n />\r\n );\r\n };\r\n }\r\n\r\n const nextPath = [...path, prop];\r\n const nextValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, nextPath);\r\n return rebuildStateShape(nextValue, nextPath, meta);\r\n },\r\n };\r\n\r\n const proxyInstance = new Proxy(baseFunction, handler);\r\n\r\n shapeCache.set(cacheKey, {\r\n proxy: proxyInstance,\r\n stateVersion: stateVersion,\r\n });\r\n\r\n return proxyInstance;\r\n }\r\n\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, [])\r\n );\r\n}\r\n\r\nexport function $cogsSignal(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n}) {\r\n return createElement(SignalRenderer, { proxy });\r\n}\r\n\r\nfunction SignalMapRenderer({\r\n proxy,\r\n\r\n rebuildStateShape,\r\n}: {\r\n proxy: {\r\n _stateKey: string;\r\n _path: string[];\r\n _mapFn: (\r\n value: any,\r\n setter: any,\r\n index: number,\r\n array: any[],\r\n arraySetter: any\r\n ) => ReactNode;\r\n };\r\n\r\n rebuildStateShape: (\r\n currentState: any,\r\n path: string[],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ) => any;\r\n}) {\r\n const value = getGlobalStore().getNestedState(proxy._stateKey, proxy._path);\r\n\r\n if (!Array.isArray(value)) {\r\n return null;\r\n }\r\n const arraySetter = rebuildStateShape(\r\n value,\r\n proxy._path\r\n ) as ArrayEndType<any>;\r\n // Use existing global state management\r\n return arraySetter.stateMapNoRender(\r\n (item, setter, index, value, arraysetter) => {\r\n // Execute map function in React context with existing state/proxies\r\n return proxy._mapFn(item, setter, index, value, arraysetter);\r\n }\r\n );\r\n}\r\nfunction SignalRenderer({\r\n proxy,\r\n}: {\r\n proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n };\r\n}) {\r\n const elementRef = useRef<HTMLSpanElement>(null);\r\n const signalId = `${proxy._stateKey}-${proxy._path.join(\".\")}`;\r\n\r\n useEffect(() => {\r\n const element = elementRef.current;\r\n if (!element || !element.parentElement) return;\r\n\r\n const parentElement = element.parentElement;\r\n const childNodes = Array.from(parentElement.childNodes);\r\n const position = childNodes.indexOf(element);\r\n\r\n let parentId = parentElement.getAttribute(\"data-parent-id\");\r\n if (!parentId) {\r\n parentId = `parent-${crypto.randomUUID()}`;\r\n parentElement.setAttribute(\"data-parent-id\", parentId);\r\n }\r\n\r\n const instanceId = `instance-${crypto.randomUUID()}`;\r\n const elementInfo = {\r\n instanceId,\r\n parentId,\r\n position,\r\n effect: proxy._effect,\r\n };\r\n\r\n getGlobalStore.getState().addSignalElement(signalId, elementInfo);\r\n\r\n // Get the raw value from the store\r\n const value = getGlobalStore\r\n .getState()\r\n .getNestedState(proxy._stateKey, proxy._path);\r\n\r\n let displayValue;\r\n if (proxy._effect) {\r\n try {\r\n displayValue = new Function(\r\n \"state\",\r\n `return (${proxy._effect})(state)`\r\n )(value);\r\n } catch (err) {\r\n console.error(\"Error evaluating effect function during mount:\", err);\r\n displayValue = value; // Fallback to raw value\r\n }\r\n } else {\r\n displayValue = value;\r\n }\r\n\r\n if (displayValue !== null && typeof displayValue === \"object\") {\r\n displayValue = JSON.stringify(displayValue);\r\n }\r\n\r\n const textNode = document.createTextNode(String(displayValue));\r\n element.replaceWith(textNode);\r\n }, [proxy._stateKey, proxy._path.join(\".\"), proxy._effect]);\r\n\r\n return createElement(\"span\", {\r\n ref: elementRef,\r\n style: { display: \"none\" },\r\n \"data-signal-id\": signalId,\r\n });\r\n}\r\nexport function $cogsSignalStore(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n}) {\r\n const value = useSyncExternalStore(\r\n (notify) => {\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(proxy._stateKey) || {\r\n components: new Map(),\r\n };\r\n stateEntry.components.set(proxy._stateKey, {\r\n forceUpdate: notify,\r\n paths: new Set([proxy._path.join(\".\")]),\r\n });\r\n return () => stateEntry.components.delete(proxy._stateKey);\r\n },\r\n () => getGlobalStore.getState().getNestedState(proxy._stateKey, proxy._path)\r\n );\r\n return createElement(\"text\", {}, String(value));\r\n}\r\n"],"names":["setAndMergeOptions","stateKey","newOptions","getInitialOptions","getGlobalStore","setInitialStateOptions","initialOptions","setOptions","options","initialOptionsPart","initialOptionsPartState","mergedOptions","needToAdd","key","addStateOptions","initialState","formElements","validation","createCogsState","opt","newInitialState","statePart","transformStateFunc","existingOptions","useCogsState","componentId","useState","uuidv4","thiState","partialState","state","updater","useCogsStateFn","setCogsOptions","setUpdaterState","setState","getKeyState","getValidationErrors","setStateLog","updateInitialStateGlobal","addValidationError","removeValidationError","setServerSyncActions","loadFromLocalStorage","localStorageKey","storedData","error","saveToLocalStorage","thisKey","currentInitialOptions","sessionId","isFunction","data","storageKey","updateGlobalState","newState","effectiveSetState","updates","createProxyHandler","startTransition","notifyComponents","stateEntry","component","update","notifyComponent","fullComponentId","stateObject","serverSync","localStorage","middleware","reactiveDeps","reactiveType","syncUpdate","dependencies","reactiveForce","forceUpdate","useCogsConfig","noStateKey","stateLog","componentUpdatesRef","useRef","componentIdRef","latestInitialOptionsRef","useEffect","prevState","syncKey","localData","localkey","useLayoutEffect","depsKey","newStateOrFunction","path","updateObj","validationKey","pathKey","prevValue","payload","signalId","isArrayOperation","elements","arrayPath","arrayValue","getNestedValue","arraySignalId","newValue","parentId","position","effect","parent","childNodes","displayValue","arrayWithoutIndex","k","v","length","newKey","oldValue","pathToCheck","shouldUpdate","reactiveTypes","depsResult","isDeepEqual","newUpdate","prevLogs","aggregatedLogs","acc","log","uniqueKey","existing","serverStateStore","updaterFinal","useMemo","shapeCache","stateVersion","invalidateCachePath","baseObj","obj","init","newProxy","rebuildStateShape","initalOptionsGet","localKey","newUpdaterState","field","serverState","currentState","meta","cacheKey","baseFunction","handler","target","thisArg","args","prop","currentPath","thisReactiveState","initialStateAtPath","selectedIndex","compareFn","sortedArray","i","item","callbackfn","isFiltered","p","arrayToMap","val","index","thisIndex","elementProxy","createElement","SignalMapRenderer","fieldName","flattenedResults","thisValue","foundIndex","foundValue","newPath","indexValue","pushFunc","fields","onMatch","currentArray","matchedItem","isMatch","updatedItem","updatedArray","updateFn","cutFunc","value","newVal","validIndices","filteredArray","lastPathElement","parentPath","parentValue","fn","$cogsSignal","parentKey","nested","thisObject","existingErrors","errorPath","result","errorMessage","fullErrorPath","formRefStore","children","hideMessage","jsx","ValidationWrapper","opts","debounce","child","formOpts","FormControlComponent","nextPath","nextValue","proxyInstance","proxy","SignalRenderer","setter","arraysetter","elementRef","element","parentElement","elementInfo","err","textNode","$cogsSignalStore","useSyncExternalStore","notify"],"mapp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A,IAAA,KAAK,UAAUA,CAAY;AAG5C,UAAMsH,IAAW,SAAS,eAAe,OAAOtH,CAAY,CAAC;AAC7D,IAAAkH,EAAQ,YAAYI,CAAQ;AAAA,EAAA,GAC3B,CAACT,EAAM,WAAWA,EAAM,MAAM,KAAK,GAAG,GAAGA,EAAM,OAAO,CAAC,GAEnDjD,EAAc,QAAQ;AAAA,IAC3B,KAAKqD;AAAA,IACL,OAAO,EAAE,SAAS,OAAO;AAAA,IACzB,kBAAkB9H;AAAA,EAAA,CACnB;AACH;AACO,SAASoI,GAAiBV,GAG9B;AACD,QAAM9B,IAAQyC;AAAA,IACZ,CAACC,MAAW;AACJ,YAAA1K,IAAazD,EAChB,SAAS,EACT,gBAAgB,IAAIuN,EAAM,SAAS,KAAK;AAAA,QACzC,gCAAgB,IAAI;AAAA,MACtB;AACW,aAAA9J,EAAA,WAAW,IAAI8J,EAAM,WAAW;AAAA,QACzC,aAAaY;AAAA,QACb,2BAAW,IAAI,CAACZ,EAAM,MAAM,KAAK,GAAG,CAAC,CAAC;AAAA,MAAA,CACvC,GACM,MAAM9J,EAAW,WAAW,OAAO8J,EAAM,SAAS;AAAA,IAC3D;AAAA,IACA,MAAMvN,EAAe,WAAW,eAAeuN,EAAM,WAAWA,EAAM,KAAK;AAAA,EAC7E;AACA,SAAOjD,EAAc,QAAQ,CAAI,GAAA,OAAOmB,CAAK,CAAC;AAChD;"}
|
|
1
|
+
{"version":3,"file":"CogsState.jsx","sources":["../src/CogsState.tsx"],"sourcesContent":["\"use client\";\r\nimport {\r\n createElement,\r\n startTransition,\r\n useEffect,\r\n useLayoutEffect,\r\n useMemo,\r\n useRef,\r\n useState,\r\n useSyncExternalStore,\r\n type ReactNode,\r\n} from \"react\";\r\n\r\nimport {\r\n debounce,\r\n getDifferences,\r\n getNestedValue,\r\n isFunction,\r\n type GenericObject,\r\n} from \"./utility.js\";\r\nimport {\r\n cutFunc,\r\n FormControlComponent,\r\n pushFunc,\r\n updateFn,\r\n ValidationWrapper,\r\n} from \"./Functions.js\";\r\nimport { isDeepEqual, transformStateFunc } from \"./utility.js\";\r\nimport type { UseMutationResult } from \"@tanstack/react-query\";\r\nimport { v4 as uuidv4 } from \"uuid\";\r\nimport { ZodArray, ZodObject, type ZodRawShape } from \"zod\";\r\n\r\nimport { formRefStore, getGlobalStore, type ComponentsType } from \"./store.js\";\r\nimport { useCogsConfig } from \"./CogsStateClient.js\";\r\n\r\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\r\n\r\nexport type ServerSyncStatus = {\r\n isFresh: boolean;\r\n isFreshTime: number;\r\n isStale: boolean;\r\n isStaleTime: number;\r\n isSyncing: boolean;\r\n isSyncingTime: number;\r\n};\r\n\r\nexport type SyncInfo = {\r\n timeStamp: number;\r\n userId: number;\r\n};\r\n\r\nexport type FormElementParams<T> = {\r\n get: () => T;\r\n\r\n set: UpdateType<T>;\r\n syncStatus: (SyncInfo & { date: Date }) | null;\r\n path: string[];\r\n validationErrors: () => string[];\r\n addValidationError: (message?: string) => void;\r\n\r\n inputProps: {\r\n ref?: React.RefObject<any>;\r\n value?: T extends boolean ? never : T;\r\n onChange?: (\r\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\r\n ) => void;\r\n onBlur?: () => void;\r\n };\r\n};\r\n\r\nexport type StateKeys = string;\r\n\r\ntype findWithFuncType<U> = (\r\n thisKey: keyof U,\r\n thisValue: U[keyof U]\r\n) => EndType<U> & StateObject<U>;\r\nexport type PushArgs<U> = (\r\n update:\r\n | Prettify<U>\r\n | ((prevState: NonNullable<Prettify<U>>[]) => NonNullable<Prettify<U>>),\r\n opts?: UpdateOpts<U>\r\n) => void;\r\n\r\ntype CutFunctionType = (\r\n index?: number,\r\n options?: { waitForSync?: boolean }\r\n) => void;\r\n\r\nexport type InferArrayElement<T> = T extends (infer U)[] ? U : never;\r\n\r\nexport type ArrayEndType<TShape extends unknown> = {\r\n findWith: findWithFuncType<InferArrayElement<TShape>>;\r\n index: (index: number) => StateObject<InferArrayElement<TShape>> & {\r\n insert: PushArgs<InferArrayElement<TShape>>;\r\n cut: CutFunctionType;\r\n _index: number;\r\n } & EndType<InferArrayElement<TShape>>;\r\n insert: PushArgs<InferArrayElement<TShape>>;\r\n cut: CutFunctionType;\r\n cutByValue: (value: string | number | boolean) => void;\r\n toggleByValue: (value: string | number | boolean) => void;\r\n stateSort: (\r\n compareFn: (\r\n a: InferArrayElement<TShape>,\r\n b: InferArrayElement<TShape>\r\n ) => number\r\n ) => ArrayEndType<TShape>;\r\n\r\n stateMapNoRender: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n $stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateFlattenOn: <K extends keyof InferArrayElement<TShape>>(\r\n field: K\r\n ) => StateObject<InferArrayElement<InferArrayElement<TShape>[K]>[]>;\r\n uniqueInsert: (\r\n payload: UpdateArg<InferArrayElement<TShape>>,\r\n fields?: (keyof InferArrayElement<TShape>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => void;\r\n stateFilter: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => void\r\n ) => ArrayEndType<TShape>;\r\n getSelected: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n getSelectedIndex: () => number;\r\n} & EndType<TShape> & {\r\n [K in keyof (any[] extends infer T ? T : never)]: never;\r\n };\r\n\r\nexport type UpdateType<T> = (\r\n payload: UpdateArg<Prettify<T>>,\r\n opts?: UpdateOpts<T>\r\n) => void;\r\nexport type FormOptsType = {\r\n key?: string;\r\n validation?: {\r\n hideMessage?: boolean;\r\n message?: string;\r\n stretch?: boolean;\r\n props?: GenericObject;\r\n disable?: boolean;\r\n };\r\n formElements?: boolean;\r\n debounceTime?: number;\r\n stateServerDifferences?: string[][];\r\n};\r\n\r\nexport type FormControl<T> = (obj: FormElementParams<T>) => JSX.Element;\r\n\r\nexport type UpdateArg<S> = S | ((prevState: S) => S);\r\nexport type UpdateOpts<T> = {\r\n afterUpdate?: (state: T) => void;\r\n debounce?: number;\r\n};\r\nexport type ObjectEndType<T> = EndType<T> & {\r\n [K in keyof T]-?: ObjectEndType<T[K]>;\r\n} & {\r\n stateObject: (callbackfn: (value: T, setter: StateObject<T>) => void) => any;\r\n delete: () => void;\r\n};\r\ntype EffectFunction<T, R> = (state: T) => R;\r\nexport type EndType<T, IsArrayElement = false> = {\r\n update: UpdateType<T>;\r\n _path: string[];\r\n _stateKey: string;\r\n formElement: (control: FormControl<T>, opts?: FormOptsType) => JSX.Element;\r\n get: () => T;\r\n $get: () => T;\r\n $derive: <R>(fn: EffectFunction<T, R>) => R;\r\n _status: \"fresh\" | \"stale\" | \"synced\";\r\n getStatus: () => \"fresh\" | \"stale\";\r\n showValidationErrors: () => string[];\r\n setValidation: (ctx: string) => void;\r\n removeValidation: (ctx: string) => void;\r\n ignoreFields: (fields: string[]) => StateObject<T>;\r\n _selected: boolean;\r\n setSelected: (value: boolean) => void;\r\n getFormRef: () => React.RefObject<any> | undefined;\r\n removeStorage: () => void;\r\n validationWrapper: ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => JSX.Element;\r\n lastSynced?: SyncInfo;\r\n} & (IsArrayElement extends true ? { cut: () => void } : {}) & {\r\n [K in keyof (any extends infer T ? T : never)]: never;\r\n };\r\n\r\nexport type StateObject<T> = (T extends any[]\r\n ? ArrayEndType<T>\r\n : T extends Record<string, unknown> | object\r\n ? { [K in keyof T]-?: StateObject<T[K]> } & ObjectEndType<T>\r\n : T extends string | number | boolean | null\r\n ? T\r\n : never) &\r\n EndType<T, true> & {\r\n getAllFormRefs: () => Map<string, React.RefObject<any>>;\r\n _componentId: string | null;\r\n getComponents: () => ComponentsType;\r\n validateZodSchema: () => void;\r\n _initialState: T;\r\n updateInitialState: (newState: T | null) => {\r\n fetchId: (field: keyof T) => string | number;\r\n };\r\n _isLoading: boolean;\r\n _serverState: T;\r\n revertToInitialState: (obj?: { validationKey?: string }) => T;\r\n middleware: (\r\n middles: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void\r\n ) => void;\r\n _isServerSynced: () => boolean;\r\n getLocalStorage: (key: string) => LocalStorageData<T> | null;\r\n };\r\n\r\nexport type CogsUpdate<T extends unknown> = UpdateType<T>;\r\n\r\nexport type EffectiveSetState<TStateObject> = (\r\n newStateOrFunction:\r\n | TStateObject\r\n | ((prevState: TStateObject) => TStateObject),\r\n path: string[],\r\n updateObj: { updateType: \"update\" | \"insert\" | \"cut\" },\r\n validationKey?: string,\r\n opts?: UpdateOpts<TStateObject>\r\n) => void;\r\n\r\nexport type UpdateTypeDetail = {\r\n timeStamp: number;\r\n stateKey: string;\r\n updateType: \"update\" | \"insert\" | \"cut\";\r\n path: string[];\r\n status: \"new\" | \"sent\" | \"synced\";\r\n oldValue: any;\r\n newValue: any;\r\n userId?: number;\r\n};\r\n\r\nexport type ActionsType<T> = {\r\n type: \"onChange\";\r\n action: ({ state, actionType }: { state: T; actionType: string }) => void;\r\n debounce?: number;\r\n}[];\r\n\r\ntype ArrayToObject<T extends string[]> = Record<T[number], string>;\r\ntype CookieType<T> = {\r\n timeStamp: number;\r\n value: T;\r\n cookieName: string;\r\n OnUnMountCookie?: Boolean;\r\n};\r\nexport type CogsCookiesType<T extends string[] = string[]> = CookieType<\r\n ArrayToObject<T>\r\n>;\r\nexport type ReactivityType = \"none\" | \"component\" | \"deps\" | \"all\";\r\n\r\ntype ValidationOptionsType = {\r\n key?: string;\r\n zodSchema?: ZodObject<ZodRawShape> | ZodArray<ZodObject<ZodRawShape>>;\r\n onBlur?: boolean;\r\n};\r\n\r\nexport type OptionsType<T extends unknown = unknown> = {\r\n log?: boolean;\r\n componentId?: string;\r\n serverSync?: ServerSyncType<T>;\r\n validation?: ValidationOptionsType;\r\n enableServerState?: boolean;\r\n middleware?: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void;\r\n\r\n modifyState?: (state: T) => T;\r\n localStorage?: { key: string | ((state: T) => string) };\r\n formElements?: FormsElementsType;\r\n enabledSync?: (state: T) => boolean;\r\n reactiveDeps?: (state: T) => any[] | true;\r\n reactiveType?: ReactivityType[] | ReactivityType;\r\n syncUpdate?: Partial<UpdateTypeDetail>;\r\n\r\n initialState?: T;\r\n dependencies?: any[]; // Just like useEffect dependencies\r\n};\r\nexport type ServerSyncType<T> = {\r\n testKey?: string;\r\n syncKey: (({ state }: { state: T }) => string) | string;\r\n syncFunction: ({ state }: { state: T }) => void;\r\n debounce?: number;\r\n mutation: UseMutationResult<any, unknown, any, unknown>;\r\n snapshot?: {\r\n name: (({ state }: { state: T }) => string) | string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\nexport type SyncActionsType<T> = {\r\n syncKey: string;\r\n\r\n rollBackState?: T;\r\n actionTimeStamp: number;\r\n retryCount?: number;\r\n status:\r\n | \"success\"\r\n | \"waiting\"\r\n | \"rolledBack\"\r\n | \"error\"\r\n | \"cancelled\"\r\n | \"failed\";\r\n snapshot?: {\r\n name: string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\n\r\nexport type ValidationWrapperOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n active: boolean;\r\n stretch?: boolean;\r\n path: string[];\r\n message?: string;\r\n data?: T;\r\n key?: string;\r\n};\r\nexport type SyncRenderOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n time: number;\r\n data?: T;\r\n key?: string;\r\n};\r\n\r\ntype FormsElementsType<T extends unknown = unknown> = {\r\n validation?: (options: ValidationWrapperOptions<T>) => React.ReactNode;\r\n syncRender?: (options: SyncRenderOptions<T>) => React.ReactNode;\r\n};\r\n\r\nexport type InitialStateInnerType<T extends unknown = unknown> = {\r\n initialState: T;\r\n} & OptionsType<T>;\r\n\r\nexport type InitialStateType<T> = {\r\n [key: string]: InitialStateInnerType<T>;\r\n};\r\n\r\nexport type AllStateTypes<T extends unknown> = Record<string, T>;\r\n\r\nexport type CogsInitialState<T> = {\r\n initialState: T;\r\n formElements?: FormsElementsType<T>;\r\n};\r\n\r\nexport type TransformedStateType<T> = {\r\n [P in keyof T]: T[P] extends CogsInitialState<infer U> ? U : T[P];\r\n};\r\n\r\nfunction setAndMergeOptions(stateKey: string, newOptions: OptionsType<any>) {\r\n const getInitialOptions = getGlobalStore.getState().getInitialOptions;\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n\r\n setInitialStateOptions(stateKey as string, {\r\n ...initialOptions,\r\n ...newOptions,\r\n });\r\n}\r\nfunction setOptions<StateKey, Opt>({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n}: {\r\n stateKey: StateKey;\r\n options?: OptionsType<any>;\r\n initialOptionsPart: Record<string, any>;\r\n}) {\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n const initialOptionsPartState = initialOptionsPart[stateKey as string] || {};\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n const mergedOptions = { ...initialOptionsPartState, ...initialOptions };\r\n\r\n let needToAdd = false;\r\n if (options) {\r\n for (const key in options) {\r\n if (!mergedOptions.hasOwnProperty(key)) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key as keyof typeof options];\r\n } else {\r\n if (\r\n key == \"localStorage\" &&\r\n options[key] &&\r\n mergedOptions[key].key !== options[key]?.key\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n }\r\n }\r\n }\r\n console.log(\"existingOptions-------\", mergedOptions);\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 (\r\n Object.keys(initialOptionsPart).length > 0 ||\r\n (opt && Object.keys(opt).length > 0)\r\n ) {\r\n Object.keys(initialOptionsPart).forEach((key) => {\r\n // Get the existing options for this state key\r\n initialOptionsPart[key] = initialOptionsPart[key] || {};\r\n\r\n initialOptionsPart[key].formElements = {\r\n ...opt?.formElements, // Global defaults first\r\n ...opt?.validation,\r\n ...(initialOptionsPart[key].formElements || {}), // State-specific overrides\r\n };\r\n const existingOptions = getInitialOptions(key);\r\n console.log(\"existingOptions\", existingOptions, initialOptionsPart[key]);\r\n if (!existingOptions) {\r\n getGlobalStore\r\n .getState()\r\n .setInitialStateOptions(key, initialOptionsPart[key]);\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\r\n setOptions({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n });\r\n\r\n const thiState =\r\n getGlobalStore.getState().cogsStateStore[stateKey as string] ||\r\n statePart[stateKey as string];\r\n const partialState = options?.modifyState\r\n ? options.modifyState(thiState)\r\n : thiState;\r\n\r\n const [state, updater] = useCogsStateFn<(typeof statePart)[StateKey]>(\r\n partialState,\r\n {\r\n stateKey: stateKey as string,\r\n syncUpdate: options?.syncUpdate,\r\n componentId,\r\n localStorage: options?.localStorage,\r\n middleware: options?.middleware,\r\n enabledSync: options?.enabledSync,\r\n reactiveType: options?.reactiveType,\r\n reactiveDeps: options?.reactiveDeps,\r\n initialState: options?.initialState,\r\n dependencies: options?.dependencies,\r\n }\r\n );\r\n\r\n return updater;\r\n };\r\n\r\n function setCogsOptions<StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options: OptionsType<(typeof statePart)[StateKey]>\r\n ) {\r\n setOptions({ stateKey, options, initialOptionsPart });\r\n }\r\n\r\n return { useCogsState, setCogsOptions };\r\n};\r\n\r\nconst {\r\n setUpdaterState,\r\n setState,\r\n getInitialOptions,\r\n getKeyState,\r\n getValidationErrors,\r\n setStateLog,\r\n updateInitialStateGlobal,\r\n addValidationError,\r\n removeValidationError,\r\n setServerSyncActions,\r\n} = getGlobalStore.getState();\r\n\r\nconst loadFromLocalStorage = (localStorageKey: string) => {\r\n if (!localStorageKey) return null;\r\n\r\n try {\r\n const storedData = window.localStorage.getItem(localStorageKey);\r\n if (!storedData) return null;\r\n\r\n const parsedData = JSON.parse(storedData);\r\n\r\n return parsedData;\r\n } catch (error) {\r\n console.error(\"Error loading from localStorage:\", error);\r\n return null;\r\n }\r\n};\r\n\r\nconst saveToLocalStorage = <T,>(\r\n state: T,\r\n thisKey: string,\r\n currentInitialOptions: any,\r\n sessionId?: string\r\n) => {\r\n if (currentInitialOptions?.log) {\r\n console.log(\r\n \"saving to localstorage\",\r\n thisKey,\r\n currentInitialOptions.localStorage?.key,\r\n sessionId\r\n );\r\n }\r\n const key = isFunction(currentInitialOptions?.localStorage?.key)\r\n ? currentInitialOptions.localStorage?.key(state)\r\n : currentInitialOptions?.localStorage?.key;\r\n if (key && sessionId) {\r\n const data: LocalStorageData<T> = {\r\n state,\r\n lastUpdated: Date.now(),\r\n lastSyncedWithServer:\r\n getGlobalStore.getState().serverSyncLog[thisKey]?.[0]?.timeStamp,\r\n baseServerState: getGlobalStore.getState().serverState[thisKey],\r\n };\r\n\r\n const storageKey = `${sessionId}-${thisKey}-${key}`;\r\n\r\n window.localStorage.setItem(storageKey, JSON.stringify(data));\r\n }\r\n};\r\n\r\ntype LocalStorageData<T> = {\r\n state: T;\r\n lastUpdated: number;\r\n lastSyncedWithServer?: number;\r\n baseServerState?: T; // Add this to track what server state our changes are based on\r\n};\r\n\r\nconst updateGlobalState = (\r\n thisKey: string,\r\n initialState: any,\r\n newState: any,\r\n effectiveSetState: EffectiveSetState<any>,\r\n componentId: string,\r\n sessionId?: string\r\n) => {\r\n // Update all global state at once\r\n const updates = {\r\n initialState: initialState,\r\n updaterState: createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n ),\r\n state: newState,\r\n };\r\n\r\n startTransition(() => {\r\n updateInitialStateGlobal(thisKey, updates.initialState);\r\n setUpdaterState(thisKey, updates.updaterState);\r\n setState(thisKey, updates.state);\r\n });\r\n};\r\n\r\nconst notifyComponents = (thisKey: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n if (!stateEntry) return;\r\n\r\n // Batch component updates\r\n const updates = new Set<() => void>();\r\n stateEntry.components.forEach((component) => {\r\n updates.add(() => component.forceUpdate());\r\n });\r\n\r\n // Schedule updates in the next tick to allow batching\r\n queueMicrotask(() => {\r\n startTransition(() => {\r\n updates.forEach((update) => update());\r\n });\r\n });\r\n};\r\n\r\nexport const notifyComponent = (stateKey: string, componentId: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // Force an update to ensure the current value is saved\r\n\r\n component.forceUpdate();\r\n }\r\n }\r\n};\r\n\r\nexport function useCogsStateFn<TStateObject extends unknown>(\r\n stateObject: TStateObject,\r\n {\r\n stateKey,\r\n serverSync,\r\n localStorage,\r\n formElements,\r\n middleware,\r\n reactiveDeps,\r\n reactiveType,\r\n componentId,\r\n initialState,\r\n syncUpdate,\r\n dependencies,\r\n }: {\r\n stateKey?: string;\r\n componentId?: string;\r\n } & OptionsType<TStateObject> = {}\r\n) {\r\n const [reactiveForce, forceUpdate] = useState({}); //this is the key to reactivity\r\n const { sessionId } = useCogsConfig();\r\n\r\n let noStateKey = stateKey ? false : true;\r\n const [thisKey] = useState(stateKey ?? uuidv4());\r\n const stateLog = getGlobalStore.getState().stateLog[thisKey];\r\n const componentUpdatesRef = useRef(new Set<string>());\r\n const componentIdRef = useRef(componentId ?? uuidv4());\r\n const latestInitialOptionsRef = useRef<any>(null);\r\n latestInitialOptionsRef.current = getInitialOptions(thisKey as string);\r\n\r\n useEffect(() => {\r\n if (syncUpdate && syncUpdate.stateKey === thisKey && syncUpdate.path?.[0]) {\r\n // Update the actual state value\r\n setState(thisKey, (prevState: any) => ({\r\n ...prevState,\r\n [syncUpdate.path![0]!]: syncUpdate.newValue,\r\n }));\r\n\r\n // Create combined key and update sync info\r\n const syncKey = `${syncUpdate.stateKey}:${syncUpdate.path.join(\".\")}`;\r\n getGlobalStore.getState().setSyncInfo(syncKey, {\r\n timeStamp: syncUpdate.timeStamp!,\r\n userId: syncUpdate.userId!,\r\n });\r\n }\r\n }, [syncUpdate]);\r\n\r\n useEffect(() => {\r\n setAndMergeOptions(thisKey as string, {\r\n initialState,\r\n });\r\n const options = latestInitialOptionsRef.current;\r\n let localData = null;\r\n\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options?.localStorage?.key(initialState)\r\n : options?.localStorage?.key;\r\n if (options?.log) {\r\n console.log(\"newoptions\", options);\r\n console.log(\"localkey\", localkey);\r\n console.log(\"initialState\", initialState);\r\n }\r\n if (localkey && sessionId) {\r\n localData = loadFromLocalStorage(\r\n sessionId + \"-\" + thisKey + \"-\" + localkey\r\n );\r\n if (!initialState) {\r\n if (options?.log) {\r\n console.log(\r\n \"localData\",\r\n localData,\r\n sessionId + \"-\" + thisKey + \"-\" + localkey\r\n );\r\n }\r\n\r\n updateGlobalState(\r\n thisKey,\r\n initialState,\r\n localData,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n\r\n notifyComponents(thisKey);\r\n forceUpdate({});\r\n }\r\n }\r\n\r\n let newState = null;\r\n if (initialState) {\r\n newState = initialState;\r\n\r\n if (localData) {\r\n if (localData.lastUpdated > (localData.lastSyncedWithServer || 0)) {\r\n newState = localData.state;\r\n }\r\n }\r\n updateGlobalState(\r\n thisKey,\r\n initialState,\r\n newState,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n\r\n notifyComponents(thisKey);\r\n forceUpdate({});\r\n }\r\n }, [initialState, ...(dependencies || [])]);\r\n\r\n useLayoutEffect(() => {\r\n if (noStateKey) {\r\n setAndMergeOptions(thisKey as string, {\r\n serverSync,\r\n formElements,\r\n initialState,\r\n localStorage,\r\n middleware,\r\n });\r\n }\r\n\r\n const depsKey = `${thisKey}////${componentIdRef.current}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(thisKey) || {\r\n components: new Map(),\r\n };\r\n\r\n stateEntry.components.set(depsKey, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set(),\r\n deps: [],\r\n depsFunction: reactiveDeps || undefined,\r\n reactiveType: reactiveType ?? [\"component\", \"deps\"],\r\n });\r\n\r\n getGlobalStore.getState().stateComponents.set(thisKey, stateEntry);\r\n //need to force update to create the stateUpdates references\r\n forceUpdate({});\r\n return () => {\r\n const depsKey = `${thisKey}////${componentIdRef.current}`;\r\n\r\n if (stateEntry) {\r\n stateEntry.components.delete(depsKey);\r\n if (stateEntry.components.size === 0) {\r\n getGlobalStore.getState().stateComponents.delete(thisKey);\r\n }\r\n }\r\n };\r\n }, []);\r\n\r\n const effectiveSetState = (\r\n newStateOrFunction:\r\n | TStateObject\r\n | ((prevState: TStateObject) => TStateObject),\r\n path: string[],\r\n updateObj: { updateType: \"insert\" | \"cut\" | \"update\" },\r\n validationKey?: string\r\n ) => {\r\n if (Array.isArray(path)) {\r\n const pathKey = `${thisKey}-${path.join(\".\")}`;\r\n componentUpdatesRef.current.add(pathKey);\r\n }\r\n setState(thisKey, (prevValue: TStateObject) => {\r\n const payload = isFunction<TStateObject>(newStateOrFunction)\r\n ? newStateOrFunction(prevValue as TStateObject)\r\n : newStateOrFunction;\r\n\r\n const signalId = `${thisKey}-${path.join(\".\")}`;\r\n if (signalId) {\r\n let isArrayOperation = false;\r\n let elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(signalId);\r\n\r\n if (\r\n (!elements || elements.size === 0) &&\r\n (updateObj.updateType === \"insert\" || updateObj.updateType === \"cut\")\r\n ) {\r\n // Remove last segment (index) from path\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n // If it's an array, use that path for signal\r\n if (Array.isArray(arrayValue)) {\r\n isArrayOperation = true;\r\n const arraySignalId = `${thisKey}-${arrayPath.join(\".\")}`;\r\n elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(arraySignalId);\r\n }\r\n }\r\n\r\n if (elements) {\r\n const newValue = isArrayOperation\r\n ? getNestedValue(payload, path.slice(0, -1))\r\n : getNestedValue(payload, path);\r\n elements.forEach(({ parentId, position, effect }) => {\r\n const parent = document.querySelector(\r\n `[data-parent-id=\"${parentId}\"]`\r\n );\r\n if (parent) {\r\n const childNodes = Array.from(parent.childNodes);\r\n if (childNodes[position]) {\r\n const displayValue = effect\r\n ? new Function(\"state\", `return (${effect})(state)`)(newValue)\r\n : newValue;\r\n childNodes[position].textContent = String(displayValue);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n if (\r\n updateObj.updateType === \"update\" &&\r\n (validationKey || latestInitialOptionsRef.current?.validationKey) &&\r\n path\r\n ) {\r\n removeValidationError(\r\n (validationKey || latestInitialOptionsRef.current?.validationKey) +\r\n \".\" +\r\n path.join(\".\")\r\n );\r\n }\r\n const arrayWithoutIndex = path.slice(0, path.length - 1);\r\n if (\r\n updateObj.updateType === \"cut\" &&\r\n latestInitialOptionsRef.current?.validationKey\r\n ) {\r\n removeValidationError(\r\n latestInitialOptionsRef.current?.validationKey +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n }\r\n if (\r\n updateObj.updateType === \"insert\" &&\r\n latestInitialOptionsRef.current?.validationKey\r\n ) {\r\n let getValidation = getValidationErrors(\r\n latestInitialOptionsRef.current?.validationKey +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n\r\n //TODO this is untested its supposed to cahnge teh validation errors alreaady stored when a new entry is push\r\n\r\n getValidation.filter(([k, v]) => {\r\n let length = k?.split(\".\").length;\r\n\r\n if (\r\n k == arrayWithoutIndex.join(\".\") &&\r\n length == arrayWithoutIndex.length - 1\r\n ) {\r\n // console.log(length, pathWithoutIndex.length);\r\n let newKey = k + \".\" + arrayWithoutIndex;\r\n removeValidationError(k!);\r\n addValidationError(newKey, v!);\r\n }\r\n });\r\n }\r\n\r\n const oldValue = getNestedValue(prevValue, path);\r\n const newValue = getNestedValue(payload, path);\r\n const pathToCheck =\r\n updateObj.updateType === \"update\"\r\n ? path.join(\".\")\r\n : [...path].slice(0, -1).join(\".\");\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n\r\n if (stateEntry) {\r\n for (const [key, component] of stateEntry.components.entries()) {\r\n let shouldUpdate = false;\r\n const reactiveTypes = Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"];\r\n\r\n // Skip if reactivity is disabled\r\n if (reactiveTypes.includes(\"none\")) {\r\n continue;\r\n }\r\n\r\n // Force update if \"all\" is specified\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n\r\n continue;\r\n }\r\n\r\n // Check component-level path reactivity\r\n if (reactiveTypes.includes(\"component\")) {\r\n if (\r\n component.paths &&\r\n (component.paths.has(pathToCheck) || component.paths.has(\"\"))\r\n ) {\r\n shouldUpdate = true;\r\n }\r\n }\r\n\r\n // Check dependency-based reactivity\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(payload);\r\n\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) {\r\n shouldUpdate = true;\r\n }\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n shouldUpdate = true;\r\n }\r\n }\r\n }\r\n\r\n if (shouldUpdate) {\r\n component.forceUpdate();\r\n }\r\n }\r\n }\r\n const timeStamp = Date.now();\r\n\r\n const newUpdate = {\r\n timeStamp,\r\n stateKey: thisKey,\r\n path,\r\n updateType: updateObj.updateType,\r\n status: \"new\" as const,\r\n oldValue,\r\n newValue,\r\n } satisfies UpdateTypeDetail;\r\n\r\n setStateLog(thisKey, (prevLogs) => {\r\n const logs = [...(prevLogs ?? []), newUpdate];\r\n\r\n // Aggregate the updates by stateKey and path\r\n const aggregatedLogs = logs.reduce((acc, log) => {\r\n const uniqueKey = `${log.stateKey}:${JSON.stringify(log.path)}`;\r\n const existing = acc.get(uniqueKey);\r\n\r\n if (existing) {\r\n // Update the existing entry with the most recent details\r\n existing.timeStamp = Math.max(existing.timeStamp, log.timeStamp);\r\n existing.newValue = log.newValue; // Overwrite with the latest value\r\n existing.oldValue = existing.oldValue ?? log.oldValue; // Retain the initial oldValue\r\n existing.updateType = log.updateType; // Update to the most recent type\r\n } else {\r\n // Add the log if no existing match is found\r\n acc.set(uniqueKey, { ...(log as any) });\r\n }\r\n\r\n return acc;\r\n }, new Map<string, typeof newUpdate>());\r\n\r\n // Convert the aggregated map back to an array\r\n return Array.from(aggregatedLogs.values());\r\n });\r\n\r\n saveToLocalStorage(\r\n payload,\r\n thisKey,\r\n latestInitialOptionsRef.current,\r\n sessionId\r\n );\r\n\r\n if (middleware) {\r\n middleware({\r\n updateLog: stateLog,\r\n update: newUpdate,\r\n });\r\n }\r\n if (latestInitialOptionsRef.current?.serverSync) {\r\n const serverStateStore = getGlobalStore.getState().serverState[thisKey];\r\n const serverSync = latestInitialOptionsRef.current?.serverSync;\r\n setServerSyncActions(thisKey, {\r\n syncKey:\r\n typeof serverSync.syncKey == \"string\"\r\n ? serverSync.syncKey\r\n : serverSync.syncKey({ state: payload }),\r\n rollBackState: serverStateStore,\r\n actionTimeStamp: Date.now() + (serverSync.debounce ?? 3000),\r\n status: \"waiting\",\r\n });\r\n }\r\n\r\n return payload;\r\n });\r\n };\r\n if (!getGlobalStore.getState().updaterState[thisKey]) {\r\n setUpdaterState(\r\n thisKey,\r\n createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n )\r\n );\r\n if (!getGlobalStore.getState().cogsStateStore[thisKey]) {\r\n setState(thisKey, stateObject);\r\n }\r\n if (!getGlobalStore.getState().initialStateGlobal[thisKey]) {\r\n updateInitialStateGlobal(thisKey, stateObject);\r\n }\r\n }\r\n\r\n const updaterFinal = useMemo(() => {\r\n // Create proxy with baseObject as target\r\n return createProxyHandler<TStateObject>(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n }, [thisKey]);\r\n\r\n return [getKeyState(thisKey), updaterFinal] as [\r\n TStateObject,\r\n StateObject<TStateObject>,\r\n ];\r\n}\r\n\r\nfunction createProxyHandler<T>(\r\n stateKey: string,\r\n effectiveSetState: EffectiveSetState<T>,\r\n componentId: string,\r\n sessionId?: string\r\n): StateObject<T> {\r\n // ADDED: Enhanced cache with versioning\r\n type CacheEntry = {\r\n proxy: any;\r\n stateVersion: number;\r\n };\r\n const shapeCache = new Map<string, CacheEntry>();\r\n let stateVersion = 0;\r\n\r\n // ADDED: Cache invalidation helper\r\n const invalidateCachePath = (path: string[]) => {\r\n const pathKey = path.join(\".\");\r\n for (const [key] of shapeCache) {\r\n if (key === pathKey || key.startsWith(pathKey + \".\")) {\r\n shapeCache.delete(key);\r\n }\r\n }\r\n stateVersion++;\r\n };\r\n\r\n const baseObj = {\r\n removeValidation: (obj?: { validationKey?: string }) => {\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n },\r\n\r\n revertToInitialState: (obj?: { validationKey?: string }) => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n if (init?.key) {\r\n removeValidationError(init?.key);\r\n }\r\n\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n\r\n // ADDED: Clear cache on revert\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newProxy = rebuildStateShape(initialState, []);\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n startTransition(() => {\r\n setUpdaterState(stateKey, newProxy);\r\n setState(stateKey, initialState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return initialState;\r\n },\r\n updateInitialState: (newState: T) => {\r\n // ADDED: Clear cache on initial state update\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newUpdaterState = createProxyHandler(\r\n stateKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n startTransition(() => {\r\n updateInitialStateGlobal(stateKey, newState);\r\n setUpdaterState(stateKey, newUpdaterState);\r\n setState(stateKey, newState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return {\r\n fetchId: (field: keyof T) => newUpdaterState.get()[field],\r\n };\r\n },\r\n _initialState: getGlobalStore.getState().initialStateGlobal[stateKey],\r\n _serverState: getGlobalStore.getState().serverState[stateKey],\r\n _isLoading: getGlobalStore.getState().isLoadingGlobal[stateKey],\r\n _isServerSynced: () => {\r\n const serverState = getGlobalStore.getState().serverState[stateKey];\r\n return Boolean(\r\n serverState && isDeepEqual(serverState, getKeyState(stateKey))\r\n );\r\n },\r\n };\r\n\r\n function rebuildStateShape(\r\n currentState: T,\r\n path: string[] = [],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ): any {\r\n const cacheKey = path.map(String).join(\".\");\r\n\r\n // MODIFIED: Cache check with version\r\n const cachedEntry = shapeCache.get(cacheKey);\r\n // if (cachedEntry?.stateVersion === stateVersion) {\r\n // return cachedEntry.proxy;\r\n // }\r\n type CallableStateObject<T> = {\r\n (): T;\r\n } & {\r\n [key: string]: any;\r\n };\r\n\r\n const baseFunction = function () {\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n } as unknown as CallableStateObject<T>;\r\n\r\n // Copy properties from baseObj to the function with type assertion\r\n Object.keys(baseObj).forEach((key) => {\r\n (baseFunction as any)[key] = (baseObj as any)[key];\r\n });\r\n\r\n const handler = {\r\n apply(target: any, thisArg: any, args: any[]) {\r\n console.log(\r\n `PROXY APPLY TRAP HIT: stateKey=${stateKey}, path=${path.join(\".\")}`\r\n ); // <--- ADD LOGGING\r\n console.trace(\"Apply trap stack trace\");\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n },\r\n\r\n get(target: any, prop: string) {\r\n if (\r\n prop !== \"then\" &&\r\n !prop.startsWith(\"$\") &&\r\n prop !== \"stateMapNoRender\"\r\n ) {\r\n const currentPath = path.join(\".\");\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n\r\n if (stateEntry) {\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // Only add paths for non-root or specifically for get() at root\r\n if (path.length > 0 || prop === \"get\") {\r\n component.paths.add(currentPath);\r\n }\r\n } else {\r\n }\r\n }\r\n }\r\n if (prop === \"_status\") {\r\n // Get current state at this path (non-reactive version)\r\n const thisReactiveState = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n }\r\n if (prop === \"getStatus\") {\r\n return function () {\r\n // Get current state at this path (reactive version)\r\n const thisReactiveState = getGlobalStore().getNestedState(\r\n stateKey,\r\n path\r\n );\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n };\r\n }\r\n if (prop === \"removeStorage\") {\r\n return () => {\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n console.log(\"removing storage\", storageKey);\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n };\r\n }\r\n if (prop === \"showValidationErrors\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n const errors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key + \".\" + path.join(\".\"));\r\n\r\n return errors;\r\n };\r\n }\r\n if (Array.isArray(currentState)) {\r\n if (prop === \"getSelected\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n if (selectedIndex === undefined) return undefined;\r\n return rebuildStateShape(\r\n currentState[selectedIndex],\r\n [...path, selectedIndex.toString()],\r\n meta\r\n );\r\n };\r\n }\r\n if (prop === \"getSelectedIndex\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n\r\n return selectedIndex ?? -1;\r\n };\r\n }\r\n if (prop === \"stateSort\") {\r\n return (\r\n compareFn: (\r\n a: InferArrayElement<T>,\r\n b: InferArrayElement<T>\r\n ) => number\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n\r\n // Create a shallow copy with original indices\r\n const arrayCopy = currentArray.map((v: any, i: number) => ({\r\n ...v,\r\n __origIndex: i.toString(),\r\n }));\r\n\r\n // Sort the copy using the provided compare function\r\n const sortedArray = [...arrayCopy].sort(compareFn);\r\n\r\n // ADDED: Clear cache for sort operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // Return the sorted array with state objects\r\n return rebuildStateShape(sortedArray as any, path, {\r\n filtered: [...(meta?.filtered || []), path],\r\n validIndices: sortedArray.map((item) =>\r\n parseInt(item.__origIndex as string)\r\n ),\r\n });\r\n };\r\n }\r\n if (prop === \"stateMap\" || prop === \"stateMapNoRender\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n const isFiltered = meta?.filtered?.some(\r\n (p) => p.join(\".\") === path.join(\".\")\r\n );\r\n const arrayToMap = isFiltered\r\n ? currentState\r\n : getGlobalStore.getState().getNestedState(stateKey, path);\r\n\r\n if (prop !== \"stateMapNoRender\") {\r\n shapeCache.clear();\r\n stateVersion++;\r\n }\r\n\r\n return arrayToMap.map((val: any, index: number) => {\r\n const thisIndex =\r\n isFiltered && val.__origIndex ? val.__origIndex : index;\r\n const elementProxy = rebuildStateShape(\r\n val,\r\n [...path, thisIndex.toString()],\r\n meta\r\n );\r\n return callbackfn(\r\n val,\r\n elementProxy,\r\n index,\r\n currentState as any,\r\n rebuildStateShape(currentState as any, path, meta)\r\n );\r\n });\r\n };\r\n }\r\n if (prop === \"$stateMap\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n return createElement(SignalMapRenderer, {\r\n proxy: {\r\n _stateKey: stateKey,\r\n _path: path,\r\n _mapFn: callbackfn as any, // Pass the actual function, not string\r\n },\r\n\r\n rebuildStateShape,\r\n });\r\n };\r\n }\r\n if (prop === \"stateFlattenOn\") {\r\n return (fieldName: string) => {\r\n const isFiltered = meta?.filtered?.some(\r\n (p) => p.join(\".\") === path.join(\".\")\r\n );\r\n const arrayToMap = isFiltered\r\n ? currentState\r\n : getGlobalStore.getState().getNestedState(stateKey, path);\r\n\r\n // ADDED: Clear shape cache for flattening operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const flattenedResults = arrayToMap.flatMap(\r\n (val: any, index: number) => {\r\n return val[fieldName] ?? [];\r\n }\r\n );\r\n\r\n return rebuildStateShape(\r\n flattenedResults,\r\n [...path, \"[*]\", fieldName],\r\n meta\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"findWith\") {\r\n return (\r\n thisKey: keyof InferArrayElement<T>,\r\n thisValue: InferArrayElement<T>[keyof InferArrayElement<T>]\r\n ) => {\r\n const foundIndex = currentState.findIndex(\r\n (obj: any) => obj[thisKey] === thisValue\r\n );\r\n if (foundIndex === -1) return undefined;\r\n const foundValue = currentState[foundIndex];\r\n const newPath = [...path, foundIndex.toString()];\r\n // console.log(\r\n // \"findWithfindWithfindWithfindWith\",\r\n // stateKey,\r\n // foundValue,\r\n // newPath,\r\n // );\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // ADDED: Clear cache for find operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n // Try returning without spread\r\n return rebuildStateShape(foundValue, newPath);\r\n };\r\n }\r\n\r\n if (prop === \"index\") {\r\n return (index: number) => {\r\n const indexValue = currentState[index];\r\n return rebuildStateShape(indexValue, [...path, index.toString()]);\r\n };\r\n }\r\n\r\n if (prop === \"insert\") {\r\n return (payload: UpdateArg<T>) => {\r\n // ADDED: Invalidate cache on insert\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, payload, path, stateKey);\r\n return rebuildStateShape(\r\n getGlobalStore.getState().cogsStateStore[stateKey],\r\n []\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"uniqueInsert\") {\r\n return (\r\n payload: UpdateArg<T>,\r\n fields?: (keyof InferArrayElement<T>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n const newValue = isFunction<T>(payload)\r\n ? payload(currentArray as any)\r\n : (payload as any);\r\n\r\n let matchedItem: any = null;\r\n const isUnique = !currentArray.some((item) => {\r\n if (fields) {\r\n const isMatch = fields.every((field) =>\r\n isDeepEqual(item[field], newValue[field])\r\n );\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n }\r\n const isMatch = isDeepEqual(item, newValue);\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n });\r\n\r\n if (isUnique) {\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, newValue, path, stateKey);\r\n } else if (onMatch && matchedItem) {\r\n const updatedItem = onMatch(matchedItem);\r\n const updatedArray = currentArray.map((item) =>\r\n isDeepEqual(item, matchedItem) ? updatedItem : item\r\n );\r\n invalidateCachePath(path);\r\n updateFn(effectiveSetState, updatedArray as any, path);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"cut\") {\r\n return (index: number, options?: { waitForSync?: boolean }) => {\r\n if (options?.waitForSync) return;\r\n // ADDED: Invalidate cache on cut\r\n invalidateCachePath(path);\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n };\r\n }\r\n if (prop === \"cutByValue\") {\r\n return (value: string | number | boolean) => {\r\n for (let index = 0; index < currentState.length; index++) {\r\n if (currentState[index] === value) {\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n }\r\n }\r\n };\r\n }\r\n if (prop === \"toggleByValue\") {\r\n return (value: string | number | boolean) => {\r\n const index = currentState.findIndex((item) => item === value);\r\n if (index > -1) {\r\n // Value exists, so cut it\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n } else {\r\n // Value doesn't exist, so insert it\r\n pushFunc(effectiveSetState, value as any, path, stateKey);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"stateFilter\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const newVal = currentState.map((v: any, i: number) => ({\r\n ...v,\r\n __origIndex: i.toString(),\r\n }));\r\n\r\n const validIndices: number[] = [];\r\n const filteredArray: Array<InferArrayElement<T>> = [];\r\n\r\n for (let i = 0; i < newVal.length; i++) {\r\n if (callbackfn(newVal[i], i)) {\r\n validIndices.push(i);\r\n filteredArray.push(newVal[i]);\r\n }\r\n }\r\n\r\n // ADDED: Clear cache for filter operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // Always include validIndices, even if it's an empty array\r\n return rebuildStateShape(filteredArray as any, path, {\r\n filtered: [...(meta?.filtered || []), path],\r\n validIndices: validIndices, // Always pass validIndices, even if empty\r\n });\r\n };\r\n }\r\n }\r\n const lastPathElement = path[path.length - 1];\r\n if (!isNaN(Number(lastPathElement))) {\r\n const parentPath = path.slice(0, -1);\r\n const parentValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n\r\n if (Array.isArray(parentValue) && prop === \"cut\") {\r\n return () =>\r\n cutFunc(\r\n effectiveSetState,\r\n parentPath,\r\n stateKey,\r\n Number(lastPathElement)\r\n );\r\n }\r\n }\r\n\r\n if (prop === \"get\") {\r\n return () => getGlobalStore.getState().getNestedState(stateKey, path);\r\n }\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$get\") {\r\n return () =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n });\r\n }\r\n if (prop === \"lastSynced\") {\r\n const syncKey = `${stateKey}:${path.join(\".\")}`;\r\n return getGlobalStore.getState().getSyncInfo(syncKey);\r\n }\r\n\r\n if (prop == \"getLocalStorage\") {\r\n return (key: string) =>\r\n loadFromLocalStorage(sessionId + \"-\" + stateKey + \"-\" + key);\r\n }\r\n if (prop === \"_selected\") {\r\n const parentPath = path.slice(0, -1);\r\n const parentKey = parentPath.join(\".\");\r\n const parent = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n if (Array.isArray(parent)) {\r\n const currentIndex = Number(path[path.length - 1]);\r\n return (\r\n currentIndex ===\r\n getGlobalStore.getState().getSelectedIndex(stateKey, parentKey)\r\n );\r\n }\r\n return undefined;\r\n }\r\n if (prop === \"setSelected\") {\r\n return (value: boolean) => {\r\n const parentPath = path.slice(0, -1);\r\n const thisIndex = Number(path[path.length - 1]);\r\n const parentKey = parentPath.join(\".\");\r\n\r\n if (value) {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, thisIndex);\r\n } else {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, undefined);\r\n }\r\n\r\n const nested = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, [...parentPath]);\r\n updateFn(effectiveSetState, nested, parentPath);\r\n\r\n // Invalidate cache for this path\r\n invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (path.length == 0) {\r\n if (prop === \"validateZodSchema\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n const addValidationError =\r\n getGlobalStore.getState().addValidationError;\r\n\r\n if (!init?.zodSchema) {\r\n throw new Error(\"Zod schema not found\");\r\n }\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n removeValidationError(init.key);\r\n const thisObject =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n\r\n try {\r\n // First clear any existing validation errors for this schema\r\n // This ensures we don't have stale errors\r\n const existingErrors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key);\r\n if (existingErrors && existingErrors.length > 0) {\r\n existingErrors.forEach(([errorPath]) => {\r\n if (errorPath && errorPath.startsWith(init.key!)) {\r\n removeValidationError(errorPath);\r\n }\r\n });\r\n }\r\n\r\n // Attempt to validate with Zod\r\n const result = init.zodSchema.safeParse(thisObject);\r\n\r\n if (!result.success) {\r\n // Process Zod errors and add them to the validation store\r\n const zodErrors = result.error.errors;\r\n\r\n zodErrors.forEach((error) => {\r\n const errorPath = error.path;\r\n const errorMessage = error.message;\r\n\r\n // Build the full path for the validation error\r\n // Format: validationKey.path.to.field\r\n const fullErrorPath = [init.key, ...errorPath].join(\".\");\r\n\r\n // Add the error to the store\r\n addValidationError(fullErrorPath, errorMessage);\r\n });\r\n\r\n notifyComponents(stateKey);\r\n\r\n return false;\r\n }\r\n\r\n return true;\r\n } catch (error) {\r\n console.error(\"Zod schema validation failed\", error);\r\n return false;\r\n }\r\n };\r\n }\r\n if (prop === \"_componentId\") return componentId;\r\n if (prop === \"getComponents\") {\r\n return () => getGlobalStore().stateComponents.get(stateKey);\r\n }\r\n if (prop === \"getAllFormRefs\") {\r\n return () => {\r\n return formRefStore.getState().getFormRefsByStateKey(stateKey);\r\n };\r\n }\r\n\r\n if (prop === \"_initialState\")\r\n return getGlobalStore.getState().initialStateGlobal[stateKey];\r\n if (prop === \"_serverState\")\r\n return getGlobalStore.getState().serverState[stateKey];\r\n if (prop === \"_isLoading\")\r\n return getGlobalStore.getState().isLoadingGlobal[stateKey];\r\n if (prop === \"revertToInitialState\")\r\n return baseObj.revertToInitialState;\r\n if (prop === \"updateInitialState\") return baseObj.updateInitialState;\r\n if (prop === \"removeValidation\") return baseObj.removeValidation;\r\n }\r\n if (prop === \"getFormRef\") {\r\n return () => {\r\n return formRefStore\r\n .getState()\r\n .getFormRef(stateKey + \".\" + path.join(\".\"));\r\n };\r\n }\r\n\r\n if (prop === \"validationWrapper\") {\r\n return ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => (\r\n <ValidationWrapper\r\n formOpts={\r\n hideMessage ? { validation: { message: \"\" } } : undefined\r\n }\r\n path={path}\r\n validationKey={\r\n getGlobalStore.getState().getInitialOptions(stateKey)\r\n ?.validation?.key || \"\"\r\n }\r\n stateKey={stateKey}\r\n validIndices={meta?.validIndices}\r\n >\r\n {children}\r\n </ValidationWrapper>\r\n );\r\n }\r\n\r\n if (prop === \"_stateKey\") return stateKey;\r\n if (prop === \"_path\") return path;\r\n if (prop === \"_isServerSynced\") return baseObj._isServerSynced;\r\n\r\n if (prop === \"update\") {\r\n return (payload: UpdateArg<T>, opts?: UpdateOpts<T>) => {\r\n // ADDED: Invalidate cache on update\r\n if (opts?.debounce) {\r\n debounce(() => {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }, opts.debounce);\r\n } else {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }\r\n invalidateCachePath(path);\r\n };\r\n }\r\n\r\n if (prop === \"formElement\") {\r\n return (child: FormControl<T>, formOpts?: FormOptsType) => {\r\n return (\r\n <FormControlComponent<T>\r\n setState={effectiveSetState}\r\n stateKey={stateKey}\r\n path={path}\r\n child={child}\r\n formOpts={formOpts}\r\n />\r\n );\r\n };\r\n }\r\n\r\n const nextPath = [...path, prop];\r\n const nextValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, nextPath);\r\n return rebuildStateShape(nextValue, nextPath, meta);\r\n },\r\n };\r\n\r\n const proxyInstance = new Proxy(baseFunction, handler);\r\n\r\n shapeCache.set(cacheKey, {\r\n proxy: proxyInstance,\r\n stateVersion: stateVersion,\r\n });\r\n\r\n return proxyInstance;\r\n }\r\n\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, [])\r\n );\r\n}\r\n\r\nexport function $cogsSignal(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n}) {\r\n return createElement(SignalRenderer, { proxy });\r\n}\r\n\r\nfunction SignalMapRenderer({\r\n proxy,\r\n\r\n rebuildStateShape,\r\n}: {\r\n proxy: {\r\n _stateKey: string;\r\n _path: string[];\r\n _mapFn: (\r\n value: any,\r\n setter: any,\r\n index: number,\r\n array: any[],\r\n arraySetter: any\r\n ) => ReactNode;\r\n };\r\n\r\n rebuildStateShape: (\r\n currentState: any,\r\n path: string[],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ) => any;\r\n}) {\r\n const value = getGlobalStore().getNestedState(proxy._stateKey, proxy._path);\r\n\r\n if (!Array.isArray(value)) {\r\n return null;\r\n }\r\n const arraySetter = rebuildStateShape(\r\n value,\r\n proxy._path\r\n ) as ArrayEndType<any>;\r\n // Use existing global state management\r\n return arraySetter.stateMapNoRender(\r\n (item, setter, index, value, arraysetter) => {\r\n // Execute map function in React context with existing state/proxies\r\n return proxy._mapFn(item, setter, index, value, arraysetter);\r\n }\r\n );\r\n}\r\nfunction SignalRenderer({\r\n proxy,\r\n}: {\r\n proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n };\r\n}) {\r\n const elementRef = useRef<HTMLSpanElement>(null);\r\n const signalId = `${proxy._stateKey}-${proxy._path.join(\".\")}`;\r\n\r\n useEffect(() => {\r\n const element = elementRef.current;\r\n if (!element || !element.parentElement) return;\r\n\r\n const parentElement = element.parentElement;\r\n const childNodes = Array.from(parentElement.childNodes);\r\n const position = childNodes.indexOf(element);\r\n\r\n let parentId = parentElement.getAttribute(\"data-parent-id\");\r\n if (!parentId) {\r\n parentId = `parent-${crypto.randomUUID()}`;\r\n parentElement.setAttribute(\"data-parent-id\", parentId);\r\n }\r\n\r\n const instanceId = `instance-${crypto.randomUUID()}`;\r\n const elementInfo = {\r\n instanceId,\r\n parentId,\r\n position,\r\n effect: proxy._effect,\r\n };\r\n\r\n getGlobalStore.getState().addSignalElement(signalId, elementInfo);\r\n\r\n // Get the raw value from the store\r\n const value = getGlobalStore\r\n .getState()\r\n .getNestedState(proxy._stateKey, proxy._path);\r\n\r\n let displayValue;\r\n if (proxy._effect) {\r\n try {\r\n displayValue = new Function(\r\n \"state\",\r\n `return (${proxy._effect})(state)`\r\n )(value);\r\n } catch (err) {\r\n console.error(\"Error evaluating effect function during mount:\", err);\r\n displayValue = value; // Fallback to raw value\r\n }\r\n } else {\r\n displayValue = value;\r\n }\r\n\r\n if (displayValue !== null && typeof displayValue === \"object\") {\r\n displayValue = JSON.stringify(displayValue);\r\n }\r\n\r\n const textNode = document.createTextNode(String(displayValue));\r\n element.replaceWith(textNode);\r\n }, [proxy._stateKey, proxy._path.join(\".\"), proxy._effect]);\r\n\r\n return createElement(\"span\", {\r\n ref: elementRef,\r\n style: { display: \"none\" },\r\n \"data-signal-id\": signalId,\r\n });\r\n}\r\nexport function $cogsSignalStore(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n}) {\r\n const value = useSyncExternalStore(\r\n (notify) => {\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(proxy._stateKey) || {\r\n components: new Map(),\r\n };\r\n stateEntry.components.set(proxy._stateKey, {\r\n forceUpdate: notify,\r\n paths: new Set([proxy._path.join(\".\")]),\r\n });\r\n return () => stateEntry.components.delete(proxy._stateKey);\r\n },\r\n () => getGlobalStore.getState().getNestedState(proxy._stateKey, proxy._path)\r\n );\r\n return createElement(\"text\", {}, String(value));\r\n}\r\n"],"names":["setAndMergeOptions","stateKey","newOptions","getInitialOptions","getGlobalStore","setInitialStateOptions","initialOptions","setOptions","options","initialOptionsPart","initialOptionsPartState","mergedOptions","needToAdd","key","addStateOptions","initialState","formElements","validation","createCogsState","opt","newInitialState","statePart","transformStateFunc","existingOptions","useCogsState","componentId","useState","uuidv4","thiState","partialState","state","updater","useCogsStateFn","setCogsOptions","setUpdaterState","setState","getKeyState","getValidationErrors","setStateLog","updateInitialStateGlobal","addValidationError","removeValidationError","setServerSyncActions","loadFromLocalStorage","localStorageKey","storedData","error","saveToLocalStorage","thisKey","currentInitialOptions","sessionId","isFunction","data","storageKey","updateGlobalState","newState","effectiveSetState","updates","createProxyHandler","startTransition","notifyComponents","stateEntry","component","update","notifyComponent","fullComponentId","stateObject","serverSync","localStorage","middleware","reactiveDeps","reactiveType","syncUpdate","dependencies","reactiveForce","forceUpdate","useCogsConfig","noStateKey","stateLog","componentUpdatesRef","useRef","componentIdRef","latestInitialOptionsRef","useEffect","prevState","syncKey","localData","localkey","useLayoutEffect","depsKey","newStateOrFunction","path","updateObj","validationKey","pathKey","prevValue","payload","signalId","isArrayOperation","elements","arrayPath","arrayValue","getNestedValue","arraySignalId","newValue","parentId","position","effect","parent","childNodes","displayValue","arrayWithoutIndex","k","v","length","newKey","oldValue","pathToCheck","shouldUpdate","reactiveTypes","depsResult","isDeepEqual","newUpdate","prevLogs","aggregatedLogs","acc","log","uniqueKey","existing","serverStateStore","updaterFinal","useMemo","shapeCache","stateVersion","invalidateCachePath","baseObj","obj","init","newProxy","rebuildStateShape","initalOptionsGet","localKey","newUpdaterState","field","serverState","currentState","meta","cacheKey","baseFunction","handler","target","thisArg","args","prop","currentPath","thisReactiveState","initialStateAtPath","selectedIndex","compareFn","sortedArray","i","item","callbackfn","isFiltered","p","arrayToMap","val","index","thisIndex","elementProxy","createElement","SignalMapRenderer","fieldName","flattenedResults","thisValue","foundIndex","foundValue","newPath","indexValue","pushFunc","fields","onMatch","currentArray","matchedItem","isMatch","updatedItem","updatedArray","updateFn","cutFunc","value","newVal","validIndices","filteredArray","lastPathElement","parentPath","parentValue","fn","$cogsSignal","parentKey","nested","thisObject","existingErrors","errorPath","result","errorMessage","fullErrorPath","formRefStore","children","hideMessage","jsx","ValidationWrapper","opts","debounce","child","formOpts","FormControlComponent","nextPath","nextValue","proxyInstance","proxy","SignalRenderer","setter","arraysetter","elementRef","element","parentElement","elementInfo","err","textNode","$cogsSignalStore","useSyncExternalStore","notify"],"mappings":";;;;;;;;;AAwYA,SAASA,GAAmBC,GAAkBC,GAA8B;AACpEC,QAAAA,IAAoBC,EAAe,SAAA,EAAW,mBAC9CC,IACJD,EAAe,SAAA,EAAW,wBAEtBE,IAAi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