arktype 2.0.2 → 2.0.4
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.
- package/README.md +18 -199
- package/out/attributes.d.ts +1 -1
- package/out/config.d.ts +1 -1
- package/out/config.js +2 -1
- package/out/keywords/keywords.js +1 -0
- package/out/keywords/string.d.ts +1 -1
- package/out/match.d.ts +72 -0
- package/out/match.js +57 -0
- package/out/parser/ast/bounds.d.ts +4 -4
- package/out/parser/ast/divisor.d.ts +5 -3
- package/out/parser/ast/utils.d.ts +5 -1
- package/out/scope.d.ts +2 -0
- package/out/scope.js +2 -0
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -1,206 +1,28 @@
|
|
|
1
|
-
<h1 align="center">ArkType
|
|
1
|
+
<h1 align="center">ArkType</h1>
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
ArkType is a runtime validation library that parses optimized validators from familiar, type-safe syntax.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
It can be used to check external data like JSON payloads or form submissions at the boundaries of your code (similar to Zod or Yup).
|
|
6
6
|
|
|
7
|
-
<
|
|
7
|
+
<video
|
|
8
|
+
autoPlay
|
|
9
|
+
loop
|
|
10
|
+
controls
|
|
11
|
+
playsInline
|
|
12
|
+
muted
|
|
13
|
+
disablePictureInPicture
|
|
14
|
+
src="https://github.com/user-attachments/assets/69fdded6-50a9-402d-a28c-afa58db63c90"
|
|
15
|
+
/>
|
|
8
16
|
|
|
9
|
-
|
|
17
|
+
## Docs
|
|
10
18
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
<a id="install" />
|
|
14
|
-
|
|
15
|
-
## Install
|
|
16
|
-
|
|
17
|
-
<img src="./ark/docs/src/assets/npm.svg" alt="Npm Icon" height="16px" /> <code>npm install arktype</code>
|
|
18
|
-
<sub>(or whatever package manager you prefer)</sub>
|
|
19
|
-
<br />
|
|
20
|
-
|
|
21
|
-
Our types are tested in [strict-mode](https://www.typescriptlang.org/tsconfig#strict) with TypeScript version `5.4+`, although you will likely have success with other versions after 5.0.
|
|
22
|
-
|
|
23
|
-
If your types work but you notice errors in node_modules, this could be due to `tsconfig` incompatibilities- please enable `compilerOptions/skipLibCheck` ([docs](https://www.typescriptlang.org/tsconfig/#skipLibCheck)).
|
|
24
|
-
|
|
25
|
-
## Your first type
|
|
26
|
-
|
|
27
|
-
Defining basic types in ArkType is just like TypeScript, so if you already know how to do that, congratulations! You already know most of ArkType's syntax 🎉
|
|
28
|
-
|
|
29
|
-
For an ever better in-editor developer experience, try the [ArkDark VSCode extension](https://marketplace.visualstudio.com/items?itemName=arktypeio.arkdark) for syntax highlighting.
|
|
30
|
-
|
|
31
|
-
```ts
|
|
32
|
-
import { type } from "arktype"
|
|
33
|
-
|
|
34
|
-
// Definitions are statically parsed and inferred as TS
|
|
35
|
-
export const user = type({
|
|
36
|
-
name: "string",
|
|
37
|
-
device: {
|
|
38
|
-
platform: "'android'|'ios'",
|
|
39
|
-
"version?": "number"
|
|
40
|
-
}
|
|
41
|
-
})
|
|
42
|
-
|
|
43
|
-
// Validators return typed data or clear, customizable errors.
|
|
44
|
-
export const out = user({
|
|
45
|
-
name: "Alan Turing",
|
|
46
|
-
device: {
|
|
47
|
-
// errors.summary: "device/platform must be 'android' or 'ios' (was 'enigma')"
|
|
48
|
-
platform: "enigma"
|
|
49
|
-
}
|
|
50
|
-
})
|
|
51
|
-
|
|
52
|
-
if (out instanceof type.errors) {
|
|
53
|
-
// a clear, user-ready error message, even for complex unions and intersections
|
|
54
|
-
console.log(out.summary)
|
|
55
|
-
} else {
|
|
56
|
-
// your valid data!
|
|
57
|
-
console.log(out)
|
|
58
|
-
}
|
|
59
|
-
```
|
|
60
|
-
|
|
61
|
-
## Example syntax
|
|
62
|
-
|
|
63
|
-
Lots more docs are on the way, but I want to highlight some of the most useful syntax patterns/features that are carried over from alpha as well as those new to the 2.0 release.
|
|
64
|
-
|
|
65
|
-
```ts
|
|
66
|
-
// Syntax carried over from 1.0 + TS
|
|
67
|
-
export const currentTsSyntax = type({
|
|
68
|
-
keyword: "null",
|
|
69
|
-
stringLiteral: "'TS'",
|
|
70
|
-
numberLiteral: "5",
|
|
71
|
-
bigintLiteral: "5n",
|
|
72
|
-
union: "string|number",
|
|
73
|
-
intersection: "boolean&true",
|
|
74
|
-
array: "Date[]",
|
|
75
|
-
grouping: "(0|1)[]",
|
|
76
|
-
objectLiteral: {
|
|
77
|
-
nested: "string",
|
|
78
|
-
"optional?": "number"
|
|
79
|
-
},
|
|
80
|
-
tuple: ["number", "number"]
|
|
81
|
-
})
|
|
82
|
-
|
|
83
|
-
// available syntax new to 2.0
|
|
84
|
-
|
|
85
|
-
export const upcomingTsSyntax = type({
|
|
86
|
-
keyof: "keyof object",
|
|
87
|
-
variadicTuples: ["true", "...", "false[]"]
|
|
88
|
-
})
|
|
89
|
-
|
|
90
|
-
// runtime-specific syntax and builtin keywords with great error messages
|
|
91
|
-
|
|
92
|
-
export const validationSyntax = type({
|
|
93
|
-
keywords: "email|uuid|creditCard|integer", // and many more
|
|
94
|
-
builtinParsers: "parse.date", // parses a Date from a string
|
|
95
|
-
nativeRegexLiteral: /@arktype\.io/,
|
|
96
|
-
embeddedRegexLiteral: "email&/@arktype\\.io/",
|
|
97
|
-
divisibility: "number%10", // a multiple of 10
|
|
98
|
-
bound: "alpha>10", // an alpha-only string with more than 10 characters
|
|
99
|
-
range: "1<=email[]<100", // a list of 1 to 99 emails
|
|
100
|
-
narrows: ["number", ":", n => n % 2 === 1], // an odd integer
|
|
101
|
-
morphs: ["string", "=>", parseFloat] // validates a string input then parses it to a number
|
|
102
|
-
})
|
|
103
|
-
|
|
104
|
-
// root-level expressions
|
|
105
|
-
|
|
106
|
-
const intersected = type({ value: "string" }, "&", { format: "'bigint'" })
|
|
107
|
-
|
|
108
|
-
// chained expressions via .or, .and, .narrow, .pipe and much more
|
|
109
|
-
// (these replace previous helper methods like union and intersection)
|
|
110
|
-
|
|
111
|
-
const user = type({
|
|
112
|
-
name: "string",
|
|
113
|
-
age: "number"
|
|
114
|
-
})
|
|
115
|
-
|
|
116
|
-
const parseUser = type("string").pipe(s => JSON.parse(s), user)
|
|
117
|
-
|
|
118
|
-
// type is fully introspectable and traversable, displayed as:
|
|
119
|
-
type ParseUser = Type<
|
|
120
|
-
(In: string) => Out<{
|
|
121
|
-
name: string
|
|
122
|
-
age: number
|
|
123
|
-
}>
|
|
124
|
-
>
|
|
125
|
-
|
|
126
|
-
const maybeMe = parseUser('{ "name": "David" }')
|
|
127
|
-
|
|
128
|
-
if (maybeMe instanceof type.errors) {
|
|
129
|
-
// "age must be a number (was missing)"
|
|
130
|
-
console.log(maybeMe.summary)
|
|
131
|
-
}
|
|
132
|
-
```
|
|
133
|
-
|
|
134
|
-
There's so much more I want to share but I want to get at least an initial version of the 2.0 branch merged tonight so look forward to that next week!
|
|
135
|
-
|
|
136
|
-
## API
|
|
137
|
-
|
|
138
|
-
ArkType supports many of TypeScript's built-in types and operators, as well as some new ones dedicated exclusively to runtime validation. In fact, we got a little ahead of ourselves and built a ton of cool features, but we're still working on getting caught up syntax and API docs. Keep an eye out for more in the next couple weeks ⛵
|
|
139
|
-
|
|
140
|
-
In the meantime, check out the examples here and use the type hints you get to learn how you can customize your types and scopes. If you want to explore some of the more advanced features, take a look at [our unit tests](./ark/type/__tests__) or ask us [on Discord](https://discord.gg/xEzdc3fJQC) if your functionality is supported. If not, [create a GitHub issue](https://github.com/arktypeio/arktype/issues/new) so we can prioritize it!
|
|
141
|
-
|
|
142
|
-
## Integrations
|
|
143
|
-
|
|
144
|
-
### tRPC
|
|
145
|
-
|
|
146
|
-
ArkType can easily be used with tRPC via the `assert` prop:
|
|
147
|
-
|
|
148
|
-
```ts
|
|
149
|
-
t.procedure.input(
|
|
150
|
-
type({
|
|
151
|
-
name: "string",
|
|
152
|
-
"age?": "number"
|
|
153
|
-
}).assert
|
|
154
|
-
)
|
|
155
|
-
```
|
|
156
|
-
|
|
157
|
-
## How?
|
|
158
|
-
|
|
159
|
-
ArkType's isomorphic parser has parallel static and dynamic implementations. This means as soon as you type a definition in your editor, you'll know the eventual result at runtime.
|
|
160
|
-
|
|
161
|
-
If you're curious, below is an example of what that looks like under the hood. If not, close that hood back up, `npm install arktype` and enjoy top-notch developer experience 🧑💻
|
|
162
|
-
|
|
163
|
-
```ts
|
|
164
|
-
export const parseOperator = (s: DynamicState): void => {
|
|
165
|
-
const lookahead = s.scanner.shift()
|
|
166
|
-
return (
|
|
167
|
-
lookahead === "" ? s.finalize()
|
|
168
|
-
: lookahead === "[" ?
|
|
169
|
-
s.scanner.shift() === "]" ?
|
|
170
|
-
s.rootToArray()
|
|
171
|
-
: s.error(incompleteArrayTokenMessage)
|
|
172
|
-
: isKeyOf(lookahead, Scanner.branchTokens) ? s.pushRootToBranch(lookahead)
|
|
173
|
-
: lookahead === ")" ? s.finalizeGroup()
|
|
174
|
-
: isKeyOf(lookahead, Scanner.comparatorStartChars) ?
|
|
175
|
-
parseBound(s, lookahead)
|
|
176
|
-
: lookahead === "%" ? parseDivisor(s)
|
|
177
|
-
: lookahead === " " ? parseOperator(s)
|
|
178
|
-
: throwInternalError(writeUnexpectedCharacterMessage(lookahead))
|
|
179
|
-
)
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
export type parseOperator<s extends StaticState> =
|
|
183
|
-
s["unscanned"] extends Scanner.shift<infer lookahead, infer unscanned> ?
|
|
184
|
-
lookahead extends "[" ?
|
|
185
|
-
unscanned extends Scanner.shift<"]", infer nextUnscanned> ?
|
|
186
|
-
state.setRoot<s, [s["root"], "[]"], nextUnscanned>
|
|
187
|
-
: error<incompleteArrayTokenMessage>
|
|
188
|
-
: lookahead extends Scanner.BranchToken ?
|
|
189
|
-
state.reduceBranch<s, lookahead, unscanned>
|
|
190
|
-
: lookahead extends ")" ? state.finalizeGroup<s, unscanned>
|
|
191
|
-
: lookahead extends Scanner.ComparatorStartChar ?
|
|
192
|
-
parseBound<s, lookahead, unscanned>
|
|
193
|
-
: lookahead extends "%" ? parseDivisor<s, unscanned>
|
|
194
|
-
: lookahead extends " " ? parseOperator<state.scanTo<s, unscanned>>
|
|
195
|
-
: error<writeUnexpectedCharacterMessage<lookahead>>
|
|
196
|
-
: state.finalize<s>
|
|
197
|
-
```
|
|
19
|
+
See our [docs site](https://arktype.io)
|
|
198
20
|
|
|
199
21
|
## Contributions
|
|
200
22
|
|
|
201
|
-
We accept and encourage pull requests from outside ArkType.
|
|
23
|
+
We accept and encourage pull requests from outside ArkType. Planned work is tracked in [this GitHub project](https://github.com/orgs/arktypeio/projects/4).
|
|
202
24
|
|
|
203
|
-
Depending on your level of familiarity with type systems and TS generics, some parts of the codebase may be hard to jump into. That said, there's plenty of opportunities for more straightforward contributions.
|
|
25
|
+
Depending on your level of familiarity with type systems and TS generics, some parts of the codebase may be hard to jump into. That said, there's plenty of opportunities for more straightforward contributions. We'd generally recommend starting with one of these issues labeled [external-contributor-friendly](https://github.com/orgs/arktypeio/projects/4/?filterQuery=label%3A%22external-contributor-friendly%22).
|
|
204
26
|
|
|
205
27
|
If you're planning on submitting a non-trivial fix or a new feature, please [create an issue first](https://github.com/arktypeio/arktype/issues/new) so everyone's on the same page. The last thing we want is for you to spend time on a submission we're unable to merge.
|
|
206
28
|
|
|
@@ -211,17 +33,13 @@ When you're ready, check out our [guide](./.github/CONTRIBUTING.md) to get start
|
|
|
211
33
|
This project is licensed under the terms of the
|
|
212
34
|
[MIT license](./LICENSE).
|
|
213
35
|
|
|
214
|
-
## Collaboration
|
|
215
|
-
|
|
216
|
-
I'd love to hear about what you're working on and how ArkType can help. Please reach out to david@arktype.io.
|
|
217
|
-
|
|
218
36
|
## Code of Conduct
|
|
219
37
|
|
|
220
38
|
We will not tolerate any form of disrespect toward members of our community. Please refer to our [Code of Conduct](./.github/CODE_OF_CONDUCT.md) and reach out to david@arktype.io immediately if you've seen or experienced an interaction that may violate these standards.
|
|
221
39
|
|
|
222
40
|
## Sponsorship
|
|
223
41
|
|
|
224
|
-
We've been working full-time on this project for
|
|
42
|
+
We've been working full-time on this project for multiple years and it means a lot to have the community behind us.
|
|
225
43
|
|
|
226
44
|
If the project has been useful to you and you are in a financial position to do so, please chip in via [GitHub Sponsors](https://github.com/sponsors/arktypeio).
|
|
227
45
|
|
|
@@ -302,6 +120,7 @@ Otherwise, consider sending me an email (david@arktype.io) or [message me on Dis
|
|
|
302
120
|
<th>Phalangers</th>
|
|
303
121
|
<th>WilliamConnatser</th>
|
|
304
122
|
<th>JameEnder</th>
|
|
123
|
+
<th>tylim88</th>
|
|
305
124
|
</tr>
|
|
306
125
|
<tr>
|
|
307
126
|
<td>
|
package/out/attributes.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export declare namespace distill {
|
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
21
|
type finalizeDistillation<t, distilled> = equals<t, distilled> extends true ? t : distilled;
|
|
22
|
-
type _distill<t, endpoint extends distill.Endpoint, seen> = t extends undefined ? t : [t] extends [anyOrNever | seen] ? t : unknown extends t ? unknown : t extends Brand<infer base> ? endpoint extends "in" ? base : t : t extends TerminallyInferredObject | Primitive ? t : t extends Function ? t extends InferredMorph<infer i, infer o> ? distillIo<i, o, endpoint, seen> : t : t extends Default<infer constraint> ? _distill<constraint, endpoint, seen> : t extends array ? distillArray<t, endpoint, seen | t> : isSafelyMappable<t> extends true ? distillMappable<t, endpoint, seen | t> : t;
|
|
22
|
+
type _distill<t, endpoint extends distill.Endpoint, seen> = t extends undefined ? t : [t] extends [anyOrNever | seen] ? t : unknown extends t ? unknown : t extends Brand<infer base> ? endpoint extends "in" ? base : t : t extends TerminallyInferredObject | Primitive ? t : t extends Function ? t extends (...args: never) => anyOrNever ? t : t extends InferredMorph<infer i, infer o> ? distillIo<i, o, endpoint, seen> : t : t extends Default<infer constraint> ? _distill<constraint, endpoint, seen> : t extends array ? distillArray<t, endpoint, seen | t> : isSafelyMappable<t> extends true ? distillMappable<t, endpoint, seen | t> : t;
|
|
23
23
|
type distillMappable<o, endpoint extends distill.Endpoint, seen> = endpoint extends "in" ? show<{
|
|
24
24
|
[k in keyof o as k extends inferredDefaultKeyOf<o> ? never : k]: _distill<o[k], endpoint, seen>;
|
|
25
25
|
} & {
|
package/out/config.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ArkSchemaRegistry } from "@ark/schema";
|
|
2
2
|
import type { Ark } from "./keywords/keywords.ts";
|
|
3
3
|
import type { exportScope } from "./module.ts";
|
|
4
|
-
export { configure, type ArkConfig, type ArkSchemaRegistry } from "@ark/schema";
|
|
4
|
+
export { configure, type ArkConfig, type ArkSchemaRegistry } from "@ark/schema/config";
|
|
5
5
|
export interface ArkTypeRegistryContents extends ArkSchemaRegistry {
|
|
6
6
|
ambient: exportScope<Ark>;
|
|
7
7
|
}
|
package/out/config.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
// eslint-disable-next-line @typescript-eslint/no-restricted-imports
|
|
2
|
+
export { configure } from "@ark/schema/config";
|
package/out/keywords/keywords.js
CHANGED
|
@@ -24,6 +24,7 @@ export const ark = scope({
|
|
|
24
24
|
}, { prereducedAliases: true, ambient: true });
|
|
25
25
|
export const keywords = ark.export();
|
|
26
26
|
export const type = ark.type;
|
|
27
|
+
// export const match: MatchParser<{}> = ark.match as never
|
|
27
28
|
export const generic = ark.generic;
|
|
28
29
|
export const schema = ark.schema;
|
|
29
30
|
export const define = ark.define;
|
package/out/keywords/string.d.ts
CHANGED
|
@@ -246,7 +246,6 @@ export declare namespace uuid {
|
|
|
246
246
|
};
|
|
247
247
|
}
|
|
248
248
|
export declare const string: Module<{
|
|
249
|
-
root: unknown;
|
|
250
249
|
trim: Submodule<trim.submodule>;
|
|
251
250
|
normalize: Submodule<{
|
|
252
251
|
root: unknown;
|
|
@@ -267,6 +266,7 @@ export declare const string: Module<{
|
|
|
267
266
|
preformatted: unknown;
|
|
268
267
|
}>;
|
|
269
268
|
}>;
|
|
269
|
+
root: unknown;
|
|
270
270
|
integer: Submodule<stringInteger.submodule>;
|
|
271
271
|
json: Submodule<stringJson.submodule>;
|
|
272
272
|
alpha: unknown;
|
package/out/match.d.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { type BaseRoot } from "@ark/schema";
|
|
2
|
+
import { Callable, type array, type Fn, type isDisjoint, type numericStringKeyOf, type propValueOf, type unionToTuple } from "@ark/util";
|
|
3
|
+
import type { distill, inferIntersection } from "./attributes.ts";
|
|
4
|
+
import type { type } from "./keywords/keywords.ts";
|
|
5
|
+
import type { InternalScope } from "./scope.ts";
|
|
6
|
+
type Thens = array<(In: any) => unknown>;
|
|
7
|
+
type MatchParserContext = {
|
|
8
|
+
thens: Thens;
|
|
9
|
+
$: unknown;
|
|
10
|
+
input: unknown;
|
|
11
|
+
};
|
|
12
|
+
export type MatchParser<$> = CaseMatchParser<{
|
|
13
|
+
thens: [];
|
|
14
|
+
$: $;
|
|
15
|
+
input: unknown;
|
|
16
|
+
}> & {
|
|
17
|
+
(): ChainableMatchParser<{
|
|
18
|
+
thens: [];
|
|
19
|
+
$: $;
|
|
20
|
+
input: unknown;
|
|
21
|
+
}>;
|
|
22
|
+
from<typedInput>(): ChainableMatchParser<{
|
|
23
|
+
thens: [];
|
|
24
|
+
$: $;
|
|
25
|
+
input: typedInput;
|
|
26
|
+
}>;
|
|
27
|
+
};
|
|
28
|
+
type addBranches<ctx extends MatchParserContext, branches extends readonly unknown[]> = branches extends Thens ? {
|
|
29
|
+
$: ctx["$"];
|
|
30
|
+
input: ctx["input"];
|
|
31
|
+
thens: [...ctx["thens"], ...branches];
|
|
32
|
+
} : never;
|
|
33
|
+
type inferMatchBranch<def, ctx extends MatchParserContext> = distill.Out<inferIntersection<ctx["input"], type.infer<def, ctx["$"]>>>;
|
|
34
|
+
type ChainableMatchParser<ctx extends MatchParserContext> = {
|
|
35
|
+
when: <def, ret>(when: type.validate<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: ctx["input"]) => never]>>;
|
|
38
|
+
default: MatchParserDefaultInvocation<ctx>;
|
|
39
|
+
};
|
|
40
|
+
type MatchParserDefaultInvocation<ctx extends MatchParserContext> = {
|
|
41
|
+
<f extends (In: ctx["input"]) => unknown>(f: f): finalizeWithDefault<ctx, ReturnType<f>>;
|
|
42
|
+
<const value>(value: value): finalizeWithDefault<ctx, value>;
|
|
43
|
+
};
|
|
44
|
+
type validateCases<cases, ctx extends MatchParserContext> = {
|
|
45
|
+
[def in keyof cases | keyof ctx["$"] | "default"]?: def extends "default" ? (In: ctx["input"]) => unknown : def extends type.validate<def, ctx["$"]> ? (In: inferMatchBranch<def, ctx>) => unknown : type.validate<def, ctx["$"]>;
|
|
46
|
+
};
|
|
47
|
+
type errorCases<cases, ctx extends MatchParserContext> = {
|
|
48
|
+
[def in keyof cases]?: def extends "default" ? (In: ctx["input"]) => unknown : def extends type.validate<def, ctx["$"]> ? (In: inferMatchBranch<def, ctx>) => unknown : type.validate<def, ctx["$"]>;
|
|
49
|
+
} & {
|
|
50
|
+
[k in Exclude<keyof ctx["$"], keyof cases>]?: (In: distill.Out<inferIntersection<ctx["input"], ctx["$"][k]>>) => unknown;
|
|
51
|
+
} & {
|
|
52
|
+
default?: (In: ctx["input"]) => unknown;
|
|
53
|
+
};
|
|
54
|
+
export type CaseMatchParser<ctx extends MatchParserContext> = <cases>(def: cases extends validateCases<cases, ctx> ? cases : errorCases<cases, ctx>) => cases extends {
|
|
55
|
+
default: (...args: never[]) => infer defaultReturn;
|
|
56
|
+
} ? finalizeWithDefault<addBranches<ctx, unionToTuple<cases[Exclude<keyof cases, "default">]>>, defaultReturn> : ChainableMatchParser<addBranches<ctx, unionToTuple<propValueOf<cases>>>>;
|
|
57
|
+
type finalizeWithDefault<ctx extends MatchParserContext, defaultReturn> = finalizeMatchParser<addBranches<ctx, [(_: ctx["input"]) => defaultReturn]>>;
|
|
58
|
+
type finalizeMatchParser<ctx extends MatchParserContext> = MatchInvocation<{
|
|
59
|
+
thens: ctx["thens"];
|
|
60
|
+
input: ctx["input"];
|
|
61
|
+
}>;
|
|
62
|
+
type MatchInvocationContext = {
|
|
63
|
+
thens: readonly Fn[];
|
|
64
|
+
input: unknown;
|
|
65
|
+
};
|
|
66
|
+
export type MatchInvocation<ctx extends MatchInvocationContext> = <const data extends ctx["input"]>(data: data) => {
|
|
67
|
+
[i in numericStringKeyOf<ctx["thens"]>]: isDisjoint<data, Parameters<ctx["thens"][i]>[0]> extends true ? never : ReturnType<ctx["thens"][i]>;
|
|
68
|
+
}[numericStringKeyOf<ctx["thens"]>];
|
|
69
|
+
export declare class InternalMatchParser extends Callable<(...args: unknown[]) => BaseRoot> {
|
|
70
|
+
constructor($: InternalScope);
|
|
71
|
+
}
|
|
72
|
+
export {};
|
package/out/match.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { intrinsic } from "@ark/schema";
|
|
2
|
+
import { Callable } from "@ark/util";
|
|
3
|
+
export class InternalMatchParser extends Callable {
|
|
4
|
+
constructor($) {
|
|
5
|
+
super(() => {
|
|
6
|
+
const matchParser = () => {
|
|
7
|
+
const handledCases = [];
|
|
8
|
+
let defaultCase = null;
|
|
9
|
+
const parser = {
|
|
10
|
+
when: (when, then) => {
|
|
11
|
+
handledCases.push({
|
|
12
|
+
when: $.parse(when),
|
|
13
|
+
then
|
|
14
|
+
});
|
|
15
|
+
return parser;
|
|
16
|
+
},
|
|
17
|
+
finalize: () => {
|
|
18
|
+
const branches = handledCases.flatMap(({ when, then }) => {
|
|
19
|
+
if (when.kind === "union") {
|
|
20
|
+
return when.branches.map(branch => ({
|
|
21
|
+
in: branch,
|
|
22
|
+
morphs: [then]
|
|
23
|
+
}));
|
|
24
|
+
}
|
|
25
|
+
if (when.hasKind("morph"))
|
|
26
|
+
return [{ in: when, morphs: [...when.morphs, then] }];
|
|
27
|
+
return [{ in: when, morphs: [then] }];
|
|
28
|
+
});
|
|
29
|
+
if (defaultCase)
|
|
30
|
+
branches.push({ in: intrinsic.unknown, morphs: [defaultCase] });
|
|
31
|
+
const matchers = $.node("union", {
|
|
32
|
+
branches,
|
|
33
|
+
ordered: true
|
|
34
|
+
});
|
|
35
|
+
return matchers.assert;
|
|
36
|
+
},
|
|
37
|
+
orThrow: () =>
|
|
38
|
+
// implicitly finalize, we don't need to do anything else because we throw either way
|
|
39
|
+
parser.finalize(),
|
|
40
|
+
default: (x) => {
|
|
41
|
+
if (x instanceof Function)
|
|
42
|
+
defaultCase = x;
|
|
43
|
+
else
|
|
44
|
+
defaultCase = () => x;
|
|
45
|
+
return parser.finalize();
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
return parser;
|
|
49
|
+
};
|
|
50
|
+
return Object.assign(() => matchParser(), {
|
|
51
|
+
only: () => matchParser()
|
|
52
|
+
});
|
|
53
|
+
}, {
|
|
54
|
+
bind: $
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import type { writeUnboundableMessage } from "@ark/schema";
|
|
2
2
|
import type { ErrorMessage, array, typeToString } from "@ark/util";
|
|
3
|
-
import type { LimitLiteral } from "../../attributes.ts";
|
|
3
|
+
import type { InferredMorph, LimitLiteral } from "../../attributes.ts";
|
|
4
4
|
import type { Comparator } from "../reduce/shared.ts";
|
|
5
5
|
import type { BoundExpressionKind, writeInvalidLimitMessage } from "../shift/operator/bounds.ts";
|
|
6
|
-
import type {
|
|
7
|
-
import type { astToString } from "./utils.ts";
|
|
6
|
+
import type { inferAstRoot } from "./infer.ts";
|
|
7
|
+
import type { astToString, writeConstrainedMorphMessage } from "./utils.ts";
|
|
8
8
|
import type { validateAst } from "./validate.ts";
|
|
9
9
|
export type validateRange<l, comparator extends Comparator, r, $, args> = [
|
|
10
10
|
l
|
|
11
11
|
] 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>;
|
|
12
|
-
export type validateBound<boundedAst, comparator extends Comparator, limit extends LimitLiteral, boundKind extends BoundExpressionKind, $, args> =
|
|
12
|
+
export type validateBound<boundedAst, comparator extends Comparator, limit extends LimitLiteral, boundKind extends BoundExpressionKind, $, args> = inferAstRoot<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> : [bounded] extends [InferredMorph] ? ErrorMessage<writeConstrainedMorphMessage<boundedAst>> : ErrorMessage<writeUnboundableMessage<typeToString<bounded>>> : never;
|
|
13
13
|
type isNumericallyBoundable<bounded> = [
|
|
14
14
|
bounded
|
|
15
15
|
] extends [number] ? true : [bounded] extends [string] ? true : [bounded] extends [array] ? true : false;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { writeIndivisibleMessage } from "@ark/schema";
|
|
2
2
|
import type { ErrorMessage } from "@ark/util";
|
|
3
|
-
import type {
|
|
3
|
+
import type { InferredMorph } from "../../attributes.ts";
|
|
4
|
+
import type { inferAstRoot } from "./infer.ts";
|
|
5
|
+
import type { writeConstrainedMorphMessage } from "./utils.ts";
|
|
4
6
|
import type { validateAst } from "./validate.ts";
|
|
5
|
-
export type validateDivisor<l, $, args> =
|
|
7
|
+
export type validateDivisor<l, $, args> = inferAstRoot<l, $, args> extends infer data ? [
|
|
6
8
|
data
|
|
7
|
-
] extends [number] ? validateAst<l, $, args> : ErrorMessage<writeIndivisibleMessage<data>> : never;
|
|
9
|
+
] extends [number] ? validateAst<l, $, args> : [data] extends [InferredMorph] ? ErrorMessage<writeConstrainedMorphMessage<l>> : ErrorMessage<writeIndivisibleMessage<data>> : never;
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
import type { Stringifiable } from "@ark/util";
|
|
1
|
+
import type { satisfy, Stringifiable } from "@ark/util";
|
|
2
2
|
import type { Comparator } from "../reduce/shared.ts";
|
|
3
|
+
import type { ArkTypeScanner } from "../shift/scanner.ts";
|
|
3
4
|
import type { DefAst, InferredAst, InfixExpression, PostfixExpression } from "./infer.ts";
|
|
4
5
|
export type astToString<ast> = ast extends InferredAst | DefAst ? ast[2] : ast extends PostfixExpression<infer operator, infer operand> ? operator extends "[]" ? `${astToString<operand>}[]` : never : ast extends InfixExpression<infer operator, infer l, infer r> ? operator extends "&" | "|" | "%" | Comparator ? `${astToString<l>} ${operator} ${astToString<r>}` : never : ast extends Stringifiable ? `${ast extends bigint ? `${ast}n` : ast}` : "...";
|
|
6
|
+
export type ConstraintOperator = satisfy<ArkTypeScanner.OperatorToken, "%" | Comparator>;
|
|
7
|
+
export type writeConstrainedMorphMessage<constrainedAst> = `To constrain the output of ${astToString<constrainedAst>}, pipe like myMorph.to('number > 0').
|
|
8
|
+
To constrain the input, intersect like myMorph.and('number > 0').`;
|
package/out/scope.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { type Brand, type ErrorType, type JsonStructure, type anyOrNever, type a
|
|
|
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
|
+
import { InternalMatchParser } from "./match.ts";
|
|
6
7
|
import type { BoundModule, Module, Submodule, instantiateExport } from "./module.ts";
|
|
7
8
|
import type { DefAst, InferredAst } from "./parser/ast/infer.ts";
|
|
8
9
|
import { type inferDefinition } from "./parser/definition.ts";
|
|
@@ -75,6 +76,7 @@ export declare class InternalScope<$ extends {} = {}> extends BaseScope<$> {
|
|
|
75
76
|
enumerated: EnumeratedTypeParser<$>;
|
|
76
77
|
instanceOf: InstanceOfTypeParser<$>;
|
|
77
78
|
type: InternalTypeParser;
|
|
79
|
+
match: InternalMatchParser;
|
|
78
80
|
declare: () => {
|
|
79
81
|
type: InternalTypeParser;
|
|
80
82
|
};
|
package/out/scope.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { $ark, BaseScope, hasArkKind, parseGeneric } from "@ark/schema";
|
|
2
2
|
import { flatMorph, isArray, isThunk, throwParseError } from "@ark/util";
|
|
3
3
|
import { parseGenericParamName } from "./generic.js";
|
|
4
|
+
import { InternalMatchParser } from "./match.js";
|
|
4
5
|
import { shallowDefaultableMessage, shallowOptionalMessage } from "./parser/ast/validate.js";
|
|
5
6
|
import { parseInnerDefinition } from "./parser/definition.js";
|
|
6
7
|
import { ArkTypeScanner } from "./parser/shift/scanner.js";
|
|
@@ -74,6 +75,7 @@ export class InternalScope extends BaseScope {
|
|
|
74
75
|
enumerated = (...values) => this.units(values);
|
|
75
76
|
instanceOf = ctor => this.node("proto", { proto: ctor }, { prereduced: true });
|
|
76
77
|
type = new InternalTypeParser(this);
|
|
78
|
+
match = new InternalMatchParser(this);
|
|
77
79
|
declare = () => ({
|
|
78
80
|
type: this.type
|
|
79
81
|
});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "arktype",
|
|
3
3
|
"description": "TypeScript's 1:1 validator, optimized from editor to runtime",
|
|
4
|
-
"version": "2.0.
|
|
4
|
+
"version": "2.0.4",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -34,14 +34,15 @@
|
|
|
34
34
|
"out"
|
|
35
35
|
],
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@ark/
|
|
38
|
-
"@ark/
|
|
37
|
+
"@ark/util": "0.39.0",
|
|
38
|
+
"@ark/schema": "0.39.0"
|
|
39
39
|
},
|
|
40
40
|
"publishConfig": {
|
|
41
41
|
"access": "public"
|
|
42
42
|
},
|
|
43
43
|
"scripts": {
|
|
44
44
|
"build": "ts ../repo/build.ts",
|
|
45
|
-
"test": "ts ../repo/testPackage.ts"
|
|
45
|
+
"test": "ts ../repo/testPackage.ts; pnpm testIntegration",
|
|
46
|
+
"testIntegration": "ts ./__tests__/integration/importConfig.ts"
|
|
46
47
|
}
|
|
47
48
|
}
|