@sinclair/typebox 0.25.23 → 0.25.25

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 (61) hide show
  1. package/compiler/compiler.d.ts +25 -28
  2. package/compiler/compiler.js +495 -495
  3. package/compiler/index.d.ts +2 -2
  4. package/compiler/index.js +47 -47
  5. package/conditional/conditional.d.ts +17 -17
  6. package/conditional/conditional.js +91 -91
  7. package/conditional/index.d.ts +2 -2
  8. package/conditional/index.js +45 -45
  9. package/conditional/structural.d.ts +11 -11
  10. package/conditional/structural.js +685 -685
  11. package/custom/custom.d.ts +12 -12
  12. package/custom/custom.js +55 -55
  13. package/custom/index.d.ts +1 -1
  14. package/custom/index.js +44 -44
  15. package/errors/errors.d.ts +67 -67
  16. package/errors/errors.js +472 -468
  17. package/errors/index.d.ts +1 -1
  18. package/errors/index.js +44 -44
  19. package/format/format.d.ts +12 -12
  20. package/format/format.js +55 -55
  21. package/format/index.d.ts +1 -1
  22. package/format/index.js +44 -44
  23. package/guard/extends.d.ts +10 -0
  24. package/guard/extends.js +50 -0
  25. package/guard/guard.d.ts +60 -60
  26. package/guard/guard.js +440 -440
  27. package/guard/index.d.ts +2 -1
  28. package/guard/index.js +45 -44
  29. package/hash/hash.d.ts +8 -8
  30. package/hash/hash.js +183 -183
  31. package/hash/index.d.ts +1 -1
  32. package/hash/index.js +44 -44
  33. package/license +22 -22
  34. package/package.json +55 -52
  35. package/readme.md +1237 -1325
  36. package/system/index.d.ts +1 -1
  37. package/system/index.js +44 -44
  38. package/system/system.d.ts +17 -17
  39. package/system/system.js +69 -69
  40. package/typebox.d.ts +422 -422
  41. package/typebox.js +388 -388
  42. package/value/cast.d.ts +26 -26
  43. package/value/cast.js +415 -420
  44. package/value/check.d.ts +8 -8
  45. package/value/check.js +405 -395
  46. package/value/clone.d.ts +3 -3
  47. package/value/clone.js +71 -71
  48. package/value/create.d.ts +14 -14
  49. package/value/create.js +378 -388
  50. package/value/delta.d.ts +43 -43
  51. package/value/delta.js +204 -204
  52. package/value/equal.d.ts +3 -3
  53. package/value/equal.js +80 -80
  54. package/value/index.d.ts +4 -4
  55. package/value/index.js +53 -53
  56. package/value/is.d.ts +11 -11
  57. package/value/is.js +53 -53
  58. package/value/pointer.d.ts +24 -24
  59. package/value/pointer.js +142 -142
  60. package/value/value.d.ts +32 -32
  61. package/value/value.js +87 -87
@@ -1,495 +1,495 @@
1
- "use strict";
2
- /*--------------------------------------------------------------------------
3
-
4
- @sinclair/typebox/compiler
5
-
6
- The MIT License (MIT)
7
-
8
- Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
9
-
10
- Permission is hereby granted, free of charge, to any person obtaining a copy
11
- of this software and associated documentation files (the "Software"), to deal
12
- in the Software without restriction, including without limitation the rights
13
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
- copies of the Software, and to permit persons to whom the Software is
15
- furnished to do so, subject to the following conditions:
16
-
17
- The above copyright notice and this permission notice shall be included in
18
- all copies or substantial portions of the Software.
19
-
20
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26
- THE SOFTWARE.
27
-
28
- ---------------------------------------------------------------------------*/
29
- Object.defineProperty(exports, "__esModule", { value: true });
30
- exports.TypeCompiler = exports.TypeCompilerUnknownTypeError = exports.MemberExpression = exports.TypeCheck = void 0;
31
- const index_1 = require("../errors/index");
32
- const index_2 = require("../system/index");
33
- const index_3 = require("../guard/index");
34
- const index_4 = require("../format/index");
35
- const index_5 = require("../custom/index");
36
- const index_6 = require("../hash/index");
37
- const Types = require("../typebox");
38
- // -------------------------------------------------------------------
39
- // TypeCheck
40
- // -------------------------------------------------------------------
41
- class TypeCheck {
42
- constructor(schema, references, checkFunc, code) {
43
- this.schema = schema;
44
- this.references = references;
45
- this.checkFunc = checkFunc;
46
- this.code = code;
47
- }
48
- /** Returns the generated validation code used to validate this type. */
49
- Code() {
50
- return this.code;
51
- }
52
- /** Returns an iterator for each error in this value. */
53
- Errors(value) {
54
- return index_1.ValueErrors.Errors(this.schema, this.references, value);
55
- }
56
- /** Returns true if the value matches the compiled type. */
57
- Check(value) {
58
- return this.checkFunc(value);
59
- }
60
- }
61
- exports.TypeCheck = TypeCheck;
62
- // -------------------------------------------------------------------
63
- // Character
64
- // -------------------------------------------------------------------
65
- var Character;
66
- (function (Character) {
67
- function DollarSign(code) {
68
- return code === 36;
69
- }
70
- Character.DollarSign = DollarSign;
71
- function Underscore(code) {
72
- return code === 95;
73
- }
74
- Character.Underscore = Underscore;
75
- function Numeric(code) {
76
- return code >= 48 && code <= 57;
77
- }
78
- Character.Numeric = Numeric;
79
- function Alpha(code) {
80
- return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
81
- }
82
- Character.Alpha = Alpha;
83
- })(Character || (Character = {}));
84
- // -------------------------------------------------------------------
85
- // Identifier
86
- // -------------------------------------------------------------------
87
- var Identifier;
88
- (function (Identifier) {
89
- function Encode($id) {
90
- const buffer = [];
91
- for (let i = 0; i < $id.length; i++) {
92
- const code = $id.charCodeAt(i);
93
- if (Character.Numeric(code) || Character.Alpha(code)) {
94
- buffer.push($id.charAt(i));
95
- }
96
- else {
97
- buffer.push(`_${code}_`);
98
- }
99
- }
100
- return buffer.join('').replace(/__/g, '_');
101
- }
102
- Identifier.Encode = Encode;
103
- })(Identifier || (Identifier = {}));
104
- // -------------------------------------------------------------------
105
- // MemberExpression
106
- // -------------------------------------------------------------------
107
- var MemberExpression;
108
- (function (MemberExpression) {
109
- function Check(propertyName) {
110
- if (propertyName.length === 0)
111
- return false;
112
- {
113
- const code = propertyName.charCodeAt(0);
114
- if (!(Character.DollarSign(code) || Character.Underscore(code) || Character.Alpha(code))) {
115
- return false;
116
- }
117
- }
118
- for (let i = 1; i < propertyName.length; i++) {
119
- const code = propertyName.charCodeAt(i);
120
- if (!(Character.DollarSign(code) || Character.Underscore(code) || Character.Alpha(code) || Character.Numeric(code))) {
121
- return false;
122
- }
123
- }
124
- return true;
125
- }
126
- function Encode(object, key) {
127
- return !Check(key) ? `${object}['${key}']` : `${object}.${key}`;
128
- }
129
- MemberExpression.Encode = Encode;
130
- })(MemberExpression = exports.MemberExpression || (exports.MemberExpression = {}));
131
- // -------------------------------------------------------------------
132
- // TypeCompiler
133
- // -------------------------------------------------------------------
134
- class TypeCompilerUnknownTypeError extends Error {
135
- constructor(schema) {
136
- super('TypeCompiler: Unknown type');
137
- this.schema = schema;
138
- }
139
- }
140
- exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError;
141
- /** Compiles Types for Runtime Type Checking */
142
- var TypeCompiler;
143
- (function (TypeCompiler) {
144
- // -------------------------------------------------------------------
145
- // Guards
146
- // -------------------------------------------------------------------
147
- function IsNumber(value) {
148
- return typeof value === 'number' && !globalThis.isNaN(value);
149
- }
150
- // -------------------------------------------------------------------
151
- // Types
152
- // -------------------------------------------------------------------
153
- function* Any(schema, value) {
154
- yield '(true)';
155
- }
156
- function* Array(schema, value) {
157
- const expression = CreateExpression(schema.items, 'value');
158
- yield `(Array.isArray(${value}) && ${value}.every(value => ${expression}))`;
159
- if (IsNumber(schema.minItems))
160
- yield `(${value}.length >= ${schema.minItems})`;
161
- if (IsNumber(schema.maxItems))
162
- yield `(${value}.length <= ${schema.maxItems})`;
163
- if (schema.uniqueItems === true)
164
- yield `((function() { const set = new Set(); for(const element of ${value}) { const hashed = hash(element); if(set.has(hashed)) { return false } else { set.add(hashed) } } return true })())`;
165
- }
166
- function* Boolean(schema, value) {
167
- yield `(typeof ${value} === 'boolean')`;
168
- }
169
- function* Constructor(schema, value) {
170
- yield* Visit(schema.returns, `${value}.prototype`);
171
- }
172
- function* Date(schema, value) {
173
- yield `(${value} instanceof Date) && !isNaN(${value}.getTime())`;
174
- if (IsNumber(schema.exclusiveMinimumTimestamp))
175
- yield `(${value}.getTime() > ${schema.exclusiveMinimumTimestamp})`;
176
- if (IsNumber(schema.exclusiveMaximumTimestamp))
177
- yield `(${value}.getTime() < ${schema.exclusiveMaximumTimestamp})`;
178
- if (IsNumber(schema.minimumTimestamp))
179
- yield `(${value}.getTime() >= ${schema.minimumTimestamp})`;
180
- if (IsNumber(schema.maximumTimestamp))
181
- yield `(${value}.getTime() <= ${schema.maximumTimestamp})`;
182
- }
183
- function* Function(schema, value) {
184
- yield `(typeof ${value} === 'function')`;
185
- }
186
- function* Integer(schema, value) {
187
- yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`;
188
- if (IsNumber(schema.multipleOf))
189
- yield `(${value} % ${schema.multipleOf} === 0)`;
190
- if (IsNumber(schema.exclusiveMinimum))
191
- yield `(${value} > ${schema.exclusiveMinimum})`;
192
- if (IsNumber(schema.exclusiveMaximum))
193
- yield `(${value} < ${schema.exclusiveMaximum})`;
194
- if (IsNumber(schema.minimum))
195
- yield `(${value} >= ${schema.minimum})`;
196
- if (IsNumber(schema.maximum))
197
- yield `(${value} <= ${schema.maximum})`;
198
- }
199
- function* Literal(schema, value) {
200
- if (typeof schema.const === 'number' || typeof schema.const === 'boolean') {
201
- yield `(${value} === ${schema.const})`;
202
- }
203
- else {
204
- yield `(${value} === '${schema.const}')`;
205
- }
206
- }
207
- function* Never(schema, value) {
208
- yield `(false)`;
209
- }
210
- function* Null(schema, value) {
211
- yield `(${value} === null)`;
212
- }
213
- function* Number(schema, value) {
214
- if (index_2.TypeSystem.AllowNaN) {
215
- yield `(typeof ${value} === 'number')`;
216
- }
217
- else {
218
- yield `(typeof ${value} === 'number' && !isNaN(${value}))`;
219
- }
220
- if (IsNumber(schema.multipleOf))
221
- yield `(${value} % ${schema.multipleOf} === 0)`;
222
- if (IsNumber(schema.exclusiveMinimum))
223
- yield `(${value} > ${schema.exclusiveMinimum})`;
224
- if (IsNumber(schema.exclusiveMaximum))
225
- yield `(${value} < ${schema.exclusiveMaximum})`;
226
- if (IsNumber(schema.minimum))
227
- yield `(${value} >= ${schema.minimum})`;
228
- if (IsNumber(schema.maximum))
229
- yield `(${value} <= ${schema.maximum})`;
230
- }
231
- function* Object(schema, value) {
232
- if (index_2.TypeSystem.AllowArrayObjects) {
233
- yield `(typeof ${value} === 'object' && ${value} !== null)`;
234
- }
235
- else {
236
- yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
237
- }
238
- if (IsNumber(schema.minProperties))
239
- yield `(Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties})`;
240
- if (IsNumber(schema.maxProperties))
241
- yield `(Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties})`;
242
- const propertyKeys = globalThis.Object.getOwnPropertyNames(schema.properties);
243
- if (schema.additionalProperties === false) {
244
- // Optimization: If the property key length matches the required keys length
245
- // then we only need check that the values property key length matches that
246
- // of the property key length. This is because exhaustive testing for values
247
- // will occur in subsequent property tests.
248
- if (schema.required && schema.required.length === propertyKeys.length) {
249
- yield `(Object.getOwnPropertyNames(${value}).length === ${propertyKeys.length})`;
250
- }
251
- else {
252
- const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`;
253
- yield `(Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key)))`;
254
- }
255
- }
256
- if (index_3.TypeGuard.TSchema(schema.additionalProperties)) {
257
- const expression = CreateExpression(schema.additionalProperties, 'value[key]');
258
- const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`;
259
- yield `(Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key) || ${expression}))`;
260
- }
261
- for (const propertyKey of propertyKeys) {
262
- const memberExpression = MemberExpression.Encode(value, propertyKey);
263
- const propertySchema = schema.properties[propertyKey];
264
- if (schema.required && schema.required.includes(propertyKey)) {
265
- yield* Visit(propertySchema, memberExpression);
266
- }
267
- else {
268
- const expression = CreateExpression(propertySchema, memberExpression);
269
- yield `(${memberExpression} === undefined ? true : (${expression}))`;
270
- }
271
- }
272
- }
273
- function* Promise(schema, value) {
274
- yield `(typeof value === 'object' && typeof ${value}.then === 'function')`;
275
- }
276
- function* Record(schema, value) {
277
- if (index_2.TypeSystem.AllowArrayObjects) {
278
- yield `(typeof ${value} === 'object' && ${value} !== null && !(${value} instanceof Date))`;
279
- }
280
- else {
281
- yield `(typeof ${value} === 'object' && ${value} !== null && !(${value} instanceof Date) && !Array.isArray(${value}))`;
282
- }
283
- const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
284
- const local = PushLocal(`new RegExp(/${keyPattern}/)`);
285
- yield `(Object.getOwnPropertyNames(${value}).every(key => ${local}.test(key)))`;
286
- const expression = CreateExpression(valueSchema, 'value');
287
- yield `(Object.values(${value}).every(value => ${expression}))`;
288
- }
289
- function* Ref(schema, value) {
290
- // Reference: If we have seen this reference before we can just yield and return
291
- // the function call. If this isn't the case we defer to visit to generate and
292
- // set the function for subsequent passes. Consider for refactor.
293
- if (state_local_function_names.has(schema.$ref))
294
- return yield `(${CreateFunctionName(schema.$ref)}(${value}))`;
295
- if (!state_reference_map.has(schema.$ref))
296
- throw Error(`TypeCompiler.Ref: Cannot de-reference schema with $id '${schema.$ref}'`);
297
- const reference = state_reference_map.get(schema.$ref);
298
- yield* Visit(reference, value);
299
- }
300
- function* Self(schema, value) {
301
- const func = CreateFunctionName(schema.$ref);
302
- yield `(${func}(${value}))`;
303
- }
304
- function* String(schema, value) {
305
- yield `(typeof ${value} === 'string')`;
306
- if (IsNumber(schema.minLength))
307
- yield `(${value}.length >= ${schema.minLength})`;
308
- if (IsNumber(schema.maxLength))
309
- yield `(${value}.length <= ${schema.maxLength})`;
310
- if (schema.pattern !== undefined) {
311
- const local = PushLocal(`${new RegExp(schema.pattern)};`);
312
- yield `(${local}.test(${value}))`;
313
- }
314
- if (schema.format !== undefined) {
315
- yield `(format('${schema.format}', ${value}))`;
316
- }
317
- }
318
- function* Tuple(schema, value) {
319
- yield `(Array.isArray(${value}))`;
320
- if (schema.items === undefined)
321
- return yield `(${value}.length === 0)`;
322
- yield `(${value}.length === ${schema.maxItems})`;
323
- for (let i = 0; i < schema.items.length; i++) {
324
- const expression = CreateExpression(schema.items[i], `${value}[${i}]`);
325
- yield `(${expression})`;
326
- }
327
- }
328
- function* Undefined(schema, value) {
329
- yield `(${value} === undefined)`;
330
- }
331
- function* Union(schema, value) {
332
- const expressions = schema.anyOf.map((schema) => CreateExpression(schema, value));
333
- yield `(${expressions.join(' || ')})`;
334
- }
335
- function* Uint8Array(schema, value) {
336
- yield `(${value} instanceof Uint8Array)`;
337
- if (IsNumber(schema.maxByteLength))
338
- yield `(${value}.length <= ${schema.maxByteLength})`;
339
- if (IsNumber(schema.minByteLength))
340
- yield `(${value}.length >= ${schema.minByteLength})`;
341
- }
342
- function* Unknown(schema, value) {
343
- yield '(true)';
344
- }
345
- function* Void(schema, value) {
346
- yield `(${value} === null)`;
347
- }
348
- function* UserDefined(schema, value) {
349
- const schema_key = `schema_key_${state_remote_custom_types.size}`;
350
- state_remote_custom_types.set(schema_key, schema);
351
- yield `(custom('${schema[Types.Kind]}', '${schema_key}', ${value}))`;
352
- }
353
- function* Visit(schema, value) {
354
- // Reference: Referenced schemas can originate from either additional schemas
355
- // or inline in the schema itself. Ideally the recursive path should align to
356
- // reference path. Consider for refactor.
357
- if (schema.$id && !state_local_function_names.has(schema.$id)) {
358
- state_local_function_names.add(schema.$id);
359
- const name = CreateFunctionName(schema.$id);
360
- const body = CreateFunction(name, schema, 'value');
361
- PushFunction(body);
362
- yield `(${name}(${value}))`;
363
- return;
364
- }
365
- const anySchema = schema;
366
- switch (anySchema[Types.Kind]) {
367
- case 'Any':
368
- return yield* Any(anySchema, value);
369
- case 'Array':
370
- return yield* Array(anySchema, value);
371
- case 'Boolean':
372
- return yield* Boolean(anySchema, value);
373
- case 'Constructor':
374
- return yield* Constructor(anySchema, value);
375
- case 'Date':
376
- return yield* Date(anySchema, value);
377
- case 'Function':
378
- return yield* Function(anySchema, value);
379
- case 'Integer':
380
- return yield* Integer(anySchema, value);
381
- case 'Literal':
382
- return yield* Literal(anySchema, value);
383
- case 'Never':
384
- return yield* Never(anySchema, value);
385
- case 'Null':
386
- return yield* Null(anySchema, value);
387
- case 'Number':
388
- return yield* Number(anySchema, value);
389
- case 'Object':
390
- return yield* Object(anySchema, value);
391
- case 'Promise':
392
- return yield* Promise(anySchema, value);
393
- case 'Record':
394
- return yield* Record(anySchema, value);
395
- case 'Ref':
396
- return yield* Ref(anySchema, value);
397
- case 'Self':
398
- return yield* Self(anySchema, value);
399
- case 'String':
400
- return yield* String(anySchema, value);
401
- case 'Tuple':
402
- return yield* Tuple(anySchema, value);
403
- case 'Undefined':
404
- return yield* Undefined(anySchema, value);
405
- case 'Union':
406
- return yield* Union(anySchema, value);
407
- case 'Uint8Array':
408
- return yield* Uint8Array(anySchema, value);
409
- case 'Unknown':
410
- return yield* Unknown(anySchema, value);
411
- case 'Void':
412
- return yield* Void(anySchema, value);
413
- default:
414
- if (!index_5.Custom.Has(anySchema[Types.Kind]))
415
- throw new TypeCompilerUnknownTypeError(schema);
416
- return yield* UserDefined(anySchema, value);
417
- }
418
- }
419
- // -------------------------------------------------------------------
420
- // Compiler State
421
- // -------------------------------------------------------------------
422
- const state_reference_map = new Map(); // tracks schemas with identifiers
423
- const state_local_variables = new Set(); // local variables and functions
424
- const state_local_function_names = new Set(); // local function names used call ref validators
425
- const state_remote_custom_types = new Map(); // remote custom types used during compilation
426
- function ResetCompiler() {
427
- state_reference_map.clear();
428
- state_local_variables.clear();
429
- state_local_function_names.clear();
430
- state_remote_custom_types.clear();
431
- }
432
- function AddReferences(schemas = []) {
433
- for (const schema of schemas) {
434
- if (!schema.$id)
435
- throw new Error(`TypeCompiler: Referenced schemas must specify an $id.`);
436
- if (state_reference_map.has(schema.$id))
437
- throw new Error(`TypeCompiler: Duplicate schema $id found for '${schema.$id}'`);
438
- state_reference_map.set(schema.$id, schema);
439
- }
440
- }
441
- function CreateExpression(schema, value) {
442
- return `(${[...Visit(schema, value)].join(' && ')})`;
443
- }
444
- function CreateFunctionName($id) {
445
- return `check_${Identifier.Encode($id)}`;
446
- }
447
- function CreateFunction(name, schema, value) {
448
- const expression = [...Visit(schema, value)].map((condition) => ` ${condition}`).join(' &&\n');
449
- return `function ${name}(value) {\n return (\n${expression}\n )\n}`;
450
- }
451
- function PushFunction(functionBody) {
452
- state_local_variables.add(functionBody);
453
- }
454
- function PushLocal(expression) {
455
- const local = `local_${state_local_variables.size}`;
456
- state_local_variables.add(`const ${local} = ${expression}`);
457
- return local;
458
- }
459
- function GetLocals() {
460
- return [...state_local_variables.values()];
461
- }
462
- // -------------------------------------------------------------------
463
- // Compile
464
- // -------------------------------------------------------------------
465
- function Build(schema, references = []) {
466
- ResetCompiler();
467
- AddReferences(references);
468
- const check = CreateFunction('check', schema, 'value');
469
- const locals = GetLocals();
470
- return `${locals.join('\n')}\nreturn ${check}`;
471
- }
472
- /** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
473
- function Compile(schema, references = []) {
474
- index_3.TypeGuard.Assert(schema, references);
475
- const code = Build(schema, references);
476
- const custom_schemas = new Map(state_remote_custom_types);
477
- const compiledFunction = globalThis.Function('custom', 'format', 'hash', code);
478
- const checkFunction = compiledFunction((kind, schema_key, value) => {
479
- if (!index_5.Custom.Has(kind) || !custom_schemas.has(schema_key))
480
- return false;
481
- const schema = custom_schemas.get(schema_key);
482
- const func = index_5.Custom.Get(kind);
483
- return func(schema, value);
484
- }, (format, value) => {
485
- if (!index_4.Format.Has(format))
486
- return false;
487
- const func = index_4.Format.Get(format);
488
- return func(value);
489
- }, (value) => {
490
- return index_6.ValueHash.Create(value);
491
- });
492
- return new TypeCheck(schema, references, checkFunction, code);
493
- }
494
- TypeCompiler.Compile = Compile;
495
- })(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {}));
1
+ "use strict";
2
+ /*--------------------------------------------------------------------------
3
+
4
+ @sinclair/typebox/compiler
5
+
6
+ The MIT License (MIT)
7
+
8
+ Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in
18
+ all copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26
+ THE SOFTWARE.
27
+
28
+ ---------------------------------------------------------------------------*/
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.TypeCompiler = exports.TypeCompilerUnknownTypeError = exports.TypeCheck = void 0;
31
+ const index_1 = require("../errors/index");
32
+ const index_2 = require("../system/index");
33
+ const index_3 = require("../guard/index");
34
+ const index_4 = require("../format/index");
35
+ const index_5 = require("../custom/index");
36
+ const index_6 = require("../hash/index");
37
+ const Types = require("../typebox");
38
+ // -------------------------------------------------------------------
39
+ // TypeCheck
40
+ // -------------------------------------------------------------------
41
+ class TypeCheck {
42
+ constructor(schema, references, checkFunc, code) {
43
+ this.schema = schema;
44
+ this.references = references;
45
+ this.checkFunc = checkFunc;
46
+ this.code = code;
47
+ }
48
+ /** Returns the generated validation code used to validate this type. */
49
+ Code() {
50
+ return this.code;
51
+ }
52
+ /** Returns an iterator for each error in this value. */
53
+ Errors(value) {
54
+ return index_1.ValueErrors.Errors(this.schema, this.references, value);
55
+ }
56
+ /** Returns true if the value matches the compiled type. */
57
+ Check(value) {
58
+ return this.checkFunc(value);
59
+ }
60
+ }
61
+ exports.TypeCheck = TypeCheck;
62
+ // -------------------------------------------------------------------
63
+ // Character
64
+ // -------------------------------------------------------------------
65
+ var Character;
66
+ (function (Character) {
67
+ function DollarSign(code) {
68
+ return code === 36;
69
+ }
70
+ Character.DollarSign = DollarSign;
71
+ function Underscore(code) {
72
+ return code === 95;
73
+ }
74
+ Character.Underscore = Underscore;
75
+ function Numeric(code) {
76
+ return code >= 48 && code <= 57;
77
+ }
78
+ Character.Numeric = Numeric;
79
+ function Alpha(code) {
80
+ return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
81
+ }
82
+ Character.Alpha = Alpha;
83
+ })(Character || (Character = {}));
84
+ // -------------------------------------------------------------------
85
+ // Identifier
86
+ // -------------------------------------------------------------------
87
+ var Identifier;
88
+ (function (Identifier) {
89
+ function Encode($id) {
90
+ const buffer = [];
91
+ for (let i = 0; i < $id.length; i++) {
92
+ const code = $id.charCodeAt(i);
93
+ if (Character.Numeric(code) || Character.Alpha(code)) {
94
+ buffer.push($id.charAt(i));
95
+ }
96
+ else {
97
+ buffer.push(`_${code}_`);
98
+ }
99
+ }
100
+ return buffer.join('').replace(/__/g, '_');
101
+ }
102
+ Identifier.Encode = Encode;
103
+ })(Identifier || (Identifier = {}));
104
+ // ------------------------------------------------------------------
105
+ // StringConstant
106
+ // ------------------------------------------------------------------
107
+ function IsString(value) {
108
+ return typeof value === 'string';
109
+ }
110
+ function StringConstant(value) {
111
+ if (!IsString(value))
112
+ throw Error('ConstantString: Not a String');
113
+ const canonical = JSON.stringify(value).slice(1, -1);
114
+ const escaped = canonical.replace(/'/g, "\\'");
115
+ return `'${escaped}'`;
116
+ }
117
+ // ------------------------------------------------------------------
118
+ // MemberExpression
119
+ // ------------------------------------------------------------------
120
+ function MemberExpression(value, key) {
121
+ return `${value}[${StringConstant(key)}]`;
122
+ }
123
+ // -------------------------------------------------------------------
124
+ // TypeCompiler
125
+ // -------------------------------------------------------------------
126
+ class TypeCompilerUnknownTypeError extends Error {
127
+ constructor(schema) {
128
+ super('TypeCompiler: Unknown type');
129
+ this.schema = schema;
130
+ }
131
+ }
132
+ exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError;
133
+ /** Compiles Types for Runtime Type Checking */
134
+ var TypeCompiler;
135
+ (function (TypeCompiler) {
136
+ // -------------------------------------------------------------------
137
+ // Guards
138
+ // -------------------------------------------------------------------
139
+ function IsNumber(value) {
140
+ return typeof value === 'number' && !globalThis.isNaN(value);
141
+ }
142
+ // -------------------------------------------------------------------
143
+ // Types
144
+ // -------------------------------------------------------------------
145
+ function* Any(schema, value) {
146
+ yield '(true)';
147
+ }
148
+ function* Array(schema, value) {
149
+ const expression = CreateExpression(schema.items, 'value');
150
+ yield `(Array.isArray(${value}) && ${value}.every(value => ${expression}))`;
151
+ if (IsNumber(schema.minItems))
152
+ yield `(${value}.length >= ${schema.minItems})`;
153
+ if (IsNumber(schema.maxItems))
154
+ yield `(${value}.length <= ${schema.maxItems})`;
155
+ if (schema.uniqueItems === true)
156
+ yield `((function() { const set = new Set(); for(const element of ${value}) { const hashed = hash(element); if(set.has(hashed)) { return false } else { set.add(hashed) } } return true })())`;
157
+ }
158
+ function* Boolean(schema, value) {
159
+ yield `(typeof ${value} === 'boolean')`;
160
+ }
161
+ function* Constructor(schema, value) {
162
+ yield* Visit(schema.returns, `${value}.prototype`);
163
+ }
164
+ function* Date(schema, value) {
165
+ yield `(${value} instanceof Date) && !isNaN(${value}.getTime())`;
166
+ if (IsNumber(schema.exclusiveMinimumTimestamp))
167
+ yield `(${value}.getTime() > ${schema.exclusiveMinimumTimestamp})`;
168
+ if (IsNumber(schema.exclusiveMaximumTimestamp))
169
+ yield `(${value}.getTime() < ${schema.exclusiveMaximumTimestamp})`;
170
+ if (IsNumber(schema.minimumTimestamp))
171
+ yield `(${value}.getTime() >= ${schema.minimumTimestamp})`;
172
+ if (IsNumber(schema.maximumTimestamp))
173
+ yield `(${value}.getTime() <= ${schema.maximumTimestamp})`;
174
+ }
175
+ function* Function(schema, value) {
176
+ yield `(typeof ${value} === 'function')`;
177
+ }
178
+ function* Integer(schema, value) {
179
+ yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`;
180
+ if (IsNumber(schema.multipleOf))
181
+ yield `(${value} % ${schema.multipleOf} === 0)`;
182
+ if (IsNumber(schema.exclusiveMinimum))
183
+ yield `(${value} > ${schema.exclusiveMinimum})`;
184
+ if (IsNumber(schema.exclusiveMaximum))
185
+ yield `(${value} < ${schema.exclusiveMaximum})`;
186
+ if (IsNumber(schema.minimum))
187
+ yield `(${value} >= ${schema.minimum})`;
188
+ if (IsNumber(schema.maximum))
189
+ yield `(${value} <= ${schema.maximum})`;
190
+ }
191
+ function* Literal(schema, value) {
192
+ if (typeof schema.const === 'number' || typeof schema.const === 'boolean') {
193
+ yield `(${value} === ${schema.const})`;
194
+ }
195
+ else if (typeof schema.const === 'string') {
196
+ yield `(${value} === ${StringConstant(schema.const)})`;
197
+ }
198
+ else {
199
+ throw Error('Invalid Literal Value');
200
+ }
201
+ }
202
+ function* Never(schema, value) {
203
+ yield `(false)`;
204
+ }
205
+ function* Null(schema, value) {
206
+ yield `(${value} === null)`;
207
+ }
208
+ function* Number(schema, value) {
209
+ if (index_2.TypeSystem.AllowNaN) {
210
+ yield `(typeof ${value} === 'number')`;
211
+ }
212
+ else {
213
+ yield `(typeof ${value} === 'number' && !isNaN(${value}))`;
214
+ }
215
+ if (IsNumber(schema.multipleOf))
216
+ yield `(${value} % ${schema.multipleOf} === 0)`;
217
+ if (IsNumber(schema.exclusiveMinimum))
218
+ yield `(${value} > ${schema.exclusiveMinimum})`;
219
+ if (IsNumber(schema.exclusiveMaximum))
220
+ yield `(${value} < ${schema.exclusiveMaximum})`;
221
+ if (IsNumber(schema.minimum))
222
+ yield `(${value} >= ${schema.minimum})`;
223
+ if (IsNumber(schema.maximum))
224
+ yield `(${value} <= ${schema.maximum})`;
225
+ }
226
+ function* Object(schema, value) {
227
+ if (index_2.TypeSystem.AllowArrayObjects) {
228
+ yield `(typeof ${value} === 'object' && ${value} !== null)`;
229
+ }
230
+ else {
231
+ yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
232
+ }
233
+ if (IsNumber(schema.minProperties))
234
+ yield `(Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties})`;
235
+ if (IsNumber(schema.maxProperties))
236
+ yield `(Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties})`;
237
+ const propertyKeys = globalThis.Object.getOwnPropertyNames(schema.properties);
238
+ if (schema.additionalProperties === false) {
239
+ // Optimization: If the property key length matches the required keys length
240
+ // then we only need check that the values property key length matches that
241
+ // of the property key length. This is because exhaustive testing for values
242
+ // will occur in subsequent property tests.
243
+ if (schema.required && schema.required.length === propertyKeys.length) {
244
+ yield `(Object.getOwnPropertyNames(${value}).length === ${propertyKeys.length})`;
245
+ }
246
+ else {
247
+ const keys = `[${propertyKeys.map((key) => `${StringConstant(key)}`).join(', ')}]`;
248
+ yield `(Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key)))`;
249
+ }
250
+ }
251
+ if (index_3.TypeGuard.TSchema(schema.additionalProperties)) {
252
+ const expression = CreateExpression(schema.additionalProperties, 'value[key]');
253
+ const keys = `[${propertyKeys.map((key) => `${StringConstant(key)}`).join(', ')}]`;
254
+ yield `(Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key) || ${expression}))`;
255
+ }
256
+ for (const propertyKey of propertyKeys) {
257
+ const memberExpression = MemberExpression(value, propertyKey);
258
+ const propertySchema = schema.properties[propertyKey];
259
+ if (schema.required && schema.required.includes(propertyKey)) {
260
+ yield* Visit(propertySchema, memberExpression);
261
+ if (index_3.TypeExtends.Undefined(propertySchema)) {
262
+ yield `(${StringConstant(propertyKey)} in ${value})`;
263
+ }
264
+ }
265
+ else {
266
+ const expression = CreateExpression(propertySchema, memberExpression);
267
+ yield `(${memberExpression} === undefined ? true : (${expression}))`;
268
+ }
269
+ }
270
+ }
271
+ function* Promise(schema, value) {
272
+ yield `(typeof value === 'object' && typeof ${value}.then === 'function')`;
273
+ }
274
+ function* Record(schema, value) {
275
+ if (index_2.TypeSystem.AllowArrayObjects) {
276
+ yield `(typeof ${value} === 'object' && ${value} !== null && !(${value} instanceof Date))`;
277
+ }
278
+ else {
279
+ yield `(typeof ${value} === 'object' && ${value} !== null && !(${value} instanceof Date) && !Array.isArray(${value}))`;
280
+ }
281
+ const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
282
+ const local = PushLocal(`${new RegExp(keyPattern)}`);
283
+ yield `(Object.getOwnPropertyNames(${value}).every(key => ${local}.test(key)))`;
284
+ const expression = CreateExpression(valueSchema, 'value');
285
+ yield `(Object.values(${value}).every(value => ${expression}))`;
286
+ }
287
+ function* Ref(schema, value) {
288
+ // Reference: If we have seen this reference before we can just yield and return
289
+ // the function call. If this isn't the case we defer to visit to generate and
290
+ // set the function for subsequent passes. Consider for refactor.
291
+ if (state_local_function_names.has(schema.$ref))
292
+ return yield `(${CreateFunctionName(schema.$ref)}(${value}))`;
293
+ if (!state_reference_map.has(schema.$ref))
294
+ throw Error(`TypeCompiler.Ref: Cannot de-reference schema with $id '${schema.$ref}'`);
295
+ const reference = state_reference_map.get(schema.$ref);
296
+ yield* Visit(reference, value);
297
+ }
298
+ function* Self(schema, value) {
299
+ const func = CreateFunctionName(schema.$ref);
300
+ yield `(${func}(${value}))`;
301
+ }
302
+ function* String(schema, value) {
303
+ yield `(typeof ${value} === 'string')`;
304
+ if (IsNumber(schema.minLength))
305
+ yield `(${value}.length >= ${schema.minLength})`;
306
+ if (IsNumber(schema.maxLength))
307
+ yield `(${value}.length <= ${schema.maxLength})`;
308
+ if (schema.pattern !== undefined) {
309
+ const local = PushLocal(`${new RegExp(schema.pattern)}`);
310
+ yield `(${local}.test(${value}))`;
311
+ }
312
+ if (schema.format !== undefined) {
313
+ yield `(format(${StringConstant(schema.format)}, ${value}))`;
314
+ }
315
+ }
316
+ function* Tuple(schema, value) {
317
+ yield `(Array.isArray(${value}))`;
318
+ if (schema.items === undefined)
319
+ return yield `(${value}.length === 0)`;
320
+ if (!IsNumber(schema.maxItems))
321
+ throw Error('MaxItems: Not a Number');
322
+ yield `(${value}.length === ${schema.maxItems})`;
323
+ for (let i = 0; i < schema.items.length; i++) {
324
+ const expression = CreateExpression(schema.items[i], `${value}[${i}]`);
325
+ yield `(${expression})`;
326
+ }
327
+ }
328
+ function* Undefined(schema, value) {
329
+ yield `(${value} === undefined)`;
330
+ }
331
+ function* Union(schema, value) {
332
+ const expressions = schema.anyOf.map((schema) => CreateExpression(schema, value));
333
+ yield `(${expressions.join(' || ')})`;
334
+ }
335
+ function* Uint8Array(schema, value) {
336
+ yield `(${value} instanceof Uint8Array)`;
337
+ if (IsNumber(schema.maxByteLength))
338
+ yield `(${value}.length <= ${schema.maxByteLength})`;
339
+ if (IsNumber(schema.minByteLength))
340
+ yield `(${value}.length >= ${schema.minByteLength})`;
341
+ }
342
+ function* Unknown(schema, value) {
343
+ yield '(true)';
344
+ }
345
+ function* Void(schema, value) {
346
+ yield `(${value} === null)`;
347
+ }
348
+ function* UserDefined(schema, value) {
349
+ const schema_key = `schema_key_${state_remote_custom_types.size}`;
350
+ state_remote_custom_types.set(schema_key, schema);
351
+ yield `(custom(${StringConstant(schema[Types.Kind])}, '${schema_key}', ${value}))`;
352
+ }
353
+ function* Visit(schema, value) {
354
+ // Reference: Referenced schemas can originate from either additional schemas
355
+ // or inline in the schema itself. Ideally the recursive path should align to
356
+ // reference path. Consider for refactor.
357
+ if (schema.$id && !state_local_function_names.has(schema.$id)) {
358
+ state_local_function_names.add(schema.$id);
359
+ const name = CreateFunctionName(schema.$id);
360
+ const body = CreateFunction(name, schema, 'value');
361
+ PushFunction(body);
362
+ yield `(${name}(${value}))`;
363
+ return;
364
+ }
365
+ const anySchema = schema;
366
+ switch (anySchema[Types.Kind]) {
367
+ case 'Any':
368
+ return yield* Any(anySchema, value);
369
+ case 'Array':
370
+ return yield* Array(anySchema, value);
371
+ case 'Boolean':
372
+ return yield* Boolean(anySchema, value);
373
+ case 'Constructor':
374
+ return yield* Constructor(anySchema, value);
375
+ case 'Date':
376
+ return yield* Date(anySchema, value);
377
+ case 'Function':
378
+ return yield* Function(anySchema, value);
379
+ case 'Integer':
380
+ return yield* Integer(anySchema, value);
381
+ case 'Literal':
382
+ return yield* Literal(anySchema, value);
383
+ case 'Never':
384
+ return yield* Never(anySchema, value);
385
+ case 'Null':
386
+ return yield* Null(anySchema, value);
387
+ case 'Number':
388
+ return yield* Number(anySchema, value);
389
+ case 'Object':
390
+ return yield* Object(anySchema, value);
391
+ case 'Promise':
392
+ return yield* Promise(anySchema, value);
393
+ case 'Record':
394
+ return yield* Record(anySchema, value);
395
+ case 'Ref':
396
+ return yield* Ref(anySchema, value);
397
+ case 'Self':
398
+ return yield* Self(anySchema, value);
399
+ case 'String':
400
+ return yield* String(anySchema, value);
401
+ case 'Tuple':
402
+ return yield* Tuple(anySchema, value);
403
+ case 'Undefined':
404
+ return yield* Undefined(anySchema, value);
405
+ case 'Union':
406
+ return yield* Union(anySchema, value);
407
+ case 'Uint8Array':
408
+ return yield* Uint8Array(anySchema, value);
409
+ case 'Unknown':
410
+ return yield* Unknown(anySchema, value);
411
+ case 'Void':
412
+ return yield* Void(anySchema, value);
413
+ default:
414
+ if (!index_5.Custom.Has(anySchema[Types.Kind]))
415
+ throw new TypeCompilerUnknownTypeError(schema);
416
+ return yield* UserDefined(anySchema, value);
417
+ }
418
+ }
419
+ // -------------------------------------------------------------------
420
+ // Compiler State
421
+ // -------------------------------------------------------------------
422
+ const state_reference_map = new Map(); // tracks schemas with identifiers
423
+ const state_local_variables = new Set(); // local variables and functions
424
+ const state_local_function_names = new Set(); // local function names used call ref validators
425
+ const state_remote_custom_types = new Map(); // remote custom types used during compilation
426
+ function ResetCompiler() {
427
+ state_reference_map.clear();
428
+ state_local_variables.clear();
429
+ state_local_function_names.clear();
430
+ state_remote_custom_types.clear();
431
+ }
432
+ function AddReferences(schemas = []) {
433
+ for (const schema of schemas) {
434
+ if (!schema.$id)
435
+ throw new Error(`TypeCompiler: Referenced schemas must specify an $id.`);
436
+ if (state_reference_map.has(schema.$id))
437
+ throw new Error(`TypeCompiler: Duplicate schema $id found for '${schema.$id}'`);
438
+ state_reference_map.set(schema.$id, schema);
439
+ }
440
+ }
441
+ function CreateExpression(schema, value) {
442
+ return `(${[...Visit(schema, value)].join(' && ')})`;
443
+ }
444
+ function CreateFunctionName($id) {
445
+ return `check_${Identifier.Encode($id)}`;
446
+ }
447
+ function CreateFunction(name, schema, value) {
448
+ const expression = [...Visit(schema, value)].map((condition) => ` ${condition}`).join(' &&\n');
449
+ return `function ${name}(value) {\n return (\n${expression}\n )\n}`;
450
+ }
451
+ function PushFunction(functionBody) {
452
+ state_local_variables.add(functionBody);
453
+ }
454
+ function PushLocal(expression) {
455
+ const local = `local_${state_local_variables.size}`;
456
+ state_local_variables.add(`const ${local} = ${expression}`);
457
+ return local;
458
+ }
459
+ function GetLocals() {
460
+ return [...state_local_variables.values()];
461
+ }
462
+ // -------------------------------------------------------------------
463
+ // Compile
464
+ // -------------------------------------------------------------------
465
+ function Build(schema, references = []) {
466
+ ResetCompiler();
467
+ AddReferences(references);
468
+ const check = CreateFunction('check', schema, 'value');
469
+ const locals = GetLocals();
470
+ return `${locals.join('\n')}\nreturn ${check}`;
471
+ }
472
+ /** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
473
+ function Compile(schema, references = []) {
474
+ index_3.TypeGuard.Assert(schema, references);
475
+ const code = Build(schema, references);
476
+ const custom_schemas = new Map(state_remote_custom_types);
477
+ const compiledFunction = globalThis.Function('custom', 'format', 'hash', code);
478
+ const checkFunction = compiledFunction((kind, schema_key, value) => {
479
+ if (!index_5.Custom.Has(kind) || !custom_schemas.has(schema_key))
480
+ return false;
481
+ const schema = custom_schemas.get(schema_key);
482
+ const func = index_5.Custom.Get(kind);
483
+ return func(schema, value);
484
+ }, (format, value) => {
485
+ if (!index_4.Format.Has(format))
486
+ return false;
487
+ const func = index_4.Format.Get(format);
488
+ return func(value);
489
+ }, (value) => {
490
+ return index_6.ValueHash.Create(value);
491
+ });
492
+ return new TypeCheck(schema, references, checkFunction, code);
493
+ }
494
+ TypeCompiler.Compile = Compile;
495
+ })(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {}));