Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
106 commits
Select commit Hold shift + click to select a range
cc5ce89
fix(ack)!: reject unsupported Draft-7 dependencies
leoafarias Dec 1, 2026
65310c1
fix(ack): bound hostname labels before Punycode decoding
leoafarias Dec 1, 2026
2f6d20e
fix(ack): preserve valid IDNA case across platforms
leoafarias Dec 1, 2026
26a07e2
fix(ack): preserve format annotations in Draft-7 export
leoafarias Dec 1, 2026
8c1ac3f
refactor(ack)!: remove duplicate list rule names
leoafarias Dec 1, 2026
01d910a
fix(ack): align email quoting and year zero format checks
leoafarias Dec 1, 2026
22b44ff
feat(ack)!: use one API for URI validation
leoafarias Dec 1, 2026
03f3f04
feat(ack)!: standardize built-in constraint keys
leoafarias Dec 1, 2026
eebac2d
test(json-schema-builder): check asserted format lowering errors
leoafarias Dec 1, 2026
134ac43
fix(ack): export SchemaOperation
leoafarias Dec 1, 2026
c4dc903
feat: expose Unicode normalization in schema import adapters
leoafarias Dec 1, 2026
4329ccb
refactor(ack): keep transparent schema contexts internal
leoafarias Dec 1, 2026
9b609fd
fix(ack)!: report nested warnings and handle nullable raw schemas
leoafarias Dec 1, 2026
20315ae
docs(ack): clarify JSON Schema import expectations
leoafarias Dec 1, 2026
697af54
feat(ack)!: share the concrete public rule annotation exports
leoafarias Dec 1, 2026
cb1bf68
docs(ack): clarify which public types support exhaustive switches
leoafarias Dec 1, 2026
b77b54e
fix(ack): preserve typed iteration in schema warning traversal
leoafarias Dec 1, 2026
db2795d
fix(generator): qualify generated model field reads
leoafarias Dec 1, 2026
7d96087
refactor(ack)!: internalize schema model rendering helpers
leoafarias Dec 1, 2026
d14c7a5
fix(generator): escape discriminator keys in emitted errors
leoafarias Dec 1, 2026
c0133ca
fix(generator): qualify class statics in constructor defaults
leoafarias Dec 1, 2026
1c09946
fix(generator)!: inherit sealed union branch naming defaults
leoafarias Dec 1, 2026
57b52ef
fix(generator): name inline JSON Schema objects in UpperCamelCase
leoafarias Dec 1, 2026
7158672
fix(generator)!: validate through class-owned schemas
leoafarias Dec 1, 2026
2c3836d
fix(generator): report invalid rule arguments at their source
leoafarias Dec 1, 2026
3c81ef9
feat(generator)!: derive Dart field names from schema-first JSON keys
leoafarias Dec 1, 2026
697e966
docs(ack): correct the datetime encode error type
leoafarias Dec 1, 2026
31c1ff8
docs(ack): print field errors in the quickstart and example
leoafarias Dec 1, 2026
1010d55
docs(ack): use validation messages in Flutter forms
leoafarias Dec 1, 2026
6b840df
docs(ack): show actual JSON Schema export output
leoafarias Dec 1, 2026
d1aea32
docs: compile public examples and correct invalid Dart snippets
leoafarias Dec 1, 2026
5c0377b
docs(ack): show root error names and JSON Pointers
leoafarias Dec 1, 2026
08cd397
docs: fill missing 1.x to 2.0 migration entries
leoafarias Dec 1, 2026
2261cbd
docs: align adapter guides with conversion and MCP behavior
leoafarias Dec 1, 2026
3de7a9f
docs: add unreleased notes for packages and Ack skills
leoafarias Dec 1, 2026
03aefb5
docs: add generator installation and MCP package metadata
leoafarias Dec 1, 2026
59f5dff
docs: reserve the unreleased Firebase AI changelog heading
leoafarias Dec 1, 2026
d2b8791
fix(generator)!: normalize union and generated model behavior
leoafarias Dec 1, 2026
d03b3fa
docs(generator): clarify reserved fields and shared builder migration
leoafarias Dec 1, 2026
98b2b81
test: satisfy linting in public snippet checks
leoafarias Dec 1, 2026
5328b43
test(generator): pin updated field reads and Set construction
leoafarias Dec 1, 2026
3ea3097
docs: complete the JSON Schema migration rows
leoafarias Dec 1, 2026
acfb12e
test(generator): expect nested generic fields to use model-owned schemas
leoafarias Dec 1, 2026
cea8b83
docs: complete the public API migration rows
leoafarias Dec 1, 2026
cb71395
docs(json-schema-builder): describe the local date codec value
leoafarias Dec 1, 2026
322f01c
test(generator): satisfy linting in wire key assertions
leoafarias Dec 1, 2026
e7bdaae
fix(generator): recognize rules without the public base type
leoafarias Dec 1, 2026
dccc05a
test(generator): pin class-owned collection schemas
leoafarias Dec 1, 2026
1500d07
test(ack): exercise legacy aliases through their public base
leoafarias Dec 1, 2026
a076566
style(json-schema): use the pinned SDK formatter
leoafarias Dec 1, 2026
548826c
test(generator): match each normalized wire key assertion
leoafarias Dec 1, 2026
09df6ce
fix(generator)!: reject custom class-owned schemas in sealed unions
leoafarias Dec 1, 2026
f0f513d
fix(ack)!: align built-in constraint keys with their rule families
leoafarias Dec 1, 2026
69f59fd
fix(json-schema): resolve warnings through nullable nodes and definit…
leoafarias Dec 1, 2026
10d95e8
fix(generator): qualify constructor defaults inherited through super …
leoafarias Dec 1, 2026
daf2a6b
docs: align validation and export guidance with Ack 2.0
leoafarias Dec 1, 2026
ad14c95
test(ack): cover schema rendering and context internals
leoafarias Dec 1, 2026
4534ee8
docs: add the NFKC normalization migration
leoafarias Dec 1, 2026
0c1e591
docs(ack): clarify internal schema keyword migration
leoafarias Dec 1, 2026
ee1460c
docs: group URI breaking notes under unreleased headings
leoafarias Dec 1, 2026
93be04f
docs(json-schema-builder): describe the import normalizer
leoafarias Dec 1, 2026
3979edd
docs(ack): move schema operation into error context guidance
leoafarias Dec 1, 2026
d477fea
fix(json-schema)!: reject dependencies when lowering to Draft-7
leoafarias Dec 1, 2026
b7c9259
fix(generator)!: prevent identifier shadowing in generated models
leoafarias Dec 1, 2026
f7e730f
docs(json-schema): clarify the default dialect and import stack limits
leoafarias Dec 1, 2026
72a64e5
fix(json-schema): bound Unicode label length before Punycode conversion
leoafarias Dec 1, 2026
a830948
fix(generator)!: unify schema-first key tokenization
leoafarias Dec 1, 2026
ef694e4
docs(generator): correct refinement and migration guidance
leoafarias Dec 1, 2026
552fd62
test(generator): cover wire keys, field names, and union diagnostics
leoafarias Dec 1, 2026
acbce0b
docs(ack): record the internal indexed schema constructor
leoafarias Dec 1, 2026
f6c5f7b
fix(generator): resolve union schema aliases in clean builds
leoafarias Dec 1, 2026
9b26114
fix(generator): use a null-aware prefix set element
leoafarias Dec 1, 2026
841f9a5
fix(json-schema)!: use ASCII-only case mapping for IDNA labels
leoafarias Dec 1, 2026
e70c605
chore(example): regenerate class-first runtime helpers
leoafarias Dec 1, 2026
dcfffe9
fix(generator): report missing Unicode normalization dependency
leoafarias Dec 1, 2026
7e7b3a5
fix(generator): show the missing union annotation hint in builds
leoafarias Dec 1, 2026
08fd358
test(docs): compile every classified public Dart snippet
leoafarias Dec 1, 2026
568440b
refactor(ack)!: make constraint attachment helpers internal
leoafarias Dec 1, 2026
67346fd
fix(json-schema): export versionless IP constraints with anyOf
leoafarias Dec 1, 2026
a3dfa01
fix(generator): report invalid discriminators on the union
leoafarias Dec 1, 2026
0d26441
fix(generator)!: express inherited case style through the public anno…
leoafarias Dec 1, 2026
2cef326
fix(ack): expose the abstract generated field schema type
leoafarias Dec 1, 2026
58c791f
test(generator): accept metadata on the model guide fence
leoafarias Dec 1, 2026
e67856e
fix(generator)!: normalize digits and acronyms in generated names
leoafarias Dec 1, 2026
3bd1d7a
fix(generator): preserve interpolated class-owned defaults
leoafarias Dec 1, 2026
46be36b
refactor(ack)!: restrict schema context implementations
leoafarias Dec 1, 2026
42f151e
fix(json-schema): relocate nested references in public nullable raw m…
leoafarias Dec 1, 2026
55ae444
fix(json-schema): show source locations in Draft-7 lowering errors
leoafarias Dec 1, 2026
19d9ed0
docs(json-schema): specify schema-model warning paths and order
leoafarias Dec 1, 2026
990f8f8
fix(generator)!: resolve inherited defaults in the receiving library
leoafarias Dec 1, 2026
b161685
refactor(ack)!: make transparent context construction private
leoafarias Dec 1, 2026
55ce7f1
docs(json-schema): clarify NFKC and ASCII-only case mapping
leoafarias Dec 1, 2026
9f03d79
fix(ack)!: validate constraints on schema copies
leoafarias Dec 1, 2026
4f68500
fix(generator)!: fall back on invalid translated JSON Schema names
leoafarias Dec 1, 2026
69c9582
fix(ack)!: name the local time constraint string_time
leoafarias Dec 1, 2026
c20d847
fix(generator)!: validate class-owned schemas before emitting facades
leoafarias Dec 1, 2026
77b9d02
fix(generator)!: reject explicit case style on schemas and libraries
leoafarias Dec 1, 2026
9dd7f71
fix(ack): infer the lazy context parent type
leoafarias Dec 1, 2026
d3c8eaa
docs(generator): clarify class-owned schema type requirements
leoafarias Dec 1, 2026
bed131d
docs(json-schema): link the import stack overflow issue
leoafarias Dec 1, 2026
8a84821
Merge remote-tracking branch 'origin/main' into release-readiness/e-p…
leoafarias Dec 1, 2026
5ba914a
Merge remote-tracking branch 'origin/release-readiness/e-public-api' …
leoafarias Dec 1, 2026
b84cc40
Merge origin/release-readiness/c-generator into release-readiness/d-j…
leoafarias Dec 1, 2026
9999102
test(generator): pin Unicode fixture to workspace toolchain
leoafarias Dec 1, 2026
ffc3037
Merge remote-tracking branch 'origin/release-readiness/d-json-schema'…
leoafarias Dec 1, 2026
863a6c5
Merge origin/main (E #272, C #274, D #271 squashes) into release-read…
leoafarias Dec 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ See [Conventional Commits](https://conventionalcommits.org) for commit guideline
* **Breaking:** Remove the deprecated beta validation annotation aliases and
their generic `kind` and `value` getters. Use the Is/Has rule annotations.

* Add the Ack skills plugin for Claude, Codex, and Cursor (#264).

## 2.0.0-beta.3

* **Breaking:** Require Dart `>=3.13.0` and Flutter `>=3.47.0`.
Expand Down
14 changes: 11 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,17 @@ dart run melos run analyze
dart run melos run test
```

The full test flow checks the agent skill manifests and compiles the Dart
snippets from Markdown. To run just those checks with Flutter on `PATH`, use
`dart test test/documentation` after bootstrap.
The full test flow checks the agent skill manifests and compiles and exercises
their Dart examples. It also checks every Dart fence in `docs/**/*.mdx` and
`packages/*/README.md`. Public examples compile together, including generated
model parts. The compilation check also runs selected offline assertions.

Public Dart fences must contain a standalone `main()`, declare a wrapper with
`compile=<wrapper>` after the `dart` fence language, or have a visible
`**Compile check skipped:**` reason immediately before the fence. See
`test/documentation/public_snippet_wrappers.dart` for wrappers and their fixture
context. Run `dart test test/documentation` after bootstrap with Flutter on
`PATH`.

For code generation changes, also run:

Expand Down
11 changes: 5 additions & 6 deletions docs/api-reference/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ Base class for all schema types.
`SchemaTransformError` / `SchemaEncodeError`), while programmer `Error` values
are rethrown with their original stack trace.
- `Runtime? parse(Object? data, {String? debugName})`: Validates `data` and returns the value; throws `AckException` on failure.
- `SchemaResult<TOut> safeParseAs<TOut extends Object>(Object? data, TOut Function(Runtime?) map, {String? debugName})`: Parses and maps the validated value to `TOut`. Mapper `Exception`s become `SchemaTransformError` failures; mapper `Error` values are rethrown with their original stack trace.
- `SchemaResult<TOut> safeParseAs<TOut extends Object>(Object? data, TOut? Function(Runtime?) map, {String? debugName})`: Parses and maps the validated value. A mapper that returns `null` produces a successful result with that value. Mapper `Exception`s become `SchemaTransformError` failures. Mapper `Error` values are rethrown with their original stack trace.
- `TOut parseAs<TOut extends Object>(Object? data, TOut Function(Runtime?) map, {String? debugName})`: Throwing variant of `safeParseAs`.
- `SchemaResult<Boundary> safeEncode(Runtime? value, {String? debugName})`: Encodes a runtime value to the boundary representation, validating nested collection contents.
- `Boundary? encode(Runtime? value, {String? debugName})`: Throwing variant of `safeEncode`.
Expand Down Expand Up @@ -156,7 +156,6 @@ Schema for validating strings. See [String Validation](../core-concepts/validati
### Format Validation

- `email()`: Must be valid email format
- `url()`: Must be valid URL format (alias for `uri()`)
- `uri()`: Must be a valid absolute URI with a scheme and host
- `uuid()`: Must be valid UUID format
- `ip({int? version})`: Must be valid IP address (version 4 or 6)
Expand Down Expand Up @@ -354,7 +353,7 @@ here. For `Ack.discriminated(...)` constraints, see
[Model Code Generation](../core-concepts/typesafe-schemas.mdx#schema-first-unions).

**Example:**
```dart
```dart compile=reference-user
import 'package:ack/ack.dart';

part 'user.g.dart';
Expand Down Expand Up @@ -425,7 +424,7 @@ Class projection is a later step: `discard` is only for tolerant, read-only
consumers, while models that round-trip unknown keys must use `capture` and may
select the target map with `captureField`.

```dart
```dart compile=reference-account
import 'package:ack/ack.dart';

part 'account.g.dart';
Expand Down Expand Up @@ -534,7 +533,7 @@ reverse direction. See [Codecs](../core-concepts/codecs.mdx).

**Built-in codecs:**

- `Ack.date()` → `CodecSchema<String, DateTime>` (ISO `YYYY-MM-DD` ↔ local-midnight `DateTime`)
- `Ack.date()` → `CodecSchema<String, DateTime>` (ISO `YYYY-MM-DD` ↔ local `DateTime(year, month, day)`)
- `Ack.datetime()` → `CodecSchema<String, DateTime>` (ISO 8601 ↔ UTC
`DateTime`; leap-second strings are rejected because Dart cannot represent
them)
Expand Down Expand Up @@ -563,7 +562,7 @@ In class-first `@Schemable()` models, use `sealed class JsonMaybe<T>` (`JsonAbse
`generateAckSchemaLibrary` returns an `AckJsonSchemaLibrary` containing
`source`, `effectiveDocument`, and `widenedPointers`. All parameters are named:

```dart
```dart compile=generator-signature
AckJsonSchemaLibrary generateAckSchemaLibrary({
required Object? document,
required Uri documentUri,
Expand Down
29 changes: 19 additions & 10 deletions docs/core-concepts/codecs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ title: Codecs

Your API sends a timestamp as an ISO string, but your code wants a `DateTime`. A codec handles that round-trip: it validates the incoming string, decodes it into the Dart type you actually use, and encodes it back when you send data out.

```dart
```dart compile=body
final when = Ack.datetime(); // CodecSchema<String, DateTime>

final dt = when.parse('2026-01-01T00:00:00Z'); // decode: String -> DateTime
Expand Down Expand Up @@ -35,7 +35,7 @@ Ack ships codecs for the most common boundary conversions:
| `Ack.uri()` | `String` ↔ `Uri` | absolute URI (scheme + host) |
| `Ack.duration()` | milliseconds `int` ↔ `Duration` | whole milliseconds |

```dart
```dart compile=body
final schema = Ack.object({
'startsAt': Ack.datetime(),
'website': Ack.uri(),
Expand Down Expand Up @@ -63,7 +63,7 @@ preserved.

Create a codec from any input schema with `Ack.codec(...)`, providing a `decode` function (boundary → runtime) and an `encode` function (runtime → boundary):

```dart
```dart compile=body
final csv = Ack.codec<String, String, List<String>>(
input: Ack.string(),
decode: (s) => s.split(','),
Expand All @@ -78,7 +78,7 @@ The three type arguments are the boundary type, the input schema's runtime type,

Call `.codec<R>(...)` on an existing schema to add a reversible conversion:

```dart
```dart compile=body
final trimmed = Ack.string().codec<String>(
decode: (s) => s.trim(),
encode: (s) => s,
Expand All @@ -93,14 +93,14 @@ midnight, Dart may construct this value with a later time of day.

Use `encode` (throws on failure) or `safeEncode` (returns a `SchemaResult`):

```dart
```dart compile=body
final result = Ack.datetime().safeEncode(DateTime.utc(2026));
if (result.isOk) {
print(result.getOrThrow()); // 2026-01-01T00:00:00.000Z
}
```

Both methods take a value of the schema's runtime type. During encoding,
Both methods take `Runtime?`. The schema determines whether it accepts `null`. During encoding,
schemas validate untyped nested lists and maps, including those produced by
`jsonDecode`, and apply the numeric coercions of the relevant schemas. Parse
values first when they need a codec's decoder, such as a date-time string that
Expand All @@ -109,8 +109,10 @@ must become a `DateTime`.
Errors surface as typed [`SchemaError`](./error-handling.mdx) values:

- `SchemaTransformError` — a `decode` function threw during parsing.
- `SchemaEncodeError` — encoding failed (for example, a one-way `transform`, or a
runtime invariant violation such as a non-UTC `DateTime` for `Ack.datetime()`).
- `SchemaEncodeError` — encoding failed, for example through a one-way
`transform`.
- `SchemaValidationError` — a codec runtime rule failed, such as passing a
non-UTC `DateTime` to `Ack.datetime()`.

An `Error` thrown by a `decode` (or `transform`) or `encode` function is a
programming bug, not bad data, so it propagates out of `parse` / `safeParse` and
Expand All @@ -127,8 +129,15 @@ Constraints added to a codec validate its **runtime** values, which the encoder
may map to something else entirely, so they are enforced locally but not
published: the export omits the keyword and `toSchemaModel().warnings` reports a
`codec_runtime_constraint_not_exported` warning. Put rules the wire should
advertise on the input schema instead — `Ack.string().minLength(5).codec(...)`
exports `minLength: 5`, while `Ack.string().codec(...).minLength(5)` does not.
advertise on the input schema. This codec exports `minLength: 5`.

```dart compile=body
final wireMinimumLength = Ack.string().minLength(5).codec<String>(
decode: (value) => value,
encode: (value) => value,
);
print(wireMinimumLength.toJsonSchema());
```
`Ack.duration()` is the exception: its boundary is the milliseconds its `min()`
and `max()` already compare, so those constraints do export.

Expand Down
12 changes: 6 additions & 6 deletions docs/core-concepts/configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Fields in [`Ack.object`](./schemas.mdx#object) are required and non-nullable by
default. Use `.optional()` when a field may be omitted, `.nullable()` when a
present field may be `null`, or both when either state is valid.

```dart
```dart compile=body
Ack.object({
'id': Ack.integer(),
'nickname': Ack.string().optional(),
Expand All @@ -30,7 +30,7 @@ presence and nullability matrix.

Control how extra fields are handled with the `additionalProperties` parameter in [`Ack.object`](./schemas.mdx#object).

```dart
```dart compile=body
// Reject extra properties (default)
Ack.object({'id': Ack.integer()});
// or explicitly:
Expand All @@ -55,14 +55,14 @@ value, not a missing key: it fails unless the field is also nullable, in which
case `.nullable().withDefault(value)` parses it as the default too. Parsing
`null` with a `withDefault` schema directly returns the default.

```dart
```dart compile=settings
final settingsSchema = Ack.object({
'theme': Ack.enumString(['light', 'dark']).withDefault('light'),
'pageSize': Ack.integer().min(1).max(100).withDefault(20),
});
```

```dart
```dart compile=use-settings
settingsSchema.parse({}); // {'theme': 'light', 'pageSize': 20}
settingsSchema.safeParse({'theme': null}); // fails: theme is not nullable
```
Expand Down Expand Up @@ -103,7 +103,7 @@ field is required.
Attach a description with `.describe()` when the schema is also used for JSON
Schema export or adapter packages.

```dart
```dart compile=library
final userIdSchema = Ack.string()
.uuid()
.describe('Stable identifier for a user account');
Expand All @@ -116,7 +116,7 @@ such as `.matches()`, can replace that message inline. Use `.constrain()` to
provide a message for a reusable custom constraint. See [Custom error
messages](./error-handling.mdx#custom-error-messages).

```dart
```dart compile=library
final usernameSchema = Ack.string().matches(
r'^[a-z0-9_]+$',
message: 'Use lowercase letters, numbers, and underscores only.',
Expand Down
27 changes: 15 additions & 12 deletions docs/core-concepts/error-handling.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ When validation fails, you want to know what went wrong and where. `safeParse()`
- `result.map((value) => ...)`: Transforms the success value and leaves failures untouched.
- `result.ifOk((value) { ... })` / `result.ifFail((error) { ... })`: Runs a side effect for just one case.

```dart
```dart compile=body
import 'package:ack/ack.dart';

final schema = Ack.string().minLength(5);
Expand Down Expand Up @@ -60,7 +60,7 @@ the error structure and represents unsupported diagnostic values as strings.
A `SchemaContext.operation` is either `SchemaOperation.parse` or
`SchemaOperation.encode`. Both values are available from `package:ack/ack.dart`.

```dart
```dart compile=body
final userSchema = Ack.object({
'name': Ack.string(),
'age': Ack.integer().min(18),
Expand Down Expand Up @@ -100,7 +100,7 @@ Each `SchemaError` subtype carries specific information about why validation fai

Raised when the input type doesn't match the expected schema type.

```dart
```dart compile=body
final schema = Ack.string();
final result = schema.safeParse(42); // Number instead of string

Expand All @@ -116,7 +116,7 @@ if (result.isFail) {

Raised when the value violates one or more validation constraints (such as `minLength`, `min`, or `email`).

```dart
```dart compile=body
final schema = Ack.string().minLength(5).email();
final result = schema.safeParse('abc');

Expand All @@ -136,7 +136,7 @@ if (result.isFail) {

Raised when validation fails within nested objects or lists. Contains a list of child errors.

```dart
```dart compile=body
final schema = Ack.object({
'name': Ack.string().minLength(2),
'age': Ack.integer().min(0),
Expand All @@ -163,7 +163,7 @@ if (result.isFail) {

Raised when custom validation logic added via `.refine()` fails.

```dart
```dart compile=body
final schema = Ack.integer().refine(
(value) => value % 2 == 0,
message: 'Must be an even number',
Expand All @@ -183,7 +183,7 @@ Raised when a `.transform()` callback throws an exception.

Callbacks receive the non-null validated runtime value; null handling belongs to the surrounding `nullable`/`withDefault` configuration. `SchemaTransformError` fires when the callback itself throws — for example, when the input passes validation but the conversion fails:

```dart
```dart compile=body
final schema = Ack.string().transform((value) {
final parsed = int.tryParse(value);
if (parsed == null) throw FormatException('Not numeric: $value');
Expand All @@ -201,15 +201,18 @@ if (result.isFail) {

### `SchemaEncodeError`

Raised when `encode()` or `safeEncode()` can't turn a runtime value back into its boundary form — for example, encoding a one-way `transform`, or a value that breaks a codec's invariant (such as a non-UTC `DateTime` for `Ack.datetime()`). Its `kind` field says which case occurred.
Raised when an encoder cannot turn a runtime value into its boundary form,
such as encoding through a one-way `transform`. Its `kind` identifies the
failure. A codec runtime validation rule produces `SchemaValidationError`.
For example, `Ack.datetime()` rejects a non-UTC `DateTime` with that type.

### Working with error types

Switch exhaustively on `SchemaError` by covering the error types below.
When listing the public concrete `AckSchema` types in a switch, include a
fallback branch for other implementations, including imported schemas.

```dart
```dart compile=error-data
final result = schema.safeParse(data);

if (result.isFail) {
Expand All @@ -236,12 +239,12 @@ if (result.isFail) {

In a `TextFormField` validator, return the error string directly:

```dart
```dart compile=field-validator
// Inside TextFormField validator
validator: (value) {
final result = someSchema.safeParse(value);
if (result.isFail) {
return result.getError().toString();
return result.getError().message;
}
return null;
}
Expand All @@ -253,7 +256,7 @@ validator: (value) {

Built-in constraints ship with default messages. For a custom message, pass `message:` to `.refine()`, or attach a constraint with `.constrain(..., message: ...)` — see [Custom Validation](../guides/custom-validation.mdx).

```dart
```dart compile=body
final schema = Ack.string().refine(
(value) => value.startsWith('ACK_'),
message: 'Value must start with ACK_',
Expand Down
20 changes: 12 additions & 8 deletions docs/core-concepts/json-serialization.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Validating incoming JSON data involves two steps:
1. **Decode JSON:** Use `dart:convert` to parse the JSON string into a Dart object (usually `Map<String, dynamic>` or `List`).
2. **Validate:** Pass the decoded object to your [Ack schema](./schemas.mdx)'s `safeParse()` method.

```dart
```dart compile=serialization
import 'dart:convert';
import 'package:ack/ack.dart';

Expand All @@ -41,7 +41,7 @@ void processApiResponse(String jsonString) {

if (result.isOk) {
// Structure and types are valid.
final validDataMap = result.getOrThrow();
final validDataMap = result.getOrThrow()!;
print('Valid JSON received: $validDataMap');

// Pass the validated map to your own model layer,
Expand All @@ -65,11 +65,11 @@ processApiResponse('not valid json'); // Decoding error

After successful validation, `result.getOrThrow()` returns a `Map<String, Object?>` whose structure and types match your schema. You can work with it directly, pass it into your own model class, or parse it into a generated immutable model:

```dart
```dart compile=serialized-map
final result = userSchema.safeParse(jsonData);

if (result.isOk) {
final validData = result.getOrThrow();
final validData = result.getOrThrow()!;

// Option 1: Work directly with the validated Map
final name = validData['name'] as String;
Expand All @@ -88,14 +88,14 @@ if (result.isOk) {

Once a schema is annotated with `@Schemable()` (see [Model Code Generation](./typesafe-schemas.mdx) for setup), parse JSON into a generated immutable model. Public `fromJson` / `toJson` cross the source Ack schema and map the validated runtime value directly onto stored fields.

```dart
```dart compile=serialized-model
import 'dart:convert';

final jsonData = jsonDecode('{"name": "Alice", "email": "alice@example.com"}');
final result = User.safeParse(jsonData);

if (result.isOk) {
final user = result.getOrThrow();
final user = result.getOrThrow()!;
print(user.name); // typed String
print(user.email); // typed String?
}
Expand All @@ -106,7 +106,9 @@ if (result.isOk) {
For schemas whose runtime values are already JSON-native (`String`, `num`,
`bool`, `List`, `Map`, and `null`), pass the validated value to `jsonEncode`:

```dart
```dart compile=serialized-map
import 'dart:convert';

final result = userSchema.safeParse({
'name': 'Alice',
'age': 30,
Expand All @@ -124,7 +126,9 @@ When a schema decodes boundary values into richer Dart types, encode through
the schema before calling `jsonEncode`. This applies each codec in the nested
structure and restores the JSON-safe boundary shape:

```dart
```dart compile=body
import 'dart:convert';

final eventSchema = Ack.object({
'name': Ack.string(),
'startsAt': Ack.datetime(),
Expand Down
Loading
Loading