Socket
Socket
Sign inDemoInstall

@sinclair/typebox

Package Overview
Dependencies
Maintainers
1
Versions
326
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@sinclair/typebox - npm Package Compare versions

Comparing version 0.11.0 to 0.12.0

2

package.json
{
"name": "@sinclair/typebox",
"version": "0.11.0",
"version": "0.12.0",
"description": "JSONSchema Type Builder with Static Type Resolution for TypeScript",

@@ -5,0 +5,0 @@ "keywords": [

@@ -101,2 +101,4 @@ <div align='center'>

The following table outlines the TypeScript type inferred via `Static<TSchema>`.
<table>

@@ -147,4 +149,4 @@ <thead>

<tr>
<td>Map</td>
<td><code>const T = Type.Map(Type.Number())</code></td>
<td>Dict</td>
<td><code>const T = Type.Dict(Type.Number())</code></td>
<td><code>type T = { [key: string] } : number</code></td>

@@ -173,2 +175,7 @@ </tr>

<tr>
<td>Unknown</td>
<td><code>const T = Type.Unknown()</code></td>
<td><code>type T = unknown</code></td>
</tr>
<tr>
<td>Null</td>

@@ -179,11 +186,6 @@ <td><code>const T = Type.Null()</code></td>

<tr>
<td>Pattern</td>
<td><code>const T = Type.Pattern(/foo/)</code></td>
<td>RegEx</td>
<td><code>const T = Type.RegEx(/foo/)</code></td>
<td><code>type T = string</code></td>
</tr>
<tr>
<td>Guid</td>
<td><code>const T = Type.Guid()</code></td>
<td><code>type T = string</code></td>
</tr>
</tbody>

@@ -194,2 +196,4 @@ </table>

The following table outlines the JSON Schema data structures.
<table>

@@ -240,4 +244,4 @@ <thead>

<tr>
<td>Map</td>
<td><code>const T = Type.Map(Type.Number())</code></td>
<td>Dict</td>
<td><code>const T = Type.Dict(Type.Number())</code></td>
<td><code>{ type: 'object', additionalProperties: { type: 'number' } }</code></td>

@@ -253,3 +257,3 @@ </tr>

<td><code>const T = Type.Union([Type.Number(), Type.String()])</code></td>
<td><code>{ oneOf: [{ type: 'number'}, {type: 'string'}] }</code></td>
<td><code>{ anyOf: [{ type: 'number'}, {type: 'string'}] }</code></td>
</tr>

@@ -272,11 +276,6 @@ <tr>

<tr>
<td>Pattern</td>
<td><code>const T = Type.Pattern(/foo/)</code></td>
<td>RegEx</td>
<td><code>const T = Type.RegEx(/foo/)</code></td>
<td><code>{ type: 'string', pattern: 'foo' }</code></td>
</tr>
<tr>
<td>Guid</td>
<td><code>const T = Type.Guid()</code></td>
<td><code>{ type: 'string', pattern: '&lt;guid-regex&gt;' }</code></td>
</tr>
</tbody>

@@ -308,2 +307,7 @@ </table>

</tr>
<tr>
<td>ReadonlyOptional</td>
<td><code>const T = Type.Object({ email: Type.ReadonlyOptional(Type.String()) })</code></td>
<td><code>type T = { readonly email?: string }</code></td>
</tr>
</tbody>

@@ -310,0 +314,0 @@ </table>

@@ -1,138 +0,170 @@

export interface UserDefinedOptions {
[prop: string]: any;
}
export declare type TFunction<U extends TSchema = TSchema, T extends TSchema[] = []> = {
type: 'function';
arguments: [...T];
returns: U;
} & UserDefinedOptions;
export declare type TConstructor<U extends TSchema = TSchema, T extends TSchema[] = []> = {
type: 'constructor';
arguments: [...T];
returns: U;
} & UserDefinedOptions;
declare type TContract = TConstructor | TFunction;
export declare type TIntersect<T extends TSchema[] = any> = {
allOf: [...T];
} & UserDefinedOptions;
export declare type TUnion<T extends TSchema[] = any> = {
oneOf: [...T];
} & UserDefinedOptions;
export declare type TTuple<T extends TSchema[] = any> = {
type: 'array';
items: [...T];
additionalItems: false;
minItems: number;
maxItems: number;
} & UserDefinedOptions;
export declare type TComposite = TIntersect | TUnion | TTuple;
export declare const ReadonlyOptionalModifier: unique symbol;
export declare const OptionalModifier: unique symbol;
export declare const ReadonlyModifier: unique symbol;
export declare type TOptional<T extends TSchema | TComposite> = T & {
export declare type TReadonlyOptional<T extends TSchema> = T & {
modifier: typeof ReadonlyOptionalModifier;
};
export declare type TOptional<T extends TSchema> = T & {
modifier: typeof OptionalModifier;
};
export declare type TReadonly<T extends TSchema | TComposite> = T & {
export declare type TReadonly<T extends TSchema> = T & {
modifier: typeof ReadonlyModifier;
};
export declare type TModifier = TOptional<TSchema | TComposite> | TReadonly<TSchema | TComposite>;
export declare type FormatOption = 'date-time' | 'time' | 'date' | 'email' | 'idn-email' | 'hostname' | 'idn-hostname' | 'ipv4' | 'ipv6' | 'uri' | 'uri-reference' | 'iri' | 'uuid' | 'iri-reference' | 'uri-template' | 'json-pointer' | 'relative-json-pointer' | 'regex';
export declare type TModifier = TReadonlyOptional<TSchema> | TOptional<TSchema> | TReadonly<TSchema>;
export declare const UnionKind: unique symbol;
export declare const IntersectKind: unique symbol;
export declare const TupleKind: unique symbol;
export declare const ObjectKind: unique symbol;
export declare const DictKind: unique symbol;
export declare const ArrayKind: unique symbol;
export declare const EnumKind: unique symbol;
export declare const LiteralKind: unique symbol;
export declare const StringKind: unique symbol;
export declare const NumberKind: unique symbol;
export declare const IntegerKind: unique symbol;
export declare const BooleanKind: unique symbol;
export declare const NullKind: unique symbol;
export declare const UnknownKind: unique symbol;
export declare const AnyKind: unique symbol;
export interface CustomOptions {
[prop: string]: any;
}
export declare type StringFormatOption = 'date-time' | 'time' | 'date' | 'email' | 'idn-email' | 'hostname' | 'idn-hostname' | 'ipv4' | 'ipv6' | 'uri' | 'uri-reference' | 'iri' | 'uuid' | 'iri-reference' | 'uri-template' | 'json-pointer' | 'relative-json-pointer' | 'regex';
declare type IsUnion<T> = [T] extends [UnionToIntersect<T>] ? false : true;
export declare type StringOptions = {
minLength?: number;
maxLength?: number;
pattern?: string;
format?: IsUnion<CustomOptions['format']> extends true ? CustomOptions['format'] | StringFormatOption : StringFormatOption;
} & Omit<CustomOptions, 'format'>;
export declare type ArrayOptions = {
uniqueItems?: boolean;
minItems?: number;
maxItems?: number;
uniqueItems?: boolean;
} & UserDefinedOptions;
} & CustomOptions;
export declare type NumberOptions = {
minimum?: number;
exclusiveMaximum?: number;
exclusiveMinimum?: number;
maximum?: number;
exclusiveMaximum?: number;
minimum?: number;
multipleOf?: number;
} & UserDefinedOptions;
/** Augmentation support for UserDefinedOptions. Used specifically for adding custom string formats. */
declare type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
declare type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;
export declare type StringOptions = {
minLength?: number;
maxLength?: number;
pattern?: string;
format?: IsUnion<UserDefinedOptions['format']> extends true ? UserDefinedOptions['format'] | FormatOption : FormatOption;
} & Omit<UserDefinedOptions, 'format'>;
export declare type TLiteral = TStringLiteral<string> | TNumberLiteral<number> | TBooleanLiteral<boolean>;
export declare type TStringLiteral<T> = {
type: 'string';
enum: [T];
} & UserDefinedOptions;
export declare type TNumberLiteral<T> = {
type: 'number';
enum: [T];
} & UserDefinedOptions;
export declare type TBooleanLiteral<T> = {
type: 'boolean';
enum: [T];
} & UserDefinedOptions;
} & CustomOptions;
export declare type TEnumType = Record<string, string | number>;
export declare type TKey = string | number;
export declare type TValue = string | number | boolean;
export declare type TIntersect<T extends TSchema[]> = {
kind: typeof IntersectKind;
allOf: [...T];
} & CustomOptions;
export declare type TUnion<T extends TSchema[]> = {
kind: typeof UnionKind;
anyOf: [...T];
} & CustomOptions;
export declare type TTuple<T extends TSchema[]> = {
kind: typeof TupleKind;
type: 'array';
items: [...T];
additionalItems: false;
minItems: number;
maxItems: number;
} & CustomOptions;
export declare type TProperties = {
[key: string]: TSchema | TComposite | TOptional<TSchema | TComposite> | TReadonly<TSchema | TComposite>;
[key: string]: TSchema;
};
export declare type TObject<T extends TProperties> = {
kind: typeof ObjectKind;
type: 'object';
properties: T;
required?: string[];
} & UserDefinedOptions;
export declare type TMap<T extends TSchema | TComposite> = {
} & CustomOptions;
export declare type TDict<T extends TSchema> = {
kind: typeof DictKind;
type: 'object';
additionalProperties: T;
} & UserDefinedOptions;
export declare type TArray<T extends TSchema | TComposite> = {
} & CustomOptions;
export declare type TArray<T extends TSchema> = {
kind: typeof ArrayKind;
type: 'array';
items: T;
} & ArrayOptions;
export declare type TEnum<T extends string | number> = {
enum: Array<T>;
} & UserDefinedOptions;
export declare type TLiteral<T extends TValue> = {
kind: typeof LiteralKind;
type: 'string' | 'number' | 'boolean';
enum: [T];
} & CustomOptions;
export declare type TEnum<T extends TKey> = {
kind: typeof EnumKind;
enum: T[];
} & CustomOptions;
export declare type TString = {
kind: typeof StringKind;
type: 'string';
} & StringOptions;
export declare type TNumber = {
kind: typeof NumberKind;
type: 'number';
} & NumberOptions;
export declare type TInteger = {
kind: typeof IntegerKind;
type: 'integer';
} & NumberOptions;
export declare type TString = {
type: 'string';
} & StringOptions;
export declare type TBoolean = {
kind: typeof BooleanKind;
type: 'boolean';
} & UserDefinedOptions;
} & CustomOptions;
export declare type TNull = {
kind: typeof NullKind;
type: 'null';
} & UserDefinedOptions;
export declare type TAny = {} & UserDefinedOptions;
export declare type TPromise<T extends TSchema | TVoid | TUndefined> = {
} & CustomOptions;
export declare type TUnknown = {
kind: typeof UnknownKind;
} & CustomOptions;
export declare type TAny = {
kind: typeof AnyKind;
} & CustomOptions;
export declare const ConstructorKind: unique symbol;
export declare const FunctionKind: unique symbol;
export declare const PromiseKind: unique symbol;
export declare const UndefinedKind: unique symbol;
export declare const VoidKind: unique symbol;
export declare type TConstructor<T extends TSchema[], U extends TSchema> = {
kind: typeof ConstructorKind;
type: 'constructor';
arguments: readonly [...T];
returns: U;
} & CustomOptions;
export declare type TFunction<T extends TSchema[], U extends TSchema> = {
kind: typeof FunctionKind;
type: 'function';
arguments: readonly [...T];
returns: U;
} & CustomOptions;
export declare type TPromise<T extends TSchema> = {
kind: typeof PromiseKind;
type: 'promise';
item: T;
} & UserDefinedOptions;
} & CustomOptions;
export declare type TUndefined = {
kind: typeof UndefinedKind;
type: 'undefined';
} & UserDefinedOptions;
} & CustomOptions;
export declare type TVoid = {
kind: typeof VoidKind;
type: 'void';
} & UserDefinedOptions;
export declare type TSchema = TLiteral | TNumber | TInteger | TBoolean | TString | TObject<any> | TArray<any> | TEnum<any> | TMap<any> | TNull | TAny | TPromise<any> | TUndefined | TVoid;
declare type StaticFunction<T> = T extends TFunction<infer R, infer U> ? (args: [...Static<U>]) => Static<R> : never;
declare type StaticConstructor<T> = T extends TConstructor<infer R, infer U> ? new (args: [...Static<U>]) => Static<R> : never;
declare type StaticContract<T extends TSchema> = T extends TFunction ? StaticFunction<T> : T extends TConstructor ? StaticConstructor<T> : never;
declare type MapStatic<T> = {
[P in keyof T]: Static<T[P]>;
};
declare type StaticIntersect<T> = T extends TIntersect<infer U> ? UnionToIntersection<MapStatic<U>[number]> : never;
declare type StaticUnion<T> = T extends TUnion<infer U> ? MapStatic<U>[number] : never;
declare type StaticTuple<T> = T extends TTuple<infer U> ? MapStatic<U> : never;
declare type StaticComposite<T extends TComposite> = T extends TIntersect ? StaticIntersect<T> : T extends TUnion ? StaticUnion<T> : T extends TTuple ? StaticTuple<T> : never;
declare type StaticLiteral<T> = T extends TStringLiteral<infer U> ? U : T extends TNumberLiteral<infer U> ? U : T extends TBooleanLiteral<infer U> ? U : never;
declare type ReadonlyPropertyKeys<T> = {
} & CustomOptions;
export declare type TSchema = TIntersect<any> | TUnion<any> | TTuple<any> | TObject<TProperties> | TArray<any> | TEnum<any> | TLiteral<any> | TString | TNumber | TInteger | TBoolean | TNull | TUnknown | TAny | TConstructor<any[], any> | TFunction<any[], any> | TPromise<any> | TUndefined | TVoid;
export declare type UnionToIntersect<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
export declare type ReadonlyOptionalPropertyKeys<T> = {
[K in keyof T]: T[K] extends TReadonlyOptional<infer U> ? K : never;
}[keyof T];
export declare type ReadonlyPropertyKeys<T> = {
[K in keyof T]: T[K] extends TReadonly<infer U> ? K : never;
}[keyof T];
declare type OptionalPropertyKeys<T> = {
export declare type OptionalPropertyKeys<T> = {
[K in keyof T]: T[K] extends TOptional<infer U> ? K : never;
}[keyof T];
declare type PropertyKeys<T> = keyof Omit<T, OptionalPropertyKeys<T> | ReadonlyPropertyKeys<T>>;
declare type StaticObjectProperties<T> = {
export declare type PropertyKeys<T> = keyof Omit<T, OptionalPropertyKeys<T> | ReadonlyPropertyKeys<T> | ReadonlyPropertyKeys<T>>;
export declare type StaticProperties<T> = {
readonly [K in ReadonlyOptionalPropertyKeys<T>]?: Static<T[K]>;
} & {
readonly [K in ReadonlyPropertyKeys<T>]: Static<T[K]>;

@@ -144,63 +176,75 @@ } & {

};
declare type StaticSchema<T extends TSchema> = T extends TObject<infer U> ? StaticObjectProperties<U> : T extends TMap<infer U> ? {
[key: string]: Static<U>;
} : T extends TArray<infer U> ? Array<Static<U>> : T extends TEnum<infer U> ? U : T extends TLiteral ? StaticLiteral<T> : T extends TString ? string : T extends TNumber ? number : T extends TInteger ? number : T extends TBoolean ? boolean : T extends TNull ? null : T extends TAny ? any : T extends TPromise<infer U> ? Promise<Static<U>> : T extends TVoid ? void : T extends TUndefined ? undefined : never;
export declare type TStatic = TComposite | TSchema | TModifier | TContract;
export declare type Static<T extends TStatic> = T extends TContract ? StaticContract<T> : T extends TComposite ? StaticComposite<T> : T extends TSchema ? StaticSchema<T> : never;
export declare class Type {
/** Modifies the inner type T into an optional T. */
static Optional<T extends TSchema | TUnion | TIntersect>(item: T): TOptional<T>;
/** Modifies the inner type T into an readonly T. */
static Readonly<T extends TSchema | TUnion | TIntersect>(item: T): TReadonly<T>;
/** Creates a Union type for the given arguments. */
static Union<T extends TSchema[]>(items: [...T], options?: UserDefinedOptions): TUnion<T>;
/** Creates an Intersect type for the given arguments. */
static Intersect<T extends TSchema[]>(items: [...T], options?: UserDefinedOptions): TIntersect<T>;
/** Creates a Tuple type for the given arguments. */
static Tuple<T extends TSchema[]>(items: [...T], options?: UserDefinedOptions): TTuple<T>;
/** Creates a `function` type for the given arguments. */
static Function<U extends TSchema, T extends TSchema[] = []>(args: T, returns: U, options?: UserDefinedOptions): TFunction<U, T>;
/** Creates a `constructor` type for the given arguments. */
static Constructor<U extends TSchema, T extends TSchema[] = []>(args: T, returns: U, options?: UserDefinedOptions): TConstructor<U, T>;
/** Creates a `Promise<T>` type. */
static Promise<T extends TSchema>(item: T, options?: UserDefinedOptions): TPromise<T>;
/** Creates a `void` type. */
static Void(options?: UserDefinedOptions): TVoid;
/** Creates a `undefined` type. */
static Undefined(options?: UserDefinedOptions): TUndefined;
/** Creates a `string` literal for the given value. */
static Literal<T extends string>(value: T, options?: UserDefinedOptions): TStringLiteral<T>;
/** Creates a `number` literal for the given value. */
static Literal<T extends number>(value: T, options?: UserDefinedOptions): TNumberLiteral<T>;
/** Creates a `boolean` literal for the given value. */
static Literal<T extends boolean>(value: T, options?: UserDefinedOptions): TBooleanLiteral<T>;
/** Creates a `object` type with the given properties. */
static Object<T extends TProperties>(properties: T, options?: UserDefinedOptions): TObject<T>;
/** Creates a `{[key: string]: T}` type for the given item. */
static Map<T extends TSchema | TUnion | TIntersect | TTuple>(item: T, options?: UserDefinedOptions): TMap<T>;
/** Creates an `Array<T>` type for the given item.` */
static Array<T extends TSchema | TUnion | TIntersect | TTuple>(items: T, options?: ArrayOptions): TArray<T>;
/** Creates an `Enum<T>` from an existing TypeScript enum definition. */
static Enum<T extends Record<string, string | number>>(item: T, options?: UserDefinedOptions): TEnum<T[keyof T]>;
/** Creates a `string` type. */
static String(options?: StringOptions): TString;
/** Creates a `number` type. */
static Number(options?: NumberOptions): TNumber;
/** Creates a `number` type that checks for `integer`. */
static Integer(options?: NumberOptions): TInteger;
export declare type StaticIntersect<T extends readonly TSchema[]> = UnionToIntersect<StaticUnion<T>>;
export declare type StaticUnion<T extends readonly TSchema[]> = {
[K in keyof T]: Static<T[K]>;
}[number];
export declare type StaticTuple<T extends readonly TSchema[]> = {
[K in keyof T]: Static<T[K]>;
};
export declare type StaticObject<T extends TProperties> = StaticProperties<T>;
export declare type StaticDict<T extends TSchema> = {
[key: string]: Static<T>;
};
export declare type StaticArray<T extends TSchema> = Array<Static<T>>;
export declare type StaticLiteral<T extends TValue> = T;
export declare type StaticEnum<T extends TKey> = T;
export declare type StaticConstructor<T extends readonly TSchema[], U extends TSchema> = new (...args: [...{
[K in keyof T]: Static<T[K]>;
}]) => Static<U>;
export declare type StaticFunction<T extends readonly TSchema[], U extends TSchema> = (...args: [...{
[K in keyof T]: Static<T[K]>;
}]) => Static<U>;
export declare type StaticPromise<T extends TSchema> = Promise<Static<T>>;
export declare type Static<T> = T extends TIntersect<infer U> ? StaticIntersect<U> : T extends TUnion<infer U> ? StaticUnion<U> : T extends TTuple<infer U> ? StaticTuple<U> : T extends TObject<infer U> ? StaticObject<U> : T extends TDict<infer U> ? StaticDict<U> : T extends TArray<infer U> ? StaticArray<U> : T extends TEnum<infer U> ? StaticEnum<U> : T extends TLiteral<infer U> ? StaticLiteral<U> : T extends TString ? string : T extends TNumber ? number : T extends TInteger ? number : T extends TBoolean ? boolean : T extends TNull ? null : T extends TUnknown ? unknown : T extends TAny ? any : T extends TConstructor<infer U, infer R> ? StaticConstructor<U, R> : T extends TFunction<infer U, infer R> ? StaticFunction<U, R> : T extends TPromise<infer U> ? StaticPromise<U> : T extends TUndefined ? undefined : T extends TVoid ? void : unknown;
export declare class TypeBuilder {
/** Modifies a schema object property to be `readonly` and `optional`. */
ReadonlyOptional<T extends TSchema>(item: T): TReadonlyOptional<T>;
/** Modifies a schema object property to be `readonly`. */
Readonly<T extends TSchema>(item: T): TReadonly<T>;
/** Modifies a schema object property to be `optional`. */
Optional<T extends TSchema>(item: T): TOptional<T>;
/** Creates an Intersect schema. */
Intersect<T extends TSchema[]>(items: [...T], options?: CustomOptions): TIntersect<T>;
/** Creates a Union schema. */
Union<T extends TSchema[]>(items: [...T], options?: CustomOptions): TUnion<T>;
/** Creates a Tuple schema. */
Tuple<T extends TSchema[]>(items: [...T], options?: CustomOptions): TTuple<T>;
/** Creates a `object` schema with the given properties. */
Object<T extends TProperties>(properties: T, options?: CustomOptions): TObject<T>;
/** Creates a `{ [key: string]: T }` schema. */
Dict<T extends TSchema>(item: T, options?: CustomOptions): TDict<T>;
/** Creates an `Array<T>` schema. */
Array<T extends TSchema>(items: T, options?: ArrayOptions): TArray<T>;
/** Creates an `Enum<T>` schema from a TypeScript `enum` definition. */
Enum<T extends TEnumType>(item: T, options?: CustomOptions): TEnum<T[keyof T]>;
/** Creates a literal schema. Supports `string | number | boolean` values. */
Literal<T extends TValue>(value: T, options?: CustomOptions): TLiteral<T>;
/** Creates a `string` schema. */
String(options?: StringOptions): TString;
/** Creates a `string` schema from a regular expression. */
RegEx(regex: RegExp): TString;
/** Creates a `number` schema. */
Number(options?: NumberOptions): TNumber;
/** Creates a `integer` schema. */
Integer(options?: NumberOptions): TInteger;
/** Creates a `boolean` type. */
static Boolean(options?: UserDefinedOptions): TBoolean;
Boolean(options?: CustomOptions): TBoolean;
/** Creates a `null` type. */
static Null(options?: UserDefinedOptions): TNull;
/** Creates a `any` type. */
static Any(options?: UserDefinedOptions): TAny;
/** Creates a `string` type that validates for the given regular expression. Alias for ```Type.String({ pattern: '...' })``` */
static Pattern(regex: RegExp): TString;
/**
* Deprecated: Use `Type.String({ format: 'uuid' })`
*
* Creates a `string` type that validate a Guid. Alias for ```Type.String({ pattern: '...' })```
*/
static Guid(): TString;
Null(options?: CustomOptions): TNull;
/** Creates an `unknown` type. */
Unknown(options?: CustomOptions): TUnknown;
/** Creates an `any` type. */
Any(options?: CustomOptions): TAny;
/** `NON-STANDARD` Creates a `constructor` schema. */
Constructor<T extends TSchema[], U extends TSchema>(args: [...T], returns: U, options?: CustomOptions): TConstructor<T, U>;
/** `NON-STANDARD` Creates a `function` schema. */
Function<T extends TSchema[], U extends TSchema>(args: [...T], returns: U, options?: CustomOptions): TFunction<T, U>;
/** `NON-STANDARD` Creates a `Promise<T>` schema. */
Promise<T extends TSchema>(item: T, options?: CustomOptions): TPromise<T>;
/** `NON-STANDARD` Creates a `undefined` schema. */
Undefined(options?: CustomOptions): TUndefined;
/** `NON-STANDARD` Creates a `void` schema. */
Void(options?: CustomOptions): TVoid;
}
export declare const Type: TypeBuilder;
export {};

@@ -30,3 +30,38 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.Type = exports.ReadonlyModifier = exports.OptionalModifier = void 0;
exports.Type = exports.TypeBuilder = exports.VoidKind = exports.UndefinedKind = exports.PromiseKind = exports.FunctionKind = exports.ConstructorKind = exports.AnyKind = exports.UnknownKind = exports.NullKind = exports.BooleanKind = exports.IntegerKind = exports.NumberKind = exports.StringKind = exports.LiteralKind = exports.EnumKind = exports.ArrayKind = exports.DictKind = exports.ObjectKind = exports.TupleKind = exports.IntersectKind = exports.UnionKind = exports.ReadonlyModifier = exports.OptionalModifier = exports.ReadonlyOptionalModifier = void 0;
// ------------------------------------------------------------------------
// Modifiers
// ------------------------------------------------------------------------
exports.ReadonlyOptionalModifier = Symbol('ReadonlyOptionalModifier');
exports.OptionalModifier = Symbol('OptionalModifier');
exports.ReadonlyModifier = Symbol('ReadonlyModifier');
// ------------------------------------------------------------------------
// Schema: Core
// ------------------------------------------------------------------------
exports.UnionKind = Symbol('UnionKind');
exports.IntersectKind = Symbol('IntersectKind');
exports.TupleKind = Symbol('TupleKind');
exports.ObjectKind = Symbol('ObjectKind');
exports.DictKind = Symbol('DictKind');
exports.ArrayKind = Symbol('ArrayKind');
exports.EnumKind = Symbol('EnumKind');
exports.LiteralKind = Symbol('LiteralKind');
exports.StringKind = Symbol('StringKind');
exports.NumberKind = Symbol('NumberKind');
exports.IntegerKind = Symbol('IntegerKind');
exports.BooleanKind = Symbol('BooleanKind');
exports.NullKind = Symbol('NullKind');
exports.UnknownKind = Symbol('UnknownKind');
exports.AnyKind = Symbol('AnyKind');
// ------------------------------------------------------------------------
// Schema: Extended
// ------------------------------------------------------------------------
exports.ConstructorKind = Symbol('ConstructorKind');
exports.FunctionKind = Symbol('FunctionKind');
exports.PromiseKind = Symbol('PromiseKind');
exports.UndefinedKind = Symbol('UndefinedKind');
exports.VoidKind = Symbol('VoidKind');
// ------------------------------------------------------------------------
// Reflect
// ------------------------------------------------------------------------
function reflect(value) {

@@ -40,131 +75,122 @@ switch (typeof value) {

}
// #endregion
// #region TModifier
exports.OptionalModifier = Symbol('OptionalModifier');
exports.ReadonlyModifier = Symbol('ReadonlyModifier');
class Type {
// #region TModifier
/** Modifies the inner type T into an optional T. */
static Optional(item) {
return { ...item, modifier: exports.OptionalModifier };
// ------------------------------------------------------------------------
// TypeBuilder
// ------------------------------------------------------------------------
class TypeBuilder {
/** Modifies a schema object property to be `readonly` and `optional`. */
ReadonlyOptional(item) {
return { ...item, modifier: exports.ReadonlyOptionalModifier };
}
/** Modifies the inner type T into an readonly T. */
static Readonly(item) {
/** Modifies a schema object property to be `readonly`. */
Readonly(item) {
return { ...item, modifier: exports.ReadonlyModifier };
}
// #endregion
// #region TComposite
/** Creates a Union type for the given arguments. */
static Union(items, options = {}) {
return { ...options, oneOf: items };
/** Modifies a schema object property to be `optional`. */
Optional(item) {
return { ...item, modifier: exports.OptionalModifier };
}
/** Creates an Intersect type for the given arguments. */
static Intersect(items, options = {}) {
return { ...options, allOf: items };
/** Creates an Intersect schema. */
Intersect(items, options = {}) {
return { ...options, kind: exports.IntersectKind, allOf: items };
}
/** Creates a Tuple type for the given arguments. */
static Tuple(items, options = {}) {
const type = 'array';
/** Creates a Union schema. */
Union(items, options = {}) {
return { ...options, kind: exports.UnionKind, anyOf: items };
}
/** Creates a Tuple schema. */
Tuple(items, options = {}) {
const additionalItems = false;
const minItems = items.length;
const maxItems = items.length;
return { ...options, type, items, additionalItems, minItems, maxItems };
return { ...options, kind: exports.TupleKind, type: 'array', items, additionalItems, minItems, maxItems };
}
// #endregion
// #region TContract
/** Creates a `function` type for the given arguments. */
static Function(args, returns, options = {}) {
return { ...options, type: 'function', arguments: args, returns };
}
/** Creates a `constructor` type for the given arguments. */
static Constructor(args, returns, options) {
return { ...options, type: 'constructor', arguments: args, returns };
}
/** Creates a `Promise<T>` type. */
static Promise(item, options = {}) {
return { ...options, type: 'promise', item };
}
/** Creates a `void` type. */
static Void(options = {}) {
return { ...options, type: 'void' };
}
/** Creates a `undefined` type. */
static Undefined(options = {}) {
return { ...options, type: 'undefined' };
}
/** Creates a literal from the given value. */
static Literal(value, options = {}) {
const type = reflect(value);
if (type === 'unknown') {
throw Error('Invalid literal value');
}
return { ...options, type, enum: [value] };
}
/** Creates a `object` type with the given properties. */
static Object(properties, options = {}) {
/** Creates a `object` schema with the given properties. */
Object(properties, options = {}) {
const property_names = Object.keys(properties);
const optional = property_names.filter(name => {
const candidate = properties[name];
return (candidate.modifier && candidate.modifier === exports.OptionalModifier);
return (candidate.modifier &&
(candidate.modifier === exports.OptionalModifier ||
candidate.modifier === exports.ReadonlyOptionalModifier));
});
const required = property_names.filter(name => !optional.includes(name));
return { ...options, type: 'object', properties, required: required.length ? required : undefined };
const required_names = property_names.filter(name => !optional.includes(name));
const required = required_names.length ? required_names : undefined;
return { ...options, kind: exports.ObjectKind, type: 'object', properties, required };
}
/** Creates a `{[key: string]: T}` type for the given item. */
static Map(item, options = {}) {
/** Creates a `{ [key: string]: T }` schema. */
Dict(item, options = {}) {
const additionalProperties = item;
return { ...options, type: 'object', additionalProperties };
return { ...options, kind: exports.DictKind, type: 'object', additionalProperties };
}
/** Creates an `Array<T>` type for the given item.` */
static Array(items, options = {}) {
return { ...options, type: 'array', items };
/** Creates an `Array<T>` schema. */
Array(items, options = {}) {
return { ...options, kind: exports.ArrayKind, type: 'array', items };
}
/** Creates an `Enum<T>` from an existing TypeScript enum definition. */
static Enum(item, options) {
// We explicitly want to ignore reverse-lookup entries for number enums hence we are
// getting only keys which are non-numeric and retrieve their value. Credits to
// https://github.com/UselessPickles/ts-enum-util (Jeff Lau) for inspiration.
/** Creates an `Enum<T>` schema from a TypeScript `enum` definition. */
Enum(item, options = {}) {
const values = Object.keys(item).filter(key => isNaN(key)).map(key => item[key]);
return { ...options, enum: values };
return { ...options, kind: exports.EnumKind, enum: values };
}
/** Creates a `string` type. */
static String(options = {}) {
return { ...options, type: 'string' };
/** Creates a literal schema. Supports `string | number | boolean` values. */
Literal(value, options = {}) {
const type = reflect(value);
if (type === 'unknown') {
throw Error(`Invalid literal value '${value}'`);
}
return { ...options, kind: exports.LiteralKind, type, enum: [value] };
}
/** Creates a `number` type. */
static Number(options = {}) {
return { ...options, type: 'number' };
/** Creates a `string` schema. */
String(options = {}) {
return { ...options, kind: exports.StringKind, type: 'string' };
}
/** Creates a `number` type that checks for `integer`. */
static Integer(options = {}) {
return { ...options, type: 'integer' };
/** Creates a `string` schema from a regular expression. */
RegEx(regex) {
return this.String({ pattern: regex.source });
}
/** Creates a `number` schema. */
Number(options = {}) {
return { ...options, kind: exports.NumberKind, type: 'number' };
}
/** Creates a `integer` schema. */
Integer(options = {}) {
return { ...options, kind: exports.IntegerKind, type: 'integer' };
}
/** Creates a `boolean` type. */
static Boolean(options = {}) {
return { ...options, type: 'boolean' };
Boolean(options = {}) {
return { ...options, kind: exports.BooleanKind, type: 'boolean' };
}
/** Creates a `null` type. */
static Null(options = {}) {
return { ...options, type: 'null' };
Null(options = {}) {
return { ...options, kind: exports.NullKind, type: 'null' };
}
/** Creates a `any` type. */
static Any(options = {}) {
return { ...options };
/** Creates an `unknown` type. */
Unknown(options = {}) {
return { ...options, kind: exports.UnknownKind };
}
// #endregion
// #region Aliases
/** Creates a `string` type that validates for the given regular expression. Alias for ```Type.String({ pattern: '...' })``` */
static Pattern(regex) {
return this.String({ pattern: regex.source });
/** Creates an `any` type. */
Any(options = {}) {
return { ...options, kind: exports.AnyKind };
}
/**
* Deprecated: Use `Type.String({ format: 'uuid' })`
*
* Creates a `string` type that validate a Guid. Alias for ```Type.String({ pattern: '...' })```
*/
static Guid() {
const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
return this.String({ pattern: regex.source });
/** `NON-STANDARD` Creates a `constructor` schema. */
Constructor(args, returns, options = {}) {
return { ...options, kind: exports.ConstructorKind, type: 'constructor', arguments: args, returns };
}
/** `NON-STANDARD` Creates a `function` schema. */
Function(args, returns, options = {}) {
return { ...options, kind: exports.FunctionKind, type: 'function', arguments: args, returns };
}
/** `NON-STANDARD` Creates a `Promise<T>` schema. */
Promise(item, options = {}) {
return { ...options, type: 'promise', kind: exports.PromiseKind, item };
}
/** `NON-STANDARD` Creates a `undefined` schema. */
Undefined(options = {}) {
return { ...options, type: 'undefined', kind: exports.UndefinedKind };
}
/** `NON-STANDARD` Creates a `void` schema. */
Void(options = {}) {
return { ...options, type: 'void', kind: exports.VoidKind };
}
}
exports.Type = Type;
exports.TypeBuilder = TypeBuilder;
exports.Type = new TypeBuilder();
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc