arktype 1.1.0-dev-2 → 2.0.0-beta.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 (225) hide show
  1. package/LICENSE +7 -0
  2. package/out/ark.d.ts +19 -0
  3. package/out/ark.js +9 -0
  4. package/out/config.d.ts +1 -0
  5. package/out/config.js +2 -0
  6. package/out/generic.d.ts +65 -0
  7. package/out/generic.js +39 -0
  8. package/out/index.d.ts +6 -0
  9. package/out/index.js +5 -0
  10. package/out/match.d.ts +71 -0
  11. package/out/match.js +50 -0
  12. package/out/module.d.ts +14 -0
  13. package/out/module.js +2 -0
  14. package/{dist → out}/parser/definition.d.ts +16 -16
  15. package/{dist → out}/parser/definition.js +12 -12
  16. package/out/parser/objectLiteral.d.ts +79 -0
  17. package/out/parser/objectLiteral.js +100 -0
  18. package/out/parser/semantic/bounds.d.ts +15 -0
  19. package/{dist → out}/parser/semantic/bounds.js +0 -1
  20. package/out/parser/semantic/default.d.ts +8 -0
  21. package/out/parser/semantic/default.js +1 -0
  22. package/out/parser/semantic/divisor.d.ts +7 -0
  23. package/out/parser/semantic/divisor.js +1 -0
  24. package/out/parser/semantic/infer.d.ts +27 -0
  25. package/out/parser/semantic/infer.js +1 -0
  26. package/out/parser/semantic/utils.d.ts +4 -0
  27. package/out/parser/semantic/utils.js +1 -0
  28. package/out/parser/semantic/validate.d.ts +30 -0
  29. package/out/parser/semantic/validate.js +2 -0
  30. package/out/parser/string/reduce/dynamic.d.ts +43 -0
  31. package/{dist → out}/parser/string/reduce/dynamic.js +50 -33
  32. package/out/parser/string/reduce/shared.d.ts +42 -0
  33. package/{dist → out}/parser/string/reduce/shared.js +22 -2
  34. package/{dist → out}/parser/string/reduce/static.d.ts +29 -27
  35. package/out/parser/string/reduce/static.js +1 -0
  36. package/out/parser/string/shift/operand/date.d.ts +9 -0
  37. package/{dist → out}/parser/string/shift/operand/date.js +5 -8
  38. package/{dist → out}/parser/string/shift/operand/enclosed.d.ts +5 -16
  39. package/{dist → out}/parser/string/shift/operand/enclosed.js +15 -15
  40. package/out/parser/string/shift/operand/genericArgs.d.ts +28 -0
  41. package/out/parser/string/shift/operand/genericArgs.js +16 -0
  42. package/out/parser/string/shift/operand/operand.d.ts +9 -0
  43. package/out/parser/string/shift/operand/operand.js +12 -0
  44. package/out/parser/string/shift/operand/unenclosed.d.ts +30 -0
  45. package/out/parser/string/shift/operand/unenclosed.js +53 -0
  46. package/out/parser/string/shift/operator/bounds.d.ts +27 -0
  47. package/out/parser/string/shift/operator/bounds.js +94 -0
  48. package/out/parser/string/shift/operator/default.d.ts +24 -0
  49. package/out/parser/string/shift/operator/default.js +23 -0
  50. package/{dist → out}/parser/string/shift/operator/divisor.d.ts +2 -4
  51. package/{dist → out}/parser/string/shift/operator/divisor.js +2 -4
  52. package/{dist → out}/parser/string/shift/operator/operator.d.ts +4 -4
  53. package/out/parser/string/shift/operator/operator.js +22 -0
  54. package/{dist → out}/parser/string/shift/scanner.d.ts +13 -17
  55. package/{dist → out}/parser/string/shift/scanner.js +27 -24
  56. package/out/parser/string/string.d.ts +28 -0
  57. package/out/parser/string/string.js +24 -0
  58. package/out/parser/tuple.d.ts +130 -0
  59. package/out/parser/tuple.js +157 -0
  60. package/out/scope.d.ts +86 -0
  61. package/out/scope.js +132 -0
  62. package/out/type.d.ts +83 -0
  63. package/out/type.js +36 -0
  64. package/package.json +37 -41
  65. package/dist/main.d.ts +0 -11
  66. package/dist/main.d.ts.map +0 -1
  67. package/dist/main.js +0 -8
  68. package/dist/main.js.map +0 -1
  69. package/dist/match.d.ts +0 -46
  70. package/dist/match.d.ts.map +0 -1
  71. package/dist/match.js +0 -23
  72. package/dist/match.js.map +0 -1
  73. package/dist/parser/definition.d.ts.map +0 -1
  74. package/dist/parser/definition.js.map +0 -1
  75. package/dist/parser/generic.d.ts +0 -44
  76. package/dist/parser/generic.d.ts.map +0 -1
  77. package/dist/parser/generic.js +0 -46
  78. package/dist/parser/generic.js.map +0 -1
  79. package/dist/parser/objectLiteral.d.ts +0 -24
  80. package/dist/parser/objectLiteral.d.ts.map +0 -1
  81. package/dist/parser/objectLiteral.js +0 -38
  82. package/dist/parser/objectLiteral.js.map +0 -1
  83. package/dist/parser/semantic/bounds.d.ts +0 -13
  84. package/dist/parser/semantic/bounds.d.ts.map +0 -1
  85. package/dist/parser/semantic/bounds.js.map +0 -1
  86. package/dist/parser/semantic/divisor.d.ts +0 -9
  87. package/dist/parser/semantic/divisor.d.ts.map +0 -1
  88. package/dist/parser/semantic/divisor.js +0 -2
  89. package/dist/parser/semantic/divisor.js.map +0 -1
  90. package/dist/parser/semantic/intersections.d.ts +0 -15
  91. package/dist/parser/semantic/intersections.d.ts.map +0 -1
  92. package/dist/parser/semantic/intersections.js +0 -2
  93. package/dist/parser/semantic/intersections.js.map +0 -1
  94. package/dist/parser/semantic/semantic.d.ts +0 -22
  95. package/dist/parser/semantic/semantic.d.ts.map +0 -1
  96. package/dist/parser/semantic/semantic.js +0 -2
  97. package/dist/parser/semantic/semantic.js.map +0 -1
  98. package/dist/parser/semantic/utils.d.ts +0 -8
  99. package/dist/parser/semantic/utils.d.ts.map +0 -1
  100. package/dist/parser/semantic/utils.js +0 -2
  101. package/dist/parser/semantic/utils.js.map +0 -1
  102. package/dist/parser/semantic/validate.d.ts +0 -24
  103. package/dist/parser/semantic/validate.d.ts.map +0 -1
  104. package/dist/parser/semantic/validate.js +0 -2
  105. package/dist/parser/semantic/validate.js.map +0 -1
  106. package/dist/parser/shared.d.ts +0 -48
  107. package/dist/parser/shared.d.ts.map +0 -1
  108. package/dist/parser/shared.js +0 -41
  109. package/dist/parser/shared.js.map +0 -1
  110. package/dist/parser/string/reduce/dynamic.d.ts +0 -40
  111. package/dist/parser/string/reduce/dynamic.d.ts.map +0 -1
  112. package/dist/parser/string/reduce/dynamic.js.map +0 -1
  113. package/dist/parser/string/reduce/shared.d.ts +0 -29
  114. package/dist/parser/string/reduce/shared.d.ts.map +0 -1
  115. package/dist/parser/string/reduce/shared.js.map +0 -1
  116. package/dist/parser/string/reduce/static.d.ts.map +0 -1
  117. package/dist/parser/string/reduce/static.js +0 -2
  118. package/dist/parser/string/reduce/static.js.map +0 -1
  119. package/dist/parser/string/shift/operand/date.d.ts +0 -11
  120. package/dist/parser/string/shift/operand/date.d.ts.map +0 -1
  121. package/dist/parser/string/shift/operand/date.js.map +0 -1
  122. package/dist/parser/string/shift/operand/enclosed.d.ts.map +0 -1
  123. package/dist/parser/string/shift/operand/enclosed.js.map +0 -1
  124. package/dist/parser/string/shift/operand/operand.d.ts +0 -9
  125. package/dist/parser/string/shift/operand/operand.d.ts.map +0 -1
  126. package/dist/parser/string/shift/operand/operand.js +0 -17
  127. package/dist/parser/string/shift/operand/operand.js.map +0 -1
  128. package/dist/parser/string/shift/operand/unenclosed.d.ts +0 -36
  129. package/dist/parser/string/shift/operand/unenclosed.d.ts.map +0 -1
  130. package/dist/parser/string/shift/operand/unenclosed.js +0 -68
  131. package/dist/parser/string/shift/operand/unenclosed.js.map +0 -1
  132. package/dist/parser/string/shift/operator/bounds.d.ts +0 -55
  133. package/dist/parser/string/shift/operator/bounds.d.ts.map +0 -1
  134. package/dist/parser/string/shift/operator/bounds.js +0 -95
  135. package/dist/parser/string/shift/operator/bounds.js.map +0 -1
  136. package/dist/parser/string/shift/operator/divisor.d.ts.map +0 -1
  137. package/dist/parser/string/shift/operator/divisor.js.map +0 -1
  138. package/dist/parser/string/shift/operator/operator.d.ts.map +0 -1
  139. package/dist/parser/string/shift/operator/operator.js +0 -29
  140. package/dist/parser/string/shift/operator/operator.js.map +0 -1
  141. package/dist/parser/string/shift/scanner.d.ts.map +0 -1
  142. package/dist/parser/string/shift/scanner.js.map +0 -1
  143. package/dist/parser/string/string.d.ts +0 -26
  144. package/dist/parser/string/string.d.ts.map +0 -1
  145. package/dist/parser/string/string.js +0 -31
  146. package/dist/parser/string/string.js.map +0 -1
  147. package/dist/parser/tuple.d.ts +0 -73
  148. package/dist/parser/tuple.d.ts.map +0 -1
  149. package/dist/parser/tuple.js +0 -134
  150. package/dist/parser/tuple.js.map +0 -1
  151. package/dist/scope.d.ts +0 -159
  152. package/dist/scope.d.ts.map +0 -1
  153. package/dist/scope.js +0 -248
  154. package/dist/scope.js.map +0 -1
  155. package/dist/scopes/ark.d.ts +0 -38
  156. package/dist/scopes/ark.d.ts.map +0 -1
  157. package/dist/scopes/ark.js +0 -24
  158. package/dist/scopes/ark.js.map +0 -1
  159. package/dist/scopes/jsObjects.d.ts +0 -19
  160. package/dist/scopes/jsObjects.d.ts.map +0 -1
  161. package/dist/scopes/jsObjects.js +0 -15
  162. package/dist/scopes/jsObjects.js.map +0 -1
  163. package/dist/scopes/parsing.d.ts +0 -18
  164. package/dist/scopes/parsing.d.ts.map +0 -1
  165. package/dist/scopes/parsing.js +0 -61
  166. package/dist/scopes/parsing.js.map +0 -1
  167. package/dist/scopes/tsGenerics.d.ts +0 -17
  168. package/dist/scopes/tsGenerics.d.ts.map +0 -1
  169. package/dist/scopes/tsGenerics.js +0 -13
  170. package/dist/scopes/tsGenerics.js.map +0 -1
  171. package/dist/scopes/tsKeywords.d.ts +0 -24
  172. package/dist/scopes/tsKeywords.d.ts.map +0 -1
  173. package/dist/scopes/tsKeywords.js +0 -20
  174. package/dist/scopes/tsKeywords.js.map +0 -1
  175. package/dist/scopes/utils/creditCard.d.ts +0 -3
  176. package/dist/scopes/utils/creditCard.d.ts.map +0 -1
  177. package/dist/scopes/utils/creditCard.js +0 -36
  178. package/dist/scopes/utils/creditCard.js.map +0 -1
  179. package/dist/scopes/utils/date.d.ts +0 -24
  180. package/dist/scopes/utils/date.d.ts.map +0 -1
  181. package/dist/scopes/utils/date.js +0 -53
  182. package/dist/scopes/utils/date.js.map +0 -1
  183. package/dist/scopes/validation.d.ts +0 -20
  184. package/dist/scopes/validation.d.ts.map +0 -1
  185. package/dist/scopes/validation.js +0 -57
  186. package/dist/scopes/validation.js.map +0 -1
  187. package/dist/type.d.ts +0 -101
  188. package/dist/type.d.ts.map +0 -1
  189. package/dist/type.js +0 -138
  190. package/dist/type.js.map +0 -1
  191. package/main.ts +0 -20
  192. package/match.ts +0 -137
  193. package/parser/definition.ts +0 -156
  194. package/parser/generic.ts +0 -208
  195. package/parser/objectLiteral.ts +0 -120
  196. package/parser/semantic/bounds.ts +0 -63
  197. package/parser/semantic/divisor.ts +0 -13
  198. package/parser/semantic/intersections.ts +0 -47
  199. package/parser/semantic/semantic.ts +0 -107
  200. package/parser/semantic/utils.ts +0 -26
  201. package/parser/semantic/validate.ts +0 -105
  202. package/parser/shared.ts +0 -141
  203. package/parser/string/reduce/dynamic.ts +0 -181
  204. package/parser/string/reduce/shared.ts +0 -73
  205. package/parser/string/reduce/static.ts +0 -300
  206. package/parser/string/shift/operand/date.ts +0 -57
  207. package/parser/string/shift/operand/enclosed.ts +0 -119
  208. package/parser/string/shift/operand/operand.ts +0 -48
  209. package/parser/string/shift/operand/unenclosed.ts +0 -282
  210. package/parser/string/shift/operator/bounds.ts +0 -229
  211. package/parser/string/shift/operator/divisor.ts +0 -36
  212. package/parser/string/shift/operator/operator.ts +0 -82
  213. package/parser/string/shift/scanner.ts +0 -209
  214. package/parser/string/string.ts +0 -93
  215. package/parser/tuple.ts +0 -475
  216. package/scope.ts +0 -573
  217. package/scopes/ark.ts +0 -64
  218. package/scopes/jsObjects.ts +0 -29
  219. package/scopes/parsing.ts +0 -81
  220. package/scopes/tsGenerics.ts +0 -28
  221. package/scopes/tsKeywords.ts +0 -39
  222. package/scopes/utils/creditCard.ts +0 -37
  223. package/scopes/utils/date.ts +0 -108
  224. package/scopes/validation.ts +0 -81
  225. package/type.ts +0 -403
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2024 ArkType
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/out/ark.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { type Ark, type ArkErrors, type inferred } from "@ark/schema";
2
+ import type { GenericHktParser } from "./generic.js";
3
+ import type { MatchParser } from "./match.js";
4
+ import type { Module } from "./module.js";
5
+ import { type Scope } from "./scope.js";
6
+ import type { DeclarationParser, DefinitionParser, TypeParser } from "./type.js";
7
+ export declare const ambient: Scope<Ark>;
8
+ export declare const ark: Module<Ark>;
9
+ export declare const type: TypeParser<{}>;
10
+ export declare namespace type {
11
+ type cast<t> = {
12
+ [inferred]?: t;
13
+ };
14
+ type errors = ArkErrors;
15
+ }
16
+ export declare const generic: GenericHktParser<{}>;
17
+ export declare const match: MatchParser<{}>;
18
+ export declare const define: DefinitionParser<{}>;
19
+ export declare const declare: DeclarationParser<{}>;
package/out/ark.js ADDED
@@ -0,0 +1,9 @@
1
+ import { keywordNodes } from "@ark/schema";
2
+ import { scope } from "./scope.js";
3
+ export const ambient = scope(keywordNodes);
4
+ export const ark = ambient.export();
5
+ export const type = ambient.type;
6
+ export const generic = ambient.generic;
7
+ export const match = ambient.match;
8
+ export const define = ambient.define;
9
+ export const declare = ambient.declare;
@@ -0,0 +1 @@
1
+ export * from "@ark/schema/config";
package/out/config.js ADDED
@@ -0,0 +1,2 @@
1
+ // eslint-disable-next-line @typescript-eslint/no-restricted-imports
2
+ export * from "@ark/schema/config";
@@ -0,0 +1,65 @@
1
+ import type { GenericParamAst, GenericParamDef, genericParamSchemasToAst, GenericProps, GenericRoot, LazyGenericBody } from "@ark/schema";
2
+ import { type array, type Callable, type conform, type ErrorMessage, type Hkt, type keyError, type WhiteSpaceToken } from "@ark/util";
3
+ import type { inferDefinition } from "./parser/definition.js";
4
+ import type { inferAstRoot } from "./parser/semantic/infer.js";
5
+ import type { validateAst } from "./parser/semantic/validate.js";
6
+ import type { state, StaticState } from "./parser/string/reduce/static.js";
7
+ import { Scanner } from "./parser/string/shift/scanner.js";
8
+ import { parseUntilFinalizer } from "./parser/string/string.js";
9
+ import type { ParseContext } from "./scope.js";
10
+ import type { inferTypeRoot, Type, validateTypeRoot } from "./type.js";
11
+ export type ParameterString<params extends string = string> = `<${params}>`;
12
+ export type extractParams<s extends ParameterString> = s extends ParameterString<infer params> ? params : never;
13
+ export type validateParameterString<s extends ParameterString, $> = parseGenericParams<extractParams<s>, $> extends keyError<infer message> ? ErrorMessage<message> : s;
14
+ export type validateGenericArg<arg, param extends GenericParamAst, $> = inferTypeRoot<arg, $> extends param[1] ? arg : Type<param[1]>;
15
+ export type GenericInstantiator<params extends array<GenericParamAst>, def, $, args$> = <const args extends {
16
+ [i in keyof params]: validateTypeRoot<args[i & keyof args], args$>;
17
+ }>(
18
+ /** @ts-expect-error treat as array */
19
+ ...args: {
20
+ [i in keyof args]: validateGenericArg<args[i], params[i & keyof params & `${number}`], args$>;
21
+ }) => Type<def extends Hkt.Kind ? Hkt.apply<def, {
22
+ [i in keyof args]: inferTypeRoot<args[i], args$>;
23
+ }> : inferDefinition<def, $, bindGenericArgs<params, args$, args>>, $>;
24
+ type bindGenericArgs<params extends array<GenericParamAst>, $, args> = {
25
+ [i in keyof params & `${number}` as params[i][0]]: inferTypeRoot<args[i & keyof args], $>;
26
+ };
27
+ export type baseGenericArgs<params extends array<GenericParamAst>> = {
28
+ [i in keyof params & `${number}` as params[i][0]]: params[i][1];
29
+ };
30
+ export interface Generic<params extends array<GenericParamAst> = array<GenericParamAst>, bodyDef = unknown, $ = {}, args$ = $> extends Callable<GenericInstantiator<params, bodyDef, $, args$>>, GenericProps<params, bodyDef, $> {
31
+ internal: GenericRoot<params, bodyDef, $>;
32
+ }
33
+ export type GenericDeclaration<name extends string = string, params extends ParameterString = ParameterString> = `${name}${params}`;
34
+ export type parseValidGenericParams<def extends ParameterString, $> = conform<parseGenericParams<extractParams<def>, $>, array<GenericParamAst>>;
35
+ export declare const emptyGenericParameterMessage = "An empty string is not a valid generic parameter name";
36
+ export type emptyGenericParameterMessage = typeof emptyGenericParameterMessage;
37
+ export declare const parseGenericParams: (def: string, ctx: ParseContext) => array<GenericParamDef>;
38
+ export type parseGenericParams<def extends string, $> = parseNextNameChar<Scanner.skipWhitespace<def>, "", [
39
+ ], $>;
40
+ declare const paramsTerminators: {
41
+ ",": boolean;
42
+ ":": boolean;
43
+ " ": true;
44
+ "\n": true;
45
+ "\t": true;
46
+ };
47
+ type ParamsTerminator = keyof typeof paramsTerminators;
48
+ declare const parseName: (scanner: Scanner, result: GenericParamDef[], ctx: ParseContext) => GenericParamDef[];
49
+ type parseName<unscanned extends string, result extends array<GenericParamAst>, $> = parseNextNameChar<Scanner.skipWhitespace<unscanned>, "", result, $>;
50
+ type parseNextNameChar<unscanned extends string, name extends string, result extends array<GenericParamAst>, $> = unscanned extends `${infer lookahead}${infer nextUnscanned}` ? lookahead extends ParamsTerminator ? name extends "" ? keyError<emptyGenericParameterMessage> : lookahead extends "," ? parseName<nextUnscanned, [...result, [name, unknown]], $> : lookahead extends ":" | WhiteSpaceToken ? _parseOptionalConstraint<unscanned, name, result, $> : never : parseNextNameChar<nextUnscanned, `${name}${lookahead}`, result, $> : name extends "" ? result : [...result, [name, unknown]];
51
+ declare const extendsToken = "extends ";
52
+ type ConstrainingToken = ":" | typeof extendsToken;
53
+ declare const _parseOptionalConstraint: (scanner: Scanner, name: string, result: GenericParamDef[], ctx: ParseContext) => GenericParamDef[];
54
+ type _parseOptionalConstraint<unscanned extends string, name extends string, result extends array<GenericParamAst>, $> = Scanner.skipWhitespace<unscanned> extends (`${ConstrainingToken}${infer nextUnscanned}`) ? parseUntilFinalizer<state.initialize<nextUnscanned>, $, {}> extends (infer finalArgState extends StaticState) ? validateAst<finalArgState["root"], $, {}> extends (ErrorMessage<infer message>) ? keyError<message> : parseName<finalArgState["unscanned"], [
55
+ ...result,
56
+ [name, inferAstRoot<finalArgState["root"], $, {}>]
57
+ ], $> : never : parseName<Scanner.skipWhitespace<unscanned> extends `,${infer nextUnscanned}` ? nextUnscanned : unscanned, [
58
+ ...result,
59
+ [name, unknown]
60
+ ], $>;
61
+ export type GenericHktParser<$ = {}> = <const paramsDef extends array<GenericParamDef>>(...params: paramsDef) => (instantiateDef: LazyGenericBody<genericParamSchemasToAst<paramsDef, $>>) => GenericHktSubclass<genericParamSchemasToAst<paramsDef, $>, $>;
62
+ export type GenericHktSubclass<params extends array<GenericParamAst>, $> = abstract new () => GenericHkt<genericParamSchemasToAst<params, $>, Hkt.Kind, $, $>;
63
+ export interface GenericHkt<params extends array<GenericParamAst>, hkt extends Hkt.Kind, $, args$> extends Generic<params, hkt, $, args$>, Hkt.Kind {
64
+ }
65
+ export {};
package/out/generic.js ADDED
@@ -0,0 +1,39 @@
1
+ import { throwParseError, whiteSpaceTokens } from "@ark/util";
2
+ import { DynamicState } from "./parser/string/reduce/dynamic.js";
3
+ import { Scanner } from "./parser/string/shift/scanner.js";
4
+ import { parseUntilFinalizer } from "./parser/string/string.js";
5
+ export const emptyGenericParameterMessage = "An empty string is not a valid generic parameter name";
6
+ export const parseGenericParams = (def, ctx) => parseName(new Scanner(def), [], ctx);
7
+ const paramsTerminators = { ...whiteSpaceTokens, ",": true, ":": true };
8
+ const parseName = (scanner, result, ctx) => {
9
+ scanner.shiftUntilNonWhitespace();
10
+ const name = scanner.shiftUntilNextTerminator();
11
+ if (name === "") {
12
+ // if we've reached the end of the string and have parsed at least one
13
+ // param, return the valid result
14
+ if (scanner.lookahead === "" && result.length)
15
+ return result;
16
+ return throwParseError(emptyGenericParameterMessage);
17
+ }
18
+ scanner.shiftUntilNonWhitespace();
19
+ return _parseOptionalConstraint(scanner, name, result, ctx);
20
+ };
21
+ const extendsToken = "extends ";
22
+ const _parseOptionalConstraint = (scanner, name, result, ctx) => {
23
+ scanner.shiftUntilNonWhitespace();
24
+ if (scanner.lookahead === ":")
25
+ scanner.shift();
26
+ else if (scanner.unscanned.startsWith(extendsToken))
27
+ scanner.jumpForward(extendsToken.length);
28
+ else {
29
+ // if we don't have a contraining token here, return now so we can
30
+ // assume in the rest of the function body we do have a constraint
31
+ if (scanner.lookahead === ",")
32
+ scanner.shift();
33
+ result.push(name);
34
+ return parseName(scanner, result, ctx);
35
+ }
36
+ const s = parseUntilFinalizer(new DynamicState(scanner, ctx, false));
37
+ result.push([name, s.root]);
38
+ return parseName(scanner, result, ctx);
39
+ };
package/out/index.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export { ArkError, ArkErrors as ArkErrors } from "@ark/schema";
2
+ export type { Ark, ArkConfig, Out, constrained, inferred } from "@ark/schema";
3
+ export { ambient, ark, declare, define, generic, match, type } from "./ark.js";
4
+ export { Module } from "./module.js";
5
+ export { scope, type Scope, type inferScope, type validateScope } from "./scope.js";
6
+ export { Type, type AnyType, type inferTypeRoot, type validateTypeRoot } from "./type.js";
package/out/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { ArkError, ArkErrors as ArkErrors } from "@ark/schema";
2
+ export { ambient, ark, declare, define, generic, match, type } from "./ark.js";
3
+ export { Module } from "./module.js";
4
+ export { scope } from "./scope.js";
5
+ export { Type } from "./type.js";
package/out/match.d.ts ADDED
@@ -0,0 +1,71 @@
1
+ import type { Narrowed, distillOut, inferIntersection } from "@ark/schema";
2
+ import type { ErrorMessage, isDisjoint, numericStringKeyOf, override, propValueOf, unionToTuple } from "@ark/util";
3
+ import type { Scope } from "./scope.js";
4
+ import type { inferTypeRoot, validateTypeRoot } from "./type.js";
5
+ type MatchParserContext = {
6
+ thens: readonly ((In: unknown) => unknown)[];
7
+ $: unknown;
8
+ exhaustiveOver: unknown;
9
+ };
10
+ export type MatchParser<$> = CaseMatchParser<{
11
+ thens: [];
12
+ exhaustiveOver: unknown;
13
+ $: $;
14
+ }> & {
15
+ (): ChainableMatchParser<{
16
+ thens: [];
17
+ exhaustiveOver: unknown;
18
+ $: $;
19
+ }>;
20
+ only: <inputs>() => ChainableMatchParser<{
21
+ thens: [];
22
+ exhaustiveOver: inputs;
23
+ $: $;
24
+ }>;
25
+ };
26
+ type matcherInputs<ctx extends MatchParserContext> = Parameters<ctx["thens"][number]>[0];
27
+ type getHandledBranches<ctx extends MatchParserContext> = Exclude<matcherInputs<ctx>, Narrowed>;
28
+ type getUnhandledBranches<ctx extends MatchParserContext> = distillOut<Exclude<ctx["exhaustiveOver"], getHandledBranches<ctx>>>;
29
+ type addBranches<ctx extends MatchParserContext, branches extends unknown[]> = override<ctx, {
30
+ thens: [...ctx["thens"], ...branches];
31
+ }>;
32
+ type validateWhenDefinition<def, ctx extends MatchParserContext> = def extends validateTypeRoot<def, ctx["$"]> ? inferMatchBranch<def, ctx> extends getHandledBranches<ctx> ? ErrorMessage<"This branch is redundant and will never be reached"> : def : validateTypeRoot<def, ctx["$"]>;
33
+ type inferMatchBranch<def, ctx extends MatchParserContext> = distillOut<inferIntersection<getUnhandledBranches<ctx>, inferTypeRoot<def, ctx["$"]>>>;
34
+ export type ChainableMatchParser<ctx extends MatchParserContext> = {
35
+ when: <def, ret>(when: validateWhenDefinition<def, ctx>, then: (In: inferMatchBranch<def, ctx>) => ret) => ChainableMatchParser<addBranches<ctx, [(In: inferMatchBranch<def, ctx>) => ret]>>;
36
+ cases: CaseMatchParser<ctx>;
37
+ orThrow: () => finalizeMatchParser<addBranches<ctx, [(In: getHandledBranches<ctx>) => never]>>;
38
+ default: MatchParserDefaultInvocation<ctx>;
39
+ finalize: (this: getUnhandledBranches<ctx> extends never ? ChainableMatchParser<ctx> : ErrorMessage<"Cannot manually finalize a non-exhaustive matcher: consider adding a `.default` case, using one of the `.orX` methods, or using `match.only<T>`">) => finalizeMatchParser<ctx>;
40
+ };
41
+ type MatchParserDefaultInvocation<ctx extends MatchParserContext> = {
42
+ <f extends (In: getUnhandledBranches<ctx>) => unknown>(f: f): finalizeWithDefault<ctx, ReturnType<f>>;
43
+ <const value>(value: value): finalizeWithDefault<ctx, value>;
44
+ };
45
+ type validateCases<cases, ctx extends MatchParserContext> = {
46
+ [def in keyof cases | keyof ctx["$"] | "default"]?: def extends "default" ? (In: getUnhandledBranches<ctx>) => unknown : def extends validateWhenDefinition<def, ctx> ? (In: inferMatchBranch<def, ctx>) => unknown : validateWhenDefinition<def, ctx>;
47
+ };
48
+ type errorCases<cases, ctx extends MatchParserContext> = {
49
+ [def in keyof cases]?: def extends "default" ? (In: getUnhandledBranches<ctx>) => unknown : def extends validateWhenDefinition<def, ctx> ? (In: inferMatchBranch<def, ctx>) => unknown : validateWhenDefinition<def, ctx>;
50
+ } & {
51
+ [k in Exclude<keyof ctx["$"], keyof cases>]?: (In: distillOut<inferIntersection<getUnhandledBranches<ctx>, ctx["$"][k]>>) => unknown;
52
+ } & {
53
+ default?: (In: getUnhandledBranches<ctx>) => unknown;
54
+ };
55
+ export type CaseMatchParser<ctx extends MatchParserContext> = <cases>(def: cases extends validateCases<cases, ctx> ? cases : errorCases<cases, ctx>) => cases extends {
56
+ default: (...args: never[]) => infer defaultReturn;
57
+ } ? finalizeWithDefault<addBranches<ctx, unionToTuple<cases[Exclude<keyof cases, "default">]>>, defaultReturn> : ChainableMatchParser<addBranches<ctx, unionToTuple<propValueOf<cases>>>>;
58
+ type finalizeWithDefault<ctx extends MatchParserContext, defaultReturn> = finalizeMatchParser<addBranches<ctx, [(_: getUnhandledBranches<ctx>) => defaultReturn]>>;
59
+ type finalizeMatchParser<ctx extends MatchParserContext> = MatchInvocation<{
60
+ thens: ctx["thens"];
61
+ initialInputs: ctx["exhaustiveOver"];
62
+ }>;
63
+ type MatchInvocationContext = {
64
+ thens: readonly ((...args: never[]) => unknown)[];
65
+ initialInputs: unknown;
66
+ };
67
+ export type MatchInvocation<ctx extends MatchInvocationContext> = <const data extends ctx["initialInputs"]>(data: data) => {
68
+ [i in numericStringKeyOf<ctx["thens"]>]: isDisjoint<data, Parameters<ctx["thens"][i]>[0]> extends true ? never : ReturnType<ctx["thens"][i]>;
69
+ }[numericStringKeyOf<ctx["thens"]>];
70
+ export declare const createMatchParser: <$>($: Scope) => MatchParser<$>;
71
+ export {};
package/out/match.js ADDED
@@ -0,0 +1,50 @@
1
+ export const createMatchParser = ($) => (() => { }).bind($);
2
+ // const matchParser = (isRestricted: boolean) => {
3
+ // const handledCases: { when: RawRoot; then: Morph }[] = []
4
+ // let defaultCase: ((x: unknown) => unknown) | null = null
5
+ // const parser = {
6
+ // when: (when: unknown, then: Morph) => {
7
+ // handledCases.push({ when: $.parseRoot(when, {}), then })
8
+ // return parser
9
+ // },
10
+ // finalize: () => {
11
+ // // TODO: exhaustiveness checking
12
+ // const branches = handledCases.flatMap(({ when, then }) => {
13
+ // if (when.kind === "union") {
14
+ // return when.branches.map((branch) => ({
15
+ // in: branch,
16
+ // morph: then
17
+ // }))
18
+ // }
19
+ // if (when.kind === "morph") {
20
+ // return [{ in: when, morph: [when.morph, then] }]
21
+ // }
22
+ // return [{ in: when, morph: then }]
23
+ // })
24
+ // if (defaultCase) {
25
+ // branches.push({ in: keywordNodes.unknown, morph: defaultCase })
26
+ // }
27
+ // const matchers = $.node("union", {
28
+ // branches,
29
+ // ordered: true
30
+ // })
31
+ // return matchers.assert
32
+ // },
33
+ // orThrow: () => {
34
+ // // implicitly finalize, we don't need to do anything else because we throw either way
35
+ // return parser.finalize()
36
+ // },
37
+ // default: (x: unknown) => {
38
+ // if (x instanceof Function) {
39
+ // defaultCase = x as never
40
+ // } else {
41
+ // defaultCase = () => x
42
+ // }
43
+ // return parser.finalize()
44
+ // }
45
+ // }
46
+ // return parser
47
+ // }
48
+ // return Object.assign(() => matchParser(false), {
49
+ // only: () => matchParser(true)
50
+ // }) as never
@@ -0,0 +1,14 @@
1
+ import { RootModule, type arkKind, type GenericProps } from "@ark/schema";
2
+ import type { anyOrNever, Hkt } from "@ark/util";
3
+ import type { Generic, GenericHkt } from "./generic.js";
4
+ import type { Type } from "./type.js";
5
+ type exportScope<$> = {
6
+ [k in keyof $]: $[k] extends {
7
+ [arkKind]: "module";
8
+ } ? [
9
+ $[k]
10
+ ] extends [anyOrNever] ? Type<$[k], $> : $[k] : $[k] extends GenericProps<infer params, infer bodyDef, infer args$> ? $[k] extends Hkt.Kind ? GenericHkt<params, $[k], $, args$> : Generic<params, bodyDef, $, args$> : Type<$[k], $>;
11
+ };
12
+ export declare const Module: new <$ = {}>(types: exportScope<$>) => Module<$>;
13
+ export type Module<$ = {}> = RootModule<exportScope<$>>;
14
+ export {};
package/out/module.js ADDED
@@ -0,0 +1,2 @@
1
+ import { RootModule } from "@ark/schema";
2
+ export const Module = RootModule;
@@ -1,24 +1,25 @@
1
- import { type Root } from "@arktype/schema";
2
- import { type defined, type equals, type ErrorMessage, type evaluate, type isAny, type isUnknown, type objectKindOrDomainOf, type optionalKeyOf, type Primitive, type requiredKeyOf } from "@arktype/util";
1
+ import { type BaseRoot, type string } from "@ark/schema";
2
+ import { type ErrorMessage, type Primitive, type anyOrNever, type array, type defined, type equals, type isUnknown, type objectKindOrDomainOf, type optionalKeyOf, type requiredKeyOf, type show } from "@ark/util";
3
+ import type { type } from "../ark.js";
3
4
  import type { ParseContext } from "../scope.js";
4
- import type { type } from "../scopes/ark.js";
5
5
  import { type inferObjectLiteral, type validateObjectLiteral } from "./objectLiteral.js";
6
6
  import type { validateString } from "./semantic/validate.js";
7
7
  import type { BaseCompletions, inferString } from "./string/string.js";
8
- import { type inferTuple, type TupleExpression, type validateTuple } from "./tuple.js";
9
- export declare const parseObject: (def: object, ctx: ParseContext) => Root;
10
- export type inferDefinition<def, $, args> = isAny<def> extends true ? never : def extends type.cast<infer t> | ThunkCast<infer t> ? t : def extends string ? inferString<def, $, args> : def extends readonly unknown[] ? inferTuple<def, $, args> : def extends RegExp ? string : def extends object ? inferObjectLiteral<def, $, args> : never;
11
- export type validateDefinition<def, $, args> = null extends undefined ? ErrorMessage<`'strict' or 'strictNullChecks' must be set to true in your tsconfig's 'compilerOptions'`> : [def] extends [Terminal] ? unknown extends def ? never : def : def extends string ? validateString<def, $, args> : def extends readonly unknown[] ? validateTuple<def, $, args> : def extends BadDefinitionType ? writeBadDefinitionTypeMessage<objectKindOrDomainOf<def>> : isUnknown<def> extends true ? // this allows the initial list of autocompletions to be populated when a user writes "type()",
12
- BaseCompletions<$, args> | {} : validateObjectLiteral<def, $, args>;
8
+ import { type TupleExpression, type inferTuple, type validateTuple } from "./tuple.js";
9
+ export declare const parseObject: (def: object, ctx: ParseContext) => BaseRoot;
10
+ export type inferDefinition<def, $, args> = [
11
+ def
12
+ ] extends [anyOrNever] ? def extends never ? never : any : def extends type.cast<infer t> | ThunkCast<infer t> ? t : def extends string ? inferString<def, $, args> : def extends array ? inferTuple<def, $, args> : def extends RegExp ? string.matching<string> : def extends object ? inferObjectLiteral<def, $, args> : never;
13
+ export type validateDefinition<def, $, args> = null extends undefined ? ErrorMessage<`'strict' or 'strictNullChecks' must be set to true in your tsconfig's 'compilerOptions'`> : [def] extends [Terminal] ? def : def extends string ? validateString<def, $, args> : def extends array ? validateTuple<def, $, args> : def extends BadDefinitionType ? ErrorMessage<writeBadDefinitionTypeMessage<objectKindOrDomainOf<def>>> : isUnknown<def> extends true ? BaseCompletions<$, args> | {} : validateObjectLiteral<def, $, args>;
13
14
  export type validateDeclared<declared, def, $, args> = def extends validateDefinition<def, $, args> ? validateInference<def, declared, $, args> : validateDefinition<def, $, args>;
14
- type validateInference<def, declared, $, args> = def extends RegExp | type.cast<unknown> | ThunkCast | TupleExpression ? validateShallowInference<def, declared, $, args> : def extends readonly unknown[] ? declared extends readonly unknown[] ? {
15
- [i in keyof declared]: i extends keyof def ? validateInference<def[i], declared[i], $, args> : unknown;
16
- } : evaluate<declarationMismatch<def, declared, $, args>> : def extends object ? evaluate<{
17
- [k in requiredKeyOf<declared>]: k extends keyof def ? validateInference<def[k], declared[k], $, args> : unknown;
15
+ type validateInference<def, declared, $, args> = def extends RegExp | type.cast<unknown> | ThunkCast | TupleExpression ? validateShallowInference<def, declared, $, args> : def extends array ? declared extends array ? {
16
+ [i in keyof declared]: i extends keyof def ? validateInference<def[i], declared[i], $, args> : declared[i];
17
+ } : show<declarationMismatch<def, declared, $, args>> : def extends object ? show<{
18
+ [k in requiredKeyOf<declared>]: k extends keyof def ? validateInference<def[k], declared[k], $, args> : declared[k];
18
19
  } & {
19
- [k in optionalKeyOf<declared> & string as `${k}?`]: `${k}?` extends keyof def ? validateInference<def[`${k}?`], defined<declared[k]>, $, args> : unknown;
20
+ [k in optionalKeyOf<declared> & string as `${k}?`]: `${k}?` extends (keyof def) ? validateInference<def[`${k}?`], defined<declared[k]>, $, args> : declared[k];
20
21
  }> : validateShallowInference<def, declared, $, args>;
21
- type validateShallowInference<def, declared, $, args> = equals<inferDefinition<def, $, args>, declared> extends true ? def : evaluate<declarationMismatch<def, declared, $, args>>;
22
+ type validateShallowInference<def, declared, $, args> = equals<inferDefinition<def, $, args>, declared> extends true ? def : show<declarationMismatch<def, declared, $, args>>;
22
23
  type declarationMismatch<def, declared, $, args> = {
23
24
  declared: declared;
24
25
  inferred: inferDefinition<def, $, args>;
@@ -26,7 +27,6 @@ type declarationMismatch<def, declared, $, args> = {
26
27
  type Terminal = RegExp | type.cast<unknown> | ((...args: never[]) => unknown);
27
28
  export type ThunkCast<t = unknown> = () => type.cast<t>;
28
29
  type BadDefinitionType = Exclude<Primitive, string>;
29
- export declare const writeBadDefinitionTypeMessage: <actual extends string>(actual: actual) => `Type definitions must be strings or objects (was ${actual})`;
30
+ export declare const writeBadDefinitionTypeMessage: <actual extends string>(actual: actual) => writeBadDefinitionTypeMessage<actual>;
30
31
  type writeBadDefinitionTypeMessage<actual extends string> = `Type definitions must be strings or objects (was ${actual})`;
31
32
  export {};
32
- //# sourceMappingURL=definition.d.ts.map
@@ -1,29 +1,29 @@
1
- import { isNode, node } from "@arktype/schema";
2
- import { isThunk, objectKindOf, stringify, throwParseError } from "@arktype/util";
3
- import { Type } from "../type.js";
1
+ import { hasArkKind } from "@ark/schema";
2
+ import { isThunk, objectKindOf, printable, throwParseError } from "@ark/util";
4
3
  import { parseObjectLiteral } from "./objectLiteral.js";
5
4
  import { parseTuple } from "./tuple.js";
6
5
  export const parseObject = (def, ctx) => {
7
6
  const objectKind = objectKindOf(def);
8
7
  switch (objectKind) {
9
8
  case undefined:
10
- if (isNode(def)) {
9
+ if (hasArkKind(def, "root"))
11
10
  return def;
12
- }
13
11
  return parseObjectLiteral(def, ctx);
14
12
  case "Array":
15
13
  return parseTuple(def, ctx);
16
14
  case "RegExp":
17
- return node({ basis: "string", pattern: def });
18
- case "Function":
15
+ return ctx.$.node("intersection", {
16
+ domain: "string",
17
+ pattern: def
18
+ }, { prereduced: true });
19
+ case "Function": {
19
20
  const resolvedDef = isThunk(def) ? def() : def;
20
- if (resolvedDef instanceof Type) {
21
- return resolvedDef.root;
22
- }
21
+ if (hasArkKind(resolvedDef, "root"))
22
+ return resolvedDef;
23
23
  return throwParseError(writeBadDefinitionTypeMessage("Function"));
24
+ }
24
25
  default:
25
- return throwParseError(writeBadDefinitionTypeMessage(objectKind ?? stringify(def)));
26
+ return throwParseError(writeBadDefinitionTypeMessage(objectKind ?? printable(def)));
26
27
  }
27
28
  };
28
29
  export const writeBadDefinitionTypeMessage = (actual) => `Type definitions must be strings or objects (was ${actual})`;
29
- //# sourceMappingURL=definition.js.map
@@ -0,0 +1,79 @@
1
+ import { type BaseRoot, type Default, type IndexNode, type of, type OptionalNode, type RequiredNode, type UndeclaredKeyBehavior, type writeInvalidPropertyKeyMessage } from "@ark/schema";
2
+ import { type anyOrNever, type Dict, type ErrorMessage, type EscapeToken, type Key, type keyError, type listable, type merge, type show } from "@ark/util";
3
+ import type { ParseContext } from "../scope.js";
4
+ import type { inferDefinition, validateDefinition } from "./definition.js";
5
+ import type { astToString } from "./semantic/utils.js";
6
+ import type { validateString } from "./semantic/validate.js";
7
+ export declare const parseObjectLiteral: (def: Dict, ctx: ParseContext) => BaseRoot;
8
+ export declare const writeInvalidUndeclaredBehaviorMessage: (actual: unknown) => string;
9
+ export declare const nonLeadingSpreadError = "Spread operator may only be used as the first key in an object";
10
+ export type inferObjectLiteral<def extends object, $, args> = show<"..." extends keyof def ? merge<inferDefinition<def["..."], $, args>, _inferObjectLiteral<def, $, args>> : _inferObjectLiteral<def, $, args>>;
11
+ /**
12
+ * Infers the contents of an object literal, ignoring a spread definition
13
+ */
14
+ type _inferObjectLiteral<def extends object, $, args> = {
15
+ -readonly [k in keyof def as nonOptionalKeyFrom<k, $, args>]: def[k] extends (DefaultValueTuple<infer baseDef, infer defaultValue>) ? def[k] extends anyOrNever ? def[k] : (In?: inferDefinition<baseDef, $, args>) => Default<defaultValue> : inferDefinition<def[k], $, args>;
16
+ } & {
17
+ -readonly [k in keyof def as optionalKeyFrom<k>]?: inferDefinition<def[k], $, args>;
18
+ };
19
+ export type validateObjectLiteral<def, $, args> = {
20
+ [k in keyof def]: k extends IndexKey<infer indexDef> ? validateString<indexDef, $, args> extends ErrorMessage<infer message> ? keyError<message> : inferDefinition<indexDef, $, args> extends (PropertyKey | of<PropertyKey, {}>) ? validateDefinition<def[k], $, args> : keyError<writeInvalidPropertyKeyMessage<indexDef>> : k extends "..." ? inferDefinition<def[k], $, args> extends object ? validateDefinition<def[k], $, args> : keyError<writeInvalidSpreadTypeMessage<astToString<def[k]>>> : k extends "+" ? UndeclaredKeyBehavior : validateDefaultableValue<def, k, $, args>;
21
+ };
22
+ type validateDefaultableValue<def, k extends keyof def, $, args> = def[k] extends DefaultValueTuple ? validateDefaultValueTuple<def[k], k, $, args> : validateDefinition<def[k], $, args>;
23
+ type DefaultValueTuple<baseDef = unknown, defaultValue = unknown> = readonly [
24
+ baseDef,
25
+ "=",
26
+ defaultValue
27
+ ];
28
+ type validateDefaultValueTuple<def extends DefaultValueTuple, k extends PropertyKey, $, args> = parseKey<k>["kind"] extends "required" ? readonly [
29
+ validateDefinition<def[0], $, args>,
30
+ "=",
31
+ inferDefinition<def[0], $, args>
32
+ ] : ErrorMessage<invalidDefaultKeyKindMessage>;
33
+ type nonOptionalKeyFrom<k, $, args> = parseKey<k> extends PreparsedKey<"required", infer inner> ? inner : parseKey<k> extends PreparsedKey<"index", infer inner> ? inferDefinition<inner, $, args> extends infer t extends Key ? t : never : never;
34
+ type optionalKeyFrom<k> = parseKey<k> extends PreparsedKey<"optional", infer inner> ? inner : never;
35
+ type PreparsedKey<kind extends ParsedKeyKind = ParsedKeyKind, key extends Key = Key> = {
36
+ kind: kind;
37
+ key: key;
38
+ };
39
+ declare namespace PreparsedKey {
40
+ type from<t extends PreparsedKey> = t;
41
+ }
42
+ type ParsedKeyKind = "required" | "optional" | "index" | MetaKey;
43
+ export type MetaKey = "..." | "+";
44
+ export type IndexKey<def extends string = string> = `[${def}]`;
45
+ export type ParsedEntry = ParsedUndeclaredEntry | ParsedSpreadEntry | RequiredNode | OptionalNode | IndexNode;
46
+ export type ParsedUndeclaredEntry = {
47
+ kind: "undeclared";
48
+ behavior: UndeclaredKeyBehavior;
49
+ };
50
+ export type ParsedSpreadEntry = {
51
+ kind: "spread";
52
+ node: BaseRoot;
53
+ };
54
+ export declare const parseEntry: (key: Key, value: unknown, ctx: ParseContext) => listable<ParsedEntry>;
55
+ export declare const invalidDefaultKeyKindMessage = "Only required keys may specify default values, e.g. { value: 'number = 0' }";
56
+ export type invalidDefaultKeyKindMessage = typeof invalidDefaultKeyKindMessage;
57
+ declare const parseKey: (key: Key) => PreparsedKey;
58
+ type parseKey<k> = k extends `${infer inner}?` ? inner extends `${infer baseName}${EscapeToken}` ? PreparsedKey.from<{
59
+ kind: "required";
60
+ key: `${baseName}?`;
61
+ }> : PreparsedKey.from<{
62
+ kind: "optional";
63
+ key: inner;
64
+ }> : k extends MetaKey ? PreparsedKey.from<{
65
+ kind: k;
66
+ key: k;
67
+ }> : k extends `${EscapeToken}${infer escapedMeta extends MetaKey}` ? PreparsedKey.from<{
68
+ kind: "required";
69
+ key: escapedMeta;
70
+ }> : k extends IndexKey<infer def> ? PreparsedKey.from<{
71
+ kind: "index";
72
+ key: def;
73
+ }> : PreparsedKey.from<{
74
+ kind: "required";
75
+ key: k extends `${EscapeToken}${infer escapedIndexKey extends IndexKey}` ? escapedIndexKey : k extends Key ? k : `${k & number}`;
76
+ }>;
77
+ export declare const writeInvalidSpreadTypeMessage: <def extends string>(def: def) => writeInvalidSpreadTypeMessage<def>;
78
+ type writeInvalidSpreadTypeMessage<def extends string> = `Spread operand must resolve to an object literal type (was ${def})`;
79
+ export {};
@@ -0,0 +1,100 @@
1
+ import { ArkErrors, normalizeIndex } from "@ark/schema";
2
+ import { append, escapeToken, isArray, printable, stringAndSymbolicEntriesOf, throwParseError } from "@ark/util";
3
+ import { writeUnassignableDefaultValueMessage } from "./semantic/default.js";
4
+ export const parseObjectLiteral = (def, ctx) => {
5
+ let spread;
6
+ const structure = {};
7
+ // We only allow a spread operator to be used as the first key in an object
8
+ // because to match JS behavior any keys before the spread are overwritten
9
+ // by the values in the target object, so there'd be no useful purpose in having it
10
+ // anywhere except for the beginning.
11
+ const parsedEntries = stringAndSymbolicEntriesOf(def).flatMap(entry => parseEntry(entry[0], entry[1], ctx));
12
+ if (parsedEntries[0]?.kind === "spread") {
13
+ // remove the spread entry so we can iterate over the remaining entries
14
+ // expecting non-spread entries
15
+ const spreadEntry = parsedEntries.shift();
16
+ if (!spreadEntry.node.hasKind("intersection") ||
17
+ !spreadEntry.node.structure) {
18
+ return throwParseError(writeInvalidSpreadTypeMessage(typeof spreadEntry.node.expression));
19
+ }
20
+ spread = spreadEntry.node.structure;
21
+ }
22
+ for (const entry of parsedEntries) {
23
+ if (entry.kind === "spread")
24
+ return throwParseError(nonLeadingSpreadError);
25
+ if (entry.kind === "undeclared") {
26
+ structure.undeclared = entry.behavior;
27
+ continue;
28
+ }
29
+ structure[entry.kind] = append(structure[entry.kind], entry);
30
+ }
31
+ const structureNode = ctx.$.node("structure", structure);
32
+ return ctx.$.schema({
33
+ domain: "object",
34
+ structure: spread?.merge(structureNode) ?? structureNode
35
+ });
36
+ };
37
+ export const writeInvalidUndeclaredBehaviorMessage = (actual) => `Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${printable(actual)})`;
38
+ export const nonLeadingSpreadError = "Spread operator may only be used as the first key in an object";
39
+ export const parseEntry = (key, value, ctx) => {
40
+ const parsedKey = parseKey(key);
41
+ if (parsedKey.kind === "+") {
42
+ if (value !== "reject" && value !== "delete" && value !== "ignore")
43
+ throwParseError(writeInvalidUndeclaredBehaviorMessage(value));
44
+ return { kind: "undeclared", behavior: value };
45
+ }
46
+ if (parsedKey.kind === "...")
47
+ return { kind: "spread", node: ctx.$.parse(value, ctx) };
48
+ const parsedValue = isArray(value) && value[1] === "=" ?
49
+ [ctx.$.parse(value[0], ctx), "=", value[2]]
50
+ : ctx.$.parse(value, ctx, true);
51
+ if (isArray(parsedValue)) {
52
+ if (parsedKey.kind !== "required")
53
+ throwParseError(invalidDefaultKeyKindMessage);
54
+ const out = parsedValue[0].traverse(parsedValue[2]);
55
+ if (out instanceof ArkErrors) {
56
+ throwParseError(writeUnassignableDefaultValueMessage(printable(parsedKey.key), out.message));
57
+ }
58
+ return ctx.$.node("optional", {
59
+ key: parsedKey.key,
60
+ value: parsedValue[0],
61
+ default: parsedValue[2]
62
+ });
63
+ }
64
+ if (parsedKey.kind === "index") {
65
+ const signature = ctx.$.parse(parsedKey.key, ctx);
66
+ const normalized = normalizeIndex(signature, parsedValue, ctx.$);
67
+ return (normalized.index ?
68
+ normalized.required ?
69
+ [normalized.index, ...normalized.required]
70
+ : normalized.index
71
+ : normalized.required ?? []);
72
+ }
73
+ return ctx.$.node(parsedKey.kind, {
74
+ key: parsedKey.key,
75
+ value: parsedValue
76
+ });
77
+ };
78
+ // single quote use here is better for TypeScript's inlined error to avoid escapes
79
+ export const invalidDefaultKeyKindMessage = `Only required keys may specify default values, e.g. { value: 'number = 0' }`;
80
+ const parseKey = (key) => typeof key === "symbol" ? { kind: "required", key }
81
+ : key.at(-1) === "?" ?
82
+ key.at(-2) === escapeToken ?
83
+ { kind: "required", key: `${key.slice(0, -2)}?` }
84
+ : {
85
+ kind: "optional",
86
+ key: key.slice(0, -1)
87
+ }
88
+ : key[0] === "[" && key.at(-1) === "]" ?
89
+ { kind: "index", key: key.slice(1, -1) }
90
+ : key[0] === escapeToken && key[1] === "[" && key.at(-1) === "]" ?
91
+ { kind: "required", key: key.slice(1) }
92
+ : key === "..." ? { kind: key, key }
93
+ : key === "+" ? { kind: key, key }
94
+ : {
95
+ kind: "required",
96
+ key: key === "\\..." ? "..."
97
+ : key === "\\+" ? "+"
98
+ : key
99
+ };
100
+ export const writeInvalidSpreadTypeMessage = (def) => `Spread operand must resolve to an object literal type (was ${def})`;
@@ -0,0 +1,15 @@
1
+ import type { LimitLiteral, writeUnboundableMessage } from "@ark/schema";
2
+ import type { ErrorMessage, array, typeToString } from "@ark/util";
3
+ import type { Comparator } from "../string/reduce/shared.js";
4
+ import type { BoundExpressionKind, writeInvalidLimitMessage } from "../string/shift/operator/bounds.js";
5
+ import type { inferAstIn } from "./infer.js";
6
+ import type { astToString } from "./utils.js";
7
+ import type { validateAst } from "./validate.js";
8
+ export type validateRange<l, comparator extends Comparator, r, $, args> = l extends LimitLiteral ? validateBound<r, comparator, l, "left", $, args> : l extends [infer leftAst, Comparator, unknown] ? ErrorMessage<writeDoubleRightBoundMessage<astToString<leftAst>>> : validateBound<l, comparator, r & LimitLiteral, "right", $, args>;
9
+ export type validateBound<boundedAst, comparator extends Comparator, limit extends LimitLiteral, boundKind extends BoundExpressionKind, $, args> = inferAstIn<boundedAst, $, args> extends infer bounded ? isNumericallyBoundable<bounded> extends true ? limit extends number ? validateAst<boundedAst, $, args> : ErrorMessage<writeInvalidLimitMessage<comparator, limit, boundKind>> : [bounded] extends [Date] ? validateAst<boundedAst, $, args> : ErrorMessage<writeUnboundableMessage<typeToString<bounded>>> : never;
10
+ type isNumericallyBoundable<bounded> = [
11
+ bounded
12
+ ] extends [number] ? true : [bounded] extends [string] ? true : [bounded] extends [array] ? true : false;
13
+ export declare const writeDoubleRightBoundMessage: <root extends string>(root: root) => writeDoubleRightBoundMessage<root>;
14
+ type writeDoubleRightBoundMessage<root extends string> = `Expression ${root} must have at most one right bound`;
15
+ export {};
@@ -1,2 +1 @@
1
1
  export const writeDoubleRightBoundMessage = (root) => `Expression ${root} must have at most one right bound`;
2
- //# sourceMappingURL=bounds.js.map
@@ -0,0 +1,8 @@
1
+ import type { ErrorMessage } from "@ark/util";
2
+ import type { UnitLiteral } from "../string/shift/operator/default.js";
3
+ import type { inferAstOut, inferTerminal } from "./infer.js";
4
+ import type { astToString } from "./utils.js";
5
+ import type { validateAst } from "./validate.js";
6
+ export type validateDefault<baseAst, unitLiteral extends UnitLiteral, $, args> = validateAst<baseAst, $, args> extends infer e extends ErrorMessage ? e : inferTerminal<unitLiteral, $, args> extends inferAstOut<baseAst, $, args> ? undefined : ErrorMessage<writeUnassignableDefaultValueMessage<astToString<baseAst>, unitLiteral>>;
7
+ export declare const writeUnassignableDefaultValueMessage: <key extends string, message extends string>(key: key, message: message) => string;
8
+ export type writeUnassignableDefaultValueMessage<baseDef extends string, defaultValue extends string> = `Default value ${defaultValue} is not assignable to ${baseDef}`;
@@ -0,0 +1 @@
1
+ export const writeUnassignableDefaultValueMessage = (key, message) => `Default value at ${key} ${message}`;