-
Notifications
You must be signed in to change notification settings - Fork 166
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
6 changed files
with
304 additions
and
73 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/*-------------------------------------------------------------------------- | ||
@sinclair/typebox/prototypes | ||
The MIT License (MIT) | ||
Copyright (c) 2017-2024 Haydn Paterson (sinclair) <[email protected]> | ||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
The above copyright notice and this permission notice shall be included in | ||
all copies or substantial portions of the Software. | ||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
THE SOFTWARE. | ||
---------------------------------------------------------------------------*/ | ||
|
||
import { TSchema, CloneType } from '@sinclair/typebox' | ||
|
||
// prettier-ignore | ||
export type TOptions<Type extends TSchema, Options extends Record<PropertyKey, unknown>> = ( | ||
Type & Options | ||
) | ||
|
||
/** `[Prototype]` Augments a schema with additional generics aware properties */ | ||
// prettier-ignore | ||
export function Options<Type extends TSchema, Options extends Record<PropertyKey, unknown>>(type: Type, options: Options): TOptions<Type, Options> { | ||
return CloneType(type, options) as never | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,156 @@ | ||
/*-------------------------------------------------------------------------- | ||
@sinclair/typebox/prototypes | ||
The MIT License (MIT) | ||
Copyright (c) 2017-2024 Haydn Paterson (sinclair) <[email protected]> | ||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
The above copyright notice and this permission notice shall be included in | ||
all copies or substantial portions of the Software. | ||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
THE SOFTWARE. | ||
---------------------------------------------------------------------------*/ | ||
|
||
import * as Types from '@sinclair/typebox' | ||
|
||
// ------------------------------------------------------------------ | ||
// Mapping: Functions and Type | ||
// ------------------------------------------------------------------ | ||
export type TMappingFunction = (schema: Types.TSchema) => Types.TSchema | ||
|
||
export interface TMappingType { | ||
input: unknown | ||
output: unknown | ||
} | ||
// ------------------------------------------------------------------ | ||
// Record Parameters | ||
// ------------------------------------------------------------------ | ||
function GetRecordPattern(record: Types.TRecord): string { | ||
return globalThis.Object.getOwnPropertyNames(record.patternProperties)[0] | ||
} | ||
function GetRecordKey(record: Types.TRecord): Types.TSchema { | ||
const pattern = GetRecordPattern(record) | ||
return ( | ||
pattern === Types.PatternStringExact ? Types.String() : | ||
pattern === Types.PatternNumberExact ? Types.Number() : | ||
pattern === Types.PatternBooleanExact ? Types.Boolean() : | ||
Types.String({ pattern }) | ||
) | ||
} | ||
function GetRecordValue(record: Types.TRecord): Types.TSchema { | ||
return record.patternProperties[GetRecordPattern(record)] | ||
} | ||
// ------------------------------------------------------------------ | ||
// Traversal | ||
// ------------------------------------------------------------------ | ||
// prettier-ignore | ||
type TApply<Type extends Types.TSchema, Func extends TMappingType, | ||
Mapped = (Func & { input: Type })['output'], | ||
Result = Mapped extends Types.TSchema ? Mapped : never | ||
> = Result | ||
// prettier-ignore | ||
type TFromProperties<Properties extends Types.TProperties, Func extends TMappingType, Result extends Types.TProperties = { | ||
[Key in keyof Properties]: TRecursiveMap<Properties[Key], Func> | ||
}> = Result | ||
function FromProperties(properties: Types.TProperties, func: TMappingFunction): Types.TProperties { | ||
return globalThis.Object.getOwnPropertyNames(properties).reduce((result, key) => { | ||
return {...result, [key]: RecursiveMap(properties[key], func) } | ||
}, {}) | ||
} | ||
// prettier-ignore | ||
type TFromRest<Types extends Types.TSchema[], Func extends TMappingType, Result extends Types.TSchema[] = []> = ( | ||
Types extends [infer Left extends Types.TSchema, ...infer Right extends Types.TSchema[]] | ||
? TFromRest<Right, Func, [...Result, TRecursiveMap<Left, Func>]> | ||
: Result | ||
) | ||
function FromRest(types: Types.TSchema[], func: TMappingFunction): Types.TSchema[] { | ||
return types.map(type => RecursiveMap(type, func)) | ||
} | ||
// prettier-ignore | ||
type TFromType<Type extends Types.TSchema, Func extends TMappingType, Result extends Types.TSchema = ( | ||
TApply<Type, Func> | ||
)> = Result | ||
function FromType(type: Types.TSchema, func: TMappingFunction): Types.TSchema { | ||
return func(type) | ||
} | ||
// ------------------------------------------------------------------ | ||
// TRecursiveMap<Type, Mapping> | ||
// ------------------------------------------------------------------ | ||
/** `[Prototype]` Applies a deep recursive map across the given type and sub types. */ | ||
// prettier-ignore | ||
export type TRecursiveMap<Type extends Types.TSchema, Func extends TMappingType, | ||
// Maps the Exterior Type | ||
Exterior extends Types.TSchema = TFromType<Type, Func>, | ||
// Maps the Interior Parameterized Types | ||
Interior extends Types.TSchema = ( | ||
Exterior extends Types.TConstructor<infer Parameters extends Types.TSchema[], infer ReturnType extends Types.TSchema> ? Types.TConstructor<TFromRest<Parameters, Func>, TFromType<ReturnType, Func>> : | ||
Exterior extends Types.TFunction<infer Parameters extends Types.TSchema[], infer ReturnType extends Types.TSchema> ? Types.TFunction<TFromRest<Parameters, Func>, TFromType<ReturnType, Func>> : | ||
Exterior extends Types.TIntersect<infer Types extends Types.TSchema[]> ? Types.TIntersect<TFromRest<Types, Func>> : | ||
Exterior extends Types.TUnion<infer Types extends Types.TSchema[]> ? Types.TUnion<TFromRest<Types, Func>> : | ||
Exterior extends Types.TTuple<infer Types extends Types.TSchema[]> ? Types.TTuple<TFromRest<Types, Func>> : | ||
Exterior extends Types.TArray<infer Type extends Types.TSchema> ? Types.TArray<TFromType<Type, Func>>: | ||
Exterior extends Types.TAsyncIterator<infer Type extends Types.TSchema> ? Types.TAsyncIterator<TFromType<Type, Func>> : | ||
Exterior extends Types.TIterator<infer Type extends Types.TSchema> ? Types.TIterator<TFromType<Type, Func>> : | ||
Exterior extends Types.TPromise<infer Type extends Types.TSchema> ? Types.TPromise<TFromType<Type, Func>> : | ||
Exterior extends Types.TObject<infer Properties extends Types.TProperties> ? Types.TObject<TFromProperties<Properties, Func>> : | ||
Exterior extends Types.TRecord<infer Key extends Types.TSchema, infer Value extends Types.TSchema> ? Types.TRecordOrObject<TFromType<Key, Func>, TFromType<Value, Func>> : | ||
Exterior | ||
), | ||
// Modifiers Derived from Exterior Type Mapping | ||
IsOptional extends number = Exterior extends Types.TOptional<Types.TSchema> ? 1 : 0, | ||
IsReadonly extends number = Exterior extends Types.TReadonly<Types.TSchema> ? 1 : 0, | ||
Result extends Types.TSchema = ( | ||
[IsReadonly, IsOptional] extends [1, 1] ? Types.TReadonlyOptional<Interior> : | ||
[IsReadonly, IsOptional] extends [0, 1] ? Types.TOptional<Interior> : | ||
[IsReadonly, IsOptional] extends [1, 0] ? Types.TReadonly<Interior> : | ||
Interior | ||
) | ||
> = Result | ||
/** `[Prototype]` Applies a deep recursive map across the given type and sub types. */ | ||
// prettier-ignore | ||
export function RecursiveMap(type: Types.TSchema, func: TMappingFunction): Types.TSchema { | ||
// Maps the Exterior Type | ||
const exterior = Types.CloneType(FromType(type, func), type) | ||
// Maps the Interior Parameterized Types | ||
const interior = ( | ||
Types.KindGuard.IsConstructor(type) ? Types.Constructor(FromRest(type.parameters, func), FromType(type.returns, func), exterior) : | ||
Types.KindGuard.IsFunction(type) ? Types.Function(FromRest(type.parameters, func), FromType(type.returns, func), exterior) : | ||
Types.KindGuard.IsIntersect(type) ? Types.Intersect(FromRest(type.allOf, func), exterior) : | ||
Types.KindGuard.IsUnion(type) ? Types.Union(FromRest(type.anyOf, func), exterior) : | ||
Types.KindGuard.IsTuple(type) ? Types.Tuple(FromRest(type.items || [], func), exterior) : | ||
Types.KindGuard.IsArray(type) ? Types.Array(FromType(type.items, func), exterior) : | ||
Types.KindGuard.IsAsyncIterator(type) ? Types.AsyncIterator(FromType(type.items, func), exterior) : | ||
Types.KindGuard.IsIterator(type) ? Types.Iterator(FromType(type.items, func), exterior) : | ||
Types.KindGuard.IsPromise(type) ? Types.Promise(FromType(type.items, func), exterior) : | ||
Types.KindGuard.IsObject(type) ? Types.Object(FromProperties(type.properties, func), exterior) : | ||
Types.KindGuard.IsRecord(type) ? Types.Record(FromType(GetRecordKey(type), func), FromType(GetRecordValue(type), func), exterior) : | ||
Types.CloneType(exterior, exterior) | ||
) | ||
// Modifiers Derived from Exterior Type Mapping | ||
const isOptional = Types.KindGuard.IsOptional(exterior) | ||
const isReadonly = Types.KindGuard.IsOptional(exterior) | ||
return ( | ||
isOptional && isReadonly ? Types.ReadonlyOptional(interior) : | ||
isOptional ? Types.Optional(interior) : | ||
isReadonly ? Types.Readonly(interior) : | ||
interior | ||
) | ||
} | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,67 +1,33 @@ | ||
### Standard Schema | ||
|
||
This example is a reference implementation of [Standard Schema](https://github.com/standard-schema/standard-schema) for TypeBox. | ||
|
||
### Overview | ||
|
||
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. | ||
|
||
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). | ||
|
||
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. | ||
|
||
[Type Adapters](https://github.com/sinclairzx81/type-adapters) | ||
Reference implementation of [Standard Schema](https://github.com/standard-schema/standard-schema) for TypeBox. | ||
|
||
### Example | ||
|
||
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. | ||
The following example augments a TypeBox schema with the required `~standard` interface. The `~standard` interface is applied via non-enumerable configuration enabling the schematics to continue to be used with strict compliant validators such as Ajv that would otherwise reject the non-standard `~standard` keyword. | ||
|
||
```typescript | ||
import { Type } from '@sinclair/typebox' | ||
import { StandardSchema } from './standard' | ||
import { Type } from '@sinclair/typebox' | ||
|
||
// The Standard Schema function will augment a TypeBox type with runtime validation | ||
// logic to validate / parse a value (as mandated by the Standard Schema interfaces). | ||
// Calling this function will render the json-schema schematics invalidated, specifically | ||
// the non-standard keyword `~standard` which ideally should be expressed as a non | ||
// serializable symbol (Ajv strict) | ||
|
||
const A = StandardSchema(Type.Object({ // const A = { | ||
x: Type.Number(), // '~standard': { version: 1, vendor: 'TypeBox', validate: [Function: validate] }, | ||
y: Type.Number(), // type: 'object', | ||
z: Type.Number(), // properties: { | ||
})) // x: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' }, | ||
// y: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' }, | ||
// z: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' } | ||
const T = StandardSchema(Type.Object({ // const A = { | ||
x: Type.Number(), // (non-enumerable) '~standard': { | ||
y: Type.Number(), // version: 1, | ||
z: Type.Number(), // vendor: 'TypeBox', | ||
})) // validate: [Function: validate] | ||
// }, | ||
// required: [ 'x', 'y', 'z' ], | ||
// [Symbol(TypeBox.Kind)]: 'Object' | ||
// } | ||
|
||
const R = A['~standard'].validate({ x: 1, y: 2, z: 3 }) // const R = { value: { x: 1, y: 2, z: 3 }, issues: [] } | ||
``` | ||
|
||
### Ajv Strict | ||
|
||
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 `~`) | ||
|
||
```typescript | ||
import Ajv from 'ajv' | ||
|
||
const ajv = new Ajv().addKeyword('~standard') // cannot be defined as keyword. | ||
|
||
const A = StandardSchema(Type.Object({ // const A = { | ||
x: Type.Number(), // '~standard': { version: 1, vendor: 'TypeBox', validate: [Function: validate] }, | ||
y: Type.Number(), // type: 'object', | ||
z: Type.Number(), // properties: { | ||
})) // x: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' }, | ||
// type: 'object', | ||
// properties: { | ||
// x: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' }, | ||
// y: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' }, | ||
// z: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' } | ||
// }, | ||
// required: [ 'x', 'y', 'z' ], | ||
// [Symbol(TypeBox.Kind)]: 'Object' | ||
// } | ||
|
||
|
||
ajv.validate(A, { x: 1, y: 2, z: 3 }) // Error: Keyword ~standard has invalid name | ||
``` | ||
const R = T['~standard'].validate({ x: 1, y: 2, z: 3 }) // const R = { | ||
// value: { x: 1, y: 2, z: 3 }, | ||
// issues: [] | ||
// } | ||
``` |
Oops, something went wrong.