arktype 1.1.0-dev-1 → 2.0.0-dev.0

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 (213) hide show
  1. package/__tests__/array.test.ts +272 -0
  2. package/__tests__/astUtils.test.ts +17 -0
  3. package/__tests__/badDefinitionType.test.ts +51 -0
  4. package/__tests__/basis.test.ts +46 -0
  5. package/__tests__/bounds.test.ts +388 -0
  6. package/__tests__/cast.test.ts +32 -0
  7. package/__tests__/completions.test.ts +46 -0
  8. package/__tests__/config.test.ts +168 -0
  9. package/__tests__/cyclic.test.ts +144 -0
  10. package/__tests__/dateLiteral.test.ts +32 -0
  11. package/__tests__/declared.test.ts +123 -0
  12. package/__tests__/discrimination.test.ts +74 -0
  13. package/__tests__/divisor.test.ts +90 -0
  14. package/__tests__/enclosed.test.ts +93 -0
  15. package/__tests__/examples.test.ts +56 -0
  16. package/__tests__/expressions.test.ts +138 -0
  17. package/__tests__/generateBenchData.ts +89 -0
  18. package/__tests__/generated/cyclic.ts +3058 -0
  19. package/__tests__/generic.test.ts +294 -0
  20. package/__tests__/group.test.ts +72 -0
  21. package/__tests__/hkt.test.ts +22 -0
  22. package/__tests__/imports.test.ts +113 -0
  23. package/__tests__/instanceof.test.ts +102 -0
  24. package/__tests__/intersection.test.ts +104 -0
  25. package/__tests__/jsdoc.test.ts +64 -0
  26. package/__tests__/keyTraversal.test.ts +73 -0
  27. package/__tests__/keyof.test.ts +134 -0
  28. package/__tests__/keywords.test.ts +188 -0
  29. package/__tests__/literal.test.ts +51 -0
  30. package/__tests__/match.test.ts +34 -0
  31. package/__tests__/methods.bench.ts +22 -0
  32. package/__tests__/morph.test.ts +409 -0
  33. package/__tests__/narrow.test.ts +102 -0
  34. package/__tests__/nodeDefinitions.test.ts +190 -0
  35. package/__tests__/object.bench.ts +28 -0
  36. package/__tests__/objectLiteral.test.ts +300 -0
  37. package/__tests__/operand.bench.ts +45 -0
  38. package/__tests__/operator.bench.ts +130 -0
  39. package/__tests__/regex.test.ts +58 -0
  40. package/__tests__/scope.bench.ts +39 -0
  41. package/__tests__/scope.test.ts +140 -0
  42. package/__tests__/string.test.ts +48 -0
  43. package/__tests__/submodule.test.ts +99 -0
  44. package/__tests__/this.test.ts +57 -0
  45. package/__tests__/thunk.test.ts +80 -0
  46. package/__tests__/traverse.test.ts +119 -0
  47. package/__tests__/tsGenerics.test.ts +12 -0
  48. package/__tests__/typeMethods.test.ts +69 -0
  49. package/__tests__/typeReference.test.ts +39 -0
  50. package/__tests__/unenclosed.test.ts +120 -0
  51. package/__tests__/union.test.ts +147 -0
  52. package/ark.ts +91 -0
  53. package/main.ts +18 -0
  54. package/match.ts +116 -0
  55. package/out/ark.d.ts +52 -0
  56. package/out/ark.d.ts.map +1 -0
  57. package/out/ark.js +19 -0
  58. package/out/ark.js.map +1 -0
  59. package/out/arkConfig.d.ts +2 -0
  60. package/out/arkConfig.d.ts.map +1 -0
  61. package/out/arkConfig.js +10 -0
  62. package/out/arkConfig.js.map +1 -0
  63. package/out/main.d.ts +7 -0
  64. package/out/main.d.ts.map +1 -0
  65. package/out/main.js +4 -0
  66. package/out/main.js.map +1 -0
  67. package/out/match.d.ts +48 -0
  68. package/out/match.d.ts.map +1 -0
  69. package/out/match.js +18 -0
  70. package/out/match.js.map +1 -0
  71. package/out/parser/definition.d.ts +32 -0
  72. package/out/parser/definition.d.ts.map +1 -0
  73. package/out/parser/definition.js +32 -0
  74. package/out/parser/definition.js.map +1 -0
  75. package/out/parser/generic.d.ts +18 -0
  76. package/out/parser/generic.d.ts.map +1 -0
  77. package/out/parser/generic.js +19 -0
  78. package/out/parser/generic.js.map +1 -0
  79. package/out/parser/objectLiteral.d.ts +33 -0
  80. package/out/parser/objectLiteral.d.ts.map +1 -0
  81. package/out/parser/objectLiteral.js +66 -0
  82. package/out/parser/objectLiteral.js.map +1 -0
  83. package/out/parser/semantic/bounds.d.ts +13 -0
  84. package/out/parser/semantic/bounds.d.ts.map +1 -0
  85. package/out/parser/semantic/bounds.js +2 -0
  86. package/out/parser/semantic/bounds.js.map +1 -0
  87. package/out/parser/semantic/divisor.d.ts +9 -0
  88. package/out/parser/semantic/divisor.d.ts.map +1 -0
  89. package/out/parser/semantic/divisor.js +2 -0
  90. package/out/parser/semantic/divisor.js.map +1 -0
  91. package/out/parser/semantic/intersections.d.ts +14 -0
  92. package/out/parser/semantic/intersections.d.ts.map +1 -0
  93. package/out/parser/semantic/intersections.js +2 -0
  94. package/out/parser/semantic/intersections.js.map +1 -0
  95. package/out/parser/semantic/semantic.d.ts +33 -0
  96. package/out/parser/semantic/semantic.d.ts.map +1 -0
  97. package/out/parser/semantic/semantic.js +2 -0
  98. package/out/parser/semantic/semantic.js.map +1 -0
  99. package/out/parser/semantic/utils.d.ts +8 -0
  100. package/out/parser/semantic/utils.d.ts.map +1 -0
  101. package/out/parser/semantic/utils.js +2 -0
  102. package/out/parser/semantic/utils.js.map +1 -0
  103. package/out/parser/semantic/validate.d.ts +24 -0
  104. package/out/parser/semantic/validate.d.ts.map +1 -0
  105. package/out/parser/semantic/validate.js +2 -0
  106. package/out/parser/semantic/validate.js.map +1 -0
  107. package/out/parser/shared.d.ts +54 -0
  108. package/out/parser/shared.d.ts.map +1 -0
  109. package/out/parser/shared.js +47 -0
  110. package/out/parser/shared.js.map +1 -0
  111. package/out/parser/string/reduce/dynamic.d.ts +42 -0
  112. package/out/parser/string/reduce/dynamic.d.ts.map +1 -0
  113. package/out/parser/string/reduce/dynamic.js +133 -0
  114. package/out/parser/string/reduce/dynamic.js.map +1 -0
  115. package/out/parser/string/reduce/shared.d.ts +56 -0
  116. package/out/parser/string/reduce/shared.d.ts.map +1 -0
  117. package/out/parser/string/reduce/shared.js +26 -0
  118. package/out/parser/string/reduce/shared.js.map +1 -0
  119. package/out/parser/string/reduce/static.d.ts +176 -0
  120. package/out/parser/string/reduce/static.d.ts.map +1 -0
  121. package/out/parser/string/reduce/static.js +2 -0
  122. package/out/parser/string/reduce/static.js.map +1 -0
  123. package/out/parser/string/shift/operand/date.d.ts +11 -0
  124. package/out/parser/string/shift/operand/date.d.ts.map +1 -0
  125. package/out/parser/string/shift/operand/date.js +26 -0
  126. package/out/parser/string/shift/operand/date.js.map +1 -0
  127. package/out/parser/string/shift/operand/enclosed.d.ts +49 -0
  128. package/out/parser/string/shift/operand/enclosed.d.ts.map +1 -0
  129. package/out/parser/string/shift/operand/enclosed.js +50 -0
  130. package/out/parser/string/shift/operand/enclosed.js.map +1 -0
  131. package/out/parser/string/shift/operand/genericArgs.d.ts +29 -0
  132. package/out/parser/string/shift/operand/genericArgs.d.ts.map +1 -0
  133. package/out/parser/string/shift/operand/genericArgs.js +25 -0
  134. package/out/parser/string/shift/operand/genericArgs.js.map +1 -0
  135. package/out/parser/string/shift/operand/operand.d.ts +9 -0
  136. package/out/parser/string/shift/operand/operand.d.ts.map +1 -0
  137. package/out/parser/string/shift/operand/operand.js +17 -0
  138. package/out/parser/string/shift/operand/operand.js.map +1 -0
  139. package/out/parser/string/shift/operand/unenclosed.d.ts +34 -0
  140. package/out/parser/string/shift/operand/unenclosed.d.ts.map +1 -0
  141. package/out/parser/string/shift/operand/unenclosed.js +68 -0
  142. package/out/parser/string/shift/operand/unenclosed.js.map +1 -0
  143. package/out/parser/string/shift/operator/bounds.d.ts +33 -0
  144. package/out/parser/string/shift/operator/bounds.d.ts.map +1 -0
  145. package/out/parser/string/shift/operator/bounds.js +106 -0
  146. package/out/parser/string/shift/operator/bounds.js.map +1 -0
  147. package/out/parser/string/shift/operator/divisor.d.ts +9 -0
  148. package/out/parser/string/shift/operator/divisor.d.ts.map +1 -0
  149. package/out/parser/string/shift/operator/divisor.js +13 -0
  150. package/out/parser/string/shift/operator/divisor.js.map +1 -0
  151. package/out/parser/string/shift/operator/operator.d.ts +13 -0
  152. package/out/parser/string/shift/operator/operator.d.ts.map +1 -0
  153. package/out/parser/string/shift/operator/operator.js +29 -0
  154. package/out/parser/string/shift/operator/operator.js.map +1 -0
  155. package/out/parser/string/shift/scanner.d.ts +71 -0
  156. package/out/parser/string/shift/scanner.d.ts.map +1 -0
  157. package/out/parser/string/shift/scanner.js +99 -0
  158. package/out/parser/string/shift/scanner.js.map +1 -0
  159. package/out/parser/string/string.d.ts +24 -0
  160. package/out/parser/string/string.d.ts.map +1 -0
  161. package/out/parser/string/string.js +23 -0
  162. package/out/parser/string/string.js.map +1 -0
  163. package/out/parser/tuple.d.ts +71 -0
  164. package/out/parser/tuple.d.ts.map +1 -0
  165. package/out/parser/tuple.js +137 -0
  166. package/out/parser/tuple.js.map +1 -0
  167. package/out/scope.d.ts +159 -0
  168. package/out/scope.d.ts.map +1 -0
  169. package/out/scope.js +253 -0
  170. package/out/scope.js.map +1 -0
  171. package/out/test.d.ts +2 -0
  172. package/out/test.d.ts.map +1 -0
  173. package/out/test.js +7 -0
  174. package/out/test.js.map +1 -0
  175. package/out/tsconfig.build.tsbuildinfo +1 -0
  176. package/out/type.d.ts +77 -0
  177. package/out/type.d.ts.map +1 -0
  178. package/out/type.js +134 -0
  179. package/out/type.js.map +1 -0
  180. package/out/util.d.ts +19 -0
  181. package/out/util.d.ts.map +1 -0
  182. package/out/util.js +7 -0
  183. package/out/util.js.map +1 -0
  184. package/package.json +13 -10
  185. package/parser/definition.ts +159 -0
  186. package/parser/generic.ts +68 -0
  187. package/parser/objectLiteral.ts +197 -0
  188. package/parser/semantic/bounds.ts +61 -0
  189. package/parser/semantic/divisor.ts +13 -0
  190. package/parser/semantic/intersections.ts +46 -0
  191. package/parser/semantic/semantic.ts +144 -0
  192. package/parser/semantic/utils.ts +26 -0
  193. package/parser/semantic/validate.ts +109 -0
  194. package/parser/shared.ts +152 -0
  195. package/parser/string/reduce/dynamic.ts +196 -0
  196. package/parser/string/reduce/shared.ts +101 -0
  197. package/parser/string/reduce/static.ts +298 -0
  198. package/parser/string/shift/operand/date.ts +54 -0
  199. package/parser/string/shift/operand/enclosed.ts +118 -0
  200. package/parser/string/shift/operand/genericArgs.ts +127 -0
  201. package/parser/string/shift/operand/operand.ts +48 -0
  202. package/parser/string/shift/operand/unenclosed.ts +268 -0
  203. package/parser/string/shift/operator/bounds.ts +264 -0
  204. package/parser/string/shift/operator/divisor.ts +36 -0
  205. package/parser/string/shift/operator/operator.ts +82 -0
  206. package/parser/string/shift/scanner.ts +209 -0
  207. package/parser/string/string.ts +90 -0
  208. package/parser/tuple.ts +474 -0
  209. package/scope.ts +574 -0
  210. package/type.ts +347 -0
  211. package/util.ts +36 -0
  212. package/dist/main.d.ts +0 -1018
  213. package/dist/main.js +0 -1450
@@ -0,0 +1,159 @@
1
+ import { isNode, schema, type TypeNode } from "@arktype/schema"
2
+ import {
3
+ isThunk,
4
+ objectKindOf,
5
+ printable,
6
+ throwParseError,
7
+ type defined,
8
+ type Dict,
9
+ type equals,
10
+ type ErrorMessage,
11
+ type evaluate,
12
+ type isAny,
13
+ type isUnknown,
14
+ type List,
15
+ type objectKindOrDomainOf,
16
+ type optionalKeyOf,
17
+ type Primitive,
18
+ type requiredKeyOf
19
+ } from "@arktype/util"
20
+ import type { type } from "../ark.js"
21
+ import type { ParseContext } from "../scope.js"
22
+ import { Type } from "../type.js"
23
+ import {
24
+ parseObjectLiteral,
25
+ type inferObjectLiteral,
26
+ type validateObjectLiteral
27
+ } from "./objectLiteral.js"
28
+ import type { validateString } from "./semantic/validate.js"
29
+ import type { BaseCompletions, inferString } from "./string/string.js"
30
+ import {
31
+ parseTuple,
32
+ type inferTuple,
33
+ type TupleExpression,
34
+ type validateTuple
35
+ } from "./tuple.js"
36
+
37
+ export const parseObject = (def: object, ctx: ParseContext): TypeNode => {
38
+ const objectKind = objectKindOf(def)
39
+ switch (objectKind) {
40
+ case undefined:
41
+ if (def instanceof Type) {
42
+ return def.root
43
+ }
44
+ if (isNode(def) && def.isType()) {
45
+ return def
46
+ }
47
+ return parseObjectLiteral(def as Dict, ctx)
48
+ case "Array":
49
+ return parseTuple(def as List, ctx)
50
+ case "RegExp":
51
+ return schema({ basis: "string", pattern: def as RegExp })
52
+ case "Function":
53
+ const resolvedDef = isThunk(def) ? def() : def
54
+ if (resolvedDef instanceof Type) {
55
+ return resolvedDef.root
56
+ }
57
+ return throwParseError(writeBadDefinitionTypeMessage("Function"))
58
+ default:
59
+ return throwParseError(
60
+ writeBadDefinitionTypeMessage(objectKind ?? printable(def))
61
+ )
62
+ }
63
+ }
64
+
65
+ export type inferDefinition<def, $, args> = isAny<def> extends true
66
+ ? never
67
+ : def extends type.cast<infer t> | ThunkCast<infer t>
68
+ ? t
69
+ : def extends string
70
+ ? inferString<def, $, args>
71
+ : def extends readonly unknown[]
72
+ ? inferTuple<def, $, args>
73
+ : def extends RegExp
74
+ ? string
75
+ : def extends object
76
+ ? inferObjectLiteral<def, $, args>
77
+ : never
78
+
79
+ export type validateDefinition<def, $, args> = null extends undefined
80
+ ? ErrorMessage<`'strict' or 'strictNullChecks' must be set to true in your tsconfig's 'compilerOptions'`>
81
+ : [def] extends [Terminal]
82
+ ? unknown extends def
83
+ ? // if def is any, never is the only way we can make validation fail
84
+ // since any would be assignable to a standard error message
85
+ never
86
+ : def
87
+ : def extends string
88
+ ? validateString<def, $, args>
89
+ : def extends readonly unknown[]
90
+ ? validateTuple<def, $, args>
91
+ : def extends BadDefinitionType
92
+ ? writeBadDefinitionTypeMessage<objectKindOrDomainOf<def>>
93
+ : isUnknown<def> extends true
94
+ ? // this allows the initial list of autocompletions to be populated when a user writes "type()",
95
+ // before having specified a definition
96
+ BaseCompletions<$, args> | {}
97
+ : validateObjectLiteral<def, $, args>
98
+
99
+ export type validateDeclared<declared, def, $, args> =
100
+ def extends validateDefinition<def, $, args>
101
+ ? validateInference<def, declared, $, args>
102
+ : validateDefinition<def, $, args>
103
+
104
+ type validateInference<def, declared, $, args> = def extends
105
+ | RegExp
106
+ | type.cast<unknown>
107
+ | ThunkCast
108
+ | TupleExpression
109
+ ? validateShallowInference<def, declared, $, args>
110
+ : def extends readonly unknown[]
111
+ ? declared extends readonly unknown[]
112
+ ? {
113
+ [i in keyof declared]: i extends keyof def
114
+ ? validateInference<def[i], declared[i], $, args>
115
+ : unknown
116
+ }
117
+ : evaluate<declarationMismatch<def, declared, $, args>>
118
+ : def extends object
119
+ ? evaluate<
120
+ {
121
+ [k in requiredKeyOf<declared>]: k extends keyof def
122
+ ? validateInference<def[k], declared[k], $, args>
123
+ : unknown
124
+ } & {
125
+ [k in optionalKeyOf<declared> &
126
+ string as `${k}?`]: `${k}?` extends keyof def
127
+ ? validateInference<def[`${k}?`], defined<declared[k]>, $, args>
128
+ : unknown
129
+ }
130
+ >
131
+ : validateShallowInference<def, declared, $, args>
132
+
133
+ type validateShallowInference<def, declared, $, args> = equals<
134
+ inferDefinition<def, $, args>,
135
+ declared
136
+ > extends true
137
+ ? def
138
+ : evaluate<declarationMismatch<def, declared, $, args>>
139
+
140
+ type declarationMismatch<def, declared, $, args> = {
141
+ declared: declared
142
+ inferred: inferDefinition<def, $, args>
143
+ }
144
+
145
+ // functions are ignored in validation so that cyclic thunk definitions can be
146
+ // inferred in scopes
147
+ type Terminal = RegExp | type.cast<unknown> | ((...args: never[]) => unknown)
148
+
149
+ export type ThunkCast<t = unknown> = () => type.cast<t>
150
+
151
+ type BadDefinitionType = Exclude<Primitive, string>
152
+
153
+ export const writeBadDefinitionTypeMessage = <actual extends string>(
154
+ actual: actual
155
+ ): writeBadDefinitionTypeMessage<actual> =>
156
+ `Type definitions must be strings or objects (was ${actual})`
157
+
158
+ type writeBadDefinitionTypeMessage<actual extends string> =
159
+ `Type definitions must be strings or objects (was ${actual})`
@@ -0,0 +1,68 @@
1
+ import { throwParseError, type nominal } from "@arktype/util"
2
+ import { writeUnexpectedCharacterMessage } from "./string/shift/operator/operator.js"
3
+ import { Scanner } from "./string/shift/scanner.js"
4
+
5
+ export type GenericDeclaration<
6
+ name extends string = string,
7
+ params extends string = string
8
+ > = `${name}<${params}>`
9
+
10
+ // we put the error in a tuple so that parseGenericParams always returns a string[]
11
+ export type GenericParamsParseError<message extends string = string> = [
12
+ nominal<message, "InvalidGenericParameters">
13
+ ]
14
+
15
+ export const parseGenericParams = (def: string) =>
16
+ parseGenericParamsRecurse(new Scanner(def))
17
+
18
+ export type parseGenericParams<def extends string> = parseParamsRecurse<
19
+ def,
20
+ "",
21
+ []
22
+ > extends infer result extends string[]
23
+ ? "" extends result[number]
24
+ ? GenericParamsParseError<emptyGenericParameterMessage>
25
+ : result
26
+ : never
27
+
28
+ export const emptyGenericParameterMessage = `An empty string is not a valid generic parameter name`
29
+
30
+ export type emptyGenericParameterMessage = typeof emptyGenericParameterMessage
31
+
32
+ const parseGenericParamsRecurse = (scanner: Scanner): string[] => {
33
+ const param = scanner.shiftUntilNextTerminator()
34
+ if (param === "") {
35
+ throwParseError(emptyGenericParameterMessage)
36
+ }
37
+ scanner.shiftUntilNonWhitespace()
38
+ const nextNonWhitespace = scanner.shift()
39
+ return nextNonWhitespace === ""
40
+ ? [param]
41
+ : nextNonWhitespace === ","
42
+ ? [param, ...parseGenericParamsRecurse(scanner)]
43
+ : throwParseError(writeUnexpectedCharacterMessage(nextNonWhitespace, ","))
44
+ }
45
+
46
+ type parseParamsRecurse<
47
+ unscanned extends string,
48
+ param extends string,
49
+ result extends string[]
50
+ > = unscanned extends `${infer lookahead}${infer nextUnscanned}`
51
+ ? lookahead extends ","
52
+ ? parseParamsRecurse<nextUnscanned, "", [...result, param]>
53
+ : lookahead extends Scanner.WhiteSpaceToken
54
+ ? param extends ""
55
+ ? // if the next char is whitespace and we aren't in the middle of a param, skip to the next one
56
+ parseParamsRecurse<Scanner.skipWhitespace<nextUnscanned>, "", result>
57
+ : Scanner.skipWhitespace<nextUnscanned> extends `${infer nextNonWhitespace}${infer rest}`
58
+ ? nextNonWhitespace extends ","
59
+ ? parseParamsRecurse<rest, "", [...result, param]>
60
+ : GenericParamsParseError<
61
+ writeUnexpectedCharacterMessage<nextNonWhitespace, ",">
62
+ >
63
+ : // params end with a single whitespace character, add the current token
64
+ [...result, param]
65
+ : parseParamsRecurse<nextUnscanned, `${param}${lookahead}`, result>
66
+ : param extends ""
67
+ ? result
68
+ : [...result, param]
@@ -0,0 +1,197 @@
1
+ import { keywords, schema, type Inner, type TypeNode } from "@arktype/schema"
2
+ import {
3
+ printable,
4
+ throwParseError,
5
+ type Dict,
6
+ type ErrorMessage,
7
+ type evaluate,
8
+ type merge
9
+ } from "@arktype/util"
10
+
11
+ import type { ParseContext } from "../scope.js"
12
+ import type { inferDefinition, validateDefinition } from "./definition.js"
13
+ import type { astToString } from "./semantic/utils.js"
14
+ import type { validateString } from "./semantic/validate.js"
15
+ import {
16
+ parseEntry,
17
+ type EntryParseResult,
18
+ type IndexedKey,
19
+ type OptionalValue,
20
+ type validateObjectValue
21
+ } from "./shared.js"
22
+
23
+ const stringAndSymbolicEntriesOf = (o: Record<string | symbol, unknown>) => [
24
+ ...Object.entries(o),
25
+ ...Object.getOwnPropertySymbols(o).map((k) => [k, o[k]] as const)
26
+ ]
27
+
28
+ export const parseObjectLiteral = (def: Dict, ctx: ParseContext): TypeNode => {
29
+ const required: Inner<"required">[] = []
30
+ const optional: Inner<"optional">[] = []
31
+
32
+ // We only allow a spread operator to be used as the first key in an object
33
+ // because to match JS behavior any keys before the spread are overwritten
34
+ // by the values in the target object, so there'd be no useful purpose in having it
35
+ // anywhere except for the beginning.
36
+ // Discussion in ArkType Discord:
37
+ // https://discord.com/channels/957797212103016458/1103023445035462678/1182814502471860334
38
+ let hasSeenFirstKey = false
39
+
40
+ const entries = stringAndSymbolicEntriesOf(def)
41
+ for (const entry of entries) {
42
+ const result = parseEntry(entry)
43
+
44
+ if (result.kind === "spread") {
45
+ if (hasSeenFirstKey) {
46
+ return throwParseError(
47
+ "Spread operator may only be used as the first key in an object"
48
+ )
49
+ }
50
+
51
+ const spreadNode = ctx.scope.parse(result.innerValue, ctx)
52
+
53
+ if (
54
+ spreadNode.kind !== "intersection" ||
55
+ !spreadNode.extends(keywords.object)
56
+ ) {
57
+ return throwParseError(
58
+ writeInvalidSpreadTypeMessage(printable(result.innerValue))
59
+ )
60
+ }
61
+
62
+ // For each key on spreadNode, add it to our object.
63
+ // We filter out keys from the spreadNode that will be defined later on this same object
64
+ // because the currently parsed definition will overwrite them.
65
+ const requiredEntriesFromSpread = (spreadNode.required ?? []).filter(
66
+ (e) => !entries.some(([k]) => k === e.key)
67
+ )
68
+
69
+ const optionalEntriesFromSpread = (spreadNode.optional ?? []).filter(
70
+ (e) => !entries.some(([k]) => k === e.key)
71
+ )
72
+
73
+ required.push(...requiredEntriesFromSpread)
74
+ optional.push(...optionalEntriesFromSpread)
75
+
76
+ continue
77
+ }
78
+
79
+ ctx.path.push(
80
+ `${
81
+ typeof result.innerKey === "symbol"
82
+ ? `[${printable(result.innerKey)}]`
83
+ : result.innerKey
84
+ }`
85
+ )
86
+ const valueNode = ctx.scope.parse(result.innerValue, ctx)
87
+
88
+ if (result.kind === "optional") {
89
+ optional.push({
90
+ key: result.innerKey,
91
+ value: valueNode
92
+ })
93
+ } else {
94
+ required.push({
95
+ key: result.innerKey,
96
+ value: valueNode
97
+ })
98
+ }
99
+ ctx.path.pop()
100
+
101
+ hasSeenFirstKey ||= true
102
+ }
103
+
104
+ return schema({
105
+ basis: "object",
106
+ required,
107
+ optional
108
+ })
109
+ }
110
+
111
+ /**
112
+ * Infers the contents of an object literal, ignoring a spread definition
113
+ * You probably want to use {@link inferObjectLiteral} instead.
114
+ */
115
+ type inferObjectLiteralInner<def extends object, $, args> = {
116
+ // since def is a const parameter, we remove the readonly modifier here
117
+ // support for builtin readonly tracked here:
118
+ // https://github.com/arktypeio/arktype/issues/808
119
+ -readonly [k in keyof def as nonOptionalKeyFrom<
120
+ k,
121
+ def[k],
122
+ $,
123
+ args
124
+ >]: inferDefinition<def[k], $, args>
125
+ } & {
126
+ -readonly [k in keyof def as optionalKeyFrom<k, def[k]>]?: inferDefinition<
127
+ def[k] extends OptionalValue<infer inner> ? inner : def[k],
128
+ $,
129
+ args
130
+ >
131
+ }
132
+
133
+ export type inferObjectLiteral<def extends object, $, args> = evaluate<
134
+ "..." extends keyof def
135
+ ? merge<
136
+ inferDefinition<def["..."], $, args>,
137
+ inferObjectLiteralInner<def, $, args>
138
+ >
139
+ : inferObjectLiteralInner<def, $, args>
140
+ >
141
+
142
+ export type validateObjectLiteral<def, $, args> = {
143
+ [k in keyof def]: k extends IndexedKey<infer indexDef>
144
+ ? validateString<indexDef, $, args> extends ErrorMessage<infer message>
145
+ ? // add a nominal type here to avoid allowing the error message as input
146
+ indexParseError<message>
147
+ : inferDefinition<indexDef, $, args> extends PropertyKey
148
+ ? // if the indexDef is syntactically and semantically valid,
149
+ // move on to the validating the value definition
150
+ validateDefinition<def[k], $, args>
151
+ : indexParseError<writeInvalidPropertyKeyMessage<indexDef>>
152
+ : k extends "..."
153
+ ? inferDefinition<def[k], $, args> extends object
154
+ ? validateDefinition<def[k], $, args>
155
+ : indexParseError<writeInvalidSpreadTypeMessage<astToString<def[k]>>>
156
+ : validateObjectValue<def[k], $, args>
157
+ }
158
+
159
+ type nonOptionalKeyFrom<k extends PropertyKey, valueDef, $, args> = parseEntry<
160
+ k,
161
+ valueDef
162
+ > extends infer result extends EntryParseResult
163
+ ? result["kind"] extends "required"
164
+ ? result["innerKey"]
165
+ : result["kind"] extends "indexed"
166
+ ? inferDefinition<result["innerKey"], $, args> & PropertyKey
167
+ : never
168
+ : never
169
+
170
+ type optionalKeyFrom<k extends PropertyKey, valueDef> = parseEntry<
171
+ k,
172
+ valueDef
173
+ > extends infer result extends EntryParseResult<"optional">
174
+ ? result["innerKey"]
175
+ : never
176
+
177
+ declare const indexParseSymbol: unique symbol
178
+
179
+ export type indexParseError<message extends string = string> = {
180
+ [indexParseSymbol]: message
181
+ }
182
+
183
+ export const writeInvalidPropertyKeyMessage = <indexDef extends string>(
184
+ indexDef: indexDef
185
+ ): writeInvalidPropertyKeyMessage<indexDef> =>
186
+ `Indexed key definition '${indexDef}' must be a string, number or symbol`
187
+
188
+ type writeInvalidPropertyKeyMessage<indexDef extends string> =
189
+ `Indexed key definition '${indexDef}' must be a string, number or symbol`
190
+
191
+ export const writeInvalidSpreadTypeMessage = <def extends string>(
192
+ def: def
193
+ ): writeInvalidSpreadTypeMessage<def> =>
194
+ `Spread operand must resolve to an object literal type (was ${def})`
195
+
196
+ type writeInvalidSpreadTypeMessage<def extends string> =
197
+ `Spread operand must resolve to an object literal type (was ${def})`
@@ -0,0 +1,61 @@
1
+ import type { NumericallyBoundable } from "@arktype/schema"
2
+ import type { ErrorMessage } from "@arktype/util"
3
+ import type {
4
+ Comparator,
5
+ InvertedComparators,
6
+ LimitLiteral
7
+ } from "../string/reduce/shared.js"
8
+ import type {
9
+ BoundExpressionKind,
10
+ writeInvalidLimitMessage,
11
+ writeUnboundableMessage
12
+ } from "../string/shift/operator/bounds.js"
13
+ import type { inferAstBase } from "./semantic.js"
14
+ import type { astToString } from "./utils.js"
15
+ import type { validateAst } from "./validate.js"
16
+
17
+ export type validateRange<
18
+ l,
19
+ comparator extends Comparator,
20
+ r,
21
+ $,
22
+ args
23
+ > = l extends LimitLiteral
24
+ ? validateBound<r, InvertedComparators[comparator], l, "left", $, args>
25
+ : l extends [infer leftAst, Comparator, unknown]
26
+ ? ErrorMessage<writeDoubleRightBoundMessage<astToString<leftAst>>>
27
+ : validateBound<l, comparator, r & LimitLiteral, "right", $, args>
28
+
29
+ export type validateBound<
30
+ boundedAst,
31
+ comparator extends Comparator,
32
+ limit extends LimitLiteral,
33
+ boundKind extends BoundExpressionKind,
34
+ $,
35
+ args
36
+ > = inferAstBase<boundedAst, $, args> extends infer bounded
37
+ ? [bounded] extends [NumericallyBoundable]
38
+ ? limit extends number
39
+ ? validateAst<boundedAst, $, args>
40
+ : ErrorMessage<writeInvalidLimitMessage<comparator, limit, boundKind>>
41
+ : bounded extends Date
42
+ ? // allow numeric or date literal as a Date limit
43
+ validateAst<boundedAst, $, args>
44
+ : ErrorMessage<
45
+ writeUnboundableMessage<
46
+ astToString<
47
+ boundKind extends "left"
48
+ ? boundedAst[0 & keyof boundedAst]
49
+ : boundedAst
50
+ >
51
+ >
52
+ >
53
+ : never
54
+
55
+ export const writeDoubleRightBoundMessage = <root extends string>(
56
+ root: root
57
+ ): writeDoubleRightBoundMessage<root> =>
58
+ `Expression ${root} must have at most one right bound`
59
+
60
+ type writeDoubleRightBoundMessage<root extends string> =
61
+ `Expression ${root} must have at most one right bound`
@@ -0,0 +1,13 @@
1
+ import type { writeIndivisibleMessage } from "@arktype/schema"
2
+ import type { ErrorMessage } from "@arktype/util"
3
+ import type { inferAstBase } from "./semantic.js"
4
+ import type { astToString } from "./utils.js"
5
+ import type { validateAst } from "./validate.js"
6
+
7
+ export type validateDivisor<l, $, args> = isDivisible<
8
+ inferAstBase<l, $, args>
9
+ > extends true
10
+ ? validateAst<l, $, args>
11
+ : ErrorMessage<writeIndivisibleMessage<astToString<l>>>
12
+
13
+ type isDivisible<data> = [data] extends [number] ? true : false
@@ -0,0 +1,46 @@
1
+ import type { MorphAst, Out } from "@arktype/schema"
2
+ import {
3
+ Hkt,
4
+ type List,
5
+ type conform,
6
+ type evaluate,
7
+ type intersectArrays,
8
+ type isAny
9
+ } from "@arktype/util"
10
+
11
+ export type inferIntersection<l, r> = [l] extends [never]
12
+ ? never
13
+ : [r] extends [never]
14
+ ? never
15
+ : [l & r] extends [never]
16
+ ? never
17
+ : isAny<l | r> extends true
18
+ ? any
19
+ : l extends MorphAst<infer lIn, infer lOut>
20
+ ? r extends MorphAst
21
+ ? never
22
+ : (In: evaluate<lIn & r>) => Out<lOut>
23
+ : r extends MorphAst<infer rIn, infer rOut>
24
+ ? (In: evaluate<rIn & l>) => Out<rOut>
25
+ : [l, r] extends [object, object]
26
+ ? intersectObjects<l, r> extends infer result
27
+ ? result
28
+ : never
29
+ : l & r
30
+
31
+ declare class MorphableIntersection extends Hkt.Kind {
32
+ f: (
33
+ In: conform<this[Hkt.key], [l: unknown, r: unknown]>
34
+ ) => inferIntersection<(typeof In)[0], (typeof In)[1]>
35
+ }
36
+
37
+ type intersectObjects<l, r> = [l, r] extends [
38
+ infer lList extends List,
39
+ infer rList extends List
40
+ ]
41
+ ? intersectArrays<lList, rList, MorphableIntersection>
42
+ : evaluate<
43
+ {
44
+ [k in keyof l]: k extends keyof r ? inferIntersection<l[k], r[k]> : l[k]
45
+ } & Omit<r, keyof l>
46
+ >
@@ -0,0 +1,144 @@
1
+ import type {
2
+ DateLiteral,
3
+ Refinements,
4
+ RegexLiteral,
5
+ distill,
6
+ is
7
+ } from "@arktype/schema"
8
+ import type {
9
+ BigintLiteral,
10
+ List,
11
+ NumberLiteral,
12
+ evaluate,
13
+ extend
14
+ } from "@arktype/util"
15
+ import type {
16
+ UnparsedScope,
17
+ resolve,
18
+ tryInferSubmoduleReference
19
+ } from "../../scope.js"
20
+ import type { GenericProps } from "../../type.js"
21
+ import type { inferDefinition } from "../definition.js"
22
+ import type {
23
+ Comparator,
24
+ InvertedComparators,
25
+ LimitLiteral
26
+ } from "../string/reduce/shared.js"
27
+ import type { StringLiteral } from "../string/shift/operand/enclosed.js"
28
+ import type { inferIntersection } from "./intersections.js"
29
+
30
+ export type inferAstRoot<ast, $, args> = inferAst<ast, $, args, {}>
31
+
32
+ export type inferAstBase<ast, $, args> = distill<inferAstRoot<ast, $, args>>
33
+
34
+ export type inferAst<
35
+ ast,
36
+ $,
37
+ args,
38
+ refinements extends Refinements
39
+ > = ast extends List
40
+ ? inferExpression<ast, $, args, refinements>
41
+ : inferTerminal<ast, $, args, refinements>
42
+
43
+ export type GenericInstantiationAst<
44
+ g extends GenericProps = GenericProps,
45
+ argAsts extends unknown[] = unknown[]
46
+ > = [g, "<>", argAsts]
47
+
48
+ export type inferExpression<
49
+ ast extends List,
50
+ $,
51
+ args,
52
+ refinements extends Refinements
53
+ > = ast extends GenericInstantiationAst
54
+ ? inferDefinition<
55
+ ast[0]["definition"],
56
+ ast[0]["$"] extends UnparsedScope
57
+ ? // If the generic was defined in the current scope, its definition can be
58
+ // resolved using the same scope as that of the input args.
59
+ $
60
+ : // Otherwise, use the scope that was explicitly associated with it.
61
+ ast[0]["$"],
62
+ {
63
+ // Using keyof g["parameters"] & number here results in the element types
64
+ // being mixed- another reason TS should not have separate `${number}` and number keys!
65
+ [i in keyof ast[0]["parameters"] &
66
+ `${number}` as ast[0]["parameters"][i]]: inferAst<
67
+ ast[2][i & keyof ast[2]],
68
+ $,
69
+ args,
70
+ refinements
71
+ >
72
+ }
73
+ >
74
+ : ast[1] extends "[]"
75
+ ? inferAst<ast[0], $, args, refinements>[]
76
+ : ast[1] extends "|"
77
+ ?
78
+ | inferAst<ast[0], $, args, refinements>
79
+ | inferAst<ast[2], $, args, refinements>
80
+ : ast[1] extends "&"
81
+ ? inferIntersection<
82
+ inferAst<ast[0], $, args, refinements>,
83
+ inferAst<ast[2], $, args, refinements>
84
+ >
85
+ : ast[1] extends Comparator
86
+ ? ast[0] extends LimitLiteral
87
+ ? inferAst<
88
+ ast[2],
89
+ $,
90
+ args,
91
+ refinements & { [_ in InvertedComparators[ast[1]]]: ast[0] }
92
+ >
93
+ : inferAst<ast[0], $, args, refinements & { [_ in ast[1]]: ast[2] }>
94
+ : ast[1] extends "%"
95
+ ? inferAst<ast[0], $, args, refinements & { [k in `%${ast[2] & string}`]: 0 }>
96
+ : ast[0] extends "keyof"
97
+ ? keyof inferAst<ast[1], $, args, refinements>
98
+ : never
99
+
100
+ export type PrefixOperator = "keyof" | "instanceof" | "===" | "node"
101
+
102
+ export type PrefixExpression<
103
+ operator extends PrefixOperator = PrefixOperator,
104
+ operand = unknown
105
+ > = [operator, operand]
106
+
107
+ export type PostfixOperator = "[]"
108
+
109
+ export type PostfixExpression<
110
+ operator extends PostfixOperator = PostfixOperator,
111
+ operand = unknown
112
+ > = readonly [operand, operator]
113
+
114
+ export type InfixOperator = "|" | "&" | Comparator | "%" | ":" | "=>" | "@"
115
+
116
+ export type InfixExpression<
117
+ operator extends InfixOperator = InfixOperator,
118
+ l = unknown,
119
+ r = unknown
120
+ > = [l, operator, r]
121
+
122
+ export type inferTerminal<
123
+ token,
124
+ $,
125
+ args,
126
+ refinements extends Refinements
127
+ > = token extends keyof args | keyof $
128
+ ? {} extends refinements
129
+ ? resolve<token, $, args>
130
+ : is<resolve<token, $, args>, evaluate<refinements>>
131
+ : token extends StringLiteral<infer text>
132
+ ? text
133
+ : token extends RegexLiteral
134
+ ? is<string, extend<refinements, { [_ in token]: true }>>
135
+ : token extends DateLiteral
136
+ ? is<Date, extend<refinements, { [_ in token]: true }>>
137
+ : token extends NumberLiteral<infer value>
138
+ ? value
139
+ : token extends BigintLiteral<infer value>
140
+ ? value
141
+ : // TODO: refinements
142
+ // doing this last allows us to infer never if it isn't valid rather than check
143
+ // if it's a valid submodule reference ahead of time
144
+ tryInferSubmoduleReference<$, token>