-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.js
More file actions
1508 lines (1416 loc) · 58.2 KB
/
Copy pathindex.js
File metadata and controls
1508 lines (1416 loc) · 58.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Native addon: optional. Core validate() uses JS codegen and works without it.
// Buffer APIs (isValid, countValid, isValidParallel) require native.
// Loading is delegated so this file stays free of `pkg-prebuilds`/`__dirname`/
// `path` (the browser entry must not pull those in via the bundler).
const native = require("./lib/native-load")();
const {
compileToJS,
compileToJSCodegen,
compileToJSCodegenWithErrors,
compileToJSCombined,
} = require("./lib/js-compiler");
const { normalizeDraft7, normalizeNullable } = require("./lib/draft7");
const { classify } = require("./lib/shape-classifier");
const { buildTier0Plan, tier0Validate } = require("./lib/tier0");
// Extract default values from a schema tree. Returns a function that applies
// defaults to an object in-place (mutates), or null if no defaults exist.
function buildDefaultsApplier(schema) {
if (typeof schema !== "object" || schema === null) return null;
const actions = [];
collectDefaults(schema, actions);
if (actions.length === 0) return null;
return (data) => {
for (let i = 0; i < actions.length; i++) actions[i](data);
};
}
function collectDefaults(schema, actions, path) {
if (typeof schema !== "object" || schema === null) return;
const props = schema.properties;
if (!props) return;
for (const [key, prop] of Object.entries(props)) {
if (prop && typeof prop === "object" && prop.default !== undefined) {
const defaultVal = prop.default;
if (!path) {
actions.push((data) => {
if (typeof data === "object" && data !== null && !(key in data)) {
data[key] =
typeof defaultVal === "object" && defaultVal !== null
? JSON.parse(JSON.stringify(defaultVal))
: defaultVal;
}
});
} else {
const parentPath = path;
actions.push((data) => {
let target = data;
for (let j = 0; j < parentPath.length; j++) {
if (typeof target !== "object" || target === null) return;
target = target[parentPath[j]];
}
if (
typeof target === "object" &&
target !== null &&
!(key in target)
) {
target[key] =
typeof defaultVal === "object" && defaultVal !== null
? JSON.parse(JSON.stringify(defaultVal))
: defaultVal;
}
});
}
}
// Recurse into nested object schemas
if (prop && typeof prop === "object" && prop.properties) {
collectDefaults(prop, actions, (path || []).concat(key));
}
}
}
// Build a function that coerces property values to match schema types in-place.
// Handles string→number, string→integer, string→boolean, number→string, boolean→string.
function buildCoercer(schema) {
if (typeof schema !== "object" || schema === null) return null;
const actions = [];
collectCoercions(schema, actions);
if (actions.length === 0) return null;
return (data) => {
for (let i = 0; i < actions.length; i++) actions[i](data);
};
}
function collectCoercions(schema, actions, path) {
if (typeof schema !== "object" || schema === null) return;
const props = schema.properties;
if (!props) return;
for (const [key, prop] of Object.entries(props)) {
if (!prop || typeof prop !== "object" || !prop.type) continue;
const targetType = Array.isArray(prop.type) ? null : prop.type;
if (!targetType) continue;
const coerce = buildSingleCoercion(targetType);
if (!coerce) continue;
if (!path) {
actions.push((data) => {
if (typeof data === "object" && data !== null && key in data) {
const coerced = coerce(data[key]);
if (coerced !== undefined) data[key] = coerced;
}
});
} else {
const parentPath = path;
actions.push((data) => {
let target = data;
for (let j = 0; j < parentPath.length; j++) {
if (typeof target !== "object" || target === null) return;
target = target[parentPath[j]];
}
if (typeof target === "object" && target !== null && key in target) {
const coerced = coerce(target[key]);
if (coerced !== undefined) target[key] = coerced;
}
});
}
// Recurse into nested object properties
if (prop.properties) {
collectCoercions(prop, actions, (path || []).concat(key));
}
}
}
function buildSingleCoercion(targetType) {
switch (targetType) {
case "number":
return (v) => {
if (typeof v === "string") {
const n = Number(v);
if (v !== "" && !isNaN(n)) return n;
}
if (typeof v === "boolean") return v ? 1 : 0;
};
case "integer":
return (v) => {
if (typeof v === "string") {
const n = Number(v);
if (v !== "" && Number.isInteger(n)) return n;
}
if (typeof v === "boolean") return v ? 1 : 0;
};
case "string":
return (v) => {
if (typeof v === "number" || typeof v === "boolean") return String(v);
};
case "boolean":
return (v) => {
if (v === "true" || v === "1") return true;
if (v === "false" || v === "0") return false;
};
default:
return null;
}
}
// Build a function that removes properties not defined in schema.properties.
// Walks nested objects recursively.
function buildRemover(schema) {
if (typeof schema !== "object" || schema === null) return null;
const actions = [];
collectRemovals(schema, actions);
if (actions.length === 0) return null;
return (data) => {
for (let i = 0; i < actions.length; i++) actions[i](data);
};
}
function collectRemovals(schema, actions, path) {
if (typeof schema !== "object" || schema === null || !schema.properties)
return;
// If this level has additionalProperties: false, add a removal action
if (schema.additionalProperties === false) {
const allowed = new Set(Object.keys(schema.properties));
if (!path) {
actions.push((data) => {
if (typeof data !== "object" || data === null || Array.isArray(data))
return;
const keys = Object.keys(data);
for (let i = 0; i < keys.length; i++) {
if (!allowed.has(keys[i])) delete data[keys[i]];
}
});
} else {
const parentPath = path;
actions.push((data) => {
let target = data;
for (let j = 0; j < parentPath.length; j++) {
if (typeof target !== "object" || target === null) return;
target = target[parentPath[j]];
}
if (
typeof target !== "object" ||
target === null ||
Array.isArray(target)
)
return;
const keys = Object.keys(target);
for (let i = 0; i < keys.length; i++) {
if (!allowed.has(keys[i])) delete target[keys[i]];
}
});
}
}
// Always recurse into nested properties (they may have their own additionalProperties: false)
for (const [key, prop] of Object.entries(schema.properties)) {
if (prop && typeof prop === "object" && prop.properties) {
collectRemovals(prop, actions, (path || []).concat(key));
}
}
}
// Generate a fast preprocess function via codegen instead of closure arrays
function buildPreprocessCodegen(schema, options) {
if (typeof schema !== 'object' || schema === null || !schema.properties) return null;
const lines = [];
const props = schema.properties;
const keys = Object.keys(props);
// removeAdditional: inline key check
if (options.removeAdditional && schema.additionalProperties === false) {
const checks = keys.map(k => `_k!==${JSON.stringify(k)}`).join('&&');
lines.push(`for(var _k in d)if(${checks})delete d[_k]`);
}
// coerceTypes: inline per property
if (options.coerceTypes) {
for (const [key, prop] of Object.entries(props)) {
if (!prop || typeof prop !== 'object' || !prop.type) continue;
const t = Array.isArray(prop.type) ? null : prop.type;
if (!t) continue;
const k = JSON.stringify(key);
if (t === 'integer') {
lines.push(`if(typeof d[${k}]==='string'){var _n=Number(d[${k}]);if(d[${k}]!==''&&Number.isInteger(_n))d[${k}]=_n}`);
lines.push(`if(typeof d[${k}]==='boolean')d[${k}]=d[${k}]?1:0`);
} else if (t === 'number') {
lines.push(`if(typeof d[${k}]==='string'){var _n=Number(d[${k}]);if(d[${k}]!==''&&!isNaN(_n))d[${k}]=_n}`);
lines.push(`if(typeof d[${k}]==='boolean')d[${k}]=d[${k}]?1:0`);
} else if (t === 'string') {
lines.push(`if(typeof d[${k}]==='number'||typeof d[${k}]==='boolean')d[${k}]=String(d[${k}])`);
} else if (t === 'boolean') {
lines.push(`if(d[${k}]==='true'||d[${k}]==='1')d[${k}]=true`);
lines.push(`if(d[${k}]==='false'||d[${k}]==='0')d[${k}]=false`);
} else if (t === 'array' && options.coerceTypes === 'array') {
lines.push(`if(${k} in d&&d[${k}]!==undefined&&!Array.isArray(d[${k}]))d[${k}]=[d[${k}]]`);
}
}
}
// defaults: inline per property
for (const [key, prop] of Object.entries(props)) {
if (prop && typeof prop === 'object' && prop.default !== undefined) {
const k = JSON.stringify(key);
const def = JSON.stringify(prop.default);
lines.push(`if(!(${k} in d))d[${k}]=${def}`);
}
}
if (lines.length === 0) return null;
// Data may legitimately be null or a non-object (e.g. a `['object','null']`
// schema), so the per-property mutations must not run on it.
lines.unshift(`if(d===null||typeof d!=='object')return`);
try {
return new Function('d', lines.join('\n'));
} catch {
return null;
}
}
// Schema compilation cache: same schema string -> reuse compiled functions
const _compileCache = new Map();
// Object identity cache: same schema object reference -> reuse entire compiled state
// Skips JSON.stringify, cache lookup, and all setup. Near-zero cost for repeated schemas.
const _identityCache = new WeakMap();
const SIMDJSON_PADDING = 64;
const VALID_RESULT = Object.freeze({ valid: true, errors: Object.freeze([]) });
const ABORT_EARLY_RESULT = Object.freeze({
valid: false,
errors: Object.freeze([Object.freeze({
code: 'ATA9000',
message: 'validation failed',
keyword: '__abort_early__',
path: '',
})]),
});
// `_CP_LEN_SOURCE`, the safe-regex embed, and the AOT helpers that consume them
// now live in `lib/aot.js` — keeping this file free of `fs`/`path`/`__dirname`
// references so a default import never touches disk. The instance and static
// AOT methods further down lazily require `./lib/aot`, so they pay nothing
// until a user calls `toStandaloneModule`/`bundleStandalone`/etc.
// Above this size, simdjson On Demand (selective field access) beats JSON.parse
// (which must materialize the full JS object tree). Buffer.from + NAPI ~2x faster.
const SIMDJSON_THRESHOLD = 8192;
// Resolve a JSON Schema path like "#/properties/name/type" to the schema object
// that *contains* the failing keyword. Used by verbose mode to populate
// `parentSchema` on validation errors. Returns undefined if the path can't be
// walked (malformed pointer or missing intermediate node).
function resolveSchemaByPath(rootSchema, schemaPath) {
if (!schemaPath || typeof schemaPath !== 'string' || !schemaPath.startsWith('#')) {
return undefined;
}
const stripped = schemaPath.slice(1);
if (!stripped || stripped === '/') return rootSchema;
const parts = stripped.split('/').filter(Boolean).map(s => s.replace(/~1/g, '/').replace(/~0/g, '~'));
// The last segment is the keyword that failed (e.g. "type"); parentSchema is
// the schema object that owns that keyword, so walk all but the last segment.
let target = rootSchema;
for (let i = 0; i < parts.length - 1; i++) {
if (target == null || typeof target !== 'object') return undefined;
target = target[parts[i]];
}
return target;
}
function parsePointerPath(path) {
if (!path) return [];
return path
.split("/")
.filter(Boolean)
.map((seg) => {
const decoded = seg.replace(/~1/g, "/").replace(/~0/g, "~");
// Per Standard Schema V1: array indices should be emitted as numbers,
// object keys as strings. Treat all-digit segments as numeric indices.
if (/^(0|[1-9][0-9]*)$/.test(decoded)) {
return { key: Number(decoded) };
}
return { key: decoded };
});
}
function createPaddedBuffer(jsonStr) {
if (typeof Buffer === 'undefined') throw new Error('createPaddedBuffer requires Node.js Buffer');
const jsonBuf = Buffer.from(jsonStr);
const padded = Buffer.allocUnsafe(jsonBuf.length + SIMDJSON_PADDING);
jsonBuf.copy(padded);
padded.fill(0, jsonBuf.length);
return { buffer: padded, length: jsonBuf.length };
}
function buildSchemaMap(schemas) {
if (!schemas) return null
const map = new Map()
if (Array.isArray(schemas)) {
for (const s of schemas) {
normalizeDraft7(s)
normalizeNullable(s)
const id = s.$id
if (!id) throw new Error('Schema in schemas option must have $id')
map.set(id, s)
}
} else {
for (const [key, s] of Object.entries(schemas)) {
normalizeDraft7(s)
normalizeNullable(s)
map.set(s.$id || key, s)
}
}
return map
}
// Compile-cache key for a root schema plus its external schemas. Must include
// the external schema CONTENT, not just their $ids: two validators can share a
// root schema string and the same $id while pointing that $id at different
// schemas (separate app instances, test suites, multi-tenant). Keying on $id
// alone reuses the wrong compiled validator and silently mis-validates.
function compileCacheKey(schemaStr, schemaMap) {
if (!schemaMap || schemaMap.size === 0) return schemaStr
const parts = []
for (const [id, s] of schemaMap) parts.push(id + '=' + JSON.stringify(s))
parts.sort()
return schemaStr + '\0' + parts.join('\0')
}
// Resolve a relative URI ref against a base URI
function resolveRelativeRef(ref, baseId) {
if (!baseId || ref.includes('://') || ref.startsWith('#')) return ref
const lastSlash = baseId.lastIndexOf('/')
if (lastSlash < 0) return ref
return baseId.substring(0, lastSlash + 1) + ref
}
// Resolve a cross-schema $ref to its target schema for preprocessing purposes.
// Handles whole-schema refs (`shared#`), relative-id matching, and JSON pointer
// fragments (`shared#/properties/id`). Returns null for local-only refs or when
// the target cannot be found. Used only to read `type`/`properties` for
// coercion/defaults/removeAdditional, never for validation.
function resolveRefForPreprocess(ref, schemaMap) {
if (!schemaMap || schemaMap.size === 0 || typeof ref !== 'string') return null
const hashIdx = ref.indexOf('#')
const baseId = hashIdx >= 0 ? ref.slice(0, hashIdx) : ref
const fragment = hashIdx >= 0 ? ref.slice(hashIdx + 1) : ''
if (!baseId) return null
let base = null
if (schemaMap.has(baseId)) base = schemaMap.get(baseId)
else if (!ref.includes('://')) {
for (const [id, s] of schemaMap) {
if (id.endsWith('/' + baseId)) { base = s; break }
}
}
if (!base) return null
if (!fragment) return base
let target = base
for (const part of fragment.split('/')) {
if (part === '') continue
if (target == null || typeof target !== 'object') return null
target = target[part.replace(/~1/g, '/').replace(/~0/g, '~')]
}
return target == null ? null : target
}
// Preprocessing (coerce/defaults/removeAdditional) reads `schema.properties` and
// each property's `type`. When the data shape lives behind a cross-schema $ref
// (a whole-schema ref like Fastify's `params: { $ref: 'shared#' }`, or a
// property ref like `{ id: { $ref: 'shared#/properties/id' } }`), follow the
// ref so the preprocessor can see the referenced shape. Returns the schema with
// such refs resolved, cloning only when a substitution is made.
function resolveSchemaForPreprocess(schema, schemaMap) {
if (!schema || typeof schema !== 'object' || !schemaMap || schemaMap.size === 0) return schema
let s = schema
// Whole-schema ref (only when it has no own properties, to avoid dropping
// sibling keywords on schemas that mix $ref with properties).
if (s.$ref && !s.properties) {
const t = resolveRefForPreprocess(s.$ref, schemaMap)
if (t && typeof t === 'object') s = t
}
if (!s.properties) return s
// Property-level refs: substitute the resolved target so coercion sees `type`.
let cloned = null
for (const key of Object.keys(s.properties)) {
const p = s.properties[key]
if (p && typeof p === 'object' && p.$ref && !p.type) {
const t = resolveRefForPreprocess(p.$ref, schemaMap)
if (t && typeof t === 'object') {
if (!cloned) { cloned = Object.assign({}, s); cloned.properties = Object.assign({}, s.properties) }
cloned.properties[key] = t
}
}
}
return cloned || s
}
class Validator {
constructor(schema, opts) {
const options = opts || {};
const schemaObj = typeof schema === "string" ? JSON.parse(schema) : schema;
// Ultra-fast path: same schema object reference -> return cached instance
// JS constructor returning an object makes `new` return that object
// Cost: one WeakMap lookup. No property copy, no setup, nothing.
if (!opts && typeof schema === "object" && schema !== null) {
const hit = _identityCache.get(schema);
if (hit) return hit;
}
// Draft 7 normalization — convert keywords to 2020-12 equivalents in-place
normalizeDraft7(schemaObj);
// OpenAPI nullable -> type union with 'null'
normalizeNullable(schemaObj);
this._schemaStr = null; // lazy: computed on first use
this._schemaObj = schemaObj;
this._options = options;
this._initialized = false;
this._nativeReady = false;
this._compiled = null;
this._fastSlot = -1;
this._jsFn = null;
this._preprocess = null;
this._applyDefaults = null;
// Schema map for cross-schema $ref resolution
this._schemaMap = buildSchemaMap(options.schemas) || new Map();
// User-supplied format checkers: { formatName: (value) => boolean }.
// Looked up at runtime when a schema references a format the built-in
// registry does not know about.
this._userFormats = options.formats || null;
// Verbose mode: when on, errors carry parentSchema (the schema object that
// produced the error). Matches ajv's `verbose: true` behavior.
this._verbose = !!options.verbose;
// richErrors: default true. Only the literal `false` opts back into the
// v0.14 error shape (no code/expected/received/docUrl, no aliases).
this._richErrors = options && options.richErrors === false ? false : true;
// Optional schema source descriptor. When supplied, the renderer pipeline
// can attach a `schemaSource` frame to enriched errors.
this._source = options && options.source && typeof options.source === 'object'
? { path: String(options.source.path || ''), content: String(options.source.content || '') }
: null;
// Build a JSON pointer -> position map for the schema text once at
// construction so each runtime error can resolve `schemaSource` without
// re-scanning the source on every validate() call.
if (this._source) {
const { buildPositionMap } = require('./lib/source-positions');
this._schemaPositions = buildPositionMap(this._source.content);
} else {
this._schemaPositions = null;
}
// Per-validate data position cache. Populated by validateJSON before
// dispatching to inner validate(); consulted by the rich-error wrap
// to attach dataFrame entries to each enriched error.
this._posCache = require('./lib/data-position-cache').createCache();
this._lastRawInput = null;
// Lazy stubs: trigger compilation on first call, then re-dispatch
this.validate = (data) => {
this._ensureCompiled();
return this.validate(data);
};
this.isValidObject = (data) => {
// Lazy: classify + build tier 0 plan on first call, not in constructor.
const _tier = classify(this._schemaObj);
if (_tier.tier === 0) {
const _plan = buildTier0Plan(this._schemaObj);
let _n = 0;
this.isValidObject = (d) => {
const r = tier0Validate(_plan, d);
if (++_n === 2) {
try { this._ensureCodegen(); } catch {}
}
return r;
};
} else {
this._ensureCodegen();
}
return this.isValidObject(data);
};
this.validateJSON = (jsonStr) => {
this._ensureCompiled();
return this.validateJSON(jsonStr);
};
this.isValidJSON = (jsonStr) => {
this._ensureCompiled();
return this.isValidJSON(jsonStr);
};
this.validateAndParse = (jsonStr) => {
if (!native) throw new Error('Native addon required for validateAndParse()');
this._ensureCompiled();
return this.validateAndParse(jsonStr);
};
this.isValid = (buf) => {
if (!native) throw new Error('Native addon required for isValid() — use validate() or isValidObject() instead');
this._ensureCompiled();
return this.isValid(buf);
};
this.countValid = (ndjsonBuf) => {
if (!native) throw new Error('Native addon required for countValid()');
this._ensureCompiled();
return this.countValid(ndjsonBuf);
};
this.batchIsValid = (buffers) => {
if (!native) throw new Error('Native addon required for batchIsValid()');
this._ensureCompiled();
return this.batchIsValid(buffers);
};
// ~standard uses self.validate() -- works with lazy because it goes through
// the instance property which gets swapped after compilation
const self = this;
Object.defineProperty(this, "~standard", {
value: Object.freeze({
version: 1,
vendor: "ata-validator",
validate(value) {
const result = self.validate(value);
if (result.valid) {
return { value };
}
return {
issues: result.errors.map((err) => ({
message: err.message,
path: parsePointerPath(err.instancePath),
})),
};
},
}),
writable: false,
enumerable: false,
configurable: false,
});
// Populate identity cache so repeated `new Validator(sameSchema)` short-circuits.
if (!opts && typeof schema === "object" && schema !== null) {
_identityCache.set(schema, this);
}
}
_ensureCompiled() {
if (this._initialized) return;
this._initialized = true;
const schemaObj = this._schemaObj;
const options = this._options;
// Lazy stringify — only computed here, not in constructor
if (!this._schemaStr) this._schemaStr = JSON.stringify(schemaObj);
// Check cache first -- reuse compiled functions for same schema
const sm = this._schemaMap.size > 0 ? this._schemaMap : null;
const mapKey = compileCacheKey(this._schemaStr, this._schemaMap);
// Custom formats are JS functions: bypass the compile cache since they can
// differ between validators that share the same schema string.
const cached = this._userFormats ? null : _compileCache.get(mapKey);
let jsFn, jsCombinedFn, jsErrFn, _isCodegen = false;
var _forceNapi = typeof process !== 'undefined' && process.env && process.env.ATA_FORCE_NAPI;
if (cached && !_forceNapi) {
jsFn = cached.jsFn;
jsCombinedFn = cached.combined;
jsErrFn = cached.errFn;
_isCodegen = !!cached.isCodegen;
} else if (!_forceNapi) {
const uf = this._userFormats;
const _cgFn = compileToJSCodegen(schemaObj, sm, uf);
jsFn = _cgFn || compileToJS(schemaObj, null, sm);
jsCombinedFn = compileToJSCombined(schemaObj, VALID_RESULT, sm, uf);
jsErrFn = compileToJSCodegenWithErrors(schemaObj, sm, uf);
_isCodegen = !!_cgFn;
if (!uf) {
_compileCache.set(mapKey, { jsFn, combined: jsCombinedFn, errFn: jsErrFn, isCodegen: _isCodegen });
}
} else {
jsFn = null; jsCombinedFn = null; jsErrFn = null;
}
this._jsFn = jsFn;
// Data mutators -- try codegen first (12x faster), fallback to closure arrays.
// Follow cross-refs so coercion/defaults/removeAdditional see the referenced
// shape (e.g. Fastify `params: { $ref: 'shared#' }` or property refs like
// `{ id: { $ref: 'shared#/properties/id' } }`).
const preprocessSchema = resolveSchemaForPreprocess(schemaObj, this._schemaMap);
let preprocess = buildPreprocessCodegen(preprocessSchema, options);
if (!preprocess) {
const applyDefaults = buildDefaultsApplier(preprocessSchema);
const applyCoerce = options.coerceTypes ? buildCoercer(preprocessSchema) : null;
const applyRemove = options.removeAdditional
? buildRemover(preprocessSchema)
: null;
const mutators = [applyRemove, applyCoerce, applyDefaults].filter(Boolean);
preprocess =
mutators.length === 0
? null
: mutators.length === 1
? mutators[0]
: (data) => {
for (let i = 0; i < mutators.length; i++) mutators[i](data);
};
}
this._applyDefaults = preprocess;
this._preprocess = preprocess;
// Detect if schema is "selective" -- doesn't recurse into arrays/deep objects.
const hasArrayTraversal =
schemaObj &&
(schemaObj.items ||
schemaObj.prefixItems ||
schemaObj.contains ||
(schemaObj.properties &&
Object.values(schemaObj.properties).some(
(p) => p && (p.items || p.prefixItems || p.contains),
)));
const useSimdjsonForLarge = !hasArrayTraversal;
if (jsFn) {
let safeErrFn = null;
if (jsErrFn) {
try {
jsErrFn({}, true);
safeErrFn = (d) => jsErrFn(d, true);
} catch {}
}
// errFn: use JS codegen if safe, else native fallback (only when native
// is available). Environments without the native addon — Cloudflare
// Workers, browser, Bun without N-API — get a JS-only fallback so the
// invalid path doesn't dereference a null _compiled.
const hasUnevaluated = schemaObj && (schemaObj.unevaluatedProperties !== undefined || schemaObj.unevaluatedItems !== undefined || this._schemaStr.includes('unevaluatedProperties') || this._schemaStr.includes('unevaluatedItems'))
const hasDynRef = this._schemaStr.includes('"$dynamicRef"') || this._schemaStr.includes('"$dynamicAnchor"')
const jsOnlyFallback = (d) => ({
valid: jsFn(d),
errors: jsFn(d) ? [] : [{
keyword: 'validation',
instancePath: '',
schemaPath: '',
params: {},
message: 'schema validation failed (detailed errors unavailable without native addon)'
}]
});
const errFn =
safeErrFn ||
(hasUnevaluated
? (d) => ({ valid: jsFn(d), errors: jsFn(d) ? [] : [{ code: 'unevaluated', path: '', message: 'unevaluated property or item' }] })
: !native
? jsOnlyFallback
: hasDynRef
? (d) => {
this._ensureNative();
return this._compiled.validateJSON(JSON.stringify(d));
}
: (d) => {
this._ensureNative();
return this._compiled.validate(d);
});
// Best path: combined validator (single pass, validates + collects errors)
// Valid data: returns VALID_RESULT, no allocation
// Invalid data: collects errors in one pass (no double validation)
// Fallback: hybridFn or jsFn + errFn for schemas combined can't handle
// Test combined at compile time -- some schemas produce broken combined code
// Test combined at compile time -- some schemas (e.g. if/then/else)
// produce broken combined code that crashes on certain inputs.
// We probe with diverse data; if any throws, fall back to hybrid.
let safeCombinedFn = null;
if (jsCombinedFn) {
try {
const probe = {};
// Populate probe with one key per known property to trigger nested paths
if (schemaObj && schemaObj.properties) {
for (const k of Object.keys(schemaObj.properties)) probe[k] = "";
}
if (schemaObj && schemaObj.if && schemaObj.if.properties) {
for (const k of Object.keys(schemaObj.if.properties)) probe[k] = "";
}
jsCombinedFn(probe);
jsCombinedFn({});
jsCombinedFn(null);
jsCombinedFn(0);
safeCombinedFn = jsCombinedFn;
} catch {}
}
if (options.abortEarly && jsFn && !hasDynRef) {
// abortEarly: do NOT enrich. Skip position lookups, suggestions, source maps.
// This is the perf-critical path for edge gateways. The richErrors wrap
// below recognises the ATA9000 stub keyword and passes the frozen result
// through unchanged, so a single shared object is returned per failure.
const _fn = jsFn;
this.validate = preprocess
? (data) => { preprocess(data); return _fn(data) ? VALID_RESULT : ABORT_EARLY_RESULT; }
: (data) => (_fn(data) ? VALID_RESULT : ABORT_EARLY_RESULT);
} else if (hasDynRef && _isCodegen && jsFn) {
// $dynamicRef with JS codegen: direct path, no wrapper layers
const _fn = jsFn, _efn = safeErrFn || errFn, _R = VALID_RESULT;
this.validate = preprocess
? (data) => { preprocess(data); return _fn(data) ? _R : _efn(data); }
: (data) => _fn(data) ? _R : _efn(data);
} else if (hasDynRef) {
// $dynamicRef without codegen: delegate to native C++ (interpretive path unreliable)
this.validate = preprocess
? (data) => { preprocess(data); return errFn(data); }
: errFn;
} else if (jsFn && jsFn._hybridFactory) {
// Zero-wrapper: hybridFactory bakes VALID_RESULT + errFn into a single function
// No arrow function wrapper, no ternary, one function call
const hybridFn = jsFn._hybridFactory(VALID_RESULT, safeCombinedFn || errFn);
this.validate = preprocess
? (data) => { preprocess(data); return hybridFn(data); }
: hybridFn;
} else if (safeCombinedFn) {
this.validate = preprocess
? (data) => { preprocess(data); return safeCombinedFn(data); }
: safeCombinedFn;
} else {
const hybridFn = jsFn && jsFn._hybridFactory
? jsFn._hybridFactory(VALID_RESULT, errFn)
: null;
this.validate = hybridFn
? preprocess
? (data) => {
preprocess(data);
return hybridFn(data);
}
: hybridFn
: preprocess
? (data) => {
preprocess(data);
return jsFn(data) ? VALID_RESULT : errFn(data);
}
: (data) => (jsFn(data) ? VALID_RESULT : errFn(data));
}
// Verbose mode: populate parentSchema on each error.
// Errors may be frozen, so clone them with the extra field.
if (this._verbose) {
const inner = this.validate;
const root = this._schemaObj;
this.validate = (data) => {
const result = inner(data);
if (result && !result.valid && result.errors) {
const enriched = result.errors.map((err) =>
err && err.parentSchema === undefined
? { ...err, parentSchema: resolveSchemaByPath(root, err.schemaPath) }
: err
);
return { valid: false, errors: enriched };
}
return result;
};
}
this.isValidObject = jsFn;
const hybridFn = jsFn._hybridFactory
? jsFn._hybridFactory(VALID_RESULT, errFn)
: null;
const jsonValidateFn = safeCombinedFn
|| hybridFn
|| ((obj) => (jsFn(obj) ? VALID_RESULT : errFn(obj)));
this.validateJSON = useSimdjsonForLarge && native
? (jsonStr) => {
if (jsonStr.length >= SIMDJSON_THRESHOLD) {
this._ensureNative();
const buf = Buffer.from(jsonStr);
if (native.rawFastValidate(this._fastSlot, buf))
return VALID_RESULT;
return this._compiled.validateJSON(jsonStr);
}
try {
return jsonValidateFn(JSON.parse(jsonStr));
} catch (e) {
if (!(e instanceof SyntaxError)) throw e;
}
this._ensureNative();
return this._compiled.validateJSON(jsonStr);
}
: (jsonStr) => {
try {
return jsonValidateFn(JSON.parse(jsonStr));
} catch (e) {
if (!(e instanceof SyntaxError)) throw e;
if (!native) return { valid: false, errors: [{ keyword: 'syntax', instancePath: '', schemaPath: '#', params: {}, message: e.message }] };
}
this._ensureNative();
return this._compiled.validateJSON(jsonStr);
};
this.isValidJSON = useSimdjsonForLarge && native
? (jsonStr) => {
if (jsonStr.length >= SIMDJSON_THRESHOLD) {
this._ensureNative();
return native.rawFastValidate(
this._fastSlot,
Buffer.from(jsonStr),
);
}
try {
return jsFn(JSON.parse(jsonStr));
} catch (e) {
if (!(e instanceof SyntaxError)) throw e;
return false;
}
}
: (jsonStr) => {
try {
return jsFn(JSON.parse(jsonStr));
} catch (e) {
if (!(e instanceof SyntaxError)) throw e;
return false;
}
};
// validateAndParse: parse the JSON, then validate. Pure JS (JSON.parse +
// validate) so it works with or without the native addon and in browsers.
{
const self = this;
this.validateAndParse = (jsonStr) => {
let value;
try {
value = JSON.parse(typeof jsonStr === 'string' ? jsonStr : new TextDecoder().decode(jsonStr));
} catch (e) {
return { valid: false, value: undefined, errors: [{ code: 'ATA9001', message: 'invalid JSON: ' + e.message, keyword: '__parse__', instancePath: '', schemaPath: '', params: {} }] };
}
const r = self.validate(value);
return { valid: r.valid, value, errors: r.errors };
};
}
// Buffer APIs: lazy native init — only compile native schema on first buffer call.
// This keeps cold start fast (JS codegen only) for users who only use validate().
if (native) {
const self = this;
this.isValid = (buf) => {
self._ensureNative();
const slot = self._fastSlot;
self.isValid = (b) => {
if (typeof b === 'string') b = Buffer.from(b);
else if (!(b instanceof Uint8Array)) throw new TypeError('isValid() requires a Buffer, Uint8Array, or string. For parsed objects, use isValidObject().');
return native.rawFastValidate(slot, b);
};
return self.isValid(buf);
};
this.countValid = (ndjsonBuf) => {
self._ensureNative();
const slot = self._fastSlot;
self.countValid = (b) => {
if (typeof b === 'string') b = Buffer.from(b);
else if (!(b instanceof Uint8Array)) throw new TypeError('countValid() requires a Buffer, Uint8Array, or string');
const r = native.rawNDJSONValidate(slot, b);
let c = 0;
for (let i = 0; i < r.length; i++) if (r[i]) c++;
return c;
};
return self.countValid(ndjsonBuf);
};
this.batchIsValid = (buffers) => {
self._ensureNative();
const slot = self._fastSlot;
self.batchIsValid = (bufs) => {
let v = 0;
for (const b of bufs) {
if (!(b instanceof Uint8Array)) throw new TypeError('batchIsValid() requires Buffer or Uint8Array elements');
if (native.rawFastValidate(slot, b)) v++;
}
return v;
};
return self.batchIsValid(buffers);
};
}
} else if (native) {
// Native-only path: no JS codegen, use native for everything
this._ensureNative();
const _hasDynamic = this._schemaStr.includes('"$dynamicRef"') || this._schemaStr.includes('"$dynamicAnchor"') || this._schemaStr.includes('"$anchor"')
// For schemas with dynamic refs/anchors, use validateJSON (C++ path with full support)
// instead of validate (NAPI direct V8 path without anchor maps)
const _validate = _hasDynamic
? (data) => this._compiled.validateJSON(JSON.stringify(data))
: (data) => this._compiled.validate(data);
this.validate = preprocess
? (data) => {
preprocess(data);
return _validate(data);
}
: _validate;
this.isValidObject = (data) => _validate(data).valid;
this.validateJSON = (jsonStr) => this._compiled.validateJSON(jsonStr);
this.isValidJSON = (jsonStr) => this._compiled.isValidJSON(jsonStr);
this.validateAndParse = (jsonStr) => this._compiled.validateAndParse(jsonStr);
{
const slot = this._fastSlot;
this.isValid = (buf) => {
if (typeof buf === 'string') buf = Buffer.from(buf);
else if (!(buf instanceof Uint8Array)) throw new TypeError('isValid() requires a Buffer, Uint8Array, or string. For parsed objects, use isValidObject().');
return native.rawFastValidate(slot, buf);
};
}
{
const slot = this._fastSlot;
this.countValid = (ndjsonBuf) => {
if (typeof ndjsonBuf === 'string') ndjsonBuf = Buffer.from(ndjsonBuf);
else if (!(ndjsonBuf instanceof Uint8Array)) throw new TypeError('countValid() requires a Buffer, Uint8Array, or string');
const results = native.rawNDJSONValidate(slot, ndjsonBuf);
let count = 0;
for (let i = 0; i < results.length; i++) if (results[i]) count++;
return count;
};
}
{
const slot = this._fastSlot;
this.batchIsValid = (buffers) => {
let valid = 0;
for (const buf of buffers) {
if (!(buf instanceof Uint8Array)) throw new TypeError('batchIsValid() requires Buffer or Uint8Array elements');
if (native.rawFastValidate(slot, buf)) valid++;
}
return valid;
};
}
}
// richErrors enrichment: layered on top of whichever validate path was
// bound above. Verbose's parentSchema flows through because enrich()
// copies it. Opt-out (`richErrors: false`) leaves the raw v0.14 shape.
if (this._richErrors && this.validate) {
const inner = this.validate;
const enrich = require('./lib/enrich-error').enrich;
this.validate = (data) => {
const result = inner(data);
if (result && !result.valid && result.errors && result.errors.length) {
// abortEarly returns the shared ATA9000 stub; preserve it as-is so the
// perf fast path stays allocation-free and the documented code stays stable.
if (result === ABORT_EARLY_RESULT) return result;
const positions = (this._lastRawInput != null) ? this._posCache.get(this._lastRawInput) : null;
const enriched = result.errors.map((e) => enrich(e, {
data,
positions,
schemaPositions: this._schemaPositions,
schemaFile: this._source ? this._source.path : undefined,
}));
if (positions) this._posCache.reset();
return { valid: false, errors: enriched };
}
return result;
};
// validateJSON also enriches: set _lastRawInput so the position cache
// can lazily build a map for dataFrame attachment. Only validateJSON
// wires this — validate(data) takes a pre-parsed object, by design.