Skip to content

Commit 4e2158d

Browse files
committed
Standard Schema Reference
1 parent 4833af5 commit 4e2158d

File tree

3 files changed

+164
-0
lines changed

3 files changed

+164
-0
lines changed

Diff for: example/standard/index.ts

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*--------------------------------------------------------------------------
2+
3+
@sinclair/typebox/standard-schema
4+
5+
The MIT License (MIT)
6+
7+
Copyright (c) 2024 Haydn Paterson (sinclair) <[email protected]>
8+
9+
Permission is hereby granted, free of charge, to any person obtaining a copy
10+
of this software and associated documentation files (the "Software"), to deal
11+
in the Software without restriction, including without limitation the rights
12+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13+
copies of the Software, and to permit persons to whom the Software is
14+
furnished to do so, subject to the following conditions:
15+
16+
The above copyright notice and this permission notice shall be included in
17+
all copies or substantial portions of the Software.
18+
19+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25+
THE SOFTWARE.
26+
27+
---------------------------------------------------------------------------*/
28+
29+
export * from './standard'

Diff for: example/standard/readme.md

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
### Standard Schema
2+
3+
This example is a reference implementation of [Standard Schema](https://github.com/standard-schema/standard-schema) for TypeBox.
4+
5+
### Overview
6+
7+
This example provides a reference implementation for the Standard Schema specification. Despite the name, this specification is NOT focused on schematics. Rather, it defines a set of common TypeScript interfaces that libraries are expected to implement to be considered "Standard" for framework integration, as defined by the specification's authors.
8+
9+
The TypeBox project has some concerns about the Standard Schema specification, particularly regarding its avoidance to separate concerns between schematics and the logic used to validate those schematics. TypeBox does respect such separation for direct interoperability with industry standard validators as well as to allow intermediate processing of types (Compile). Additionally, augmenting schematics in the way proposed by Standard Schema would render Json Schema invalidated (which is a general concern for interoperability with Json Schema validation infrastructure, such as Ajv).
10+
11+
The Standard Schema specification is currently in its RFC stage. TypeBox advocates for renaming the specification to better reflect its purpose, such as "Common Interface for Type Integration." Additionally, the requirement for type libraries to adopt a common interface for integration warrants review. The reference project link provided below demonstrates an alternative approach that would enable integration of all type libraries (including those not immediately compatible with Standard Schema) to be integrated into frameworks (such as tRPC) without modification to a library's core structure.
12+
13+
[Type Adapters](https://github.com/sinclairzx81/type-adapters)
14+
15+
### Example
16+
17+
The Standard Schema function will augment TypeBox's Json Schema with runtime validation methods. These methods are assigned to the sub property `~standard`. Once a type is augmented, it should no longer be considered valid Json Schema.
18+
19+
```typescript
20+
import { Type } from '@sinclair/typebox'
21+
import { StandardSchema } from './standard'
22+
23+
// The Standard Schema function will augment a TypeBox type with runtime validation
24+
// logic to validate / parse a value (as mandated by the Standard Schema interfaces).
25+
// Calling this function will render the json-schema schematics invalidated, specifically
26+
// the non-standard keyword `~standard` which ideally should be expressed as a non
27+
// serializable symbol (Ajv strict)
28+
29+
const A = StandardSchema(Type.Object({ // const A = {
30+
x: Type.Number(), // '~standard': { version: 1, vendor: 'TypeBox', validate: [Function: validate] },
31+
y: Type.Number(), // type: 'object',
32+
z: Type.Number(), // properties: {
33+
})) // x: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' },
34+
// y: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' },
35+
// z: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' }
36+
// },
37+
// required: [ 'x', 'y', 'z' ],
38+
// [Symbol(TypeBox.Kind)]: 'Object'
39+
// }
40+
41+
const R = A['~standard'].validate({ x: 1, y: 2, z: 3 }) // const R = { value: { x: 1, y: 2, z: 3 }, issues: [] }
42+
```
43+
44+
### Ajv Strict
45+
46+
Applying Standard Schema to a TypeBox types renders them unusable in Ajv. The issue is due to the `~standard` property being un-assignable as a keyword (due to the leading `~`)
47+
48+
```typescript
49+
import Ajv from 'ajv'
50+
51+
const ajv = new Ajv().addKeyword('~standard') // cannot be defined as keyword.
52+
53+
const A = StandardSchema(Type.Object({ // const A = {
54+
x: Type.Number(), // '~standard': { version: 1, vendor: 'TypeBox', validate: [Function: validate] },
55+
y: Type.Number(), // type: 'object',
56+
z: Type.Number(), // properties: {
57+
})) // x: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' },
58+
// y: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' },
59+
// z: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' }
60+
// },
61+
// required: [ 'x', 'y', 'z' ],
62+
// [Symbol(TypeBox.Kind)]: 'Object'
63+
// }
64+
65+
66+
ajv.validate(A, { x: 1, y: 2, z: 3 }) // Error: Keyword ~standard has invalid name
67+
```

Diff for: example/standard/standard.ts

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*--------------------------------------------------------------------------
2+
3+
@sinclair/typebox/standard-schema
4+
5+
The MIT License (MIT)
6+
7+
Copyright (c) 2024 Haydn Paterson (sinclair) <[email protected]>
8+
9+
Permission is hereby granted, free of charge, to any person obtaining a copy
10+
of this software and associated documentation files (the "Software"), to deal
11+
in the Software without restriction, including without limitation the rights
12+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13+
copies of the Software, and to permit persons to whom the Software is
14+
furnished to do so, subject to the following conditions:
15+
16+
The above copyright notice and this permission notice shall be included in
17+
all copies or substantial portions of the Software.
18+
19+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25+
THE SOFTWARE.
26+
27+
---------------------------------------------------------------------------*/
28+
29+
import { AssertError, Value, ValueError } from '@sinclair/typebox/value'
30+
import { TSchema, StaticDecode, CloneType } from '@sinclair/typebox'
31+
32+
// ------------------------------------------------------------------
33+
// StandardSchema: Common
34+
// ------------------------------------------------------------------
35+
interface StandardResult<Output> {
36+
value: Output
37+
issues: [ValueError[]]
38+
}
39+
interface StandardSchema<Input = unknown, Output = Input> {
40+
readonly "~standard": StandardSchemaProps<Input, Output>;
41+
}
42+
43+
interface StandardSchemaProps<Input = unknown, Output = Input> {
44+
readonly version: 1;
45+
readonly vendor: 'TypeBox';
46+
readonly validate: (value: unknown) => StandardResult<Output>;
47+
readonly types?: undefined;
48+
}
49+
// ------------------------------------------------------------------
50+
// StandardSchema: TypeBox
51+
// ------------------------------------------------------------------
52+
export type TStandardSchema<Input = unknown, Output = Input, Result = Input & StandardSchema<Input, Output>> = Result
53+
/**
54+
* Augments a Json Schema with runtime validation logic required by StandardSchema. Wrapping a type in this way renders the type
55+
* incompatible with the Json Schema specification.
56+
*/
57+
export function StandardSchema<Type extends TSchema>(schema: Type, references: TSchema[] = []): TStandardSchema<Type, StaticDecode<Type>> {
58+
const validate = (value: unknown) => {
59+
try {
60+
return { value: Value.Parse(schema, references, value) }
61+
} catch (error) {
62+
const asserted = error instanceof AssertError ? error : undefined
63+
return asserted ? { issues: [...asserted.Errors()] } : { issues: ['Unknown error']}
64+
}
65+
}
66+
const standard = { version: 1, vendor: 'TypeBox', validate }
67+
return CloneType(schema, { ['~standard']: standard }) as never
68+
}

0 commit comments

Comments
 (0)