@sinclair/typebox 0.24.5 → 0.24.8

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.
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  /*--------------------------------------------------------------------------
3
3
 
4
- @sinclair/typebox/value
4
+ @sinclair/typebox/guards
5
5
 
6
6
  The MIT License (MIT)
7
7
 
@@ -26,17 +26,15 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26
26
  THE SOFTWARE.
27
27
 
28
28
  ---------------------------------------------------------------------------*/
29
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
30
+ if (k2 === undefined) k2 = k;
31
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
32
+ }) : (function(o, m, k, k2) {
33
+ if (k2 === undefined) k2 = k;
34
+ o[k2] = m[k];
35
+ }));
36
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
37
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
38
+ };
29
39
  Object.defineProperty(exports, "__esModule", { value: true });
30
- exports.Reflect = void 0;
31
- function Reflect(value) {
32
- if (value === undefined)
33
- return 'undefined';
34
- if (value === null)
35
- return 'null';
36
- if (typeof value === 'object' && !globalThis.Array.isArray(value) && value !== null)
37
- return 'object';
38
- if (typeof value === 'object' && globalThis.Array.isArray(value))
39
- return 'array';
40
- return typeof value;
41
- }
42
- exports.Reflect = Reflect;
40
+ __exportStar(require("./guard"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sinclair/typebox",
3
- "version": "0.24.5",
3
+ "version": "0.24.8",
4
4
  "description": "JSONSchema Type Builder with Static Type Resolution for TypeScript",
5
5
  "keywords": [
6
6
  "json-schema",
package/readme.md CHANGED
@@ -62,6 +62,7 @@ License MIT
62
62
  - [Generic Types](#Generic-Types)
63
63
  - [Unsafe Types](#Unsafe-Types)
64
64
  - [Values](#Values)
65
+ - [Guards](#Guards)
65
66
  - [Strict](#Strict)
66
67
  - [Validation](#Validation)
67
68
  - [Compiler](#Compiler)
@@ -435,7 +436,7 @@ In addition to JSON schema types, TypeBox provides several extended types that a
435
436
  │ │ │ │
436
437
  ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
437
438
  │ const T = Type.Uint8Array() │ type T = Uint8Array │ const T = { │
438
- │ │ │ type: 'Uint8Array',
439
+ │ │ │ type: 'object',
439
440
  │ │ │ specialized: 'Uint8Array' │
440
441
  │ │ │ } │
441
442
  │ │ │ │
@@ -449,7 +450,8 @@ In addition to JSON schema types, TypeBox provides several extended types that a
449
450
  │ │ │ │
450
451
  ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
451
452
  │ const T = Type.Undefined() │ type T = undefined │ const T = { │
452
- │ │ │ type: 'undefined'
453
+ │ │ │ type: 'object',
454
+ │ │ │ specialized: 'Undefined' │
453
455
  │ │ │ } │
454
456
  │ │ │ │
455
457
  ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
@@ -600,28 +602,65 @@ const T = StringEnum(['A', 'B', 'C']) // const T = {
600
602
 
601
603
  type T = Static<typeof T> // type T = 'A' | 'B' | 'C'
602
604
  ```
605
+
603
606
  <a name="Values"></a>
604
607
 
605
608
  ### Values
606
609
 
607
- TypeBox can construct default values for types. TypeBox will create reasonable defaults for any given type, or produce values based on the schemas the `default` value if specified.
610
+ TypeBox can create values from types. It creates reasonable defaults for each value which can overrided by specifying a `default` value.
608
611
 
609
612
  ```typescript
610
613
  import { Value } from '@sinclair/typebox/value'
611
- import { Type } from '@sinclair/typebox'
614
+ import { Type } from '@sinclair/typebox'
612
615
 
613
616
  const T = Type.Object({
614
617
  x: Type.Number({ default: 1 }),
615
- y: Type.Number({ default: 2 }),
616
- z: Type.Number()
618
+ y: Type.Number(),
617
619
  })
618
620
 
619
621
  const V = Value.Create(T) // const V = {
620
622
  // x: 1,
621
- // y: 2,
622
- // z: 0
623
+ // y: 0,
623
624
  // }
624
625
  ```
626
+ TypeBox also allows values to be upgraded to match the schematics of a given type. The `Value.Cast(...)` function can be used to upgrade a value into a target type while retaining as much information of the original value as possible. Casts are immutable operations.
627
+
628
+ ```typescript
629
+ import { Value } from '@sinclair/typebox/value'
630
+ import { Type } from '@sinclair/typebox'
631
+
632
+ const T = Type.Object({
633
+ x: Type.Number(),
634
+ y: Type.Number()
635
+ })
636
+
637
+ const A = Value.Cast(T, null) // const A = { x: 0, y: 0 }
638
+
639
+ const B = Value.Cast(T, { x: 1 }) // const B = { x: 1, y: 0 }
640
+
641
+ const C = Value.Cast(T, { x: 1, y: 2, z: 3 }) // const C = { x: 1, y: 2 }
642
+ ```
643
+
644
+ <a name="Guards"></a>
645
+
646
+ ### Guards
647
+
648
+ If reflecting on TypeBox types, it can be helpful to test if a value matches a TypeBox schematic. This can be achieved using the TypeGuard namespace. The TypeGuard namespace offers exhaustive checks for each known TypeBox type.
649
+
650
+ ```typescript
651
+ import { TypeGuard } from '@sinclair/typebox/guard'
652
+ import { Type } from '@sinclair/typebox'
653
+
654
+ const T: any = {} // T is any
655
+
656
+ const { type } = T // unsafe: type is any
657
+
658
+ if(TypeGuard.TString(T)) {
659
+
660
+ const { type } = T // safe: type is 'string'
661
+ }
662
+
663
+ ```
625
664
 
626
665
  <a name="Strict"></a>
627
666
 
@@ -702,7 +741,7 @@ const ajv = addFormats(new Ajv({}), [
702
741
  //
703
742
  //--------------------------------------------------------------------------------------------
704
743
 
705
- const Vector = Type.Object({
744
+ const T = Type.Object({
706
745
  x: Type.Number(),
707
746
  y: Type.Number(),
708
747
  z: Type.Number(),
@@ -714,7 +753,7 @@ const Vector = Type.Object({
714
753
  //
715
754
  //--------------------------------------------------------------------------------------------
716
755
 
717
- const OK = ajv.validate(Vector, {
756
+ const OK = ajv.validate(T, {
718
757
  x: 1,
719
758
  y: 2,
720
759
  z: 3
@@ -727,7 +766,7 @@ Please refer to the official AJV [documentation](https://ajv.js.org/guide/gettin
727
766
 
728
767
  ### Compiler
729
768
 
730
- TypeBox includes a specialized type compiler that can be used as a runtime type checker in absense of a JSON Schema validator. This compiler is optimized for high throughput validation scenarios and generally performs better than AJV for most structural checks. Please note that this compiler is not fully JSON Schema compliant and is limited to TypeBox types only. The `TypeCompiler` contains a `Compile(T)` function that returns a `TypeCheck<T>` object that can be used to test the validity of a value as well as obtain errors.
769
+ TypeBox includes a specialized `TypeCompiler` that can be used as a runtime type checker in lieu of a JSON Schema validator. This compiler is optimized for high throughput Web Socket messaging and can perform better than AJV for some structural checks. Please note that this compiler is not fully JSON Schema compliant and is limited to known TypeBox types only. The `TypeCompiler` contains a `Compile(T)` function that returns a `TypeCheck<T>` object that can be used to test the validity of a value as well as obtain errors.
731
770
 
732
771
  ```typescript
733
772
  import { TypeCompiler } from '@sinclair/typebox/compiler'
@@ -747,7 +786,7 @@ const OK = C.Check({
747
786
  z: 3
748
787
  }) // -> true
749
788
  ```
750
- Errors can be obtained by calling the `Errors(...)` function. This function returns an iterator that may contain zero or more errors for the given value. For performance, you should only call `Errors(V)` if the `Check(V)` function returns false.
789
+ Errors can be obtained by calling the `Errors(...)` function. This function returns an iterator that may contain zero or more errors for the given value. For performance, you should only call `Errors(V)` if the `Check(V)` function returns `false`.
751
790
  ```typescript
752
791
  const C = TypeCompiler.Compile(Type.Object({
753
792
  x: Type.Number(),
@@ -763,7 +802,7 @@ if(!C.Check(V)) {
763
802
  }
764
803
  }
765
804
  ```
766
- To inspect the generated validation code created by the compiler. You can call the `Code()` function on the `TypeCheck<T>` object.
805
+ The TypeCompiler generates JavaScript validation routines types that are evaluated at runtime. You can inspect the generated code by calling the `Code()` function of the `TypeCheck<T>` object.
767
806
 
768
807
  ```typescript
769
808
  const C = TypeCompiler.Compile(Type.String())
@@ -783,4 +822,4 @@ console.log(C.Code())
783
822
 
784
823
  ### Contribute
785
824
 
786
- TypeBox is open to community contribution, however please ensure you submit an open issue before submitting your pull request. The TypeBox project does preference open community discussion prior to accepting new features.
825
+ TypeBox is open to community contribution. Please ensure you submit an open issue before submitting your pull request. The TypeBox project preferences open community discussion prior to accepting new features.
package/typebox.d.ts CHANGED
@@ -22,12 +22,10 @@ export interface SchemaOptions {
22
22
  title?: string;
23
23
  /** Description of this schema */
24
24
  description?: string;
25
- /** Default value hint for this schema */
25
+ /** Default value for this schema */
26
26
  default?: any;
27
27
  /** Example values matching this schema. */
28
28
  examples?: any;
29
- /** Design metadata for this schema */
30
- design?: DesignType;
31
29
  [prop: string]: any;
32
30
  }
33
31
  export interface TSchema extends SchemaOptions {
@@ -0,0 +1,5 @@
1
+ import * as Types from '../typebox';
2
+ export declare namespace ValueCast {
3
+ function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any): any;
4
+ function Cast<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: any): Types.Static<T>;
5
+ }
package/value/cast.js ADDED
@@ -0,0 +1,251 @@
1
+ "use strict";
2
+ /*--------------------------------------------------------------------------
3
+
4
+ @sinclair/typebox/value
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.ValueCast = void 0;
31
+ const Types = require("../typebox");
32
+ const create_1 = require("./create");
33
+ const check_1 = require("./check");
34
+ // --------------------------------------------------------------------------
35
+ // Specialized Union Patch. Because a value can be one of many different
36
+ // unions with properties potentially overlapping, we need a strategy
37
+ // in which to resolve the appropriate schema to patch from.
38
+ //
39
+ // The following will score each union type found within the types anyOf
40
+ // array. Typically this is executed for objects only, so the score is a
41
+ // essentially a tally of how many properties are valid. The reasoning
42
+ // here is the discriminator field would tip the scales in favor of that
43
+ // union if other properties overlap and match.
44
+ // --------------------------------------------------------------------------
45
+ var UnionValueCast;
46
+ (function (UnionValueCast) {
47
+ function Score(schema, references, value) {
48
+ let score = 0;
49
+ if (schema[Types.Kind] === 'Object' && typeof value === 'object' && value !== null) {
50
+ const objectSchema = schema;
51
+ const entries = globalThis.Object.entries(objectSchema.properties);
52
+ score += entries.reduce((acc, [key, schema]) => acc + (check_1.ValueCheck.Check(schema, references, value[key]) ? 1 : 0), 0);
53
+ }
54
+ return score;
55
+ }
56
+ function Select(schema, references, value) {
57
+ let select = schema.anyOf[0];
58
+ let best = 0;
59
+ for (const subschema of schema.anyOf) {
60
+ const score = Score(subschema, references, value);
61
+ if (score > best) {
62
+ select = subschema;
63
+ best = score;
64
+ }
65
+ }
66
+ return select;
67
+ }
68
+ function Create(schema, references, value) {
69
+ return check_1.ValueCheck.Check(schema, references, value) ? value : ValueCast.Cast(Select(schema, references, value), references, value);
70
+ }
71
+ UnionValueCast.Create = Create;
72
+ })(UnionValueCast || (UnionValueCast = {}));
73
+ var ValueCast;
74
+ (function (ValueCast) {
75
+ const ids = new Map();
76
+ function Any(schema, references, value) {
77
+ return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
78
+ }
79
+ function Array(schema, references, value) {
80
+ if (check_1.ValueCheck.Check(schema, references, value))
81
+ return value;
82
+ if (!globalThis.Array.isArray(value))
83
+ return create_1.ValueCreate.Create(schema, references);
84
+ return value.map((val) => Visit(schema.items, references, val));
85
+ }
86
+ function Boolean(schema, references, value) {
87
+ return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
88
+ }
89
+ function Constructor(schema, references, value) {
90
+ if (check_1.ValueCheck.Check(schema, references, value))
91
+ return create_1.ValueCreate.Create(schema, references);
92
+ const required = new Set(schema.returns.required || []);
93
+ const result = function () { };
94
+ for (const [key, property] of globalThis.Object.entries(schema.returns.properties)) {
95
+ if (!required.has(key) && value.prototype[key] === undefined)
96
+ continue;
97
+ result.prototype[key] = Visit(property, references, value.prototype[key]);
98
+ }
99
+ return result;
100
+ }
101
+ function Enum(schema, references, value) {
102
+ return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
103
+ }
104
+ function Function(schema, references, value) {
105
+ return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
106
+ }
107
+ function Integer(schema, references, value) {
108
+ return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
109
+ }
110
+ function Literal(schema, references, value) {
111
+ return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
112
+ }
113
+ function Null(schema, references, value) {
114
+ return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
115
+ }
116
+ function Number(schema, references, value) {
117
+ return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
118
+ }
119
+ function Object(schema, references, value) {
120
+ if (check_1.ValueCheck.Check(schema, references, value))
121
+ return value;
122
+ if (value === null || typeof value !== 'object')
123
+ return create_1.ValueCreate.Create(schema, references);
124
+ ids.set(schema.$id, schema);
125
+ const required = new Set(schema.required || []);
126
+ const result = {};
127
+ for (const [key, property] of globalThis.Object.entries(schema.properties)) {
128
+ if (!required.has(key) && value[key] === undefined)
129
+ continue;
130
+ result[key] = Visit(property, references, value[key]);
131
+ }
132
+ return result;
133
+ }
134
+ function Promise(schema, references, value) {
135
+ return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
136
+ }
137
+ function Record(schema, references, value) {
138
+ if (check_1.ValueCheck.Check(schema, references, value))
139
+ return value;
140
+ if (value === null || typeof value !== 'object' || globalThis.Array.isArray(value))
141
+ return create_1.ValueCreate.Create(schema, references);
142
+ const subschemaKey = globalThis.Object.keys(schema.patternProperties)[0];
143
+ const subschema = schema.patternProperties[subschemaKey];
144
+ const result = {};
145
+ for (const [propKey, propValue] of globalThis.Object.entries(value)) {
146
+ result[propKey] = Visit(subschema, references, propValue);
147
+ }
148
+ return result;
149
+ }
150
+ function Recursive(schema, references, value) {
151
+ throw Error('Cannot patch recursive schemas');
152
+ }
153
+ function Ref(schema, references, value) {
154
+ const reference = references.find((reference) => reference.$id === schema.$ref);
155
+ if (reference === undefined)
156
+ throw new Error(`CastValue.Ref: Cannot find schema with $id '${schema.$ref}'.`);
157
+ return Visit(reference, references, value);
158
+ }
159
+ function Self(schema, references, value) {
160
+ const reference = references.find((reference) => reference.$id === schema.$ref);
161
+ if (reference === undefined)
162
+ throw new Error(`CastValue.Self: Cannot find schema with $id '${schema.$ref}'.`);
163
+ return Visit(reference, references, value);
164
+ }
165
+ function String(schema, references, value) {
166
+ return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
167
+ }
168
+ function Tuple(schema, references, value) {
169
+ if (check_1.ValueCheck.Check(schema, references, value))
170
+ return value;
171
+ if (!globalThis.Array.isArray(value))
172
+ return create_1.ValueCreate.Create(schema, references);
173
+ if (schema.items === undefined)
174
+ return [];
175
+ return schema.items.map((schema, index) => Visit(schema, references, value[index]));
176
+ }
177
+ function Undefined(schema, references, value) {
178
+ return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
179
+ }
180
+ function Union(schema, references, value) {
181
+ return UnionValueCast.Create(schema, references, value);
182
+ }
183
+ function Uint8Array(schema, references, value) {
184
+ return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
185
+ }
186
+ function Unknown(schema, references, value) {
187
+ return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
188
+ }
189
+ function Void(schema, references, value) {
190
+ return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
191
+ }
192
+ function Visit(schema, references, value) {
193
+ const anyReferences = schema.$id === undefined ? references : [schema, ...references];
194
+ const anySchema = schema;
195
+ switch (schema[Types.Kind]) {
196
+ case 'Any':
197
+ return Any(anySchema, anyReferences, value);
198
+ case 'Array':
199
+ return Array(anySchema, anyReferences, value);
200
+ case 'Boolean':
201
+ return Boolean(anySchema, anyReferences, value);
202
+ case 'Constructor':
203
+ return Constructor(anySchema, anyReferences, value);
204
+ case 'Enum':
205
+ return Enum(anySchema, anyReferences, value);
206
+ case 'Function':
207
+ return Function(anySchema, anyReferences, value);
208
+ case 'Integer':
209
+ return Integer(anySchema, anyReferences, value);
210
+ case 'Literal':
211
+ return Literal(anySchema, anyReferences, value);
212
+ case 'Null':
213
+ return Null(anySchema, anyReferences, value);
214
+ case 'Number':
215
+ return Number(anySchema, anyReferences, value);
216
+ case 'Object':
217
+ return Object(anySchema, anyReferences, value);
218
+ case 'Promise':
219
+ return Promise(anySchema, anyReferences, value);
220
+ case 'Record':
221
+ return Record(anySchema, anyReferences, value);
222
+ case 'Rec':
223
+ return Recursive(anySchema, anyReferences, value);
224
+ case 'Ref':
225
+ return Ref(anySchema, anyReferences, value);
226
+ case 'Self':
227
+ return Self(anySchema, anyReferences, value);
228
+ case 'String':
229
+ return String(anySchema, anyReferences, value);
230
+ case 'Tuple':
231
+ return Tuple(anySchema, anyReferences, value);
232
+ case 'Undefined':
233
+ return Undefined(anySchema, anyReferences, value);
234
+ case 'Union':
235
+ return Union(anySchema, anyReferences, value);
236
+ case 'Uint8Array':
237
+ return Uint8Array(anySchema, anyReferences, value);
238
+ case 'Unknown':
239
+ return Unknown(anySchema, anyReferences, value);
240
+ case 'Void':
241
+ return Void(anySchema, anyReferences, value);
242
+ default:
243
+ throw Error(`Unknown schema kind '${schema[Types.Kind]}'`);
244
+ }
245
+ }
246
+ ValueCast.Visit = Visit;
247
+ function Cast(schema, references, value) {
248
+ return schema.$id === undefined ? Visit(schema, references, value) : Visit(schema, [schema, ...references], value);
249
+ }
250
+ ValueCast.Cast = Cast;
251
+ })(ValueCast = exports.ValueCast || (exports.ValueCast = {}));
package/value/check.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import * as Types from '../typebox';
2
- export declare namespace CheckValue {
3
- function Visit<T extends Types.TSchema>(schema: T, value: any): boolean;
4
- function Check<T extends Types.TSchema>(schema: T, value: any): boolean;
2
+ export declare namespace ValueCheck {
3
+ function Check<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: any): boolean;
5
4
  }