cogsbox-state 0.5.231 → 0.5.232
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 +46 -46
- package/dist/CogsState.jsx.map +1 -1
- package/package.json +1 -1
- package/src/CogsState.tsx +2 -1
package/dist/CogsState.jsx
CHANGED
|
@@ -21,13 +21,13 @@ function ve({
|
|
|
21
21
|
options: i,
|
|
22
22
|
initialOptionsPart: S
|
|
23
23
|
}) {
|
|
24
|
-
const g = H(e) || {}, m = S[e] || {},
|
|
24
|
+
const g = H(e) || {}, m = S[e] || {}, $ = n.getState().setInitialStateOptions, p = { ...m, ...g };
|
|
25
25
|
let I = !1;
|
|
26
26
|
if (i)
|
|
27
27
|
for (const s in i)
|
|
28
28
|
p.hasOwnProperty(s) ? (s == "localStorage" && i[s] && p[s].key !== i[s]?.key && (I = !0, p[s] = i[s]), s == "initialState" && i[s] && p[s] !== i[s] && // Different references
|
|
29
29
|
!W(p[s], i[s]) && (I = !0, p[s] = i[s])) : (I = !0, p[s] = i[s]);
|
|
30
|
-
I &&
|
|
30
|
+
I && $(e, p);
|
|
31
31
|
}
|
|
32
32
|
function et(e, { formElements: i, validation: S }) {
|
|
33
33
|
return { initialState: e, formElements: i, validation: S };
|
|
@@ -44,7 +44,7 @@ const tt = (e, i) => {
|
|
|
44
44
|
// State-specific overrides
|
|
45
45
|
}, H(I) || n.getState().setInitialStateOptions(I, m[I]);
|
|
46
46
|
}), n.getState().setInitialStates(g), n.getState().setCreatedState(g);
|
|
47
|
-
const
|
|
47
|
+
const $ = (I, s) => {
|
|
48
48
|
const [v] = ne(s?.componentId ?? ge());
|
|
49
49
|
ve({
|
|
50
50
|
stateKey: I,
|
|
@@ -72,7 +72,7 @@ const tt = (e, i) => {
|
|
|
72
72
|
function p(I, s) {
|
|
73
73
|
ve({ stateKey: I, options: s, initialOptionsPart: m }), s.localStorage && Ue(I, s), se(I);
|
|
74
74
|
}
|
|
75
|
-
return { useCogsState:
|
|
75
|
+
return { useCogsState: $, setCogsOptions: p };
|
|
76
76
|
}, {
|
|
77
77
|
setUpdaterState: re,
|
|
78
78
|
setState: Z,
|
|
@@ -91,9 +91,9 @@ const tt = (e, i) => {
|
|
|
91
91
|
S.localStorage?.key,
|
|
92
92
|
g
|
|
93
93
|
);
|
|
94
|
-
const
|
|
95
|
-
if (
|
|
96
|
-
const p = `${g}-${i}-${
|
|
94
|
+
const $ = B(S?.localStorage?.key) ? S.localStorage?.key(e) : S?.localStorage?.key;
|
|
95
|
+
if ($ && g) {
|
|
96
|
+
const p = `${g}-${i}-${$}`;
|
|
97
97
|
let I;
|
|
98
98
|
try {
|
|
99
99
|
I = ie(p)?.lastSyncedWithServer;
|
|
@@ -120,21 +120,21 @@ const tt = (e, i) => {
|
|
|
120
120
|
}, Ue = (e, i) => {
|
|
121
121
|
const S = n.getState().cogsStateStore[e], { sessionId: g } = we(), m = B(i?.localStorage?.key) ? i.localStorage.key(S) : i?.localStorage?.key;
|
|
122
122
|
if (m && g) {
|
|
123
|
-
const
|
|
123
|
+
const $ = ie(
|
|
124
124
|
`${g}-${e}-${m}`
|
|
125
125
|
);
|
|
126
|
-
if (
|
|
127
|
-
return Z(e,
|
|
126
|
+
if ($ && $.lastUpdated > ($.lastSyncedWithServer || 0))
|
|
127
|
+
return Z(e, $.state), se(e), !0;
|
|
128
128
|
}
|
|
129
129
|
return !1;
|
|
130
|
-
}, $e = (e, i, S, g, m,
|
|
130
|
+
}, $e = (e, i, S, g, m, $) => {
|
|
131
131
|
const p = {
|
|
132
132
|
initialState: i,
|
|
133
133
|
updaterState: ae(
|
|
134
134
|
e,
|
|
135
135
|
g,
|
|
136
136
|
m,
|
|
137
|
-
|
|
137
|
+
$
|
|
138
138
|
),
|
|
139
139
|
state: S
|
|
140
140
|
};
|
|
@@ -184,7 +184,7 @@ function De(e, {
|
|
|
184
184
|
serverSync: S,
|
|
185
185
|
localStorage: g,
|
|
186
186
|
formElements: m,
|
|
187
|
-
reactiveDeps:
|
|
187
|
+
reactiveDeps: $,
|
|
188
188
|
reactiveType: p,
|
|
189
189
|
componentId: I,
|
|
190
190
|
initialState: s,
|
|
@@ -251,7 +251,7 @@ function De(e, {
|
|
|
251
251
|
forceUpdate: () => b({}),
|
|
252
252
|
paths: /* @__PURE__ */ new Set(),
|
|
253
253
|
deps: [],
|
|
254
|
-
depsFunction:
|
|
254
|
+
depsFunction: $ || void 0,
|
|
255
255
|
reactiveType: p ?? ["component", "deps"]
|
|
256
256
|
}), n.getState().stateComponents.set(y, a), b({}), () => {
|
|
257
257
|
const o = `${y}////${z.current}`;
|
|
@@ -271,21 +271,21 @@ function De(e, {
|
|
|
271
271
|
const P = a.slice(0, -1), D = G(u, P);
|
|
272
272
|
if (Array.isArray(D)) {
|
|
273
273
|
j = !0;
|
|
274
|
-
const
|
|
275
|
-
T = n.getState().signalDomElements.get(
|
|
274
|
+
const E = `${y}-${P.join(".")}`;
|
|
275
|
+
T = n.getState().signalDomElements.get(E);
|
|
276
276
|
}
|
|
277
277
|
}
|
|
278
278
|
if (T) {
|
|
279
279
|
const P = j ? G(u, a.slice(0, -1)) : G(u, a);
|
|
280
|
-
T.forEach(({ parentId: D, position:
|
|
280
|
+
T.forEach(({ parentId: D, position: E, effect: O }) => {
|
|
281
281
|
const _ = document.querySelector(
|
|
282
282
|
`[data-parent-id="${D}"]`
|
|
283
283
|
);
|
|
284
284
|
if (_) {
|
|
285
285
|
const L = Array.from(_.childNodes);
|
|
286
|
-
if (L[
|
|
286
|
+
if (L[E]) {
|
|
287
287
|
const F = O ? new Function("state", `return (${O})(state)`)(P) : P;
|
|
288
|
-
L[
|
|
288
|
+
L[E].textContent = String(F);
|
|
289
289
|
}
|
|
290
290
|
}
|
|
291
291
|
});
|
|
@@ -302,29 +302,29 @@ function De(e, {
|
|
|
302
302
|
).filter(([T, P]) => {
|
|
303
303
|
let D = T?.split(".").length;
|
|
304
304
|
if (T == w.join(".") && D == w.length - 1) {
|
|
305
|
-
let
|
|
306
|
-
J(T), Fe(
|
|
305
|
+
let E = T + "." + w;
|
|
306
|
+
J(T), Fe(E, P);
|
|
307
307
|
}
|
|
308
308
|
});
|
|
309
309
|
const k = n.getState().stateComponents.get(y);
|
|
310
|
-
if (k) {
|
|
310
|
+
if (console.log("stateEntry", k), k) {
|
|
311
311
|
const j = ue(h, u), T = new Set(j), P = o.updateType === "update" ? a.join(".") : a.slice(0, -1).join(".") || "";
|
|
312
312
|
for (const [
|
|
313
313
|
D,
|
|
314
|
-
|
|
314
|
+
E
|
|
315
315
|
] of k.components.entries()) {
|
|
316
316
|
let O = !1;
|
|
317
|
-
const _ = Array.isArray(
|
|
318
|
-
if (!_.includes("none")) {
|
|
317
|
+
const _ = Array.isArray(E.reactiveType) ? E.reactiveType : [E.reactiveType || "component"];
|
|
318
|
+
if (console.log("component", E), !_.includes("none")) {
|
|
319
319
|
if (_.includes("all")) {
|
|
320
|
-
|
|
320
|
+
E.forceUpdate();
|
|
321
321
|
continue;
|
|
322
322
|
}
|
|
323
|
-
if (_.includes("component") && ((
|
|
323
|
+
if (_.includes("component") && ((E.paths.has(P) || E.paths.has("")) && (O = !0), !O))
|
|
324
324
|
for (const L of T) {
|
|
325
325
|
let F = L;
|
|
326
326
|
for (; ; ) {
|
|
327
|
-
if (
|
|
327
|
+
if (E.paths.has(F)) {
|
|
328
328
|
O = !0;
|
|
329
329
|
break;
|
|
330
330
|
}
|
|
@@ -336,7 +336,7 @@ function De(e, {
|
|
|
336
336
|
);
|
|
337
337
|
if (!isNaN(
|
|
338
338
|
Number(F.substring(ce + 1))
|
|
339
|
-
) &&
|
|
339
|
+
) && E.paths.has(Se)) {
|
|
340
340
|
O = !0;
|
|
341
341
|
break;
|
|
342
342
|
}
|
|
@@ -348,12 +348,12 @@ function De(e, {
|
|
|
348
348
|
}
|
|
349
349
|
if (O) break;
|
|
350
350
|
}
|
|
351
|
-
if (!O && _.includes("deps") &&
|
|
352
|
-
const L =
|
|
351
|
+
if (!O && _.includes("deps") && E.depsFunction) {
|
|
352
|
+
const L = E.depsFunction(u);
|
|
353
353
|
let F = !1;
|
|
354
|
-
typeof L == "boolean" ? L && (F = !0) : W(
|
|
354
|
+
typeof L == "boolean" ? L && (F = !0) : W(E.deps, L) || (E.deps = L, F = !0), F && (O = !0);
|
|
355
355
|
}
|
|
356
|
-
O &&
|
|
356
|
+
O && E.forceUpdate();
|
|
357
357
|
}
|
|
358
358
|
}
|
|
359
359
|
}
|
|
@@ -377,9 +377,9 @@ function De(e, {
|
|
|
377
377
|
newValue: M
|
|
378
378
|
};
|
|
379
379
|
if (je(y, (j) => {
|
|
380
|
-
const P = [...j ?? [], q].reduce((D,
|
|
381
|
-
const O = `${
|
|
382
|
-
return _ ? (_.timeStamp = Math.max(_.timeStamp,
|
|
380
|
+
const P = [...j ?? [], q].reduce((D, E) => {
|
|
381
|
+
const O = `${E.stateKey}:${JSON.stringify(E.path)}`, _ = D.get(O);
|
|
382
|
+
return _ ? (_.timeStamp = Math.max(_.timeStamp, E.timeStamp), _.newValue = E.newValue, _.oldValue = _.oldValue ?? E.oldValue, _.updateType = E.updateType) : D.set(O, { ...E }), D;
|
|
383
383
|
}, /* @__PURE__ */ new Map());
|
|
384
384
|
return Array.from(P.values());
|
|
385
385
|
}), Ie(
|
|
@@ -421,12 +421,12 @@ function De(e, {
|
|
|
421
421
|
}
|
|
422
422
|
function ae(e, i, S, g) {
|
|
423
423
|
const m = /* @__PURE__ */ new Map();
|
|
424
|
-
let
|
|
424
|
+
let $ = 0;
|
|
425
425
|
const p = (v) => {
|
|
426
426
|
const r = v.join(".");
|
|
427
427
|
for (const [f] of m)
|
|
428
428
|
(f === r || f.startsWith(r + ".")) && m.delete(f);
|
|
429
|
-
|
|
429
|
+
$++;
|
|
430
430
|
}, I = {
|
|
431
431
|
removeValidation: (v) => {
|
|
432
432
|
v?.validationKey && J(v.validationKey);
|
|
@@ -435,7 +435,7 @@ function ae(e, i, S, g) {
|
|
|
435
435
|
const r = n.getState().getInitialOptions(e)?.validation;
|
|
436
436
|
r?.key && J(r?.key), v?.validationKey && J(v.validationKey);
|
|
437
437
|
const f = n.getState().initialStateGlobal[e];
|
|
438
|
-
n.getState().clearSelectedIndexesForState(e), m.clear(),
|
|
438
|
+
n.getState().clearSelectedIndexesForState(e), m.clear(), $++;
|
|
439
439
|
const R = s(f, []), b = H(e), C = B(b?.localStorage?.key) ? b?.localStorage?.key(f) : b?.localStorage?.key, U = `${g}-${e}-${C}`;
|
|
440
440
|
U && localStorage.removeItem(U), re(e, R), Z(e, f);
|
|
441
441
|
const y = n.getState().stateComponents.get(e);
|
|
@@ -444,7 +444,7 @@ function ae(e, i, S, g) {
|
|
|
444
444
|
}), f;
|
|
445
445
|
},
|
|
446
446
|
updateInitialState: (v) => {
|
|
447
|
-
m.clear(),
|
|
447
|
+
m.clear(), $++;
|
|
448
448
|
const r = ae(
|
|
449
449
|
e,
|
|
450
450
|
i,
|
|
@@ -667,7 +667,7 @@ function ae(e, i, S, g) {
|
|
|
667
667
|
if (c === "stateFlattenOn")
|
|
668
668
|
return (t) => {
|
|
669
669
|
const a = v;
|
|
670
|
-
m.clear(),
|
|
670
|
+
m.clear(), $++;
|
|
671
671
|
const o = a.flatMap(
|
|
672
672
|
(l) => l[t] ?? []
|
|
673
673
|
);
|
|
@@ -965,7 +965,7 @@ function ae(e, i, S, g) {
|
|
|
965
965
|
}, U = new Proxy(b, C);
|
|
966
966
|
return m.set(R, {
|
|
967
967
|
proxy: U,
|
|
968
|
-
stateVersion:
|
|
968
|
+
stateVersion: $
|
|
969
969
|
}), U;
|
|
970
970
|
}
|
|
971
971
|
return s(
|
|
@@ -984,7 +984,7 @@ function We({
|
|
|
984
984
|
S,
|
|
985
985
|
e._path
|
|
986
986
|
).stateMapNoRender(
|
|
987
|
-
(m,
|
|
987
|
+
(m, $, p, I, s) => e._mapFn(m, $, p, I, s)
|
|
988
988
|
) : null;
|
|
989
989
|
}
|
|
990
990
|
function Ge({
|
|
@@ -1049,16 +1049,16 @@ function Le({
|
|
|
1049
1049
|
}) {
|
|
1050
1050
|
const [, m] = ne({});
|
|
1051
1051
|
return pe(() => {
|
|
1052
|
-
const
|
|
1052
|
+
const $ = `${e}////${i}`, p = n.getState().stateComponents.get(e) || {
|
|
1053
1053
|
components: /* @__PURE__ */ new Map()
|
|
1054
1054
|
};
|
|
1055
|
-
return p.components.set(
|
|
1055
|
+
return p.components.set($, {
|
|
1056
1056
|
forceUpdate: () => m({}),
|
|
1057
1057
|
paths: /* @__PURE__ */ new Set([S.join(".")])
|
|
1058
1058
|
// ATOMIC: Subscribes only to this item's path.
|
|
1059
1059
|
}), n.getState().stateComponents.set(e, p), () => {
|
|
1060
1060
|
const I = n.getState().stateComponents.get(e);
|
|
1061
|
-
I && I.components.delete(
|
|
1061
|
+
I && I.components.delete($);
|
|
1062
1062
|
};
|
|
1063
1063
|
}, [e, i, S.join(".")]), /* @__PURE__ */ ee(ke, { children: g });
|
|
1064
1064
|
}
|
package/dist/CogsState.jsx.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CogsState.jsx","sources":["../src/CogsState.tsx"],"sourcesContent":["\"use client\";\r\n\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 superjson from \"superjson\";\r\nimport { v4 as uuidv4 } from \"uuid\";\r\nimport { z } from \"zod\";\r\n\r\nimport { formRefStore, getGlobalStore, type ComponentsType } from \"./store.js\";\r\nimport { useCogsConfig } from \"./CogsStateClient.js\";\r\nimport { applyPatch } from \"fast-json-patch\";\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, T> = (\r\n update:\r\n | Prettify<U>\r\n | ((prevState: NonNullable<Prettify<U>>[]) => NonNullable<Prettify<U>>),\r\n opts?: UpdateOpts<U>\r\n) => StateObject<T>;\r\n\r\ntype CutFunctionType<T> = (\r\n index?: number,\r\n options?: { waitForSync?: boolean }\r\n) => StateObject<T>;\r\n\r\nexport type InferArrayElement<T> = T extends (infer U)[] ? U : never;\r\ntype ArraySpecificPrototypeKeys =\r\n | \"concat\"\r\n | \"copyWithin\"\r\n | \"fill\"\r\n | \"find\"\r\n | \"findIndex\"\r\n | \"flat\"\r\n | \"flatMap\"\r\n | \"includes\"\r\n | \"indexOf\"\r\n | \"join\"\r\n | \"keys\"\r\n | \"lastIndexOf\"\r\n | \"map\"\r\n | \"pop\"\r\n | \"push\"\r\n | \"reduce\"\r\n | \"reduceRight\"\r\n | \"reverse\"\r\n | \"shift\"\r\n | \"slice\"\r\n | \"some\"\r\n | \"sort\"\r\n | \"splice\"\r\n | \"unshift\"\r\n | \"values\"\r\n | \"entries\"\r\n | \"every\"\r\n | \"filter\"\r\n | \"forEach\"\r\n | \"with\";\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>, TShape>;\r\n cut: CutFunctionType<TShape>;\r\n _index: number;\r\n } & EndType<InferArrayElement<TShape>>;\r\n insert: PushArgs<InferArrayElement<TShape>, TShape>;\r\n cut: CutFunctionType<TShape>;\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 stateFind: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => boolean\r\n ) => StateObject<InferArrayElement<TShape>> | undefined;\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 clearSelected: () => void;\r\n getSelectedIndex: () => number;\r\n last: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n} & EndType<TShape>;\r\n\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\n\r\nexport type UpdateType<T> = (\r\n payload: UpdateArg<T>,\r\n opts?: UpdateOpts<T>\r\n) => void;\r\n\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 applyJsonPatch: (patches: any[]) => void;\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\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 toggleSelected: () => void;\r\n getFormRef: () => React.RefObject<any> | undefined;\r\n removeStorage: () => void;\r\n sync: () => 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\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 getDifferences: () => string[];\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: UpdateArg<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?: z.ZodTypeAny;\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 serverState?: {\r\n id?: string | number;\r\n data?: T;\r\n status?: \"pending\" | \"error\" | \"success\";\r\n };\r\n sync?: {\r\n action: (state: T) => Promise<{\r\n success: boolean;\r\n data?: any;\r\n error?: any;\r\n errors?: Array<{\r\n path: (string | number)[];\r\n message: string;\r\n }>;\r\n }>;\r\n onSuccess?: (data: any) => void;\r\n onError?: (error: any) => void;\r\n };\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?: {\r\n key: string | ((state: T) => string);\r\n onChange?: (state: T) => void;\r\n };\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\r\n snapshot?: {\r\n name: (({ state }: { state: T }) => string) | string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\nexport type SyncActionsType<T> = {\r\n syncKey: string;\r\n\r\n rollBackState?: T;\r\n actionTimeStamp: number;\r\n retryCount?: number;\r\n status:\r\n | \"success\"\r\n | \"waiting\"\r\n | \"rolledBack\"\r\n | \"error\"\r\n | \"cancelled\"\r\n | \"failed\";\r\n snapshot?: {\r\n name: string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\n\r\nexport type ValidationWrapperOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n active: boolean;\r\n stretch?: boolean;\r\n path: string[];\r\n message?: string;\r\n data?: T;\r\n key?: string;\r\n};\r\nexport type SyncRenderOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n time: number;\r\n data?: T;\r\n key?: string;\r\n};\r\n\r\ntype FormsElementsType<T extends unknown = unknown> = {\r\n validation?: (options: ValidationWrapperOptions<T>) => React.ReactNode;\r\n syncRender?: (options: SyncRenderOptions<T>) => React.ReactNode;\r\n};\r\n\r\nexport type InitialStateInnerType<T extends unknown = unknown> = {\r\n initialState: T;\r\n} & OptionsType<T>;\r\n\r\nexport type InitialStateType<T> = {\r\n [key: string]: InitialStateInnerType<T>;\r\n};\r\n\r\nexport type AllStateTypes<T extends unknown> = Record<string, T>;\r\n\r\nexport type CogsInitialState<T> = {\r\n initialState: T;\r\n formElements?: FormsElementsType<T>;\r\n};\r\n\r\nexport type TransformedStateType<T> = {\r\n [P in keyof T]: T[P] extends CogsInitialState<infer U> ? U : T[P];\r\n};\r\n\r\nfunction setAndMergeOptions(stateKey: string, newOptions: OptionsType<any>) {\r\n const getInitialOptions = getGlobalStore.getState().getInitialOptions;\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n\r\n setInitialStateOptions(stateKey as string, {\r\n ...initialOptions,\r\n ...newOptions,\r\n });\r\n}\r\n\r\n// Fix for the setOptions function\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 if (\r\n key == \"initialState\" &&\r\n options[key] &&\r\n mergedOptions[key] !== options[key] && // Different references\r\n !isDeepEqual(mergedOptions[key], options[key]) // And different values\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (needToAdd) {\r\n setInitialStateOptions(stateKey as string, mergedOptions);\r\n }\r\n}\r\nexport function addStateOptions<T extends unknown>(\r\n initialState: T,\r\n { formElements, validation }: OptionsType<T>\r\n) {\r\n return { initialState: initialState, formElements, validation } as T;\r\n}\r\n\r\nexport const createCogsState = <State extends Record<string, unknown>>(\r\n initialState: State,\r\n opt?: { formElements?: FormsElementsType; validation?: ValidationOptionsType }\r\n) => {\r\n let newInitialState = initialState;\r\n\r\n // Extract state parts and options using transformStateFunc\r\n const [statePart, initialOptionsPart] =\r\n transformStateFunc<State>(newInitialState);\r\n\r\n // Apply global formElements as defaults to each state key's options\r\n if (\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\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 getGlobalStore.getState().setCreatedState(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 as any,\r\n dependencies: options?.dependencies,\r\n serverState: options?.serverState,\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 if (options.localStorage) {\r\n loadAndApplyLocalStorage(stateKey as string, options);\r\n }\r\n\r\n notifyComponents(stateKey as string);\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\nconst saveToLocalStorage = <T,>(\r\n state: T,\r\n thisKey: string,\r\n currentInitialOptions: any,\r\n sessionId?: string,\r\n lastSyncedWithServer?: number\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\r\n const key = isFunction(currentInitialOptions?.localStorage?.key)\r\n ? currentInitialOptions.localStorage?.key(state)\r\n : currentInitialOptions?.localStorage?.key;\r\n\r\n if (key && sessionId) {\r\n const storageKey = `${sessionId}-${thisKey}-${key}`;\r\n\r\n // Get existing data to preserve lastSyncedWithServer if not explicitly updating it\r\n let existingLastSynced: number | undefined;\r\n try {\r\n const existing = loadFromLocalStorage(storageKey);\r\n existingLastSynced = existing?.lastSyncedWithServer;\r\n } catch {\r\n // Ignore errors, will use undefined\r\n }\r\n\r\n const data: LocalStorageData<T> = {\r\n state,\r\n lastUpdated: Date.now(),\r\n lastSyncedWithServer: lastSyncedWithServer ?? existingLastSynced,\r\n };\r\n\r\n // Use SuperJSON serialize to get the json part only\r\n const superJsonResult = superjson.serialize(data);\r\n window.localStorage.setItem(\r\n storageKey,\r\n JSON.stringify(superJsonResult.json)\r\n );\r\n }\r\n};\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 // Parse the json part back normally\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\nconst loadAndApplyLocalStorage = (stateKey: string, options: any) => {\r\n const currentState = getGlobalStore.getState().cogsStateStore[stateKey];\r\n const { sessionId } = useCogsConfig();\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options.localStorage.key(currentState)\r\n : options?.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n const localData = loadFromLocalStorage(\r\n `${sessionId}-${stateKey}-${localkey}`\r\n );\r\n\r\n if (\r\n localData &&\r\n localData.lastUpdated > (localData.lastSyncedWithServer || 0)\r\n ) {\r\n setState(stateKey, localData.state);\r\n\r\n notifyComponents(stateKey);\r\n return true;\r\n }\r\n }\r\n return false;\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 updateInitialStateGlobal(thisKey, updates.initialState);\r\n setUpdaterState(thisKey, updates.updaterState);\r\n setState(thisKey, updates.state);\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 const reactiveTypes = component\r\n ? Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"]\r\n : null;\r\n if (!reactiveTypes?.includes(\"none\")) {\r\n updates.add(() => component.forceUpdate());\r\n }\r\n });\r\n\r\n // Schedule updates in the next tick to allow batching\r\n queueMicrotask(() => {\r\n updates.forEach((update) => update());\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 const reactiveTypes = component\r\n ? Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"]\r\n : null;\r\n\r\n // Skip if reactivity is disabled\r\n if (reactiveTypes?.includes(\"none\")) {\r\n return;\r\n }\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\nconst getUpdateValues = (\r\n updateType: string,\r\n prevValue: any,\r\n payload: any,\r\n path: string[]\r\n) => {\r\n switch (updateType) {\r\n case \"update\":\r\n return {\r\n oldValue: getNestedValue(prevValue, path),\r\n newValue: getNestedValue(payload, path),\r\n };\r\n case \"insert\":\r\n return {\r\n oldValue: null, // or undefined\r\n newValue: getNestedValue(payload, path),\r\n };\r\n case \"cut\":\r\n return {\r\n oldValue: getNestedValue(prevValue, path),\r\n newValue: null, // or undefined\r\n };\r\n default:\r\n return { oldValue: null, newValue: null };\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 reactiveDeps,\r\n reactiveType,\r\n componentId,\r\n initialState,\r\n syncUpdate,\r\n dependencies,\r\n serverState,\r\n }: {\r\n stateKey?: string;\r\n componentId?: string;\r\n initialState?: TStateObject;\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<OptionsType<TStateObject> | null>(\r\n null\r\n );\r\n latestInitialOptionsRef.current = (getInitialOptions(thisKey as string) ??\r\n null) as OptionsType<TStateObject> | null;\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 useEffect(() => {\r\n // Only proceed if initialState is provided\r\n if (initialState) {\r\n setAndMergeOptions(thisKey as string, {\r\n initialState,\r\n });\r\n\r\n const options = latestInitialOptionsRef.current;\r\n const hasServerId = options?.serverState?.id !== undefined;\r\n const hasServerData =\r\n hasServerId &&\r\n options?.serverState?.status === \"success\" &&\r\n options?.serverState?.data;\r\n\r\n const currentGloballyStoredInitialState =\r\n getGlobalStore.getState().initialStateGlobal[thisKey];\r\n\r\n const initialStateChanged =\r\n (currentGloballyStoredInitialState &&\r\n !isDeepEqual(currentGloballyStoredInitialState, initialState)) ||\r\n !currentGloballyStoredInitialState;\r\n\r\n if (!initialStateChanged && !hasServerData) {\r\n return;\r\n }\r\n\r\n let localData = null;\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options?.localStorage?.key(initialState)\r\n : options?.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n localData = loadFromLocalStorage(`${sessionId}-${thisKey}-${localkey}`);\r\n }\r\n\r\n let newState = initialState;\r\n let isFromServer = false;\r\n\r\n const serverTimestamp = hasServerData ? Date.now() : 0;\r\n const localTimestamp = localData?.lastUpdated || 0;\r\n const lastSyncTimestamp = localData?.lastSyncedWithServer || 0;\r\n\r\n if (hasServerData && serverTimestamp > localTimestamp) {\r\n newState = options.serverState!.data!;\r\n isFromServer = true;\r\n } else if (localData && localTimestamp > lastSyncTimestamp) {\r\n newState = localData.state;\r\n if (options?.localStorage?.onChange) {\r\n options?.localStorage?.onChange(newState);\r\n }\r\n }\r\n\r\n // Update the global state\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 // Save to localStorage if we used server data\r\n if (isFromServer && localkey && sessionId) {\r\n saveToLocalStorage(newState, thisKey, options, sessionId, Date.now());\r\n }\r\n\r\n // Notify components of the change\r\n notifyComponents(thisKey);\r\n\r\n const reactiveTypes = Array.isArray(reactiveType)\r\n ? reactiveType\r\n : [reactiveType || \"component\"];\r\n\r\n if (!reactiveTypes.includes(\"none\")) {\r\n forceUpdate({});\r\n }\r\n }\r\n }, [\r\n initialState,\r\n serverState?.status,\r\n serverState?.data,\r\n ...(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: latestInitialOptionsRef.current?.middleware,\r\n });\r\n }\r\n\r\n const componentKey = `${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(componentKey, {\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 componentKey = `${thisKey}////${componentIdRef.current}`;\r\n\r\n if (stateEntry) {\r\n stateEntry.components.delete(componentKey);\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: UpdateArg<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?.validation?.key) &&\r\n path\r\n ) {\r\n removeValidationError(\r\n (validationKey || latestInitialOptionsRef.current?.validation?.key) +\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?.validation?.key\r\n ) {\r\n removeValidationError(\r\n latestInitialOptionsRef.current?.validation?.key +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n }\r\n if (\r\n updateObj.updateType === \"insert\" &&\r\n latestInitialOptionsRef.current?.validation?.key\r\n ) {\r\n let getValidation = getValidationErrors(\r\n latestInitialOptionsRef.current?.validation?.key +\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 stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n if (stateEntry) {\r\n const changedPaths = getDifferences(prevValue, payload);\r\n const changedPathsSet = new Set(changedPaths);\r\n const primaryPathToCheck =\r\n updateObj.updateType === \"update\"\r\n ? path.join(\".\")\r\n : path.slice(0, -1).join(\".\") || \"\";\r\n\r\n for (const [\r\n componentKey,\r\n component,\r\n ] 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 if (reactiveTypes.includes(\"none\")) continue;\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n continue;\r\n }\r\n\r\n if (reactiveTypes.includes(\"component\")) {\r\n if (\r\n component.paths.has(primaryPathToCheck) ||\r\n component.paths.has(\"\")\r\n ) {\r\n shouldUpdate = true;\r\n }\r\n\r\n if (!shouldUpdate) {\r\n for (const changedPath of changedPathsSet) {\r\n let currentPathToCheck = changedPath;\r\n while (true) {\r\n if (component.paths.has(currentPathToCheck)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n const lastDotIndex = currentPathToCheck.lastIndexOf(\".\");\r\n if (lastDotIndex !== -1) {\r\n const parentPath = currentPathToCheck.substring(\r\n 0,\r\n lastDotIndex\r\n );\r\n if (\r\n !isNaN(\r\n Number(currentPathToCheck.substring(lastDotIndex + 1))\r\n )\r\n ) {\r\n if (component.paths.has(parentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n }\r\n currentPathToCheck = parentPath;\r\n } else {\r\n currentPathToCheck = \"\";\r\n }\r\n if (currentPathToCheck === \"\") {\r\n break;\r\n }\r\n }\r\n if (shouldUpdate) break;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(payload);\r\n let depsChanged = false;\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) depsChanged = true;\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n depsChanged = true;\r\n }\r\n if (depsChanged) {\r\n shouldUpdate = true;\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 path = path.map((p, i) => {\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n\r\n return i === path.length - 1 &&\r\n [\"insert\", \"cut\"].includes(updateObj.updateType)\r\n ? (arrayValue.length - 1).toString()\r\n : p;\r\n });\r\n\r\n const { oldValue, newValue } = getUpdateValues(\r\n updateObj.updateType,\r\n prevValue,\r\n payload,\r\n path\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 (latestInitialOptionsRef.current?.middleware) {\r\n latestInitialOptionsRef.current!.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, sessionId]);\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 getGlobalStore.getState().clearSelectedIndexesForState(stateKey);\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\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 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 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\r\n if (localStorage.getItem(storageKey)) {\r\n localStorage.removeItem(storageKey);\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\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\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 (meta?.validIndices && !Array.isArray(currentState)) {\r\n meta = { ...meta, validIndices: undefined };\r\n }\r\n const mutationMethods = new Set([\r\n \"insert\",\r\n \"cut\",\r\n \"cutByValue\",\r\n \"toggleByValue\",\r\n \"uniqueInsert\",\r\n \"update\",\r\n \"applyJsonPatch\",\r\n \"setSelected\",\r\n \"toggleSelected\",\r\n \"clearSelected\",\r\n \"sync\",\r\n \"validateZodSchema\",\r\n \"revertToInitialState\",\r\n \"updateInitialState\",\r\n \"removeValidation\",\r\n \"setValidation\",\r\n \"removeStorage\",\r\n \"middleware\",\r\n \"_componentId\",\r\n \"_stateKey\",\r\n \"getComponents\",\r\n ]);\r\n if (\r\n prop !== \"then\" &&\r\n !prop.startsWith(\"$\") &&\r\n prop !== \"stateMapNoRender\" &&\r\n !mutationMethods.has(prop)\r\n ) {\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n // console.log(\"adding path\", fullComponentId, path, prop);\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 && !component.pathsInitialized) {\r\n // Mark as initialized immediately to prevent re-processing\r\n component.pathsInitialized = true;\r\n\r\n // Now do the path tracking logic ONCE\r\n if (!component.paths.has(\"\")) {\r\n const currentPath = path.join(\".\");\r\n let needsAdd = true;\r\n for (const existingPath of component.paths) {\r\n if (\r\n currentPath.startsWith(existingPath) &&\r\n (currentPath === existingPath ||\r\n currentPath[existingPath.length] === \".\")\r\n ) {\r\n needsAdd = false;\r\n break;\r\n }\r\n }\r\n\r\n if (needsAdd) {\r\n // console.log(\r\n // \"adding path actualyl adding\",\r\n // fullComponentId,\r\n // path,\r\n // prop\r\n // );\r\n component.paths.add(currentPath);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (prop === \"getDifferences\") {\r\n return () => {\r\n const differences = getDifferences(\r\n getGlobalStore.getState().cogsStateStore[stateKey],\r\n getGlobalStore.getState().initialStateGlobal[stateKey]\r\n );\r\n return differences;\r\n };\r\n }\r\n if (prop === \"sync\" && path.length === 0) {\r\n return async function () {\r\n // Get the options for this state key\r\n const options = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey);\r\n const sync = options?.sync;\r\n\r\n if (!sync) {\r\n console.error(`No mutation defined for state key \"${stateKey}\"`);\r\n return { success: false, error: `No mutation defined` };\r\n }\r\n\r\n // Get the root state\r\n const state = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, []);\r\n\r\n // Get validation key\r\n const validationKey = options?.validation?.key;\r\n\r\n try {\r\n // Execute the mutation action\r\n const response = await sync.action(state);\r\n\r\n // Handle validation errors\r\n if (\r\n response &&\r\n !response.success &&\r\n response.errors &&\r\n validationKey\r\n ) {\r\n // Clear existing errors\r\n getGlobalStore.getState().removeValidationError(validationKey);\r\n\r\n // Add new validation errors\r\n response.errors.forEach((error) => {\r\n const errorPath = [validationKey, ...error.path].join(\".\");\r\n\r\n getGlobalStore\r\n .getState()\r\n .addValidationError(errorPath, error.message);\r\n });\r\n\r\n // Notify components to update\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 // Call success/error callbacks\r\n if (response?.success && sync.onSuccess) {\r\n sync.onSuccess(response.data);\r\n } else if (!response?.success && sync.onError) {\r\n sync.onError(response.error);\r\n }\r\n\r\n return response;\r\n } catch (error) {\r\n if (sync.onError) {\r\n sync.onError(error);\r\n }\r\n return { success: false, error };\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 // 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\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 const getSourceArrayAndIndices = (): {\r\n item: any;\r\n originalIndex: number;\r\n }[] => {\r\n // If meta exists, we're in a chain. Use the currentState and map it to its original index.\r\n if (meta?.validIndices) {\r\n return (currentState as any[]).map((item, index) => ({\r\n item,\r\n originalIndex: meta!.validIndices![index]!,\r\n }));\r\n }\r\n // Otherwise, this is the first operation. Use the full array from the global store.\r\n const sourceArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n return sourceArray.map((item, index) => ({\r\n item,\r\n originalIndex: index,\r\n }));\r\n };\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 === \"clearSelected\") {\r\n return () => {\r\n getGlobalStore.getState().clearSelectedIndex({ stateKey, path });\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 sourceWithIndices = getSourceArrayAndIndices();\r\n const sortedResult = [...sourceWithIndices].sort((a, b) =>\r\n compareFn(a.item, b.item)\r\n );\r\n const newCurrentState = sortedResult.map(({ item }) => item);\r\n // We construct the meta object with the CORRECT property name: `validIndices`.\r\n const newMeta = {\r\n ...meta,\r\n validIndices: sortedResult.map(\r\n ({ originalIndex }) => originalIndex\r\n ),\r\n };\r\n return rebuildStateShape(newCurrentState as any, path, newMeta);\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 sourceWithIndices = getSourceArrayAndIndices();\r\n const filteredResult = sourceWithIndices.filter(\r\n ({ item }, index) => callbackfn(item, index)\r\n );\r\n const newCurrentState = filteredResult.map(({ item }) => item);\r\n // We construct the meta object with the CORRECT property name: `validIndices`.\r\n const newMeta = {\r\n ...meta,\r\n validIndices: filteredResult.map(\r\n ({ originalIndex }) => originalIndex\r\n ),\r\n };\r\n return rebuildStateShape(newCurrentState as any, path, newMeta);\r\n };\r\n }\r\n // This code goes inside the `get` trap of `createProxyHandler`\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 ) => React.ReactNode // Your callback returns the JSX to render\r\n ) => {\r\n const arrayToMap = currentState as any[];\r\n\r\n return arrayToMap.map((item, index) => {\r\n let originalIndex: number;\r\n if (\r\n meta?.validIndices &&\r\n meta.validIndices[index] !== undefined\r\n ) {\r\n originalIndex = meta.validIndices[index]!;\r\n } else {\r\n originalIndex = index;\r\n }\r\n\r\n // The specific path for this individual item in the array.\r\n const finalPath = [...path, originalIndex.toString()];\r\n\r\n // The proxy for this item, which can be used for updates.\r\n const setter = rebuildStateShape(item, finalPath, meta);\r\n\r\n // A stable and unique ID for this item's wrapper component.\r\n const itemComponentId = `${componentId}-${path.join(\".\")}-${originalIndex}`;\r\n\r\n // Call the user's render function to get their actual component JSX.\r\n const userComponentJsx = callbackfn(item, setter, index);\r\n\r\n // Transparently wrap the user's component in our internal registration component.\r\n return (\r\n <CogsItemWrapper\r\n key={originalIndex} // The wrapper itself needs a key for React's mapping.\r\n stateKey={stateKey}\r\n itemComponentId={itemComponentId}\r\n itemPath={finalPath} // Pass the specific path for atomic updates.\r\n >\r\n {userComponentJsx}\r\n </CogsItemWrapper>\r\n );\r\n });\r\n };\r\n }\r\n if (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 ) => any\r\n ) => {\r\n const arrayToMap = currentState as any[];\r\n return arrayToMap.map((item, index) => {\r\n let originalIndex: number;\r\n // We READ from the meta object using the CORRECT property name: `validIndices`.\r\n if (\r\n meta?.validIndices &&\r\n meta.validIndices[index] !== undefined\r\n ) {\r\n originalIndex = meta.validIndices[index]!;\r\n } else {\r\n originalIndex = index;\r\n }\r\n const finalPath = [...path, originalIndex.toString()];\r\n\r\n const setter = rebuildStateShape(item, finalPath, meta); // Pass meta through\r\n return callbackfn(\r\n item,\r\n setter,\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\r\n if (prop === \"stateFlattenOn\") {\r\n return (fieldName: string) => {\r\n const arrayToMap = currentState as any[];\r\n shapeCache.clear();\r\n stateVersion++;\r\n const flattenedResults = arrayToMap.flatMap(\r\n (val: any) => val[fieldName] ?? []\r\n );\r\n return rebuildStateShape(\r\n flattenedResults as any,\r\n [...path, \"[*]\", fieldName],\r\n meta\r\n );\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 if (prop === \"last\") {\r\n // Added handler for 'last'\r\n return () => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n if (currentArray.length === 0) return undefined;\r\n const lastIndex = currentArray.length - 1;\r\n const lastValue = currentArray[lastIndex];\r\n const newPath = [...path, lastIndex.toString()];\r\n // shapeCache.clear(); // Decide if you need cache invalidation for 'last' access\r\n // stateVersion++;\r\n return rebuildStateShape(lastValue, newPath);\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().getNestedState(stateKey, path),\r\n path\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 return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, path),\r\n path\r\n );\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 if (prop === \"stateFind\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const found = sourceWithIndices.find(({ item }, index) =>\r\n callbackfn(item, index)\r\n );\r\n if (!found) return undefined;\r\n const finalPath = [...path, found.originalIndex.toString()];\r\n return rebuildStateShape(found.item, finalPath, meta);\r\n };\r\n }\r\n\r\n if (prop === \"findWith\") {\r\n return (thisKey: keyof InferArrayElement<T>, thisValue: any) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const found = sourceWithIndices.find(\r\n ({ item }) => item[thisKey] === thisValue\r\n );\r\n if (!found) return undefined;\r\n const finalPath = [...path, found.originalIndex.toString()];\r\n return rebuildStateShape(found.item, finalPath, meta);\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\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 (prop === \"toggleSelected\") {\r\n return () => {\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 const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, parentKey);\r\n\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(\r\n stateKey,\r\n parentKey,\r\n selectedIndex === thisIndex ? undefined : thisIndex\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 invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (path.length == 0) {\r\n if (prop === \"applyJsonPatch\") {\r\n return (patches: any[]) => {\r\n // This part is correct.\r\n const currentState =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n const patchResult = applyPatch(currentState, patches);\r\n const newState = patchResult.newDocument;\r\n\r\n // This is also correct.\r\n updateGlobalState(\r\n stateKey,\r\n getGlobalStore.getState().initialStateGlobal[stateKey],\r\n newState,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n\r\n // ===================================================================\r\n // REPLACE THE OLD LOGIC WITH THIS DIRECT COPY\r\n // ===================================================================\r\n\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey); // Use stateKey here\r\n\r\n if (stateEntry) {\r\n // Use `getDifferences` between the state before and after the patch.\r\n const changedPaths = getDifferences(currentState, newState);\r\n const changedPathsSet = new Set(changedPaths);\r\n\r\n // There is no single `primaryPathToCheck` for a patch, so we just check against the full set.\r\n\r\n for (const [\r\n componentKey,\r\n component,\r\n ] 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 if (reactiveTypes.includes(\"none\")) continue;\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n continue;\r\n }\r\n\r\n if (reactiveTypes.includes(\"component\")) {\r\n // This is the core logic that needs to be copied.\r\n // Check if any of the component's watched paths are in the set of changed paths.\r\n if (component.paths.has(\"\")) {\r\n // Always update for root listeners\r\n shouldUpdate = true;\r\n }\r\n\r\n if (!shouldUpdate) {\r\n for (const changedPath of changedPathsSet) {\r\n // Direct match first (fastest)\r\n if (component.paths.has(changedPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n\r\n // Check parent paths more efficiently\r\n let dotIndex = changedPath.lastIndexOf(\".\");\r\n while (dotIndex !== -1) {\r\n const parentPath = changedPath.substring(0, dotIndex);\r\n if (component.paths.has(parentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n // Skip numeric segments more efficiently\r\n const lastSegment = changedPath.substring(\r\n dotIndex + 1\r\n );\r\n if (!isNaN(Number(lastSegment))) {\r\n // For array indices, check the parent collection path\r\n const parentDotIndex = parentPath.lastIndexOf(\".\");\r\n if (parentDotIndex !== -1) {\r\n const grandParentPath = parentPath.substring(\r\n 0,\r\n parentDotIndex\r\n );\r\n if (component.paths.has(grandParentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n }\r\n }\r\n dotIndex = parentPath.lastIndexOf(\".\");\r\n }\r\n\r\n if (shouldUpdate) break;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n // Use `newState` (the result of the patch) for dependency checks.\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(newState);\r\n let depsChanged = false;\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) depsChanged = true;\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n depsChanged = true;\r\n }\r\n if (depsChanged) {\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 };\r\n }\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// This is an internal component. It should NOT be exported.\r\nfunction CogsItemWrapper({\r\n stateKey,\r\n itemComponentId,\r\n itemPath,\r\n children,\r\n}: {\r\n stateKey: string;\r\n itemComponentId: string;\r\n itemPath: string[];\r\n children: React.ReactNode;\r\n}) {\r\n // This is a real component, so we can safely call hooks.\r\n const [, forceUpdate] = useState({});\r\n\r\n // We use useLayoutEffect to register the component and clean up when it unmounts.\r\n useLayoutEffect(() => {\r\n const fullComponentId = `${stateKey}////${itemComponentId}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey) || {\r\n components: new Map(),\r\n };\r\n\r\n // Register the component with its unique ID and its specific, atomic path.\r\n stateEntry.components.set(fullComponentId, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set([itemPath.join(\".\")]), // ATOMIC: Subscribes only to this item's path.\r\n });\r\n\r\n getGlobalStore.getState().stateComponents.set(stateKey, stateEntry);\r\n\r\n // Return a cleanup function to unregister on unmount.\r\n return () => {\r\n const currentEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (currentEntry) {\r\n currentEntry.components.delete(fullComponentId);\r\n }\r\n };\r\n }, [stateKey, itemComponentId, itemPath.join(\".\")]); // Effect dependency array is stable.\r\n\r\n // Render the actual component the user provided.\r\n return <>{children}</>;\r\n}\r\n"],"names":["setAndMergeOptions","stateKey","newOptions","getInitialOptions","getGlobalStore","setInitialStateOptions","initialOptions","setOptions","options","initialOptionsPart","initialOptionsPartState","mergedOptions","needToAdd","key","isDeepEqual","addStateOptions","initialState","formElements","validation","createCogsState","opt","newInitialState","statePart","transformStateFunc","useCogsState","componentId","useState","uuidv4","thiState","partialState","state","updater","useCogsStateFn","setCogsOptions","loadAndApplyLocalStorage","notifyComponents","setUpdaterState","setState","getKeyState","getValidationErrors","setStateLog","updateInitialStateGlobal","addValidationError","removeValidationError","setServerSyncActions","saveToLocalStorage","thisKey","currentInitialOptions","sessionId","lastSyncedWithServer","isFunction","storageKey","existingLastSynced","loadFromLocalStorage","data","superJsonResult","superjson","localStorageKey","storedData","error","currentState","useCogsConfig","localkey","localData","updateGlobalState","newState","effectiveSetState","updates","createProxyHandler","stateEntry","component","update","notifyComponent","fullComponentId","getUpdateValues","updateType","prevValue","payload","path","getNestedValue","stateObject","serverSync","localStorage","reactiveDeps","reactiveType","syncUpdate","dependencies","serverState","reactiveForce","forceUpdate","noStateKey","stateLog","componentUpdatesRef","useRef","componentIdRef","latestInitialOptionsRef","useEffect","prevState","syncKey","hasServerData","currentGloballyStoredInitialState","isFromServer","serverTimestamp","localTimestamp","lastSyncTimestamp","useLayoutEffect","componentKey","newStateOrFunction","updateObj","validationKey","pathKey","signalId","isArrayOperation","elements","arrayPath","arrayValue","arraySignalId","newValue","parentId","position","effect","parent","childNodes","displayValue","arrayWithoutIndex","k","v","length","newKey","changedPaths","getDifferences","changedPathsSet","primaryPathToCheck","shouldUpdate","reactiveTypes","changedPath","currentPathToCheck","lastDotIndex","parentPath","depsResult","depsChanged","timeStamp","p","i","oldValue","newUpdate","prevLogs","aggregatedLogs","acc","log","uniqueKey","existing","serverStateStore","updaterFinal","useMemo","shapeCache","stateVersion","invalidateCachePath","baseObj","obj","init","newProxy","rebuildStateShape","initalOptionsGet","localKey","newUpdaterState","startTransition","field","meta","cacheKey","baseFunction","handler","target","thisArg","args","prop","mutationMethods","currentPath","needsAdd","existingPath","sync","response","errorPath","thisReactiveState","initialStateAtPath","getSourceArrayAndIndices","item","index","selectedIndex","compareFn","sortedResult","a","b","newCurrentState","newMeta","originalIndex","callbackfn","filteredResult","finalPath","setter","itemComponentId","userComponentJsx","jsx","CogsItemWrapper","createElement","SignalMapRenderer","fieldName","arrayToMap","flattenedResults","val","indexValue","currentArray","lastIndex","lastValue","newPath","pushFunc","fields","onMatch","matchedItem","isMatch","updatedItem","updatedArray","updateFn","cutFunc","value","found","thisValue","lastPathElement","parentValue","fn","$cogsSignal","parentKey","thisIndex","nested","patches","applyPatch","dotIndex","lastSegment","parentDotIndex","grandParentPath","thisObject","existingErrors","result","errorMessage","fullErrorPath","formRefStore","children","hideMessage","ValidationWrapper","opts","debounce","child","formOpts","FormControlComponent","nextPath","nextValue","proxyInstance","proxy","SignalRenderer","arraysetter","elementRef","element","parentElement","elementInfo","err","textNode","$cogsSignalStore","useSyncExternalStore","notify","itemPath","currentEntry"],"mappings":";;;;;;;;;;;AAocA,SAASA,GAAmBC,GAAkBC,GAA8B;AACpEC,QAAAA,IAAoBC,EAAe,SAAA,EAAW,mBAC9CC,IACJD,EAAe,SAAA,EAAW,wBAEtBE,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC;AAEjE,EAAAI,EAAuBJ,GAAoB;AAAA,IACzC,GAAGK;AAAA,IACH,GAAGJ;AAAA,EAAA,CACJ;AACH;AAGA,SAASK,GAA0B;AAAA,EACjC,UAAAN;AAAA,EACA,SAAAO;AAAA,EACA,oBAAAC;AACF,GAIG;AACD,QAAMH,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC,GAC3DS,IAA0BD,EAAmBR,CAAkB,KAAK,CAAC,GACrEI,IACJD,EAAe,SAAA,EAAW,wBACtBO,IAAgB,EAAE,GAAGD,GAAyB,GAAGJ,EAAe;AAEtE,MAAIM,IAAY;AAChB,MAAIJ;AACF,eAAWK,KAAOL;AAChB,MAAKG,EAAc,eAAeE,CAAG,KAKjCA,KAAO,kBACPL,EAAQK,CAAG,KACXF,EAAcE,CAAG,EAAE,QAAQL,EAAQK,CAAG,GAAG,QAE7BD,IAAA,IACED,EAAAE,CAAG,IAAIL,EAAQK,CAAG,IAGhCA,KAAO,kBACPL,EAAQK,CAAG,KACXF,EAAcE,CAAG,MAAML,EAAQK,CAAG;AAAA,MAClC,CAACC,EAAYH,EAAcE,CAAG,GAAGL,EAAQK,CAAG,CAAC,MAEjCD,IAAA,IACED,EAAAE,CAAG,IAAIL,EAAQK,CAAG,OAlBtBD,IAAA,IACED,EAAAE,CAAG,IAAIL,EAAQK,CAA2B;AAuB9D,EAAID,KACFP,EAAuBJ,GAAoBU,CAAa;AAE5D;AACO,SAASI,GACdC,GACA,EAAE,cAAAC,GAAc,YA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e,WAAW,eAAe6P,EAAM,WAAWA,EAAM,KAAK;AAAA,EAC7E;AACA,SAAOrD,GAAc,QAAQ,CAAI,GAAA,OAAOoB,CAAK,CAAC;AAChD;AAEA,SAASrB,GAAgB;AAAA,EACvB,UAAA1M;AAAA,EACA,iBAAAuM;AAAA,EACA,UAAAqE;AAAA,EACA,UAAAvB;AACF,GAKG;AAED,QAAM,GAAG7J,CAAW,IAAI/D,GAAS,EAAE;AAGnC,SAAA+E,GAAgB,MAAM;AACpB,UAAMhC,IAAkB,GAAGxE,CAAQ,OAAOuM,CAAe,IACnDnI,IAAajE,EAChB,SAAA,EACA,gBAAgB,IAAIH,CAAQ,KAAK;AAAA,MAClC,gCAAgB,IAAI;AAAA,IACtB;AAGW,WAAAoE,EAAA,WAAW,IAAII,GAAiB;AAAA,MACzC,aAAa,MAAMgB,EAAY,EAAE;AAAA,MACjC,2BAAW,IAAI,CAACoL,EAAS,KAAK,GAAG,CAAC,CAAC;AAAA;AAAA,IAAA,CACpC,GAEDzQ,EAAe,SAAS,EAAE,gBAAgB,IAAIH,GAAUoE,CAAU,GAG3D,MAAM;AACX,YAAMyM,IAAe1Q,EAClB,SACA,EAAA,gBAAgB,IAAIH,CAAQ;AAC/B,MAAI6Q,KACWA,EAAA,WAAW,OAAOrM,CAAe;AAAA,IAElD;AAAA,EAAA,GACC,CAACxE,GAAUuM,GAAiBqE,EAAS,KAAK,GAAG,CAAC,CAAC,4BAGxC,UAAAvB,GAAS;AACrB;"}
|
|
1
|
+
{"version":3,"file":"CogsState.jsx","sources":["../src/CogsState.tsx"],"sourcesContent":["\"use client\";\r\n\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 superjson from \"superjson\";\r\nimport { v4 as uuidv4 } from \"uuid\";\r\nimport { z } from \"zod\";\r\n\r\nimport { formRefStore, getGlobalStore, type ComponentsType } from \"./store.js\";\r\nimport { useCogsConfig } from \"./CogsStateClient.js\";\r\nimport { applyPatch } from \"fast-json-patch\";\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, T> = (\r\n update:\r\n | Prettify<U>\r\n | ((prevState: NonNullable<Prettify<U>>[]) => NonNullable<Prettify<U>>),\r\n opts?: UpdateOpts<U>\r\n) => StateObject<T>;\r\n\r\ntype CutFunctionType<T> = (\r\n index?: number,\r\n options?: { waitForSync?: boolean }\r\n) => StateObject<T>;\r\n\r\nexport type InferArrayElement<T> = T extends (infer U)[] ? U : never;\r\ntype ArraySpecificPrototypeKeys =\r\n | \"concat\"\r\n | \"copyWithin\"\r\n | \"fill\"\r\n | \"find\"\r\n | \"findIndex\"\r\n | \"flat\"\r\n | \"flatMap\"\r\n | \"includes\"\r\n | \"indexOf\"\r\n | \"join\"\r\n | \"keys\"\r\n | \"lastIndexOf\"\r\n | \"map\"\r\n | \"pop\"\r\n | \"push\"\r\n | \"reduce\"\r\n | \"reduceRight\"\r\n | \"reverse\"\r\n | \"shift\"\r\n | \"slice\"\r\n | \"some\"\r\n | \"sort\"\r\n | \"splice\"\r\n | \"unshift\"\r\n | \"values\"\r\n | \"entries\"\r\n | \"every\"\r\n | \"filter\"\r\n | \"forEach\"\r\n | \"with\";\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>, TShape>;\r\n cut: CutFunctionType<TShape>;\r\n _index: number;\r\n } & EndType<InferArrayElement<TShape>>;\r\n insert: PushArgs<InferArrayElement<TShape>, TShape>;\r\n cut: CutFunctionType<TShape>;\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 stateFind: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => boolean\r\n ) => StateObject<InferArrayElement<TShape>> | undefined;\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 clearSelected: () => void;\r\n getSelectedIndex: () => number;\r\n last: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n} & EndType<TShape>;\r\n\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\n\r\nexport type UpdateType<T> = (\r\n payload: UpdateArg<T>,\r\n opts?: UpdateOpts<T>\r\n) => void;\r\n\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 applyJsonPatch: (patches: any[]) => void;\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\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 toggleSelected: () => void;\r\n getFormRef: () => React.RefObject<any> | undefined;\r\n removeStorage: () => void;\r\n sync: () => 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\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 getDifferences: () => string[];\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: UpdateArg<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?: z.ZodTypeAny;\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 serverState?: {\r\n id?: string | number;\r\n data?: T;\r\n status?: \"pending\" | \"error\" | \"success\";\r\n };\r\n sync?: {\r\n action: (state: T) => Promise<{\r\n success: boolean;\r\n data?: any;\r\n error?: any;\r\n errors?: Array<{\r\n path: (string | number)[];\r\n message: string;\r\n }>;\r\n }>;\r\n onSuccess?: (data: any) => void;\r\n onError?: (error: any) => void;\r\n };\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?: {\r\n key: string | ((state: T) => string);\r\n onChange?: (state: T) => void;\r\n };\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\r\n snapshot?: {\r\n name: (({ state }: { state: T }) => string) | string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\nexport type SyncActionsType<T> = {\r\n syncKey: string;\r\n\r\n rollBackState?: T;\r\n actionTimeStamp: number;\r\n retryCount?: number;\r\n status:\r\n | \"success\"\r\n | \"waiting\"\r\n | \"rolledBack\"\r\n | \"error\"\r\n | \"cancelled\"\r\n | \"failed\";\r\n snapshot?: {\r\n name: string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\n\r\nexport type ValidationWrapperOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n active: boolean;\r\n stretch?: boolean;\r\n path: string[];\r\n message?: string;\r\n data?: T;\r\n key?: string;\r\n};\r\nexport type SyncRenderOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n time: number;\r\n data?: T;\r\n key?: string;\r\n};\r\n\r\ntype FormsElementsType<T extends unknown = unknown> = {\r\n validation?: (options: ValidationWrapperOptions<T>) => React.ReactNode;\r\n syncRender?: (options: SyncRenderOptions<T>) => React.ReactNode;\r\n};\r\n\r\nexport type InitialStateInnerType<T extends unknown = unknown> = {\r\n initialState: T;\r\n} & OptionsType<T>;\r\n\r\nexport type InitialStateType<T> = {\r\n [key: string]: InitialStateInnerType<T>;\r\n};\r\n\r\nexport type AllStateTypes<T extends unknown> = Record<string, T>;\r\n\r\nexport type CogsInitialState<T> = {\r\n initialState: T;\r\n formElements?: FormsElementsType<T>;\r\n};\r\n\r\nexport type TransformedStateType<T> = {\r\n [P in keyof T]: T[P] extends CogsInitialState<infer U> ? U : T[P];\r\n};\r\n\r\nfunction setAndMergeOptions(stateKey: string, newOptions: OptionsType<any>) {\r\n const getInitialOptions = getGlobalStore.getState().getInitialOptions;\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n\r\n setInitialStateOptions(stateKey as string, {\r\n ...initialOptions,\r\n ...newOptions,\r\n });\r\n}\r\n\r\n// Fix for the setOptions function\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 if (\r\n key == \"initialState\" &&\r\n options[key] &&\r\n mergedOptions[key] !== options[key] && // Different references\r\n !isDeepEqual(mergedOptions[key], options[key]) // And different values\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (needToAdd) {\r\n setInitialStateOptions(stateKey as string, mergedOptions);\r\n }\r\n}\r\nexport function addStateOptions<T extends unknown>(\r\n initialState: T,\r\n { formElements, validation }: OptionsType<T>\r\n) {\r\n return { initialState: initialState, formElements, validation } as T;\r\n}\r\n\r\nexport const createCogsState = <State extends Record<string, unknown>>(\r\n initialState: State,\r\n opt?: { formElements?: FormsElementsType; validation?: ValidationOptionsType }\r\n) => {\r\n let newInitialState = initialState;\r\n\r\n // Extract state parts and options using transformStateFunc\r\n const [statePart, initialOptionsPart] =\r\n transformStateFunc<State>(newInitialState);\r\n\r\n // Apply global formElements as defaults to each state key's options\r\n if (\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\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 getGlobalStore.getState().setCreatedState(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 as any,\r\n dependencies: options?.dependencies,\r\n serverState: options?.serverState,\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 if (options.localStorage) {\r\n loadAndApplyLocalStorage(stateKey as string, options);\r\n }\r\n\r\n notifyComponents(stateKey as string);\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\nconst saveToLocalStorage = <T,>(\r\n state: T,\r\n thisKey: string,\r\n currentInitialOptions: any,\r\n sessionId?: string,\r\n lastSyncedWithServer?: number\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\r\n const key = isFunction(currentInitialOptions?.localStorage?.key)\r\n ? currentInitialOptions.localStorage?.key(state)\r\n : currentInitialOptions?.localStorage?.key;\r\n\r\n if (key && sessionId) {\r\n const storageKey = `${sessionId}-${thisKey}-${key}`;\r\n\r\n // Get existing data to preserve lastSyncedWithServer if not explicitly updating it\r\n let existingLastSynced: number | undefined;\r\n try {\r\n const existing = loadFromLocalStorage(storageKey);\r\n existingLastSynced = existing?.lastSyncedWithServer;\r\n } catch {\r\n // Ignore errors, will use undefined\r\n }\r\n\r\n const data: LocalStorageData<T> = {\r\n state,\r\n lastUpdated: Date.now(),\r\n lastSyncedWithServer: lastSyncedWithServer ?? existingLastSynced,\r\n };\r\n\r\n // Use SuperJSON serialize to get the json part only\r\n const superJsonResult = superjson.serialize(data);\r\n window.localStorage.setItem(\r\n storageKey,\r\n JSON.stringify(superJsonResult.json)\r\n );\r\n }\r\n};\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 // Parse the json part back normally\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\nconst loadAndApplyLocalStorage = (stateKey: string, options: any) => {\r\n const currentState = getGlobalStore.getState().cogsStateStore[stateKey];\r\n const { sessionId } = useCogsConfig();\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options.localStorage.key(currentState)\r\n : options?.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n const localData = loadFromLocalStorage(\r\n `${sessionId}-${stateKey}-${localkey}`\r\n );\r\n\r\n if (\r\n localData &&\r\n localData.lastUpdated > (localData.lastSyncedWithServer || 0)\r\n ) {\r\n setState(stateKey, localData.state);\r\n\r\n notifyComponents(stateKey);\r\n return true;\r\n }\r\n }\r\n return false;\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 updateInitialStateGlobal(thisKey, updates.initialState);\r\n setUpdaterState(thisKey, updates.updaterState);\r\n setState(thisKey, updates.state);\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 const reactiveTypes = component\r\n ? Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"]\r\n : null;\r\n if (!reactiveTypes?.includes(\"none\")) {\r\n updates.add(() => component.forceUpdate());\r\n }\r\n });\r\n\r\n // Schedule updates in the next tick to allow batching\r\n queueMicrotask(() => {\r\n updates.forEach((update) => update());\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 const reactiveTypes = component\r\n ? Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"]\r\n : null;\r\n\r\n // Skip if reactivity is disabled\r\n if (reactiveTypes?.includes(\"none\")) {\r\n return;\r\n }\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\nconst getUpdateValues = (\r\n updateType: string,\r\n prevValue: any,\r\n payload: any,\r\n path: string[]\r\n) => {\r\n switch (updateType) {\r\n case \"update\":\r\n return {\r\n oldValue: getNestedValue(prevValue, path),\r\n newValue: getNestedValue(payload, path),\r\n };\r\n case \"insert\":\r\n return {\r\n oldValue: null, // or undefined\r\n newValue: getNestedValue(payload, path),\r\n };\r\n case \"cut\":\r\n return {\r\n oldValue: getNestedValue(prevValue, path),\r\n newValue: null, // or undefined\r\n };\r\n default:\r\n return { oldValue: null, newValue: null };\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 reactiveDeps,\r\n reactiveType,\r\n componentId,\r\n initialState,\r\n syncUpdate,\r\n dependencies,\r\n serverState,\r\n }: {\r\n stateKey?: string;\r\n componentId?: string;\r\n initialState?: TStateObject;\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<OptionsType<TStateObject> | null>(\r\n null\r\n );\r\n latestInitialOptionsRef.current = (getInitialOptions(thisKey as string) ??\r\n null) as OptionsType<TStateObject> | null;\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 useEffect(() => {\r\n // Only proceed if initialState is provided\r\n if (initialState) {\r\n setAndMergeOptions(thisKey as string, {\r\n initialState,\r\n });\r\n\r\n const options = latestInitialOptionsRef.current;\r\n const hasServerId = options?.serverState?.id !== undefined;\r\n const hasServerData =\r\n hasServerId &&\r\n options?.serverState?.status === \"success\" &&\r\n options?.serverState?.data;\r\n\r\n const currentGloballyStoredInitialState =\r\n getGlobalStore.getState().initialStateGlobal[thisKey];\r\n\r\n const initialStateChanged =\r\n (currentGloballyStoredInitialState &&\r\n !isDeepEqual(currentGloballyStoredInitialState, initialState)) ||\r\n !currentGloballyStoredInitialState;\r\n\r\n if (!initialStateChanged && !hasServerData) {\r\n return;\r\n }\r\n\r\n let localData = null;\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options?.localStorage?.key(initialState)\r\n : options?.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n localData = loadFromLocalStorage(`${sessionId}-${thisKey}-${localkey}`);\r\n }\r\n\r\n let newState = initialState;\r\n let isFromServer = false;\r\n\r\n const serverTimestamp = hasServerData ? Date.now() : 0;\r\n const localTimestamp = localData?.lastUpdated || 0;\r\n const lastSyncTimestamp = localData?.lastSyncedWithServer || 0;\r\n\r\n if (hasServerData && serverTimestamp > localTimestamp) {\r\n newState = options.serverState!.data!;\r\n isFromServer = true;\r\n } else if (localData && localTimestamp > lastSyncTimestamp) {\r\n newState = localData.state;\r\n if (options?.localStorage?.onChange) {\r\n options?.localStorage?.onChange(newState);\r\n }\r\n }\r\n\r\n // Update the global state\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 // Save to localStorage if we used server data\r\n if (isFromServer && localkey && sessionId) {\r\n saveToLocalStorage(newState, thisKey, options, sessionId, Date.now());\r\n }\r\n\r\n // Notify components of the change\r\n notifyComponents(thisKey);\r\n\r\n const reactiveTypes = Array.isArray(reactiveType)\r\n ? reactiveType\r\n : [reactiveType || \"component\"];\r\n\r\n if (!reactiveTypes.includes(\"none\")) {\r\n forceUpdate({});\r\n }\r\n }\r\n }, [\r\n initialState,\r\n serverState?.status,\r\n serverState?.data,\r\n ...(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: latestInitialOptionsRef.current?.middleware,\r\n });\r\n }\r\n\r\n const componentKey = `${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(componentKey, {\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 componentKey = `${thisKey}////${componentIdRef.current}`;\r\n\r\n if (stateEntry) {\r\n stateEntry.components.delete(componentKey);\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: UpdateArg<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?.validation?.key) &&\r\n path\r\n ) {\r\n removeValidationError(\r\n (validationKey || latestInitialOptionsRef.current?.validation?.key) +\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?.validation?.key\r\n ) {\r\n removeValidationError(\r\n latestInitialOptionsRef.current?.validation?.key +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n }\r\n if (\r\n updateObj.updateType === \"insert\" &&\r\n latestInitialOptionsRef.current?.validation?.key\r\n ) {\r\n let getValidation = getValidationErrors(\r\n latestInitialOptionsRef.current?.validation?.key +\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 stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n console.log(\"stateEntry\", stateEntry);\r\n if (stateEntry) {\r\n const changedPaths = getDifferences(prevValue, payload);\r\n const changedPathsSet = new Set(changedPaths);\r\n const primaryPathToCheck =\r\n updateObj.updateType === \"update\"\r\n ? path.join(\".\")\r\n : path.slice(0, -1).join(\".\") || \"\";\r\n\r\n for (const [\r\n componentKey,\r\n component,\r\n ] 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 console.log(\"component\", component);\r\n if (reactiveTypes.includes(\"none\")) continue;\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n continue;\r\n }\r\n\r\n if (reactiveTypes.includes(\"component\")) {\r\n if (\r\n component.paths.has(primaryPathToCheck) ||\r\n component.paths.has(\"\")\r\n ) {\r\n shouldUpdate = true;\r\n }\r\n\r\n if (!shouldUpdate) {\r\n for (const changedPath of changedPathsSet) {\r\n let currentPathToCheck = changedPath;\r\n while (true) {\r\n if (component.paths.has(currentPathToCheck)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n const lastDotIndex = currentPathToCheck.lastIndexOf(\".\");\r\n if (lastDotIndex !== -1) {\r\n const parentPath = currentPathToCheck.substring(\r\n 0,\r\n lastDotIndex\r\n );\r\n if (\r\n !isNaN(\r\n Number(currentPathToCheck.substring(lastDotIndex + 1))\r\n )\r\n ) {\r\n if (component.paths.has(parentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n }\r\n currentPathToCheck = parentPath;\r\n } else {\r\n currentPathToCheck = \"\";\r\n }\r\n if (currentPathToCheck === \"\") {\r\n break;\r\n }\r\n }\r\n if (shouldUpdate) break;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(payload);\r\n let depsChanged = false;\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) depsChanged = true;\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n depsChanged = true;\r\n }\r\n if (depsChanged) {\r\n shouldUpdate = true;\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 path = path.map((p, i) => {\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n\r\n return i === path.length - 1 &&\r\n [\"insert\", \"cut\"].includes(updateObj.updateType)\r\n ? (arrayValue.length - 1).toString()\r\n : p;\r\n });\r\n\r\n const { oldValue, newValue } = getUpdateValues(\r\n updateObj.updateType,\r\n prevValue,\r\n payload,\r\n path\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 (latestInitialOptionsRef.current?.middleware) {\r\n latestInitialOptionsRef.current!.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, sessionId]);\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 getGlobalStore.getState().clearSelectedIndexesForState(stateKey);\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\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 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 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\r\n if (localStorage.getItem(storageKey)) {\r\n localStorage.removeItem(storageKey);\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\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\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 (meta?.validIndices && !Array.isArray(currentState)) {\r\n meta = { ...meta, validIndices: undefined };\r\n }\r\n const mutationMethods = new Set([\r\n \"insert\",\r\n \"cut\",\r\n \"cutByValue\",\r\n \"toggleByValue\",\r\n \"uniqueInsert\",\r\n \"update\",\r\n \"applyJsonPatch\",\r\n \"setSelected\",\r\n \"toggleSelected\",\r\n \"clearSelected\",\r\n \"sync\",\r\n \"validateZodSchema\",\r\n \"revertToInitialState\",\r\n \"updateInitialState\",\r\n \"removeValidation\",\r\n \"setValidation\",\r\n \"removeStorage\",\r\n \"middleware\",\r\n \"_componentId\",\r\n \"_stateKey\",\r\n \"getComponents\",\r\n ]);\r\n if (\r\n prop !== \"then\" &&\r\n !prop.startsWith(\"$\") &&\r\n prop !== \"stateMapNoRender\" &&\r\n !mutationMethods.has(prop)\r\n ) {\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n // console.log(\"adding path\", fullComponentId, path, prop);\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 && !component.pathsInitialized) {\r\n // Mark as initialized immediately to prevent re-processing\r\n component.pathsInitialized = true;\r\n\r\n // Now do the path tracking logic ONCE\r\n if (!component.paths.has(\"\")) {\r\n const currentPath = path.join(\".\");\r\n let needsAdd = true;\r\n for (const existingPath of component.paths) {\r\n if (\r\n currentPath.startsWith(existingPath) &&\r\n (currentPath === existingPath ||\r\n currentPath[existingPath.length] === \".\")\r\n ) {\r\n needsAdd = false;\r\n break;\r\n }\r\n }\r\n\r\n if (needsAdd) {\r\n // console.log(\r\n // \"adding path actualyl adding\",\r\n // fullComponentId,\r\n // path,\r\n // prop\r\n // );\r\n component.paths.add(currentPath);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (prop === \"getDifferences\") {\r\n return () => {\r\n const differences = getDifferences(\r\n getGlobalStore.getState().cogsStateStore[stateKey],\r\n getGlobalStore.getState().initialStateGlobal[stateKey]\r\n );\r\n return differences;\r\n };\r\n }\r\n if (prop === \"sync\" && path.length === 0) {\r\n return async function () {\r\n // Get the options for this state key\r\n const options = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey);\r\n const sync = options?.sync;\r\n\r\n if (!sync) {\r\n console.error(`No mutation defined for state key \"${stateKey}\"`);\r\n return { success: false, error: `No mutation defined` };\r\n }\r\n\r\n // Get the root state\r\n const state = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, []);\r\n\r\n // Get validation key\r\n const validationKey = options?.validation?.key;\r\n\r\n try {\r\n // Execute the mutation action\r\n const response = await sync.action(state);\r\n\r\n // Handle validation errors\r\n if (\r\n response &&\r\n !response.success &&\r\n response.errors &&\r\n validationKey\r\n ) {\r\n // Clear existing errors\r\n getGlobalStore.getState().removeValidationError(validationKey);\r\n\r\n // Add new validation errors\r\n response.errors.forEach((error) => {\r\n const errorPath = [validationKey, ...error.path].join(\".\");\r\n\r\n getGlobalStore\r\n .getState()\r\n .addValidationError(errorPath, error.message);\r\n });\r\n\r\n // Notify components to update\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 // Call success/error callbacks\r\n if (response?.success && sync.onSuccess) {\r\n sync.onSuccess(response.data);\r\n } else if (!response?.success && sync.onError) {\r\n sync.onError(response.error);\r\n }\r\n\r\n return response;\r\n } catch (error) {\r\n if (sync.onError) {\r\n sync.onError(error);\r\n }\r\n return { success: false, error };\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 // 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\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 const getSourceArrayAndIndices = (): {\r\n item: any;\r\n originalIndex: number;\r\n }[] => {\r\n // If meta exists, we're in a chain. Use the currentState and map it to its original index.\r\n if (meta?.validIndices) {\r\n return (currentState as any[]).map((item, index) => ({\r\n item,\r\n originalIndex: meta!.validIndices![index]!,\r\n }));\r\n }\r\n // Otherwise, this is the first operation. Use the full array from the global store.\r\n const sourceArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n return sourceArray.map((item, index) => ({\r\n item,\r\n originalIndex: index,\r\n }));\r\n };\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 === \"clearSelected\") {\r\n return () => {\r\n getGlobalStore.getState().clearSelectedIndex({ stateKey, path });\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 sourceWithIndices = getSourceArrayAndIndices();\r\n const sortedResult = [...sourceWithIndices].sort((a, b) =>\r\n compareFn(a.item, b.item)\r\n );\r\n const newCurrentState = sortedResult.map(({ item }) => item);\r\n // We construct the meta object with the CORRECT property name: `validIndices`.\r\n const newMeta = {\r\n ...meta,\r\n validIndices: sortedResult.map(\r\n ({ originalIndex }) => originalIndex\r\n ),\r\n };\r\n return rebuildStateShape(newCurrentState as any, path, newMeta);\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 sourceWithIndices = getSourceArrayAndIndices();\r\n const filteredResult = sourceWithIndices.filter(\r\n ({ item }, index) => callbackfn(item, index)\r\n );\r\n const newCurrentState = filteredResult.map(({ item }) => item);\r\n // We construct the meta object with the CORRECT property name: `validIndices`.\r\n const newMeta = {\r\n ...meta,\r\n validIndices: filteredResult.map(\r\n ({ originalIndex }) => originalIndex\r\n ),\r\n };\r\n return rebuildStateShape(newCurrentState as any, path, newMeta);\r\n };\r\n }\r\n // This code goes inside the `get` trap of `createProxyHandler`\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 ) => React.ReactNode // Your callback returns the JSX to render\r\n ) => {\r\n const arrayToMap = currentState as any[];\r\n\r\n return arrayToMap.map((item, index) => {\r\n let originalIndex: number;\r\n if (\r\n meta?.validIndices &&\r\n meta.validIndices[index] !== undefined\r\n ) {\r\n originalIndex = meta.validIndices[index]!;\r\n } else {\r\n originalIndex = index;\r\n }\r\n\r\n // The specific path for this individual item in the array.\r\n const finalPath = [...path, originalIndex.toString()];\r\n\r\n // The proxy for this item, which can be used for updates.\r\n const setter = rebuildStateShape(item, finalPath, meta);\r\n\r\n // A stable and unique ID for this item's wrapper component.\r\n const itemComponentId = `${componentId}-${path.join(\".\")}-${originalIndex}`;\r\n\r\n // Call the user's render function to get their actual component JSX.\r\n const userComponentJsx = callbackfn(item, setter, index);\r\n\r\n // Transparently wrap the user's component in our internal registration component.\r\n return (\r\n <CogsItemWrapper\r\n key={originalIndex} // The wrapper itself needs a key for React's mapping.\r\n stateKey={stateKey}\r\n itemComponentId={itemComponentId}\r\n itemPath={finalPath} // Pass the specific path for atomic updates.\r\n >\r\n {userComponentJsx}\r\n </CogsItemWrapper>\r\n );\r\n });\r\n };\r\n }\r\n if (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 ) => any\r\n ) => {\r\n const arrayToMap = currentState as any[];\r\n return arrayToMap.map((item, index) => {\r\n let originalIndex: number;\r\n // We READ from the meta object using the CORRECT property name: `validIndices`.\r\n if (\r\n meta?.validIndices &&\r\n meta.validIndices[index] !== undefined\r\n ) {\r\n originalIndex = meta.validIndices[index]!;\r\n } else {\r\n originalIndex = index;\r\n }\r\n const finalPath = [...path, originalIndex.toString()];\r\n\r\n const setter = rebuildStateShape(item, finalPath, meta); // Pass meta through\r\n return callbackfn(\r\n item,\r\n setter,\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\r\n if (prop === \"stateFlattenOn\") {\r\n return (fieldName: string) => {\r\n const arrayToMap = currentState as any[];\r\n shapeCache.clear();\r\n stateVersion++;\r\n const flattenedResults = arrayToMap.flatMap(\r\n (val: any) => val[fieldName] ?? []\r\n );\r\n return rebuildStateShape(\r\n flattenedResults as any,\r\n [...path, \"[*]\", fieldName],\r\n meta\r\n );\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 if (prop === \"last\") {\r\n // Added handler for 'last'\r\n return () => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n if (currentArray.length === 0) return undefined;\r\n const lastIndex = currentArray.length - 1;\r\n const lastValue = currentArray[lastIndex];\r\n const newPath = [...path, lastIndex.toString()];\r\n // shapeCache.clear(); // Decide if you need cache invalidation for 'last' access\r\n // stateVersion++;\r\n return rebuildStateShape(lastValue, newPath);\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().getNestedState(stateKey, path),\r\n path\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 return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, path),\r\n path\r\n );\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 if (prop === \"stateFind\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const found = sourceWithIndices.find(({ item }, index) =>\r\n callbackfn(item, index)\r\n );\r\n if (!found) return undefined;\r\n const finalPath = [...path, found.originalIndex.toString()];\r\n return rebuildStateShape(found.item, finalPath, meta);\r\n };\r\n }\r\n\r\n if (prop === \"findWith\") {\r\n return (thisKey: keyof InferArrayElement<T>, thisValue: any) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const found = sourceWithIndices.find(\r\n ({ item }) => item[thisKey] === thisValue\r\n );\r\n if (!found) return undefined;\r\n const finalPath = [...path, found.originalIndex.toString()];\r\n return rebuildStateShape(found.item, finalPath, meta);\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\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 (prop === \"toggleSelected\") {\r\n return () => {\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 const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, parentKey);\r\n\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(\r\n stateKey,\r\n parentKey,\r\n selectedIndex === thisIndex ? undefined : thisIndex\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 invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (path.length == 0) {\r\n if (prop === \"applyJsonPatch\") {\r\n return (patches: any[]) => {\r\n // This part is correct.\r\n const currentState =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n const patchResult = applyPatch(currentState, patches);\r\n const newState = patchResult.newDocument;\r\n\r\n // This is also correct.\r\n updateGlobalState(\r\n stateKey,\r\n getGlobalStore.getState().initialStateGlobal[stateKey],\r\n newState,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n\r\n // ===================================================================\r\n // REPLACE THE OLD LOGIC WITH THIS DIRECT COPY\r\n // ===================================================================\r\n\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey); // Use stateKey here\r\n\r\n if (stateEntry) {\r\n // Use `getDifferences` between the state before and after the patch.\r\n const changedPaths = getDifferences(currentState, newState);\r\n const changedPathsSet = new Set(changedPaths);\r\n\r\n // There is no single `primaryPathToCheck` for a patch, so we just check against the full set.\r\n\r\n for (const [\r\n componentKey,\r\n component,\r\n ] 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 if (reactiveTypes.includes(\"none\")) continue;\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n continue;\r\n }\r\n\r\n if (reactiveTypes.includes(\"component\")) {\r\n // This is the core logic that needs to be copied.\r\n // Check if any of the component's watched paths are in the set of changed paths.\r\n if (component.paths.has(\"\")) {\r\n // Always update for root listeners\r\n shouldUpdate = true;\r\n }\r\n\r\n if (!shouldUpdate) {\r\n for (const changedPath of changedPathsSet) {\r\n // Direct match first (fastest)\r\n if (component.paths.has(changedPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n\r\n // Check parent paths more efficiently\r\n let dotIndex = changedPath.lastIndexOf(\".\");\r\n while (dotIndex !== -1) {\r\n const parentPath = changedPath.substring(0, dotIndex);\r\n if (component.paths.has(parentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n // Skip numeric segments more efficiently\r\n const lastSegment = changedPath.substring(\r\n dotIndex + 1\r\n );\r\n if (!isNaN(Number(lastSegment))) {\r\n // For array indices, check the parent collection path\r\n const parentDotIndex = parentPath.lastIndexOf(\".\");\r\n if (parentDotIndex !== -1) {\r\n const grandParentPath = parentPath.substring(\r\n 0,\r\n parentDotIndex\r\n );\r\n if (component.paths.has(grandParentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n }\r\n }\r\n dotIndex = parentPath.lastIndexOf(\".\");\r\n }\r\n\r\n if (shouldUpdate) break;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n // Use `newState` (the result of the patch) for dependency checks.\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(newState);\r\n let depsChanged = false;\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) depsChanged = true;\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n depsChanged = true;\r\n }\r\n if (depsChanged) {\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 };\r\n }\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// This is an internal component. It should NOT be exported.\r\nfunction CogsItemWrapper({\r\n stateKey,\r\n itemComponentId,\r\n itemPath,\r\n children,\r\n}: {\r\n stateKey: string;\r\n itemComponentId: string;\r\n itemPath: string[];\r\n children: React.ReactNode;\r\n}) {\r\n // This is a real component, so we can safely call hooks.\r\n const [, forceUpdate] = useState({});\r\n\r\n // We use useLayoutEffect to register the component and clean up when it unmounts.\r\n useLayoutEffect(() => {\r\n const fullComponentId = `${stateKey}////${itemComponentId}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey) || {\r\n components: new Map(),\r\n };\r\n\r\n // Register the component with its unique ID and its specific, atomic path.\r\n stateEntry.components.set(fullComponentId, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set([itemPath.join(\".\")]), // ATOMIC: Subscribes only to this item's path.\r\n });\r\n\r\n getGlobalStore.getState().stateComponents.set(stateKey, stateEntry);\r\n\r\n // Return a cleanup function to unregister on unmount.\r\n return () => {\r\n const currentEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (currentEntry) {\r\n currentEntry.components.delete(fullComponentId);\r\n }\r\n };\r\n }, [stateKey, itemComponentId, itemPath.join(\".\")]); // Effect dependency array is stable.\r\n\r\n // Render the actual component the user provided.\r\n return <>{children}</>;\r\n}\r\n"],"names":["setAndMergeOptions","stateKey","newOptions","getInitialOptions","getGlobalStore","setInitialStateOptions","initialOptions","setOptions","options","initialOptionsPart","initialOptionsPartState","mergedOptions","needToAdd","key","isDeepEqual","addStateOptions","initialState","formElements","validation","createCogsState","opt","newInitialState","statePart","transformStateFunc","useCogsState","componentId","useState","uuidv4","thiState","partialState","state","updater","useCogsStateFn","setCogsOptions","loadAndApplyLocalStorage","notifyComponents","setUpdaterState","setState","getKeyState","getValidationErrors","setStateLog","updateInitialStateGlobal","addValidationError","removeValidationError","setServerSyncActions","saveToLocalStorage","thisKey","currentInitialOptions","sessionId","lastSyncedWithServer","isFunction","storageKey","existingLastSynced","loadFromLocalStorage","data","superJsonResult","superjson","localStorageKey","storedData","error","currentState","useCogsConfig","localkey","localData","updateGlobalState","newState","effectiveSetState","updates","createProxyHandler","stateEntry","component","update","notifyComponent","fullComponentId","getUpdateValues","updateType","prevValue","payload","path","getNestedValue","stateObject","serverSync","localStorage","reactiveDeps","reactiveType","syncUpdate","dependencies","serverState","reactiveForce","forceUpdate","noStateKey","stateLog","componentUpdatesRef","useRef","componentIdRef","latestInitialOptionsRef","useEffect","prevState","syncKey","hasServerData","currentGloballyStoredInitialState","isFromServer","serverTimestamp","localTimestamp","lastSyncTimestamp","useLayoutEffect","componentKey","newStateOrFunction","updateObj","validationKey","pathKey","signalId","isArrayOperation","elements","arrayPath","arrayValue","arraySignalId","newValue","parentId","position","effect","parent","childNodes","displayValue","arrayWithoutIndex","k","v","length","newKey","changedPaths","getDifferences","changedPathsSet","primaryPathToCheck","shouldUpdate","reactiveTypes","changedPath","currentPathToCheck","lastDotIndex","parentPath","depsResult","depsChanged","timeStamp","p","i","oldValue","newUpdate","prevLogs","aggregatedLogs","acc","log","uniqueKey","existing","serverStateStore","updaterFinal","useMemo","shapeCache","stateVersion","invalidateCachePath","baseObj","obj","init","newProxy","rebuildStateShape","initalOptionsGet","localKey","newUpdaterState","startTransition","field","meta","cacheKey","baseFunction","handler","target","thisArg","args","prop","mutationMethods","currentPath","needsAdd","existingPath","sync","response","errorPath","thisReactiveState","initialStateAtPath","getSourceArrayAndIndices","item","index","selectedIndex","compareFn","sortedResult","a","b","newCurrentState","newMeta","originalIndex","callbackfn","filteredResult","finalPath","setter","itemComponentId","userComponentJsx","jsx","CogsItemWrapper","createElement","SignalMapRenderer","fieldName","arrayToMap","flattenedResults","val","indexValue","currentArray","lastIndex","lastValue","newPath","pushFunc","fields","onMatch","matchedItem","isMatch","updatedItem","updatedArray","updateFn","cutFunc","value","found","thisValue","lastPathElement","parentValue","fn","$cogsSignal","parentKey","thisIndex","nested","patches","applyPatch","dotIndex","lastSegment","parentDotIndex","grandParentPath","thisObject","existingErrors","result","errorMessage","fullErrorPath","formRefStore","children","hideMessage","ValidationWrapper","opts","debounce","child","formOpts","FormControlComponent","nextPath","nextValue","proxyInstance","proxy","SignalRenderer","arraysetter","elementRef","element","parentElement","elementInfo","err","textNode","$cogsSignalStore","useSyncExternalStore","notify","itemPath","currentEntry"],"mappings":";;;;;;;;;;;AAocA,SAASA,GAAmBC,GAAkBC,GAA8B;AACpEC,QAAAA,IAAoBC,EAAe,SAAA,EAAW,mBAC9CC,IACJD,EAAe,SAAA,EAAW,wBAEtBE,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC;AAEjE,EAAAI,EAAuBJ,GAAoB;AAAA,IACzC,GAAGK;AAAA,IACH,GAAGJ;AAAA,EAAA,CACJ;AACH;AAGA,SAASK,GAA0B;AAAA,EACjC,UAAAN;AAAA,EACA,SAAAO;AAAA,EACA,oBAAAC;AACF,GAIG;AACD,QAAMH,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC,GAC3DS,IAA0BD,EAAmBR,CAAkB,KAAK,CAAC,GACrEI,IACJD,EAAe,SAAA,EAAW,wBACtBO,IAAgB,EAAE,GAAGD,GAAyB,GAAGJ,EAAe;AAEtE,MAAIM,IAAY;AAChB,MAAIJ;AACF,eAAWK,KAAOL;AAChB,MAAKG,EAAc,eAAeE,CAAG,KAKjCA,KAAO,kBACPL,EAAQK,CAAG,KACXF,EAAcE,CAAG,EAAE,QAAQL,EAAQK,CAAG,GAAG,QAE7BD,IAAA,IACED,EAAAE,CAAG,IAAIL,EAAQK,CAAG,IAGhCA,KAAO,kBACPL,EAAQK,CAAG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AS,KAAK,GAAG,CAAC,CAAC,4BAGxC,UAAAvB,GAAS;AACrB;"}
|
package/package.json
CHANGED
package/src/CogsState.tsx
CHANGED
|
@@ -1099,6 +1099,7 @@ export function useCogsStateFn<TStateObject extends unknown>(
|
|
|
1099
1099
|
}
|
|
1100
1100
|
|
|
1101
1101
|
const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);
|
|
1102
|
+
console.log("stateEntry", stateEntry);
|
|
1102
1103
|
if (stateEntry) {
|
|
1103
1104
|
const changedPaths = getDifferences(prevValue, payload);
|
|
1104
1105
|
const changedPathsSet = new Set(changedPaths);
|
|
@@ -1115,7 +1116,7 @@ export function useCogsStateFn<TStateObject extends unknown>(
|
|
|
1115
1116
|
const reactiveTypes = Array.isArray(component.reactiveType)
|
|
1116
1117
|
? component.reactiveType
|
|
1117
1118
|
: [component.reactiveType || "component"];
|
|
1118
|
-
|
|
1119
|
+
console.log("component", component);
|
|
1119
1120
|
if (reactiveTypes.includes("none")) continue;
|
|
1120
1121
|
if (reactiveTypes.includes("all")) {
|
|
1121
1122
|
component.forceUpdate();
|