cogsbox-state 0.5.432 → 0.5.434
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +596 -238
- package/dist/CogsState.d.ts +93 -104
- package/dist/CogsState.jsx +1529 -1058
- package/dist/CogsState.jsx.map +1 -1
- package/dist/Functions.d.ts +1 -15
- package/dist/Functions.jsx +40 -187
- package/dist/Functions.jsx.map +1 -1
- package/dist/index.js +18 -19
- package/dist/store.d.ts +94 -92
- package/dist/store.js +230 -295
- package/dist/store.js.map +1 -1
- package/dist/useValidateZodPath.d.ts +1 -1
- package/dist/utility.d.ts +2 -2
- package/dist/utility.js +152 -169
- package/dist/utility.js.map +1 -1
- package/package.json +2 -1
- package/src/CogsState.tsx +2847 -1685
- package/src/Functions.tsx +167 -303
- package/src/store.ts +440 -440
- package/src/utility.ts +76 -95
- package/dist/useValidateZodPath.js +0 -59
- package/dist/useValidateZodPath.js.map +0 -1
package/src/utility.ts
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
|
-
import type { InitialStateType, TransformedStateType } from
|
|
1
|
+
import type { InitialStateType, TransformedStateType } from './CogsState';
|
|
2
|
+
import { getGlobalStore } from './store';
|
|
2
3
|
export const isObject = (item: any): item is Record<string, any> => {
|
|
3
4
|
return (
|
|
4
|
-
item && typeof item ===
|
|
5
|
+
item && typeof item === 'object' && !Array.isArray(item) && item !== null
|
|
5
6
|
);
|
|
6
7
|
};
|
|
7
8
|
export type GenericObject = Record<string, any>;
|
|
8
9
|
|
|
9
10
|
export const isFunction = <TStateObject extends unknown>(
|
|
10
11
|
arg: any
|
|
11
|
-
): arg is (prev: TStateObject) => TStateObject => typeof arg ===
|
|
12
|
+
): arg is (prev: TStateObject) => TStateObject => typeof arg === 'function';
|
|
12
13
|
|
|
13
14
|
export const isArray = (item: any): item is Array<any> => {
|
|
14
15
|
return Array.isArray(item);
|
|
@@ -92,12 +93,12 @@ export function updateNestedProperty(
|
|
|
92
93
|
...state.slice(index + 1),
|
|
93
94
|
];
|
|
94
95
|
} else {
|
|
95
|
-
console.log(
|
|
96
|
+
console.log('errorstate', state, path);
|
|
96
97
|
throw new Error(
|
|
97
|
-
`Invalid array index "${index}" in path "${path.join(
|
|
98
|
+
`Invalid array index "${index}" in path "${path.join('.')}".`
|
|
98
99
|
);
|
|
99
100
|
}
|
|
100
|
-
} else if (typeof state ===
|
|
101
|
+
} else if (typeof state === 'object' && state !== null) {
|
|
101
102
|
if (head && head in state) {
|
|
102
103
|
return {
|
|
103
104
|
...state,
|
|
@@ -106,12 +107,12 @@ export function updateNestedProperty(
|
|
|
106
107
|
} else {
|
|
107
108
|
console.log(`Invalid property`, head, tail, path);
|
|
108
109
|
throw new Error(
|
|
109
|
-
`Invalid property "${head}" in path "${path.join(
|
|
110
|
+
`Invalid property "${head}" in path "${path.join('.')}".`
|
|
110
111
|
);
|
|
111
112
|
}
|
|
112
113
|
} else {
|
|
113
114
|
throw new Error(
|
|
114
|
-
`Cannot update nested property at path "${path.join(
|
|
115
|
+
`Cannot update nested property at path "${path.join('.')}". The path does not exist.`
|
|
115
116
|
);
|
|
116
117
|
}
|
|
117
118
|
}
|
|
@@ -137,10 +138,10 @@ export function deleteNestedProperty(path: string[], state: any): any {
|
|
|
137
138
|
}
|
|
138
139
|
} else {
|
|
139
140
|
throw new Error(
|
|
140
|
-
`Invalid array index "${index}" in path "${path.join(
|
|
141
|
+
`Invalid array index "${index}" in path "${path.join('.')}".`
|
|
141
142
|
);
|
|
142
143
|
}
|
|
143
|
-
} else if (typeof state ===
|
|
144
|
+
} else if (typeof state === 'object' && state !== null) {
|
|
144
145
|
if (tail.length === 0) {
|
|
145
146
|
// Delete the property and return the new object
|
|
146
147
|
const { [head]: _, ...rest } = state;
|
|
@@ -152,30 +153,29 @@ export function deleteNestedProperty(path: string[], state: any): any {
|
|
|
152
153
|
};
|
|
153
154
|
} else {
|
|
154
155
|
throw new Error(
|
|
155
|
-
`Invalid property "${head}" in path "${path.join(
|
|
156
|
+
`Invalid property "${head}" in path "${path.join('.')}".`
|
|
156
157
|
);
|
|
157
158
|
}
|
|
158
159
|
} else {
|
|
159
160
|
throw new Error(
|
|
160
|
-
`Cannot delete nested property at path "${path.join(
|
|
161
|
+
`Cannot delete nested property at path "${path.join('.')}". The path does not exist.`
|
|
161
162
|
);
|
|
162
163
|
}
|
|
163
164
|
}
|
|
164
|
-
|
|
165
165
|
export function getNestedValue<TStateObject extends unknown>(
|
|
166
166
|
obj: TStateObject,
|
|
167
|
-
pathArray: string[]
|
|
167
|
+
pathArray: string[],
|
|
168
|
+
stateKey: string // <-- ADD THIS ARGUMENT
|
|
168
169
|
) {
|
|
169
170
|
let value: any = obj;
|
|
170
171
|
|
|
171
172
|
for (let i = 0; i < pathArray.length; i++) {
|
|
172
173
|
const key = pathArray[i]!;
|
|
173
174
|
if (value === undefined || value === null) {
|
|
174
|
-
// Cannot traverse further
|
|
175
175
|
return undefined;
|
|
176
176
|
}
|
|
177
177
|
|
|
178
|
-
if (typeof key ===
|
|
178
|
+
if (typeof key === 'string' && key.startsWith('id:')) {
|
|
179
179
|
if (!Array.isArray(value)) {
|
|
180
180
|
console.error("Path segment with 'id:' requires an array.", {
|
|
181
181
|
path: pathArray,
|
|
@@ -183,97 +183,61 @@ export function getNestedValue<TStateObject extends unknown>(
|
|
|
183
183
|
});
|
|
184
184
|
return undefined;
|
|
185
185
|
}
|
|
186
|
-
const targetId = key.split(":")[1];
|
|
187
|
-
value = value.find((item: any) => String(item.id) === targetId);
|
|
188
|
-
} else if (Array.isArray(value)) {
|
|
189
|
-
value = value[parseInt(key)];
|
|
190
|
-
} else {
|
|
191
|
-
value = value[key];
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
return value;
|
|
195
|
-
}
|
|
196
186
|
|
|
197
|
-
|
|
198
|
-
path: string[],
|
|
199
|
-
state: any,
|
|
200
|
-
newValue: any
|
|
201
|
-
) {
|
|
202
|
-
if (path.length === 0) {
|
|
203
|
-
return newValue;
|
|
204
|
-
}
|
|
187
|
+
// --- START OF THE SURGICAL FIX ---
|
|
205
188
|
|
|
206
|
-
|
|
207
|
-
|
|
189
|
+
// 1. Construct the FULL path of the item we are looking for.
|
|
190
|
+
const parentPath = pathArray.slice(0, i);
|
|
191
|
+
const fullItemPathToFind = [stateKey, ...parentPath, key].join('.');
|
|
208
192
|
|
|
209
|
-
|
|
210
|
-
|
|
193
|
+
// 2. Get the metadata for the PARENT array.
|
|
194
|
+
const parentShadowKey = [stateKey, ...parentPath].join('.');
|
|
195
|
+
const parentShadowMeta = getGlobalStore
|
|
196
|
+
.getState()
|
|
197
|
+
.shadowStateStore.get(parentShadowKey);
|
|
211
198
|
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
199
|
+
if (!parentShadowMeta?.arrayKeys) {
|
|
200
|
+
console.error(
|
|
201
|
+
'No arrayKeys found in shadow state for parent path:',
|
|
202
|
+
parentShadowKey
|
|
216
203
|
);
|
|
204
|
+
return undefined;
|
|
217
205
|
}
|
|
218
|
-
const targetId = key.split(":")[1];
|
|
219
|
-
const index = current.findIndex(
|
|
220
|
-
(item: any) => String(item.id) === targetId
|
|
221
|
-
);
|
|
222
206
|
|
|
223
|
-
|
|
224
|
-
|
|
207
|
+
// 3. Find the INDEX of the full item path in the parent's arrayKeys.
|
|
208
|
+
const itemIndex = parentShadowMeta.arrayKeys.indexOf(fullItemPathToFind);
|
|
209
|
+
|
|
210
|
+
if (itemIndex === -1) {
|
|
211
|
+
console.error(
|
|
212
|
+
`Item key ${fullItemPathToFind} not found in parent's arrayKeys:`,
|
|
213
|
+
parentShadowMeta.arrayKeys
|
|
214
|
+
);
|
|
215
|
+
return undefined;
|
|
225
216
|
}
|
|
226
|
-
// Create a copy of the object at the found index to avoid direct mutation
|
|
227
|
-
current[index] = { ...current[index] };
|
|
228
|
-
current = current[index];
|
|
229
|
-
} else {
|
|
230
|
-
// Create a copy of the object/array to avoid direct mutation
|
|
231
|
-
current[key] = Array.isArray(current[key])
|
|
232
|
-
? [...current[key]]
|
|
233
|
-
: { ...current[key] };
|
|
234
|
-
current = current[key];
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
217
|
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
);
|
|
247
|
-
}
|
|
248
|
-
const targetId = lastKey.split(":")[1];
|
|
249
|
-
const index = current.findIndex(
|
|
250
|
-
(item: any) => String(item.id) === targetId
|
|
251
|
-
);
|
|
252
|
-
if (index === -1) {
|
|
253
|
-
throw new Error(
|
|
254
|
-
`Item with id "${targetId}" not found in array to update.`
|
|
255
|
-
);
|
|
218
|
+
// 4. Use that index to get the item from the plain JS array.
|
|
219
|
+
value = value[itemIndex];
|
|
220
|
+
|
|
221
|
+
// --- END OF THE SURGICAL FIX ---
|
|
222
|
+
} else if (Array.isArray(value)) {
|
|
223
|
+
value = value[parseInt(key)];
|
|
224
|
+
} else {
|
|
225
|
+
value = value[key];
|
|
256
226
|
}
|
|
257
|
-
// Replace the item at its correct index
|
|
258
|
-
current[index] = newValue;
|
|
259
|
-
} else {
|
|
260
|
-
// This is the old logic, which works for normal properties.
|
|
261
|
-
current[lastKey] = newValue;
|
|
262
227
|
}
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
return newState;
|
|
228
|
+
return value;
|
|
266
229
|
}
|
|
230
|
+
|
|
267
231
|
type DifferencePaths = string[];
|
|
268
232
|
|
|
269
233
|
export function getDifferences(
|
|
270
234
|
obj1: any,
|
|
271
235
|
obj2: any,
|
|
272
|
-
currentPath: string =
|
|
236
|
+
currentPath: string = ''
|
|
273
237
|
): DifferencePaths {
|
|
274
238
|
let differences: DifferencePaths = [];
|
|
275
239
|
// Handling null and undefined cases
|
|
276
|
-
if (typeof obj1 ===
|
|
240
|
+
if (typeof obj1 === 'function' && typeof obj2 === 'function') {
|
|
277
241
|
return differences;
|
|
278
242
|
}
|
|
279
243
|
if (
|
|
@@ -290,7 +254,7 @@ export function getDifferences(
|
|
|
290
254
|
}
|
|
291
255
|
|
|
292
256
|
// Handling primitive types
|
|
293
|
-
if (typeof obj1 !==
|
|
257
|
+
if (typeof obj1 !== 'object' || typeof obj2 !== 'object') {
|
|
294
258
|
if (obj1 !== obj2) {
|
|
295
259
|
return [currentPath];
|
|
296
260
|
}
|
|
@@ -340,12 +304,29 @@ export function getDifferences(
|
|
|
340
304
|
});
|
|
341
305
|
return differences;
|
|
342
306
|
}
|
|
307
|
+
export function deepMerge(target: any, source: any): any {
|
|
308
|
+
const output = { ...target };
|
|
309
|
+
if (isObject(target) && isObject(source)) {
|
|
310
|
+
Object.keys(source).forEach((key) => {
|
|
311
|
+
if (isObject(source[key])) {
|
|
312
|
+
if (!(key in target)) {
|
|
313
|
+
Object.assign(output, { [key]: source[key] });
|
|
314
|
+
} else {
|
|
315
|
+
output[key] = deepMerge(target[key], source[key]);
|
|
316
|
+
}
|
|
317
|
+
} else {
|
|
318
|
+
Object.assign(output, { [key]: source[key] });
|
|
319
|
+
}
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
return output;
|
|
323
|
+
}
|
|
343
324
|
|
|
344
325
|
export function getDifferencesArray(obj1: any, obj2: any) {
|
|
345
326
|
const convertedDiff = getDifferences(obj1, obj2).map((string) =>
|
|
346
327
|
string
|
|
347
|
-
.replace(/\[(\w+)\]/g,
|
|
348
|
-
.split(
|
|
328
|
+
.replace(/\[(\w+)\]/g, '.$1')
|
|
329
|
+
.split('.')
|
|
349
330
|
.filter(Boolean)
|
|
350
331
|
);
|
|
351
332
|
|
|
@@ -354,7 +335,7 @@ export function getDifferencesArray(obj1: any, obj2: any) {
|
|
|
354
335
|
export function getArrayLengthDifferences(
|
|
355
336
|
obj1: any,
|
|
356
337
|
obj2: any,
|
|
357
|
-
currentPath: string =
|
|
338
|
+
currentPath: string = ''
|
|
358
339
|
): string[] {
|
|
359
340
|
let differences: string[] = [];
|
|
360
341
|
|
|
@@ -373,7 +354,7 @@ export function getArrayLengthDifferences(
|
|
|
373
354
|
if (obj1.length !== obj2.length) {
|
|
374
355
|
differences.push(currentPath);
|
|
375
356
|
}
|
|
376
|
-
} else if (typeof obj1 ===
|
|
357
|
+
} else if (typeof obj1 === 'object' && typeof obj2 === 'object') {
|
|
377
358
|
// Recursively check for nested arrays
|
|
378
359
|
const keys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);
|
|
379
360
|
for (const key of keys) {
|
|
@@ -394,8 +375,8 @@ export function getArrayLengthDifferences(
|
|
|
394
375
|
export function getArrayLengthDifferencesArray(obj1: any, obj2: any) {
|
|
395
376
|
const convertedDiff = getArrayLengthDifferences(obj1, obj2).map((string) =>
|
|
396
377
|
string
|
|
397
|
-
.replace(/\[(\w+)\]/g,
|
|
398
|
-
.split(
|
|
378
|
+
.replace(/\[(\w+)\]/g, '.$1')
|
|
379
|
+
.split('.')
|
|
399
380
|
.filter(Boolean)
|
|
400
381
|
);
|
|
401
382
|
|
|
@@ -405,7 +386,7 @@ export function getArrayLengthDifferencesArray(obj1: any, obj2: any) {
|
|
|
405
386
|
export function transformStateFunc<State extends unknown>(initialState: State) {
|
|
406
387
|
const isInitialStateType = (state: any): state is InitialStateType<State> => {
|
|
407
388
|
return Object.values(state).some((value) =>
|
|
408
|
-
value?.hasOwnProperty(
|
|
389
|
+
value?.hasOwnProperty('initialState')
|
|
409
390
|
);
|
|
410
391
|
};
|
|
411
392
|
let initalOptions: GenericObject = {};
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
import "react";
|
|
2
|
-
import { ZodArray as y, ZodObject as m, ZodOptional as f, ZodNullable as u, ZodEffects as l } from "zod";
|
|
3
|
-
import { create as w } from "zustand";
|
|
4
|
-
import "uuid";
|
|
5
|
-
import { getGlobalStore as g } from "./store.js";
|
|
6
|
-
w((t, o) => ({
|
|
7
|
-
results: {},
|
|
8
|
-
request: {},
|
|
9
|
-
getResultsByKey: (r) => o().results[r],
|
|
10
|
-
setResults: (r) => (n) => {
|
|
11
|
-
t((e) => ({
|
|
12
|
-
results: {
|
|
13
|
-
...e.results,
|
|
14
|
-
[r]: typeof n == "function" ? n(e.results[r]) : n
|
|
15
|
-
}
|
|
16
|
-
}));
|
|
17
|
-
},
|
|
18
|
-
setRequest: (r) => (n) => t((e) => ({
|
|
19
|
-
request: {
|
|
20
|
-
...e.request,
|
|
21
|
-
[r]: typeof n == "function" ? n(e.request[r]) : n
|
|
22
|
-
}
|
|
23
|
-
})),
|
|
24
|
-
getRequestsByKey: (r) => o().request[r]
|
|
25
|
-
}));
|
|
26
|
-
async function v(t, o, r, n) {
|
|
27
|
-
let e = o;
|
|
28
|
-
const d = g.getState().addValidationError;
|
|
29
|
-
for (const s of r)
|
|
30
|
-
if (e = c(e), e instanceof y) {
|
|
31
|
-
const i = Number(s);
|
|
32
|
-
if (!isNaN(i))
|
|
33
|
-
e = e.element;
|
|
34
|
-
else
|
|
35
|
-
throw new Error(`Invalid path: array index expected but got '${s}'.`);
|
|
36
|
-
} else if (e instanceof m)
|
|
37
|
-
if (s in e.shape)
|
|
38
|
-
e = e.shape[s];
|
|
39
|
-
else
|
|
40
|
-
throw new Error(`Invalid path: key '${s}' not found in schema.`);
|
|
41
|
-
else
|
|
42
|
-
throw new Error(`Invalid path: key '${s}' not found in schema.`);
|
|
43
|
-
e = c(e, !0);
|
|
44
|
-
const a = await e.safeParseAsync(n);
|
|
45
|
-
if (!a.success) {
|
|
46
|
-
const s = a.error.issues.map((p) => p.message).join(", "), i = [t, ...r].join(".");
|
|
47
|
-
return d(i, s), { success: !1, message: s };
|
|
48
|
-
}
|
|
49
|
-
return { success: !0, message: void 0 };
|
|
50
|
-
}
|
|
51
|
-
function c(t, o = !1) {
|
|
52
|
-
for (; t instanceof f || t instanceof u || !o && t instanceof l; )
|
|
53
|
-
t instanceof f || t instanceof u ? t = t.unwrap() : t instanceof l && (t = t._def.schema);
|
|
54
|
-
return t;
|
|
55
|
-
}
|
|
56
|
-
export {
|
|
57
|
-
v as validateZodPathFunc
|
|
58
|
-
};
|
|
59
|
-
//# sourceMappingURL=useValidateZodPath.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"useValidateZodPath.js","sources":["../src/useValidateZodPath.ts"],"sourcesContent":["import { useEffect, useState } from \"react\";\r\nimport {\r\n z,\r\n ZodArray,\r\n ZodEffects,\r\n ZodError,\r\n ZodNullable,\r\n ZodObject,\r\n ZodOptional,\r\n type SafeParseReturnType,\r\n type ZodRawShape,\r\n type ZodTypeAny,\r\n} from \"zod\";\r\nimport { create } from \"zustand\";\r\nimport { v4 as uuidv4 } from \"uuid\";\r\nimport { getGlobalStore } from \"./store\";\r\n\r\n// Your existing types and store\r\nexport type ResultItem = {\r\n status: \"loading\" | \"success\" | \"failure\" | \"error\";\r\n message?: string;\r\n};\r\ntype RequestType = Array<{ path: string[]; data: any; key: string }>;\r\n\r\ntype ResultsState = {\r\n results: Record<string, Record<string, ResultItem>>;\r\n request: Record<string, RequestType>;\r\n getResultsByKey: (key: string) => Record<string, ResultItem> | undefined;\r\n setResults: (\r\n key: string\r\n ) => (\r\n result:\r\n | Record<string, ResultItem>\r\n | ((prevState: Record<string, ResultItem>) => Record<string, ResultItem>)\r\n ) => void;\r\n setRequest: (\r\n key: string\r\n ) => (\r\n request: RequestType | ((prevState: RequestType) => RequestType)\r\n ) => void;\r\n getRequestsByKey: (\r\n key: string\r\n ) => Array<{ path: string[]; data: any; key: string }> | undefined;\r\n};\r\n\r\nexport const useResultsStore = create<ResultsState>((set, get) => ({\r\n results: {},\r\n request: {},\r\n getResultsByKey: (key) => get().results[key],\r\n setResults: (key) => (result) => {\r\n set((state) => {\r\n return {\r\n results: {\r\n ...state.results,\r\n [key]:\r\n typeof result === \"function\" ? result(state.results[key]!) : result,\r\n },\r\n };\r\n });\r\n },\r\n setRequest: (key) => (request) =>\r\n set((state) => ({\r\n request: {\r\n ...state.request,\r\n [key]:\r\n typeof request === \"function\"\r\n ? request(state.request[key]!)\r\n : request,\r\n },\r\n })),\r\n getRequestsByKey: (key) => get().request[key],\r\n}));\r\n\r\nexport default function useValidateZodPath<T extends ZodRawShape>(\r\n validationKey: string,\r\n schema: ZodObject<T>,\r\n stateKey?: string\r\n) {\r\n const [thisKey, setThisKey] = useState(stateKey ?? uuidv4());\r\n const [requests, setRequests] = useState<RequestType | undefined>(undefined);\r\n\r\n const [localResults, setLocalResults] = useState<Record<string, ResultItem>>(\r\n {}\r\n );\r\n const results = stateKey\r\n ? useResultsStore((state) => state.getResultsByKey(thisKey))\r\n : localResults;\r\n const setResults = stateKey\r\n ? useResultsStore.getState().setResults(thisKey)\r\n : setLocalResults;\r\n\r\n useEffect(() => {\r\n requests?.forEach(async ({ path, data, key }) => {\r\n setResults((prevResults) => ({\r\n ...prevResults,\r\n [key]: { status: \"loading\" },\r\n })); // prevResults is saying its any\r\n\r\n try {\r\n const response = await validateZodPathFunc(\r\n validationKey,\r\n schema,\r\n path,\r\n data\r\n );\r\n setResults((prevResults) => ({\r\n ...prevResults,\r\n [key]: {\r\n status: response.success ? \"success\" : \"failure\",\r\n message: response.success ? undefined : response.message, // Now just a string\r\n },\r\n }));\r\n } catch (error) {\r\n console.error(error);\r\n setResults((prevResults) => ({\r\n ...prevResults,\r\n [key]: {\r\n status: \"error\",\r\n message:\r\n error instanceof Error\r\n ? error.message\r\n : \"An unknown error occurred\",\r\n },\r\n }));\r\n }\r\n });\r\n\r\n // Clear requests after processing\r\n if (requests && requests.length > 0) {\r\n setRequests([]);\r\n }\r\n }, [requests, schema]);\r\n\r\n const validateZodPath = (\r\n path: string[],\r\n data: any,\r\n results?: Record<string, ResultItem> | undefined\r\n ) => {\r\n const pathKey = path.join(\".\");\r\n\r\n setResults((prevResults) => ({\r\n ...prevResults,\r\n [pathKey]: { status: \"loading\" },\r\n }));\r\n setRequests((prevRequests) => [\r\n ...(prevRequests ?? []),\r\n { path, data, key: pathKey },\r\n ]);\r\n\r\n return results?.[pathKey]?.status ?? \"loading\";\r\n };\r\n\r\n const getZodPathResults = (path: string[]) => {\r\n const pathKey = path.join(\".\");\r\n let endsWith = Object.keys(results ?? {}).filter(\r\n (key) =>\r\n key.endsWith(pathKey) && key.split(\".\").length === path.length + 1\r\n );\r\n\r\n return results?.[pathKey] ?? endsWith ?? null;\r\n };\r\n\r\n return { validateZodPath, getZodPathResults, zodPathResults: results };\r\n}\r\n\r\nexport async function validateZodPathFunc<T extends ZodRawShape, U>(\r\n validationKey: string,\r\n schema: ZodTypeAny,\r\n path: string[],\r\n data: U\r\n): Promise<{ success: boolean; message?: string }> {\r\n let currentSchema: ZodTypeAny = schema;\r\n const addValidationError = getGlobalStore.getState().addValidationError;\r\n\r\n for (const key of path) {\r\n currentSchema = unwrapSchema(currentSchema);\r\n\r\n if (currentSchema instanceof ZodArray) {\r\n const index = Number(key);\r\n if (!isNaN(index)) {\r\n currentSchema = currentSchema.element;\r\n } else {\r\n throw new Error(`Invalid path: array index expected but got '${key}'.`);\r\n }\r\n } else if (currentSchema instanceof ZodObject) {\r\n if (key in currentSchema.shape) {\r\n currentSchema = currentSchema.shape[key];\r\n } else {\r\n throw new Error(`Invalid path: key '${key}' not found in schema.`);\r\n }\r\n } else {\r\n throw new Error(`Invalid path: key '${key}' not found in schema.`);\r\n }\r\n }\r\n\r\n // Ensure the final schema is fully unwrapped\r\n currentSchema = unwrapSchema(currentSchema, true);\r\n // Now currentSchema should be the schema at the end of the path, and we can validate.\r\n const result: SafeParseReturnType<any, any> =\r\n await currentSchema.safeParseAsync(data);\r\n\r\n if (!result.success) {\r\n const messages = result.error.issues\r\n .map((issue) => issue.message)\r\n .join(\", \");\r\n\r\n const fullErrorPath = [validationKey, ...path].join(\".\");\r\n addValidationError(fullErrorPath, messages);\r\n return { success: false, message: messages };\r\n }\r\n\r\n return { success: true, message: undefined };\r\n}\r\n\r\nfunction unwrapSchema(\r\n schema: ZodTypeAny,\r\n notEffects: boolean = false\r\n): ZodTypeAny {\r\n while (\r\n schema instanceof ZodOptional ||\r\n schema instanceof ZodNullable ||\r\n (!notEffects && schema instanceof ZodEffects)\r\n ) {\r\n if (schema instanceof ZodOptional || schema instanceof ZodNullable) {\r\n schema = schema.unwrap();\r\n } else if (schema instanceof ZodEffects) {\r\n schema = schema._def.schema;\r\n }\r\n }\r\n return schema;\r\n}\r\n"],"names":["create","set","get","key","result","state","request","validateZodPathFunc","validationKey","schema","path","data","currentSchema","addValidationError","getGlobalStore","unwrapSchema","ZodArray","index","ZodObject","messages","issue","fullErrorPath","notEffects","ZodOptional","ZodNullable","ZodEffects"],"mappings":";;;;;AA6C+BA,EAAqB,CAACC,GAAKC,OAAS;AAAA,EACjE,SAAS,CAAC;AAAA,EACV,SAAS,CAAC;AAAA,EACV,iBAAiB,CAACC,MAAQD,EAAI,EAAE,QAAQC,CAAG;AAAA,EAC3C,YAAY,CAACA,MAAQ,CAACC,MAAW;AAC/B,IAAAH,EAAI,CAACI,OACI;AAAA,MACL,SAAS;AAAA,QACP,GAAGA,EAAM;AAAA,QACT,CAACF,CAAG,GACF,OAAOC,KAAW,aAAaA,EAAOC,EAAM,QAAQF,CAAG,CAAE,IAAIC;AAAA,MAAA;AAAA,IAEnE,EACD;AAAA,EACH;AAAA,EACA,YAAY,CAACD,MAAQ,CAACG,MACpBL,EAAI,CAACI,OAAW;AAAA,IACd,SAAS;AAAA,MACP,GAAGA,EAAM;AAAA,MACT,CAACF,CAAG,GACF,OAAOG,KAAY,aACfA,EAAQD,EAAM,QAAQF,CAAG,CAAE,IAC3BG;AAAA,IAAA;AAAA,EACR,EACA;AAAA,EACJ,kBAAkB,CAACH,MAAQD,EAAI,EAAE,QAAQC,CAAG;AAC9C,EAAE;AA8FF,eAAsBI,EACpBC,GACAC,GACAC,GACAC,GACiD;AACjD,MAAIC,IAA4BH;AAC1B,QAAAI,IAAqBC,EAAe,SAAA,EAAW;AAErD,aAAWX,KAAOO;AAGhB,QAFAE,IAAgBG,EAAaH,CAAa,GAEtCA,aAAyBI,GAAU;AAC/B,YAAAC,IAAQ,OAAOd,CAAG;AACpB,UAAA,CAAC,MAAMc,CAAK;AACd,QAAAL,IAAgBA,EAAc;AAAA;AAE9B,cAAM,IAAI,MAAM,+CAA+CT,CAAG,IAAI;AAAA,IACxE,WACSS,aAAyBM;AAC9B,UAAAf,KAAOS,EAAc;AACP,QAAAA,IAAAA,EAAc,MAAMT,CAAG;AAAA;AAEvC,cAAM,IAAI,MAAM,sBAAsBA,CAAG,wBAAwB;AAAA;AAGnE,YAAM,IAAI,MAAM,sBAAsBA,CAAG,wBAAwB;AAKrD,EAAAS,IAAAG,EAAaH,GAAe,EAAI;AAEhD,QAAMR,IACJ,MAAMQ,EAAc,eAAeD,CAAI;AAErC,MAAA,CAACP,EAAO,SAAS;AACb,UAAAe,IAAWf,EAAO,MAAM,OAC3B,IAAI,CAACgB,MAAUA,EAAM,OAAO,EAC5B,KAAK,IAAI,GAENC,IAAgB,CAACb,GAAe,GAAGE,CAAI,EAAE,KAAK,GAAG;AACvD,WAAAG,EAAmBQ,GAAeF,CAAQ,GACnC,EAAE,SAAS,IAAO,SAASA,EAAS;AAAA,EAAA;AAG7C,SAAO,EAAE,SAAS,IAAM,SAAS,OAAU;AAC7C;AAEA,SAASJ,EACPN,GACAa,IAAsB,IACV;AACZ,SACEb,aAAkBc,KAClBd,aAAkBe,KACjB,CAACF,KAAcb,aAAkBgB;AAE9B,IAAAhB,aAAkBc,KAAed,aAAkBe,IACrDf,IAASA,EAAO,OAAO,IACdA,aAAkBgB,MAC3BhB,IAASA,EAAO,KAAK;AAGlB,SAAAA;AACT;"}
|