diff --git a/example/prototypes/index.ts b/example/prototypes/index.ts index d5d9aeda..dd5f572e 100644 --- a/example/prototypes/index.ts +++ b/example/prototypes/index.ts @@ -28,6 +28,8 @@ THE SOFTWARE. export * from './discriminated-union' export * from './from-schema' +export * from './options' export * from './partial-deep' export * from './union-enum' export * from './union-oneof' +export * from './recursive-map' diff --git a/example/prototypes/options.ts b/example/prototypes/options.ts new file mode 100644 index 00000000..0270acbb --- /dev/null +++ b/example/prototypes/options.ts @@ -0,0 +1,40 @@ +/*-------------------------------------------------------------------------- + +@sinclair/typebox/prototypes + +The MIT License (MIT) + +Copyright (c) 2017-2024 Haydn Paterson (sinclair) + +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 & Options +) + +/** `[Prototype]` Augments a schema with additional generics aware properties */ +// prettier-ignore +export function Options>(type: Type, options: Options): TOptions { + return CloneType(type, options) as never +} diff --git a/example/prototypes/readme.md b/example/prototypes/readme.md index cd95b34f..f3aea908 100644 --- a/example/prototypes/readme.md +++ b/example/prototypes/readme.md @@ -69,4 +69,54 @@ const T = UnionOneOf([ // const T = { type T = Static // type T = 'A' | 'B' | 'C' +``` + +## Options + +By default, TypeBox does not represent arbituary options as generics aware properties. However, there are cases where having options observable to the type system can be useful, for example conditionally mapping schematics based on custom metadata. The Options function makes user defined options generics aware. + +```typescript +import { Options } from './prototypes' + +const A = Options(Type.String(), { foo: 1 }) // Options + +type A = typeof A extends { foo: number } ? true : false // true: foo property is observable to the type system +``` + +## Recursive Map + +The Recursive Map type enables deep structural remapping of a type and it's internal constituents. This type accepts a TSchema type and a mapping type function (expressed via HKT). The HKT is applied when traversing the type and it's interior. The mapping HKT can apply conditional tests to each visited type to remap into a new form. The following augments a schematic via Options, and conditionally remaps any schema with an default annotation to make it optional. + +```typescript +import { Type, TOptional, Static, TSchema } from '@sinclair/typebox' + +import { TRecursiveMap, TMappingType, Options } from './prototypes' + +// ------------------------------------------------------------------ +// StaticDefault +// ------------------------------------------------------------------ +export interface StaticDefaultMapping extends TMappingType { + output: ( + this['input'] extends TSchema // if input schematic contains an default + ? this['input'] extends { default: unknown } // annotation, remap it to be optional, + ? TOptional // otherwise just return the schema as is. + : this['input'] + : this['input'] + ) +} +export type StaticDefault = ( + Static> +) + +// ------------------------------------------------------------------ +// Usage +// ------------------------------------------------------------------ + +const T = Type.Object({ + x: Options(Type.String(), { default: 'hello' }), + y: Type.String() +}) + +type T = StaticDefault // { x?: string, y: string } +type S = Static // { x: string, y: string } ``` \ No newline at end of file diff --git a/example/prototypes/recursive-map.ts b/example/prototypes/recursive-map.ts new file mode 100644 index 00000000..0443bed9 --- /dev/null +++ b/example/prototypes/recursive-map.ts @@ -0,0 +1,156 @@ +/*-------------------------------------------------------------------------- + +@sinclair/typebox/prototypes + +The MIT License (MIT) + +Copyright (c) 2017-2024 Haydn Paterson (sinclair) + +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 = Result +// prettier-ignore +type TFromProperties +}> = 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 [infer Left extends Types.TSchema, ...infer Right extends Types.TSchema[]] + ? TFromRest]> + : Result +) +function FromRest(types: Types.TSchema[], func: TMappingFunction): Types.TSchema[] { + return types.map(type => RecursiveMap(type, func)) +} +// prettier-ignore +type TFromType +)> = Result +function FromType(type: Types.TSchema, func: TMappingFunction): Types.TSchema { + return func(type) +} +// ------------------------------------------------------------------ +// TRecursiveMap +// ------------------------------------------------------------------ +/** `[Prototype]` Applies a deep recursive map across the given type and sub types. */ +// prettier-ignore +export type TRecursiveMap, + // Maps the Interior Parameterized Types + Interior extends Types.TSchema = ( + Exterior extends Types.TConstructor ? Types.TConstructor, TFromType> : + Exterior extends Types.TFunction ? Types.TFunction, TFromType> : + Exterior extends Types.TIntersect ? Types.TIntersect> : + Exterior extends Types.TUnion ? Types.TUnion> : + Exterior extends Types.TTuple ? Types.TTuple> : + Exterior extends Types.TArray ? Types.TArray>: + Exterior extends Types.TAsyncIterator ? Types.TAsyncIterator> : + Exterior extends Types.TIterator ? Types.TIterator> : + Exterior extends Types.TPromise ? Types.TPromise> : + Exterior extends Types.TObject ? Types.TObject> : + Exterior extends Types.TRecord ? Types.TRecordOrObject, TFromType> : + Exterior + ), + // Modifiers Derived from Exterior Type Mapping + IsOptional extends number = Exterior extends Types.TOptional ? 1 : 0, + IsReadonly extends number = Exterior extends Types.TReadonly ? 1 : 0, + Result extends Types.TSchema = ( + [IsReadonly, IsOptional] extends [1, 1] ? Types.TReadonlyOptional : + [IsReadonly, IsOptional] extends [0, 1] ? Types.TOptional : + [IsReadonly, IsOptional] extends [1, 0] ? Types.TReadonly : + 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 + ) +} + + + diff --git a/example/standard/readme.md b/example/standard/readme.md index 343d6061..6dc31026 100644 --- a/example/standard/readme.md +++ b/example/standard/readme.md @@ -1,60 +1,24 @@ ### 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' } // }, @@ -62,6 +26,8 @@ const A = StandardSchema(Type.Object({ // const A = { // [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: [] + // } +``` \ No newline at end of file diff --git a/example/standard/standard.ts b/example/standard/standard.ts index b61dcbba..ef5ca384 100644 --- a/example/standard/standard.ts +++ b/example/standard/standard.ts @@ -26,43 +26,60 @@ THE SOFTWARE. ---------------------------------------------------------------------------*/ -import { AssertError, Value, ValueError } from '@sinclair/typebox/value' +import { AssertError, Value, ValueError, ValueErrorType } from '@sinclair/typebox/value' import { TSchema, StaticDecode, CloneType } from '@sinclair/typebox' // ------------------------------------------------------------------ -// StandardSchema: Common +// StandardSchema // ------------------------------------------------------------------ interface StandardResult { value: Output - issues: [ValueError[]] + issues: ValueError[] } interface StandardSchema { - readonly "~standard": StandardSchemaProps; + readonly "~standard": StandardSchemaProperties } - -interface StandardSchemaProps { - readonly version: 1; - readonly vendor: 'TypeBox'; - readonly validate: (value: unknown) => StandardResult; - readonly types?: undefined; +interface StandardSchemaProperties { + readonly version: 1 + readonly vendor: 'TypeBox' + readonly validate: (value: unknown) => StandardResult + readonly types?: undefined } // ------------------------------------------------------------------ -// StandardSchema: TypeBox +// Issues // ------------------------------------------------------------------ -export type TStandardSchema> = Result -/** - * Augments a Json Schema with runtime validation logic required by StandardSchema. Wrapping a type in this way renders the type - * incompatible with the Json Schema specification. - */ -export function StandardSchema(schema: Type, references: TSchema[] = []): TStandardSchema> { - const validate = (value: unknown) => { +// prettier-ignore +function CreateIssues(schema: TSchema, value: unknown, error: unknown): ValueError[] { + const isAssertError = error instanceof AssertError ? error : undefined + return !isAssertError + ? [{errors: [], message: 'Unknown error', path: '/', type: ValueErrorType.Kind, schema, value }] + : [...isAssertError.Errors()] +} +// ------------------------------------------------------------------ +// Validate +// ------------------------------------------------------------------ +// prettier-ignore +function CreateValidator(schema: Type, references: TSchema[]): (value: unknown) => StandardResult> { + return (value: unknown): StandardResult> => { try { - return { value: Value.Parse(schema, references, value) } + return { value: Value.Parse(schema, references, value), issues: [] } } catch (error) { - const asserted = error instanceof AssertError ? error : undefined - return asserted ? { issues: [...asserted.Errors()] } : { issues: ['Unknown error']} + return { value: undefined, issues: CreateIssues(schema, value, error) } } } - const standard = { version: 1, vendor: 'TypeBox', validate } - return CloneType(schema, { ['~standard']: standard }) as never +} +// ------------------------------------------------------------------ +// StandardSchema +// ------------------------------------------------------------------ +/** Augments a TypeBox type with the `~standard` validation interface. */ +export type TStandardSchema = ( + Input & StandardSchema +) +/** Augments a TypeBox type with the `~standard` validation interface. */ +export function StandardSchema(schema: Type, references: TSchema[] = []): TStandardSchema> { + const standard = { version: 1, vendor: 'TypeBox', validate: CreateValidator(schema, references) } + return Object.defineProperty(CloneType(schema), "~standard", { + enumerable: false, + value: standard + }) as never } \ No newline at end of file