@ivlev-dev/silent-validation 0.0.0-stage → 0.13.0

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.
Files changed (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +573 -2
  3. package/dist/engine.d.ts +15 -0
  4. package/dist/engine.d.ts.map +1 -0
  5. package/dist/engine.js +967 -0
  6. package/dist/engine.js.map +1 -0
  7. package/dist/index.d.ts +15 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +13 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/messages.d.ts +17 -0
  12. package/dist/messages.d.ts.map +1 -0
  13. package/dist/messages.js +508 -0
  14. package/dist/messages.js.map +1 -0
  15. package/dist/model.d.ts +3 -0
  16. package/dist/model.d.ts.map +1 -0
  17. package/dist/model.js +3 -0
  18. package/dist/model.js.map +1 -0
  19. package/dist/modifiers.d.ts +7 -0
  20. package/dist/modifiers.d.ts.map +1 -0
  21. package/dist/modifiers.js +58 -0
  22. package/dist/modifiers.js.map +1 -0
  23. package/dist/property.d.ts +3 -0
  24. package/dist/property.d.ts.map +1 -0
  25. package/dist/property.js +42 -0
  26. package/dist/property.js.map +1 -0
  27. package/dist/registry.d.ts +11 -0
  28. package/dist/registry.d.ts.map +1 -0
  29. package/dist/registry.js +187 -0
  30. package/dist/registry.js.map +1 -0
  31. package/dist/rule.d.ts +7 -0
  32. package/dist/rule.d.ts.map +1 -0
  33. package/dist/rule.js +34 -0
  34. package/dist/rule.js.map +1 -0
  35. package/dist/rules/collections.d.ts +54 -0
  36. package/dist/rules/collections.d.ts.map +1 -0
  37. package/dist/rules/collections.js +116 -0
  38. package/dist/rules/collections.js.map +1 -0
  39. package/dist/rules/comparison.d.ts +36 -0
  40. package/dist/rules/comparison.d.ts.map +1 -0
  41. package/dist/rules/comparison.js +45 -0
  42. package/dist/rules/comparison.js.map +1 -0
  43. package/dist/rules/custom.d.ts +10 -0
  44. package/dist/rules/custom.d.ts.map +1 -0
  45. package/dist/rules/custom.js +12 -0
  46. package/dist/rules/custom.js.map +1 -0
  47. package/dist/rules/numbers.d.ts +61 -0
  48. package/dist/rules/numbers.d.ts.map +1 -0
  49. package/dist/rules/numbers.js +90 -0
  50. package/dist/rules/numbers.js.map +1 -0
  51. package/dist/rules/presence.d.ts +34 -0
  52. package/dist/rules/presence.d.ts.map +1 -0
  53. package/dist/rules/presence.js +66 -0
  54. package/dist/rules/presence.js.map +1 -0
  55. package/dist/rules/strings.d.ts +102 -0
  56. package/dist/rules/strings.d.ts.map +1 -0
  57. package/dist/rules/strings.js +234 -0
  58. package/dist/rules/strings.js.map +1 -0
  59. package/dist/rules/types.d.ts +76 -0
  60. package/dist/rules/types.d.ts.map +1 -0
  61. package/dist/rules/types.js +128 -0
  62. package/dist/rules/types.js.map +1 -0
  63. package/dist/schema.d.ts +11 -0
  64. package/dist/schema.d.ts.map +1 -0
  65. package/dist/schema.js +147 -0
  66. package/dist/schema.js.map +1 -0
  67. package/dist/thenable.d.ts +4 -0
  68. package/dist/thenable.d.ts.map +1 -0
  69. package/dist/thenable.js +16 -0
  70. package/dist/thenable.js.map +1 -0
  71. package/dist/type-validation.d.ts +44 -0
  72. package/dist/type-validation.d.ts.map +1 -0
  73. package/dist/type-validation.js +850 -0
  74. package/dist/type-validation.js.map +1 -0
  75. package/dist/types.d.ts +113 -0
  76. package/dist/types.d.ts.map +1 -0
  77. package/dist/types.js +22 -0
  78. package/dist/types.js.map +1 -0
  79. package/package.json +49 -3
package/dist/engine.js ADDED
@@ -0,0 +1,967 @@
1
+ import { DEFAULT_LOCALE, getValidationConfig, resolveMessage, resolveMessageAsync } from "./messages.js";
2
+ import { constructorOf, readFieldValue } from "./property.js";
3
+ import { classStateRevision, validationStateFor } from "./registry.js";
4
+ import { readInstanceSchema } from "./schema.js";
5
+ import { isThenable, suppress } from "./thenable.js";
6
+ import { MAX_DEPTH, validateFastPrimitive, validateType } from "./type-validation.js";
7
+ import { AsyncRuleError, ValidationException } from "./types.js";
8
+ const planCache = new WeakMap();
9
+ let planBuildCount = 0;
10
+ /** @internal Диагностический счётчик построений плана полей (для тестов). */
11
+ export function validationPlanBuilds() {
12
+ return planBuildCount;
13
+ }
14
+ const EMPTY_NESTED = [];
15
+ function assertInstance(instance) {
16
+ if (typeof instance !== "object" || instance === null) {
17
+ throw new TypeError("Валидируемое значение должно быть объектом");
18
+ }
19
+ if (Array.isArray(instance) && constructorOf(instance) === Array) {
20
+ throw new TypeError("Валидируемое значение должно быть объектом");
21
+ }
22
+ }
23
+ function createConfig(options) {
24
+ const base = getValidationConfig();
25
+ if (options === undefined) {
26
+ return base;
27
+ }
28
+ const locale = options.locale ?? base.locale;
29
+ const resolve = options.resolve ?? base.resolve;
30
+ const messages = options.messages ?? base.messages;
31
+ const cascade = options.cascade ?? base.cascade;
32
+ return {
33
+ ...(locale === undefined ? {} : { locale }),
34
+ ...(resolve === undefined ? {} : { resolve }),
35
+ ...(messages === undefined ? {} : { messages }),
36
+ ...(cascade === undefined ? {} : { cascade }),
37
+ };
38
+ }
39
+ function createState(options) {
40
+ const config = createConfig(options);
41
+ return {
42
+ errors: [],
43
+ config,
44
+ locale: config.locale ?? DEFAULT_LOCALE,
45
+ labels: options?.labels,
46
+ callGroups: options?.groups,
47
+ stopAtFirst: options?.stopAtFirst === true,
48
+ cascade: options?.cascade ?? config.cascade ?? true,
49
+ types: options?.types !== false,
50
+ visiting: new WeakSet(),
51
+ nestedSeen: undefined,
52
+ runtime: undefined,
53
+ stopped: false,
54
+ };
55
+ }
56
+ function toItems(value) {
57
+ if (Array.isArray(value)) {
58
+ return value;
59
+ }
60
+ if (value instanceof Set) {
61
+ return Array.from(value);
62
+ }
63
+ return undefined;
64
+ }
65
+ function isNestedObject(value) {
66
+ return typeof value === "object" && value !== null && !Array.isArray(value);
67
+ }
68
+ function groupsMatch(ruleGroups, callGroups) {
69
+ if (callGroups === undefined || callGroups.length === 0) {
70
+ return true;
71
+ }
72
+ if (ruleGroups === undefined || ruleGroups.length === 0) {
73
+ return true;
74
+ }
75
+ return ruleGroups.some((group) => callGroups.includes(group));
76
+ }
77
+ function rootPathSegment(path) {
78
+ let index = 0;
79
+ while (index < path.length) {
80
+ const char = path[index];
81
+ if (char === "." || char === "[") {
82
+ break;
83
+ }
84
+ index += 1;
85
+ }
86
+ return path.slice(0, index);
87
+ }
88
+ function labelAtPath(labels, fieldName, path) {
89
+ if (labels === undefined) {
90
+ return undefined;
91
+ }
92
+ if (Object.hasOwn(labels, path)) {
93
+ const exact = labels[path];
94
+ if (typeof exact === "string") {
95
+ return exact;
96
+ }
97
+ }
98
+ if (path !== fieldName && rootPathSegment(path) !== fieldName) {
99
+ return undefined;
100
+ }
101
+ if (!Object.hasOwn(labels, fieldName)) {
102
+ return undefined;
103
+ }
104
+ const short = labels[fieldName];
105
+ return typeof short === "string" ? short : undefined;
106
+ }
107
+ function labelOf(call) {
108
+ return (call.entry.options.label
109
+ ?? call.slot.label
110
+ ?? labelAtPath(call.state.labels, call.slot.fieldName, call.path)
111
+ ?? call.slot.fieldName);
112
+ }
113
+ function buildMessage(call, label) {
114
+ return resolveMessage(messageContext(call, label), call.state.config);
115
+ }
116
+ async function buildMessageAsync(call, label) {
117
+ return resolveMessageAsync(messageContext(call, label), call.state.config);
118
+ }
119
+ function messageContext(call, label) {
120
+ const rule = call.entry.rule;
121
+ const options = call.entry.options;
122
+ const messageKey = options.messageKey
123
+ ?? (rule.name === "each" && call.index === undefined
124
+ ? "validation.eachValue"
125
+ : undefined);
126
+ return {
127
+ rule: rule.name,
128
+ key: `validation.${rule.name}`,
129
+ field: call.slot.fieldName,
130
+ label,
131
+ value: call.value,
132
+ params: rule.params,
133
+ locale: call.state.locale,
134
+ instance: call.target,
135
+ path: call.path,
136
+ ...(call.index === undefined ? {} : { index: call.index }),
137
+ ...(options.message === undefined ? {} : { message: options.message }),
138
+ ...(messageKey === undefined ? {} : { messageKey }),
139
+ };
140
+ }
141
+ function createError(call) {
142
+ const label = labelOf(call);
143
+ return {
144
+ field: call.slot.fieldName,
145
+ rule: call.entry.rule.name,
146
+ message: buildMessage(call, label),
147
+ params: call.entry.rule.params,
148
+ value: call.value,
149
+ path: call.path,
150
+ label,
151
+ ...(call.index === undefined ? {} : { index: call.index }),
152
+ };
153
+ }
154
+ async function createErrorAsync(call) {
155
+ const label = labelOf(call);
156
+ return {
157
+ field: call.slot.fieldName,
158
+ rule: call.entry.rule.name,
159
+ message: await buildMessageAsync(call, label),
160
+ params: call.entry.rule.params,
161
+ value: call.value,
162
+ path: call.path,
163
+ label,
164
+ ...(call.index === undefined ? {} : { index: call.index }),
165
+ };
166
+ }
167
+ function pushError(call) {
168
+ call.state.errors.push(createError(call));
169
+ if (call.state.stopAtFirst) {
170
+ call.state.stopped = true;
171
+ }
172
+ }
173
+ async function pushErrorAsync(call) {
174
+ call.state.errors.push(await createErrorAsync(call));
175
+ if (call.state.stopAtFirst) {
176
+ call.state.stopped = true;
177
+ }
178
+ }
179
+ function withoutResolver(config) {
180
+ return {
181
+ ...(config.locale === undefined ? {} : { locale: config.locale }),
182
+ ...(config.messages === undefined ? {} : { messages: config.messages }),
183
+ ...(config.cascade === undefined ? {} : { cascade: config.cascade }),
184
+ };
185
+ }
186
+ async function resolveErrorAsync(error, target, state) {
187
+ const key = `validation.${error.rule}`;
188
+ const context = {
189
+ rule: error.rule,
190
+ key,
191
+ field: error.field,
192
+ label: error.label,
193
+ value: error.value,
194
+ params: error.params,
195
+ locale: state.locale,
196
+ instance: target,
197
+ path: error.path,
198
+ ...(error.index === undefined ? {} : { index: error.index }),
199
+ };
200
+ return {
201
+ ...error,
202
+ message: await resolveMessageAsync(context, state.config),
203
+ };
204
+ }
205
+ async function rerenderErrorsAsync(state, start, target) {
206
+ for (let index = start; index < state.errors.length; index += 1) {
207
+ const error = state.errors[index];
208
+ if (error === undefined) {
209
+ continue;
210
+ }
211
+ state.errors[index] = await resolveErrorAsync(error, target, state);
212
+ }
213
+ }
214
+ function createRunContext(call) {
215
+ return {
216
+ instance: call.target,
217
+ field: call.slot.fieldName,
218
+ label: labelOf(call),
219
+ path: call.path,
220
+ params: call.entry.rule.params,
221
+ };
222
+ }
223
+ function evaluateSync(check, value, call) {
224
+ const result = check(value, createRunContext(call));
225
+ if (isThenable(result)) {
226
+ suppress(result);
227
+ throw new AsyncRuleError(call.slot.fieldName, call.entry.rule.name);
228
+ }
229
+ return result === true;
230
+ }
231
+ async function evaluateAsync(check, value, call) {
232
+ return (await check(value, createRunContext(call))) === true;
233
+ }
234
+ function isRunnable(entry, slot, target, state) {
235
+ if (entry.options.when !== undefined) {
236
+ const condition = entry.options.when(target);
237
+ if (isThenable(condition)) {
238
+ suppress(condition);
239
+ throw new AsyncRuleError(slot.fieldName, "when");
240
+ }
241
+ if (!condition) {
242
+ return false;
243
+ }
244
+ }
245
+ return groupsMatch(entry.options.groups ?? slot.groups, state.callGroups);
246
+ }
247
+ async function isRunnableAsync(entry, slot, target, state) {
248
+ if (entry.options.when !== undefined) {
249
+ const condition = entry.options.when(target);
250
+ const runnable = isThenable(condition) ? await condition : condition;
251
+ if (!runnable) {
252
+ return false;
253
+ }
254
+ }
255
+ return groupsMatch(entry.options.groups ?? slot.groups, state.callGroups);
256
+ }
257
+ function callFor(target, slot, entry, value, path, index, state) {
258
+ return { target, slot, entry, value, path, index, state };
259
+ }
260
+ function fieldPlan(target, withSchema) {
261
+ const ctor = constructorOf(target);
262
+ if (ctor === null) {
263
+ return buildFieldPlan(target, withSchema);
264
+ }
265
+ const revision = classStateRevision(ctor);
266
+ const schema = withSchema ? readInstanceSchema(target) : undefined;
267
+ let cached = planCache.get(ctor);
268
+ if (cached === undefined || cached.revision !== revision) {
269
+ cached = { revision, schema, withSchema: undefined, plain: undefined };
270
+ planCache.set(ctor, cached);
271
+ }
272
+ else if (withSchema && cached.schema !== schema) {
273
+ cached = { ...cached, schema, withSchema: undefined };
274
+ planCache.set(ctor, cached);
275
+ }
276
+ const existing = withSchema ? cached.withSchema : cached.plain;
277
+ if (existing !== undefined) {
278
+ return existing;
279
+ }
280
+ const built = buildFieldPlan(target, withSchema, schema);
281
+ cached = {
282
+ revision,
283
+ schema: withSchema ? schema : cached.schema,
284
+ withSchema: withSchema ? built : cached.withSchema,
285
+ plain: withSchema ? cached.plain : built,
286
+ };
287
+ planCache.set(ctor, cached);
288
+ return built;
289
+ }
290
+ function buildFieldPlan(target, withSchema, schema = undefined) {
291
+ planBuildCount += 1;
292
+ const fields = constructorOf(target) === null
293
+ ? undefined
294
+ : validationStateFor(target).fields;
295
+ const byName = new Map();
296
+ if (fields !== undefined) {
297
+ for (const slot of fields.values()) {
298
+ if (typeof slot.field === "string" && !byName.has(slot.fieldName)) {
299
+ byName.set(slot.fieldName, slot);
300
+ }
301
+ }
302
+ }
303
+ const plan = [];
304
+ const used = new Set();
305
+ if (withSchema) {
306
+ const resolved = schema === undefined ? readInstanceSchema(target) : schema;
307
+ if (resolved !== null) {
308
+ for (const [name, typeSchema] of Object.entries(resolved)) {
309
+ const slot = byName.get(name);
310
+ if (slot !== undefined && fields !== undefined) {
311
+ for (const candidate of fields.values()) {
312
+ if (typeof candidate.field === "string" && candidate.fieldName === name) {
313
+ used.add(candidate);
314
+ }
315
+ }
316
+ }
317
+ plan.push({
318
+ key: slot?.field ?? name,
319
+ fieldName: name,
320
+ slot,
321
+ schema: typeSchema,
322
+ });
323
+ }
324
+ }
325
+ }
326
+ if (fields !== undefined) {
327
+ for (const slot of fields.values()) {
328
+ if (used.has(slot)) {
329
+ continue;
330
+ }
331
+ plan.push({
332
+ key: slot.field,
333
+ fieldName: slot.fieldName,
334
+ slot,
335
+ schema: undefined,
336
+ });
337
+ }
338
+ }
339
+ return plan;
340
+ }
341
+ function schemaSkips(schema, value) {
342
+ let current = schema;
343
+ while (Array.isArray(current)) {
344
+ const tag = current[0];
345
+ if (tag === "optional" && value === undefined) {
346
+ return true;
347
+ }
348
+ if (tag === "nullable" && value === null) {
349
+ return true;
350
+ }
351
+ if (tag !== "optional" && tag !== "nullable") {
352
+ return false;
353
+ }
354
+ current = current[1];
355
+ }
356
+ return false;
357
+ }
358
+ function depthLocation(prefix, state) {
359
+ const path = prefix.endsWith(".") ? prefix.slice(0, -1) : prefix;
360
+ const base = path.replace(/(?:\[[^\]]*\])+$/, "");
361
+ const dot = base.lastIndexOf(".");
362
+ const field = dot >= 0 ? base.slice(dot + 1) : base;
363
+ const label = labelAtPath(state.labels, field, path) ?? field;
364
+ return { field, label, path };
365
+ }
366
+ function depthMessageContext(target, location, state) {
367
+ return {
368
+ rule: "type",
369
+ key: "validation.depth",
370
+ field: location.field,
371
+ label: location.label,
372
+ value: target,
373
+ params: { type: "depth" },
374
+ locale: state.locale,
375
+ instance: target,
376
+ path: location.path,
377
+ };
378
+ }
379
+ function depthErrorSync(target, prefix, state) {
380
+ const location = depthLocation(prefix, state);
381
+ return {
382
+ field: location.field,
383
+ rule: "type",
384
+ message: resolveMessage(depthMessageContext(target, location, state), state.config),
385
+ params: { type: "depth" },
386
+ value: target,
387
+ path: location.path,
388
+ label: location.label,
389
+ };
390
+ }
391
+ async function depthErrorAsync(target, prefix, state) {
392
+ const location = depthLocation(prefix, state);
393
+ return {
394
+ field: location.field,
395
+ rule: "type",
396
+ message: await resolveMessageAsync(depthMessageContext(target, location, state), state.config),
397
+ params: { type: "depth" },
398
+ value: target,
399
+ path: location.path,
400
+ label: location.label,
401
+ };
402
+ }
403
+ function pushDepthSync(target, prefix, state) {
404
+ state.errors.push(depthErrorSync(target, prefix, state));
405
+ if (state.stopAtFirst) {
406
+ state.stopped = true;
407
+ }
408
+ }
409
+ async function pushDepthAsync(target, prefix, state) {
410
+ state.errors.push(await depthErrorAsync(target, prefix, state));
411
+ if (state.stopAtFirst) {
412
+ state.stopped = true;
413
+ }
414
+ }
415
+ function uniqueNested(entries) {
416
+ if (entries.length <= 1) {
417
+ return entries;
418
+ }
419
+ const seen = new Map();
420
+ const unique = [];
421
+ for (const entry of entries) {
422
+ let paths = seen.get(entry.instance);
423
+ if (paths === undefined) {
424
+ paths = new Set();
425
+ seen.set(entry.instance, paths);
426
+ }
427
+ if (paths.has(entry.path)) {
428
+ continue;
429
+ }
430
+ paths.add(entry.path);
431
+ unique.push(entry);
432
+ }
433
+ return unique;
434
+ }
435
+ function completeFieldPreparation(target, run, value, path, state, asyncTypes) {
436
+ const slot = run.slot;
437
+ if (state.types && run.schema !== undefined && !schemaSkips(run.schema, value)) {
438
+ const typeConfig = asyncTypes && state.config.resolve !== undefined
439
+ ? withoutResolver(state.config)
440
+ : state.config;
441
+ const label = slot?.label
442
+ ?? labelAtPath(state.labels, run.fieldName, path)
443
+ ?? run.fieldName;
444
+ let nested = EMPTY_NESTED;
445
+ let failed = false;
446
+ const fast = validateFastPrimitive(value, run.schema, {
447
+ instance: target,
448
+ field: run.fieldName,
449
+ label,
450
+ path,
451
+ config: typeConfig,
452
+ labels: state.labels,
453
+ });
454
+ if (fast !== undefined) {
455
+ if (fast !== null) {
456
+ failed = true;
457
+ state.errors.push(fast);
458
+ }
459
+ }
460
+ else {
461
+ const collected = [];
462
+ const runtime = state.runtime ??= { visiting: state.visiting };
463
+ const result = validateType(value, run.schema, {
464
+ instance: target,
465
+ field: run.fieldName,
466
+ label,
467
+ path,
468
+ config: typeConfig,
469
+ labels: state.labels,
470
+ runtime,
471
+ nested: collected,
472
+ stopAtFirst: state.stopAtFirst,
473
+ });
474
+ if (result !== null) {
475
+ failed = true;
476
+ const errors = Array.isArray(result) ? result : [result];
477
+ const limit = state.stopAtFirst ? 1 : errors.length;
478
+ for (let index = 0; index < limit; index += 1) {
479
+ const error = errors[index];
480
+ if (error !== undefined) {
481
+ state.errors.push(error);
482
+ }
483
+ }
484
+ }
485
+ nested = uniqueNested(collected);
486
+ }
487
+ if (state.stopAtFirst && failed) {
488
+ state.stopped = true;
489
+ return null;
490
+ }
491
+ if (failed && !state.cascade) {
492
+ return null;
493
+ }
494
+ return { value, path, nested };
495
+ }
496
+ return { value, path, nested: EMPTY_NESTED };
497
+ }
498
+ function prepareField(target, run, prefix, state) {
499
+ const value = readFieldValue(target, run.key);
500
+ const slot = run.slot;
501
+ if (slot !== undefined && slot.optional && (value === null || value === undefined)) {
502
+ return null;
503
+ }
504
+ if (slot !== undefined) {
505
+ for (const condition of slot.conditions) {
506
+ const result = condition(target, value);
507
+ if (isThenable(result)) {
508
+ suppress(result);
509
+ throw new AsyncRuleError(slot.fieldName, "validateIf");
510
+ }
511
+ if (result !== true) {
512
+ return null;
513
+ }
514
+ }
515
+ }
516
+ const path = `${prefix}${run.fieldName}`;
517
+ if (state.types && run.schema !== undefined && !schemaSkips(run.schema, value)) {
518
+ const label = slot?.label
519
+ ?? labelAtPath(state.labels, run.fieldName, path)
520
+ ?? run.fieldName;
521
+ let nested = EMPTY_NESTED;
522
+ let failed = false;
523
+ const fast = validateFastPrimitive(value, run.schema, {
524
+ instance: target,
525
+ field: run.fieldName,
526
+ label,
527
+ path,
528
+ config: state.config,
529
+ labels: state.labels,
530
+ });
531
+ if (fast !== undefined) {
532
+ if (fast !== null) {
533
+ failed = true;
534
+ state.errors.push(fast);
535
+ }
536
+ }
537
+ else {
538
+ const collected = [];
539
+ const runtime = state.runtime ??= { visiting: state.visiting };
540
+ const result = validateType(value, run.schema, {
541
+ instance: target,
542
+ field: run.fieldName,
543
+ label,
544
+ path,
545
+ config: state.config,
546
+ labels: state.labels,
547
+ runtime,
548
+ nested: collected,
549
+ stopAtFirst: state.stopAtFirst,
550
+ });
551
+ if (result !== null) {
552
+ failed = true;
553
+ const errors = Array.isArray(result) ? result : [result];
554
+ const limit = state.stopAtFirst ? 1 : errors.length;
555
+ for (let index = 0; index < limit; index += 1) {
556
+ const error = errors[index];
557
+ if (error !== undefined) {
558
+ state.errors.push(error);
559
+ }
560
+ }
561
+ }
562
+ nested = uniqueNested(collected);
563
+ }
564
+ if (state.stopAtFirst && failed) {
565
+ state.stopped = true;
566
+ return null;
567
+ }
568
+ if (failed && !state.cascade) {
569
+ return null;
570
+ }
571
+ return { value, path, nested };
572
+ }
573
+ return { value, path, nested: EMPTY_NESTED };
574
+ }
575
+ async function prepareFieldAsync(target, run, prefix, state) {
576
+ const value = readFieldValue(target, run.key);
577
+ const slot = run.slot;
578
+ if (slot !== undefined && slot.optional && (value === null || value === undefined)) {
579
+ return null;
580
+ }
581
+ const path = `${prefix}${run.fieldName}`;
582
+ if (slot !== undefined) {
583
+ for (const condition of slot.conditions) {
584
+ const result = condition(target, value);
585
+ if (isThenable(result)) {
586
+ if ((await result) !== true) {
587
+ return null;
588
+ }
589
+ }
590
+ else if (result !== true) {
591
+ return null;
592
+ }
593
+ }
594
+ }
595
+ return completeFieldPreparation(target, run, value, path, state, true);
596
+ }
597
+ function shouldVisitNested(instance, path, state) {
598
+ const nestedSeen = state.nestedSeen ??= new WeakMap();
599
+ const seen = nestedSeen.get(instance);
600
+ if (seen?.has(path) === true) {
601
+ return false;
602
+ }
603
+ if (seen === undefined) {
604
+ nestedSeen.set(instance, new Set([path]));
605
+ }
606
+ else {
607
+ seen.add(path);
608
+ }
609
+ return true;
610
+ }
611
+ function runNestedSync(nested, state, depth) {
612
+ for (const entry of nested) {
613
+ if (state.stopped) {
614
+ return;
615
+ }
616
+ const path = `${entry.path}.`;
617
+ if (!shouldVisitNested(entry.instance, path, state)) {
618
+ continue;
619
+ }
620
+ runInstanceSync(entry.instance, path, state, depth);
621
+ }
622
+ }
623
+ async function runNestedAsync(nested, state, depth) {
624
+ for (const entry of nested) {
625
+ if (state.stopped) {
626
+ return;
627
+ }
628
+ const path = `${entry.path}.`;
629
+ if (!shouldVisitNested(entry.instance, path, state)) {
630
+ continue;
631
+ }
632
+ await runInstanceAsync(entry.instance, path, state, depth);
633
+ }
634
+ }
635
+ function runFieldSync(target, run, prefix, state, depth) {
636
+ const prepared = prepareField(target, run, prefix, state);
637
+ if (prepared === null) {
638
+ return;
639
+ }
640
+ if (prepared.nested.length > 0) {
641
+ runNestedSync(prepared.nested, state, depth + 1);
642
+ if (state.stopped) {
643
+ return;
644
+ }
645
+ }
646
+ const slot = run.slot;
647
+ if (slot === undefined) {
648
+ return;
649
+ }
650
+ for (let index = slot.rules.length - 1; index >= 0; index -= 1) {
651
+ if (state.stopped) {
652
+ return;
653
+ }
654
+ const entry = slot.rules[index];
655
+ if (entry === undefined) {
656
+ continue;
657
+ }
658
+ runRuleSync(target, slot, entry, prepared.value, prepared.path, state, depth);
659
+ }
660
+ }
661
+ function runRuleSync(target, slot, entry, value, path, state, depth) {
662
+ if (!isRunnable(entry, slot, target, state)) {
663
+ return;
664
+ }
665
+ const rule = entry.rule;
666
+ if (entry.options.each === true) {
667
+ const items = toItems(value);
668
+ if (items === undefined) {
669
+ pushError(callFor(target, slot, entry, value, path, undefined, state));
670
+ return;
671
+ }
672
+ for (let index = 0; index < items.length; index += 1) {
673
+ if (state.stopped) {
674
+ return;
675
+ }
676
+ const item = items[index];
677
+ const itemCall = callFor(target, slot, entry, item, `${path}[${index}]`, index, state);
678
+ if (!evaluateSync(rule.check, item, itemCall)) {
679
+ pushError(itemCall);
680
+ }
681
+ }
682
+ return;
683
+ }
684
+ if (rule.nested === "object") {
685
+ if (!evaluateSync(rule.check, value, callFor(target, slot, entry, value, path, undefined, state))) {
686
+ pushError(callFor(target, slot, entry, value, path, undefined, state));
687
+ return;
688
+ }
689
+ if (isNestedObject(value)) {
690
+ if (shouldVisitNested(value, `${path}.`, state)) {
691
+ runInstanceSync(value, `${path}.`, state, depth + 1);
692
+ }
693
+ }
694
+ else {
695
+ pushError(callFor(target, slot, entry, value, path, undefined, state));
696
+ }
697
+ return;
698
+ }
699
+ if (rule.nested === "each") {
700
+ const items = toItems(value);
701
+ if (items === undefined) {
702
+ pushError(callFor(target, slot, entry, value, path, undefined, state));
703
+ return;
704
+ }
705
+ for (let index = 0; index < items.length; index += 1) {
706
+ if (state.stopped) {
707
+ return;
708
+ }
709
+ const item = items[index];
710
+ const itemPath = `${path}[${index}]`;
711
+ if (isNestedObject(item)) {
712
+ if (shouldVisitNested(item, `${itemPath}.`, state)) {
713
+ runInstanceSync(item, `${itemPath}.`, state, depth + 1);
714
+ }
715
+ }
716
+ else {
717
+ pushError(callFor(target, slot, entry, item, itemPath, index, state));
718
+ }
719
+ }
720
+ return;
721
+ }
722
+ const call = callFor(target, slot, entry, value, path, undefined, state);
723
+ if (!evaluateSync(rule.check, value, call)) {
724
+ pushError(call);
725
+ }
726
+ }
727
+ function runInstanceSync(target, prefix, state, depth) {
728
+ if (state.visiting.has(target)) {
729
+ return;
730
+ }
731
+ if (depth > MAX_DEPTH) {
732
+ pushDepthSync(target, prefix, state);
733
+ return;
734
+ }
735
+ state.visiting.add(target);
736
+ try {
737
+ for (const run of fieldPlan(target, state.types)) {
738
+ if (state.stopped) {
739
+ return;
740
+ }
741
+ runFieldSync(target, run, prefix, state, depth);
742
+ }
743
+ }
744
+ finally {
745
+ state.visiting.delete(target);
746
+ }
747
+ }
748
+ async function runFieldAsync(target, run, prefix, state, depth) {
749
+ const start = state.errors.length;
750
+ const prepared = await prepareFieldAsync(target, run, prefix, state);
751
+ if (state.config.resolve !== undefined && state.errors.length > start) {
752
+ await rerenderErrorsAsync(state, start, target);
753
+ }
754
+ if (prepared === null) {
755
+ return;
756
+ }
757
+ if (prepared.nested.length > 0) {
758
+ await runNestedAsync(prepared.nested, state, depth + 1);
759
+ if (state.stopped) {
760
+ return;
761
+ }
762
+ }
763
+ const slot = run.slot;
764
+ if (slot === undefined) {
765
+ return;
766
+ }
767
+ for (let index = slot.rules.length - 1; index >= 0; index -= 1) {
768
+ if (state.stopped) {
769
+ return;
770
+ }
771
+ const entry = slot.rules[index];
772
+ if (entry === undefined) {
773
+ continue;
774
+ }
775
+ await runRuleAsync(target, slot, entry, prepared.value, prepared.path, state, depth);
776
+ }
777
+ }
778
+ async function runRuleAsync(target, slot, entry, value, path, state, depth) {
779
+ if (!(await isRunnableAsync(entry, slot, target, state))) {
780
+ return;
781
+ }
782
+ const rule = entry.rule;
783
+ if (entry.options.each === true) {
784
+ const items = toItems(value);
785
+ if (items === undefined) {
786
+ await pushErrorAsync(callFor(target, slot, entry, value, path, undefined, state));
787
+ return;
788
+ }
789
+ for (let index = 0; index < items.length; index += 1) {
790
+ if (state.stopped) {
791
+ return;
792
+ }
793
+ const item = items[index];
794
+ const itemCall = callFor(target, slot, entry, item, `${path}[${index}]`, index, state);
795
+ if (!(await evaluateAsync(rule.check, item, itemCall))) {
796
+ await pushErrorAsync(itemCall);
797
+ }
798
+ }
799
+ return;
800
+ }
801
+ if (rule.nested === "object") {
802
+ const call = callFor(target, slot, entry, value, path, undefined, state);
803
+ if (!(await evaluateAsync(rule.check, value, call))) {
804
+ await pushErrorAsync(call);
805
+ return;
806
+ }
807
+ if (isNestedObject(value)) {
808
+ if (shouldVisitNested(value, `${path}.`, state)) {
809
+ await runInstanceAsync(value, `${path}.`, state, depth + 1);
810
+ }
811
+ }
812
+ else {
813
+ await pushErrorAsync(call);
814
+ }
815
+ return;
816
+ }
817
+ if (rule.nested === "each") {
818
+ const items = toItems(value);
819
+ if (items === undefined) {
820
+ await pushErrorAsync(callFor(target, slot, entry, value, path, undefined, state));
821
+ return;
822
+ }
823
+ for (let index = 0; index < items.length; index += 1) {
824
+ if (state.stopped) {
825
+ return;
826
+ }
827
+ const item = items[index];
828
+ const itemPath = `${path}[${index}]`;
829
+ if (isNestedObject(item)) {
830
+ if (shouldVisitNested(item, `${itemPath}.`, state)) {
831
+ await runInstanceAsync(item, `${itemPath}.`, state, depth + 1);
832
+ }
833
+ }
834
+ else {
835
+ await pushErrorAsync(callFor(target, slot, entry, item, itemPath, index, state));
836
+ }
837
+ }
838
+ return;
839
+ }
840
+ const call = callFor(target, slot, entry, value, path, undefined, state);
841
+ if (!(await evaluateAsync(rule.check, value, call))) {
842
+ await pushErrorAsync(call);
843
+ }
844
+ }
845
+ async function runInstanceAsync(target, prefix, state, depth) {
846
+ if (state.visiting.has(target)) {
847
+ return;
848
+ }
849
+ if (depth > MAX_DEPTH) {
850
+ await pushDepthAsync(target, prefix, state);
851
+ return;
852
+ }
853
+ state.visiting.add(target);
854
+ try {
855
+ for (const run of fieldPlan(target, state.types)) {
856
+ if (state.stopped) {
857
+ return;
858
+ }
859
+ await runFieldAsync(target, run, prefix, state, depth);
860
+ }
861
+ }
862
+ finally {
863
+ state.visiting.delete(target);
864
+ }
865
+ }
866
+ function makeResult(state) {
867
+ return { valid: state.errors.length === 0, errors: state.errors };
868
+ }
869
+ export function validate(instance, options) {
870
+ assertInstance(instance);
871
+ const state = createState(options);
872
+ runInstanceSync(instance, "", state, 0);
873
+ return makeResult(state);
874
+ }
875
+ export async function validateAsync(instance, options) {
876
+ assertInstance(instance);
877
+ const state = createState(options);
878
+ await runInstanceAsync(instance, "", state, 0);
879
+ return makeResult(state);
880
+ }
881
+ function runFieldsSync(instance, fields, options) {
882
+ assertInstance(instance);
883
+ const state = createState(options);
884
+ if (fields.size === 0) {
885
+ return makeResult(state);
886
+ }
887
+ for (const run of fieldPlan(instance, state.types)) {
888
+ if (state.stopped) {
889
+ break;
890
+ }
891
+ if (!fields.has(run.fieldName)) {
892
+ continue;
893
+ }
894
+ runFieldSync(instance, run, "", state, 0);
895
+ }
896
+ return makeResult(state);
897
+ }
898
+ async function runFieldsAsync(instance, fields, options) {
899
+ assertInstance(instance);
900
+ const state = createState(options);
901
+ if (fields.size === 0) {
902
+ return makeResult(state);
903
+ }
904
+ for (const run of fieldPlan(instance, state.types)) {
905
+ if (state.stopped) {
906
+ break;
907
+ }
908
+ if (!fields.has(run.fieldName)) {
909
+ continue;
910
+ }
911
+ await runFieldAsync(instance, run, "", state, 0);
912
+ }
913
+ return makeResult(state);
914
+ }
915
+ export function validateProperty(instance, field, options) {
916
+ return runFieldsSync(instance, new Set([field]), options);
917
+ }
918
+ export async function validatePropertyAsync(instance, field, options) {
919
+ return runFieldsAsync(instance, new Set([field]), options);
920
+ }
921
+ export function validateFieldKey(instance, key, options) {
922
+ assertInstance(instance);
923
+ const state = createState(options);
924
+ for (const run of fieldPlan(instance, state.types)) {
925
+ if (state.stopped) {
926
+ break;
927
+ }
928
+ if (run.key !== key) {
929
+ continue;
930
+ }
931
+ runFieldSync(instance, run, "", state, 0);
932
+ }
933
+ return makeResult(state);
934
+ }
935
+ export function validatePartial(instance, fields, options) {
936
+ return runFieldsSync(instance, new Set(fields), options);
937
+ }
938
+ export async function validatePartialAsync(instance, fields, options) {
939
+ return runFieldsAsync(instance, new Set(fields), options);
940
+ }
941
+ export function safeParse(instance, options) {
942
+ const result = validate(instance, options);
943
+ if (result.valid) {
944
+ return { success: true, data: instance, errors: [] };
945
+ }
946
+ return { success: false, errors: result.errors };
947
+ }
948
+ export async function safeParseAsync(instance, options) {
949
+ const result = await validateAsync(instance, options);
950
+ if (result.valid) {
951
+ return { success: true, data: instance, errors: [] };
952
+ }
953
+ return { success: false, errors: result.errors };
954
+ }
955
+ export function validateOrThrow(instance, options) {
956
+ const result = validate(instance, options);
957
+ if (!result.valid) {
958
+ throw new ValidationException(result);
959
+ }
960
+ }
961
+ export async function validateOrThrowAsync(instance, options) {
962
+ const result = await validateAsync(instance, options);
963
+ if (!result.valid) {
964
+ throw new ValidationException(result);
965
+ }
966
+ }
967
+ //# sourceMappingURL=engine.js.map