cogsbox-state 0.5.463 → 0.5.465

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