arktype 2.0.0-rc.9 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/out/attributes.d.ts +94 -0
  2. package/out/attributes.js +3 -0
  3. package/out/generic.d.ts +13 -13
  4. package/out/index.d.ts +3 -1
  5. package/out/index.js +2 -1
  6. package/out/keywords/{constructors/Array.d.ts → Array.d.ts} +2 -2
  7. package/out/keywords/{constructors/Array.js → Array.js} +2 -2
  8. package/out/keywords/{constructors/FormData.d.ts → FormData.d.ts} +2 -2
  9. package/out/keywords/{constructors/FormData.js → FormData.js} +2 -2
  10. package/out/keywords/{constructors/TypedArray.d.ts → TypedArray.d.ts} +1 -1
  11. package/out/keywords/{constructors/TypedArray.js → TypedArray.js} +2 -2
  12. package/out/keywords/builtins.js +2 -2
  13. package/out/keywords/{constructors/constructors.d.ts → constructors.d.ts} +1 -1
  14. package/out/keywords/{constructors/constructors.js → constructors.js} +2 -2
  15. package/out/keywords/keywords.d.ts +14 -13
  16. package/out/keywords/keywords.js +9 -5
  17. package/out/keywords/number.d.ts +23 -0
  18. package/out/keywords/{number/epoch.js → number.js} +22 -1
  19. package/out/keywords/string.d.ts +327 -0
  20. package/out/keywords/string.js +398 -0
  21. package/out/keywords/ts.d.ts +31 -4
  22. package/out/keywords/ts.js +21 -8
  23. package/out/methods/array.d.ts +6 -7
  24. package/out/methods/base.d.ts +461 -35
  25. package/out/methods/date.d.ts +5 -6
  26. package/out/methods/instantiate.d.ts +4 -4
  27. package/out/methods/morph.d.ts +6 -6
  28. package/out/methods/number.d.ts +8 -9
  29. package/out/methods/object.d.ts +39 -15
  30. package/out/methods/string.d.ts +9 -10
  31. package/out/parser/ast/bounds.d.ts +1 -1
  32. package/out/parser/ast/default.d.ts +2 -2
  33. package/out/parser/ast/generic.d.ts +17 -0
  34. package/out/parser/ast/infer.d.ts +8 -22
  35. package/out/parser/ast/validate.d.ts +13 -9
  36. package/out/parser/ast/validate.js +3 -1
  37. package/out/parser/definition.d.ts +17 -8
  38. package/out/parser/definition.js +38 -3
  39. package/out/parser/objectLiteral.d.ts +39 -39
  40. package/out/parser/objectLiteral.js +83 -67
  41. package/out/parser/property.d.ts +36 -0
  42. package/out/parser/property.js +16 -0
  43. package/out/parser/reduce/dynamic.d.ts +8 -9
  44. package/out/parser/reduce/shared.d.ts +1 -1
  45. package/out/parser/reduce/static.d.ts +4 -4
  46. package/out/parser/shift/operand/date.d.ts +1 -1
  47. package/out/parser/shift/operand/enclosed.d.ts +3 -4
  48. package/out/parser/shift/operand/operand.d.ts +3 -3
  49. package/out/parser/shift/operand/operand.js +2 -2
  50. package/out/parser/shift/operand/unenclosed.d.ts +13 -5
  51. package/out/parser/shift/operand/unenclosed.js +5 -4
  52. package/out/parser/shift/operator/bounds.d.ts +5 -5
  53. package/out/parser/shift/operator/bounds.js +5 -4
  54. package/out/parser/shift/operator/brand.d.ts +6 -0
  55. package/out/parser/shift/operator/brand.js +5 -0
  56. package/out/parser/shift/operator/default.d.ts +3 -2
  57. package/out/parser/shift/operator/default.js +4 -1
  58. package/out/parser/shift/operator/divisor.d.ts +2 -2
  59. package/out/parser/shift/operator/operator.d.ts +4 -3
  60. package/out/parser/shift/operator/operator.js +7 -5
  61. package/out/parser/shift/scanner.d.ts +31 -55
  62. package/out/parser/shift/scanner.js +24 -83
  63. package/out/parser/string.d.ts +5 -4
  64. package/out/parser/string.js +18 -1
  65. package/out/parser/tupleExpressions.d.ts +48 -0
  66. package/out/parser/tupleExpressions.js +67 -0
  67. package/out/parser/tupleLiteral.d.ts +95 -0
  68. package/out/parser/tupleLiteral.js +122 -0
  69. package/out/scope.d.ts +17 -12
  70. package/out/scope.js +25 -41
  71. package/out/type.d.ts +63 -5
  72. package/out/type.js +3 -2
  73. package/package.json +8 -8
  74. package/out/keywords/constructors/Date.d.ts +0 -31
  75. package/out/keywords/inference.d.ts +0 -220
  76. package/out/keywords/inference.js +0 -2
  77. package/out/keywords/number/epoch.d.ts +0 -9
  78. package/out/keywords/number/integer.d.ts +0 -3
  79. package/out/keywords/number/integer.js +0 -5
  80. package/out/keywords/number/number.d.ts +0 -53
  81. package/out/keywords/number/number.js +0 -21
  82. package/out/keywords/string/alpha.d.ts +0 -7
  83. package/out/keywords/string/alpha.js +0 -2
  84. package/out/keywords/string/alphanumeric.d.ts +0 -7
  85. package/out/keywords/string/alphanumeric.js +0 -2
  86. package/out/keywords/string/capitalize.d.ts +0 -15
  87. package/out/keywords/string/capitalize.js +0 -12
  88. package/out/keywords/string/creditCard.d.ts +0 -8
  89. package/out/keywords/string/creditCard.js +0 -37
  90. package/out/keywords/string/date.d.ts +0 -55
  91. package/out/keywords/string/date.js +0 -98
  92. package/out/keywords/string/digits.d.ts +0 -7
  93. package/out/keywords/string/digits.js +0 -2
  94. package/out/keywords/string/email.d.ts +0 -7
  95. package/out/keywords/string/email.js +0 -4
  96. package/out/keywords/string/integer.d.ts +0 -16
  97. package/out/keywords/string/integer.js +0 -16
  98. package/out/keywords/string/ip.d.ts +0 -20
  99. package/out/keywords/string/ip.js +0 -23
  100. package/out/keywords/string/json.d.ts +0 -16
  101. package/out/keywords/string/json.js +0 -53
  102. package/out/keywords/string/lower.d.ts +0 -15
  103. package/out/keywords/string/lower.js +0 -12
  104. package/out/keywords/string/normalize.d.ts +0 -88
  105. package/out/keywords/string/normalize.js +0 -43
  106. package/out/keywords/string/numeric.d.ts +0 -15
  107. package/out/keywords/string/numeric.js +0 -13
  108. package/out/keywords/string/semver.d.ts +0 -7
  109. package/out/keywords/string/semver.js +0 -4
  110. package/out/keywords/string/string.d.ts +0 -108
  111. package/out/keywords/string/string.js +0 -41
  112. package/out/keywords/string/trim.d.ts +0 -15
  113. package/out/keywords/string/trim.js +0 -14
  114. package/out/keywords/string/upper.d.ts +0 -15
  115. package/out/keywords/string/upper.js +0 -12
  116. package/out/keywords/string/url.d.ts +0 -15
  117. package/out/keywords/string/url.js +0 -37
  118. package/out/keywords/string/utils.d.ts +0 -2
  119. package/out/keywords/string/utils.js +0 -10
  120. package/out/keywords/string/uuid.d.ts +0 -42
  121. package/out/keywords/string/uuid.js +0 -19
  122. package/out/keywords/utils.d.ts +0 -1
  123. package/out/keywords/utils.js +0 -2
  124. package/out/methods/validator.d.ts +0 -11
  125. package/out/methods/validator.js +0 -1
  126. package/out/parser/tuple.d.ts +0 -143
  127. package/out/parser/tuple.js +0 -164
  128. /package/out/{keywords/constructors/Date.js → parser/ast/generic.js} +0 -0
package/out/scope.d.ts CHANGED
@@ -1,13 +1,20 @@
1
1
  import { BaseScope, type AliasDefEntry, type ArkScopeConfig, type BaseNode, type BaseParseContext, type BaseParseContextInput, type BaseParseOptions, type BaseRoot, type GenericAst, type GenericParamAst, type GenericParamDef, type NodeKind, type NodeSchema, type PreparsedNodeResolution, type PrivateDeclaration, type RootKind, type RootSchema, type arkKind, type exportedNameOf, type nodeOfKind, type reducibleKindOf, type toInternalScope, type writeDuplicateAliasError } from "@ark/schema";
2
- import { type ErrorType, type Json, type anyOrNever, type array, type flattenListable, type noSuggest, type nominal } from "@ark/util";
2
+ import { type Brand, type ErrorType, type JsonStructure, type anyOrNever, type array, type flattenListable, type noSuggest } from "@ark/util";
3
3
  import type { ArkSchemaRegistry } from "./config.ts";
4
4
  import { type GenericDeclaration, type GenericParser, type ParameterString, type baseGenericConstraints, type parseGenericParams, type parseValidGenericParams } from "./generic.ts";
5
5
  import type { Ark, type } from "./keywords/keywords.ts";
6
6
  import type { BoundModule, Module, Submodule, instantiateExport } from "./module.ts";
7
7
  import type { DefAst, InferredAst } from "./parser/ast/infer.ts";
8
- import { type inferDefinition, type validateDefinition } from "./parser/definition.ts";
9
- import { InternalTypeParser, type DeclarationParser, type DefinitionParser, type EnumeratedTypeParser, type SchemaParser, type TypeParser, type UnitTypeParser } from "./type.ts";
10
- export type ScopeParser = <const def>(def: scope.validate<def>, config?: ArkScopeConfig) => Scope<scope.infer<def>>;
8
+ import { type inferDefinition } from "./parser/definition.ts";
9
+ import type { ParsedOptionalProperty } from "./parser/property.ts";
10
+ import type { ParsedDefaultableProperty } from "./parser/shift/operator/default.ts";
11
+ import { InternalTypeParser, type DeclarationParser, type DefinitionParser, type EnumeratedTypeParser, type InstanceOfTypeParser, type SchemaParser, type TypeParser, type UnitTypeParser } from "./type.ts";
12
+ /** The convenience properties attached to `scope` */
13
+ export type ScopeParserAttachments = Omit<ScopeParser, never>;
14
+ export interface ScopeParser {
15
+ <const def>(def: scope.validate<def>, config?: ArkScopeConfig): Scope<scope.infer<def>>;
16
+ define: <const def>(def: scope.validate<def>) => def;
17
+ }
11
18
  export type ModuleParser = <const def>(def: scope.validate<def>, config?: ArkScopeConfig) => scope.infer<def> extends infer $ ? Module<{
12
19
  [k in exportedNameOf<$>]: $[k];
13
20
  }> : never;
@@ -15,7 +22,7 @@ export type bindThis<def> = {
15
22
  this: Def<def>;
16
23
  };
17
24
  /** nominal type for an unparsed definition used during scope bootstrapping */
18
- type Def<def = {}> = nominal<def, "unparsed">;
25
+ type Def<def = {}> = Brand<def, "unparsed">;
19
26
  /** sentinel indicating a scope that will be associated with a generic has not yet been parsed */
20
27
  export type UnparsedScope = "$";
21
28
  /** These are legal as values of a scope but not as definitions in other contexts */
@@ -58,39 +65,36 @@ export interface InternalScope {
58
65
  constructor: typeof InternalScope;
59
66
  }
60
67
  export declare class InternalScope<$ extends {} = {}> extends BaseScope<$> {
61
- private parseCache;
62
- protected cacheGetter<name extends keyof this>(name: name, value: this[name]): this[name];
63
68
  get ambientAttachments(): Ark.boundTypeAttachments<$> | undefined;
64
69
  protected preparseOwnAliasEntry(k: string, v: unknown): AliasDefEntry;
65
70
  parseGenericParams(def: string, opts: BaseParseOptions): array<GenericParamDef>;
66
71
  protected normalizeRootScopeValue(resolution: unknown): unknown;
67
72
  protected preparseOwnDefinitionFormat(def: unknown, opts: BaseParseOptions): BaseRoot | BaseParseContextInput;
68
73
  parseOwnDefinitionFormat(def: unknown, ctx: BaseParseContext): BaseRoot;
69
- parseString(def: string, ctx: BaseParseContext): BaseRoot;
70
74
  unit: UnitTypeParser<$>;
71
75
  enumerated: EnumeratedTypeParser<$>;
76
+ instanceOf: InstanceOfTypeParser<$>;
72
77
  type: InternalTypeParser;
73
78
  declare: () => {
74
79
  type: InternalTypeParser;
75
80
  };
76
- define: (def: unknown) => unknown;
81
+ define<def>(def: def): def;
77
82
  static scope: ScopeParser;
78
83
  static module: ModuleParser;
79
84
  }
80
85
  export declare const scope: ScopeParser;
81
86
  export declare namespace scope {
82
87
  type validate<def> = {
83
- [k in keyof def]: k extends noSuggest ? unknown : parseScopeKey<k, def>["params"] extends infer params ? params extends array<GenericParamAst> ? params["length"] extends 0 ? def[k] extends type.Any | PreparsedResolution ? def[k] : k extends (PrivateDeclaration<infer name extends keyof def & string>) ? ErrorType<writeDuplicateAliasError<name>> : validateDefinition<def[k], bootstrapAliases<def>, {}> : validateDefinition<def[k], bootstrapAliases<def>, baseGenericConstraints<params>> : params : never;
88
+ [k in keyof def]: k extends noSuggest ? unknown : parseScopeKey<k, def>["params"] extends infer params ? params extends array<GenericParamAst> ? params["length"] extends 0 ? def[k] extends type.Any | PreparsedResolution ? def[k] : k extends (PrivateDeclaration<infer name extends keyof def & string>) ? ErrorType<writeDuplicateAliasError<name>> : type.validate<def[k], bootstrapAliases<def>, {}> : type.validate<def[k], bootstrapAliases<def>, baseGenericConstraints<params>> : params : never;
84
89
  };
85
90
  type infer<def> = inferBootstrapped<bootstrapAliases<def>>;
86
91
  }
87
- export declare const module: ModuleParser;
88
92
  export interface Scope<$ = {}> {
89
93
  t: $;
90
94
  [arkKind]: "scope";
91
95
  config: ArkScopeConfig;
92
96
  references: readonly BaseNode[];
93
- json: Json;
97
+ json: JsonStructure;
94
98
  exportedNames: array<exportedNameOf<$>>;
95
99
  /** The set of names defined at the root-level of the scope mapped to their
96
100
  * corresponding definitions.**/
@@ -133,4 +137,5 @@ type parseGenericScopeKey<name extends string, params extends string, def> = {
133
137
  name: name;
134
138
  params: parseGenericParams<params, bootstrapAliases<def>>;
135
139
  };
140
+ export type InnerParseResult = BaseRoot | ParsedOptionalProperty | ParsedDefaultableProperty;
136
141
  export {};
package/out/scope.js CHANGED
@@ -1,19 +1,12 @@
1
1
  import { $ark, BaseScope, hasArkKind, parseGeneric } from "@ark/schema";
2
- import { domainOf, flatMorph, hasDomain, isThunk, throwParseError } from "@ark/util";
2
+ import { flatMorph, isArray, isThunk, throwParseError } from "@ark/util";
3
3
  import { parseGenericParamName } from "./generic.js";
4
- import { parseObject, writeBadDefinitionTypeMessage } from "./parser/definition.js";
5
- import { DynamicState } from "./parser/reduce/dynamic.js";
6
- import { writeUnexpectedCharacterMessage } from "./parser/shift/operator/operator.js";
7
- import { Scanner } from "./parser/shift/scanner.js";
8
- import { fullStringParse } from "./parser/string.js";
4
+ import { shallowDefaultableMessage, shallowOptionalMessage } from "./parser/ast/validate.js";
5
+ import { parseInnerDefinition } from "./parser/definition.js";
6
+ import { ArkTypeScanner } from "./parser/shift/scanner.js";
9
7
  import { InternalTypeParser } from "./type.js";
10
8
  export const $arkTypeRegistry = $ark;
11
9
  export class InternalScope extends BaseScope {
12
- parseCache = {};
13
- cacheGetter(name, value) {
14
- Object.defineProperty(this, name, { value });
15
- return value;
16
- }
17
10
  get ambientAttachments() {
18
11
  if (!$arkTypeRegistry.typeAttachments)
19
12
  return;
@@ -43,7 +36,11 @@ export class InternalScope extends BaseScope {
43
36
  ];
44
37
  }
45
38
  parseGenericParams(def, opts) {
46
- return parseGenericParamName(new Scanner(def), [], this.createParseContext({ ...opts, def, prefix: "generic" }));
39
+ return parseGenericParamName(new ArkTypeScanner(def), [], this.createParseContext({
40
+ ...opts,
41
+ def,
42
+ prefix: "generic"
43
+ }));
47
44
  }
48
45
  normalizeRootScopeValue(resolution) {
49
46
  if (isThunk(resolution) && !hasArkKind(resolution, "generic"))
@@ -60,46 +57,33 @@ export class InternalScope extends BaseScope {
60
57
  parseOwnDefinitionFormat(def, ctx) {
61
58
  const isScopeAlias = ctx.alias && ctx.alias in this.aliases;
62
59
  // if the definition being parsed is not a scope alias and is not a
63
- // generic instantiation (i.e. opts don't include args), add this as a resolution.
60
+ // generic instantiation (i.e. opts don't include args), add `this` as a resolution.
61
+ // if we're parsing a nested string, ctx.args will have already been set
64
62
  if (!isScopeAlias && !ctx.args)
65
63
  ctx.args = { this: ctx.id };
66
- if (typeof def === "string") {
67
- if (ctx.args && Object.keys(ctx.args).some(k => def.includes(k))) {
68
- // we can only rely on the cache if there are no contextual
69
- // resolutions like "this" or generic args
70
- return this.parseString(def, ctx);
71
- }
72
- return (this.parseCache[def] ??= this.parseString(def, ctx));
64
+ const result = parseInnerDefinition(def, ctx);
65
+ if (isArray(result)) {
66
+ if (result[1] === "=")
67
+ return throwParseError(shallowDefaultableMessage);
68
+ if (result[1] === "?")
69
+ return throwParseError(shallowOptionalMessage);
73
70
  }
74
- return hasDomain(def, "object") ?
75
- parseObject(def, ctx)
76
- : throwParseError(writeBadDefinitionTypeMessage(domainOf(def)));
77
- }
78
- parseString(def, ctx) {
79
- const aliasResolution = this.maybeResolveRoot(def);
80
- if (aliasResolution)
81
- return aliasResolution;
82
- const aliasArrayResolution = def.endsWith("[]") ?
83
- this.maybeResolveRoot(def.slice(0, -2))?.array()
84
- : undefined;
85
- if (aliasArrayResolution)
86
- return aliasArrayResolution;
87
- const s = new DynamicState(new Scanner(def), ctx);
88
- const node = fullStringParse(s);
89
- if (s.finalizer === ">")
90
- throwParseError(writeUnexpectedCharacterMessage(">"));
91
- return node;
71
+ return result;
92
72
  }
93
73
  unit = value => this.units([value]);
94
74
  enumerated = (...values) => this.units(values);
75
+ instanceOf = ctor => this.node("proto", { proto: ctor }, { prereduced: true });
95
76
  type = new InternalTypeParser(this);
96
77
  declare = () => ({
97
78
  type: this.type
98
79
  });
99
- define = ((def) => def).bind(this);
80
+ define(def) {
81
+ return def;
82
+ }
100
83
  static scope = ((def, config = {}) => new InternalScope(def, config));
101
84
  static module = ((def, config = {}) => this.scope(def, config).export());
102
85
  }
103
- export const scope = InternalScope.scope;
104
- export const module = InternalScope.module;
86
+ export const scope = Object.assign(InternalScope.scope, {
87
+ define: def => def
88
+ });
105
89
  export const Scope = InternalScope;
package/out/type.d.ts CHANGED
@@ -1,31 +1,88 @@
1
1
  import { ArkErrors, BaseRoot, type BaseParseOptions, type MetaSchema, type Morph, type Predicate, type RootSchema } from "@ark/schema";
2
2
  import { Callable, Hkt, type Constructor, type array, type conform } from "@ark/util";
3
+ import type { distill } from "./attributes.ts";
3
4
  import type { Generic, GenericParser, ParameterString, baseGenericConstraints, parseValidGenericParams, validateParameterString } from "./generic.ts";
4
- import type { distill } from "./keywords/inference.ts";
5
5
  import type { Ark, keywords, type } from "./keywords/keywords.ts";
6
6
  import type { BaseType } from "./methods/base.ts";
7
7
  import type { instantiateType } from "./methods/instantiate.ts";
8
- import type { validateDeclared, validateDefinition } from "./parser/definition.ts";
9
- import type { IndexOneOperator, IndexZeroOperator, TupleInfixOperator } from "./parser/tuple.ts";
8
+ import type { validateDeclared } from "./parser/definition.ts";
9
+ import type { ArgTwoOperator, IndexZeroOperator, TupleInfixOperator } from "./parser/tupleExpressions.ts";
10
10
  import type { InternalScope, ModuleParser, Scope, ScopeParser, bindThis } from "./scope.ts";
11
11
  /** The convenience properties attached to `type` */
12
12
  export type TypeParserAttachments = Omit<TypeParser, never>;
13
13
  export interface TypeParser<$ = {}> extends Ark.boundTypeAttachments<$> {
14
+ /**
15
+ * Create a {@link Type} from your definition.
16
+ *
17
+ * @example const person = type({ name: "string" })
18
+ */
14
19
  <const def, r = Type<type.infer<def, $>, $>>(def: type.validate<def, $>): r;
15
- <const params extends ParameterString, const def>(params: validateParameterString<params, $>, def: validateDefinition<def, $, baseGenericConstraints<parseValidGenericParams<params, $>>>): Generic<parseValidGenericParams<params, $>, def, $>;
16
- <const zero, const one, const rest extends array, r = Type<type.infer<[zero, one, ...rest], $>, $>>(_0: zero extends IndexZeroOperator ? zero : type.validate<zero, $>, _1: zero extends "keyof" ? type.validate<one, $> : zero extends "instanceof" ? conform<one, Constructor> : zero extends "===" ? conform<one, unknown> : conform<one, IndexOneOperator>, ..._2: zero extends "===" ? rest : zero extends "instanceof" ? conform<rest, readonly Constructor[]> : one extends TupleInfixOperator ? one extends ":" ? [Predicate<distill.In<type.infer<zero, $>>>] : one extends "=>" ? [Morph<distill.Out<type.infer<zero, $>>, unknown>] : one extends "@" ? [MetaSchema] : [type.validate<rest[0], $>] : []): r;
20
+ /**
21
+ * Create a {@link Generic} from a parameter string and body definition.
22
+ *
23
+ * @param params A string like "<t, n extends number>" specifying the
24
+ * {@link Generic}'s parameters and any associated constraints via `extends`.
25
+ *
26
+ * @param def The definition for the body of the {@link Generic}. Can reference the
27
+ * parameter names specified in the previous argument in addition to aliases
28
+ * from its {@link Scope}.
29
+ *
30
+ * @example const boxOf = type("<t extends string | number>", { contents: "t" })
31
+ */
32
+ <const params extends ParameterString, const def>(params: validateParameterString<params, $>, def: type.validate<def, $, baseGenericConstraints<parseValidGenericParams<params, $>>>): Generic<parseValidGenericParams<params, $>, def, $>;
33
+ /**
34
+ * Create a {@link Type} from a [tuple expression](http://localhost:3000/docs/expressions)
35
+ * spread as this function's arguments.
36
+ *
37
+ * @example type("string", "|", { foo: "number" })
38
+ */
39
+ <const zero, const one, const rest extends array, r = Type<type.infer<[zero, one, ...rest], $>, $>>(_0: zero extends IndexZeroOperator ? zero : type.validate<zero, $>, _1: zero extends "keyof" ? type.validate<one, $> : zero extends "instanceof" ? conform<one, Constructor> : zero extends "===" ? conform<one, unknown> : conform<one, ArgTwoOperator>, ..._2: zero extends "===" ? rest : zero extends "instanceof" ? conform<rest, readonly Constructor[]> : one extends TupleInfixOperator ? one extends ":" ? [Predicate<distill.In<type.infer<zero, $>>>] : one extends "=>" ? [Morph<distill.Out<type.infer<zero, $>>, unknown>] : one extends "@" ? [MetaSchema] : [type.validate<rest[0], $>] : []): r;
40
+ /**
41
+ * An alias of the {@link ArkErrors} class, an instance of which is returned when a {@link Type}
42
+ * is invoked with invalid input.
43
+ *
44
+ * @example
45
+ * const out = myType(data)
46
+ *
47
+ * if(out instanceof type.errors) console.log(out.summary)
48
+ *
49
+ */
17
50
  errors: typeof ArkErrors;
18
51
  hkt: typeof Hkt;
19
52
  keywords: typeof keywords;
53
+ /**
54
+ * The {@link Scope} in which definitions passed to this function will be parsed.
55
+ */
20
56
  $: Scope<$>;
57
+ /**
58
+ * An alias of `type` with no type-level validation or inference.
59
+ *
60
+ * Useful when wrapping `type` or using it to parse a dynamic definition.
61
+ */
21
62
  raw(def: unknown): BaseType<any, $>;
22
63
  module: ModuleParser;
23
64
  scope: ScopeParser;
24
65
  define: DefinitionParser<$>;
25
66
  generic: GenericParser<$>;
26
67
  schema: SchemaParser<$>;
68
+ /**
69
+ * Create a {@link Type} that is satisfied only by a value strictly equal (`===`) to the argument passed to this function.
70
+ * @example const foo = type.unit('foo') // {@link Type}<'foo'>
71
+ * @example const sym: unique symbol = Symbol(); type.unit(sym) // {@link Type}<typeof sym>
72
+ */
27
73
  unit: UnitTypeParser<$>;
74
+ /**
75
+ * Create a {@link Type} that is satisfied only by a value strictly equal (`===`) to one of the arguments passed to this function.
76
+ * @example const enum = type.enumerated('foo', 'bar', obj) // obj is a by-reference object
77
+ * @example const tupleForm = type(['===', 'foo', 'bar', obj])
78
+ * @example const argsForm = type('===', 'foo', 'bar', obj)
79
+ */
28
80
  enumerated: EnumeratedTypeParser<$>;
81
+ /**
82
+ * Create a {@link Type} that is satisfied only by a value of a specific class.
83
+ * @example const array = type.instanceOf(Array)
84
+ */
85
+ instanceOf: InstanceOfTypeParser<$>;
29
86
  }
30
87
  export declare class InternalTypeParser extends Callable<(...args: unknown[]) => BaseRoot | Generic, TypeParserAttachments> {
31
88
  constructor($: InternalScope);
@@ -34,6 +91,7 @@ export type DeclarationParser<$> = <preinferred>() => {
34
91
  type: <const def>(def: validateDeclared<preinferred, def, $, bindThis<def>>) => Type<preinferred, $>;
35
92
  };
36
93
  export type UnitTypeParser<$> = <const t>(value: t) => Type<t, $>;
94
+ export type InstanceOfTypeParser<$> = <const t extends object>(ctor: Constructor<t>) => Type<t, $>;
37
95
  export type EnumeratedTypeParser<$> = <const values extends readonly unknown[]>(...values: values) => Type<values[number], $>;
38
96
  export type DefinitionParser<$> = <const def>(def: type.validate<def, $>) => def;
39
97
  export type SchemaParser<$> = (schema: RootSchema, opts?: BaseParseOptions) => Type<unknown, $>;
package/out/type.js CHANGED
@@ -15,7 +15,8 @@ export class InternalTypeParser extends Callable {
15
15
  // this won't be defined during bootstrapping, but externally always will be
16
16
  keywords: $.ambient,
17
17
  unit: $.unit,
18
- enumerated: $.enumerated
18
+ enumerated: $.enumerated,
19
+ instanceOf: $.instanceOf
19
20
  },
20
21
  // also won't be defined during bootstrapping
21
22
  $.ambientAttachments);
@@ -32,7 +33,7 @@ export class InternalTypeParser extends Callable {
32
33
  // treat as a generic
33
34
  const paramString = args[0].slice(1, -1);
34
35
  const params = $.parseGenericParams(paramString, {});
35
- return new GenericRoot(params, args[1], $, $);
36
+ return new GenericRoot(params, args[1], $, $, null);
36
37
  }
37
38
  // otherwise, treat as a tuple expression. technically, this also allows
38
39
  // non-expression tuple definitions to be parsed, but it's not a supported
package/package.json CHANGED
@@ -1,18 +1,18 @@
1
1
  {
2
2
  "name": "arktype",
3
3
  "description": "TypeScript's 1:1 validator, optimized from editor to runtime",
4
- "version": "2.0.0-rc.9",
4
+ "version": "2.0.1",
5
5
  "license": "MIT",
6
- "author": {
7
- "name": "David Blass",
8
- "email": "david@arktype.io",
9
- "url": "https://arktype.io"
10
- },
11
6
  "repository": {
12
7
  "type": "git",
13
8
  "url": "https://github.com/arktypeio/arktype.git",
14
9
  "directory": "ark/type"
15
10
  },
11
+ "author": {
12
+ "name": "David Blass",
13
+ "email": "david@arktype.io",
14
+ "url": "https://arktype.io"
15
+ },
16
16
  "type": "module",
17
17
  "main": "./out/index.js",
18
18
  "types": "./out/index.d.ts",
@@ -34,8 +34,8 @@
34
34
  "out"
35
35
  ],
36
36
  "dependencies": {
37
- "@ark/schema": "0.11.0",
38
- "@ark/util": "0.11.0"
37
+ "@ark/util": "0.36.0",
38
+ "@ark/schema": "0.36.0"
39
39
  },
40
40
  "publishConfig": {
41
41
  "access": "public"
@@ -1,31 +0,0 @@
1
- import type { Branded, constrain, constraint, Constraints, Literal, Narrowed, normalizeLimit, Optional } from "../inference.ts";
2
- export type AtOrAfter<rule> = {
3
- atOrAfter: constraint<rule>;
4
- };
5
- export type AtOrBefore<rule> = {
6
- atOrBefore: constraint<rule>;
7
- };
8
- export type After<rule> = {
9
- after: constraint<rule>;
10
- };
11
- export type Before<rule> = {
12
- before: constraint<rule>;
13
- };
14
- export declare namespace Date {
15
- type atOrAfter<rule> = constrain<Date, AtOrAfter<rule>>;
16
- type after<rule> = constrain<Date, After<rule>>;
17
- type atOrBefore<rule> = constrain<Date, AtOrBefore<rule>>;
18
- type before<rule> = constrain<Date, Before<rule>>;
19
- type narrowed = constrain<Date, Narrowed>;
20
- type optional = constrain<Date, Optional>;
21
- type branded<rule> = constrain<Date, Branded<rule>>;
22
- type literal<rule> = constrain<Date, Literal<rule>>;
23
- type is<constraints extends Constraints> = constrain<Date, constraints>;
24
- type afterSchemaToConstraint<schema, rule> = schema extends {
25
- exclusive: true;
26
- } ? After<normalizeLimit<rule>> : AtOrAfter<normalizeLimit<rule>>;
27
- type beforeSchemaToConstraint<schema, rule> = schema extends {
28
- exclusive: true;
29
- } ? Before<normalizeLimit<rule>> : AtOrBefore<normalizeLimit<rule>>;
30
- type withConstraint<constraint> = constraint extends After<infer rule> ? after<rule> : constraint extends Before<infer rule> ? before<rule> : constraint extends AtOrAfter<infer rule> ? atOrAfter<rule> : constraint extends AtOrBefore<infer rule> ? atOrBefore<rule> : constraint extends Optional ? optional : constraint extends Narrowed ? narrowed : never;
31
- }
@@ -1,220 +0,0 @@
1
- import type { ArkError, ArkErrors, Constraint, constraintKindOf, Morph, NodeSchema } from "@ark/schema";
2
- import { type anyOrNever, type array, type conform, type equals, type Hkt, type intersectArrays, type isSafelyMappable, type leftIfEqual, type objectKindOf, type Primitive, type show } from "@ark/util";
3
- import type { Type } from "../type.ts";
4
- import type { arkPrototypes } from "./constructors/constructors.ts";
5
- import type { Date } from "./constructors/Date.ts";
6
- import type { type } from "./keywords.ts";
7
- import type { DivisibleBy, number } from "./number/number.ts";
8
- import type { Matching, string } from "./string/string.ts";
9
- export type { arkPrototypes as object } from "./constructors/constructors.ts";
10
- export type { number } from "./number/number.ts";
11
- export type { string } from "./string/string.ts";
12
- export type Comparator = "<" | "<=" | ">" | ">=" | "==";
13
- export type RegexLiteral<source extends string = string> = `/${source}/`;
14
- export type DateLiteral<source extends string = string> = `d"${source}"` | `d'${source}'`;
15
- export type ConstraintSet = Record<PropertyKey, 1>;
16
- export type Constraints = Record<string, ConstraintSet>;
17
- export declare const constrained: " arkConstrained";
18
- export type constrained = typeof constrained;
19
- export type constrain<base, constraints extends Constraints> = base & {
20
- [constrained]: constraints;
21
- };
22
- export type LimitLiteral = number | DateLiteral;
23
- export type normalizeLimit<limit> = limit extends DateLiteral<infer source> ? source : limit extends number | string ? limit : never;
24
- export type constraint<rule> = {
25
- [k in rule & PropertyKey]: 1;
26
- };
27
- export type Literal<rule> = {
28
- literal: constraint<rule>;
29
- };
30
- export type Narrowed = {
31
- predicate: {
32
- "?": 1;
33
- };
34
- };
35
- export type Branded<rule> = {
36
- predicate: constraint<rule>;
37
- };
38
- export type primitiveConstraintKindOf<In> = Extract<Constraint.PrimitiveKind, constraintKindOf<In>>;
39
- export type AtLeastLength<rule> = {
40
- atLeastLength: constraint<rule>;
41
- };
42
- export type AtMostLength<rule> = {
43
- atMostLength: constraint<rule>;
44
- };
45
- export type MoreThanLength<rule> = {
46
- moreThanLength: constraint<rule>;
47
- };
48
- export type LessThanLength<rule> = {
49
- lessThanLength: constraint<rule>;
50
- };
51
- export type ExactlyLength<rule> = {
52
- atLeastLength: constraint<rule>;
53
- atMostLength: constraint<rule>;
54
- };
55
- export type applyConstraintSchema<t, kind extends Constraint.PrimitiveKind, schema extends NodeSchema<kind>> = t extends InferredMorph<infer i, infer o> ? (In: leftIfEqual<i, applyConstraint<i, schemaToConstraint<kind, schema>>>) => o : leftIfEqual<t, applyConstraint<t, schemaToConstraint<kind, schema>>>;
56
- export type applyConstraint<t, constraint> = parseConstraints<t> extends ([
57
- infer base,
58
- infer constraints extends Constraints
59
- ]) ? [
60
- number,
61
- base
62
- ] extends [base, number] ? number.is<constraint & constraints> : [string, base] extends [base, string] ? string.is<constraint & constraints> : [Date, base] extends [base, Date] ? Date.is<constraint & constraints> : constrain<base, constraints & constraint> : [number, t] extends [t, number] ? number.withConstraint<constraint> : [string, t] extends [t, string] ? string.withConstraint<constraint> : [Date, t] extends [t, Date] ? Date.withConstraint<constraint> : constrain<t, conform<constraint, Constraints>>;
63
- export type parseConstraints<t> = t extends constrain<infer base, infer constraints> ? equals<t, number & {
64
- [constrained]: constraints;
65
- }> extends true ? [
66
- number,
67
- constraints
68
- ] : equals<t, string & {
69
- [constrained]: constraints;
70
- }> extends true ? [
71
- string,
72
- constraints
73
- ] : equals<t, bigint & {
74
- [constrained]: constraints;
75
- }> extends true ? [
76
- bigint,
77
- constraints
78
- ] : equals<t, symbol & {
79
- [constrained]: constraints;
80
- }> extends true ? [
81
- symbol,
82
- constraints
83
- ] : objectKindOf<t> extends infer kind ? kind extends BuiltinTerminalObjectKind ? [
84
- arkPrototypes.instanceOf<kind>,
85
- constraints
86
- ] : kind extends "Array" ? null : kind extends undefined ? [Omit<base, constrained>, constraints] : [base, constraints] : never : null;
87
- export type normalizePrimitiveConstraintRoot<schema extends NodeSchema<Constraint.PrimitiveKind>> = "rule" extends keyof schema ? conform<schema["rule"], PropertyKey> : conform<schema, PropertyKey>;
88
- type minLengthSchemaToConstraint<schema, rule> = schema extends {
89
- exclusive: true;
90
- } ? MoreThanLength<rule> : AtLeastLength<rule>;
91
- type maxLengthSchemaToConstraint<schema, rule> = schema extends {
92
- exclusive: true;
93
- } ? LessThanLength<rule> : AtMostLength<rule>;
94
- export type schemaToConstraint<kind extends Constraint.PrimitiveKind, schema extends NodeSchema<kind>> = normalizePrimitiveConstraintRoot<schema> extends infer rule ? kind extends "pattern" ? Matching<rule> : kind extends "divisor" ? DivisibleBy<rule> : kind extends "min" ? number.minSchemaToConstraint<schema, rule> : kind extends "max" ? number.maxSchemaToConstraint<schema, rule> : kind extends "minLength" ? minLengthSchemaToConstraint<schema, rule> : kind extends "maxLength" ? maxLengthSchemaToConstraint<schema, rule> : kind extends "exactLength" ? ExactlyLength<rule> : kind extends "after" ? Date.afterSchemaToConstraint<schema, rule> : kind extends "before" ? Date.beforeSchemaToConstraint<schema, rule> : Narrowed : never;
95
- export type distill<t, opts extends distill.Options = {}> = finalizeDistillation<t, _distill<t, opts>>;
96
- export declare namespace distill {
97
- type Endpoint = "in" | "out" | "out.introspectable";
98
- type Options = {
99
- endpoint?: Endpoint;
100
- branded?: true;
101
- };
102
- type In<t> = distill<t, {
103
- endpoint: "in";
104
- }>;
105
- type Out<t> = distill<t, {
106
- endpoint: "out";
107
- }>;
108
- namespace brandable {
109
- type In<t> = distill<t, {
110
- endpoint: "in";
111
- branded: true;
112
- }>;
113
- type Out<t> = distill<t, {
114
- endpoint: "out";
115
- branded: true;
116
- }>;
117
- namespace introspectable {
118
- type Out<t> = distill<t, {
119
- endpoint: "out.introspectable";
120
- branded: true;
121
- }>;
122
- }
123
- }
124
- type unbranded<t> = distill<t>;
125
- namespace introspectable {
126
- type Out<t> = distill<t, {
127
- endpoint: "out.introspectable";
128
- }>;
129
- }
130
- }
131
- type finalizeDistillation<t, distilled> = equals<t, distilled> extends true ? t : distilled;
132
- export type includesMorphs<t> = [
133
- _distill<t, {
134
- endpoint: "in";
135
- branded: true;
136
- }>,
137
- _distill<t, {
138
- endpoint: "out";
139
- branded: true;
140
- }>
141
- ] extends ([
142
- _distill<t, {
143
- endpoint: "out";
144
- branded: true;
145
- }>,
146
- _distill<t, {
147
- endpoint: "in";
148
- branded: true;
149
- }>
150
- ]) ? false : true;
151
- type _distill<t, opts extends distill.Options> = t extends undefined ? t : [t] extends [anyOrNever] ? t : parseConstraints<t> extends ([
152
- infer base,
153
- infer constraints extends Constraints
154
- ]) ? opts["branded"] extends true ? constrain<_distill<base, opts>, constraints> : _distill<base, opts> : unknown extends t ? unknown : t extends TerminallyInferredObject | Primitive ? t : t extends InferredMorph<infer i, infer o> ? opts["branded"] extends true ? distillIo<i, o, opts> : distillUnbrandedIo<t, i, o, opts> : t extends array ? distillArray<t, opts> : t extends InferredDefault<infer t> ? _distill<t, opts> : t extends Function ? t : isSafelyMappable<t> extends true ? distillMappable<t, opts> : t;
155
- type distillMappable<o, opts extends distill.Options> = opts["endpoint"] extends "in" ? show<{
156
- [k in keyof o as k extends inferredOptionalOrDefaultKeyOf<o> ? never : k]: _distill<o[k], opts>;
157
- } & {
158
- [k in inferredOptionalOrDefaultKeyOf<o>]?: _distill<o[k], opts>;
159
- }> : show<{
160
- [k in keyof o as k extends inferredOptionalKeyOf<o> ? never : k]: _distill<o[k], opts>;
161
- } & {
162
- [k in keyof o as k extends inferredOptionalKeyOf<o> ? k : never]?: _distill<o[k], opts>;
163
- }>;
164
- type distillUnbrandedIo<t extends InferredMorph, i, o extends Out, opts extends distill.Options> = t extends (InferredMorph<constrain<infer constrainedIn, any>, Out<constrain<infer constrainedOut, any>>>) ? distillIo<constrainedIn, o extends To ? To<constrainedOut> : Out<constrainedOut>, opts> : t extends InferredMorph<constrain<infer constrainedIn, any>> ? distillIo<constrainedIn, o, opts> : t extends InferredMorph<any, Out<constrain<infer constrainedOut, any>>> ? distillIo<i, o extends To ? To<constrainedOut> : Out<constrainedOut>, opts> : distillIo<i, o, opts>;
165
- type distillIo<i, o extends Out, opts extends distill.Options> = opts["endpoint"] extends "in" ? _distill<i, opts> : opts["endpoint"] extends "out.introspectable" ? o extends To<infer validatedOut> ? _distill<validatedOut, opts> : unknown : opts["endpoint"] extends "out" ? _distill<o[1], opts> : _distill<o[1], opts> extends infer r ? o extends To ? (In: i) => To<r> : (In: i) => Out<r> : never;
166
- type inferredOptionalOrDefaultKeyOf<o> = inferredDefaultKeyOf<o> | inferredOptionalKeyOf<o>;
167
- type inferredDefaultKeyOf<o> = keyof o extends infer k ? k extends keyof o ? [
168
- o[k]
169
- ] extends [anyOrNever] ? never : o[k] extends InferredDefault ? k : never : never : never;
170
- type inferredOptionalKeyOf<o> = keyof o extends infer k ? k extends keyof o ? [
171
- o[k]
172
- ] extends [anyOrNever] ? never : o[k] extends InferredOptional ? k : never : never : never;
173
- type distillArray<t extends array, opts extends distill.Options> = _distillArray<[...t], opts, []> extends infer result ? distillNonArraykeys<t, t extends unknown[] ? result : Readonly<t>, opts> : never;
174
- type distillNonArraykeys<originalArray extends array, distilledArray, opts extends distill.Options> = keyof originalArray extends keyof distilledArray | constrained ? distilledArray : distilledArray & _distill<{
175
- [k in keyof originalArray as k extends (keyof distilledArray | (opts["branded"] extends true ? never : constrained)) ? never : k]: originalArray[k];
176
- }, opts>;
177
- type _distillArray<t extends array, opts extends distill.Options, prefix extends array> = t extends readonly [infer head, ...infer tail] ? _distillArray<tail, opts, [...prefix, _distill<head, opts>]> : [...prefix, ...distillPostfix<t, opts>];
178
- type distillPostfix<t extends array, opts extends distill.Options, postfix extends array = []> = t extends readonly [...infer init, infer last] ? distillPostfix<init, opts, [_distill<last, opts>, ...postfix]> : [...{
179
- [i in keyof t]: _distill<t[i], opts>;
180
- }, ...postfix];
181
- type BuiltinTerminalObjectKind = Exclude<keyof arkPrototypes.instances, "Array" | "Function">;
182
- /** Objects we don't want to expand during inference like Date or Promise */
183
- type TerminallyInferredObject = arkPrototypes.instanceOf<BuiltinTerminalObjectKind> | ArkEnv.prototypes;
184
- export type inferPredicate<t, predicate> = predicate extends (data: any, ...args: any[]) => data is infer narrowed ? t extends constrain<unknown, infer constraints> ? applyConstraintSchema<constrain<narrowed, constraints>, "predicate", any> : applyConstraintSchema<narrowed, "predicate", any> : applyConstraintSchema<t, "predicate", any>;
185
- export type constrainWithPredicate<t> = t extends constrain<unknown, infer constraints> ? applyConstraintSchema<constrain<t, constraints>, "predicate", any> : applyConstraintSchema<t, "predicate", any>;
186
- export type inferPipes<t, pipes extends Morph[]> = pipes extends [infer head extends Morph, ...infer tail extends Morph[]] ? inferPipes<pipes[0] extends type.cast<infer tPipe> ? inferPipe<t, tPipe> : inferMorphOut<head> extends infer out ? (In: distill.brandable.In<t>) => Out<out> : never, tail> : t;
187
- export type inferMorphOut<morph extends Morph> = Exclude<ReturnType<morph>, ArkError | ArkErrors>;
188
- export type Out<o = any> = ["=>", o, boolean];
189
- export type To<o = any> = ["=>", o, true];
190
- export type InferredMorph<i = any, o extends Out = Out> = (In: i) => o;
191
- export type Optional = {
192
- optional?: {};
193
- };
194
- export type InferredOptional<t = unknown> = constrain<t, Optional>;
195
- export type Default<v = any> = ["=", v];
196
- export type InferredDefault<t = any, v = any> = (In?: t) => Default<v>;
197
- export type termOrType<t> = t | Type<t, any>;
198
- export type inferIntersection<l, r> = _inferIntersection<l, r, false>;
199
- export type inferPipe<l, r> = _inferIntersection<l, r, true>;
200
- type _inferIntersection<l, r, piped extends boolean> = [
201
- l & r
202
- ] extends [infer t extends anyOrNever] ? t : l extends InferredMorph<infer lIn, infer lOut> ? r extends InferredMorph<any, infer rOut> ? piped extends true ? (In: lIn) => rOut : never : piped extends true ? (In: lIn) => To<r> : (In: _inferIntersection<lIn, r, false>) => lOut : r extends InferredMorph<infer rIn, infer rOut> ? (In: _inferIntersection<rIn, l, false>) => rOut : parseConstraints<l> extends ([
203
- infer lBase,
204
- infer lConstraints extends Constraints
205
- ]) ? parseConstraints<r> extends ([
206
- infer rBase,
207
- infer rConstraints extends Constraints
208
- ]) ? constrain<_inferIntersection<lBase, rBase, piped>, lConstraints & rConstraints> : constrain<_inferIntersection<lBase, r, piped>, lConstraints> : parseConstraints<r> extends ([
209
- infer rBase,
210
- infer rConstraints extends Constraints
211
- ]) ? constrain<_inferIntersection<l, rBase, piped>, rConstraints> : [l, r] extends [object, object] ? intersectObjects<l, r, piped> extends infer result ? result : never : l & r;
212
- interface MorphableIntersection<piped extends boolean> extends Hkt<[unknown, unknown]> {
213
- body: _inferIntersection<this[0], this[1], piped>;
214
- }
215
- type intersectObjects<l, r, piped extends boolean> = l extends array ? r extends array ? intersectArrays<l, r, MorphableIntersection<piped>> : // for an intersection with exactly one array operand like { name: string } & string[],
216
- l & r : r extends array ? l & r : show<{
217
- [k in keyof l]: k extends keyof r ? _inferIntersection<l[k], r[k], piped> : l[k];
218
- } & {
219
- [k in keyof r]: k extends keyof l ? _inferIntersection<l[k], r[k], piped> : r[k];
220
- }>;
@@ -1,2 +0,0 @@
1
- import { noSuggest } from "@ark/util";
2
- export const constrained = noSuggest("arkConstrained");
@@ -1,9 +0,0 @@
1
- import type { AtLeast, AtMost, DivisibleBy, number } from "./number.ts";
2
- /**
3
- * As per the ECMA-262 specification:
4
- * A time value supports a slightly smaller range of -8,640,000,000,000,000 to 8,640,000,000,000,000 milliseconds.
5
- *
6
- * @see https://262.ecma-international.org/15.0/index.html#sec-time-values-and-time-range
7
- */
8
- export declare const epoch: import("@ark/schema").BaseRoot<import("@ark/schema").InternalRootDeclaration>;
9
- export type epoch = number.is<DivisibleBy<1> & AtMost<8640000000000000> & AtLeast<-8640000000000000>>;
@@ -1,3 +0,0 @@
1
- import type { number } from "./number.ts";
2
- export declare const integer: import("@ark/schema").BaseRoot<import("@ark/schema").InternalRootDeclaration>;
3
- export type integer = number.divisibleBy<1>;
@@ -1,5 +0,0 @@
1
- import { rootSchema } from "@ark/schema";
2
- export const integer = rootSchema({
3
- domain: "number",
4
- divisor: 1
5
- });