ata-validator 1.60.0 → 1.61.1

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 (56) hide show
  1. package/README.md +134 -6
  2. package/bin/ata.js +84 -0
  3. package/build.d.ts +29 -0
  4. package/build.mjs +2 -0
  5. package/compiled-bare-rich.d.ts +6 -0
  6. package/compiled-bare.d.ts +7 -0
  7. package/compiled-bare.js +5 -0
  8. package/compiled-bare.mjs +35 -0
  9. package/compiled-object.d.ts +11 -0
  10. package/compiled-object.js +6 -0
  11. package/compiled-object.mjs +3 -0
  12. package/compiled-plain.d.ts +16 -0
  13. package/compiled-plain.js +5 -0
  14. package/compiled-plain.mjs +3 -0
  15. package/compiled.d.ts +3 -1
  16. package/index.browser.mjs +2 -2
  17. package/index.bundle.mjs +2 -2
  18. package/index.d.ts +9 -0
  19. package/index.edge.mjs +2 -2
  20. package/index.js +48 -0
  21. package/index.mjs +1 -1
  22. package/index.node.mjs +1 -1
  23. package/lib/aot-build.js +81 -6
  24. package/lib/aot-impl.js +24 -21
  25. package/lib/bun-target.js +612 -0
  26. package/lib/codegen-engine.js +9 -3
  27. package/lib/combined-runtime.js +1 -1
  28. package/lib/compiled-bare-rich.js +54 -0
  29. package/lib/compiled-bare.js +44 -0
  30. package/lib/compiled-common.js +17 -2
  31. package/lib/compiled-defaults.browser.js +9 -0
  32. package/lib/compiled-defaults.js +8 -0
  33. package/lib/compiled-object.js +123 -0
  34. package/lib/compiled-plain.js +57 -0
  35. package/lib/compiled.js +2 -1
  36. package/lib/email-literal.js +29 -0
  37. package/lib/enrich-error.js +5 -1
  38. package/lib/error-codes.js +6 -76
  39. package/lib/formats-source.js +20 -3
  40. package/lib/formats.js +1 -1
  41. package/lib/js-compiler-errors.js +49 -10
  42. package/lib/js-compiler.js +92 -13
  43. package/lib/json-rejections.js +159 -0
  44. package/lib/native-codes.js +67 -0
  45. package/lib/native-message.js +8 -0
  46. package/lib/native.browser.js +11 -0
  47. package/lib/public-api.js +1 -0
  48. package/lib/rejections.js +13 -152
  49. package/lib/standard-schema.js +1 -1
  50. package/lib/tier0.js +1 -1
  51. package/lib/validator-core.js +46 -4
  52. package/lib/verify.js +386 -0
  53. package/lib/version.js +1 -1
  54. package/lite.js +1 -0
  55. package/lite.mjs +1 -1
  56. package/package.json +44 -9
package/lib/rejections.js CHANGED
@@ -1,13 +1,12 @@
1
1
  'use strict';
2
2
 
3
- // The rejection objects validate() and validateJSON() return, and the helpers
3
+ // The rejection objects validate() returns, and the helpers
4
4
  // that build their errors on first read: declaration-order sorting,
5
5
  // enrichment, typo correlation and source frames. Shared by the validator core
6
6
  // and by the wrapper around a compiled module, so both report errors through
7
- // the same code.
7
+ // the same code. The one validateJSON() returns is in lib/json-rejections.js.
8
8
 
9
9
  const { ordinalFor: schemaOrdinal, rankFor: schemaRank } = require('./schema-order');
10
- const { setDiagnosticSource: attachDiagnosticSource } = require('./diagnostic-source');
11
10
 
12
11
  // Rejection result with errors materialized on first read. The accessor
13
12
  // lives on the prototype so constructing one is a plain allocation; an
@@ -80,6 +79,15 @@ class RichRejection {
80
79
  return raw;
81
80
  }
82
81
  }
82
+ // The position map builder of lib/json-rejections.js, which sets it when it
83
+ // loads. Only validateJSON passes JSON text here, and the code that calls it
84
+ // loads that module first (were it not, the call below throws, it does not
85
+ // skip the frames); validate() and a compiled wrapper without the JSON
86
+ // entry points never load it, so their bundles carry neither it nor the
87
+ // rejection validateJSON returns (532 bytes gzipped of the wrapper).
88
+ let _positionsFor = null;
89
+ function _setPositionsFor (fn) { _positionsFor = fn; }
90
+
83
91
  // Orders a raw error list and gives it the shape the caller asked for: the
84
92
  // legacy key set, or enriched. Shared by both rejection classes below.
85
93
  function presentErrors(raw, data, rawInput, self, root, enrich) {
@@ -87,7 +95,7 @@ function presentErrors(raw, data, rawInput, self, root, enrich) {
87
95
  // The position map, resolved on the first read of an error's frame (see
88
96
  // defineLazyFrames in lib/enrich-error.js): a walk of the document that a
89
97
  // caller reading messages and paths never needs.
90
- const lazyPositions = enrich && raw.length && rawInput != null ? lazyPositionsFor(self, rawInput, raw) : null;
98
+ const lazyPositions = enrich && raw.length && rawInput != null ? _positionsFor(self, rawInput, raw) : null;
91
99
  // One options object for the whole list, not one per error.
92
100
  const opts = enrich && raw.length
93
101
  ? {
@@ -126,153 +134,6 @@ Object.defineProperty(RichRejection.prototype, 'errors', {
126
134
  });
127
135
 
128
136
 
129
- // The rejection validateJSON returns. Everything the text path adds over
130
- // validate(data), the value tree enrichment needs, the position map, the
131
- // diagnostic payload, happens on first access to `.errors`. Reading `.valid`
132
- // touches none of it. The JSON text is held here rather than read back off the
133
- // validator, so the result does not depend on what the instance does next.
134
- class LazyJsonRejection {
135
- // `parsed`, when given, is the document the inner path parsed from
136
- // `jsonStr` and validated, after defaults, coercion and removal: reading the
137
- // errors uses it instead of parsing the text again, which on a 5 MB
138
- // document was a third of what reading them cost.
139
- constructor(result, jsonStr, self, enrich, parsed) {
140
- this.valid = false;
141
- this._result = result;
142
- this._jsonStr = jsonStr;
143
- this._self = self;
144
- this._enrich = enrich;
145
- this._cached = null;
146
- this._parsed = parsed;
147
- }
148
- toJSON() {
149
- return { valid: false, errors: this.errors };
150
- }
151
- }
152
- Object.defineProperty(LazyJsonRejection.prototype, 'errors', {
153
- enumerable: true,
154
- configurable: true,
155
- get() {
156
- if (this._cached !== null) return this._cached;
157
- const self = this._self;
158
- const enrich = this._enrich;
159
- const jsonStr = this._jsonStr;
160
- // Reading the inner errors realizes the inner lazy layer, if there was one.
161
- const raw = this._result.errors || [];
162
- if (!raw.length) { this._cached = raw; return raw; }
163
-
164
- // The enrich pass plucks `received` from the value tree and the suggestion
165
- // engine (required-typo, format hints, coercion nudges) walks it too.
166
- let parsedData = this._parsed;
167
- if (parsedData === undefined) {
168
- try { parsedData = JSON.parse(jsonStr); } catch { parsedData = undefined; }
169
- // What was checked is the document after defaults, coercion and removal,
170
- // so `received` has to come from that, as it does for validate(). A
171
- // default that failed its own schema has no value in the text at all.
172
- if (parsedData !== undefined && self._preprocess) self._preprocess(parsedData);
173
- }
174
-
175
- // Errors the inner path already enriched carry a `received` key: enrich()
176
- // always sets one, even when there is no value to show. `code` is not a
177
- // safe signal, because branch-collapse attaches codes to raw errors, and
178
- // `docUrl` is not either, because the generated error functions stamp it
179
- // on raw errors; taking it as the signal left those errors without
180
- // `received` or a suggestion on the text path while validate() had both.
181
- if (!raw[0] || !('received' in raw[0])) {
182
- // Declaration order, as validate() applies it; the text path used to
183
- // enrich in emission order.
184
- const ordered = needsOrdering(raw) ? sortErrorsBySchemaOrder(self._schemaObj, raw) : raw;
185
- // The position map waits for the first read of a frame (lib/enrich-error
186
- // defineLazyFrames); until then reading the list costs the enrichment alone.
187
- const lazyPositions = lazyPositionsFor(self, jsonStr, ordered);
188
- const enrichOpts = {
189
- data: parsedData,
190
- positions: null,
191
- lazyPositions,
192
- schemaPositions: self._schemaPositions,
193
- schemaFile: self._source ? self._source.path : undefined,
194
- };
195
- const enriched = ordered.map((e) => enrich(e, enrichOpts));
196
- if (enriched.length > 1) attachRelated(enriched);
197
- attachDiagnosticSource(enriched, {
198
- data: parsedData,
199
- text: jsonStr,
200
- // Read by the diagnostic renderer only, which resolves the same map.
201
- get positions () { return lazyPositions(); },
202
- schema: self._schemaObj,
203
- mutatesInput: self._mutatesInput === true,
204
- });
205
- this._cached = enriched;
206
- return enriched;
207
- }
208
-
209
- // Already enriched, so the frames are usually attached too. Only a gap in
210
- // them is worth another walk of the document: resolving the map to discover
211
- // there was nothing to fill cost a second full walk on every rejection.
212
- if (raw.some((e) => e && !e.dataFrame)) {
213
- const positions = self._pos().targeted(jsonStr, wantedPointersFor(raw.filter((e) => e && !e.dataFrame)));
214
- if (positions) {
215
- for (const e of raw) {
216
- if (e && !e.dataFrame) {
217
- const path = e.path != null ? e.path : (e.instancePath || '');
218
- const p = positions[path];
219
- if (p) e.dataFrame = { byteOffset: p.byteOffset, length: p.length, line: p.line, col: p.col, text: p.text };
220
- }
221
- }
222
- self._posCache.reset();
223
- }
224
- }
225
- if (raw.length > 1) attachRelated(raw);
226
- attachDiagnosticSource(raw, {
227
- data: parsedData,
228
- text: jsonStr,
229
- schema: self._schemaObj,
230
- mutatesInput: self._mutatesInput === true,
231
- });
232
- this._cached = raw;
233
- return raw;
234
- },
235
- });
236
-
237
- // The targeted position map for a list, built on the first call and shared
238
- // by every error's frame accessor (lib/enrich-error defineLazyFrames).
239
- function lazyPositionsFor (self, text, errors) {
240
- let done = false;
241
- let positions = null;
242
- return () => {
243
- if (done) return positions;
244
- done = true;
245
- positions = self._pos().targeted(text, wantedPointersFor(errors));
246
- if (positions) self._posCache.reset();
247
- return positions;
248
- };
249
- }
250
-
251
- // The pointers a set of errors will ask the position map about. lib/enrich-error
252
- // looks up the error's own path, and for an additional or unevaluated property
253
- // the child pointer named in `params`, unescaped, which is the form it asks for.
254
- // The escaped form goes in too: including a pointer that is never read costs
255
- // nothing, and the cache answers anything outside this set from the full map
256
- // rather than reporting no position.
257
- function wantedPointersFor (errors) {
258
- const wanted = new Set();
259
- for (const e of errors) {
260
- if (!e) continue;
261
- const path = e.path != null ? e.path : (e.instancePath || '');
262
- wanted.add(path);
263
- if (e.instancePath != null && e.instancePath !== path) wanted.add(e.instancePath);
264
- const params = e.params;
265
- const named = params && (params.additionalProperty || params.unevaluatedProperty);
266
- if (typeof named === 'string') {
267
- wanted.add(path + '/' + named);
268
- if (named.indexOf('~') !== -1 || named.indexOf('/') !== -1) {
269
- wanted.add(path + '/' + named.replace(/~/g, '~0').replace(/\//g, '~1'));
270
- }
271
- }
272
- }
273
- return wanted;
274
- }
275
-
276
137
  // A raw error in the legacy shape. The error generator writes `code` and
277
138
  // `docUrl` into its literals because a standalone module returns them as they
278
139
  // are; the runtime's legacy shape never had them, and the interpreter leaves
@@ -411,4 +272,4 @@ function attachRelated (errors) {
411
272
  return errors;
412
273
  }
413
274
 
414
- module.exports = { LazyRejection, RichRejection, presentErrors, needsOrdering, LazyJsonRejection, _enrichLazy, attachRelated, sortErrorsBySchemaOrder, stripOrdinal, wantedPointersFor };
275
+ module.exports = { LazyRejection, RichRejection, presentErrors, needsOrdering, _enrichLazy, attachRelated, sortErrorsBySchemaOrder, stripOrdinal, _setPositionsFor };
@@ -117,7 +117,7 @@ function standardSchemaFor(self, getSchema, validate) {
117
117
  if (!message) {
118
118
  // The native engine reports numeric codes without a message; the
119
119
  // enrich pass knows how to word those. Rare, so required lazily.
120
- message = require('./enrich-error').enrich(err, {}).message;
120
+ message = require('./native-message')(err);
121
121
  }
122
122
  issues[i] = { message, path: parsePointerPath(path) };
123
123
  }
package/lib/tier0.js CHANGED
@@ -47,7 +47,7 @@ const F_MULT = 16;
47
47
  const PROTO_NAMES = new Set([...Object.getOwnPropertyNames(Object.prototype), '__proto__']);
48
48
  const _hop = Object.prototype.hasOwnProperty;
49
49
  // Deno removes the __proto__ accessor; read the prototype another way there.
50
- const _PN = ({}).__proto__ === Object.prototype;
50
+ const _PN = typeof Bun === 'undefined' && ({}).__proto__ === Object.prototype; // JavaScriptCore goes through Object.getPrototypeOf, see js-compiler's _PN
51
51
 
52
52
  function primConstraint(key, propSchema) {
53
53
  const t = propSchema.type;
@@ -19,6 +19,14 @@ const { normalizeKeywords, schemaUsesKeywords } = require('./keywords');
19
19
  // bundle built from lite.js never contains it. Until something registers, the
20
20
  // core behaves exactly as it does where `new Function` is blocked: every
21
21
  // schema runs on the interpreted engine, which passes the same test suite.
22
+ // Whether this process runs code compiled ahead of time, where generated
23
+ // code falls to an interpreter: Bun's flag for its compiler, or the
24
+ // environment saying so (an executable built before the flag existed).
25
+ function aotHost() {
26
+ if (env('ATA_ENGINE') === 'interpreter') return true;
27
+ const b = typeof Bun !== 'undefined' ? Bun : undefined;
28
+ return !!(b && b.isAOT === true);
29
+ }
22
30
  let _codegen = null;
23
31
  let compileToJS, compileToJSCodegen, compileToJSCodegenWithErrors, compileToJSCombined;
24
32
  function _registerCodegen(engine) {
@@ -37,6 +45,10 @@ let _aotLoader = null;
37
45
  // index.browser.mjs, null in every other entry, which then carry none of it.
38
46
  let _tiering = null;
39
47
  function _registerTiering(t) { _tiering = t; }
48
+ // Called with each validator the constructor finishes. The Node entry uses it
49
+ // to warm the engine once the event loop is free (see index.js).
50
+ let _onBuilt = null;
51
+ function _registerBuiltHook(f) { _onBuilt = f; }
40
52
  function _registerAot(load) {
41
53
  _aotLoader = load;
42
54
  }
@@ -341,7 +353,14 @@ function resolveSchemaByPath(rootSchema, schemaPath) {
341
353
  // by every page that loads the package, validating or not.
342
354
  let LazyRejection, RichRejection, LazyJsonRejection, _enrichLazy, presentErrors, needsOrdering, sortErrorsBySchemaOrder, stripOrdinal;
343
355
  function _loadRejections() {
344
- ({ LazyRejection, RichRejection, LazyJsonRejection, _enrichLazy, presentErrors, needsOrdering, sortErrorsBySchemaOrder, stripOrdinal } = require('./rejections'));
356
+ ({ LazyRejection, RichRejection, _enrichLazy, presentErrors, needsOrdering, sortErrorsBySchemaOrder, stripOrdinal } = require('./rejections'));
357
+ }
358
+ // The rejection validateJSON returns, and the position map an error's frame
359
+ // reads, loaded with the first rejection that carries JSON text: a process
360
+ // that only ever calls validate() never parses them (lib/json-rejections.js,
361
+ // lib/diagnostic-source.js).
362
+ function _loadJsonRejections() {
363
+ if (LazyJsonRejection === undefined) ({ LazyJsonRejection } = require('./json-rejections'));
345
364
  }
346
365
 
347
366
  // Text that does not parse, reported the same way on every path and platform:
@@ -772,7 +791,13 @@ class Validator {
772
791
  if (options.engine !== undefined && options.engine !== 'auto' && options.engine !== 'interpreter') {
773
792
  throw new TypeError("engine must be 'auto' or 'interpreter', got " + JSON.stringify(options.engine));
774
793
  }
775
- this._interpretOnly = options.engine === 'interpreter';
794
+ // Under an ahead-of-time compiler the generated code is interpreted and
795
+ // the interpreted engine, plain JavaScript, is compiled: measured on
796
+ // Bun's compiler, 80 against 530 ns a document. So the default flips
797
+ // there: Bun.isAOT once Bun ships it, ATA_ENGINE=interpreter until then
798
+ // and for any other host. `engine: 'auto'` asked for by name keeps the
799
+ // generated code.
800
+ this._interpretOnly = options.engine === 'interpreter' || (options.engine === undefined && aotHost());
776
801
  this._initialized = false;
777
802
  this._nativeReady = false;
778
803
  this._compiled = null;
@@ -861,8 +886,10 @@ class Validator {
861
886
  this._verdictTail = null;
862
887
  this._validateTail = null;
863
888
  this._entryExt = null;
864
- // The browser build warms the engine once, when the page is idle (lib/tiering.js).
889
+ // The browser build warms the engine once, when the page is idle (lib/tiering.js);
890
+ // the Node entry does the same once the event loop is free (index.js).
865
891
  if (_tiering !== null) _tiering.built(this);
892
+ if (_onBuilt !== null) _onBuilt(this);
866
893
 
867
894
  // Public methods start as memoized accessors on the prototype; nothing is
868
895
  // allocated per instance until one is first read. See _defineLazyMethod
@@ -950,7 +977,10 @@ class Validator {
950
977
 
951
978
  // Check cache first -- reuse compiled functions for same schema
952
979
  const sm = this._schemaMap.size > 0 ? this._schemaMap : null;
953
- const mapKey = compileCacheKey(this._schemaStr, this._schemaMap);
980
+ // The generated code takes the form of the target engine (js-compiler's
981
+ // setTargetEngine), so a function written for one engine is never handed
982
+ // to a compile asked for the other in the same process.
983
+ const mapKey = compileCacheKey(this._schemaStr, this._schemaMap) + '\u0000' + (_codegen && _codegen.jsCompiler && typeof _codegen.jsCompiler.targetEngine === 'function' ? _codegen.jsCompiler.targetEngine() : 'v8');
954
984
  var _forceNapi = this._interpretOnly || env('ATA_FORCE_NAPI');
955
985
  // Custom formats are JS functions: bypass the compile cache since they can
956
986
  // differ between validators that share the same schema string. An
@@ -1261,6 +1291,7 @@ class Validator {
1261
1291
  // literal with a getter here cost a closure plus an accessor
1262
1292
  // definition on every rejection, several hundred nanoseconds
1263
1293
  // before any error was read.
1294
+ if (rawInput != null) _loadJsonRejections();
1264
1295
  return new RichRejection(result, data, rawInput, self, root, enrich);
1265
1296
  }
1266
1297
  return result;
@@ -1297,6 +1328,7 @@ class Validator {
1297
1328
  // and on the codegen path that realizes the inner lazy layer, which is
1298
1329
  // the document walk this exists to avoid.
1299
1330
  if (result && result.valid === false) {
1331
+ _loadJsonRejections();
1300
1332
  return new LazyJsonRejection(result, jsonStr, this, enrich, parsed);
1301
1333
  }
1302
1334
  return result;
@@ -1913,6 +1945,14 @@ function compile(schema, opts) {
1913
1945
  // JSONSchema type (see index.d.ts) to an inline schema object so TypeScript
1914
1946
  // gives autocomplete and value checking while authoring. Returns the schema
1915
1947
  // untouched so it can be passed straight to Validator, toStandaloneModule, etc.
1948
+ // `schemaOf<T>()`: the JSON Schema of a TypeScript type, written in by
1949
+ // @ata-project/unplugin at build time from the type and its JSDoc tags. It
1950
+ // has no run-time form: a call that reaches here was not replaced, and the
1951
+ // loud error is better than an empty schema that accepts everything.
1952
+ function schemaOf () {
1953
+ throw new Error('schemaOf<T>() is replaced at build time by @ata-project/unplugin (with ts-json-schema-generator installed); it has no run-time form. Write the JSON Schema, or build with the plugin.');
1954
+ }
1955
+
1916
1956
  function defineSchema (schema) {
1917
1957
  return schema;
1918
1958
  }
@@ -2402,12 +2442,14 @@ module.exports = {
2402
2442
  SIMDJSON_PADDING,
2403
2443
  parseJSON,
2404
2444
  defineSchema,
2445
+ schemaOf,
2405
2446
  };
2406
2447
  // How an entry registers the code generator. Not enumerable, so the exported
2407
2448
  // surface of `require('ata-validator')` is what it was.
2408
2449
  Object.defineProperty(module.exports, '_registerCodegen', { value: _registerCodegen, enumerable: false });
2409
2450
  Object.defineProperty(module.exports, '_setCodegenLoader', { value: (load) => { _loadCodegen = load; }, enumerable: false });
2410
2451
  Object.defineProperty(module.exports, '_registerTiering', { value: _registerTiering, enumerable: false });
2452
+ Object.defineProperty(module.exports, '_registerBuiltHook', { value: _registerBuiltHook, enumerable: false });
2411
2453
  Object.defineProperty(module.exports, '_codegenRegistered', { value: () => _codegen !== null, enumerable: false });
2412
2454
  Object.defineProperty(module.exports, '_tiering', { get: () => _tiering, enumerable: false });
2413
2455
  Object.defineProperty(module.exports, '_registerAot', { value: _registerAot, enumerable: false });