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