arktype 3.0.0-beta.0 → 3.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 (51) hide show
  1. package/README.md +162 -10
  2. package/out/attributes.d.ts +4 -2
  3. package/out/checkers.d.ts +37 -2
  4. package/out/{chunk-Z4F45ZTE.js → chunk-2U2AWCI3.js} +3 -3
  5. package/out/{chunk-5NJWD7CO.js → chunk-5U2ZMDNI.js} +215 -140
  6. package/out/{chunk-KJ3C5GTL.js → chunk-DLWCO4RV.js} +1 -1
  7. package/out/{chunk-H4VRNKMB.js → chunk-E3DZXEZK.js} +1 -1
  8. package/out/{chunk-EJZJUYPI.js → chunk-EVCML554.js} +2 -2
  9. package/out/{chunk-KI2MOYNT.js → chunk-GPNK5353.js} +184 -32
  10. package/out/{chunk-LUXERINN.js → chunk-RAZ3TXOE.js} +40 -38
  11. package/out/chunk-SWOOCAHN.js +4 -0
  12. package/out/{chunk-ARTS74PX.js → chunk-UETB6YE2.js} +1 -1
  13. package/out/{chunk-JHDPSG5Y.js → chunk-UK5UGFOX.js} +6 -6
  14. package/out/{chunk-WEPQK3AY.js → chunk-VV6YDN2D.js} +441 -145
  15. package/out/codecs.js +5 -5
  16. package/out/config.d.ts +6 -3
  17. package/out/i18n.d.ts +1 -1
  18. package/out/i18n.js +1 -1
  19. package/out/index.d.ts +1 -1
  20. package/out/index.js +5 -5
  21. package/out/internal.d.ts +1 -0
  22. package/out/internal.js +11 -11
  23. package/out/island.js +2 -2
  24. package/out/islandDependency.js +11 -11
  25. package/out/keywords/functions.d.ts +24 -24
  26. package/out/keywords/keywords.d.ts +2 -2
  27. package/out/keywords/phrases.d.ts +23 -23
  28. package/out/keywords/ts.js +2 -2
  29. package/out/locale.d.ts +1 -1
  30. package/out/locales/de.js +1 -1
  31. package/out/locales/en.js +3 -3
  32. package/out/match.d.ts +5 -3
  33. package/out/mutatesInput.js +2 -2
  34. package/out/parser/definition.d.ts +54 -3
  35. package/out/parser/shift/operand/unenclosed.d.ts +3 -1
  36. package/out/parser/shift/operand/unresolvable.d.ts +68 -0
  37. package/out/parser/shift/operator/bounds.d.ts +4 -1
  38. package/out/runtime.d.ts +34 -25
  39. package/out/runtime.js +2 -2
  40. package/out/runtimeDevelopment.js +63 -4
  41. package/out/scope.d.ts +4 -4
  42. package/out/standalone/artifact.d.ts +4 -0
  43. package/out/standalone/baking.d.ts +8 -1
  44. package/out/standalone/sites.d.ts +6 -3
  45. package/out/standalone/values.d.ts +2 -0
  46. package/out/type.d.ts +42 -5
  47. package/package.json +49 -6
  48. package/skills/arktype/SKILL.md +211 -92
  49. package/skills/arktype/references/migrating.md +990 -255
  50. package/skills/arktype/references/precompile.md +8 -5
  51. package/out/chunk-EDEN5UWG.js +0 -4
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: arktype
3
- description: Write, review or debug runtime validation in TypeScript with ArkType (the `arktype` package), precompile it with `@ark/aot`, or migrate to it. Use when code imports from "arktype" or "@ark/aot"; when a TypeScript project needs to validate or parse untrusted data, like API request bodies, route handlers, form data, query params, env vars, JSON, config files, webhooks or LLM tool inputs; when adding a schema or validator; when setting up precompiled validation or fixing an error from `[plugin arktype]` or `arktype-precompile`; or when converting schemas from Zod, Valibot, TypeBox, Yup, Joi, Effect Schema or JSON Schema, e.g. "migrate this project from Zod to ArkType".
3
+ description: Write, review or debug runtime validation in TypeScript with ArkType (the `arktype` package), precompile it with `@ark/aot`, migrate to it, or upgrade it from ArkType 2. Use when code imports from "arktype" or "@ark/aot"; when a TypeScript project needs to validate or parse untrusted data, like API request bodies, route handlers, form data, query params, env vars, JSON, config files, webhooks or LLM tool inputs; when adding a schema or validator; when setting up precompiled validation or fixing an error from `[plugin arktype]` or `arktype-precompile`; when converting schemas from Zod, Valibot, TypeBox, Yup, Joi, Effect Schema or JSON Schema, e.g. "migrate this project from Zod to ArkType"; or when upgrading `arktype` from 2.x to 3.
4
4
  ---
5
5
 
6
6
  # ArkType
@@ -9,7 +9,32 @@ ArkType definitions are TypeScript type syntax, written as strings and objects,
9
9
 
10
10
  ## Migrating a project
11
11
 
12
- Migrating from Zod, Valibot, TypeBox, Yup, Joi, Effect Schema or JSON Schema? Read [references/migrating.md](references/migrating.md) first and follow its steps. It has the workflow, a table for each library and the defaults that differ. In short: rewrite each schema where it is, under the same name; keep what it accepts, rejects and returns identical; keep the code free of casts and `any`; before removing Zod, compare the schemas the tests don't cover with their originals on the same inputs, all of them if there's no `test` script; swap packages with the project's package manager; and run the `typecheck` and `test` scripts until both pass, without changing what a test expects. If asked to precompile too, set it up last, as [references/precompile.md](references/precompile.md) says.
12
+ Migrating from Zod, Valibot, TypeBox, Yup, Joi, Effect Schema or JSON Schema? Read [references/migrating.md](references/migrating.md) first and follow its steps. It has the workflow, the defaults that differ and a section of tables for each library: skip the sections for libraries the project doesn't use. In short:
13
+
14
+ 1. Write a config file that sets the old library's defaults, for Zod `configure({ onUndeclaredKey: "delete", exactOptionalPropertyTypes: false })`, and import it first in every file that creates a Type. In a package others install, or a project that already has ArkType Types, don't call `configure()`, which would change those Types too: the reference's step 2 has what to write instead.
15
+ 2. Rewrite each schema where it is, under the same name, keeping what it accepts, rejects and returns. Keep each custom message as a `message`.
16
+ 3. Keep the code free of casts and `any`.
17
+ 4. Before removing the old library, compare the schemas the tests don't cover with their originals on the same inputs, all of them if there's no `test` script.
18
+ 5. Swap packages with the project's package manager, then run the `typecheck` and `test` scripts until both pass, without changing what a test expects.
19
+
20
+ If asked to precompile too, set it up last, as [references/precompile.md](references/precompile.md) says.
21
+
22
+ ## Upgrading from ArkType 2
23
+
24
+ Follow https://arktype.io/docs/upgrading.md, whose checklist links each breaking change. What most code hits:
25
+
26
+ | ArkType 2 | ArkType 3 |
27
+ | -------------------------------------------------------------- | -------------------------------------------------------------------------- |
28
+ | `out[0]`, `out.length`, `out.map(...)`, `for (const e of out)` | the same on `out.issues` |
29
+ | `error.message`, for text naming its path | `out.summary`, a line per error; `error.message` now leaves the path out |
30
+ | `error.problem`, `{ problem: "..." }` | `error.message`, `{ message: "..." }`, reworded as a whole sentence |
31
+ | `out.flatProblemsByPath`, `out.byPath`, `out.flatByPath` | `flatMessagesByPath(out)`, `byPath(out)`, `flatByPath(out)` from `arktype` |
32
+ | `out.message`, `out.toTraversalError()` | `out.summary`, `new TraversalError(out)` |
33
+ | `error.hasCode("min")`, `error.toString()` | `error.code === "min"`, `error.message`: errors are plain objects |
34
+ | `ctx.errors.add(...)` | `ctx.error(...)` or `ctx.reject(...)` |
35
+ | `configure()` anywhere, the `clone` option | a config file imported before any Type is created; remove `clone` |
36
+
37
+ Then update snapshots of error text: a message no longer says what the value was, like `(was a number)`. Replace adapters written for ArkType 2 as [Integrations](#integrations) says: they pass valid data and fail on the first invalid input.
13
38
 
14
39
  ## Precompiling
15
40
 
@@ -46,7 +71,7 @@ declare const body: string
46
71
  const out = User(JSON.parse(body))
47
72
 
48
73
  if (out instanceof type.errors) {
49
- // every problem, one per line, e.g. `email must be an email address`
74
+ // every error, one per line, e.g. `email must be an email address`
50
75
  console.error(out.summary)
51
76
  } else {
52
77
  // out is narrowed to User
@@ -55,8 +80,8 @@ if (out instanceof type.errors) {
55
80
  ```
56
81
 
57
82
  - Calling a type returns the validated data or an `ArkErrors` instance. It does not throw, so check with `instanceof type.errors` rather than wrapping it in `try`/`catch`.
58
- - `ArkErrors` is not an array. Read individual errors from `out.issues`, e.g. `out.issues[0]` or `out.issues.map(e => e.message)`, each with a `path`, `code` and `message`.
59
- - `User.assert(data)` throws instead, for places where invalid data is a bug.
83
+ - `ArkErrors` is not an array. Read individual errors from `out.issues`, e.g. `out.issues[0]` or `out.issues.map(e => e.message)`, each with a `path`, `code` and `message`. A `message` leaves out its path, like `must be an email address`.
84
+ - `User.assert(data)` throws a `TraversalError` instead, for places where invalid data is a bug. In a `catch`, check `e instanceof TraversalError` (from `arktype`) and read `e.arkErrors.issues`.
60
85
  - Name types in PascalCase (`User`). Name types that transform their input in camelCase (`parseUser`), since they behave like functions.
61
86
  - `typeof User.infer` is the output type. `typeof User.inferIn` is the input type, which differs once a type transforms its input or has defaults.
62
87
 
@@ -64,48 +89,53 @@ if (out instanceof type.errors) {
64
89
 
65
90
  Strings use TypeScript's operators. Write string literals in single quotes inside the definition. Object types don't go in strings: `"{ a: string }"` doesn't parse, so write objects as objects and name them in a scope to reuse them in a string.
66
91
 
67
- | Want | Write |
68
- | ---------------------- | ------------------------------------------------------------------- |
69
- | optional key | `"key?": "string"` |
70
- | default (objects only) | `count: "number = 0"`, `plan: "'free' \| 'pro' = 'free'"` |
71
- | union | `"string \| number"`, `"'a' \| 'b'"` |
72
- | array | `"string[]"`, `"(string \| number)[]"` |
73
- | tuple | `["string", "number"]` |
74
- | number range | `"number > 0"`, `"0 <= number < 1"`, `"1 <= number.integer <= 100"` |
75
- | string or array length | `"string > 0"`, `"1 <= string <= 255"`, `"string[] >= 1"` |
76
- | divisibility | `"number % 2"` |
77
- | regex | `/^\d+$/` as a RegExp, or `"/^\\d+$/"` in a string |
78
- | record | `"Record<string, number>"` or `{ "[string]": "number" }` |
79
- | class instance | `"Date"`, `"Map"`, or `type.instanceOf(MyClass)` |
80
- | enum from values | `type.enumerated("a", "b")` or `type.valueOf(MyEnum)` |
81
- | array of a Type | `Item.array()`, `Item.array().atLeastLength(1)` |
82
- | custom error message | `type("string >= 8").configure({ message: "Too short" })` |
92
+ | Want | Write |
93
+ | ----------------------- | ------------------------------------------------------------------------ |
94
+ | optional key | `"key?": "string"` |
95
+ | default (objects only) | `count: "number = 0"`, `plan: "'free' \| 'pro' = 'free'"` |
96
+ | object or array default | `tags: "string[] = []"`, or a function: `Tags.default(() => [])` |
97
+ | union | `"string \| number"`, `"'a' \| 'b'"` |
98
+ | array | `"string[]"`, `"(string \| number)[]"` |
99
+ | tuple | `["string", "number"]` |
100
+ | number range | `"number > 0"`, `"0 <= number < 1"`, `"1 <= number.integer <= 100"` |
101
+ | string or array length | `"string > 0"`, `"1 <= string <= 255"`, `"string[] >= 1"` |
102
+ | divisibility | `"number % 2"` |
103
+ | regex | `/^\d+$/` as a RegExp, or `"/^\\d+$/"` in a string |
104
+ | record | `"Record<string, number>"` or `{ "[string]": "number" }` |
105
+ | class instance | `"Date"`, `"Map"`, or `type.instanceOf(MyClass)` |
106
+ | enum from values | `type.enumerated("a", "b")` or `type.valueOf(MyEnum)` |
107
+ | array of a Type | `Item.array()`, `Item.array().atLeastLength(1)` |
108
+ | custom error message | `type("string >= 8").configure({ message: "Use 8 or more characters" })` |
83
109
 
84
110
  A regex with flags, like `/^a$/i`, must be a RegExp. Bounds bind tighter than `|`, so `"string <= 500 | null"` is a string of at most 500 characters, or null.
85
111
 
86
- Common keywords: `string.email`, `string.uuid`, `string.url`, `string.ip`, `string.semver`, `string.date.iso`, `string.alphanumeric`, `number.integer`, `number.safe`, `number.epoch`. The full list is at https://arktype.io/docs/keywords.md.
112
+ Common keywords: `string.email`, `string.uuid`, `string.url`, `string.ip`, `string.semver`, `string.date.iso`, `string.alphanumeric`, `number.integer`, `number.safe`, `number.epoch`, and `object.json` for JSON data. The full list is at https://arktype.io/docs/keywords.md.
87
113
 
88
114
  ## From Zod
89
115
 
90
- What a Zod schema becomes. To migrate a project, follow [references/migrating.md](references/migrating.md), which has every library and the defaults that differ, like Zod removing undeclared keys where ArkType keeps them.
91
-
92
- | Zod | ArkType |
93
- | ----------------------------------------- | -------------------------------------------------------------- |
94
- | `z.object({ ... })` | `type({ ... })` |
95
- | `z.string().min(1).max(100)` | `"1 <= string <= 100"` |
96
- | `z.string().email()`, `.url()`, `.uuid()` | `"string.email"`, `"string.url"`, `"string.uuid"` |
97
- | `z.number().int().positive()` | `"number.integer > 0"` |
98
- | `z.enum(["a", "b"])` | `"'a' \| 'b'"` |
99
- | `.optional()`, `.nullable()` | `"key?": "T \| undefined"`, `"T \| null"` |
100
- | `.default(x)` | `key: "T = x"` or `key: T.default(x)` |
101
- | `z.array(T).min(1)` | `T.array().atLeastLength(1)`, or `"string[] >= 1"` in a string |
102
- | `z.union([A, B])`, `z.discriminatedUnion` | `A.or(B)` |
103
- | `.extend({ ... })` | `.merge({ ... })` |
104
- | `.refine(fn, message)` | `.narrow((v, ctx) => fn(v) \|\| ctx.reject({ message }))` |
105
- | `.transform(fn)` | `.pipe(fn)` |
106
- | `z.coerce.number()` | `type("unknown").pipe(Number).to("number")` |
107
- | `z.infer<typeof T>`, `z.input` | `typeof T.infer`, `typeof T.inferIn` |
108
- | `T.parse(x)`, `T.safeParse(x)` | `T.assert(x)`, `T(x)` checked with `instanceof type.errors` |
116
+ What a Zod schema becomes. To migrate a project, follow [references/migrating.md](references/migrating.md), which has every API, each library and the defaults that differ.
117
+
118
+ | Zod | ArkType |
119
+ | ----------------------------------------- | ------------------------------------------------------------------------ |
120
+ | `z.object({ ... })` | `type({ ... })`, which keeps undeclared keys unless configured |
121
+ | `z.string().min(1).max(100)` | `"1 <= string <= 100"` |
122
+ | `z.string().email()`, `.url()`, `.uuid()` | `"string.email"`, `"string.url"`, `"string.uuid"` |
123
+ | `z.number().int().positive()` | `"number.integer > 0"` |
124
+ | `z.enum(["a", "b"])` | `"'a' \| 'b'"` |
125
+ | `.optional()` on a key | `"key?": "T \| undefined"`, or `"key?": "T"` with Zod's defaults set |
126
+ | `.nullable()` | `"T \| null"` |
127
+ | `.default(x)` | `key: "T = x"` or `key: T.default(x)` |
128
+ | `z.array(T).min(1)` | `T.array().atLeastLength(1)`, or `"string[] >= 1"` in a string |
129
+ | `z.union([A, B])`, `z.discriminatedUnion` | `A.or(B)` |
130
+ | `.extend({ ... })`, `.pick({ a: true })` | `.merge({ ... })`, `.pick("a")` |
131
+ | `.refine(fn, message)` | `.narrow((v, ctx) => fn(v) \|\| ctx.reject({ message }))` |
132
+ | `.refine(fn, { message, path })` | `ctx.reject({ message, relativePath: path })` |
133
+ | `.min(1, "Name is required")` | `["string >= 1", "@", { message: "Name is required" }]` as a key's value |
134
+ | `.transform(fn)` | `.pipe(fn)` |
135
+ | `z.coerce.number()` | `type("unknown").pipe(Number).to("number")` |
136
+ | `z.infer<typeof T>`, `z.input` | `typeof T.infer`, `typeof T.inferIn` |
137
+ | `T.parse(x)`, `T.safeParse(x)` | `T.assert(x)`, `T(x)` checked with `instanceof type.errors` |
138
+ | `e instanceof ZodError` in a `catch` | `e instanceof TraversalError`, then `e.arkErrors.issues` |
109
139
 
110
140
  ## Composing types
111
141
 
@@ -129,10 +159,28 @@ const CustomerDraft = Customer.partial()
129
159
  Never interpolate a type into a string, as in ``type(`${Address}[]`)``. Use `Address.array()`, `Address.or(...)` and the other chained methods, or a tuple expression like `[Address, "[]"]`.
130
160
 
131
161
  - `.merge()` adds keys and replaces existing ones. `.and()` intersects, and throws when a key's types conflict.
132
- - To share keys between types, merge a base Type. To reuse a pattern across Types, define a Generic: `const Page = type("<t>", { items: "t[]", total: "number" })`, called as `Page(Item)`.
133
- - A helper can compose Types by taking a `Type<t>` and calling its methods, which type-checks without casts: `const withId = <t extends object>(T: Type<t>) => T.and({ id: "string" })`. In a precompiled project, keep its body to one expression, or consts and one `return`, and call it with Types the build knows, like `withId(User)`. A helper that passes a generic definition to `type()` needs casts.
134
- - A function that accepts any Type takes `type.Any`, not `Type<any>`. To keep the output type, like a form-action wrapper that validates and passes the data on, make it generic: `<T extends type.Any>(schema: T, action: (data: T["infer"]) => void)`. To embed the Type it receives in a new definition, take `type.Any<t>`: `const page = <t>(item: type.Any<t>) => type({ items: item.array(), total: "number" })`.
162
+ - `.merge()`, `"..."`, `.pick()`, `.omit()` and `.partial()` drop a `.narrow()` on the object they read, or throw if it also deletes undeclared keys. Keep the keys in a Type of their own, derive from that, and add each `.narrow()` last.
163
+ - To share keys between types, merge a base Type, or `.pick()` them: `User.get("nick")` is the key's Type without its `?` or its default. To reuse a pattern across Types, define a Generic: `const Page = type("<t>", { items: "t[]", total: "number" })`, called as `Page(Item)`. In a Generic's body, `Omit`, `Pick`, `Partial`, `Required` and `Merge` do what the methods of those names do: `const Create = type("<t extends object>", "Omit<t, 'id'>")`.
135
164
  - `.as<T>()` is a cast. To infer a narrower type, use `.narrow()` with a type predicate, e.g. `(s): s is \`data-${string}\` => s.startsWith("data-")`.
165
+ - A definition built at runtime goes to `type.raw`, which infers nothing, then gets its type: `type.raw(Object.fromEntries(FLAGS.map(flag => [flag, "boolean"]))).as<Record<Flag, boolean>>()`.
166
+
167
+ A function that takes a Type types its parameter by what it does with it:
168
+
169
+ | The function | Signature |
170
+ | ------------------------------------------- | -------------------------------------------------------------------------------------------------- |
171
+ | validates and returns the data | `<t>(schema: { assert: (data: unknown) => t }, data: unknown): t`, or as a `class Repo<t>`'s field |
172
+ | returns the errors rather than throwing | `<t>(schema: (data: unknown) => t \| ArkErrors, data: unknown)`, checked with `instanceof` |
173
+ | needs the Type itself, with its output type | `<T extends type.Any>(schema: T): T["infer"]` |
174
+ | calls `.and()`, `.or()` or `.array()` on it | `<t extends object>(T: Type<t>) => T.and({ id: "string" })` |
175
+ | puts it in a new definition | `<t>(item: type.Any<t>) => type({ items: item.array(), total: "number" })` |
176
+ | reads its `.props` | `(T: Type<Record<string, unknown>>) => T.props.map(prop => prop.key)` |
177
+ | picks, omits, merges or makes partial | not a function: a Generic, as above |
178
+ | only stores or forwards it | `type.Any`, not `Type<any>` |
179
+
180
+ - On a `type.Any` parameter, a method given a definition, like `T.or("null")` or `T.and({ ... })`, infers `any` with no error, and so does calling it. Annotate the call: `const out: T["infer"] | type.errors = schema(data)`.
181
+ - The `t` of a `type.Any<t>` isn't the output type once a Type has a default or a transform. `T["infer"]` is.
182
+ - A Type exported from a scope isn't a `Type<t>`, so pass it as `type(types.User)`. A Generic takes it as it is.
183
+ - In a precompiled project, keep a helper's body to one expression, or consts and one `return`, and call it with a Type the build knows, like `User`. A helper that passes a generic definition to `type()` needs casts.
136
184
 
137
185
  ## Parsing and transforming
138
186
 
@@ -168,12 +216,13 @@ const Env = type({
168
216
  Other morph keywords: `string.trim`, `string.lower`, `string.upper`, `string.numeric.parse`, `string.date.parse`, `string.date.iso.parse`, `string.url.parse`.
169
217
 
170
218
  - A `.parse` keyword accepts only strings. When the value may already be parsed, keep both in a union: `"number | string.numeric.parse"`.
219
+ - A check after a transform goes in `.to()`: `type("string.trim").to("string > 0")`.
171
220
  - A union can't include a morph whose input overlaps another branch, so `type("unknown").pipe(Number).or("undefined")` throws. Start the morph from the narrowest input, like `"string.numeric.parse | undefined"`, or handle the other case inside the pipe.
172
221
  - A default is an input, so a morph's default is what it parses: `flag: type("'true' | 'false'").pipe(s => s === "true").default("false")`.
173
222
 
174
223
  ## Custom rules
175
224
 
176
- Use `.narrow()` when a rule involves more than one value. Return `true` to accept, or `ctx.reject()` to give a message and a path. A narrow on an object runs only once every key is valid, so its error is never reported alongside a key's.
225
+ Use `.narrow()` when a rule involves more than one value. Return `true` to accept, or `ctx.reject()` to say what was wrong and where: a `message`, one whole sentence like `"Passwords must match"`, at a `relativePath` from the value being narrowed.
177
226
 
178
227
  ```ts
179
228
  const Signup = type({
@@ -183,59 +232,80 @@ const Signup = type({
183
232
  (data, ctx) =>
184
233
  data.password === data.confirmPassword ||
185
234
  ctx.reject({
186
- expected: "identical to password",
187
- actual: "",
188
- path: ["confirmPassword"]
235
+ message: "Passwords must match",
236
+ relativePath: ["confirmPassword"]
189
237
  })
190
238
  )
191
239
  ```
192
240
 
241
+ - Use `relativePath`, not `path`. `path` is from the root of the data, so it names the wrong key once the object is nested or in an array.
242
+ - Always reject with text. Returning `false` reads `must be valid according to an anonymous predicate`.
243
+ - For several errors, call `ctx.error({ message, relativePath })` for each, then return `true`.
244
+ - A narrow on an object runs only once every key is valid, so its error is never reported alongside a key's.
245
+ - A narrow can't give a literal its own text. ArkType calls it on each literal the Type allows, like `false`, `null`, `undefined` or `'a'`, when the Type is defined, and removes those it rejects, so `type("boolean").narrow((v, ctx) => v || ctx.reject({ message: "Accept the terms" }))` reads `must be true`. Write the values allowed, with the message: `type("true").configure({ message: "Accept the terms" })`.
246
+
193
247
  ## Error messages
194
248
 
195
- `.configure({ message })` replaces a Type's whole message, and `.describe()` what follows "must be". Each applies wherever that Type is used, including a precompiled build. A message on a key's value applies when the value is wrong, not when the key is missing, which reads `terms must be "on" (was missing)`, or `terms must be "on"` precompiled. To use it then too, configure the `required` code in the config module, where its function receives the missing key's `propString` and the `valueMeta` of the key's whole value, so configure that value last, after any `.pipe()` or `.to()`:
249
+ There are two ways to say what's wrong. Choose by the text you have:
250
+
251
+ | The text is | Write it as | An issue's `message` | Its line of `out.summary` |
252
+ | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ----------------------- | ----------------------------- |
253
+ | a whole sentence, like any Zod message: `"Enter a valid email"` | `message`, in `.configure({ message })`, a `"@"` tuple or `ctx.reject({ message })` | `Enter a valid email` | `email: Enter a valid email` |
254
+ | what the value must be: `"a valid email"` | `.describe(text)`, `.configure({ expected: text })`, `ctx.reject(text)`, `ctx.mustBe(text)` | `must be a valid email` | `email must be a valid email` |
255
+
256
+ - A message from Zod, or any sentence a user reads, is always a `message`. Passed as a string to `ctx.reject()`, to `ctx.mustBe()`, to `.describe()`, as `expected` or as a string after `"@"`, it would read `must be Enter a valid email`.
257
+ - An issue's `message` is what a form library, or anything else reading the Type through Standard Schema, shows beside the field. `out.summary`, and the `TraversalError` `.assert()` throws, write a line for each error with its path.
258
+ - A `message` isn't composed into other text. What a Type is `expected` to be is: a union lists it, as in `must be a valid email or null`. So with `| null` or `| undefined`, configure the whole union, as in `["string.email | null", "@", { message }]`: a message on one branch is lost for a value of the wrong type. With `exactOptionalPropertyTypes: false`, an optional or defaulted key's value is such a union, so write `"role?": ["'admin' | 'user' | undefined", "@", { message }]`: a message on an enum, a literal or a boolean alone is never said there.
259
+ - A `message` on `string.date.parse`, `string.url.parse` or `string.json.parse` isn't said for a string that fails to parse. Check, then convert: `type("string.date").pipe(s => new Date(s)).configure({ message })`.
260
+
261
+ In a definition, a tuple with `"@"` configures a value where it's written, as Zod's `.min(1, "Name is required")` does. For a message per check, name the check after it, by its error code (`minLength`, `maxLength`, `pattern`, `min`, `max`, `divisor`), in the tuple or as `.configure()`'s second argument:
196
262
 
197
263
  ```ts
198
- import { configure } from "arktype/config"
199
-
200
- configure({
201
- required: {
202
- message: ctx =>
203
- typeof ctx.valueMeta.message === "string" ?
204
- ctx.valueMeta.message
205
- : `${ctx.propString} is required`
206
- }
264
+ const Invite = type({
265
+ name: ["string > 0", "@", { message: "Name is required" }],
266
+ email: ["string.email", "@", { message: "Enter a valid email" }],
267
+ password: type("string >= 8 & /[0-9]/")
268
+ .configure({ message: "Use 8 or more characters" }, "minLength")
269
+ .configure({ message: "Include a number" }, "pattern")
207
270
  })
271
+
272
+ // name: Name is required
273
+ // email: Enter a valid email
274
+ // password: Include a number
275
+ // password: Use 8 or more characters
276
+ const out = Invite({ name: "", email: "x", password: "short" })
208
277
  ```
209
278
 
210
- To show each message beside its field, group `out.issues` by `issue.path.join(".")`, keeping the first message for each key.
279
+ - A string `message` on a key's whole value, like `name`'s, is what the key says when its value is wrong, `undefined` included, and when the key is missing, so `Invite({})` reads the same for `name` and `email`. It covers Zod's `required_error`.
280
+ - Configure a whole-value message last, after any `.pipe()` or `.to()`: `type("'on'").pipe(() => true).configure({ message: "Accept the terms" })`.
281
+ - A message for one check leaves other errors with ArkType's text, like `password must be a string (was missing)`. To give those their own, name `"domain"` for a wrong type and `"self"` for a missing key.
282
+ - A code names every check of that kind in the Type, nested keys' included, so configure a key's value, not the object around it. An array's length and its elements' are both `minLength`: configure the length on its own Type and intersect, as in `type("unknown[] >= 1").configure({ message: "Add one" }, "minLength").and(Tag.array())`.
283
+ - Configure a whole-value message before per-check ones, since it replaces those configured earlier.
284
+ - After a `.pipe()` or `.to()`, a code doesn't reach the Type the output is checked with, and a whole-value or `"self"` message on the transformed Type replaces the ones inside it. Configure that Type before passing it: `type("string.trim").to(type("string > 0").configure({ message: "Name is required" }))`.
285
+ - Several failed checks report a pattern before a length. For an empty field to say `Email is required` first, as Zod's `.min(1, "...").email("...")` did, leave out the `>= 1` and choose by the value: `.configure({ message: e => (e.data === "" ? "Email is required" : "Enter a valid email") }, "pattern")`. For a length's message to come before a pattern's, write the pattern as a `.narrow()`, which runs once the length passes.
286
+
287
+ To show each message beside its field, group `out.issues` by `issue.path.join(".")`, keeping the first `issue.message` for each key.
211
288
 
212
289
  ## Recursive and cyclic types
213
290
 
214
- Use a scope, where definitions can reference each other by name.
291
+ A type that refers to itself uses `this`. Types that refer to each other go in a scope, where definitions reference each other by name:
215
292
 
216
293
  ```ts
217
- import { scope } from "arktype"
294
+ import { scope, type } from "arktype"
295
+
296
+ const TreeNode = type({ value: "number", children: "this[]" })
218
297
 
219
298
  const types = scope({
220
- TreeNode: {
221
- value: "number",
222
- children: "TreeNode[]"
223
- }
299
+ User: { name: "string", "posts?": "Post[]" },
300
+ Post: { title: "string", author: "User" }
224
301
  }).export()
225
302
 
226
- const tree = types.TreeNode({ value: 1, children: [] })
303
+ const post = types.Post({ title: "Hello", author: { name: "Ada" } })
227
304
  ```
228
305
 
229
- Don't wrap definitions inside a scope with `type()`. They're resolved within the scope, and `type()` would resolve them globally.
306
+ Don't wrap definitions inside a scope with `type()`. They're resolved within the scope, and `type()` would resolve them globally, so an alias there is `unresolvable`. For a `.narrow()` or a `.pipe()` inside a scope, write a tuple: `["Tag[]", ":", (tags, ctx) => ...]` or `["string", "=>", s => s.trim()]`. For JSON data, use the built-in `"string | number | boolean | null | object.json"` rather than a recursive type of your own.
230
307
 
231
- A type that only refers to itself can use `this`, as in `type({ name: "string", children: "this[]" })`. Types that refer to each other, like a JSON value and a JSON object, go in a scope:
232
-
233
- ```ts
234
- const json = scope({
235
- Json: "string | number | boolean | null | Json[] | JsonObject",
236
- JsonObject: { "[string]": "Json" }
237
- }).export()
238
- ```
308
+ TypeScript can't write an inferred cycle in a `.d.ts`: `tsc` declares it as `any`, or fails with `TS5088`. In a package or project whose declarations are emitted, write them with `npx arktype-precompile --declare` (from `@ark/aot`) instead, which names each cycle for its alias and changes nothing at runtime. See https://arktype.io/docs/precompile/advanced.md.
239
309
 
240
310
  ## Extra keys
241
311
 
@@ -248,38 +318,87 @@ const Stripped = type({ "+": "delete", name: "string" })
248
318
 
249
319
  To remove them everywhere, as Zod does, call `configure({ onUndeclaredKey: "delete" })` instead. `.merge()` takes `"+"` from the object merged in, so with per-object `"+"`, write `.merge({ "+": "delete", ... })`; with the global setting, merged objects keep deleting.
250
320
 
251
- An object that deletes keys, whether by `"+"` or by `configure`, transforms its input, so a union of such objects throws unless a key like a literal `kind` tells them apart.
321
+ An object that deletes keys, whether by `"+"` or by `configure`, or that has a default or a transform at a key, transforms its input. A union holding one throws a `ParseError` saying it's indeterminate when another branch could accept the same data: a second object with no literal key like `kind` to tell them apart, or an array, a `Date` or a `Record` beside it. Choose the branch in a `.pipe()` instead:
322
+
323
+ ```ts
324
+ const Item = type({ "+": "delete", id: "string" })
325
+ const Items = Item.array()
326
+
327
+ const OneOrMany = type("object").pipe(v =>
328
+ Array.isArray(v) ? Items(v) : Item(v)
329
+ )
330
+ ```
331
+
332
+ Where objects delete keys, don't `.narrow()` a union of them at an optional key or before `.or("null")`: its errors become one `union` issue at the union's path, without the failing key's path. Narrow the object holding the key, and reject with `relativePath: ["key"]`.
252
333
 
253
334
  ## Integrations
254
335
 
255
336
  - ArkType types are [Standard Schema](https://standardschema.dev), so they work directly with tRPC, oRPC, Hono and other libraries that accept one. The MCP TypeScript SDK takes them as a tool's `inputSchema` from its second major version, `@modelcontextprotocol/server`; `@modelcontextprotocol/sdk` accepts only Zod. react-hook-form takes them through `standardSchemaResolver` from `@hookform/resolvers/standard-schema`.
337
+ - For a model's structured output or a tool, the AI SDK takes a Type as `schema` or `inputSchema`. The OpenAI SDK takes one through `standardResponseFormat` and `standardFunction` from `openai/helpers/standard-schema` (6.49 or later, every key required), and the Anthropic SDK through `betaStandardSchemaOutputFormat` and `betaStandardSchemaTool` from `@anthropic-ai/sdk/helpers/beta/standard-schema` (0.121 or later). LangChain's `tool()` type-checks with a Type but throws when the tool runs: give it `schema: T.toJsonSchema()` and call `T.assert(input)` inside.
338
+ - Prefer a library's Standard Schema entry point (`standardSchemaResolver`, Hono's `sValidator` from `@hono/standard-validator`, Superforms' `standard()`) over an adapter written for ArkType 2 (`@hono/arktype-validator`, Superforms' `arktype()`, `arktypeResolver` before `@hookform/resolvers` 5), which fails on invalid input.
256
339
  - `User.toJsonSchema()` returns the equivalent JSON Schema. It throws for what JSON Schema can't express, like `Date`, `bigint`, a morph or a `.narrow()`. Handle those with a `fallback` keyed by the error's `code`, e.g. `{ fallback: { date: ctx => ({ ...ctx.base, type: "string", format: "date-time" }) } }`, or pass `{ fallback: annotatingFallback }` (exported from `arktype`) to write them as `x-arktype-*` keywords instead.
257
- - Global configuration (error messages, `onUndeclaredKey`, `numberAllowsInfinity`, and so on) goes through `configure` from `arktype/config`, in its own file, imported first by every file that creates a Type. Calling `configure` after any Type is created, even by reading a keyword like `type.number`, throws unless it changes nothing. See https://arktype.io/docs/configuration.md.
340
+ - A model reads what a tool's parameter means from its JSON Schema `description`, which `.describe("the name of a city")` writes. The same text is what the field's errors say it must be. On a Type with checks, `.describe(text, "self")` leaves each check its own error, like `must be at most 7`.
341
+ - Global configuration (error messages, `onUndeclaredKey`, `exactOptionalPropertyTypes`, `numberAllowsInfinity`, and so on) goes through `configure` from `arktype/config`, in its own file, imported first by every file that creates a Type. Calling `configure` after any Type is created, even by reading a keyword like `type.number`, throws unless it changes nothing. See https://arktype.io/docs/configuration.md.
258
342
 
259
343
  ## Check your work
260
344
 
261
- ArkType reports most mistakes in a definition as a TypeScript error at the definition, and the rest as a `ParseError` thrown when the definition runs. After writing or changing types, run the project's typecheck script (or `npx tsc --noEmit`) and its tests, then call each type on a valid and an invalid value and read the result.
345
+ ArkType reports most mistakes in a definition as a TypeScript error at the definition, and the rest as a `ParseError` thrown when the definition runs. After writing or changing types:
346
+
347
+ 1. Run the project's typecheck script, or `npx tsc --noEmit`.
348
+ 2. Call each new or changed type on a valid and an invalid value and read what it says, in a scratch file you delete afterwards:
349
+
350
+ ```ts
351
+ import { type } from "arktype"
352
+
353
+ const User = type({
354
+ name: ["string > 0", "@", { message: "Name is required" }],
355
+ "age?": "number.integer >= 0"
356
+ })
357
+
358
+ const check = (T: type.Any, valid: unknown, invalid: unknown) => {
359
+ const out = T(valid)
360
+ if (out instanceof type.errors) throw new Error(`rejected: ${out.summary}`)
361
+ const errors = T(invalid)
362
+ if (!(errors instanceof type.errors)) throw new Error("accepted invalid data")
363
+ // read each line: "must be Name is required" means a message was passed as `expected`
364
+ console.log(errors.summary)
365
+ }
366
+
367
+ check(User, { name: "Ada" }, { name: "", age: -1 })
368
+ ```
369
+
370
+ 3. Run the project's tests.
262
371
 
263
372
  ## Errors and their fixes
264
373
 
265
- | Error | Fix |
266
- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
267
- | `'a' is unresolvable` | quote a string literal, `"'a'"`, or use the keyword's full name: `number.integer`, `string.email`, `Date` |
268
- | `'{' is unresolvable` | write an object as an object, not in a string |
269
- | `'Type' is unresolvable` | don't interpolate a Type into a string; use `Item.array()`, `Item.or(...)` or `[Item, "[]"]` |
270
- | `'^' is unresolvable` | put a regex in slashes, `"/^a$/"` |
271
- | `Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple` | give the default in an object, `{ count: "number = 0" }` |
272
- | `Only required keys may specify default values` | drop the `?`: a key with a default may be missing |
273
- | `An unordered union of a type including a morph and a type with overlapping input is indeterminate` | narrow the morph's input so no other branch accepts it, as in `"string.numeric.parse \| undefined"`, or tell objects apart by a literal key |
274
- | `Intersection at a of string and number results in an unsatisfiable type` | `.and()` found conflicting keys; use `.merge()` to replace them |
275
- | `Index keys "a", "b" should be specified as named props` | write `Record<"a" \| "b", T>` as `{ a: T, b: T }` |
276
- | `configure() must be called before any Type is created` | import the module calling `configure()` before any module that creates a Type |
374
+ | Error | Fix |
375
+ | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
376
+ | `'a' is unresolvable`, or `'int' is unresolvable. Did you mean 'number.integer'?` | use the name it suggests, or quote a string literal, `"'a'"`. Keywords have full names: `number.integer`, `string.email`, `Date` |
377
+ | `Type definitions must be strings or objects (was Function)` | a class is `type.instanceOf(MyClass)` or a keyword like `"Date"`, and a predicate is `.narrow(fn)` |
378
+ | `configure() has no option 'clone'` | remove an option 3.0 dropped, like `clone`, or use the name the error suggests for a misspelled one |
379
+ | `problem was removed in 3.0; write message` | rename `problem` to `message` in `.configure()` and `ctx.reject()`, and write it as a whole sentence |
380
+ | `'{' is unresolvable` | write an object as an object, not in a string |
381
+ | `'Type' is unresolvable` | don't interpolate a Type into a string; use `Item.array()`, `Item.or(...)` or `[Item, "[]"]` |
382
+ | `'^\d+$' is unresolvable`, or part of another regex, like `'^'` | put a regex in slashes, `"/^\\d+$/"` |
383
+ | `Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple` | give the default in an object, `{ count: "number = 0" }` |
384
+ | `Only required keys may specify default values` | drop the `?`: a key with a default may be missing |
385
+ | `Argument of type 'never[]' is not assignable to parameter of type '() => ...'` at `.default([])` | an object or array default is a function, `.default(() => [])`, or `"string[] = []"` in a string |
386
+ | `An unordered union of a type including a morph and a type with overlapping input is indeterminate` | narrow the morph's input so no other branch accepts it, as in `"string.numeric.parse \| undefined"`; for objects that delete keys, see [Extra keys](#extra-keys) |
387
+ | `merge operand must be an object (was (In: { ... }) => To<...>)`, or `pick`, `omit`, `partial` | the object has a `.narrow()` and deletes undeclared keys: call the method on the object before its `.narrow()`, then add the narrow |
388
+ | `Intersection at a of string and number results in an unsatisfiable type` | `.and()` found conflicting keys; use `.merge()` to replace them |
389
+ | `Index keys "a", "b" should be specified as named props` | write `Record<"a" \| "b", T>` as `{ a: T, b: T }` |
390
+ | `configure() must be called before any Type is created` | import the module calling `configure()` before any module that creates a Type |
391
+ | `Must use import to load ES Module: .../arktype/out/index.js`, from Jest | arktype ships ES modules only: add `transformIgnorePatterns: ["/node_modules/(?!(\\.pnpm\|arktype\|arkregex\|arksets\|@ark)/)"]` and a transform that reads JavaScript, like the `ts-jest/presets/js-with-ts` preset |
392
+ | an error message reading `must be Enter a valid email` | a sentence was passed as `expected`; pass it as `message` |
277
393
 
278
394
  ## Mistakes to avoid
279
395
 
280
396
  - `number` rejects `NaN`, `Infinity` and `-Infinity`. Allow them in one type with `"number | number.Infinity | number.NegativeInfinity"` (or `number.NaN`), or everywhere with `configure({ numberAllowsInfinity: true })`.
281
- - Don't mutate the argument of a `.pipe()` callback. It's the caller's data; the `clone` option that used to copy it no longer exists.
282
- - An optional key can be missing, but not present with the value `undefined`, mirroring TypeScript's `exactOptionalPropertyTypes`. Write `"key?": "string | undefined"` to allow both.
397
+ - An array passes an object whose keys are all optional, and a `Record` its elements fit, like `"Record<string, unknown>"`. To reject it, add `.narrow((o, ctx) => !Array.isArray(o) || ctx.mustBe("an object"))`.
398
+ - Validation is synchronous. An async `.narrow()` is a type error, and an async `.pipe()` puts its promise in the output, where an error it reports after an `await` is lost. Run async checks on the validated data.
399
+ - Don't mutate the argument of a `.pipe()` callback. It's the caller's data; the `clone` option that used to copy it no longer exists. Output shares what a Type didn't change with its input too, where Zod returns copies, so copy a parsed array before sorting or pushing to it.
400
+ - An optional key can be missing, but not present with the value `undefined`, mirroring TypeScript's `exactOptionalPropertyTypes`. An object built like `{ DEBUG: process.env.DEBUG }` holds `undefined` for an unset variable, and a default doesn't replace it either. Write `"key?": "string | undefined"` to allow both, or set `configure({ exactOptionalPropertyTypes: false })` where the project's tsconfig doesn't enable that option.
401
+ - With `"sideEffects": false` in `package.json`, a bundler drops `import "./arktype.config.ts"`, so the bundle runs without the config. List the file: `"sideEffects": ["./src/arktype.config.ts"]`.
283
402
  - Don't hand-write a TypeScript interface next to the type. Derive it with `typeof T.infer`, so the two can't drift.
284
403
  - An invalid definition is a TypeScript error at the definition itself, with a message saying what's wrong. Fix it there rather than casting it away.
285
404
  - An `ArkErrors` may find its issues when first read, so they describe the data as it is then. Read `out.summary` or `out.issues` before the validated data can change, as reactive form state, an Immer draft or an `await` before reporting allow.