@ivlev-dev/silent-validation 0.12.0 → 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.
package/dist/engine.js CHANGED
@@ -3,9 +3,14 @@ import { constructorOf, readFieldValue } from "./property.js";
3
3
  import { classStateRevision, validationStateFor } from "./registry.js";
4
4
  import { readInstanceSchema } from "./schema.js";
5
5
  import { isThenable, suppress } from "./thenable.js";
6
- import { validateFastPrimitive, validateType } from "./type-validation.js";
6
+ import { MAX_DEPTH, validateFastPrimitive, validateType } from "./type-validation.js";
7
7
  import { AsyncRuleError, ValidationException } from "./types.js";
8
8
  const planCache = new WeakMap();
9
+ let planBuildCount = 0;
10
+ /** @internal Диагностический счётчик построений плана полей (для тестов). */
11
+ export function validationPlanBuilds() {
12
+ return planBuildCount;
13
+ }
9
14
  const EMPTY_NESTED = [];
10
15
  function assertInstance(instance) {
11
16
  if (typeof instance !== "object" || instance === null) {
@@ -69,6 +74,17 @@ function groupsMatch(ruleGroups, callGroups) {
69
74
  }
70
75
  return ruleGroups.some((group) => callGroups.includes(group));
71
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
+ }
72
88
  function labelAtPath(labels, fieldName, path) {
73
89
  if (labels === undefined) {
74
90
  return undefined;
@@ -79,7 +95,7 @@ function labelAtPath(labels, fieldName, path) {
79
95
  return exact;
80
96
  }
81
97
  }
82
- if (path !== fieldName && !path.startsWith(`${fieldName}[`)) {
98
+ if (path !== fieldName && rootPathSegment(path) !== fieldName) {
83
99
  return undefined;
84
100
  }
85
101
  if (!Object.hasOwn(labels, fieldName)) {
@@ -228,6 +244,16 @@ function isRunnable(entry, slot, target, state) {
228
244
  }
229
245
  return groupsMatch(entry.options.groups ?? slot.groups, state.callGroups);
230
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
+ }
231
257
  function callFor(target, slot, entry, value, path, index, state) {
232
258
  return { target, slot, entry, value, path, index, state };
233
259
  }
@@ -254,7 +280,7 @@ function fieldPlan(target, withSchema) {
254
280
  const built = buildFieldPlan(target, withSchema, schema);
255
281
  cached = {
256
282
  revision,
257
- schema,
283
+ schema: withSchema ? schema : cached.schema,
258
284
  withSchema: withSchema ? built : cached.withSchema,
259
285
  plain: withSchema ? cached.plain : built,
260
286
  };
@@ -262,11 +288,16 @@ function fieldPlan(target, withSchema) {
262
288
  return built;
263
289
  }
264
290
  function buildFieldPlan(target, withSchema, schema = undefined) {
265
- const validation = validationStateFor(target);
291
+ planBuildCount += 1;
292
+ const fields = constructorOf(target) === null
293
+ ? undefined
294
+ : validationStateFor(target).fields;
266
295
  const byName = new Map();
267
- for (const slot of validation.fields.values()) {
268
- if (typeof slot.field === "string" && !byName.has(slot.fieldName)) {
269
- byName.set(slot.fieldName, slot);
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
+ }
270
301
  }
271
302
  }
272
303
  const plan = [];
@@ -276,8 +307,8 @@ function buildFieldPlan(target, withSchema, schema = undefined) {
276
307
  if (resolved !== null) {
277
308
  for (const [name, typeSchema] of Object.entries(resolved)) {
278
309
  const slot = byName.get(name);
279
- if (slot !== undefined) {
280
- for (const candidate of validation.fields.values()) {
310
+ if (slot !== undefined && fields !== undefined) {
311
+ for (const candidate of fields.values()) {
281
312
  if (typeof candidate.field === "string" && candidate.fieldName === name) {
282
313
  used.add(candidate);
283
314
  }
@@ -292,16 +323,18 @@ function buildFieldPlan(target, withSchema, schema = undefined) {
292
323
  }
293
324
  }
294
325
  }
295
- for (const slot of validation.fields.values()) {
296
- if (used.has(slot)) {
297
- continue;
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
+ });
298
337
  }
299
- plan.push({
300
- key: slot.field,
301
- fieldName: slot.fieldName,
302
- slot,
303
- schema: undefined,
304
- });
305
338
  }
306
339
  return plan;
307
340
  }
@@ -322,6 +355,63 @@ function schemaSkips(schema, value) {
322
355
  }
323
356
  return false;
324
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
+ }
325
415
  function uniqueNested(entries) {
326
416
  if (entries.length <= 1) {
327
417
  return entries;
@@ -342,7 +432,70 @@ function uniqueNested(entries) {
342
432
  }
343
433
  return unique;
344
434
  }
345
- function prepareField(target, run, prefix, state, asyncTypes = false) {
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) {
346
499
  const value = readFieldValue(target, run.key);
347
500
  const slot = run.slot;
348
501
  if (slot !== undefined && slot.optional && (value === null || value === undefined)) {
@@ -350,19 +503,18 @@ function prepareField(target, run, prefix, state, asyncTypes = false) {
350
503
  }
351
504
  if (slot !== undefined) {
352
505
  for (const condition of slot.conditions) {
353
- if (!condition(target, value)) {
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) {
354
512
  return null;
355
513
  }
356
514
  }
357
515
  }
358
516
  const path = `${prefix}${run.fieldName}`;
359
- if (state.types && run.schema !== undefined) {
360
- if (schemaSkips(run.schema, value)) {
361
- return null;
362
- }
363
- const typeConfig = asyncTypes && state.config.resolve !== undefined
364
- ? withoutResolver(state.config)
365
- : state.config;
517
+ if (state.types && run.schema !== undefined && !schemaSkips(run.schema, value)) {
366
518
  const label = slot?.label
367
519
  ?? labelAtPath(state.labels, run.fieldName, path)
368
520
  ?? run.fieldName;
@@ -373,7 +525,7 @@ function prepareField(target, run, prefix, state, asyncTypes = false) {
373
525
  field: run.fieldName,
374
526
  label,
375
527
  path,
376
- config: typeConfig,
528
+ config: state.config,
377
529
  labels: state.labels,
378
530
  });
379
531
  if (fast !== undefined) {
@@ -390,10 +542,11 @@ function prepareField(target, run, prefix, state, asyncTypes = false) {
390
542
  field: run.fieldName,
391
543
  label,
392
544
  path,
393
- config: typeConfig,
545
+ config: state.config,
394
546
  labels: state.labels,
395
547
  runtime,
396
548
  nested: collected,
549
+ stopAtFirst: state.stopAtFirst,
397
550
  });
398
551
  if (result !== null) {
399
552
  failed = true;
@@ -419,6 +572,28 @@ function prepareField(target, run, prefix, state, asyncTypes = false) {
419
572
  }
420
573
  return { value, path, nested: EMPTY_NESTED };
421
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
+ }
422
597
  function shouldVisitNested(instance, path, state) {
423
598
  const nestedSeen = state.nestedSeen ??= new WeakMap();
424
599
  const seen = nestedSeen.get(instance);
@@ -433,7 +608,7 @@ function shouldVisitNested(instance, path, state) {
433
608
  }
434
609
  return true;
435
610
  }
436
- function runNestedSync(nested, state) {
611
+ function runNestedSync(nested, state, depth) {
437
612
  for (const entry of nested) {
438
613
  if (state.stopped) {
439
614
  return;
@@ -442,10 +617,10 @@ function runNestedSync(nested, state) {
442
617
  if (!shouldVisitNested(entry.instance, path, state)) {
443
618
  continue;
444
619
  }
445
- runInstanceSync(entry.instance, path, state);
620
+ runInstanceSync(entry.instance, path, state, depth);
446
621
  }
447
622
  }
448
- async function runNestedAsync(nested, state) {
623
+ async function runNestedAsync(nested, state, depth) {
449
624
  for (const entry of nested) {
450
625
  if (state.stopped) {
451
626
  return;
@@ -454,16 +629,16 @@ async function runNestedAsync(nested, state) {
454
629
  if (!shouldVisitNested(entry.instance, path, state)) {
455
630
  continue;
456
631
  }
457
- await runInstanceAsync(entry.instance, path, state);
632
+ await runInstanceAsync(entry.instance, path, state, depth);
458
633
  }
459
634
  }
460
- function runFieldSync(target, run, prefix, state) {
635
+ function runFieldSync(target, run, prefix, state, depth) {
461
636
  const prepared = prepareField(target, run, prefix, state);
462
637
  if (prepared === null) {
463
638
  return;
464
639
  }
465
640
  if (prepared.nested.length > 0) {
466
- runNestedSync(prepared.nested, state);
641
+ runNestedSync(prepared.nested, state, depth + 1);
467
642
  if (state.stopped) {
468
643
  return;
469
644
  }
@@ -480,10 +655,10 @@ function runFieldSync(target, run, prefix, state) {
480
655
  if (entry === undefined) {
481
656
  continue;
482
657
  }
483
- runRuleSync(target, slot, entry, prepared.value, prepared.path, state);
658
+ runRuleSync(target, slot, entry, prepared.value, prepared.path, state, depth);
484
659
  }
485
660
  }
486
- function runRuleSync(target, slot, entry, value, path, state) {
661
+ function runRuleSync(target, slot, entry, value, path, state, depth) {
487
662
  if (!isRunnable(entry, slot, target, state)) {
488
663
  return;
489
664
  }
@@ -513,7 +688,7 @@ function runRuleSync(target, slot, entry, value, path, state) {
513
688
  }
514
689
  if (isNestedObject(value)) {
515
690
  if (shouldVisitNested(value, `${path}.`, state)) {
516
- runInstanceSync(value, `${path}.`, state);
691
+ runInstanceSync(value, `${path}.`, state, depth + 1);
517
692
  }
518
693
  }
519
694
  else {
@@ -535,7 +710,7 @@ function runRuleSync(target, slot, entry, value, path, state) {
535
710
  const itemPath = `${path}[${index}]`;
536
711
  if (isNestedObject(item)) {
537
712
  if (shouldVisitNested(item, `${itemPath}.`, state)) {
538
- runInstanceSync(item, `${itemPath}.`, state);
713
+ runInstanceSync(item, `${itemPath}.`, state, depth + 1);
539
714
  }
540
715
  }
541
716
  else {
@@ -549,26 +724,30 @@ function runRuleSync(target, slot, entry, value, path, state) {
549
724
  pushError(call);
550
725
  }
551
726
  }
552
- function runInstanceSync(target, prefix, state) {
727
+ function runInstanceSync(target, prefix, state, depth) {
553
728
  if (state.visiting.has(target)) {
554
729
  return;
555
730
  }
731
+ if (depth > MAX_DEPTH) {
732
+ pushDepthSync(target, prefix, state);
733
+ return;
734
+ }
556
735
  state.visiting.add(target);
557
736
  try {
558
737
  for (const run of fieldPlan(target, state.types)) {
559
738
  if (state.stopped) {
560
739
  return;
561
740
  }
562
- runFieldSync(target, run, prefix, state);
741
+ runFieldSync(target, run, prefix, state, depth);
563
742
  }
564
743
  }
565
744
  finally {
566
745
  state.visiting.delete(target);
567
746
  }
568
747
  }
569
- async function runFieldAsync(target, run, prefix, state) {
748
+ async function runFieldAsync(target, run, prefix, state, depth) {
570
749
  const start = state.errors.length;
571
- const prepared = prepareField(target, run, prefix, state, true);
750
+ const prepared = await prepareFieldAsync(target, run, prefix, state);
572
751
  if (state.config.resolve !== undefined && state.errors.length > start) {
573
752
  await rerenderErrorsAsync(state, start, target);
574
753
  }
@@ -576,7 +755,7 @@ async function runFieldAsync(target, run, prefix, state) {
576
755
  return;
577
756
  }
578
757
  if (prepared.nested.length > 0) {
579
- await runNestedAsync(prepared.nested, state);
758
+ await runNestedAsync(prepared.nested, state, depth + 1);
580
759
  if (state.stopped) {
581
760
  return;
582
761
  }
@@ -593,11 +772,11 @@ async function runFieldAsync(target, run, prefix, state) {
593
772
  if (entry === undefined) {
594
773
  continue;
595
774
  }
596
- await runRuleAsync(target, slot, entry, prepared.value, prepared.path, state);
775
+ await runRuleAsync(target, slot, entry, prepared.value, prepared.path, state, depth);
597
776
  }
598
777
  }
599
- async function runRuleAsync(target, slot, entry, value, path, state) {
600
- if (!isRunnable(entry, slot, target, state)) {
778
+ async function runRuleAsync(target, slot, entry, value, path, state, depth) {
779
+ if (!(await isRunnableAsync(entry, slot, target, state))) {
601
780
  return;
602
781
  }
603
782
  const rule = entry.rule;
@@ -627,7 +806,7 @@ async function runRuleAsync(target, slot, entry, value, path, state) {
627
806
  }
628
807
  if (isNestedObject(value)) {
629
808
  if (shouldVisitNested(value, `${path}.`, state)) {
630
- await runInstanceAsync(value, `${path}.`, state);
809
+ await runInstanceAsync(value, `${path}.`, state, depth + 1);
631
810
  }
632
811
  }
633
812
  else {
@@ -649,7 +828,7 @@ async function runRuleAsync(target, slot, entry, value, path, state) {
649
828
  const itemPath = `${path}[${index}]`;
650
829
  if (isNestedObject(item)) {
651
830
  if (shouldVisitNested(item, `${itemPath}.`, state)) {
652
- await runInstanceAsync(item, `${itemPath}.`, state);
831
+ await runInstanceAsync(item, `${itemPath}.`, state, depth + 1);
653
832
  }
654
833
  }
655
834
  else {
@@ -663,17 +842,21 @@ async function runRuleAsync(target, slot, entry, value, path, state) {
663
842
  await pushErrorAsync(call);
664
843
  }
665
844
  }
666
- async function runInstanceAsync(target, prefix, state) {
845
+ async function runInstanceAsync(target, prefix, state, depth) {
667
846
  if (state.visiting.has(target)) {
668
847
  return;
669
848
  }
849
+ if (depth > MAX_DEPTH) {
850
+ await pushDepthAsync(target, prefix, state);
851
+ return;
852
+ }
670
853
  state.visiting.add(target);
671
854
  try {
672
855
  for (const run of fieldPlan(target, state.types)) {
673
856
  if (state.stopped) {
674
857
  return;
675
858
  }
676
- await runFieldAsync(target, run, prefix, state);
859
+ await runFieldAsync(target, run, prefix, state, depth);
677
860
  }
678
861
  }
679
862
  finally {
@@ -686,13 +869,13 @@ function makeResult(state) {
686
869
  export function validate(instance, options) {
687
870
  assertInstance(instance);
688
871
  const state = createState(options);
689
- runInstanceSync(instance, "", state);
872
+ runInstanceSync(instance, "", state, 0);
690
873
  return makeResult(state);
691
874
  }
692
875
  export async function validateAsync(instance, options) {
693
876
  assertInstance(instance);
694
877
  const state = createState(options);
695
- await runInstanceAsync(instance, "", state);
878
+ await runInstanceAsync(instance, "", state, 0);
696
879
  return makeResult(state);
697
880
  }
698
881
  function runFieldsSync(instance, fields, options) {
@@ -708,7 +891,7 @@ function runFieldsSync(instance, fields, options) {
708
891
  if (!fields.has(run.fieldName)) {
709
892
  continue;
710
893
  }
711
- runFieldSync(instance, run, "", state);
894
+ runFieldSync(instance, run, "", state, 0);
712
895
  }
713
896
  return makeResult(state);
714
897
  }
@@ -725,7 +908,7 @@ async function runFieldsAsync(instance, fields, options) {
725
908
  if (!fields.has(run.fieldName)) {
726
909
  continue;
727
910
  }
728
- await runFieldAsync(instance, run, "", state);
911
+ await runFieldAsync(instance, run, "", state, 0);
729
912
  }
730
913
  return makeResult(state);
731
914
  }
@@ -745,7 +928,7 @@ export function validateFieldKey(instance, key, options) {
745
928
  if (run.key !== key) {
746
929
  continue;
747
930
  }
748
- runFieldSync(instance, run, "", state);
931
+ runFieldSync(instance, run, "", state, 0);
749
932
  }
750
933
  return makeResult(state);
751
934
  }