arktype 2.0.0 → 2.0.2

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 ADDED
@@ -0,0 +1,343 @@
1
+ <h1 align="center">ArkType <sub><sup>TypeScript's 1:1 validator</sup></sub></h1>
2
+
3
+ ## What is it?
4
+
5
+ <p>ArkType is a runtime validation library that can infer <b>TypeScript definitions 1:1</b> and reuse them as <b>highly-optimized validators</b> for your data.</p>
6
+
7
+ <p>With each character you type, you'll get <b>immediate feedback from your editor</b> in the form of either a fully-inferred <code>Type</code> or a specific and helpful <code>ParseError</code>.</p>
8
+
9
+ <p>This result exactly mirrors what you can expect to happen at runtime down to the punctuation of the error message- <b>no plugins required</b>.</p>
10
+
11
+ Check out [how it works](#how) or [scroll slightly](#install) to read about installation.
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
+ ```
198
+
199
+ ## Contributions
200
+
201
+ We accept and encourage pull requests from outside ArkType.
202
+
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.
204
+
205
+ 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
+
207
+ When you're ready, check out our [guide](./.github/CONTRIBUTING.md) to get started!
208
+
209
+ ## License
210
+
211
+ This project is licensed under the terms of the
212
+ [MIT license](./LICENSE).
213
+
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
+ ## Code of Conduct
219
+
220
+ 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
+
222
+ ## Sponsorship
223
+
224
+ We've been working full-time on this project for over a year and it means a lot to have the community behind us.
225
+
226
+ 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
+
228
+ Otherwise, consider sending me an email (david@arktype.io) or [message me on Discord](https://arktype.io/discord) to let me know you're a fan of ArkType. Either would make my day!
229
+
230
+ ### ArkSponsors ⛵
231
+
232
+ <table>
233
+ <tr>
234
+ <th>sam-goodwin</th>
235
+ <th>fubhy</th>
236
+ </tr>
237
+ <tr>
238
+ <td>
239
+ <a href="https://github.com/sam-goodwin"
240
+ ><img
241
+ height="64px"
242
+ src="https://avatars.githubusercontent.com/u/38672686"
243
+ /></a>
244
+ </td>
245
+ <td>
246
+ <a href="https://github.com/fubhy"
247
+ ><img
248
+ height="64px"
249
+ src="https://avatars.githubusercontent.com/u/1172528"
250
+ /></a>
251
+ </td>
252
+ </tr>
253
+ </table>
254
+
255
+ ### Sponsors 🥰
256
+
257
+ <table>
258
+ <tr>
259
+ <th>tmm</th>
260
+ <th>mishushakov</th>
261
+ <th>mewhhaha</th>
262
+ <th>codeandcats</th>
263
+ <th>drwpwrs</th>
264
+ </tr>
265
+ <tr>
266
+ <td>
267
+ <a href="https://github.com/tmm"
268
+ ><img
269
+ height="64px"
270
+ src="https://avatars.githubusercontent.com/u/6759464"
271
+ /></a>
272
+ </td>
273
+ <td>
274
+ <a href="https://github.com/mishushakov"
275
+ ><img height="64px" src="https://avatars.githubusercontent.com/u/10400064"
276
+ /></a>
277
+ </td>
278
+ <td>
279
+ <a href="https://github.com/mewhhaha"
280
+ ><img
281
+ height="64px"
282
+ src="https://avatars.githubusercontent.com/u/3399205"
283
+ /></a>
284
+ </td>
285
+ <td>
286
+ <a href="https://github.com/codeandcats"
287
+ ><img
288
+ height="64px"
289
+ src="https://avatars.githubusercontent.com/u/6035934"
290
+ /></a>
291
+ </td>
292
+ <td>
293
+ <a href="https://github.com/drwpwrs"
294
+ ><img
295
+ height="64px"
296
+ src="https://avatars.githubusercontent.com/u/49917220"
297
+ /></a>
298
+ </td>
299
+ </tr>
300
+ <tr>
301
+ <th>Timeraa</th>
302
+ <th>Phalangers</th>
303
+ <th>WilliamConnatser</th>
304
+ <th>JameEnder</th>
305
+ </tr>
306
+ <tr>
307
+ <td>
308
+ <a href="https://github.com/Timeraa"
309
+ ><img
310
+ height="64px"
311
+ src="https://avatars.githubusercontent.com/u/29104008"
312
+ /></a>
313
+ </td>
314
+ <td>
315
+ <a href="https://github.com/Phalangers"
316
+ ><img
317
+ height="64px"
318
+ src="https://avatars.githubusercontent.com/u/13227796"
319
+ /></a>
320
+ </td>
321
+ <td>
322
+ <a href="https://github.com/WilliamConnatser"
323
+ ><img
324
+ height="64px"
325
+ src="https://avatars.githubusercontent.com/u/43946230"
326
+ /></a>
327
+ </td>
328
+ <td>
329
+ <a href="https://github.com/JameEnder"
330
+ ><img
331
+ height="64px"
332
+ src="https://avatars.githubusercontent.com/u/47925045"
333
+ /></a>
334
+ </td>
335
+ <td>
336
+ <a href="https://github.com/tylim88"
337
+ ><img
338
+ height="64px"
339
+ src="https://avatars.githubusercontent.com/u/5227509"
340
+ /></a>
341
+ </td>
342
+ </tr>
343
+ </table>
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 * from "@ark/schema/config";
4
+ export { configure, type ArkConfig, type ArkSchemaRegistry } from "@ark/schema";
5
5
  export interface ArkTypeRegistryContents extends ArkSchemaRegistry {
6
6
  ambient: exportScope<Ark>;
7
7
  }
package/out/config.js CHANGED
@@ -1,2 +1 @@
1
- // eslint-disable-next-line @typescript-eslint/no-restricted-imports
2
- export * from "@ark/schema/config";
1
+ export { configure } from "@ark/schema";
@@ -1,4 +1,4 @@
1
- import { hasArkKind, isNode } from "@ark/schema";
1
+ import { hasArkKind } from "@ark/schema";
2
2
  import { domainOf, hasDomain, isThunk, objectKindOf, printable, throwParseError } from "@ark/util";
3
3
  import { parseObjectLiteral } from "./objectLiteral.js";
4
4
  import { parseString } from "./string.js";
@@ -12,24 +12,7 @@ export const parseInnerDefinition = (def, ctx) => {
12
12
  // resolutions like "this" or generic args
13
13
  return parseString(def, ctx);
14
14
  }
15
- // include parseConfigHash in cacheId to ensure that if global config
16
- // is updated, we reparse strings
17
- const cacheId = `${ctx.$.id}:${ctx.$.configSnapshot.hash}`;
18
- const scopeCache = (parseCache[cacheId] ??= {});
19
- const cachedResult = scopeCache[def];
20
- if (cachedResult) {
21
- // even though we know $ is the same, we still need to call bindReference
22
- // to ensure config changes have been reflected
23
- if (isNode(cachedResult))
24
- scopeCache[def] = ctx.$.bindReference(cachedResult);
25
- else {
26
- // update node element of optional or defaultable tuple
27
- ;
28
- cachedResult[0] = ctx.$.bindReference(cachedResult[0]);
29
- }
30
- return scopeCache[def];
31
- }
32
- // if we're parsing from scratch, we don't need to worry about binding
15
+ const scopeCache = (parseCache[ctx.$.id] ??= {});
33
16
  return (scopeCache[def] ??= parseString(def, ctx));
34
17
  }
35
18
  return hasDomain(def, "object") ?
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.0",
4
+ "version": "2.0.2",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -34,8 +34,8 @@
34
34
  "out"
35
35
  ],
36
36
  "dependencies": {
37
- "@ark/util": "0.35.0",
38
- "@ark/schema": "0.35.0"
37
+ "@ark/schema": "0.37.0",
38
+ "@ark/util": "0.37.0"
39
39
  },
40
40
  "publishConfig": {
41
41
  "access": "public"