@sinclair/typebox 0.24.50 → 0.24.52

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 (47) hide show
  1. package/compiler/compiler.d.ts +25 -28
  2. package/compiler/compiler.js +408 -409
  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 +657 -657
  11. package/errors/errors.d.ts +60 -60
  12. package/errors/errors.js +398 -398
  13. package/errors/index.d.ts +1 -1
  14. package/errors/index.js +44 -44
  15. package/format/format.d.ts +12 -12
  16. package/format/format.js +55 -55
  17. package/format/index.d.ts +1 -1
  18. package/format/index.js +44 -44
  19. package/guard/guard.d.ts +56 -56
  20. package/guard/guard.js +351 -351
  21. package/guard/index.d.ts +1 -1
  22. package/guard/index.js +44 -44
  23. package/license +22 -22
  24. package/package.json +43 -40
  25. package/readme.md +1152 -1152
  26. package/typebox.d.ts +408 -408
  27. package/typebox.js +383 -383
  28. package/value/cast.d.ts +26 -26
  29. package/value/cast.js +364 -364
  30. package/value/check.d.ts +8 -8
  31. package/value/check.js +331 -331
  32. package/value/clone.d.ts +3 -3
  33. package/value/clone.js +65 -65
  34. package/value/create.d.ts +14 -14
  35. package/value/create.js +357 -357
  36. package/value/delta.d.ts +22 -22
  37. package/value/delta.js +168 -168
  38. package/value/equal.d.ts +3 -3
  39. package/value/equal.js +74 -74
  40. package/value/index.d.ts +3 -3
  41. package/value/index.js +48 -48
  42. package/value/is.d.ts +10 -10
  43. package/value/is.js +49 -49
  44. package/value/pointer.d.ts +24 -24
  45. package/value/pointer.js +142 -142
  46. package/value/value.d.ts +31 -31
  47. package/value/value.js +81 -81
@@ -1,409 +1,408 @@
1
- "use strict";
2
- /*--------------------------------------------------------------------------
3
-
4
- @sinclair/typebox/compiler
5
-
6
- The MIT License (MIT)
7
-
8
- Copyright (c) 2022 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.Property = exports.TypeCheck = void 0;
31
- const index_1 = require("../errors/index");
32
- const index_2 = require("../guard/index");
33
- const index_3 = require("../format/index");
34
- const Types = require("../typebox");
35
- // -------------------------------------------------------------------
36
- // TypeCheck
37
- // -------------------------------------------------------------------
38
- class TypeCheck {
39
- constructor(schema, references, checkFunc, code) {
40
- this.schema = schema;
41
- this.references = references;
42
- this.checkFunc = checkFunc;
43
- this.code = code;
44
- }
45
- /** Returns the generated validation code used to validate this type. */
46
- Code() {
47
- return this.code;
48
- }
49
- /** Returns an iterator for each error in this value. */
50
- Errors(value) {
51
- return index_1.ValueErrors.Errors(this.schema, this.references, value);
52
- }
53
- /** Returns true if the value matches the given type. */
54
- Check(value) {
55
- return this.checkFunc(value);
56
- }
57
- }
58
- exports.TypeCheck = TypeCheck;
59
- // -------------------------------------------------------------------
60
- // Property
61
- // -------------------------------------------------------------------
62
- var Property;
63
- (function (Property) {
64
- function DollarSign(code) {
65
- return code === 36;
66
- }
67
- function Underscore(code) {
68
- return code === 95;
69
- }
70
- function Numeric(code) {
71
- return code >= 48 && code <= 57;
72
- }
73
- function Alpha(code) {
74
- return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
75
- }
76
- function Check(propertyName) {
77
- if (propertyName.length === 0)
78
- return false;
79
- {
80
- const code = propertyName.charCodeAt(0);
81
- if (!(DollarSign(code) || Underscore(code) || Alpha(code))) {
82
- return false;
83
- }
84
- }
85
- for (let i = 1; i < propertyName.length; i++) {
86
- const code = propertyName.charCodeAt(i);
87
- if (!(DollarSign(code) || Underscore(code) || Alpha(code) || Numeric(code))) {
88
- return false;
89
- }
90
- }
91
- return true;
92
- }
93
- Property.Check = Check;
94
- })(Property = exports.Property || (exports.Property = {}));
95
- // -------------------------------------------------------------------
96
- // TypeCompiler
97
- // -------------------------------------------------------------------
98
- class TypeCompilerUnknownTypeError extends Error {
99
- constructor(schema) {
100
- super('TypeCompiler: Unknown type');
101
- this.schema = schema;
102
- }
103
- }
104
- exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError;
105
- /** Compiles Types for Runtime Type Checking */
106
- var TypeCompiler;
107
- (function (TypeCompiler) {
108
- // -------------------------------------------------------------------
109
- // Types
110
- // -------------------------------------------------------------------
111
- function* Any(schema, value) {
112
- yield '(true)';
113
- }
114
- function* Array(schema, value) {
115
- const expression = CreateExpression(schema.items, 'value');
116
- if (schema.minItems !== undefined)
117
- yield `(${value}.length >= ${schema.minItems})`;
118
- if (schema.maxItems !== undefined)
119
- yield `(${value}.length <= ${schema.maxItems})`;
120
- if (schema.uniqueItems !== undefined)
121
- yield `(new Set(${value}).size === ${value}.length)`;
122
- yield `(Array.isArray(${value}) && ${value}.every(value => ${expression}))`;
123
- }
124
- function* Boolean(schema, value) {
125
- yield `(typeof ${value} === 'boolean')`;
126
- }
127
- function* Constructor(schema, value) {
128
- yield* Visit(schema.returns, `${value}.prototype`);
129
- }
130
- function* Function(schema, value) {
131
- yield `(typeof ${value} === 'function')`;
132
- }
133
- function* Integer(schema, value) {
134
- yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`;
135
- if (schema.multipleOf !== undefined)
136
- yield `(${value} % ${schema.multipleOf} === 0)`;
137
- if (schema.exclusiveMinimum !== undefined)
138
- yield `(${value} > ${schema.exclusiveMinimum})`;
139
- if (schema.exclusiveMaximum !== undefined)
140
- yield `(${value} < ${schema.exclusiveMaximum})`;
141
- if (schema.minimum !== undefined)
142
- yield `(${value} >= ${schema.minimum})`;
143
- if (schema.maximum !== undefined)
144
- yield `(${value} <= ${schema.maximum})`;
145
- }
146
- function* Literal(schema, value) {
147
- if (typeof schema.const === 'number' || typeof schema.const === 'boolean') {
148
- yield `(${value} === ${schema.const})`;
149
- }
150
- else {
151
- yield `(${value} === '${schema.const}')`;
152
- }
153
- }
154
- function* Never(schema, value) {
155
- yield `(false)`;
156
- }
157
- function* Null(schema, value) {
158
- yield `(${value} === null)`;
159
- }
160
- function* Number(schema, value) {
161
- yield `(typeof ${value} === 'number')`;
162
- if (schema.multipleOf !== undefined)
163
- yield `(${value} % ${schema.multipleOf} === 0)`;
164
- if (schema.exclusiveMinimum !== undefined)
165
- yield `(${value} > ${schema.exclusiveMinimum})`;
166
- if (schema.exclusiveMaximum !== undefined)
167
- yield `(${value} < ${schema.exclusiveMaximum})`;
168
- if (schema.minimum !== undefined)
169
- yield `(${value} >= ${schema.minimum})`;
170
- if (schema.maximum !== undefined)
171
- yield `(${value} <= ${schema.maximum})`;
172
- }
173
- function* Object(schema, value) {
174
- yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
175
- if (schema.minProperties !== undefined)
176
- yield `(Object.keys(${value}).length >= ${schema.minProperties})`;
177
- if (schema.maxProperties !== undefined)
178
- yield `(Object.keys(${value}).length <= ${schema.maxProperties})`;
179
- const propertyKeys = globalThis.Object.keys(schema.properties);
180
- if (schema.additionalProperties === false) {
181
- // Optimization: If the property key length matches the required keys length
182
- // then we only need check that the values property key length matches that
183
- // of the property key length. This is because exhaustive testing for values
184
- // will occur in subsequent property tests.
185
- if (schema.required && schema.required.length === propertyKeys.length) {
186
- yield `(Object.keys(${value}).length === ${propertyKeys.length})`;
187
- }
188
- else {
189
- const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`;
190
- yield `(Object.keys(${value}).every(key => ${keys}.includes(key)))`;
191
- }
192
- }
193
- if (index_2.TypeGuard.TSchema(schema.additionalProperties)) {
194
- const expression = CreateExpression(schema.additionalProperties, 'value[key]');
195
- const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`;
196
- yield `(Object.keys(${value}).every(key => ${keys}.includes(key) || ${expression}))`;
197
- }
198
- for (const propertyKey of propertyKeys) {
199
- const memberExpression = Property.Check(propertyKey) ? `${value}.${propertyKey}` : `${value}['${propertyKey}']`;
200
- const propertySchema = schema.properties[propertyKey];
201
- if (schema.required && schema.required.includes(propertyKey)) {
202
- yield* Visit(propertySchema, memberExpression);
203
- }
204
- else {
205
- const expression = CreateExpression(propertySchema, memberExpression);
206
- yield `(${memberExpression} === undefined ? true : (${expression}))`;
207
- }
208
- }
209
- }
210
- function* Promise(schema, value) {
211
- yield `(typeof value === 'object' && typeof ${value}.then === 'function')`;
212
- }
213
- function* Record(schema, value) {
214
- yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
215
- const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
216
- const local = PushLocal(`new RegExp(/${keyPattern}/)`);
217
- yield `(Object.keys(${value}).every(key => ${local}.test(key)))`;
218
- const expression = CreateExpression(valueSchema, 'value');
219
- yield `(Object.values(${value}).every(value => ${expression}))`;
220
- }
221
- function* Ref(schema, value) {
222
- // Reference: If we have seen this reference before we can just yield and return
223
- // the function call. If this isn't the case we defer to visit to generate and
224
- // set the function for subsequent passes. Consider for refactor.
225
- if (names.has(schema.$ref))
226
- return yield `(${CreateFunctionName(schema.$ref)}(${value}))`;
227
- if (!referenceMap.has(schema.$ref))
228
- throw Error(`TypeCompiler.Ref: Cannot de-reference schema with $id '${schema.$ref}'`);
229
- const reference = referenceMap.get(schema.$ref);
230
- yield* Visit(reference, value);
231
- }
232
- function* Self(schema, value) {
233
- const func = CreateFunctionName(schema.$ref);
234
- yield `(${func}(${value}))`;
235
- }
236
- function* String(schema, value) {
237
- yield `(typeof ${value} === 'string')`;
238
- if (schema.minLength !== undefined) {
239
- yield `(${value}.length >= ${schema.minLength})`;
240
- }
241
- if (schema.maxLength !== undefined) {
242
- yield `(${value}.length <= ${schema.maxLength})`;
243
- }
244
- if (schema.pattern !== undefined) {
245
- const local = PushLocal(`new RegExp(/${schema.pattern}/);`);
246
- yield `(${local}.test(${value}))`;
247
- }
248
- if (schema.format !== undefined) {
249
- yield `(format('${schema.format}', ${value}))`;
250
- }
251
- }
252
- function* Tuple(schema, value) {
253
- yield `(Array.isArray(${value}))`;
254
- if (schema.items === undefined)
255
- return yield `(${value}.length === 0)`;
256
- yield `(${value}.length === ${schema.maxItems})`;
257
- for (let i = 0; i < schema.items.length; i++) {
258
- const expression = CreateExpression(schema.items[i], `${value}[${i}]`);
259
- yield `(${expression})`;
260
- }
261
- }
262
- function* Undefined(schema, value) {
263
- yield `(${value} === undefined)`;
264
- }
265
- function* Union(schema, value) {
266
- const expressions = schema.anyOf.map((schema) => CreateExpression(schema, value));
267
- yield `(${expressions.join(' || ')})`;
268
- }
269
- function* Uint8Array(schema, value) {
270
- yield `(${value} instanceof Uint8Array)`;
271
- if (schema.maxByteLength)
272
- yield `(${value}.length <= ${schema.maxByteLength})`;
273
- if (schema.minByteLength)
274
- yield `(${value}.length >= ${schema.minByteLength})`;
275
- }
276
- function* Unknown(schema, value) {
277
- yield '(true)';
278
- }
279
- function* Void(schema, value) {
280
- yield `(${value} === null)`;
281
- }
282
- function* Visit(schema, value) {
283
- // Reference: Referenced schemas can originate from either additional schemas
284
- // or inline in the schema itself. Ideally the recursive path should align to
285
- // reference path. Consider for refactor.
286
- if (schema.$id && !names.has(schema.$id)) {
287
- names.add(schema.$id);
288
- const name = CreateFunctionName(schema.$id);
289
- const body = CreateFunction(name, schema, 'value');
290
- PushFunction(body);
291
- yield `(${name}(${value}))`;
292
- return;
293
- }
294
- const anySchema = schema;
295
- switch (anySchema[Types.Kind]) {
296
- case 'Any':
297
- return yield* Any(anySchema, value);
298
- case 'Array':
299
- return yield* Array(anySchema, value);
300
- case 'Boolean':
301
- return yield* Boolean(anySchema, value);
302
- case 'Constructor':
303
- return yield* Constructor(anySchema, value);
304
- case 'Function':
305
- return yield* Function(anySchema, value);
306
- case 'Integer':
307
- return yield* Integer(anySchema, value);
308
- case 'Literal':
309
- return yield* Literal(anySchema, value);
310
- case 'Never':
311
- return yield* Never(anySchema, value);
312
- case 'Null':
313
- return yield* Null(anySchema, value);
314
- case 'Number':
315
- return yield* Number(anySchema, value);
316
- case 'Object':
317
- return yield* Object(anySchema, value);
318
- case 'Promise':
319
- return yield* Promise(anySchema, value);
320
- case 'Record':
321
- return yield* Record(anySchema, value);
322
- case 'Ref':
323
- return yield* Ref(anySchema, value);
324
- case 'Self':
325
- return yield* Self(anySchema, value);
326
- case 'String':
327
- return yield* String(anySchema, value);
328
- case 'Tuple':
329
- return yield* Tuple(anySchema, value);
330
- case 'Undefined':
331
- return yield* Undefined(anySchema, value);
332
- case 'Union':
333
- return yield* Union(anySchema, value);
334
- case 'Uint8Array':
335
- return yield* Uint8Array(anySchema, value);
336
- case 'Unknown':
337
- return yield* Unknown(anySchema, value);
338
- case 'Void':
339
- return yield* Void(anySchema, value);
340
- default:
341
- throw new TypeCompilerUnknownTypeError(schema);
342
- }
343
- }
344
- // -------------------------------------------------------------------
345
- // Compile State
346
- // -------------------------------------------------------------------
347
- const referenceMap = new Map();
348
- const locals = new Set(); // local variables and functions
349
- const names = new Set(); // cache of local functions
350
- function ResetCompiler() {
351
- referenceMap.clear();
352
- locals.clear();
353
- names.clear();
354
- }
355
- function AddReferences(schemas = []) {
356
- for (const schema of schemas) {
357
- if (!schema.$id)
358
- throw new Error(`TypeCompiler: Referenced schemas must specify an $id.`);
359
- if (referenceMap.has(schema.$id))
360
- throw new Error(`TypeCompiler: Duplicate schema $id found for '${schema.$id}'`);
361
- referenceMap.set(schema.$id, schema);
362
- }
363
- }
364
- function CreateExpression(schema, value) {
365
- return [...Visit(schema, value)].join(' && ');
366
- }
367
- function CreateFunctionName($id) {
368
- return `check_${$id.replace(/-/g, '_')}`;
369
- }
370
- function CreateFunction(name, schema, value) {
371
- const expression = [...Visit(schema, value)].map((condition) => ` ${condition}`).join(' &&\n');
372
- return `function ${name}(value) {\n return (\n${expression}\n )\n}`;
373
- }
374
- function PushFunction(functionBody) {
375
- locals.add(functionBody);
376
- }
377
- function PushLocal(expression) {
378
- const local = `local_${locals.size}`;
379
- locals.add(`const ${local} = ${expression}`);
380
- return local;
381
- }
382
- function GetLocals() {
383
- return [...locals.values()];
384
- }
385
- // -------------------------------------------------------------------
386
- // Compile
387
- // -------------------------------------------------------------------
388
- function Build(schema, references = []) {
389
- ResetCompiler();
390
- AddReferences(references);
391
- const check = CreateFunction('check', schema, 'value');
392
- const locals = GetLocals();
393
- return `${locals.join('\n')}\nreturn ${check}`;
394
- }
395
- /** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
396
- function Compile(schema, references = []) {
397
- index_2.TypeGuard.Assert(schema, references);
398
- const code = Build(schema, references);
399
- const func1 = globalThis.Function('format', code);
400
- const func2 = func1((format, value) => {
401
- if (!index_3.Format.Has(format))
402
- return false;
403
- const func = index_3.Format.Get(format);
404
- return func(value);
405
- });
406
- return new TypeCheck(schema, references, func2, code);
407
- }
408
- TypeCompiler.Compile = Compile;
409
- })(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {}));
1
+ "use strict";
2
+ /*--------------------------------------------------------------------------
3
+
4
+ @sinclair/typebox/compiler
5
+
6
+ The MIT License (MIT)
7
+
8
+ Copyright (c) 2022 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("../guard/index");
33
+ const index_3 = require("../format/index");
34
+ const Types = require("../typebox");
35
+ // -------------------------------------------------------------------
36
+ // TypeCheck
37
+ // -------------------------------------------------------------------
38
+ class TypeCheck {
39
+ constructor(schema, references, checkFunc, code) {
40
+ this.schema = schema;
41
+ this.references = references;
42
+ this.checkFunc = checkFunc;
43
+ this.code = code;
44
+ }
45
+ /** Returns the generated validation code used to validate this type. */
46
+ Code() {
47
+ return this.code;
48
+ }
49
+ /** Returns an iterator for each error in this value. */
50
+ Errors(value) {
51
+ return index_1.ValueErrors.Errors(this.schema, this.references, value);
52
+ }
53
+ /** Returns true if the value matches the given type. */
54
+ Check(value) {
55
+ return this.checkFunc(value);
56
+ }
57
+ }
58
+ exports.TypeCheck = TypeCheck;
59
+ // ------------------------------------------------------------------
60
+ // Guards
61
+ // ------------------------------------------------------------------
62
+ function IsNumber(value) {
63
+ return value !== undefined && typeof value === 'number';
64
+ }
65
+ function IsBoolean(value) {
66
+ return value !== undefined && typeof value === 'boolean';
67
+ }
68
+ function IsString(value) {
69
+ return value !== undefined && typeof value === 'string';
70
+ }
71
+ // ------------------------------------------------------------------
72
+ // StringConstant
73
+ // ------------------------------------------------------------------
74
+ function StringConstant(value) {
75
+ if (!IsString(value))
76
+ throw Error('ConstantString: Not a String');
77
+ const canonical = JSON.stringify(value).slice(1, -1);
78
+ const escaped = canonical.replace(/'/g, "\\'");
79
+ return `'${escaped}'`;
80
+ }
81
+ // ------------------------------------------------------------------
82
+ // MemberExpression
83
+ // ------------------------------------------------------------------
84
+ function MemberExpression(value, key) {
85
+ return `${value}[${StringConstant(key)}]`;
86
+ }
87
+ // -------------------------------------------------------------------
88
+ // TypeCompiler
89
+ // -------------------------------------------------------------------
90
+ class TypeCompilerUnknownTypeError extends Error {
91
+ constructor(schema) {
92
+ super('TypeCompiler: Unknown type');
93
+ this.schema = schema;
94
+ }
95
+ }
96
+ exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError;
97
+ /** Compiles Types for Runtime Type Checking */
98
+ var TypeCompiler;
99
+ (function (TypeCompiler) {
100
+ // -------------------------------------------------------------------
101
+ // Types
102
+ // -------------------------------------------------------------------
103
+ function* Any(schema, value) {
104
+ yield '(true)';
105
+ }
106
+ function* Array(schema, value) {
107
+ const expression = CreateExpression(schema.items, 'value');
108
+ if (IsNumber(schema.minItems))
109
+ yield `(${value}.length >= ${schema.minItems})`;
110
+ if (IsNumber(schema.maxItems))
111
+ yield `(${value}.length <= ${schema.maxItems})`;
112
+ if (IsBoolean(schema.uniqueItems))
113
+ yield `(new Set(${value}).size === ${value}.length)`;
114
+ yield `(Array.isArray(${value}) && ${value}.every(value => ${expression}))`;
115
+ }
116
+ function* Boolean(schema, value) {
117
+ yield `(typeof ${value} === 'boolean')`;
118
+ }
119
+ function* Constructor(schema, value) {
120
+ yield* Visit(schema.returns, `${value}.prototype`);
121
+ }
122
+ function* Function(schema, value) {
123
+ yield `(typeof ${value} === 'function')`;
124
+ }
125
+ function* Integer(schema, value) {
126
+ yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`;
127
+ if (IsNumber(schema.multipleOf))
128
+ yield `(${value} % ${schema.multipleOf} === 0)`;
129
+ if (IsNumber(schema.exclusiveMinimum))
130
+ yield `(${value} > ${schema.exclusiveMinimum})`;
131
+ if (IsNumber(schema.exclusiveMaximum))
132
+ yield `(${value} < ${schema.exclusiveMaximum})`;
133
+ if (IsNumber(schema.minimum))
134
+ yield `(${value} >= ${schema.minimum})`;
135
+ if (IsNumber(schema.maximum))
136
+ yield `(${value} <= ${schema.maximum})`;
137
+ }
138
+ function* Literal(schema, value) {
139
+ if (typeof schema.const === 'number' || typeof schema.const === 'boolean') {
140
+ yield `(${value} === ${schema.const})`;
141
+ }
142
+ else if (typeof schema.const === 'string') {
143
+ yield `(${value} === ${StringConstant(schema.const)})`;
144
+ }
145
+ else {
146
+ throw Error('Invalid Literal Value');
147
+ }
148
+ }
149
+ function* Never(schema, value) {
150
+ yield `(false)`;
151
+ }
152
+ function* Null(schema, value) {
153
+ yield `(${value} === null)`;
154
+ }
155
+ function* Number(schema, value) {
156
+ yield `(typeof ${value} === 'number')`;
157
+ if (IsNumber(schema.multipleOf))
158
+ yield `(${value} % ${schema.multipleOf} === 0)`;
159
+ if (IsNumber(schema.exclusiveMinimum))
160
+ yield `(${value} > ${schema.exclusiveMinimum})`;
161
+ if (IsNumber(schema.exclusiveMaximum))
162
+ yield `(${value} < ${schema.exclusiveMaximum})`;
163
+ if (IsNumber(schema.minimum))
164
+ yield `(${value} >= ${schema.minimum})`;
165
+ if (IsNumber(schema.maximum))
166
+ yield `(${value} <= ${schema.maximum})`;
167
+ }
168
+ function* Object(schema, value) {
169
+ yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
170
+ if (IsNumber(schema.minProperties))
171
+ yield `(Object.keys(${value}).length >= ${schema.minProperties})`;
172
+ if (IsNumber(schema.maxProperties))
173
+ yield `(Object.keys(${value}).length <= ${schema.maxProperties})`;
174
+ const propertyKeys = globalThis.Object.keys(schema.properties);
175
+ if (schema.additionalProperties === false) {
176
+ // Optimization: If the property key length matches the required keys length
177
+ // then we only need check that the values property key length matches that
178
+ // of the property key length. This is because exhaustive testing for values
179
+ // will occur in subsequent property tests.
180
+ if (schema.required && schema.required.length === propertyKeys.length) {
181
+ yield `(Object.keys(${value}).length === ${propertyKeys.length})`;
182
+ }
183
+ else {
184
+ const keys = `[${propertyKeys.map((key) => `${StringConstant(key)}`).join(', ')}]`;
185
+ yield `(Object.keys(${value}).every(key => ${keys}.includes(key)))`;
186
+ }
187
+ }
188
+ if (index_2.TypeGuard.TSchema(schema.additionalProperties)) {
189
+ const expression = CreateExpression(schema.additionalProperties, 'value[key]');
190
+ const keys = `[${propertyKeys.map((key) => `${StringConstant(key)}`).join(', ')}]`;
191
+ yield `(Object.keys(${value}).every(key => ${keys}.includes(key) || ${expression}))`;
192
+ }
193
+ for (const propertyKey of propertyKeys) {
194
+ const memberExpression = MemberExpression(value, propertyKey);
195
+ const propertySchema = schema.properties[propertyKey];
196
+ if (schema.required && schema.required.includes(propertyKey)) {
197
+ yield* Visit(propertySchema, memberExpression);
198
+ }
199
+ else {
200
+ const expression = CreateExpression(propertySchema, memberExpression);
201
+ yield `(${memberExpression} === undefined ? true : (${expression}))`;
202
+ }
203
+ }
204
+ }
205
+ function* Promise(schema, value) {
206
+ yield `(typeof value === 'object' && typeof ${value}.then === 'function')`;
207
+ }
208
+ function* Record(schema, value) {
209
+ yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
210
+ const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
211
+ const local = PushLocal(`${new RegExp(keyPattern)}`);
212
+ yield `(Object.keys(${value}).every(key => ${local}.test(key)))`;
213
+ const expression = CreateExpression(valueSchema, 'value');
214
+ yield `(Object.values(${value}).every(value => ${expression}))`;
215
+ }
216
+ function* Ref(schema, value) {
217
+ // Reference: If we have seen this reference before we can just yield and return
218
+ // the function call. If this isn't the case we defer to visit to generate and
219
+ // set the function for subsequent passes. Consider for refactor.
220
+ if (names.has(schema.$ref))
221
+ return yield `(${CreateFunctionName(schema.$ref)}(${value}))`;
222
+ if (!referenceMap.has(schema.$ref))
223
+ throw Error(`TypeCompiler.Ref: Cannot de-reference schema with $id '${schema.$ref}'`);
224
+ const reference = referenceMap.get(schema.$ref);
225
+ yield* Visit(reference, value);
226
+ }
227
+ function* Self(schema, value) {
228
+ const func = CreateFunctionName(schema.$ref);
229
+ yield `(${func}(${value}))`;
230
+ }
231
+ function* String(schema, value) {
232
+ yield `(typeof ${value} === 'string')`;
233
+ if (IsNumber(schema.minLength)) {
234
+ yield `(${value}.length >= ${schema.minLength})`;
235
+ }
236
+ if (IsNumber(schema.maxLength)) {
237
+ yield `(${value}.length <= ${schema.maxLength})`;
238
+ }
239
+ if (IsString(schema.pattern)) {
240
+ const local = PushLocal(`${new RegExp(schema.pattern)}`);
241
+ yield `(${local}.test(${value}))`;
242
+ }
243
+ if (schema.format !== undefined) {
244
+ yield `(format(${StringConstant(schema.format)}, ${value}))`;
245
+ }
246
+ }
247
+ function* Tuple(schema, value) {
248
+ yield `(Array.isArray(${value}))`;
249
+ if (schema.items === undefined)
250
+ return yield `(${value}.length === 0)`;
251
+ if (!IsNumber(schema.maxItems))
252
+ throw Error('MaxItems: Not a Number');
253
+ yield `(${value}.length === ${schema.maxItems})`;
254
+ for (let i = 0; i < schema.items.length; i++) {
255
+ const expression = CreateExpression(schema.items[i], `${value}[${i}]`);
256
+ yield `(${expression})`;
257
+ }
258
+ }
259
+ function* Undefined(schema, value) {
260
+ yield `(${value} === undefined)`;
261
+ }
262
+ function* Union(schema, value) {
263
+ const expressions = schema.anyOf.map((schema) => CreateExpression(schema, value));
264
+ yield `(${expressions.join(' || ')})`;
265
+ }
266
+ function* Uint8Array(schema, value) {
267
+ yield `(${value} instanceof Uint8Array)`;
268
+ if (IsNumber(schema.maxByteLength))
269
+ yield `(${value}.length <= ${schema.maxByteLength})`;
270
+ if (IsNumber(schema.minByteLength))
271
+ yield `(${value}.length >= ${schema.minByteLength})`;
272
+ }
273
+ function* Unknown(schema, value) {
274
+ yield '(true)';
275
+ }
276
+ function* Void(schema, value) {
277
+ yield `(${value} === null)`;
278
+ }
279
+ function* Visit(schema, value) {
280
+ // Reference: Referenced schemas can originate from either additional schemas
281
+ // or inline in the schema itself. Ideally the recursive path should align to
282
+ // reference path. Consider for refactor.
283
+ if (schema.$id && !names.has(schema.$id)) {
284
+ names.add(schema.$id);
285
+ const name = CreateFunctionName(schema.$id);
286
+ const body = CreateFunction(name, schema, 'value');
287
+ PushFunction(body);
288
+ yield `(${name}(${value}))`;
289
+ return;
290
+ }
291
+ const anySchema = schema;
292
+ switch (anySchema[Types.Kind]) {
293
+ case 'Any':
294
+ return yield* Any(anySchema, value);
295
+ case 'Array':
296
+ return yield* Array(anySchema, value);
297
+ case 'Boolean':
298
+ return yield* Boolean(anySchema, value);
299
+ case 'Constructor':
300
+ return yield* Constructor(anySchema, value);
301
+ case 'Function':
302
+ return yield* Function(anySchema, value);
303
+ case 'Integer':
304
+ return yield* Integer(anySchema, value);
305
+ case 'Literal':
306
+ return yield* Literal(anySchema, value);
307
+ case 'Never':
308
+ return yield* Never(anySchema, value);
309
+ case 'Null':
310
+ return yield* Null(anySchema, value);
311
+ case 'Number':
312
+ return yield* Number(anySchema, value);
313
+ case 'Object':
314
+ return yield* Object(anySchema, value);
315
+ case 'Promise':
316
+ return yield* Promise(anySchema, value);
317
+ case 'Record':
318
+ return yield* Record(anySchema, value);
319
+ case 'Ref':
320
+ return yield* Ref(anySchema, value);
321
+ case 'Self':
322
+ return yield* Self(anySchema, value);
323
+ case 'String':
324
+ return yield* String(anySchema, value);
325
+ case 'Tuple':
326
+ return yield* Tuple(anySchema, value);
327
+ case 'Undefined':
328
+ return yield* Undefined(anySchema, value);
329
+ case 'Union':
330
+ return yield* Union(anySchema, value);
331
+ case 'Uint8Array':
332
+ return yield* Uint8Array(anySchema, value);
333
+ case 'Unknown':
334
+ return yield* Unknown(anySchema, value);
335
+ case 'Void':
336
+ return yield* Void(anySchema, value);
337
+ default:
338
+ throw new TypeCompilerUnknownTypeError(schema);
339
+ }
340
+ }
341
+ // -------------------------------------------------------------------
342
+ // Compile State
343
+ // -------------------------------------------------------------------
344
+ const referenceMap = new Map();
345
+ const locals = new Set(); // local variables and functions
346
+ const names = new Set(); // cache of local functions
347
+ function ResetCompiler() {
348
+ referenceMap.clear();
349
+ locals.clear();
350
+ names.clear();
351
+ }
352
+ function AddReferences(schemas = []) {
353
+ for (const schema of schemas) {
354
+ if (!schema.$id)
355
+ throw new Error(`TypeCompiler: Referenced schemas must specify an $id.`);
356
+ if (referenceMap.has(schema.$id))
357
+ throw new Error(`TypeCompiler: Duplicate schema $id found for '${schema.$id}'`);
358
+ referenceMap.set(schema.$id, schema);
359
+ }
360
+ }
361
+ function CreateExpression(schema, value) {
362
+ return [...Visit(schema, value)].join(' && ');
363
+ }
364
+ function CreateFunctionName($id) {
365
+ if (!/^[a-zA-Z0-9_-]+$/.test($id))
366
+ throw Error(`Invalid $id: '${$id}'`);
367
+ return `check_${$id.replace(/-/g, '_')}`;
368
+ }
369
+ function CreateFunction(name, schema, value) {
370
+ const expression = [...Visit(schema, value)].map((condition) => ` ${condition}`).join(' &&\n');
371
+ return `function ${name}(value) {\n return (\n${expression}\n )\n}`;
372
+ }
373
+ function PushFunction(functionBody) {
374
+ locals.add(functionBody);
375
+ }
376
+ function PushLocal(expression) {
377
+ const local = `local_${locals.size}`;
378
+ locals.add(`const ${local} = ${expression}`);
379
+ return local;
380
+ }
381
+ function GetLocals() {
382
+ return [...locals.values()];
383
+ }
384
+ // -------------------------------------------------------------------
385
+ // Compile
386
+ // -------------------------------------------------------------------
387
+ function Build(schema, references = []) {
388
+ ResetCompiler();
389
+ AddReferences(references);
390
+ const check = CreateFunction('check', schema, 'value');
391
+ const locals = GetLocals();
392
+ return `${locals.join('\n')}\nreturn ${check}`;
393
+ }
394
+ /** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
395
+ function Compile(schema, references = []) {
396
+ index_2.TypeGuard.Assert(schema, references);
397
+ const code = Build(schema, references);
398
+ const func1 = globalThis.Function('format', code);
399
+ const func2 = func1((format, value) => {
400
+ if (!index_3.Format.Has(format))
401
+ return false;
402
+ const func = index_3.Format.Get(format);
403
+ return func(value);
404
+ });
405
+ return new TypeCheck(schema, references, func2, code);
406
+ }
407
+ TypeCompiler.Compile = Compile;
408
+ })(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {}));