Skip to content

Commit

Permalink
Implement Module Deref Types
Browse files Browse the repository at this point in the history
  • Loading branch information
sinclairzx81 committed Nov 16, 2024
1 parent 53c3d75 commit 8596282
Show file tree
Hide file tree
Showing 37 changed files with 1,298 additions and 618 deletions.
83 changes: 47 additions & 36 deletions example/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,46 +4,57 @@ import { Value, ValuePointer } from '@sinclair/typebox/value'
import { Parse, StaticParseAsType } from '@sinclair/typebox/syntax'
import { Type, TypeGuard, Kind, Static, TSchema } from '@sinclair/typebox'

// -----------------------------------------------------------
// Create: Type
// -----------------------------------------------------------

const T = Type.Object({
x: Type.Number(),
y: Type.Number(),
z: Type.Number(),
// KindGuard.IsLiteralValue

// New Types:
// - Awaited (Computed)
// - Partial (Computed)
// - Pick (Computed)
// - Omit (Computed)
// - Required
// - KeyOf

//
// Todo:
// - Have more problems dealing with options not mapping over correctly. This is a
// problem for deferred types as the XRef can't be naively assign options post
// creation. I could check for these cases however.
// - Support Recursive Deref. This will be challenging, but ideally we want to
// support Partial(Required(Partial(Type.Ref('A')))). This probably means
// ditching the current XRef for a Deferred node like thing.

const M = Parse('string')

// const Module = Parse(`module {
// type A = {
// x: number
// y: number
// z: number
// }

// type K = 'z' | 'y'

// type T = Partial<Pick<A, K>>
// }`)

const Module = Type.Module({
A: Type.Object({
x: Type.Number(),
y: Type.Number(),
z: Type.Number(),
}),
K: Type.Union([Type.Literal('z'), Type.Literal('y')]),
T: Type.Partial(Type.Omit(Type.Ref('A'), Type.Ref('K'))),
})

type T = Static<typeof T>
const T = Module.Import('T')

console.log(T)
function test(value: Static<typeof T>) {}

// -----------------------------------------------------------
// Parse: Type
// -----------------------------------------------------------
console.dir(T, { depth: 100 })

const S = Parse({ T }, `{ x: T, y: T, z: T }`)
type A = Static<typeof T>

type S = Static<typeof S>
// Ok(T, { nodes: [{ nodes: [{ nodes: [] }, { nodes: [] }] }] })

// -----------------------------------------------------------
// Create: Value
// -----------------------------------------------------------

const V = Value.Create(T)

console.log(V)

// -----------------------------------------------------------
// Compile: Type
// -----------------------------------------------------------

const C = TypeCompiler.Compile(T)

console.log(C.Code())

// -----------------------------------------------------------
// Check: Value
// -----------------------------------------------------------

console.log(C.Check(V))
const A = Type.Omit(Type.String(), Type.Ref('A'))
2 changes: 1 addition & 1 deletion src/compiler/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ export namespace TypeCompiler {
}
function* FromImport(schema: TImport, references: TSchema[], value: string): IterableIterator<string> {
const definitions = globalThis.Object.values(schema.$defs) as TSchema[]
const target = schema.$defs[schema.$ref] as TSchema
const target = schema.$defs[schema.$ref as never] as TSchema
yield* Visit(target, [...references, ...definitions], value)
}
function* FromInteger(schema: TInteger, references: TSchema[], value: string): IterableIterator<string> {
Expand Down
2 changes: 1 addition & 1 deletion src/errors/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ function* FromFunction(schema: TFunction, references: TSchema[], path: string, v
}
function* FromImport(schema: TImport, references: TSchema[], path: string, value: any): IterableIterator<ValueError> {
const definitions = globalThis.Object.values(schema.$defs) as TSchema[]
const target = schema.$defs[schema.$ref] as TSchema
const target = schema.$defs[schema.$ref as never] as TSchema
yield* Visit(target, [...references, ...definitions], path, value)
}
function* FromInteger(schema: TInteger, references: TSchema[], path: string, value: any): IterableIterator<ValueError> {
Expand Down
8 changes: 4 additions & 4 deletions src/syntax/static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -788,8 +788,8 @@ type Required = Static.Tuple<[
// ------------------------------------------------------------------
// prettier-ignore
interface PickMapping extends Static.IMapping {
output: this['input'] extends ['Pick', LAngle, infer Type extends Types.TSchema, Comma, infer PropertyKey extends Types.TSchema, RAngle]
? Types.TPick<Type, Types.TIndexPropertyKeys<PropertyKey>>
output: this['input'] extends ['Pick', LAngle, infer Type extends Types.TSchema, Comma, infer Key extends Types.TSchema, RAngle]
? Types.TPick<Type, Key>
: never
}
// prettier-ignore
Expand All @@ -801,8 +801,8 @@ type Pick = Static.Tuple<[
// ------------------------------------------------------------------
// prettier-ignore
interface OmitMapping extends Static.IMapping {
output: this['input'] extends ['Omit', LAngle, infer Type extends Types.TSchema, Comma, infer PropertyKey extends Types.TSchema, RAngle]
? Types.TOmit<Type, Types.TIndexPropertyKeys<PropertyKey>>
output: this['input'] extends ['Omit', LAngle, infer Type extends Types.TSchema, Comma, infer Key extends Types.TSchema, RAngle]
? Types.TOmit<Type, Key>
: never
}
// prettier-ignore
Expand Down
94 changes: 57 additions & 37 deletions src/type/awaited/awaited.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,76 +26,96 @@ THE SOFTWARE.
---------------------------------------------------------------------------*/

import { CreateType } from '../create/type'
import { Ensure } from '../helpers/index'
import type { TSchema, SchemaOptions } from '../schema/index'
import { Computed, type TComputed } from '../computed/index'
import { Intersect, type TIntersect } from '../intersect/index'
import { Union, type TUnion } from '../union/index'
import { type TPromise } from '../promise/index'
import { CreateType } from '../create/type'
import { Ref, type TRef } from '../ref/index'

// ------------------------------------------------------------------
// TypeGuard
// ------------------------------------------------------------------
import { IsIntersect, IsUnion, IsPromise } from '../guard/kind'
// ------------------------------------------------------------------
// FromRest
// ------------------------------------------------------------------
import { IsIntersect, IsUnion, IsPromise, IsRef, IsComputed } from '../guard/kind'

// ----------------------------------------------------------------
// FromComputed
// ----------------------------------------------------------------
// prettier-ignore
type TFromRest<T extends TSchema[], Acc extends TSchema[] = []> =
T extends [infer L extends TSchema, ...infer R extends TSchema[]]
? TFromRest<R, [...Acc, TAwaited<L>]>
: Acc
type TFromComputed<Target extends string, Parameters extends TSchema[]> = Ensure<(
TComputed<'Awaited', [TComputed<Target, Parameters>]>
)>
// prettier-ignore
function FromComputed<Target extends string, Parameters extends TSchema[]>(target: Target, parameters: Parameters): TFromComputed<Target, Parameters> {
return Computed('Awaited', [Computed(target, parameters)]) as never
}
// ----------------------------------------------------------------
// Ref
// ----------------------------------------------------------------
type TFromRef<Ref extends string> = Ensure<TComputed<'Awaited', [TRef<Ref>]>>
// prettier-ignore
function FromRest<T extends TSchema[]>(T: [...T]) : TFromRest<T> {
return T.map(L => AwaitedResolve(L)) as never
function FromRef<Ref extends string>($ref: Ref): TFromRef<Ref> {
return Computed('Awaited', [Ref($ref)]) as never
}
// ----------------------------------------------------------------
// FromIntersect
// ----------------------------------------------------------------
// prettier-ignore
type TFromIntersect<T extends TSchema[]> = TIntersect<TFromRest<T>>
type TFromIntersect<Types extends TSchema[]> = (
TIntersect<TFromRest<Types>>
)
// prettier-ignore
function FromIntersect<T extends TSchema[]>(T: [...T]): TFromIntersect<T> {
return Intersect(FromRest(T) as TSchema[]) as never
function FromIntersect<Types extends TSchema[]>(types: [...Types]): TFromIntersect<Types> {
return Intersect(FromRest(types) as TSchema[]) as never
}
// ----------------------------------------------------------------
// FromUnion
// ----------------------------------------------------------------
// prettier-ignore
type TFromUnion<T extends TSchema[]> = TUnion<TFromRest<T>>
type TFromUnion<Types extends TSchema[]> = TUnion<TFromRest<Types>>
// prettier-ignore
function FromUnion<T extends TSchema[]>(T: [...T]): TFromUnion<T> {
return Union(FromRest(T) as TSchema[]) as never
function FromUnion<Types extends TSchema[]>(types: [...Types]): TFromUnion<Types> {
return Union(FromRest(types) as TSchema[]) as never
}
// ----------------------------------------------------------------
// Promise
// ----------------------------------------------------------------
type TFromPromise<T extends TSchema> = TAwaited<T>
type TFromPromise<Type extends TSchema> = TAwaited<Type>
// prettier-ignore
function FromPromise<T extends TSchema>(T: T): TFromPromise<T> {
return AwaitedResolve(T) as never
function FromPromise<Type extends TSchema>(type: Type): TFromPromise<Type> {
return Awaited(type) as never
}
// ----------------------------------------------------------------
// AwaitedResolve
// ----------------------------------------------------------------
// ------------------------------------------------------------------
// FromRest
// ------------------------------------------------------------------
// prettier-ignore
function AwaitedResolve<T extends TSchema>(T: T): TAwaited<T> {
return (
IsIntersect(T) ? FromIntersect(T.allOf) :
IsUnion(T) ? FromUnion(T.anyOf) :
IsPromise(T) ? FromPromise(T.item) :
T
) as never
type TFromRest<Types extends TSchema[], Result extends TSchema[] = []> = (
Types extends [infer Left extends TSchema, ...infer Right extends TSchema[]]
? TFromRest<Right, [...Result, TAwaited<Left>]>
: Result
)
// prettier-ignore
function FromRest<Types extends TSchema[]>(types: [...Types]) : TFromRest<Types> {
return types.map(type => Awaited(type)) as never
}
// ------------------------------------------------------------------
// TAwaited
// ------------------------------------------------------------------
// prettier-ignore
export type TAwaited<T extends TSchema> =
T extends TIntersect<infer S> ? TIntersect<TFromRest<S>> :
T extends TUnion<infer S> ? TUnion<TFromRest<S>> :
T extends TPromise<infer S> ? TAwaited<S> :
T
export type TAwaited<Type extends TSchema> = (
Type extends TComputed<infer Target extends string, infer Parameters extends TSchema[]> ? TFromComputed<Target, Parameters> :
Type extends TRef<infer Ref extends string> ? TFromRef<Ref> :
Type extends TIntersect<infer Types extends TSchema[]> ? TIntersect<TFromRest<Types>> :
Type extends TUnion<infer Types extends TSchema[]> ? TUnion<TFromRest<Types>> :
Type extends TPromise<infer Type extends TSchema> ? TAwaited<Type> :
Type
)
/** `[JavaScript]` Constructs a type by recursively unwrapping Promise types */
export function Awaited<T extends TSchema>(T: T, options?: SchemaOptions): TAwaited<T> {
return CreateType(AwaitedResolve(T), options) as never
export function Awaited<T extends TSchema>(type: T, options?: SchemaOptions): TAwaited<T> {
return CreateType(
IsComputed(type) ? FromComputed(type.target, type.parameters) : IsIntersect(type) ? FromIntersect(type.allOf) : IsUnion(type) ? FromUnion(type.anyOf) : IsPromise(type) ? FromPromise(type.item) : IsRef(type) ? FromRef(type.$ref) : type,
options,
) as never
}
44 changes: 44 additions & 0 deletions src/type/computed/computed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*--------------------------------------------------------------------------
@sinclair/typebox/type
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 type { TSchema, SchemaOptions } from '../schema/index'
import { CreateType } from '../create/index'
import { Kind } from '../symbols/symbols'

// ------------------------------------------------------------------
// Computed
// ------------------------------------------------------------------
export interface TComputed<Target extends string = string, Parameters extends TSchema[] = []> extends TSchema {
[Kind]: 'Computed'
target: Target
parameters: Parameters
}
/** `[Internal]` Creates a deferred computed type. This type is used exclusively in modules to defer resolution of computable types that contain interior references */
export function Computed<Target extends string, Parameters extends TSchema[]>(target: Target, parameters: [...Parameters], options?: SchemaOptions): TComputed<Target, Parameters> {
return CreateType({ [Kind]: 'Computed', target, parameters }, options) as never
}
29 changes: 29 additions & 0 deletions src/type/computed/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*--------------------------------------------------------------------------
@sinclair/typebox/type
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.
---------------------------------------------------------------------------*/

export * from './computed'
17 changes: 13 additions & 4 deletions src/type/guard/kind.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,10 @@ THE SOFTWARE.
import * as ValueGuard from './value'
import { Kind, Hint, TransformKind, ReadonlyKind, OptionalKind } from '../symbols/index'
import { TransformOptions } from '../transform/index'
import { TTemplateLiteral } from '../template-literal/index'
import { TArray } from '../array/index'
import { TBoolean } from '../boolean/index'
import type { TTemplateLiteral } from '../template-literal/index'
import type { TArray } from '../array/index'
import type { TBoolean } from '../boolean/index'
import type { TComputed } from '../computed/index'
import type { TRecord } from '../record/index'
import type { TString } from '../string/index'
import type { TUnion } from '../union/index'
Expand All @@ -44,7 +45,7 @@ import type { TImport } from '../module/index'
import type { TInteger } from '../integer/index'
import type { TIntersect } from '../intersect/index'
import type { TIterator } from '../iterator/index'
import type { TLiteral } from '../literal/index'
import type { TLiteral, TLiteralValue } from '../literal/index'
import type { TMappedKey, TMappedResult } from '../mapped/index'
import type { TNever } from '../never/index'
import type { TNot } from '../not/index'
Expand Down Expand Up @@ -95,6 +96,10 @@ export function IsBigInt(value: unknown): value is TBigInt {
export function IsBoolean(value: unknown): value is TBoolean {
return IsKindOf(value, 'Boolean')
}
/** `[Kind-Only]` Returns true if the given value is TComputed */
export function IsComputed(value: unknown): value is TComputed {
return IsKindOf(value, 'Computed')
}
/** `[Kind-Only]` Returns true if the given value is TConstructor */
export function IsConstructor(value: unknown): value is TConstructor {
return IsKindOf(value, 'Constructor')
Expand Down Expand Up @@ -143,6 +148,10 @@ export function IsLiteralNumber(value: unknown): value is TLiteral<number> {
export function IsLiteralBoolean(value: unknown): value is TLiteral<boolean> {
return IsLiteral(value) && ValueGuard.IsBoolean(value.const)
}
/** `[Kind-Only]` Returns true if the given value is TLiteralValue */
export function IsLiteralValue(value: unknown): value is TLiteralValue {
return ValueGuard.IsBoolean(value) || ValueGuard.IsNumber(value) || ValueGuard.IsString(value)
}
/** `[Kind-Only]` Returns true if the given value is TLiteral */
export function IsLiteral(value: unknown): value is TLiteral {
return IsKindOf(value, 'Literal')
Expand Down
Loading

0 comments on commit 8596282

Please sign in to comment.