cogsbox-state 0.5.432 → 0.5.435

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.
@@ -1,1231 +1,1809 @@
1
1
  "use client";
2
- import { jsx as $t } from "react/jsx-runtime";
3
- import { useState as dt, useRef as q, useEffect as at, useLayoutEffect as pt, useMemo as Et, createElement as gt, useSyncExternalStore as Ft, startTransition as Ut, useCallback as St } from "react";
4
- import { transformStateFunc as Dt, isDeepEqual as X, isFunction as et, getNestedValue as L, getDifferences as Pt, debounce as Lt } from "./utility.js";
5
- import { pushFunc as At, updateFn as ut, cutFunc as ft, ValidationWrapper as Gt, FormControlComponent as Ht } from "./Functions.jsx";
6
- import zt from "superjson";
7
- import { v4 as kt } from "uuid";
8
- import "zod";
9
- import { getGlobalStore as o, formRefStore as bt } from "./store.js";
10
- import { useCogsConfig as Rt } from "./CogsStateClient.jsx";
11
- import { applyPatch as Wt } from "fast-json-patch";
12
- import Bt from "react-use-measure";
13
- import "ulid";
14
- function Mt(t, s) {
15
- const S = o.getState().getInitialOptions, g = o.getState().setInitialStateOptions, I = S(t) || {};
16
- g(t, {
17
- ...I,
18
- ...s
2
+ import { jsx as re, Fragment as ke } from "react/jsx-runtime";
3
+ import { memo as Re, useState as X, useRef as G, useCallback as ce, useEffect as Q, useLayoutEffect as de, useMemo as ge, createElement as le, startTransition as je } from "react";
4
+ import { createRoot as Ce } from "react-dom/client";
5
+ import { transformStateFunc as Fe, isFunction as ee, isArray as Te, getDifferences as Pe, isDeepEqual as se } from "./utility.js";
6
+ import { ValidationWrapper as be } from "./Functions.jsx";
7
+ import Oe from "superjson";
8
+ import { v4 as te } from "uuid";
9
+ import { getGlobalStore as t, formRefStore as pe } from "./store.js";
10
+ import { useCogsConfig as _e } from "./CogsStateClient.jsx";
11
+ import { useInView as Le } from "react-intersection-observer";
12
+ function he(e, i) {
13
+ const f = t.getState().getInitialOptions, g = t.getState().setInitialStateOptions, h = f(e) || {};
14
+ g(e, {
15
+ ...h,
16
+ ...i
19
17
  });
20
18
  }
21
- function Nt({
22
- stateKey: t,
23
- options: s,
24
- initialOptionsPart: S
19
+ function Ee({
20
+ stateKey: e,
21
+ options: i,
22
+ initialOptionsPart: f
25
23
  }) {
26
- const g = lt(t) || {}, I = S[t] || {}, T = o.getState().setInitialStateOptions, A = { ...I, ...g };
27
- let v = !1;
28
- if (s)
29
- for (const i in s)
30
- A.hasOwnProperty(i) ? (i == "localStorage" && s[i] && A[i].key !== s[i]?.key && (v = !0, A[i] = s[i]), i == "initialState" && s[i] && A[i] !== s[i] && // Different references
31
- !X(A[i], s[i]) && (v = !0, A[i] = s[i])) : (v = !0, A[i] = s[i]);
32
- v && T(t, A);
24
+ const g = ae(e) || {}, h = f[e] || {}, p = t.getState().setInitialStateOptions, M = { ...h, ...g };
25
+ let l = !1;
26
+ if (i)
27
+ for (const u in i)
28
+ M.hasOwnProperty(u) ? (u == "localStorage" && i[u] && M[u].key !== i[u]?.key && (l = !0, M[u] = i[u]), u == "defaultState" && i[u] && M[u] !== i[u] && !se(M[u], i[u]) && (l = !0, M[u] = i[u])) : (l = !0, M[u] = i[u]);
29
+ l && p(e, M);
33
30
  }
34
- function Se(t, { formElements: s, validation: S }) {
35
- return { initialState: t, formElements: s, validation: S };
31
+ function it(e, { formElements: i, validation: f }) {
32
+ return { initialState: e, formElements: i, validation: f };
36
33
  }
37
- const me = (t, s) => {
38
- let S = t;
39
- const [g, I] = Dt(S);
40
- (Object.keys(I).length > 0 || s && Object.keys(s).length > 0) && Object.keys(I).forEach((v) => {
41
- I[v] = I[v] || {}, I[v].formElements = {
42
- ...s?.formElements,
43
- // Global defaults first
44
- ...s?.validation,
45
- ...I[v].formElements || {}
46
- // State-specific overrides
47
- }, lt(v) || o.getState().setInitialStateOptions(v, I[v]);
48
- }), o.getState().setInitialStates(g), o.getState().setCreatedState(g);
49
- const T = (v, i) => {
50
- const [$] = dt(i?.componentId ?? kt());
51
- Nt({
52
- stateKey: v,
53
- options: i,
54
- initialOptionsPart: I
34
+ const ct = (e, i) => {
35
+ let f = e;
36
+ const [g, h] = Fe(f);
37
+ Object.keys(g).forEach((l) => {
38
+ let u = h[l] || {};
39
+ const A = {
40
+ ...u
41
+ };
42
+ if (i?.formElements && (A.formElements = {
43
+ ...i.formElements,
44
+ ...u.formElements || {}
45
+ }), i?.validation && (A.validation = {
46
+ ...i.validation,
47
+ ...u.validation || {}
48
+ }, i.validation.key && !u.validation?.key && (A.validation.key = `${i.validation.key}.${l}`)), Object.keys(A).length > 0) {
49
+ const b = ae(l);
50
+ b ? t.getState().setInitialStateOptions(l, {
51
+ ...b,
52
+ ...A
53
+ }) : t.getState().setInitialStateOptions(l, A);
54
+ }
55
+ }), Object.keys(g).forEach((l) => {
56
+ t.getState().initializeShadowState(l, g[l]);
57
+ });
58
+ const p = (l, u) => {
59
+ const [A] = X(u?.componentId ?? te());
60
+ Ee({
61
+ stateKey: l,
62
+ options: u,
63
+ initialOptionsPart: h
64
+ });
65
+ const b = t.getState().getShadowValue(l) || g[l], o = u?.modifyState ? u.modifyState(b) : b;
66
+ return Be(o, {
67
+ stateKey: l,
68
+ syncUpdate: u?.syncUpdate,
69
+ componentId: A,
70
+ localStorage: u?.localStorage,
71
+ middleware: u?.middleware,
72
+ reactiveType: u?.reactiveType,
73
+ reactiveDeps: u?.reactiveDeps,
74
+ defaultState: u?.defaultState,
75
+ dependencies: u?.dependencies,
76
+ serverState: u?.serverState
55
77
  });
56
- const y = o.getState().cogsStateStore[v] || g[v], n = i?.modifyState ? i.modifyState(y) : y, [w, O] = Xt(
57
- n,
58
- {
59
- stateKey: v,
60
- syncUpdate: i?.syncUpdate,
61
- componentId: $,
62
- localStorage: i?.localStorage,
63
- middleware: i?.middleware,
64
- enabledSync: i?.enabledSync,
65
- reactiveType: i?.reactiveType,
66
- reactiveDeps: i?.reactiveDeps,
67
- initialState: i?.initialState,
68
- dependencies: i?.dependencies,
69
- serverState: i?.serverState
70
- }
71
- );
72
- return O;
73
78
  };
74
- function A(v, i) {
75
- Nt({ stateKey: v, options: i, initialOptionsPart: I }), i.localStorage && Yt(v, i), ot(v);
79
+ function M(l, u) {
80
+ Ee({ stateKey: l, options: u, initialOptionsPart: h }), u.localStorage && xe(l, u), ie(l);
76
81
  }
77
- return { useCogsState: T, setCogsOptions: A };
82
+ return { useCogsState: p, setCogsOptions: M };
78
83
  }, {
79
- setUpdaterState: mt,
80
- setState: st,
81
- getInitialOptions: lt,
82
- getKeyState: Ot,
83
- getValidationErrors: qt,
84
- setStateLog: Jt,
85
- updateInitialStateGlobal: xt,
86
- addValidationError: Tt,
87
- removeValidationError: tt,
88
- setServerSyncActions: Zt
89
- } = o.getState(), Ct = (t, s, S, g, I) => {
90
- S?.log && console.log(
84
+ getInitialOptions: ae,
85
+ getValidationErrors: Ne,
86
+ setStateLog: We,
87
+ updateInitialStateGlobal: $e,
88
+ addValidationError: ve,
89
+ removeValidationError: ne
90
+ } = t.getState(), He = (e, i, f, g, h) => {
91
+ f?.log && console.log(
91
92
  "saving to localstorage",
92
- s,
93
- S.localStorage?.key,
93
+ i,
94
+ f.localStorage?.key,
94
95
  g
95
96
  );
96
- const T = et(S?.localStorage?.key) ? S.localStorage?.key(t) : S?.localStorage?.key;
97
- if (T && g) {
98
- const A = `${g}-${s}-${T}`;
99
- let v;
97
+ const p = ee(f?.localStorage?.key) ? f.localStorage?.key(e) : f?.localStorage?.key;
98
+ if (p && g) {
99
+ const M = `${g}-${i}-${p}`;
100
+ let l;
100
101
  try {
101
- v = yt(A)?.lastSyncedWithServer;
102
+ l = Se(M)?.lastSyncedWithServer;
102
103
  } catch {
103
104
  }
104
- const i = {
105
- state: t,
105
+ const u = t.getState().getShadowMetadata(i, []), A = {
106
+ state: e,
106
107
  lastUpdated: Date.now(),
107
- lastSyncedWithServer: I ?? v
108
- }, $ = zt.serialize(i);
108
+ lastSyncedWithServer: l,
109
+ stateSource: u?.stateSource,
110
+ baseServerState: u?.baseServerState
111
+ }, b = Oe.serialize(A);
109
112
  window.localStorage.setItem(
110
- A,
111
- JSON.stringify($.json)
113
+ M,
114
+ JSON.stringify(b.json)
112
115
  );
113
116
  }
114
- }, yt = (t) => {
115
- if (!t) return null;
117
+ }, Se = (e) => {
118
+ if (!e) return null;
116
119
  try {
117
- const s = window.localStorage.getItem(t);
118
- return s ? JSON.parse(s) : null;
119
- } catch (s) {
120
- return console.error("Error loading from localStorage:", s), null;
120
+ const i = window.localStorage.getItem(e);
121
+ return i ? JSON.parse(i) : null;
122
+ } catch (i) {
123
+ return console.error("Error loading from localStorage:", i), null;
121
124
  }
122
- }, Yt = (t, s) => {
123
- const S = o.getState().cogsStateStore[t], { sessionId: g } = Rt(), I = et(s?.localStorage?.key) ? s.localStorage.key(S) : s?.localStorage?.key;
124
- if (I && g) {
125
- const T = yt(
126
- `${g}-${t}-${I}`
125
+ }, xe = (e, i) => {
126
+ const f = t.getState().getShadowValue(e), { sessionId: g } = _e(), h = ee(i?.localStorage?.key) ? i.localStorage.key(f) : i?.localStorage?.key;
127
+ if (h && g) {
128
+ const p = Se(
129
+ `${g}-${e}-${h}`
127
130
  );
128
- if (T && T.lastUpdated > (T.lastSyncedWithServer || 0))
129
- return st(t, T.state), ot(t), !0;
131
+ if (p && p.lastUpdated > (p.lastSyncedWithServer || 0))
132
+ return ie(e), !0;
130
133
  }
131
134
  return !1;
132
- }, jt = (t, s, S, g, I, T) => {
133
- const A = {
134
- initialState: s,
135
- updaterState: It(
136
- t,
137
- g,
138
- I,
139
- T
140
- ),
141
- state: S
142
- };
143
- xt(t, A.initialState), mt(t, A.updaterState), st(t, A.state);
144
- }, ot = (t) => {
145
- const s = o.getState().stateComponents.get(t);
146
- if (!s) return;
147
- const S = /* @__PURE__ */ new Set();
148
- s.components.forEach((g) => {
149
- (g ? Array.isArray(g.reactiveType) ? g.reactiveType : [g.reactiveType || "component"] : null)?.includes("none") || S.add(() => g.forceUpdate());
135
+ }, ie = (e) => {
136
+ const i = t.getState().getShadowMetadata(e, []);
137
+ if (!i) return;
138
+ const f = /* @__PURE__ */ new Set();
139
+ i?.components?.forEach((g) => {
140
+ (g ? Array.isArray(g.reactiveType) ? g.reactiveType : [g.reactiveType || "component"] : null)?.includes("none") || f.add(() => g.forceUpdate());
150
141
  }), queueMicrotask(() => {
151
- S.forEach((g) => g());
142
+ f.forEach((g) => g());
152
143
  });
153
- }, Ie = (t, s) => {
154
- const S = o.getState().stateComponents.get(t);
155
- if (S) {
156
- const g = `${t}////${s}`, I = S.components.get(g);
157
- if ((I ? Array.isArray(I.reactiveType) ? I.reactiveType : [I.reactiveType || "component"] : null)?.includes("none"))
144
+ }, lt = (e, i) => {
145
+ const f = t.getState().getShadowMetadata(e, []);
146
+ if (f) {
147
+ const g = `${e}////${i}`, h = f?.components?.get(g);
148
+ if ((h ? Array.isArray(h.reactiveType) ? h.reactiveType : [h.reactiveType || "component"] : null)?.includes("none"))
158
149
  return;
159
- I && I.forceUpdate();
160
- }
161
- }, Qt = (t, s, S, g) => {
162
- switch (t) {
163
- case "update":
164
- return {
165
- oldValue: L(s, g),
166
- newValue: L(S, g)
167
- };
168
- case "insert":
169
- return {
170
- oldValue: null,
171
- // or undefined
172
- newValue: L(S, g)
173
- };
174
- case "cut":
175
- return {
176
- oldValue: L(s, g),
177
- newValue: null
178
- // or undefined
179
- };
180
- default:
181
- return { oldValue: null, newValue: null };
150
+ h && h.forceUpdate();
182
151
  }
183
152
  };
184
- function Xt(t, {
185
- stateKey: s,
186
- serverSync: S,
187
- localStorage: g,
188
- formElements: I,
189
- reactiveDeps: T,
190
- reactiveType: A,
191
- componentId: v,
192
- initialState: i,
193
- syncUpdate: $,
194
- dependencies: y,
195
- serverState: n
153
+ function we(e, i, f, g) {
154
+ const h = t.getState(), p = h.getShadowMetadata(e, i);
155
+ if (h.setShadowMetadata(e, i, {
156
+ ...p,
157
+ isDirty: !1,
158
+ stateSource: "server",
159
+ lastServerSync: g || Date.now()
160
+ }), Array.isArray(f)) {
161
+ const M = h.getShadowMetadata(e, i);
162
+ M?.arrayKeys && M.arrayKeys.forEach((l, u) => {
163
+ const A = l.split(".").slice(1), b = f[u];
164
+ b !== void 0 && we(
165
+ e,
166
+ A,
167
+ b,
168
+ g
169
+ );
170
+ });
171
+ } else f && typeof f == "object" && f.constructor === Object && Object.keys(f).forEach((M) => {
172
+ const l = [...i, M], u = f[M];
173
+ we(e, l, u, g);
174
+ });
175
+ }
176
+ function Be(e, {
177
+ stateKey: i,
178
+ localStorage: f,
179
+ formElements: g,
180
+ reactiveDeps: h,
181
+ reactiveType: p,
182
+ componentId: M,
183
+ defaultState: l,
184
+ syncUpdate: u,
185
+ dependencies: A,
186
+ serverState: b
196
187
  } = {}) {
197
- const [w, O] = dt({}), { sessionId: p } = Rt();
198
- let K = !s;
199
- const [f] = dt(s ?? kt()), z = o.getState().stateLog[f], c = q(/* @__PURE__ */ new Set()), nt = q(v ?? kt()), R = q(
188
+ const [o, S] = X({}), { sessionId: T } = _e();
189
+ let W = !i;
190
+ const [c] = X(i ?? te()), x = t.getState().stateLog[c], Y = G(/* @__PURE__ */ new Set()), J = G(M ?? te()), U = G(
200
191
  null
201
192
  );
202
- R.current = lt(f) ?? null, at(() => {
203
- if ($ && $.stateKey === f && $.path?.[0]) {
204
- st(f, (e) => ({
205
- ...e,
206
- [$.path[0]]: $.newValue
207
- }));
208
- const r = `${$.stateKey}:${$.path.join(".")}`;
209
- o.getState().setSyncInfo(r, {
210
- timeStamp: $.timeStamp,
211
- userId: $.userId
193
+ U.current = ae(c) ?? null, Q(() => {
194
+ if (u && u.stateKey === c && u.path?.[0]) {
195
+ const n = `${u.stateKey}:${u.path.join(".")}`;
196
+ t.getState().setSyncInfo(n, {
197
+ timeStamp: u.timeStamp,
198
+ userId: u.userId
212
199
  });
213
200
  }
214
- }, [$]), at(() => {
215
- if (i) {
216
- Mt(f, {
217
- initialState: i
201
+ }, [u]);
202
+ const v = ce(
203
+ (n) => {
204
+ const a = n ? { ...ae(c), ...n } : ae(c), d = a?.defaultState || l || e;
205
+ if (a?.serverState?.status === "success" && a?.serverState?.data !== void 0)
206
+ return {
207
+ value: a.serverState.data,
208
+ source: "server",
209
+ timestamp: a.serverState.timestamp || Date.now()
210
+ };
211
+ if (a?.localStorage?.key && T) {
212
+ const m = ee(a.localStorage.key) ? a.localStorage.key(d) : a.localStorage.key, P = Se(
213
+ `${T}-${c}-${m}`
214
+ );
215
+ if (P && P.lastUpdated > (a?.serverState?.timestamp || 0))
216
+ return {
217
+ value: P.state,
218
+ source: "localStorage",
219
+ timestamp: P.lastUpdated
220
+ };
221
+ }
222
+ return {
223
+ value: d || e,
224
+ source: "default",
225
+ timestamp: Date.now()
226
+ };
227
+ },
228
+ [c, l, e, T]
229
+ );
230
+ Q(() => {
231
+ t.getState().setServerStateUpdate(c, b);
232
+ }, [b, c]), Q(() => t.getState().subscribeToPath(c, (r) => {
233
+ if (r?.type === "SERVER_STATE_UPDATE") {
234
+ const a = r.serverState;
235
+ if (a?.status === "success" && a.data !== void 0) {
236
+ he(c, { serverState: a });
237
+ const w = typeof a.merge == "object" ? a.merge : a.merge === !0 ? {} : null, m = t.getState().getShadowValue(c), P = a.data;
238
+ if (w && Array.isArray(m) && Array.isArray(P)) {
239
+ const D = w.key || "id", j = new Set(
240
+ m.map((O) => O[D])
241
+ ), F = P.filter((O) => !j.has(O[D]));
242
+ F.length > 0 && F.forEach((O) => {
243
+ t.getState().insertShadowArrayElement(c, [], O);
244
+ const L = t.getState().getShadowMetadata(c, []);
245
+ if (L?.arrayKeys) {
246
+ const N = L.arrayKeys[L.arrayKeys.length - 1];
247
+ if (N) {
248
+ const B = N.split(".").slice(1);
249
+ t.getState().setShadowMetadata(c, B, {
250
+ isDirty: !1,
251
+ stateSource: "server",
252
+ lastServerSync: a.timestamp || Date.now()
253
+ });
254
+ const V = t.getState().getShadowValue(N);
255
+ V && typeof V == "object" && !Array.isArray(V) && Object.keys(V).forEach((E) => {
256
+ const $ = [...B, E];
257
+ t.getState().setShadowMetadata(c, $, {
258
+ isDirty: !1,
259
+ stateSource: "server",
260
+ lastServerSync: a.timestamp || Date.now()
261
+ });
262
+ });
263
+ }
264
+ }
265
+ });
266
+ } else
267
+ t.getState().initializeShadowState(c, P), we(
268
+ c,
269
+ [],
270
+ P,
271
+ a.timestamp
272
+ );
273
+ const R = t.getState().getShadowMetadata(c, []);
274
+ t.getState().setShadowMetadata(c, [], {
275
+ ...R,
276
+ stateSource: "server",
277
+ lastServerSync: a.timestamp || Date.now(),
278
+ isDirty: !1
279
+ });
280
+ }
281
+ }
282
+ }), [c, v]), Q(() => {
283
+ const n = t.getState().getShadowMetadata(c, []);
284
+ if (n && n.stateSource)
285
+ return;
286
+ const r = ae(c);
287
+ if (r?.defaultState !== void 0 || l !== void 0) {
288
+ const a = r?.defaultState || l;
289
+ r?.defaultState || he(c, {
290
+ defaultState: a
218
291
  });
219
- const r = R.current, a = r?.serverState?.id !== void 0 && r?.serverState?.status === "success" && r?.serverState?.data, d = o.getState().initialStateGlobal[f];
220
- if (!(d && !X(d, i) || !d) && !a)
221
- return;
222
- let l = null;
223
- const m = et(r?.localStorage?.key) ? r?.localStorage?.key(i) : r?.localStorage?.key;
224
- m && p && (l = yt(`${p}-${f}-${m}`));
225
- let x = i, b = !1;
226
- const F = a ? Date.now() : 0, W = l?.lastUpdated || 0, D = l?.lastSyncedWithServer || 0;
227
- a && F > W ? (x = r.serverState.data, b = !0) : l && W > D && (x = l.state, r?.localStorage?.onChange && r?.localStorage?.onChange(x)), o.getState().initializeShadowState(f, i), jt(
228
- f,
229
- i,
230
- x,
231
- it,
232
- nt.current,
233
- p
234
- ), b && m && p && Ct(x, f, r, p, Date.now()), ot(f), (Array.isArray(A) ? A : [A || "component"]).includes("none") || O({});
292
+ const { value: d, source: w, timestamp: m } = v();
293
+ t.getState().initializeShadowState(c, d), t.getState().setShadowMetadata(c, [], {
294
+ stateSource: w,
295
+ lastServerSync: w === "server" ? m : void 0,
296
+ isDirty: !1,
297
+ baseServerState: w === "server" ? d : void 0
298
+ }), ie(c);
235
299
  }
236
- }, [
237
- i,
238
- n?.status,
239
- n?.data,
240
- ...y || []
241
- ]), pt(() => {
242
- K && Mt(f, {
243
- serverSync: S,
244
- formElements: I,
245
- initialState: i,
246
- localStorage: g,
247
- middleware: R.current?.middleware
300
+ }, [c, ...A || []]), de(() => {
301
+ W && he(c, {
302
+ formElements: g,
303
+ defaultState: l,
304
+ localStorage: f,
305
+ middleware: U.current?.middleware
248
306
  });
249
- const r = `${f}////${nt.current}`, e = o.getState().stateComponents.get(f) || {
250
- components: /* @__PURE__ */ new Map()
251
- };
252
- return e.components.set(r, {
253
- forceUpdate: () => O({}),
307
+ const n = `${c}////${J.current}`, r = t.getState().getShadowMetadata(c, []), a = r?.components || /* @__PURE__ */ new Map();
308
+ return a.set(n, {
309
+ forceUpdate: () => S({}),
310
+ reactiveType: p ?? ["component", "deps"],
254
311
  paths: /* @__PURE__ */ new Set(),
255
- deps: [],
256
- depsFunction: T || void 0,
257
- reactiveType: A ?? ["component", "deps"]
258
- }), o.getState().stateComponents.set(f, e), O({}), () => {
259
- e && (e.components.delete(r), e.components.size === 0 && o.getState().stateComponents.delete(f));
312
+ depsFunction: h || void 0,
313
+ deps: h ? h(t.getState().getShadowValue(c)) : [],
314
+ prevDeps: h ? h(t.getState().getShadowValue(c)) : []
315
+ }), t.getState().setShadowMetadata(c, [], {
316
+ ...r,
317
+ components: a
318
+ }), S({}), () => {
319
+ const d = t.getState().getShadowMetadata(c, []), w = d?.components?.get(n);
320
+ w?.paths && w.paths.forEach((m) => {
321
+ const R = m.split(".").slice(1), D = t.getState().getShadowMetadata(c, R);
322
+ D?.pathComponents && D.pathComponents.size === 0 && (delete D.pathComponents, t.getState().setShadowMetadata(c, R, D));
323
+ }), d?.components && t.getState().setShadowMetadata(c, [], d);
260
324
  };
261
325
  }, []);
262
- const it = (r, e, a, d) => {
263
- if (Array.isArray(e)) {
264
- const l = `${f}-${e.join(".")}`;
265
- c.current.add(l);
326
+ const K = G(null), oe = (n, r, a, d) => {
327
+ const w = [c, ...r].join(".");
328
+ if (Array.isArray(r)) {
329
+ const V = `${c}-${r.join(".")}`;
330
+ Y.current.add(V);
266
331
  }
267
- const u = o.getState();
268
- st(f, (l) => {
269
- const m = et(r) ? r(l) : r, x = `${f}-${e.join(".")}`;
270
- if (x) {
271
- let P = !1, h = u.signalDomElements.get(x);
272
- if ((!h || h.size === 0) && (a.updateType === "insert" || a.updateType === "cut")) {
273
- const C = e.slice(0, -1), V = L(m, C);
274
- if (Array.isArray(V)) {
275
- P = !0;
276
- const E = `${f}-${C.join(".")}`;
277
- h = u.signalDomElements.get(E);
332
+ const m = t.getState(), P = m.getShadowMetadata(c, r), R = m.getShadowValue(w), D = a.updateType === "insert" && ee(n) ? n({ state: R, uuid: te() }) : ee(n) ? n(R) : n, F = {
333
+ timeStamp: Date.now(),
334
+ stateKey: c,
335
+ path: r,
336
+ updateType: a.updateType,
337
+ status: "new",
338
+ oldValue: R,
339
+ newValue: D
340
+ };
341
+ switch (a.updateType) {
342
+ case "insert": {
343
+ m.insertShadowArrayElement(c, r, F.newValue), m.markAsDirty(c, r, { bubble: !0 });
344
+ const V = m.getShadowMetadata(c, r);
345
+ if (V?.arrayKeys) {
346
+ const E = V.arrayKeys[V.arrayKeys.length - 1];
347
+ if (E) {
348
+ const $ = E.split(".").slice(1);
349
+ m.markAsDirty(c, $, { bubble: !1 });
278
350
  }
279
351
  }
280
- if (h) {
281
- const C = P ? L(m, e.slice(0, -1)) : L(m, e);
282
- h.forEach(({ parentId: V, position: E, effect: M }) => {
283
- const Z = document.querySelector(
284
- `[data-parent-id="${V}"]`
285
- );
286
- if (Z) {
287
- const G = Array.from(Z.childNodes);
288
- if (G[E]) {
289
- const U = M ? new Function("state", `return (${M})(state)`)(C) : C;
290
- G[E].textContent = String(U);
352
+ break;
353
+ }
354
+ case "cut": {
355
+ const V = r.slice(0, -1);
356
+ m.removeShadowArrayElement(c, r), m.markAsDirty(c, V, { bubble: !0 });
357
+ break;
358
+ }
359
+ case "update": {
360
+ m.updateShadowAtPath(c, r, F.newValue), m.markAsDirty(c, r, { bubble: !0 });
361
+ break;
362
+ }
363
+ }
364
+ if (console.log("sdadasdasd", K.current, F), K.current && K.current.connected && K.current.updateState({ operation: F }), P?.signals && P.signals.length > 0) {
365
+ const V = a.updateType === "cut" ? null : D;
366
+ P.signals.forEach(({ parentId: E, position: $, effect: I }) => {
367
+ const y = document.querySelector(`[data-parent-id="${E}"]`);
368
+ if (y) {
369
+ const k = Array.from(y.childNodes);
370
+ if (k[$]) {
371
+ let C = V;
372
+ if (I && V !== null)
373
+ try {
374
+ C = new Function(
375
+ "state",
376
+ `return (${I})(state)`
377
+ )(V);
378
+ } catch (_) {
379
+ console.error("Error evaluating effect function:", _);
291
380
  }
381
+ C != null && typeof C == "object" && (C = JSON.stringify(C)), k[$].textContent = String(C ?? "");
382
+ }
383
+ }
384
+ });
385
+ }
386
+ if (a.updateType === "insert" && P?.mapWrappers && P.mapWrappers.length > 0) {
387
+ const V = m.getShadowMetadata(c, r)?.arrayKeys || [], E = V[V.length - 1], $ = m.getShadowValue(E), I = m.getShadowValue(
388
+ [c, ...r].join(".")
389
+ );
390
+ if (!E || $ === void 0) return;
391
+ P.mapWrappers.forEach((y) => {
392
+ let k = !0, C = -1;
393
+ if (y.meta?.transforms && y.meta.transforms.length > 0) {
394
+ for (const _ of y.meta.transforms)
395
+ if (_.type === "filter" && !_.fn($, -1)) {
396
+ k = !1;
397
+ break;
292
398
  }
399
+ if (k) {
400
+ const _ = Ie(
401
+ c,
402
+ r,
403
+ y.meta.transforms
404
+ ), q = y.meta.transforms.find(
405
+ (H) => H.type === "sort"
406
+ );
407
+ if (q) {
408
+ const H = _.map((z) => ({
409
+ key: z,
410
+ value: m.getShadowValue(z)
411
+ }));
412
+ H.push({ key: E, value: $ }), H.sort((z, Z) => q.fn(z.value, Z.value)), C = H.findIndex(
413
+ (z) => z.key === E
414
+ );
415
+ } else
416
+ C = _.length;
417
+ }
418
+ } else
419
+ k = !0, C = V.length - 1;
420
+ if (k && y.containerRef && y.containerRef.isConnected) {
421
+ const _ = document.createElement("div");
422
+ _.setAttribute("data-item-path", E);
423
+ const q = Array.from(y.containerRef.children);
424
+ C >= 0 && C < q.length ? y.containerRef.insertBefore(
425
+ _,
426
+ q[C]
427
+ ) : y.containerRef.appendChild(_);
428
+ const H = Ce(_), z = te(), Z = E.split(".").slice(1), ue = y.rebuildStateShape({
429
+ path: y.path,
430
+ currentState: I,
431
+ componentId: y.componentId,
432
+ meta: y.meta
293
433
  });
434
+ H.render(
435
+ le(Me, {
436
+ stateKey: c,
437
+ itemComponentId: z,
438
+ itemPath: Z,
439
+ localIndex: C,
440
+ arraySetter: ue,
441
+ rebuildStateShape: y.rebuildStateShape,
442
+ renderFn: y.mapFn
443
+ })
444
+ );
294
445
  }
295
- }
296
- a.updateType === "update" && (d || R.current?.validation?.key) && e && tt(
297
- (d || R.current?.validation?.key) + "." + e.join(".")
298
- );
299
- const b = e.slice(0, e.length - 1);
300
- a.updateType === "cut" && R.current?.validation?.key && tt(
301
- R.current?.validation?.key + "." + b.join(".")
302
- ), a.updateType === "insert" && R.current?.validation?.key && qt(
303
- R.current?.validation?.key + "." + b.join(".")
304
- ).filter((h) => {
305
- let C = h?.split(".").length;
306
- const V = "";
307
- if (h == b.join(".") && C == b.length - 1) {
308
- let E = h + "." + b;
309
- tt(h), Tt(E, V);
446
+ });
447
+ }
448
+ if (a.updateType === "cut") {
449
+ const V = r.slice(0, -1), E = m.getShadowMetadata(c, V);
450
+ E?.mapWrappers && E.mapWrappers.length > 0 && E.mapWrappers.forEach(($) => {
451
+ if ($.containerRef && $.containerRef.isConnected) {
452
+ const I = $.containerRef.querySelector(
453
+ `[data-item-path="${w}"]`
454
+ );
455
+ I && I.remove();
310
456
  }
311
457
  });
312
- const F = u.stateComponents.get(f);
313
- if (F) {
314
- const P = Pt(l, m), h = new Set(P), C = a.updateType === "update" ? e.join(".") : e.slice(0, -1).join(".") || "";
315
- for (const [
316
- V,
317
- E
318
- ] of F.components.entries()) {
319
- let M = !1;
320
- const Z = Array.isArray(E.reactiveType) ? E.reactiveType : [E.reactiveType || "component"];
321
- if (!Z.includes("none")) {
322
- if (Z.includes("all")) {
323
- E.forceUpdate();
324
- continue;
325
- }
326
- if (Z.includes("component") && ((E.paths.has(C) || E.paths.has("")) && (M = !0), !M))
327
- for (const G of h) {
328
- let U = G;
329
- for (; ; ) {
330
- if (E.paths.has(U)) {
331
- M = !0;
332
- break;
333
- }
334
- const k = U.lastIndexOf(".");
335
- if (k !== -1) {
336
- const N = U.substring(
337
- 0,
338
- k
339
- );
340
- if (!isNaN(
341
- Number(U.substring(k + 1))
342
- ) && E.paths.has(N)) {
343
- M = !0;
344
- break;
345
- }
346
- U = N;
347
- } else
348
- U = "";
349
- if (U === "")
350
- break;
458
+ }
459
+ a.updateType === "update" && (d || U.current?.validation?.key) && r && ne(
460
+ (d || U.current?.validation?.key) + "." + r.join(".")
461
+ );
462
+ const O = r.slice(0, r.length - 1);
463
+ a.updateType === "cut" && U.current?.validation?.key && ne(
464
+ U.current?.validation?.key + "." + O.join(".")
465
+ ), a.updateType === "insert" && U.current?.validation?.key && Ne(
466
+ U.current?.validation?.key + "." + O.join(".")
467
+ ).filter((E) => {
468
+ let $ = E?.split(".").length;
469
+ const I = "";
470
+ if (E == O.join(".") && $ == O.length - 1) {
471
+ let y = E + "." + O;
472
+ ne(E), ve(y, I);
473
+ }
474
+ });
475
+ const L = m.getShadowValue(c), N = m.getShadowMetadata(c, []), B = /* @__PURE__ */ new Set();
476
+ if (!N?.components)
477
+ return L;
478
+ if (a.updateType === "update")
479
+ P?.pathComponents && P.pathComponents.forEach((V) => {
480
+ if (B.has(V))
481
+ return;
482
+ const E = N.components?.get(V);
483
+ E && ((Array.isArray(E.reactiveType) ? E.reactiveType : [E.reactiveType || "component"]).includes("none") || (E.forceUpdate(), B.add(V)));
484
+ }), D && typeof D == "object" && !Te(D) && R && typeof R == "object" && !Te(R) && Pe(D, R).forEach((E) => {
485
+ const $ = E.split("."), I = [...r, ...$], y = m.getShadowMetadata(c, I);
486
+ y?.pathComponents && y.pathComponents.forEach((k) => {
487
+ if (B.has(k))
488
+ return;
489
+ const C = N.components?.get(k);
490
+ C && ((Array.isArray(C.reactiveType) ? C.reactiveType : [C.reactiveType || "component"]).includes("none") || (C.forceUpdate(), B.add(k)));
491
+ });
492
+ });
493
+ else if (a.updateType === "insert" || a.updateType === "cut") {
494
+ const V = a.updateType === "insert" ? r : r.slice(0, -1), E = m.getShadowMetadata(c, V);
495
+ if (E?.signals && E.signals.length > 0) {
496
+ const $ = [c, ...V].join("."), I = m.getShadowValue($);
497
+ E.signals.forEach(({ parentId: y, position: k, effect: C }) => {
498
+ const _ = document.querySelector(
499
+ `[data-parent-id="${y}"]`
500
+ );
501
+ if (_) {
502
+ const q = Array.from(_.childNodes);
503
+ if (q[k]) {
504
+ let H = I;
505
+ if (C)
506
+ try {
507
+ H = new Function(
508
+ "state",
509
+ `return (${C})(state)`
510
+ )(I);
511
+ } catch (z) {
512
+ console.error("Error evaluating effect function:", z), H = I;
351
513
  }
352
- if (M) break;
353
- }
354
- if (!M && Z.includes("deps") && E.depsFunction) {
355
- const G = E.depsFunction(m);
356
- let U = !1;
357
- typeof G == "boolean" ? G && (U = !0) : X(E.deps, G) || (E.deps = G, U = !0), U && (M = !0);
514
+ H != null && typeof H == "object" && (H = JSON.stringify(H)), q[k].textContent = String(H ?? "");
358
515
  }
359
- M && E.forceUpdate();
360
516
  }
361
- }
517
+ });
362
518
  }
363
- const W = Date.now();
364
- let { oldValue: D, newValue: B } = Qt(
365
- a.updateType,
366
- l,
367
- m,
368
- e
369
- );
370
- const ct = {
371
- timeStamp: W,
372
- stateKey: f,
373
- path: e,
374
- updateType: a.updateType,
375
- status: "new",
376
- oldValue: D,
377
- newValue: B
378
- };
379
- switch (a.updateType) {
380
- case "insert": {
381
- const P = e.slice(0, -1), C = e[e.length - 1].split(":")[1];
382
- B = L(m, P).find((E) => E.id == C), D = null, u.insertShadowArrayElement(f, P, B);
383
- break;
384
- }
385
- case "cut": {
386
- D = L(l, e), B = null, u.removeShadowArrayElement(f, e);
387
- break;
388
- }
389
- case "update": {
390
- D = L(l, e), B = L(m, e);
391
- const P = e.map((h, C) => {
392
- const V = e.slice(0, C + 1), E = L(m, V);
393
- return E?.id ? `id:${E.id}` : h;
394
- });
395
- u.updateShadowAtPath(f, P, B);
396
- break;
519
+ E?.pathComponents && E.pathComponents.forEach(($) => {
520
+ if (!B.has($)) {
521
+ const I = N.components?.get($);
522
+ I && (I.forceUpdate(), B.add($));
397
523
  }
524
+ });
525
+ }
526
+ return N.components.forEach((V, E) => {
527
+ if (B.has(E))
528
+ return;
529
+ const $ = Array.isArray(V.reactiveType) ? V.reactiveType : [V.reactiveType || "component"];
530
+ if ($.includes("all")) {
531
+ V.forceUpdate(), B.add(E);
532
+ return;
398
533
  }
399
- if (Jt(f, (P) => {
400
- const h = [...P ?? [], ct], C = /* @__PURE__ */ new Map();
401
- return h.forEach((V) => {
402
- const E = `${V.stateKey}:${JSON.stringify(V.path)}`, M = C.get(E);
403
- M ? (M.timeStamp = Math.max(M.timeStamp, V.timeStamp), M.newValue = V.newValue, M.oldValue = M.oldValue ?? V.oldValue, M.updateType = V.updateType) : C.set(E, { ...V });
404
- }), Array.from(C.values());
405
- }), Ct(
406
- m,
407
- f,
408
- R.current,
409
- p
410
- ), R.current?.middleware && R.current.middleware({
411
- updateLog: z,
412
- update: ct
413
- }), R.current?.serverSync) {
414
- const P = u.serverState[f], h = R.current?.serverSync;
415
- Zt(f, {
416
- syncKey: typeof h.syncKey == "string" ? h.syncKey : h.syncKey({ state: m }),
417
- rollBackState: P,
418
- actionTimeStamp: Date.now() + (h.debounce ?? 3e3),
419
- status: "waiting"
420
- });
534
+ if ($.includes("deps") && V.depsFunction) {
535
+ const I = m.getShadowValue(c), y = V.depsFunction(I);
536
+ let k = !1;
537
+ y === !0 ? k = !0 : Array.isArray(y) && (se(V.prevDeps, y) || (V.prevDeps = y, k = !0)), k && (V.forceUpdate(), B.add(E));
421
538
  }
422
- return m;
423
- });
539
+ }), B.clear(), We(c, (V) => {
540
+ const E = [...V ?? [], F], $ = /* @__PURE__ */ new Map();
541
+ return E.forEach((I) => {
542
+ const y = `${I.stateKey}:${JSON.stringify(I.path)}`, k = $.get(y);
543
+ k ? (k.timeStamp = Math.max(k.timeStamp, I.timeStamp), k.newValue = I.newValue, k.oldValue = k.oldValue ?? I.oldValue, k.updateType = I.updateType) : $.set(y, { ...I });
544
+ }), Array.from($.values());
545
+ }), He(
546
+ D,
547
+ c,
548
+ U.current,
549
+ T
550
+ ), U.current?.middleware && U.current.middleware({
551
+ updateLog: x,
552
+ update: F
553
+ }), L;
424
554
  };
425
- o.getState().updaterState[f] || (mt(
426
- f,
427
- It(
428
- f,
429
- it,
430
- nt.current,
431
- p
555
+ t.getState().initialStateGlobal[c] || $e(c, e);
556
+ const fe = ge(() => De(
557
+ c,
558
+ oe,
559
+ J.current,
560
+ T
561
+ ), [c, T]), s = U.current?.cogsSync;
562
+ return s && (K.current = s(fe)), fe;
563
+ }
564
+ function qe(e) {
565
+ return !e || e.length === 0 ? "" : e.map(
566
+ (i) => (
567
+ // Safely stringify dependencies. An empty array becomes '[]'.
568
+ `${i.type}${JSON.stringify(i.dependencies || [])}`
432
569
  )
433
- ), o.getState().cogsStateStore[f] || st(f, t), o.getState().initialStateGlobal[f] || xt(f, t));
434
- const vt = Et(() => It(
435
- f,
436
- it,
437
- nt.current,
438
- p
439
- ), [f, p]);
440
- return [Ot(f), vt];
570
+ ).join("");
441
571
  }
442
- function It(t, s, S, g) {
443
- const I = /* @__PURE__ */ new Map();
444
- let T = 0;
445
- const A = (y) => {
446
- const n = y.join(".");
447
- for (const [w] of I)
448
- (w === n || w.startsWith(n + ".")) && I.delete(w);
449
- T++;
450
- }, v = {
451
- removeValidation: (y) => {
452
- y?.validationKey && tt(y.validationKey);
453
- },
454
- revertToInitialState: (y) => {
455
- const n = o.getState().getInitialOptions(t)?.validation;
456
- n?.key && tt(n?.key), y?.validationKey && tt(y.validationKey);
457
- const w = o.getState().initialStateGlobal[t];
458
- o.getState().initializeShadowState(t, w), o.getState().clearSelectedIndexesForState(t), I.clear(), T++;
459
- const O = $(w, []), p = lt(t), K = et(p?.localStorage?.key) ? p?.localStorage?.key(w) : p?.localStorage?.key, f = `${g}-${t}-${K}`;
460
- f && localStorage.removeItem(f), mt(t, O), st(t, w);
461
- const z = o.getState().stateComponents.get(t);
462
- return z && z.components.forEach((c) => {
463
- c.forceUpdate();
464
- }), w;
465
- },
466
- updateInitialState: (y) => {
467
- I.clear(), T++;
468
- const n = It(
469
- t,
470
- s,
471
- S,
472
- g
473
- ), w = o.getState().initialStateGlobal[t], O = lt(t), p = et(O?.localStorage?.key) ? O?.localStorage?.key(w) : O?.localStorage?.key, K = `${g}-${t}-${p}`;
474
- return localStorage.getItem(K) && localStorage.removeItem(K), Ut(() => {
475
- xt(t, y), o.getState().initializeShadowState(t, y), mt(t, n), st(t, y);
476
- const f = o.getState().stateComponents.get(t);
477
- f && f.components.forEach((z) => {
478
- z.forceUpdate();
479
- });
480
- }), {
481
- fetchId: (f) => n.get()[f]
482
- };
483
- },
484
- _initialState: o.getState().initialStateGlobal[t],
485
- _serverState: o.getState().serverState[t],
486
- _isLoading: o.getState().isLoadingGlobal[t],
487
- _isServerSynced: () => {
488
- const y = o.getState().serverState[t];
489
- return !!(y && X(y, Ot(t)));
490
- }
491
- };
492
- function i(y) {
493
- const n = [t, ...y].join(".");
494
- return o.getState().shadowStateStore.get(n)?.arrayKeys || null;
495
- }
496
- function $(y, n = [], w) {
497
- const O = n.map(String).join(".");
498
- I.get(O);
499
- const p = function() {
500
- return o().getNestedState(t, n);
501
- };
502
- Object.keys(v).forEach((z) => {
503
- p[z] = v[z];
572
+ const Ie = (e, i, f) => {
573
+ let g = t.getState().getShadowMetadata(e, i)?.arrayKeys || [];
574
+ if (!f || f.length === 0)
575
+ return g;
576
+ let h = g.map((p) => ({
577
+ key: p,
578
+ value: t.getState().getShadowValue(p)
579
+ }));
580
+ for (const p of f)
581
+ p.type === "filter" ? h = h.filter(
582
+ ({ value: M }, l) => p.fn(M, l)
583
+ ) : p.type === "sort" && h.sort((M, l) => p.fn(M.value, l.value));
584
+ return h.map(({ key: p }) => p);
585
+ }, Ve = (e, i, f) => {
586
+ const g = `${e}////${i}`, p = t.getState().getShadowMetadata(e, [])?.components?.get(g);
587
+ if (!p || p.reactiveType == "none" || !(Array.isArray(p.reactiveType) ? p.reactiveType : [p.reactiveType]).includes("component"))
588
+ return;
589
+ const M = [e, ...f].join(".");
590
+ p.paths.add(M);
591
+ const l = t.getState().getShadowMetadata(e, f) || {}, u = l.pathComponents || /* @__PURE__ */ new Set();
592
+ u.add(g), t.getState().setShadowMetadata(e, f, {
593
+ ...l,
594
+ pathComponents: u
595
+ });
596
+ }, ye = (e, i, f) => {
597
+ const g = t.getState(), h = g.getShadowMetadata(e, []), p = /* @__PURE__ */ new Set();
598
+ h?.components && h.components.forEach((l, u) => {
599
+ (Array.isArray(l.reactiveType) ? l.reactiveType : [l.reactiveType || "component"]).includes("all") && (l.forceUpdate(), p.add(u));
600
+ }), g.getShadowMetadata(e, [...i, "getSelected"])?.pathComponents?.forEach((l) => {
601
+ h?.components?.get(l)?.forceUpdate();
602
+ });
603
+ const M = g.getShadowMetadata(e, i);
604
+ for (let l of M?.arrayKeys || []) {
605
+ const u = l + ".selected", A = g.getShadowMetadata(
606
+ e,
607
+ u.split(".").slice(1)
608
+ );
609
+ l == f && A?.pathComponents?.forEach((b) => {
610
+ h?.components?.get(b)?.forceUpdate();
504
611
  });
505
- const K = {
506
- apply(z, c, nt) {
507
- return o().getNestedState(t, n);
612
+ }
613
+ };
614
+ function De(e, i, f, g) {
615
+ const h = /* @__PURE__ */ new Map();
616
+ let p = 0;
617
+ const M = (b) => {
618
+ const o = b.join(".");
619
+ for (const [S] of h)
620
+ (S === o || S.startsWith(o + ".")) && h.delete(S);
621
+ p++;
622
+ };
623
+ function l({
624
+ currentState: b,
625
+ path: o = [],
626
+ meta: S,
627
+ componentId: T
628
+ }) {
629
+ const W = o.map(String).join("."), c = [e, ...o].join(".");
630
+ b = t.getState().getShadowValue(c, S?.validIds);
631
+ const x = function() {
632
+ return t().getShadowValue(e, o);
633
+ }, Y = {
634
+ apply(U, v, K) {
508
635
  },
509
- get(z, c) {
510
- const nt = /* @__PURE__ */ new Set([
511
- "insert",
512
- "cut",
513
- "cutByValue",
514
- "toggleByValue",
515
- "uniqueInsert",
516
- "update",
517
- "applyJsonPatch",
518
- "setSelected",
519
- "toggleSelected",
520
- "clearSelected",
521
- "sync",
522
- "validateZodSchema",
523
- "revertToInitialState",
524
- "updateInitialState",
525
- "removeValidation",
526
- "setValidation",
527
- "removeStorage",
528
- "middleware",
529
- "_componentId",
530
- "_stateKey",
531
- "getComponents"
532
- ]);
533
- if (c !== "then" && !c.startsWith("$") && c !== "stateMapNoRender" && !nt.has(c)) {
534
- const r = `${t}////${S}`, e = o.getState().stateComponents.get(t);
535
- if (e) {
536
- const a = e.components.get(r);
537
- if (a && !a.paths.has("")) {
538
- const d = n.join(".");
539
- let u = !0;
540
- for (const l of a.paths)
541
- if (d.startsWith(l) && (d === l || d[l.length] === ".")) {
542
- u = !1;
543
- break;
544
- }
545
- u && a.paths.add(d);
546
- }
547
- }
548
- }
549
- if (c === "getDifferences")
550
- return () => Pt(
551
- o.getState().cogsStateStore[t],
552
- o.getState().initialStateGlobal[t]
553
- );
554
- if (c === "sync" && n.length === 0)
636
+ get(U, v) {
637
+ if (v === "_rebuildStateShape")
638
+ return l;
639
+ if (Object.getOwnPropertyNames(u).includes(v) && o.length === 0)
640
+ return u[v];
641
+ if (v === "getDifferences")
642
+ return () => {
643
+ const s = t.getState().getShadowMetadata(e, []), n = t.getState().getShadowValue(e);
644
+ let r;
645
+ return s?.stateSource === "server" && s.baseServerState ? r = s.baseServerState : r = t.getState().initialStateGlobal[e], Pe(n, r);
646
+ };
647
+ if (v === "sync" && o.length === 0)
555
648
  return async function() {
556
- const r = o.getState().getInitialOptions(t), e = r?.sync;
557
- if (!e)
558
- return console.error(`No mutation defined for state key "${t}"`), { success: !1, error: "No mutation defined" };
559
- const a = o.getState().getNestedState(t, []), d = r?.validation?.key;
649
+ const s = t.getState().getInitialOptions(e), n = s?.sync;
650
+ if (!n)
651
+ return console.error(`No mutation defined for state key "${e}"`), { success: !1, error: "No mutation defined" };
652
+ const r = t.getState().getShadowValue(e, []), a = s?.validation?.key;
560
653
  try {
561
- const u = await e.action(a);
562
- return u && !u.success && u.errors && d && (o.getState().removeValidationError(d), u.errors.forEach((l) => {
563
- const m = [d, ...l.path].join(".");
564
- o.getState().addValidationError(m, l.message);
565
- }), ot(t)), u?.success && e.onSuccess ? e.onSuccess(u.data) : !u?.success && e.onError && e.onError(u.error), u;
566
- } catch (u) {
567
- return e.onError && e.onError(u), { success: !1, error: u };
654
+ const d = await n.action(r);
655
+ if (d && !d.success && d.errors && a && (t.getState().removeValidationError(a), d.errors.forEach((w) => {
656
+ const m = [a, ...w.path].join(".");
657
+ t.getState().addValidationError(m, w.message);
658
+ }), ie(e)), d?.success) {
659
+ const w = t.getState().getShadowMetadata(e, []);
660
+ t.getState().setShadowMetadata(e, [], {
661
+ ...w,
662
+ isDirty: !1,
663
+ lastServerSync: Date.now(),
664
+ stateSource: "server",
665
+ baseServerState: r
666
+ // Update base server state
667
+ }), n.onSuccess && n.onSuccess(d.data);
668
+ } else !d?.success && n.onError && n.onError(d.error);
669
+ return d;
670
+ } catch (d) {
671
+ return n.onError && n.onError(d), { success: !1, error: d };
568
672
  }
569
673
  };
570
- if (c === "_status") {
571
- const r = o.getState().getNestedState(t, n), e = o.getState().initialStateGlobal[t], a = L(e, n);
572
- return X(r, a) ? "fresh" : "stale";
573
- }
574
- if (c === "getStatus")
575
- return function() {
576
- const r = o().getNestedState(
577
- t,
578
- n
579
- ), e = o.getState().initialStateGlobal[t], a = L(e, n);
580
- return X(r, a) ? "fresh" : "stale";
674
+ if (v === "_status" || v === "getStatus") {
675
+ const s = () => {
676
+ const n = t.getState().getShadowMetadata(e, o), r = t.getState().getShadowValue(c);
677
+ return n?.isDirty === !0 ? "dirty" : n?.isDirty === !1 || n?.stateSource === "server" ? "synced" : n?.stateSource === "localStorage" ? "restored" : n?.stateSource === "default" ? "fresh" : t.getState().getShadowMetadata(e, [])?.stateSource === "server" && !n?.isDirty ? "synced" : r !== void 0 && !n ? "fresh" : "unknown";
581
678
  };
582
- if (c === "removeStorage")
679
+ return v === "_status" ? s() : s;
680
+ }
681
+ if (v === "removeStorage")
583
682
  return () => {
584
- const r = o.getState().initialStateGlobal[t], e = lt(t), a = et(e?.localStorage?.key) ? e.localStorage.key(r) : e?.localStorage?.key, d = `${g}-${t}-${a}`;
585
- d && localStorage.removeItem(d);
683
+ const s = t.getState().initialStateGlobal[e], n = ae(e), r = ee(n?.localStorage?.key) ? n.localStorage.key(s) : n?.localStorage?.key, a = `${g}-${e}-${r}`;
684
+ a && localStorage.removeItem(a);
586
685
  };
587
- if (c === "showValidationErrors")
686
+ if (v === "showValidationErrors")
588
687
  return () => {
589
- const r = o.getState().getInitialOptions(t)?.validation;
590
- if (!r?.key) throw new Error("Validation key not found");
591
- return o.getState().getValidationErrors(r.key + "." + n.join("."));
688
+ const s = t.getState().getInitialOptions(e)?.validation;
689
+ if (!s?.key) throw new Error("Validation key not found");
690
+ return t.getState().getValidationErrors(s.key + "." + o.join("."));
592
691
  };
593
- if (Array.isArray(y)) {
594
- if (c === "getSelected")
692
+ if (Array.isArray(b)) {
693
+ if (v === "getSelected")
595
694
  return () => {
596
- const r = o.getState().getSelectedIndex(t, n.join("."));
597
- if (r === void 0) return;
598
- const e = o.getState().getNestedState(t, n);
599
- if (!e || r >= e.length)
695
+ const s = e + "." + o.join(".");
696
+ Ve(e, T, [
697
+ ...o,
698
+ "getSelected"
699
+ ]);
700
+ const n = t.getState().selectedIndicesMap;
701
+ if (!n || !n.has(s))
600
702
  return;
601
- const a = e[r], d = `id:${a.id}`;
602
- return $(a, [...n, d], w);
603
- };
604
- if (c === "clearSelected")
605
- return () => {
606
- o.getState().clearSelectedIndex({ stateKey: t, path: n });
703
+ const r = n.get(s);
704
+ if (S?.validIds && !S.validIds.includes(r))
705
+ return;
706
+ const a = t.getState().getShadowValue(r);
707
+ if (a)
708
+ return l({
709
+ currentState: a,
710
+ path: r.split(".").slice(1),
711
+ componentId: T
712
+ });
607
713
  };
608
- if (c === "getSelectedIndex")
609
- return () => {
610
- const r = o.getState().getSelectedIndex(t, n.join("."));
611
- if (r === void 0) return -1;
612
- if (w?.validIds) {
613
- const a = (i(n) || [])[r];
614
- return a ? w.validIds.indexOf(a) : -1;
615
- }
616
- return r;
714
+ if (v === "getSelectedIndex")
715
+ return () => t.getState().getSelectedIndex(
716
+ e + "." + o.join("."),
717
+ S?.validIds
718
+ );
719
+ if (v === "clearSelected")
720
+ return ye(e, o), () => {
721
+ t.getState().clearSelectedIndex({
722
+ arrayKey: e + "." + o.join(".")
723
+ });
617
724
  };
618
- if (c === "useVirtualView")
619
- return (r) => {
725
+ if (v === "useVirtualView")
726
+ return (s) => {
620
727
  const {
621
- itemHeight: e = 50,
622
- overscan: a = 6,
623
- stickToBottom: d = !1,
624
- dependencies: u = []
625
- } = r, l = q(null), [m, x] = dt({
728
+ itemHeight: n = 50,
729
+ overscan: r = 6,
730
+ stickToBottom: a = !1,
731
+ scrollStickTolerance: d = 75
732
+ } = s, w = G(null), [m, P] = X({
626
733
  startIndex: 0,
627
734
  endIndex: 10
628
- }), [b, F] = dt(0), W = q(!0), D = q(!1), B = q(0), ct = q(m);
629
- i(n), at(() => o.getState().subscribeToShadowState(t, () => {
630
- F((N) => N + 1);
631
- }), [t]);
632
- const P = o().getNestedState(
633
- t,
634
- n
635
- ), h = P.length, { totalHeight: C, positions: V } = Et(() => {
636
- const N = o.getState().getShadowMetadata(t, n)?.arrayKeys || [];
637
- let _ = 0;
638
- const H = [];
639
- for (let j = 0; j < h; j++) {
640
- H[j] = _;
641
- const Y = N[j];
642
- let J = e;
643
- Y && (J = o.getState().getShadowMetadata(t, [...n, Y])?.virtualizer?.itemHeight || e), _ += J;
644
- }
645
- return { totalHeight: _, positions: H };
646
- }, [
647
- h,
648
- t,
649
- n.join("."),
650
- e,
651
- b
652
- ]), E = Et(() => {
653
- const k = Math.max(0, m.startIndex), N = Math.min(h, m.endIndex), H = o.getState().getShadowMetadata(t, n)?.arrayKeys || [], j = P.slice(k, N), Y = H.slice(k, N);
654
- return $(j, n, {
655
- ...w,
656
- validIds: Y
735
+ }), [R, D] = X({}), j = G(!0), F = G({
736
+ isUserScrolling: !1,
737
+ lastScrollTop: 0,
738
+ scrollUpCount: 0,
739
+ isNearBottom: !0
740
+ }), O = G(
741
+ /* @__PURE__ */ new Map()
742
+ );
743
+ de(() => {
744
+ if (!a || !w.current || F.current.isUserScrolling)
745
+ return;
746
+ const I = w.current;
747
+ I.scrollTo({
748
+ top: I.scrollHeight,
749
+ behavior: j.current ? "instant" : "smooth"
657
750
  });
658
- }, [m.startIndex, m.endIndex, P, h]), M = St(() => {
659
- const k = o.getState().getShadowMetadata(t, n);
660
- if (!k || k && k?.arrayKeys?.length === 0)
661
- return !1;
662
- const N = h - 1, _ = [...n, k.arrayKeys[N]];
663
- if (N >= 0) {
664
- const H = o.getState().getShadowMetadata(t, _);
665
- if (H?.virtualizer?.domRef) {
666
- const j = H.virtualizer.domRef;
667
- if (j && j.scrollIntoView)
668
- return j.scrollIntoView({
669
- behavior: "auto",
670
- block: "end",
671
- inline: "nearest"
672
- }), !0;
751
+ }, [R, a]);
752
+ const L = t.getState().getShadowMetadata(e, o)?.arrayKeys || [], { totalHeight: N, itemOffsets: B } = ge(() => {
753
+ let I = 0;
754
+ const y = /* @__PURE__ */ new Map();
755
+ return (t.getState().getShadowMetadata(e, o)?.arrayKeys || []).forEach((C) => {
756
+ const _ = C.split(".").slice(1), q = t.getState().getShadowMetadata(e, _)?.virtualizer?.itemHeight || n;
757
+ y.set(C, {
758
+ height: q,
759
+ offset: I
760
+ }), I += q;
761
+ }), O.current = y, { totalHeight: I, itemOffsets: y };
762
+ }, [L.length, n]);
763
+ de(() => {
764
+ if (a && L.length > 0 && w.current && !F.current.isUserScrolling && j.current) {
765
+ const I = w.current, y = () => {
766
+ if (I.clientHeight > 0) {
767
+ const k = Math.ceil(
768
+ I.clientHeight / n
769
+ ), C = L.length - 1, _ = Math.max(
770
+ 0,
771
+ C - k - r
772
+ );
773
+ P({ startIndex: _, endIndex: C }), requestAnimationFrame(() => {
774
+ E("instant"), j.current = !1;
775
+ });
776
+ } else
777
+ requestAnimationFrame(y);
778
+ };
779
+ y();
780
+ }
781
+ }, [L.length, a, n, r]);
782
+ const V = ce(() => {
783
+ const I = w.current;
784
+ if (!I) return;
785
+ const y = I.scrollTop, { scrollHeight: k, clientHeight: C } = I, _ = F.current, q = k - (y + C), H = _.isNearBottom;
786
+ _.isNearBottom = q <= d, y < _.lastScrollTop ? (_.scrollUpCount++, _.scrollUpCount > 3 && H && (_.isUserScrolling = !0, console.log("User scrolled away from bottom"))) : _.isNearBottom && (_.isUserScrolling = !1, _.scrollUpCount = 0), _.lastScrollTop = y;
787
+ let z = 0;
788
+ for (let Z = 0; Z < L.length; Z++) {
789
+ const ue = L[Z], me = O.current.get(ue);
790
+ if (me && me.offset + me.height > y) {
791
+ z = Z;
792
+ break;
673
793
  }
674
794
  }
675
- return !1;
676
- }, [t, n, h]);
677
- at(() => {
678
- if (!d || h === 0) return;
679
- const k = h > B.current, N = B.current === 0 && h > 0;
680
- if ((k || N) && W.current && !D.current) {
681
- const _ = Math.ceil(
682
- (l.current?.clientHeight || 0) / e
683
- ), H = {
684
- startIndex: Math.max(
685
- 0,
686
- h - _ - a
687
- ),
688
- endIndex: h
689
- };
690
- x(H);
691
- const j = setTimeout(() => {
692
- G(h - 1, "smooth");
693
- }, 50);
694
- return () => clearTimeout(j);
795
+ if (z !== m.startIndex) {
796
+ const Z = Math.ceil(C / n);
797
+ P({
798
+ startIndex: Math.max(0, z - r),
799
+ endIndex: Math.min(
800
+ L.length - 1,
801
+ z + Z + r
802
+ )
803
+ });
695
804
  }
696
- B.current = h;
697
- }, [h, e, a]), at(() => {
698
- const k = l.current;
699
- if (!k) return;
700
- const N = () => {
701
- const { scrollTop: _, scrollHeight: H, clientHeight: j } = k, Y = H - _ - j;
702
- W.current = Y < 5, Y > 100 && (D.current = !0), Y < 5 && (D.current = !1);
703
- let J = 0;
704
- for (let Q = 0; Q < V.length; Q++)
705
- if (V[Q] > _ - e * a) {
706
- J = Math.max(0, Q - 1);
707
- break;
708
- }
709
- let rt = J;
710
- const Vt = _ + j;
711
- for (let Q = J; Q < V.length && !(V[Q] > Vt + e * a); Q++)
712
- rt = Q;
713
- const ht = Math.max(0, J), wt = Math.min(
714
- h,
715
- rt + 1 + a
716
- );
717
- (ht !== ct.current.startIndex || wt !== ct.current.endIndex) && (ct.current = {
718
- startIndex: ht,
719
- endIndex: wt
720
- }, x({
721
- startIndex: ht,
722
- endIndex: wt
723
- }));
805
+ }, [
806
+ L.length,
807
+ m.startIndex,
808
+ n,
809
+ r,
810
+ d
811
+ ]);
812
+ Q(() => {
813
+ const I = w.current;
814
+ if (!(!I || !a))
815
+ return I.addEventListener("scroll", V, {
816
+ passive: !0
817
+ }), () => {
818
+ I.removeEventListener("scroll", V);
819
+ };
820
+ }, [V, a]);
821
+ const E = ce(
822
+ (I = "smooth") => {
823
+ const y = w.current;
824
+ if (!y) return;
825
+ F.current.isUserScrolling = !1, F.current.isNearBottom = !0, F.current.scrollUpCount = 0;
826
+ const k = () => {
827
+ const C = (_ = 0) => {
828
+ if (_ > 5) return;
829
+ const q = y.scrollHeight, H = y.scrollTop, z = y.clientHeight;
830
+ H + z >= q - 1 || (y.scrollTo({
831
+ top: q,
832
+ behavior: I
833
+ }), setTimeout(() => {
834
+ const Z = y.scrollHeight, ue = y.scrollTop;
835
+ (Z !== q || ue + z < Z - 1) && C(_ + 1);
836
+ }, 50));
837
+ };
838
+ C();
839
+ };
840
+ "requestIdleCallback" in window ? requestIdleCallback(k, { timeout: 100 }) : requestAnimationFrame(() => {
841
+ requestAnimationFrame(k);
842
+ });
843
+ },
844
+ []
845
+ );
846
+ return Q(() => {
847
+ if (!a || !w.current) return;
848
+ const I = w.current, y = F.current;
849
+ let k;
850
+ const C = () => {
851
+ clearTimeout(k), k = setTimeout(() => {
852
+ !y.isUserScrolling && y.isNearBottom && E(
853
+ j.current ? "instant" : "smooth"
854
+ );
855
+ }, 100);
856
+ }, _ = new MutationObserver(() => {
857
+ y.isUserScrolling || C();
858
+ });
859
+ _.observe(I, {
860
+ childList: !0,
861
+ subtree: !0,
862
+ attributes: !0,
863
+ attributeFilter: ["style", "class"]
864
+ // More specific than just 'height'
865
+ });
866
+ const q = (H) => {
867
+ H.target instanceof HTMLImageElement && !y.isUserScrolling && C();
724
868
  };
725
- if (k.addEventListener("scroll", N, {
726
- passive: !0
727
- }), d && h > 0 && !D.current) {
728
- const { scrollTop: _ } = k;
729
- _ === 0 && (k.scrollTop = k.scrollHeight, W.current = !0);
730
- }
731
- return N(), () => {
732
- k.removeEventListener("scroll", N);
869
+ return I.addEventListener("load", q, !0), j.current ? setTimeout(() => {
870
+ E("instant");
871
+ }, 0) : C(), () => {
872
+ clearTimeout(k), _.disconnect(), I.removeEventListener("load", q, !0);
733
873
  };
734
- }, [V, h, e, a, d]);
735
- const Z = St(() => {
736
- W.current = !0, D.current = !1, !M() && l.current && (l.current.scrollTop = l.current.scrollHeight);
737
- }, [M]), G = St(
738
- (k, N = "smooth") => {
739
- const _ = l.current;
740
- if (!_) return;
741
- if (k === h - 1) {
742
- _.scrollTo({
743
- top: _.scrollHeight,
744
- behavior: N
745
- });
746
- return;
747
- }
748
- const J = (o.getState().getShadowMetadata(t, n)?.arrayKeys || [])[k];
749
- let rt;
750
- J && (rt = o.getState().getShadowMetadata(t, [...n, J])?.virtualizer?.domRef), rt ? rt.scrollIntoView({
751
- behavior: N,
752
- block: "center"
753
- }) : V[k] !== void 0 && _.scrollTo({
754
- top: V[k],
755
- behavior: N
874
+ }, [a, L.length, E]), {
875
+ virtualState: ge(() => {
876
+ const I = t.getState(), y = I.getShadowValue(
877
+ [e, ...o].join(".")
878
+ ), k = I.getShadowMetadata(e, o)?.arrayKeys || [], C = y.slice(
879
+ m.startIndex,
880
+ m.endIndex + 1
881
+ ), _ = k.slice(
882
+ m.startIndex,
883
+ m.endIndex + 1
884
+ );
885
+ return l({
886
+ currentState: C,
887
+ path: o,
888
+ componentId: T,
889
+ meta: { ...S, validIds: _ }
756
890
  });
757
- },
758
- [V, t, n, h]
759
- // Add totalCount to the dependencies
760
- ), U = {
761
- outer: {
762
- ref: l,
763
- style: { overflowY: "auto", height: "100%" }
764
- },
765
- inner: {
766
- style: {
767
- height: `${C}px`,
768
- position: "relative"
891
+ }, [m.startIndex, m.endIndex, L.length]),
892
+ virtualizerProps: {
893
+ outer: {
894
+ ref: w,
895
+ style: {
896
+ overflowY: "auto",
897
+ height: "100%",
898
+ position: "relative"
899
+ }
900
+ },
901
+ inner: {
902
+ style: {
903
+ height: `${N}px`,
904
+ position: "relative"
905
+ }
906
+ },
907
+ list: {
908
+ style: {
909
+ transform: `translateY(${O.current.get(
910
+ L[m.startIndex]
911
+ )?.offset || 0}px)`
912
+ }
769
913
  }
770
914
  },
771
- list: {
772
- style: {
773
- transform: `translateY(${V[m.startIndex] || 0}px)`
915
+ scrollToBottom: E,
916
+ scrollToIndex: (I, y = "smooth") => {
917
+ if (w.current && L[I]) {
918
+ const k = O.current.get(L[I])?.offset || 0;
919
+ w.current.scrollTo({ top: k, behavior: y });
774
920
  }
775
921
  }
776
922
  };
777
- return {
778
- virtualState: E,
779
- virtualizerProps: U,
780
- scrollToBottom: Z,
781
- scrollToIndex: G
782
- };
783
923
  };
784
- if (c === "stateMap")
785
- return (r) => {
786
- const e = y, a = w?.validIds || i(n) || [], d = $(y, n, w);
787
- return e.map((u, l) => {
788
- const m = a[l] || `id:${u.id}`, x = [...n, m], b = $(u, x, w);
789
- return r(
790
- u,
791
- b,
792
- l,
793
- y,
794
- d
795
- );
924
+ if (v === "stateMap")
925
+ return (s) => {
926
+ const [n, r] = X(
927
+ S?.validIds ?? t.getState().getShadowMetadata(e, o)?.arrayKeys
928
+ ), a = t.getState().getShadowValue(c, S?.validIds);
929
+ if (!n)
930
+ throw new Error("No array keys found for mapping");
931
+ const d = l({
932
+ currentState: a,
933
+ path: o,
934
+ componentId: T,
935
+ meta: S
796
936
  });
797
- };
798
- if (c === "stateMapNoRender")
799
- return (r) => {
800
- const e = y, a = w?.validIds || i(n) || [], d = $(y, n, w);
801
- return e.map((u, l) => {
802
- const m = a[l] || `id:${u.id}`, x = [...n, m], b = $(u, x, w);
803
- return r(
804
- u,
805
- b,
806
- l,
807
- y,
937
+ return a.map((w, m) => {
938
+ const P = n[m]?.split(".").slice(1), R = l({
939
+ currentState: w,
940
+ path: P,
941
+ componentId: T,
942
+ meta: S
943
+ });
944
+ return s(
945
+ R,
946
+ m,
808
947
  d
809
948
  );
810
949
  });
811
950
  };
812
- if (c === "$stateMap")
813
- return (r) => gt(Kt, {
814
- proxy: { _stateKey: t, _path: n, _mapFn: r },
815
- rebuildStateShape: $
951
+ if (v === "$stateMap")
952
+ return (s) => le(Ge, {
953
+ proxy: {
954
+ _stateKey: e,
955
+ _path: o,
956
+ _mapFn: s,
957
+ _meta: S
958
+ },
959
+ rebuildStateShape: l
816
960
  });
817
- if (c === "stateList")
818
- return (r) => {
819
- const e = y;
820
- if (!Array.isArray(e)) return null;
821
- const a = w?.validIds || i(n) || [], d = i(n) || [], u = $(
822
- e,
823
- n,
824
- w
961
+ if (v === "stateFind")
962
+ return (s) => {
963
+ const n = S?.validIds ?? t.getState().getShadowMetadata(e, o)?.arrayKeys;
964
+ if (n)
965
+ for (let r = 0; r < n.length; r++) {
966
+ const a = n[r];
967
+ if (!a) continue;
968
+ const d = t.getState().getShadowValue(a);
969
+ if (s(d, r)) {
970
+ const w = a.split(".").slice(1);
971
+ return l({
972
+ currentState: d,
973
+ path: w,
974
+ componentId: T,
975
+ meta: S
976
+ // Pass along meta for potential further chaining
977
+ });
978
+ }
979
+ }
980
+ };
981
+ if (v === "stateFilter")
982
+ return (s) => {
983
+ const n = S?.validIds ?? t.getState().getShadowMetadata(e, o)?.arrayKeys;
984
+ if (!n)
985
+ throw new Error("No array keys found for filtering.");
986
+ const r = [], a = b.filter(
987
+ (d, w) => s(d, w) ? (r.push(n[w]), !0) : !1
825
988
  );
826
- return e.map((l, m) => {
827
- const x = a[m] || `id:${l.id}`, b = d.indexOf(x), F = [...n, x], W = $(l, F, w), D = `${S}-${n.join(".")}-${x}`;
828
- return gt(ee, {
829
- key: x,
830
- stateKey: t,
831
- itemComponentId: D,
832
- itemPath: F,
833
- children: r(
834
- l,
835
- W,
836
- { localIndex: m, originalIndex: b },
837
- e,
838
- u
839
- )
840
- });
989
+ return l({
990
+ currentState: a,
991
+ path: o,
992
+ componentId: T,
993
+ meta: {
994
+ validIds: r,
995
+ transforms: [
996
+ ...S?.transforms || [],
997
+ {
998
+ type: "filter",
999
+ fn: s
1000
+ }
1001
+ ]
1002
+ }
841
1003
  });
842
1004
  };
843
- if (c === "stateFlattenOn")
844
- return (r) => {
845
- const e = y;
846
- I.clear(), T++;
847
- const a = e.flatMap(
848
- (d) => d[r] ?? []
849
- );
850
- return $(
851
- a,
852
- [...n, "[*]", r],
853
- w
1005
+ if (v === "stateSort")
1006
+ return (s) => {
1007
+ const n = S?.validIds ?? t.getState().getShadowMetadata(e, o)?.arrayKeys;
1008
+ if (!n)
1009
+ throw new Error("No array keys found for sorting");
1010
+ const r = b.map((a, d) => ({
1011
+ item: a,
1012
+ key: n[d]
1013
+ }));
1014
+ return r.sort((a, d) => s(a.item, d.item)).filter(Boolean), l({
1015
+ currentState: r.map((a) => a.item),
1016
+ path: o,
1017
+ componentId: T,
1018
+ meta: {
1019
+ validIds: r.map((a) => a.key),
1020
+ transforms: [
1021
+ ...S?.transforms || [],
1022
+ { type: "sort", fn: s }
1023
+ ]
1024
+ }
1025
+ });
1026
+ };
1027
+ if (v === "stream")
1028
+ return function(s = {}) {
1029
+ const {
1030
+ bufferSize: n = 100,
1031
+ flushInterval: r = 100,
1032
+ bufferStrategy: a = "accumulate",
1033
+ store: d,
1034
+ onFlush: w
1035
+ } = s;
1036
+ let m = [], P = !1, R = null;
1037
+ const D = (N) => {
1038
+ if (!P) {
1039
+ if (a === "sliding" && m.length >= n)
1040
+ m.shift();
1041
+ else if (a === "dropping" && m.length >= n)
1042
+ return;
1043
+ m.push(N), m.length >= n && j();
1044
+ }
1045
+ }, j = () => {
1046
+ if (m.length === 0) return;
1047
+ const N = [...m];
1048
+ if (m = [], d) {
1049
+ const B = d(N);
1050
+ B !== void 0 && (Array.isArray(B) ? B : [B]).forEach((E) => {
1051
+ i(E, o, {
1052
+ updateType: "insert"
1053
+ });
1054
+ });
1055
+ } else
1056
+ N.forEach((B) => {
1057
+ i(B, o, {
1058
+ updateType: "insert"
1059
+ });
1060
+ });
1061
+ w?.(N);
1062
+ };
1063
+ r > 0 && (R = setInterval(j, r));
1064
+ const F = te(), O = t.getState().getShadowMetadata(e, o) || {}, L = O.streams || /* @__PURE__ */ new Map();
1065
+ return L.set(F, { buffer: m, flushTimer: R }), t.getState().setShadowMetadata(e, o, {
1066
+ ...O,
1067
+ streams: L
1068
+ }), {
1069
+ write: (N) => D(N),
1070
+ writeMany: (N) => N.forEach(D),
1071
+ flush: () => j(),
1072
+ pause: () => {
1073
+ P = !0;
1074
+ },
1075
+ resume: () => {
1076
+ P = !1, m.length > 0 && j();
1077
+ },
1078
+ close: () => {
1079
+ j(), R && clearInterval(R);
1080
+ const N = t.getState().getShadowMetadata(e, o);
1081
+ N?.streams && N.streams.delete(F);
1082
+ }
1083
+ };
1084
+ };
1085
+ if (v === "stateList")
1086
+ return (s) => /* @__PURE__ */ re(() => {
1087
+ const r = G(/* @__PURE__ */ new Map()), a = S?.transforms && S.transforms.length > 0 ? `${T}-${qe(S.transforms)}` : `${T}-base`, [d, w] = X({}), { validIds: m, arrayValues: P } = ge(() => {
1088
+ const D = t.getState().getShadowMetadata(e, o)?.transformCaches?.get(a);
1089
+ let j;
1090
+ D && D.validIds ? j = D.validIds : (j = Ie(
1091
+ e,
1092
+ o,
1093
+ S?.transforms
1094
+ ), t.getState().setTransformCache(e, o, a, {
1095
+ validIds: j,
1096
+ computedAt: Date.now(),
1097
+ transforms: S?.transforms || []
1098
+ }));
1099
+ const F = t.getState().getShadowValue(c, j);
1100
+ return {
1101
+ validIds: j,
1102
+ arrayValues: F || []
1103
+ };
1104
+ }, [a, d]);
1105
+ if (console.log("freshValues", m, P), Q(() => {
1106
+ const D = t.getState().subscribeToPath(c, (j) => {
1107
+ if (j.type === "GET_SELECTED")
1108
+ return;
1109
+ const O = t.getState().getShadowMetadata(e, o)?.transformCaches;
1110
+ if (O)
1111
+ for (const L of O.keys())
1112
+ L.startsWith(T) && O.delete(L);
1113
+ (j.type === "INSERT" || j.type === "REMOVE" || j.type === "CLEAR_SELECTION") && (console.log("sssssssssssssssssssssssssssss", j), w({}));
1114
+ });
1115
+ return () => {
1116
+ D();
1117
+ };
1118
+ }, [T, c]), !Array.isArray(P))
1119
+ return null;
1120
+ const R = l({
1121
+ currentState: P,
1122
+ path: o,
1123
+ componentId: T,
1124
+ meta: {
1125
+ ...S,
1126
+ validIds: m
1127
+ }
1128
+ });
1129
+ return console.log("sssssssssssssssssssssssssssss", R), /* @__PURE__ */ re(ke, { children: P.map((D, j) => {
1130
+ const F = m[j];
1131
+ if (!F)
1132
+ return null;
1133
+ let O = r.current.get(F);
1134
+ O || (O = te(), r.current.set(F, O));
1135
+ const L = F.split(".").slice(1);
1136
+ return le(Me, {
1137
+ key: F,
1138
+ stateKey: e,
1139
+ itemComponentId: O,
1140
+ itemPath: L,
1141
+ localIndex: j,
1142
+ arraySetter: R,
1143
+ rebuildStateShape: l,
1144
+ renderFn: s
1145
+ });
1146
+ }) });
1147
+ }, {});
1148
+ if (v === "stateFlattenOn")
1149
+ return (s) => {
1150
+ const n = b;
1151
+ h.clear(), p++;
1152
+ const r = n.flatMap(
1153
+ (a) => a[s] ?? []
854
1154
  );
1155
+ return l({
1156
+ currentState: r,
1157
+ path: [...o, "[*]", s],
1158
+ componentId: T,
1159
+ meta: S
1160
+ });
855
1161
  };
856
- if (c === "index")
857
- return (r) => {
858
- const a = (w?.validIds || i(n))?.[r];
859
- if (!a)
860
- return $(void 0, [
861
- ...n,
862
- r.toString()
863
- ]);
864
- const u = o.getState().getNestedState(t, n).find(
865
- (m) => `id:${m.id}` === a
866
- ), l = [...n, a];
867
- return $(u, l, w);
1162
+ if (v === "index")
1163
+ return (s) => {
1164
+ const r = t.getState().getShadowMetadata(e, o)?.arrayKeys?.filter(
1165
+ (w) => !S?.validIds || S?.validIds && S?.validIds?.includes(w)
1166
+ )?.[s];
1167
+ if (!r) return;
1168
+ const a = t.getState().getShadowValue(r, S?.validIds);
1169
+ return l({
1170
+ currentState: a,
1171
+ path: r.split(".").slice(1),
1172
+ componentId: T,
1173
+ meta: S
1174
+ });
868
1175
  };
869
- if (c === "last")
1176
+ if (v === "last")
870
1177
  return () => {
871
- const r = o.getState().getNestedState(t, n);
872
- if (r.length === 0) return;
873
- const e = r.length - 1, a = r[e], d = [...n, e.toString()];
874
- return $(a, d);
1178
+ const s = t.getState().getShadowValue(e, o);
1179
+ if (s.length === 0) return;
1180
+ const n = s.length - 1, r = s[n], a = [...o, n.toString()];
1181
+ return l({
1182
+ currentState: r,
1183
+ path: a,
1184
+ componentId: T,
1185
+ meta: S
1186
+ });
875
1187
  };
876
- if (c === "insert")
877
- return (r) => (A(n), At(s, r, n, t), $(
878
- o.getState().getNestedState(t, n),
879
- n
880
- ));
881
- if (c === "uniqueInsert")
882
- return (r, e, a) => {
883
- const d = o.getState().getNestedState(t, n), u = et(r) ? r(d) : r;
884
- let l = null;
885
- if (!d.some((x) => {
886
- const b = e ? e.every(
887
- (F) => X(x[F], u[F])
888
- ) : X(x, u);
889
- return b && (l = x), b;
1188
+ if (v === "insert")
1189
+ return (s, n) => (i(s, o, { updateType: "insert" }), l({
1190
+ currentState: t.getState().getShadowValue(e, o),
1191
+ path: o,
1192
+ componentId: T,
1193
+ meta: S
1194
+ }));
1195
+ if (v === "uniqueInsert")
1196
+ return (s, n, r) => {
1197
+ const a = t.getState().getShadowValue(e, o), d = ee(s) ? s(a) : s;
1198
+ let w = null;
1199
+ if (!a.some((P) => {
1200
+ const R = n ? n.every(
1201
+ (D) => se(P[D], d[D])
1202
+ ) : se(P, d);
1203
+ return R && (w = P), R;
890
1204
  }))
891
- A(n), At(s, u, n, t);
892
- else if (a && l) {
893
- const x = a(l), b = d.map(
894
- (F) => X(F, l) ? x : F
1205
+ M(o), i(d, o, { updateType: "insert" });
1206
+ else if (r && w) {
1207
+ const P = r(w), R = a.map(
1208
+ (D) => se(D, w) ? P : D
895
1209
  );
896
- A(n), ut(s, b, n);
1210
+ M(o), i(R, o, {
1211
+ updateType: "update"
1212
+ });
897
1213
  }
898
1214
  };
899
- if (c === "cut")
900
- return (r, e) => {
901
- if (!e?.waitForSync)
902
- return A(n), ft(s, n, t, r), $(
903
- o.getState().getNestedState(t, n),
904
- n
905
- );
1215
+ if (v === "cut")
1216
+ return (s, n) => {
1217
+ const r = S?.validIds ?? t.getState().getShadowMetadata(e, o)?.arrayKeys;
1218
+ if (!r || r.length === 0) return;
1219
+ const a = s == -1 ? r.length - 1 : s !== void 0 ? s : r.length - 1, d = r[a];
1220
+ if (!d) return;
1221
+ const w = d.split(".").slice(1);
1222
+ i(b, w, {
1223
+ updateType: "cut"
1224
+ });
906
1225
  };
907
- if (c === "cutByValue")
908
- return (r) => {
909
- const e = y.findIndex((a) => a === r);
910
- e > -1 && ft(s, n, t, e);
1226
+ if (v === "cutSelected")
1227
+ return () => {
1228
+ t.getState().getShadowMetadata(e, o)?.arrayKeys;
1229
+ const s = Ie(
1230
+ e,
1231
+ o,
1232
+ S?.transforms
1233
+ );
1234
+ if (console.log("validKeys", s), !s || s.length === 0) return;
1235
+ const n = t.getState().selectedIndicesMap.get(c);
1236
+ let r = s.findIndex(
1237
+ (d) => d === n
1238
+ );
1239
+ console.log("indexToCut", r);
1240
+ const a = s[r == -1 ? s.length - 1 : r]?.split(".").slice(1);
1241
+ console.log("pathForCut", a), i(b, a, {
1242
+ updateType: "cut"
1243
+ });
911
1244
  };
912
- if (c === "toggleByValue")
913
- return (r) => {
914
- const e = y.findIndex((a) => a === r);
915
- e > -1 ? ft(s, n, t, e) : At(s, r, n, t);
1245
+ if (v === "cutByValue")
1246
+ return (s) => {
1247
+ const n = t.getState().getShadowMetadata(e, o), r = S?.validIds ?? n?.arrayKeys;
1248
+ if (!r) return;
1249
+ let a = null;
1250
+ for (const d of r)
1251
+ if (t.getState().getShadowValue(d) === s) {
1252
+ a = d;
1253
+ break;
1254
+ }
1255
+ if (a) {
1256
+ const d = a.split(".").slice(1);
1257
+ i(null, d, { updateType: "cut" });
1258
+ }
916
1259
  };
917
- if (c === "stateFilter")
918
- return (r) => {
919
- const e = w?.validIds || i(n) || [], a = o.getState().getNestedState(t, n), d = new Map(
920
- a.map((m) => [`id:${m.id}`, m])
921
- ), u = [], l = [];
922
- return e.forEach((m, x) => {
923
- const b = d.get(m);
924
- b && r(b, x) && (u.push(m), l.push(b));
925
- }), $(l, n, {
926
- validIds: u
927
- });
1260
+ if (v === "toggleByValue")
1261
+ return (s) => {
1262
+ const n = t.getState().getShadowMetadata(e, o), r = S?.validIds ?? n?.arrayKeys;
1263
+ if (!r) return;
1264
+ let a = null;
1265
+ for (const d of r) {
1266
+ const w = t.getState().getShadowValue(d);
1267
+ if (console.log("itemValue sdasdasdasd", w), w === s) {
1268
+ a = d;
1269
+ break;
1270
+ }
1271
+ }
1272
+ if (console.log("itemValue keyToCut", a), a) {
1273
+ const d = a.split(".").slice(1);
1274
+ console.log("itemValue keyToCut", a), i(s, d, {
1275
+ updateType: "cut"
1276
+ });
1277
+ } else
1278
+ i(s, o, { updateType: "insert" });
928
1279
  };
929
- if (c === "stateSort")
930
- return (r) => {
931
- const a = y.map((l) => ({
932
- item: l,
933
- id: `id:${l.id}`
934
- }));
935
- a.sort((l, m) => r(l.item, m.item));
936
- const d = a.map((l) => l.item), u = a.map((l) => l.id);
937
- return $(d, n, {
938
- validIds: u
1280
+ if (v === "findWith")
1281
+ return (s, n) => {
1282
+ const r = t.getState().getShadowMetadata(e, o)?.arrayKeys;
1283
+ if (!r)
1284
+ throw new Error("No array keys found for sorting");
1285
+ let a = null, d = [];
1286
+ for (const w of r) {
1287
+ let m = t.getState().getShadowValue(w, S?.validIds);
1288
+ if (m && m[s] === n) {
1289
+ a = m, d = w.split(".").slice(1);
1290
+ break;
1291
+ }
1292
+ }
1293
+ return l({
1294
+ currentState: a,
1295
+ path: d,
1296
+ componentId: T,
1297
+ meta: S
939
1298
  });
940
1299
  };
941
- if (c === "findWith")
942
- return (r, e) => {
943
- const a = y.find(
944
- (l) => l[r] === e
945
- );
946
- if (!a) return;
947
- const d = `id:${a.id}`, u = [...n, d];
948
- return $(a, u, w);
949
- };
950
- }
951
- const R = n[n.length - 1];
952
- if (!isNaN(Number(R))) {
953
- const r = n.slice(0, -1), e = o.getState().getNestedState(t, r);
954
- if (Array.isArray(e) && c === "cut")
955
- return () => ft(
956
- s,
957
- r,
958
- t,
959
- Number(R)
960
- );
961
1300
  }
962
- if (c === "get")
1301
+ if (v === "cut") {
1302
+ let s = t.getState().getShadowValue(o.join("."));
963
1303
  return () => {
964
- if (w?.validIds && Array.isArray(y)) {
965
- const r = o.getState().getNestedState(t, n);
966
- if (!Array.isArray(r)) return [];
967
- const e = new Map(
968
- r.map((a) => [`id:${a.id}`, a])
969
- );
970
- return w.validIds.map((a) => e.get(a)).filter(Boolean);
971
- }
972
- return o.getState().getNestedState(t, n);
1304
+ i(s, o, { updateType: "cut" });
973
1305
  };
974
- if (c === "$derive")
975
- return (r) => _t({
976
- _stateKey: t,
977
- _path: n,
978
- _effect: r.toString()
1306
+ }
1307
+ if (v === "get")
1308
+ return () => (Ve(e, T, o), t.getState().getShadowValue(c, S?.validIds));
1309
+ if (v === "$derive")
1310
+ return (s) => Ae({
1311
+ _stateKey: e,
1312
+ _path: o,
1313
+ _effect: s.toString(),
1314
+ _meta: S
979
1315
  });
980
- if (c === "$get")
981
- return () => _t({ _stateKey: t, _path: n });
982
- if (c === "lastSynced") {
983
- const r = `${t}:${n.join(".")}`;
984
- return o.getState().getSyncInfo(r);
1316
+ if (v === "$get")
1317
+ return () => Ae({ _stateKey: e, _path: o, _meta: S });
1318
+ if (v === "lastSynced") {
1319
+ const s = `${e}:${o.join(".")}`;
1320
+ return t.getState().getSyncInfo(s);
985
1321
  }
986
- if (c == "getLocalStorage")
987
- return (r) => yt(g + "-" + t + "-" + r);
988
- if (c === "_selected") {
989
- const r = n.slice(0, -1), e = r.join(".");
990
- if (Array.isArray(
991
- o.getState().getNestedState(t, r)
1322
+ if (v == "getLocalStorage")
1323
+ return (s) => Se(g + "-" + e + "-" + s);
1324
+ if (v === "isSelected") {
1325
+ const s = [e, ...o].slice(0, -1);
1326
+ if (ye(e, o, void 0), Array.isArray(
1327
+ t.getState().getShadowValue(s.join("."), S?.validIds)
992
1328
  )) {
993
- const a = n[n.length - 1];
994
- return i(r)?.indexOf(a) === o.getState().getSelectedIndex(t, e);
1329
+ o[o.length - 1];
1330
+ const n = s.join("."), r = t.getState().selectedIndicesMap.get(n), a = e + "." + o.join(".");
1331
+ return r === a;
995
1332
  }
996
1333
  return;
997
1334
  }
998
- if (c === "setSelected")
999
- return (r) => {
1000
- const e = n.slice(0, -1), a = n[n.length - 1], u = i(e)?.indexOf(a);
1001
- if (u === void 0 || u === -1) return;
1002
- const l = e.join(".");
1003
- o.getState().setSelectedIndex(
1004
- t,
1005
- l,
1006
- r ? u : void 0
1007
- );
1008
- const m = o.getState().getNestedState(t, [...e]);
1009
- ut(s, m, e), A(e);
1335
+ if (v === "setSelected")
1336
+ return (s) => {
1337
+ const n = o.slice(0, -1), r = e + "." + n.join("."), a = e + "." + o.join(".");
1338
+ ye(e, n, void 0), t.getState().selectedIndicesMap.get(r), s && t.getState().setSelectedIndex(r, a);
1010
1339
  };
1011
- if (c === "toggleSelected")
1340
+ if (v === "toggleSelected")
1012
1341
  return () => {
1013
- const r = n.slice(0, -1), e = n[n.length - 1], d = i(r)?.indexOf(e);
1014
- if (d === void 0 || d === -1) return;
1015
- const u = r.join("."), l = o.getState().getSelectedIndex(t, u);
1016
- o.getState().setSelectedIndex(
1017
- t,
1018
- u,
1019
- l === d ? void 0 : d
1020
- );
1021
- const m = o.getState().getNestedState(t, [...r]);
1022
- ut(s, m, r), A(r);
1342
+ const s = o.slice(0, -1), n = e + "." + s.join("."), r = e + "." + o.join(".");
1343
+ t.getState().selectedIndicesMap.get(n) === r ? t.getState().clearSelectedIndex({ arrayKey: n }) : t.getState().setSelectedIndex(n, r);
1023
1344
  };
1024
- if (n.length == 0) {
1025
- if (c === "addValidation")
1026
- return (r) => {
1027
- const e = o.getState().getInitialOptions(t)?.validation;
1028
- if (!e?.key) throw new Error("Validation key not found");
1029
- tt(e.key), r.forEach((a) => {
1030
- const d = [e.key, ...a.path].join(".");
1031
- Tt(d, a.message);
1032
- }), ot(t);
1345
+ if (v === "_componentId")
1346
+ return T;
1347
+ if (o.length == 0) {
1348
+ if (v === "addValidation")
1349
+ return (s) => {
1350
+ const n = t.getState().getInitialOptions(e)?.validation;
1351
+ if (!n?.key) throw new Error("Validation key not found");
1352
+ ne(n.key), s.forEach((r) => {
1353
+ const a = [n.key, ...r.path].join(".");
1354
+ ve(a, r.message);
1355
+ }), ie(e);
1033
1356
  };
1034
- if (c === "applyJsonPatch")
1035
- return (r) => {
1036
- const e = o.getState().cogsStateStore[t], a = Wt(e, r).newDocument;
1037
- jt(
1038
- t,
1039
- o.getState().initialStateGlobal[t],
1040
- a,
1041
- s,
1042
- S,
1043
- g
1044
- ), ot(t);
1357
+ if (v === "applyJsonPatch")
1358
+ return (s) => {
1359
+ const n = t.getState(), r = (a) => !a || a === "/" ? [] : a.split("/").slice(1).map((d) => d.replace(/~1/g, "/").replace(/~0/g, "~"));
1360
+ for (const a of s) {
1361
+ const d = r(a.path);
1362
+ switch (a.op) {
1363
+ case "add":
1364
+ case "replace": {
1365
+ const { value: w } = a;
1366
+ n.updateShadowAtPath(e, d, w), n.markAsDirty(e, d, { bubble: !0 });
1367
+ break;
1368
+ }
1369
+ case "remove": {
1370
+ n.removeShadowArrayElement(e, d);
1371
+ const w = d.slice(0, -1);
1372
+ n.markAsDirty(e, w, { bubble: !0 });
1373
+ break;
1374
+ }
1375
+ }
1376
+ }
1045
1377
  };
1046
- if (c === "validateZodSchema")
1378
+ if (v === "validateZodSchema")
1047
1379
  return () => {
1048
- const r = o.getState().getInitialOptions(t)?.validation;
1049
- if (!r?.zodSchema || !r?.key)
1380
+ const s = t.getState().getInitialOptions(e)?.validation;
1381
+ if (!s?.zodSchema || !s?.key)
1050
1382
  throw new Error("Zod schema or validation key not found");
1051
- tt(r.key);
1052
- const e = o.getState().cogsStateStore[t], a = r.zodSchema.safeParse(e);
1053
- return a.success ? !0 : (a.error.errors.forEach((d) => {
1054
- const u = [r.key, ...d.path].join(".");
1055
- Tt(u, d.message);
1056
- }), ot(t), !1);
1383
+ ne(s.key);
1384
+ const n = t.getState().getShadowValue(e), r = s.zodSchema.safeParse(n);
1385
+ return r.success ? !0 : (r.error.errors.forEach((a) => {
1386
+ const d = [s.key, ...a.path].join(".");
1387
+ ve(d, a.message);
1388
+ }), ie(e), !1);
1057
1389
  };
1058
- if (c === "_componentId") return S;
1059
- if (c === "getComponents")
1060
- return () => o().stateComponents.get(t);
1061
- if (c === "getAllFormRefs")
1062
- return () => bt.getState().getFormRefsByStateKey(t);
1063
- if (c === "_initialState")
1064
- return o.getState().initialStateGlobal[t];
1065
- if (c === "_serverState")
1066
- return o.getState().serverState[t];
1067
- if (c === "_isLoading")
1068
- return o.getState().isLoadingGlobal[t];
1069
- if (c === "revertToInitialState")
1070
- return v.revertToInitialState;
1071
- if (c === "updateInitialState") return v.updateInitialState;
1072
- if (c === "removeValidation") return v.removeValidation;
1390
+ if (v === "getComponents")
1391
+ return () => t.getState().getShadowMetadata(e, [])?.components;
1392
+ if (v === "getAllFormRefs")
1393
+ return () => pe.getState().getFormRefsByStateKey(e);
1073
1394
  }
1074
- if (c === "getFormRef")
1075
- return () => bt.getState().getFormRef(t + "." + n.join("."));
1076
- if (c === "validationWrapper")
1395
+ if (v === "getFormRef")
1396
+ return () => pe.getState().getFormRef(e + "." + o.join("."));
1397
+ if (v === "validationWrapper")
1077
1398
  return ({
1078
- children: r,
1079
- hideMessage: e
1080
- }) => /* @__PURE__ */ $t(
1081
- Gt,
1399
+ children: s,
1400
+ hideMessage: n
1401
+ }) => /* @__PURE__ */ re(
1402
+ be,
1082
1403
  {
1083
- formOpts: e ? { validation: { message: "" } } : void 0,
1084
- path: n,
1085
- stateKey: t,
1086
- children: r
1404
+ formOpts: n ? { validation: { message: "" } } : void 0,
1405
+ path: o,
1406
+ stateKey: e,
1407
+ children: s
1087
1408
  }
1088
1409
  );
1089
- if (c === "_stateKey") return t;
1090
- if (c === "_path") return n;
1091
- if (c === "_isServerSynced") return v._isServerSynced;
1092
- if (c === "update")
1093
- return (r, e) => {
1094
- if (e?.debounce)
1095
- Lt(() => {
1096
- ut(s, r, n, "");
1097
- const a = o.getState().getNestedState(t, n);
1098
- e?.afterUpdate && e.afterUpdate(a);
1099
- }, e.debounce);
1100
- else {
1101
- ut(s, r, n, "");
1102
- const a = o.getState().getNestedState(t, n);
1103
- e?.afterUpdate && e.afterUpdate(a);
1410
+ if (v === "_stateKey") return e;
1411
+ if (v === "_path") return o;
1412
+ if (v === "update")
1413
+ return (s) => (i(s, o, { updateType: "update" }), {
1414
+ /**
1415
+ * Marks this specific item, which was just updated, as 'synced' (not dirty).
1416
+ */
1417
+ synced: () => {
1418
+ const n = t.getState().getShadowMetadata(e, o);
1419
+ t.getState().setShadowMetadata(e, o, {
1420
+ ...n,
1421
+ isDirty: !1,
1422
+ // EXPLICITLY set to false, not just undefined
1423
+ stateSource: "server",
1424
+ // Mark as coming from server
1425
+ lastServerSync: Date.now()
1426
+ // Add timestamp
1427
+ });
1428
+ const r = [e, ...o].join(".");
1429
+ t.getState().notifyPathSubscribers(r, {
1430
+ type: "SYNC_STATUS_CHANGE",
1431
+ isDirty: !1
1432
+ });
1104
1433
  }
1105
- A(n);
1434
+ });
1435
+ if (v === "toggle") {
1436
+ const s = t.getState().getShadowValue([e, ...o].join("."));
1437
+ if (console.log("currentValueAtPath", s), typeof b != "boolean")
1438
+ throw new Error("toggle() can only be used on boolean values");
1439
+ return () => {
1440
+ i(!s, o, {
1441
+ updateType: "update"
1442
+ });
1106
1443
  };
1107
- if (c === "formElement")
1108
- return (r, e) => /* @__PURE__ */ $t(
1109
- Ht,
1444
+ }
1445
+ if (v === "formElement")
1446
+ return (s, n) => /* @__PURE__ */ re(
1447
+ be,
1110
1448
  {
1111
- setState: s,
1112
- stateKey: t,
1113
- path: n,
1114
- child: r,
1115
- formOpts: e
1449
+ formOpts: n,
1450
+ path: o,
1451
+ stateKey: e,
1452
+ children: /* @__PURE__ */ re(
1453
+ Ze,
1454
+ {
1455
+ stateKey: e,
1456
+ path: o,
1457
+ rebuildStateShape: l,
1458
+ setState: i,
1459
+ formOpts: n,
1460
+ renderFn: s
1461
+ }
1462
+ )
1116
1463
  }
1117
1464
  );
1118
- const it = [...n, c], vt = o.getState().getNestedState(t, it);
1119
- return $(vt, it, w);
1465
+ const oe = [...o, v], fe = t.getState().getShadowValue(e, oe);
1466
+ return l({
1467
+ currentState: fe,
1468
+ path: oe,
1469
+ componentId: T,
1470
+ meta: S
1471
+ });
1120
1472
  }
1121
- }, f = new Proxy(p, K);
1122
- return I.set(O, {
1123
- proxy: f,
1124
- stateVersion: T
1125
- }), f;
1473
+ }, J = new Proxy(x, Y);
1474
+ return h.set(W, {
1475
+ proxy: J,
1476
+ stateVersion: p
1477
+ }), J;
1126
1478
  }
1127
- return $(
1128
- o.getState().getNestedState(t, [])
1129
- );
1479
+ const u = {
1480
+ removeValidation: (b) => {
1481
+ b?.validationKey && ne(b.validationKey);
1482
+ },
1483
+ revertToInitialState: (b) => {
1484
+ const o = t.getState().getInitialOptions(e)?.validation;
1485
+ o?.key && ne(o.key), b?.validationKey && ne(b.validationKey);
1486
+ const S = t.getState().getShadowMetadata(e, []);
1487
+ S?.stateSource === "server" && S.baseServerState ? S.baseServerState : t.getState().initialStateGlobal[e];
1488
+ const T = t.getState().initialStateGlobal[e];
1489
+ t.getState().clearSelectedIndexesForState(e), h.clear(), p++, t.getState().initializeShadowState(e, T), l({
1490
+ currentState: T,
1491
+ path: [],
1492
+ componentId: f
1493
+ });
1494
+ const W = ae(e), c = ee(W?.localStorage?.key) ? W?.localStorage?.key(T) : W?.localStorage?.key, x = `${g}-${e}-${c}`;
1495
+ x && localStorage.removeItem(x);
1496
+ const Y = t.getState().getShadowMetadata(e, []);
1497
+ return Y && Y?.components?.forEach((J) => {
1498
+ J.forceUpdate();
1499
+ }), T;
1500
+ },
1501
+ updateInitialState: (b) => {
1502
+ h.clear(), p++;
1503
+ const o = De(
1504
+ e,
1505
+ i,
1506
+ f,
1507
+ g
1508
+ ), S = t.getState().initialStateGlobal[e], T = ae(e), W = ee(T?.localStorage?.key) ? T?.localStorage?.key(S) : T?.localStorage?.key, c = `${g}-${e}-${W}`;
1509
+ return localStorage.getItem(c) && localStorage.removeItem(c), je(() => {
1510
+ $e(e, b), t.getState().initializeShadowState(e, b);
1511
+ const x = t.getState().getShadowMetadata(e, []);
1512
+ x && x?.components?.forEach((Y) => {
1513
+ Y.forceUpdate();
1514
+ });
1515
+ }), {
1516
+ fetchId: (x) => o.get()[x]
1517
+ };
1518
+ }
1519
+ };
1520
+ return l({
1521
+ currentState: t.getState().getShadowValue(e, []),
1522
+ componentId: f,
1523
+ path: []
1524
+ });
1130
1525
  }
1131
- function _t(t) {
1132
- return gt(te, { proxy: t });
1526
+ function Ae(e) {
1527
+ return le(ze, { proxy: e });
1133
1528
  }
1134
- function Kt({
1135
- proxy: t,
1136
- rebuildStateShape: s
1529
+ function Ge({
1530
+ proxy: e,
1531
+ rebuildStateShape: i
1137
1532
  }) {
1138
- const S = o().getNestedState(t._stateKey, t._path);
1139
- return Array.isArray(S) ? s(
1140
- S,
1141
- t._path
1142
- ).stateMapNoRender(
1143
- (I, T, A, v, i) => t._mapFn(I, T, A, v, i)
1144
- ) : null;
1533
+ const f = G(null), g = G(`map-${crypto.randomUUID()}`), h = G(!1), p = G(/* @__PURE__ */ new Map());
1534
+ Q(() => {
1535
+ const l = f.current;
1536
+ if (!l || h.current) return;
1537
+ const u = setTimeout(() => {
1538
+ const A = t.getState().getShadowMetadata(e._stateKey, e._path) || {}, b = A.mapWrappers || [];
1539
+ b.push({
1540
+ instanceId: g.current,
1541
+ mapFn: e._mapFn,
1542
+ containerRef: l,
1543
+ rebuildStateShape: i,
1544
+ path: e._path,
1545
+ componentId: g.current,
1546
+ meta: e._meta
1547
+ }), t.getState().setShadowMetadata(e._stateKey, e._path, {
1548
+ ...A,
1549
+ mapWrappers: b
1550
+ }), h.current = !0, M();
1551
+ }, 0);
1552
+ return () => {
1553
+ if (clearTimeout(u), g.current) {
1554
+ const A = t.getState().getShadowMetadata(e._stateKey, e._path) || {};
1555
+ A.mapWrappers && (A.mapWrappers = A.mapWrappers.filter(
1556
+ (b) => b.instanceId !== g.current
1557
+ ), t.getState().setShadowMetadata(e._stateKey, e._path, A));
1558
+ }
1559
+ p.current.forEach((A) => A.unmount());
1560
+ };
1561
+ }, []);
1562
+ const M = () => {
1563
+ const l = f.current;
1564
+ if (!l) return;
1565
+ const u = t.getState().getShadowValue(
1566
+ [e._stateKey, ...e._path].join("."),
1567
+ e._meta?.validIds
1568
+ );
1569
+ if (!Array.isArray(u)) return;
1570
+ const A = e._meta?.validIds ?? t.getState().getShadowMetadata(e._stateKey, e._path)?.arrayKeys ?? [], b = i({
1571
+ currentState: u,
1572
+ path: e._path,
1573
+ componentId: g.current,
1574
+ meta: e._meta
1575
+ });
1576
+ u.forEach((o, S) => {
1577
+ const T = A[S];
1578
+ if (!T) return;
1579
+ const W = te(), c = document.createElement("div");
1580
+ c.setAttribute("data-item-path", T), l.appendChild(c);
1581
+ const x = Ce(c);
1582
+ p.current.set(T, x);
1583
+ const Y = T.split(".").slice(1);
1584
+ x.render(
1585
+ le(Me, {
1586
+ stateKey: e._stateKey,
1587
+ itemComponentId: W,
1588
+ itemPath: Y,
1589
+ localIndex: S,
1590
+ arraySetter: b,
1591
+ rebuildStateShape: i,
1592
+ renderFn: e._mapFn
1593
+ })
1594
+ );
1595
+ });
1596
+ };
1597
+ return /* @__PURE__ */ re("div", { ref: f, "data-map-container": g.current });
1145
1598
  }
1146
- function te({
1147
- proxy: t
1599
+ function ze({
1600
+ proxy: e
1148
1601
  }) {
1149
- const s = q(null), S = `${t._stateKey}-${t._path.join(".")}`;
1150
- return at(() => {
1151
- const g = s.current;
1152
- if (!g || !g.parentElement) return;
1153
- const I = g.parentElement, A = Array.from(I.childNodes).indexOf(g);
1154
- let v = I.getAttribute("data-parent-id");
1155
- v || (v = `parent-${crypto.randomUUID()}`, I.setAttribute("data-parent-id", v));
1156
- const $ = {
1157
- instanceId: `instance-${crypto.randomUUID()}`,
1158
- parentId: v,
1159
- position: A,
1160
- effect: t._effect
1161
- };
1162
- o.getState().addSignalElement(S, $);
1163
- const y = o.getState().getNestedState(t._stateKey, t._path);
1164
- let n = y;
1165
- if (t._effect)
1166
- try {
1167
- n = new Function(
1168
- "state",
1169
- `return (${t._effect})(state)`
1170
- )(y);
1171
- } catch (O) {
1172
- console.error("Error evaluating effect function:", O);
1602
+ const i = G(null), f = G(null), g = G(!1), h = `${e._stateKey}-${e._path.join(".")}`, p = t.getState().getShadowValue(
1603
+ [e._stateKey, ...e._path].join("."),
1604
+ e._meta?.validIds
1605
+ );
1606
+ return Q(() => {
1607
+ const M = i.current;
1608
+ if (!M || g.current) return;
1609
+ const l = setTimeout(() => {
1610
+ if (!M.parentElement) {
1611
+ console.warn("Parent element not found for signal", h);
1612
+ return;
1173
1613
  }
1174
- n !== null && typeof n == "object" && (n = JSON.stringify(n));
1175
- const w = document.createTextNode(String(n));
1176
- g.replaceWith(w);
1177
- }, [t._stateKey, t._path.join("."), t._effect]), gt("span", {
1178
- ref: s,
1179
- style: { display: "none" },
1180
- "data-signal-id": S
1614
+ const u = M.parentElement, b = Array.from(u.childNodes).indexOf(M);
1615
+ let o = u.getAttribute("data-parent-id");
1616
+ o || (o = `parent-${crypto.randomUUID()}`, u.setAttribute("data-parent-id", o)), f.current = `instance-${crypto.randomUUID()}`;
1617
+ const S = t.getState().getShadowMetadata(e._stateKey, e._path) || {}, T = S.signals || [];
1618
+ T.push({
1619
+ instanceId: f.current,
1620
+ parentId: o,
1621
+ position: b,
1622
+ effect: e._effect
1623
+ }), t.getState().setShadowMetadata(e._stateKey, e._path, {
1624
+ ...S,
1625
+ signals: T
1626
+ });
1627
+ let W = p;
1628
+ if (e._effect)
1629
+ try {
1630
+ W = new Function(
1631
+ "state",
1632
+ `return (${e._effect})(state)`
1633
+ )(p);
1634
+ } catch (x) {
1635
+ console.error("Error evaluating effect function:", x);
1636
+ }
1637
+ W !== null && typeof W == "object" && (W = JSON.stringify(W));
1638
+ const c = document.createTextNode(String(W ?? ""));
1639
+ M.replaceWith(c), g.current = !0;
1640
+ }, 0);
1641
+ return () => {
1642
+ if (clearTimeout(l), f.current) {
1643
+ const u = t.getState().getShadowMetadata(e._stateKey, e._path) || {};
1644
+ u.signals && (u.signals = u.signals.filter(
1645
+ (A) => A.instanceId !== f.current
1646
+ ), t.getState().setShadowMetadata(e._stateKey, e._path, u));
1647
+ }
1648
+ };
1649
+ }, []), le("span", {
1650
+ ref: i,
1651
+ style: { display: "contents" },
1652
+ "data-signal-id": h
1181
1653
  });
1182
1654
  }
1183
- function ye(t) {
1184
- const s = Ft(
1185
- (S) => {
1186
- const g = o.getState().stateComponents.get(t._stateKey) || { components: /* @__PURE__ */ new Map() };
1187
- return g.components.set(t._stateKey, {
1188
- forceUpdate: S,
1189
- paths: /* @__PURE__ */ new Set([t._path.join(".")])
1190
- }), o.getState().stateComponents.set(t._stateKey, g), () => g.components.delete(t._stateKey);
1655
+ const Me = Re(
1656
+ Ye,
1657
+ (e, i) => e.itemPath.join(".") === i.itemPath.join(".") && e.stateKey === i.stateKey && e.itemComponentId === i.itemComponentId && e.localIndex === i.localIndex
1658
+ ), Je = (e) => {
1659
+ const [i, f] = X(!1);
1660
+ return de(() => {
1661
+ if (!e.current) {
1662
+ f(!0);
1663
+ return;
1664
+ }
1665
+ const g = Array.from(e.current.querySelectorAll("img"));
1666
+ if (g.length === 0) {
1667
+ f(!0);
1668
+ return;
1669
+ }
1670
+ let h = 0;
1671
+ const p = () => {
1672
+ h++, h === g.length && f(!0);
1673
+ };
1674
+ return g.forEach((M) => {
1675
+ M.complete ? p() : (M.addEventListener("load", p), M.addEventListener("error", p));
1676
+ }), () => {
1677
+ g.forEach((M) => {
1678
+ M.removeEventListener("load", p), M.removeEventListener("error", p);
1679
+ });
1680
+ };
1681
+ }, [e.current]), i;
1682
+ };
1683
+ function Ye({
1684
+ stateKey: e,
1685
+ itemComponentId: i,
1686
+ itemPath: f,
1687
+ localIndex: g,
1688
+ arraySetter: h,
1689
+ rebuildStateShape: p,
1690
+ renderFn: M
1691
+ }) {
1692
+ const [, l] = X({}), { ref: u, inView: A } = Le(), b = G(null), o = Je(b), S = G(!1), T = [e, ...f].join(".");
1693
+ Ue(e, i, l);
1694
+ const W = ce(
1695
+ (U) => {
1696
+ b.current = U, u(U);
1191
1697
  },
1192
- () => o.getState().getNestedState(t._stateKey, t._path)
1698
+ [u]
1193
1699
  );
1194
- return gt("text", {}, String(s));
1700
+ Q(() => {
1701
+ t.getState().subscribeToPath(T, (U) => {
1702
+ l({});
1703
+ });
1704
+ }, []), Q(() => {
1705
+ if (!A || !o || S.current)
1706
+ return;
1707
+ const U = b.current;
1708
+ if (U && U.offsetHeight > 0) {
1709
+ S.current = !0;
1710
+ const v = U.offsetHeight;
1711
+ t.getState().setShadowMetadata(e, f, {
1712
+ virtualizer: {
1713
+ itemHeight: v,
1714
+ domRef: U
1715
+ }
1716
+ });
1717
+ const K = f.slice(0, -1), oe = [e, ...K].join(".");
1718
+ t.getState().notifyPathSubscribers(oe, {
1719
+ type: "ITEMHEIGHT",
1720
+ itemKey: f.join("."),
1721
+ ref: b.current
1722
+ });
1723
+ }
1724
+ }, [A, o, e, f]);
1725
+ const c = [e, ...f].join("."), x = t.getState().getShadowValue(c);
1726
+ if (x === void 0)
1727
+ return null;
1728
+ const Y = p({
1729
+ currentState: x,
1730
+ path: f,
1731
+ componentId: i
1732
+ }), J = M(Y, g, h);
1733
+ return /* @__PURE__ */ re("div", { ref: W, children: J });
1195
1734
  }
1196
- function ee({
1197
- stateKey: t,
1198
- itemComponentId: s,
1199
- itemPath: S,
1200
- children: g
1735
+ function Ze({
1736
+ stateKey: e,
1737
+ path: i,
1738
+ rebuildStateShape: f,
1739
+ renderFn: g,
1740
+ formOpts: h,
1741
+ setState: p
1201
1742
  }) {
1202
- const [, I] = dt({}), [T, A] = Bt(), v = q(null), i = q(null), $ = St(
1203
- (y) => {
1204
- T(y), v.current = y;
1743
+ const [M] = X(() => te()), [, l] = X({}), u = [e, ...i].join(".");
1744
+ Ue(e, M, l);
1745
+ const A = t.getState().getShadowValue(u), [b, o] = X(A), S = G(!1), T = G(null);
1746
+ Q(() => {
1747
+ !S.current && !se(A, b) && o(A);
1748
+ }, [A]), Q(() => {
1749
+ const J = t.getState().subscribeToPath(u, (U) => {
1750
+ l({});
1751
+ });
1752
+ return () => {
1753
+ J(), T.current && (clearTimeout(T.current), S.current = !1);
1754
+ };
1755
+ }, []);
1756
+ const W = ce(
1757
+ (J) => {
1758
+ o(J), S.current = !0, T.current && clearTimeout(T.current);
1759
+ const U = h?.debounceTime ?? 200;
1760
+ T.current = setTimeout(() => {
1761
+ S.current = !1, p(J, i, { updateType: "update" });
1762
+ }, U);
1205
1763
  },
1206
- [T]
1207
- );
1208
- return at(() => {
1209
- A.height > 0 && A.height !== i.current && (i.current = A.height, o.getState().setShadowMetadata(t, S, {
1210
- virtualizer: { itemHeight: A.height, domRef: v.current }
1211
- }));
1212
- }, [A.height, t, S]), pt(() => {
1213
- const y = `${t}////${s}`, n = o.getState().stateComponents.get(t) || { components: /* @__PURE__ */ new Map() };
1214
- return n.components.set(y, {
1215
- forceUpdate: () => I({}),
1216
- paths: /* @__PURE__ */ new Set([S.join(".")])
1217
- }), o.getState().stateComponents.set(t, n), () => {
1218
- const w = o.getState().stateComponents.get(t);
1219
- w && w.components.delete(y);
1764
+ [p, i, h?.debounceTime]
1765
+ ), c = ce(() => {
1766
+ T.current && (clearTimeout(T.current), S.current = !1, p(b, i, { updateType: "update" }));
1767
+ }, [p, i, b]), x = f({
1768
+ currentState: A,
1769
+ path: i,
1770
+ componentId: M
1771
+ }), Y = new Proxy(x, {
1772
+ get(J, U) {
1773
+ return U === "inputProps" ? {
1774
+ value: b ?? "",
1775
+ onChange: (v) => {
1776
+ W(v.target.value);
1777
+ },
1778
+ onBlur: c,
1779
+ ref: pe.getState().getFormRef(e + "." + i.join("."))
1780
+ } : J[U];
1781
+ }
1782
+ });
1783
+ return /* @__PURE__ */ re(ke, { children: g(Y) });
1784
+ }
1785
+ function Ue(e, i, f) {
1786
+ const g = `${e}////${i}`;
1787
+ de(() => {
1788
+ const h = t.getState().getShadowMetadata(e, []), p = h?.components || /* @__PURE__ */ new Map();
1789
+ return p.set(g, {
1790
+ forceUpdate: () => f({}),
1791
+ paths: /* @__PURE__ */ new Set(),
1792
+ reactiveType: ["component"]
1793
+ }), t.getState().setShadowMetadata(e, [], {
1794
+ ...h,
1795
+ components: p
1796
+ }), () => {
1797
+ const M = t.getState().getShadowMetadata(e, []);
1798
+ M?.components && M.components.delete(g);
1220
1799
  };
1221
- }, [t, s, S.join(".")]), /* @__PURE__ */ $t("div", { ref: $, children: g });
1800
+ }, [e, g]);
1222
1801
  }
1223
1802
  export {
1224
- _t as $cogsSignal,
1225
- ye as $cogsSignalStore,
1226
- Se as addStateOptions,
1227
- me as createCogsState,
1228
- Ie as notifyComponent,
1229
- Xt as useCogsStateFn
1803
+ Ae as $cogsSignal,
1804
+ it as addStateOptions,
1805
+ ct as createCogsState,
1806
+ lt as notifyComponent,
1807
+ Be as useCogsStateFn
1230
1808
  };
1231
1809
  //# sourceMappingURL=CogsState.jsx.map