From 8c1ac3f8c26eace62603f265c9149aec8b085d33 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 08:54:36 -0500 Subject: [PATCH 01/57] refactor(ack)!: remove duplicate list rule names Release-readiness item E1. Use the default for Q1. --- docs/api-reference/index.mdx | 8 ++++---- docs/core-concepts/schemas.mdx | 4 ++-- docs/core-concepts/validation.mdx | 10 +++++----- docs/getting-started/migration-guide.mdx | 1 + docs/guides/common-recipes.mdx | 4 ++-- docs/guides/json-schema-integration.mdx | 2 +- packages/ack/CHANGELOG.md | 3 +++ .../extensions/list_schema_extensions.dart | 16 ++------------- .../core_concepts_schemas_examples_test.dart | 4 ++-- ...ore_concepts_validation_examples_test.dart | 9 +++------ .../guides_common_recipes_examples_test.dart | 4 ++-- .../overview_doc_examples_test.dart | 6 +++--- .../list_rule_aliases_removed.dart.txt | 9 +++++++++ .../json_schema_import_public_api_test.dart | 8 ++++++++ .../ack/test/reference_semantics_test.dart | 2 +- .../list_schema_extensions_test.dart | 20 +++++++++---------- packages/ack_firebase_ai/CHANGELOG.md | 6 ++++++ ...firebase_ai_response_json_schema_test.dart | 6 +++--- ...irebase_ai_response_json_schema_cases.dart | 6 +++--- packages/ack_generator/CHANGELOG.md | 6 ++++++ .../integration/ack_infer_graph_test.dart | 2 +- .../ack_infer_runtime_build_test.dart | 2 +- packages/ack_json_schema_builder/CHANGELOG.md | 6 ++++++ .../example/example.dart | 6 +++--- .../test/to_json_schema_builder_test.dart | 2 +- 25 files changed, 88 insertions(+), 64 deletions(-) create mode 100644 packages/ack/test/fixtures/public_api/list_rule_aliases_removed.dart.txt diff --git a/docs/api-reference/index.mdx b/docs/api-reference/index.mdx index ed6d8699..8c1cf300 100644 --- a/docs/api-reference/index.mdx +++ b/docs/api-reference/index.mdx @@ -203,10 +203,10 @@ Schema for validating booleans. Validates `true` and `false` values strictly — Schema for validating arrays. See [List Validation](../core-concepts/validation.mdx#list-constraints). -- `minItems(int min)`: Minimum number of items (alias: `minLength`) -- `maxItems(int max)`: Maximum number of items (alias: `maxLength`) -- `exactLength(int exact)`: Exact number of items (alias: `length`) -- `nonEmpty()`: List must have at least one item (alias: `notEmpty`) +- `minItems(int min)`: Minimum number of items +- `maxItems(int max)`: Maximum number of items +- `length(int exact)`: Exact number of items +- `notEmpty()`: List must have at least one item - `unique()`: All items must be unique ## `ObjectSchema` diff --git a/docs/core-concepts/schemas.mdx b/docs/core-concepts/schemas.mdx index e5557cfe..451ee104 100644 --- a/docs/core-concepts/schemas.mdx +++ b/docs/core-concepts/schemas.mdx @@ -108,8 +108,8 @@ final tagsSchema = Ack.list(Ack.string()); // With constraints final itemsSchema = Ack.list(Ack.string()) - .minLength(1) - .maxLength(10) + .minItems(1) + .maxItems(10) .unique(); // List of objects diff --git a/docs/core-concepts/validation.mdx b/docs/core-concepts/validation.mdx index fca108ac..82824500 100644 --- a/docs/core-concepts/validation.mdx +++ b/docs/core-concepts/validation.mdx @@ -271,16 +271,16 @@ Ack.number().finite() Apply these to [`Ack.list()`](./schemas.mdx#list) schemas. -### `minLength(int min)` +### `minItems(int min)` Requires at least `min` items. ```dart -Ack.list(Ack.string()).minLength(1) +Ack.list(Ack.string()).minItems(1) ``` -### `maxLength(int max)` +### `maxItems(int max)` Requires at most `max` items. ```dart -Ack.list(Ack.integer()).maxLength(10) +Ack.list(Ack.integer()).maxItems(10) ``` ### `length(int count)` @@ -290,7 +290,7 @@ Ack.list(Ack.boolean()).length(5) ``` ### `notEmpty()` -Requires a non-empty list. Equivalent to `minLength(1)`. +Requires a non-empty list. Equivalent to `minItems(1)`. ```dart Ack.list(Ack.object({})).notEmpty() ``` diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 9b3d2838..e2cc1c53 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -168,6 +168,7 @@ and errors: | `ack_generator\|ack_models` & `ack_generator\|ack_model_json` in `build.yaml` | `2.0.0` | `ack_generator:ack_generator` (plus optional `ack_generator:ack_json_schema` for `.schema.json` files) | | `@AckType()` `*Type` extension type, `.args`, `ModelType.parse(...)` | `2.0.0` | Generated `Model` class with typed fields, `Model.parse(...)`, `Model.safeParse(...)`, `Model.fromJson(...)`, `model.toJson()` | | `Ack.enumCodec(MyEnum.values)` | `2.0.0` | `Ack.enumValues(MyEnum.values)` | +| `ListSchema.minLength`, `maxLength`, `exactLength`, `nonEmpty` | `2.0.0` | Use `minItems`, `maxItems`, `length`, and `notEmpty`, respectively. | | `schema.toMap()` | `2.0.0` | `schema.toJsonSchema()` or `schema.toSchemaModel()` | | `server.registerAckModelTool(...)` (`ack_mcp_dart`) | `2.0.0` | `server.registerAckTool(name, input: Model.schema, callback: ...)`; return a `CallToolResult` from the callback | | `convertAckSchemaModelToBuilder(model)` (`ack_json_schema_builder`) | `2.0.0` | `schema.toJsonSchemaBuilder()` | diff --git a/docs/guides/common-recipes.mdx b/docs/guides/common-recipes.mdx index 0c0a449a..8f00fcba 100644 --- a/docs/guides/common-recipes.mdx +++ b/docs/guides/common-recipes.mdx @@ -88,14 +88,14 @@ final cartSchema = Ack.object({ 'productId': Ack.string(), 'quantity': Ack.integer().positive(), 'price': Ack.double().positive(), - })).minLength(1).maxLength(50), + })).minItems(1).maxItems(50), }); // Tags with max 5 items final postSchema = Ack.object({ 'title': Ack.string().minLength(5).maxLength(100), 'content': Ack.string().minLength(10), - 'tags': Ack.list(Ack.string()).maxLength(5), + 'tags': Ack.list(Ack.string()).maxItems(5), }); ``` diff --git a/docs/guides/json-schema-integration.mdx b/docs/guides/json-schema-integration.mdx index 8a4bd3d5..e44a10ea 100644 --- a/docs/guides/json-schema-integration.mdx +++ b/docs/guides/json-schema-integration.mdx @@ -651,7 +651,7 @@ final shapeSchema = Ack.discriminated( // Nested arrays and objects final complexSchema = Ack.object({ - 'users': Ack.list(userSchema).minLength(1), + 'users': Ack.list(userSchema).minItems(1), 'metadata': Ack.object({ 'version': Ack.string(), 'tags': Ack.list(Ack.string()).unique(), diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 5fa627cc..dbc16fe8 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -2,6 +2,9 @@ ### Breaking +* **Breaking:** Use `minItems`, `maxItems`, `length`, and `notEmpty` for + lists. The duplicate list method names are removed. + * **Breaking:** International hostname and email format checks no longer apply NFKC normalization by default. Pass `unicodeNormalizer: nfkc` from `package:unorm_dart` to `Ack.fromJsonSchema()` to keep the earlier diff --git a/packages/ack/lib/src/schemas/extensions/list_schema_extensions.dart b/packages/ack/lib/src/schemas/extensions/list_schema_extensions.dart index df2b81c7..f598a192 100644 --- a/packages/ack/lib/src/schemas/extensions/list_schema_extensions.dart +++ b/packages/ack/lib/src/schemas/extensions/list_schema_extensions.dart @@ -13,33 +13,21 @@ extension ListSchemaExtensions< return withConstraint(ComparisonConstraint.listMinItems(n)); } - /// Alias for [minItems]. - ListSchema minLength(int n) => minItems(n); - /// Adds a constraint that the list must have no more than [n] items. ListSchema maxItems(int n) { return withConstraint(ComparisonConstraint.listMaxItems(n)); } - /// Alias for [maxItems]. - ListSchema maxLength(int n) => maxItems(n); - /// Adds a constraint that the list must have exactly [n] items. - ListSchema exactLength(int n) { + ListSchema length(int n) { return withConstraint(ComparisonConstraint.listExactItems(n)); } - /// Alias for [exactLength]. - ListSchema length(int n) => exactLength(n); - /// Adds a constraint that the list must not be empty. - ListSchema nonEmpty() { + ListSchema notEmpty() { return minItems(1); } - /// Alias for [nonEmpty]. - ListSchema notEmpty() => nonEmpty(); - /// Adds a constraint that all items in the list must be unique. ListSchema unique() { return withConstraint(ListUniqueItemsConstraint()); diff --git a/packages/ack/test/documentation/core_concepts_schemas_examples_test.dart b/packages/ack/test/documentation/core_concepts_schemas_examples_test.dart index a80ecbc9..a9551e9f 100644 --- a/packages/ack/test/documentation/core_concepts_schemas_examples_test.dart +++ b/packages/ack/test/documentation/core_concepts_schemas_examples_test.dart @@ -85,8 +85,8 @@ void main() { expect(tagsSchema.safeParse(['news', 'tech']).isOk, isTrue); final itemsSchema = Ack.list(Ack.string()) - .minLength(1) - .maxLength(3) + .minItems(1) + .maxItems(3) .unique(); expect(itemsSchema.safeParse(['a', 'b']).isOk, isTrue); expect(itemsSchema.safeParse([]).isFail, isTrue); diff --git a/packages/ack/test/documentation/core_concepts_validation_examples_test.dart b/packages/ack/test/documentation/core_concepts_validation_examples_test.dart index 36ff0ae7..5d4d5134 100644 --- a/packages/ack/test/documentation/core_concepts_validation_examples_test.dart +++ b/packages/ack/test/documentation/core_concepts_validation_examples_test.dart @@ -116,17 +116,14 @@ void main() { group('List constraints', () { test('length and uniqueness', () { + expect(Ack.list(Ack.string()).minItems(1).safeParse([]).isFail, isTrue); expect( - Ack.list(Ack.string()).minLength(1).safeParse([]).isFail, - isTrue, - ); - expect( - Ack.list(Ack.string()).minLength(1).safeParse(['item']).isOk, + Ack.list(Ack.string()).minItems(1).safeParse(['item']).isOk, isTrue, ); expect( - Ack.list(Ack.integer()).maxLength(2).safeParse([1, 2, 3]).isFail, + Ack.list(Ack.integer()).maxItems(2).safeParse([1, 2, 3]).isFail, isTrue, ); expect( diff --git a/packages/ack/test/documentation/guides_common_recipes_examples_test.dart b/packages/ack/test/documentation/guides_common_recipes_examples_test.dart index e7306dda..10d15185 100644 --- a/packages/ack/test/documentation/guides_common_recipes_examples_test.dart +++ b/packages/ack/test/documentation/guides_common_recipes_examples_test.dart @@ -99,7 +99,7 @@ void main() { 'quantity': Ack.integer().positive(), 'price': Ack.double().positive(), }), - ).minLength(1).maxLength(50), + ).minItems(1).maxItems(50), }); expect( @@ -115,7 +115,7 @@ void main() { final postSchema = Ack.object({ 'title': Ack.string().minLength(5).maxLength(100), 'content': Ack.string().minLength(10), - 'tags': Ack.list(Ack.string()).maxLength(5), + 'tags': Ack.list(Ack.string()).maxItems(5), }); expect( diff --git a/packages/ack/test/documentation/overview_doc_examples_test.dart b/packages/ack/test/documentation/overview_doc_examples_test.dart index b84e7403..59e61c50 100644 --- a/packages/ack/test/documentation/overview_doc_examples_test.dart +++ b/packages/ack/test/documentation/overview_doc_examples_test.dart @@ -53,7 +53,7 @@ void main() { 'quantity': Ack.integer().positive(), 'price': Ack.double().positive(), }), - ).minLength(1), + ).minItems(1), 'total': Ack.double().positive(), }); @@ -93,7 +93,7 @@ void main() { 'quantity': Ack.integer().positive(), 'price': Ack.double().positive(), }), - ).minLength(1), + ).minItems(1), 'total': Ack.double().positive(), }); @@ -204,7 +204,7 @@ void main() { 'quantity': Ack.integer().positive(), 'price': Ack.double().positive(), }), - ).minLength(1), + ).minItems(1), 'total': Ack.double().positive(), }); diff --git a/packages/ack/test/fixtures/public_api/list_rule_aliases_removed.dart.txt b/packages/ack/test/fixtures/public_api/list_rule_aliases_removed.dart.txt new file mode 100644 index 00000000..a8dfa96c --- /dev/null +++ b/packages/ack/test/fixtures/public_api/list_rule_aliases_removed.dart.txt @@ -0,0 +1,9 @@ +import 'package:ack/ack.dart'; + +void main() { + final list = Ack.list(Ack.string()); + list.minLength(1); + list.maxLength(2); + list.exactLength(2); + list.nonEmpty(); +} diff --git a/packages/ack/test/json_schema_import_public_api_test.dart b/packages/ack/test/json_schema_import_public_api_test.dart index 253988ce..2f0ca721 100644 --- a/packages/ack/test/json_schema_import_public_api_test.dart +++ b/packages/ack/test/json_schema_import_public_api_test.dart @@ -22,6 +22,14 @@ Future _compileFixture(String name) { } void main() { + test('list schemas expose a single name for each length rule', () async { + final result = await _compileFixture('list_rule_aliases_removed'); + expect(result.exitCode, isNot(0)); + for (final name in ['minLength', 'maxLength', 'exactLength', 'nonEmpty']) { + expect(result.stderr, contains("The method '$name' isn't defined")); + } + }); + test( 'public barrel does not expose the removed top-level importer', () async { diff --git a/packages/ack/test/reference_semantics_test.dart b/packages/ack/test/reference_semantics_test.dart index 8bc58d2b..d81f05f2 100644 --- a/packages/ack/test/reference_semantics_test.dart +++ b/packages/ack/test/reference_semantics_test.dart @@ -103,7 +103,7 @@ void main() { }); test('exports exact list lengths as item-count constraints', () { - final schema = Ack.list(Ack.string()).exactLength(2); + final schema = Ack.list(Ack.string()).length(2); expect(schema.safeParse(['one']).isFail, isTrue); expect(schema.toJsonSchema(), { diff --git a/packages/ack/test/schemas/extensions/list_schema_extensions_test.dart b/packages/ack/test/schemas/extensions/list_schema_extensions_test.dart index fc34efcd..1d706825 100644 --- a/packages/ack/test/schemas/extensions/list_schema_extensions_test.dart +++ b/packages/ack/test/schemas/extensions/list_schema_extensions_test.dart @@ -3,7 +3,7 @@ import 'package:test/test.dart'; void main() { group('ListSchemaExtensions', () { - group('minLength', () { + group('minItems', () { test('should pass if list is long enough', () { final schema = ListSchema(StringSchema()).minItems(2); final result = schema.safeParse(['a', 'b']); @@ -24,7 +24,7 @@ void main() { }); }); - group('maxLength', () { + group('maxItems', () { test('should pass if list is short enough', () { final schema = ListSchema(StringSchema()).maxItems(2); final result = schema.safeParse(['a', 'b']); @@ -45,15 +45,15 @@ void main() { }); }); - group('exactLength', () { - test('length should pass if string is exact length', () { - final schema = Ack.list(Ack.string()).exactLength(2); + group('length', () { + test('length should pass if the list has the exact length', () { + final schema = Ack.list(Ack.string()).length(2); final result = schema.safeParse(['a', 'b']); expect(result.isOk, isTrue); }); - test('length should fail if string is not exact length', () { - final schema = Ack.list(Ack.string()).exactLength(2); + test('length should fail if the list has a different length', () { + final schema = Ack.list(Ack.string()).length(2); final result = schema.safeParse(['a']); expect(result.isOk, isFalse); expect( @@ -66,15 +66,15 @@ void main() { }); }); - group('nonEmpty', () { + group('notEmpty', () { test('nonempty should pass if list is not empty', () { - final schema = Ack.list(Ack.string()).nonEmpty(); + final schema = Ack.list(Ack.string()).notEmpty(); final result = schema.safeParse(['a']); expect(result.isOk, isTrue); }); test('nonempty should fail if list is empty', () { - final schema = Ack.list(Ack.string()).nonEmpty(); + final schema = Ack.list(Ack.string()).notEmpty(); final result = schema.safeParse([]); expect(result.isOk, isFalse); expect( diff --git a/packages/ack_firebase_ai/CHANGELOG.md b/packages/ack_firebase_ai/CHANGELOG.md index 76e7ddd3..d524b4dd 100644 --- a/packages/ack_firebase_ai/CHANGELOG.md +++ b/packages/ack_firebase_ai/CHANGELOG.md @@ -1,3 +1,9 @@ +## Unreleased + +### Changed + +* Use the canonical Ack list constraint names in adapter fixtures. + ## 2.0.0-beta.3 ### Breaking diff --git a/packages/ack_firebase_ai/test/live_firebase_ai_response_json_schema_test.dart b/packages/ack_firebase_ai/test/live_firebase_ai_response_json_schema_test.dart index ff579023..c89ed0c7 100644 --- a/packages/ack_firebase_ai/test/live_firebase_ai_response_json_schema_test.dart +++ b/packages/ack_firebase_ai/test/live_firebase_ai_response_json_schema_test.dart @@ -94,7 +94,7 @@ List<_LiveFirebaseAiSchemaCase> _liveFirebaseAiSchemaCases() => [ Ack.enumString(['unknown']), ]), }, additionalProperties: false), - ).minLength(2).maxLength(3), + ).minItems(2).maxItems(3), }, additionalProperties: false).describe('Issue triage response'), prompt: 'Return issue triage JSON only. Use category "bug", confidence 87, ' @@ -148,8 +148,8 @@ List<_LiveFirebaseAiSchemaCase> _liveFirebaseAiSchemaCases() => [ schema: Ack.object({ 'id': Ack.string().uuid(), 'labels': Ack.list(Ack.enumString(['alpha', 'beta', 'stable'])) - .minLength(2) - .maxLength(2), + .minItems(2) + .maxItems(2), 'payload': Ack.any(), }, additionalProperties: true).describe('Flexible event response'), prompt: diff --git a/packages/ack_firebase_ai/test/support/firebase_ai_response_json_schema_cases.dart b/packages/ack_firebase_ai/test/support/firebase_ai_response_json_schema_cases.dart index a073183d..2d7c88af 100644 --- a/packages/ack_firebase_ai/test/support/firebase_ai_response_json_schema_cases.dart +++ b/packages/ack_firebase_ai/test/support/firebase_ai_response_json_schema_cases.dart @@ -154,8 +154,8 @@ List firebaseAiResponseJsonSchemaCases() => [ 'default', ], schema: Ack.list(Ack.string().uuid()) - .minLength(1) - .maxLength(3) + .minItems(1) + .maxItems(3) .unique() .withDefault(['00000000-0000-0000-0000-000000000000']), ), @@ -173,7 +173,7 @@ List firebaseAiResponseJsonSchemaCases() => [ 'name': Ack.string().minLength(2).maxLength(50).describe('Full name'), 'age': Ack.integer().min(0).max(120).optional(), 'role': Ack.enumString(['admin', 'member']), - 'tags': Ack.list(Ack.string()).minLength(1).maxLength(5).optional(), + 'tags': Ack.list(Ack.string()).minItems(1).maxItems(5).optional(), }, additionalProperties: false).describe('User payload'), ), AckSchemaResponseJsonSchemaCase( diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index cccdff65..5f36bc7e 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -1,3 +1,9 @@ +## Unreleased + +### Changed + +* Use the canonical Ack list constraint names in generator fixtures. + ## 2.0.0-beta.3 ### Breaking diff --git a/packages/ack_generator/test/integration/ack_infer_graph_test.dart b/packages/ack_generator/test/integration/ack_infer_graph_test.dart index 05d045ad..6c98d595 100644 --- a/packages/ack_generator/test/integration/ack_infer_graph_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_graph_test.dart @@ -609,7 +609,7 @@ final answer = Ack.anyOf([Ack.string(), Ack.number(), Ack.list(Ack.string())]); final interactionSchema = Ack.object({ 'value': Ack.anyOf([Ack.string(), Ack.integer(), Ack.boolean()]), 'maybe': Ack.anyOf([Ack.literal('none'), Ack.any()]).nullable(), - 'options': Ack.list(option).minLength(1).optional(), + 'options': Ack.list(option).minItems(1).optional(), 'values': Ack.map(answer).optional(), 'nested': Ack.anyOf([ Ack.lazy('word', () => Ack.enumString(['a', 'b'])), diff --git a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart index bf73fd0a..15f40601 100644 --- a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart @@ -257,7 +257,7 @@ final choiceOptionSchema = Ack.anyOf([ @Schemable() final choiceFieldSchema = Ack.object({ - 'options': Ack.list(choiceOptionSchema).minLength(1).optional(), + 'options': Ack.list(choiceOptionSchema).minItems(1).optional(), }); final opaqueValueSchema = Ack.string().codec( diff --git a/packages/ack_json_schema_builder/CHANGELOG.md b/packages/ack_json_schema_builder/CHANGELOG.md index c5ad40ff..3b85a862 100644 --- a/packages/ack_json_schema_builder/CHANGELOG.md +++ b/packages/ack_json_schema_builder/CHANGELOG.md @@ -1,3 +1,9 @@ +## Unreleased + +### Changed + +* Use `minItems` and `maxItems` in the list conversion example. + ## 2.0.0-beta.3 ### Breaking diff --git a/packages/ack_json_schema_builder/example/example.dart b/packages/ack_json_schema_builder/example/example.dart index 62c7b1a0..cbce7abe 100644 --- a/packages/ack_json_schema_builder/example/example.dart +++ b/packages/ack_json_schema_builder/example/example.dart @@ -25,7 +25,7 @@ void main() async { 'name': Ack.string().minLength(2), 'email': Ack.string().email(), }), - 'tags': Ack.list(Ack.string()).minLength(1).maxLength(10), + 'tags': Ack.list(Ack.string()).minItems(1).maxItems(10), 'published': Ack.boolean().optional(), }); @@ -41,8 +41,8 @@ void main() async { // Example 4: Array Schema print('\nExample 4: Array Schema'); final tagsSchema = Ack.list(Ack.string().minLength(1)) - .minLength(1) - .maxLength(5); + .minItems(1) + .maxItems(5); tagsSchema.toJsonSchemaBuilder(); print('Converted array schema with constraints'); diff --git a/packages/ack_json_schema_builder/test/to_json_schema_builder_test.dart b/packages/ack_json_schema_builder/test/to_json_schema_builder_test.dart index 72c7d9da..6ae5e3ed 100644 --- a/packages/ack_json_schema_builder/test/to_json_schema_builder_test.dart +++ b/packages/ack_json_schema_builder/test/to_json_schema_builder_test.dart @@ -116,7 +116,7 @@ void main() { }); test('converts array with minItems', () { - final schema = Ack.list(Ack.string()).minLength(1); + final schema = Ack.list(Ack.string()).minItems(1); final result = schema.toJsonSchemaBuilder(); expect(result, isNotNull); From 22b44ff0ba70a534f4f936163a3792c820237a09 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 08:57:11 -0500 Subject: [PATCH 02/57] feat(ack)!: use one API for URI validation Release readiness E1 and decision Q2. --- docs/api-reference/index.mdx | 2 +- docs/core-concepts/configuration.mdx | 2 +- docs/core-concepts/schemas.mdx | 2 +- docs/core-concepts/typesafe-schemas.mdx | 2 +- docs/core-concepts/validation.mdx | 6 ------ docs/getting-started/migration-guide.mdx | 3 ++- docs/guides/common-recipes.mdx | 2 +- packages/ack/CHANGELOG.md | 3 +++ packages/ack/lib/ack.dart | 1 - packages/ack/lib/src/annotations/constraints.dart | 12 +++--------- .../schemas/extensions/string_schema_extensions.dart | 7 ------- packages/ack/test/annotations/ack_model_test.dart | 1 - packages/ack/test/annotations/exports_test.dart | 6 ++---- .../ack/test/documentation/best_practices_test.dart | 2 +- .../core_concepts_schemas_examples_test.dart | 2 +- .../ack/test/documentation/error_catalog_test.dart | 2 +- .../ack/test/documentation/error_clarity_test.dart | 2 +- .../guides_common_recipes_examples_test.dart | 2 +- .../fixtures/public_api/uri_aliases_removed.dart.txt | 8 ++++++++ packages/ack/test/json_schema_conformance_test.dart | 4 ++-- .../ack/test/json_schema_import_public_api_test.dart | 11 +++++++++++ .../test/schemas/comprehensive_json_schema_test.dart | 2 +- .../extensions/string_schema_extensions_test.dart | 4 ++-- packages/ack_generator/CHANGELOG.md | 2 ++ .../lib/src/inference/schema_inference.dart | 3 --- .../test/integration/class_model_emitter_test.dart | 8 ++++---- .../test/integration/validate_alias_test.dart | 5 ----- .../ack_generator/test/src/ack_exports_test.dart | 1 - packages/ack_json_schema_builder/CHANGELOG.md | 2 ++ packages/ack_json_schema_builder/README.md | 2 +- .../ack/skills/build-data-classes-with-ack/SKILL.md | 2 +- .../ack/skills/using-ack/references/migrate-1x.md | 4 +++- 32 files changed, 57 insertions(+), 60 deletions(-) create mode 100644 packages/ack/test/fixtures/public_api/uri_aliases_removed.dart.txt diff --git a/docs/api-reference/index.mdx b/docs/api-reference/index.mdx index 8c1cf300..7c2c321f 100644 --- a/docs/api-reference/index.mdx +++ b/docs/api-reference/index.mdx @@ -406,7 +406,7 @@ compile-time error. - presence & nullability: `@IsRequired`, `@IsOptional`, `@IsNotNull` - numeric: `@HasMin`, `@HasMax`, `@IsMultipleOf`, `@IsPositive`, `@IsNegative` - strings: `@HasMinLength`, `@HasMaxLength`, `@HasMatch`, `@IsEmail`, `@IsNotEmpty` -- string formats: `@IsUrl`, `@IsUri`, `@IsUuid`, `@IsDate`, `@IsDateTime`, `@IsIp` (`version: 4` or `6` for one family) +- string formats: `@IsUri`, `@IsUuid`, `@IsDate`, `@IsDateTime`, `@IsIp` (`version: 4` or `6` for one family) - collections: `@IsNotEmpty`, `@HasMinItems`, `@HasMaxItems`, `@HasUniqueItems` diff --git a/docs/core-concepts/configuration.mdx b/docs/core-concepts/configuration.mdx index 5f417b7f..1c00090c 100644 --- a/docs/core-concepts/configuration.mdx +++ b/docs/core-concepts/configuration.mdx @@ -19,7 +19,7 @@ Ack.object({ 'id': Ack.integer(), 'nickname': Ack.string().optional(), 'middleName': Ack.string().nullable(), - 'avatarUrl': Ack.string().url().optional().nullable(), + 'avatarUrl': Ack.string().uri().optional().nullable(), }); ``` diff --git a/docs/core-concepts/schemas.mdx b/docs/core-concepts/schemas.mdx index 451ee104..fb958833 100644 --- a/docs/core-concepts/schemas.mdx +++ b/docs/core-concepts/schemas.mdx @@ -47,7 +47,7 @@ final usernameSchema = Ack.string() final emailSchema = Ack.string().email(); // URL validation -final websiteSchema = Ack.string().url(); +final websiteSchema = Ack.string().uri(); // Date/datetime strings final dateSchema = Ack.string().date(); // YYYY-MM-DD diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index 4696654e..9299a46b 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -392,7 +392,7 @@ Rule annotations follow the field type. `Is…` names what the value is, and - presence & nullability: `@IsRequired`, `@IsOptional`, `@IsNotNull`; - numeric: `@HasMin`, `@HasMax`, `@IsMultipleOf`, `@IsPositive`, `@IsNegative`; - strings: `@HasMinLength`, `@HasMaxLength`, `@HasMatch`, `@IsEmail`, `@IsNotEmpty`; -- string formats: `@IsUrl`, `@IsUri`, `@IsUuid`, `@IsDate`, `@IsDateTime`, `@IsIp` (`version: 4` or `6` for one family); +- string formats: `@IsUri`, `@IsUuid`, `@IsDate`, `@IsDateTime`, `@IsIp` (`version: 4` or `6` for one family); - lists and sets: `@IsNotEmpty`, `@HasMinItems`, `@HasMaxItems`, `@HasUniqueItems`. diff --git a/docs/core-concepts/validation.mdx b/docs/core-concepts/validation.mdx index 82824500..9e9d4e2b 100644 --- a/docs/core-concepts/validation.mdx +++ b/docs/core-concepts/validation.mdx @@ -148,12 +148,6 @@ Requires the string to end with `suffix`. Ack.string().endsWith('.dart') ``` -### `url()` -Alias for `uri()`. Requires a valid URL. -```dart -Ack.string().url() -``` - ### `ip({int? version})` Requires a valid IP address. Set `version` to `4` or `6` to restrict the version. ```dart diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index e2cc1c53..267229cb 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -147,7 +147,7 @@ and errors: | `@Pattern(r'...')` / `@Matches(r'...')` | `@Validate.matches(r'...')` | `@HasMatch(r'...')` (not anchored; use `^...$` for a full-string match) | | `@NotEmpty()` | `@Validate.notEmpty()` | `@IsNotEmpty()` (works on `String`, `List`, and `Set`) | | `@Email()` | `@Validate.email()` | `@IsEmail()` | -| `@Url()` | `@Validate.url()` | `@IsUrl()` | +| `@Url()` | `@Validate.url()` / `@IsUrl()` | `@IsUri()` | | `@Uri()` | `@Validate.uri()` | `@IsUri()` | | `@Uuid()` | `@Validate.uuid()` | `@IsUuid()` | | `@Date()` | `@Validate.date()` | `@IsDate()` | @@ -169,6 +169,7 @@ and errors: | `@AckType()` `*Type` extension type, `.args`, `ModelType.parse(...)` | `2.0.0` | Generated `Model` class with typed fields, `Model.parse(...)`, `Model.safeParse(...)`, `Model.fromJson(...)`, `model.toJson()` | | `Ack.enumCodec(MyEnum.values)` | `2.0.0` | `Ack.enumValues(MyEnum.values)` | | `ListSchema.minLength`, `maxLength`, `exactLength`, `nonEmpty` | `2.0.0` | Use `minItems`, `maxItems`, `length`, and `notEmpty`, respectively. | +| `StringSchema.url()` | Use `StringSchema.uri()` for the same validation and schema export. | | `schema.toMap()` | `2.0.0` | `schema.toJsonSchema()` or `schema.toSchemaModel()` | | `server.registerAckModelTool(...)` (`ack_mcp_dart`) | `2.0.0` | `server.registerAckTool(name, input: Model.schema, callback: ...)`; return a `CallToolResult` from the callback | | `convertAckSchemaModelToBuilder(model)` (`ack_json_schema_builder`) | `2.0.0` | `schema.toJsonSchemaBuilder()` | diff --git a/docs/guides/common-recipes.mdx b/docs/guides/common-recipes.mdx index 8f00fcba..e106f32e 100644 --- a/docs/guides/common-recipes.mdx +++ b/docs/guides/common-recipes.mdx @@ -176,7 +176,7 @@ import 'package:http/http.dart' as http; final githubUserSchema = Ack.object({ 'login': Ack.string(), 'id': Ack.integer(), - 'avatar_url': Ack.string().url(), + 'avatar_url': Ack.string().uri(), 'name': Ack.string().nullable(), 'email': Ack.string().email().nullable(), 'bio': Ack.string().nullable(), diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index dbc16fe8..d29cffb3 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -1,5 +1,8 @@ ## Unreleased +* **Breaking:** Replace `StringSchema.url()` with `uri()`, and `@IsUrl()` with + `@IsUri()`. URI validation and JSON Schema output are unchanged. + ### Breaking * **Breaking:** Use `minItems`, `maxItems`, `length`, and `notEmpty` for diff --git a/packages/ack/lib/ack.dart b/packages/ack/lib/ack.dart index 91815ea6..46e970d3 100644 --- a/packages/ack/lib/ack.dart +++ b/packages/ack/lib/ack.dart @@ -30,7 +30,6 @@ export 'src/annotations/constraints.dart' IsPositive, IsRequired, IsUri, - IsUrl, IsUuid, Validate; export 'src/annotations/schemable.dart'; diff --git a/packages/ack/lib/src/annotations/constraints.dart b/packages/ack/lib/src/annotations/constraints.dart index f67d251d..222ad08a 100644 --- a/packages/ack/lib/src/annotations/constraints.dart +++ b/packages/ack/lib/src/annotations/constraints.dart @@ -142,12 +142,6 @@ final class IsEmail extends AckRule { const IsEmail() : super._('email'); } -/// Adds `.url()` to an inferred string schema. -@Target({TargetKind.field, TargetKind.parameter}) -final class IsUrl extends AckRule { - const IsUrl() : super._('url'); -} - /// Adds `.uri()` to an inferred string schema. @Target({TargetKind.field, TargetKind.parameter}) final class IsUri extends AckRule { @@ -297,9 +291,9 @@ final class Validate { @Deprecated('Use @IsEmail instead. Validate is removed before Ack 2.0.0.') const factory Validate.email() = IsEmail; - /// Returns [IsUrl]. - @Deprecated('Use @IsUrl instead. Validate is removed before Ack 2.0.0.') - const factory Validate.url() = IsUrl; + /// Returns [IsUri]. + @Deprecated('Use @IsUri instead. Validate is removed before Ack 2.0.0.') + const factory Validate.url() = IsUri; /// Returns [IsUri]. @Deprecated('Use @IsUri instead. Validate is removed before Ack 2.0.0.') diff --git a/packages/ack/lib/src/schemas/extensions/string_schema_extensions.dart b/packages/ack/lib/src/schemas/extensions/string_schema_extensions.dart index 686d8633..3bcb0fd5 100644 --- a/packages/ack/lib/src/schemas/extensions/string_schema_extensions.dart +++ b/packages/ack/lib/src/schemas/extensions/string_schema_extensions.dart @@ -30,13 +30,6 @@ extension StringSchemaExtensions on StringSchema { return withConstraint(PatternConstraint.email()); } - /// Adds a constraint that the string must be a valid URI. - /// - /// This is an alias for [uri]. Validates absolute URIs with a scheme and host. - StringSchema url() { - return withConstraint(PatternConstraint.uri()); - } - /// Adds a constraint that the string must be a valid UUID. StringSchema uuid() { return withConstraint(PatternConstraint.uuid()); diff --git a/packages/ack/test/annotations/ack_model_test.dart b/packages/ack/test/annotations/ack_model_test.dart index 798d7307..94b5d4af 100644 --- a/packages/ack/test/annotations/ack_model_test.dart +++ b/packages/ack/test/annotations/ack_model_test.dart @@ -57,7 +57,6 @@ void main() { IsNegative(), IsNotEmpty(), IsEmail(), - IsUrl(), IsUri(), IsUuid(), IsDate(), diff --git a/packages/ack/test/annotations/exports_test.dart b/packages/ack/test/annotations/exports_test.dart index b9e00231..e7ee720d 100644 --- a/packages/ack/test/annotations/exports_test.dart +++ b/packages/ack/test/annotations/exports_test.dart @@ -45,7 +45,6 @@ void main() { HasMatch(r'^\d+$'), IsNotEmpty(), IsEmail(), - IsUrl(), IsUri(), IsUuid(), IsDate(), @@ -57,7 +56,7 @@ void main() { ack.IsUuid(), ]; - expect(values, hasLength(25)); + expect(values, hasLength(24)); expect(values.skip(2), everyElement(isA())); expect(AckUnknownPropertyPolicy.values, hasLength(3)); }); @@ -124,7 +123,6 @@ void main() { ack.HasMatch('^a'), ack.IsNotEmpty(), ack.IsEmail(), - ack.IsUrl(), ack.IsUri(), ack.IsUuid(), ack.IsDate(), @@ -138,7 +136,7 @@ void main() { expect(contact.email.address, 'ada@example.com'); expect(schemable.name, 'Contact'); expect(key.name, 'email_address'); - expect(rules, hasLength(22)); + expect(rules, hasLength(21)); expect((rules[10] as ack.HasMatch).pattern, '^a'); }, ); diff --git a/packages/ack/test/documentation/best_practices_test.dart b/packages/ack/test/documentation/best_practices_test.dart index b28008de..710829b6 100644 --- a/packages/ack/test/documentation/best_practices_test.dart +++ b/packages/ack/test/documentation/best_practices_test.dart @@ -78,7 +78,7 @@ void main() { } final configSchema = Ack.object({ - 'apiUrl': Ack.string().url(), + 'apiUrl': Ack.string().uri(), 'timeout': Ack.integer().positive(), 'retries': Ack.integer().min(0).max(5), }); diff --git a/packages/ack/test/documentation/core_concepts_schemas_examples_test.dart b/packages/ack/test/documentation/core_concepts_schemas_examples_test.dart index a9551e9f..768e7199 100644 --- a/packages/ack/test/documentation/core_concepts_schemas_examples_test.dart +++ b/packages/ack/test/documentation/core_concepts_schemas_examples_test.dart @@ -38,7 +38,7 @@ void main() { expect(emailSchema.safeParse('valid@example.com').isOk, isTrue); expect(emailSchema.safeParse('invalid-email').isFail, isTrue); - final websiteSchema = Ack.string().url(); + final websiteSchema = Ack.string().uri(); expect(websiteSchema.safeParse('https://example.com').isOk, isTrue); final dateSchema = Ack.string().date(); diff --git a/packages/ack/test/documentation/error_catalog_test.dart b/packages/ack/test/documentation/error_catalog_test.dart index e64015f0..b8cc91e1 100644 --- a/packages/ack/test/documentation/error_catalog_test.dart +++ b/packages/ack/test/documentation/error_catalog_test.dart @@ -141,7 +141,7 @@ void main() { examples.add( ErrorExample( - schema: Ack.string().url(), + schema: Ack.string().uri(), input: 'not-a-url', description: 'Invalid URL format', ), diff --git a/packages/ack/test/documentation/error_clarity_test.dart b/packages/ack/test/documentation/error_clarity_test.dart index 315599da..e6e3eef3 100644 --- a/packages/ack/test/documentation/error_clarity_test.dart +++ b/packages/ack/test/documentation/error_clarity_test.dart @@ -259,7 +259,7 @@ void main() { }, { 'name': 'URL format', - 'schema': Ack.string().url(), + 'schema': Ack.string().uri(), 'input': 'not-a-url', 'expectedHints': ['url', 'valid'], }, diff --git a/packages/ack/test/documentation/guides_common_recipes_examples_test.dart b/packages/ack/test/documentation/guides_common_recipes_examples_test.dart index 10d15185..34330229 100644 --- a/packages/ack/test/documentation/guides_common_recipes_examples_test.dart +++ b/packages/ack/test/documentation/guides_common_recipes_examples_test.dart @@ -203,7 +203,7 @@ void main() { final githubUserSchema = Ack.object({ 'login': Ack.string(), 'id': Ack.integer(), - 'avatar_url': Ack.string().url(), + 'avatar_url': Ack.string().uri(), 'name': Ack.string().nullable(), 'email': Ack.string().email().nullable(), 'bio': Ack.string().nullable(), diff --git a/packages/ack/test/fixtures/public_api/uri_aliases_removed.dart.txt b/packages/ack/test/fixtures/public_api/uri_aliases_removed.dart.txt new file mode 100644 index 00000000..88027f51 --- /dev/null +++ b/packages/ack/test/fixtures/public_api/uri_aliases_removed.dart.txt @@ -0,0 +1,8 @@ +import 'package:ack/ack.dart'; +import 'package:ack/annotations.dart' as annotations; + +void main() { + Ack.string().url(); + const IsUrl(); + const annotations.IsUrl(); +} diff --git a/packages/ack/test/json_schema_conformance_test.dart b/packages/ack/test/json_schema_conformance_test.dart index 8917fd5f..57009c06 100644 --- a/packages/ack/test/json_schema_conformance_test.dart +++ b/packages/ack/test/json_schema_conformance_test.dart @@ -72,7 +72,7 @@ void main() { }); test('string-url', () { - final ackSchema = Ack.string().url(); + final ackSchema = Ack.string().uri(); final ackOutput = ackSchema.toJsonSchema(); final zodReference = loadReferenceFixture('string-url'); expect(ackOutput, equals(zodReference)); @@ -593,7 +593,7 @@ void main() { }), 'image': Ack.object({ 'kind': Ack.literal('image'), - 'url': Ack.string().url(), + 'url': Ack.string().uri(), }), }, ).nullable(); diff --git a/packages/ack/test/json_schema_import_public_api_test.dart b/packages/ack/test/json_schema_import_public_api_test.dart index 2f0ca721..5c6a4e8d 100644 --- a/packages/ack/test/json_schema_import_public_api_test.dart +++ b/packages/ack/test/json_schema_import_public_api_test.dart @@ -22,6 +22,17 @@ Future _compileFixture(String name) { } void main() { + test('the URI rule is the only public name for URI validation', () async { + final result = await _compileFixture('uri_aliases_removed'); + expect(result.exitCode, isNot(0)); + expect(result.stderr, contains("The method 'url' isn't defined")); + final diagnostics = result.stderr as String; + expect( + RegExp("Couldn't find constructor 'IsUrl'").allMatches(diagnostics), + hasLength(2), + ); + }); + test('list schemas expose a single name for each length rule', () async { final result = await _compileFixture('list_rule_aliases_removed'); expect(result.exitCode, isNot(0)); diff --git a/packages/ack/test/schemas/comprehensive_json_schema_test.dart b/packages/ack/test/schemas/comprehensive_json_schema_test.dart index 9fe3df79..56354cc3 100644 --- a/packages/ack/test/schemas/comprehensive_json_schema_test.dart +++ b/packages/ack/test/schemas/comprehensive_json_schema_test.dart @@ -31,7 +31,7 @@ void main() { }); test('should validate URL format', () { - final schema = Ack.string().url(); + final schema = Ack.string().uri(); expect(schema.safeParse('https://example.com').isOk, isTrue); expect(schema.safeParse('not-a-url').isOk, isFalse); }); diff --git a/packages/ack/test/schemas/extensions/string_schema_extensions_test.dart b/packages/ack/test/schemas/extensions/string_schema_extensions_test.dart index 74900339..d6694785 100644 --- a/packages/ack/test/schemas/extensions/string_schema_extensions_test.dart +++ b/packages/ack/test/schemas/extensions/string_schema_extensions_test.dart @@ -90,13 +90,13 @@ void main() { }); test('url should pass for valid url', () { - final schema = StringSchema().url(); + final schema = StringSchema().uri(); final result = schema.safeParse('https://example.com'); expect(result.isOk, isTrue); }); test('url should fail for invalid url', () { - final schema = StringSchema().url(); + final schema = StringSchema().uri(); final result = schema.safeParse('not-a-url'); expect(result.isOk, isFalse); expect( diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 5f36bc7e..d80d4356 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -1,5 +1,7 @@ ## Unreleased +* **Breaking:** Replace `@IsUrl()` with `@IsUri()` and regenerate model parts. + ### Changed * Use the canonical Ack list constraint names in generator fixtures. diff --git a/packages/ack_generator/lib/src/inference/schema_inference.dart b/packages/ack_generator/lib/src/inference/schema_inference.dart index bbf24f90..04b47888 100644 --- a/packages/ack_generator/lib/src/inference/schema_inference.dart +++ b/packages/ack_generator/lib/src/inference/schema_inference.dart @@ -187,9 +187,6 @@ final class AckSchemaInference { case 'IsEmail': _require(declaration, type, annotation, isString, 'String field'); addScalarConstraint('.email()'); - case 'IsUrl': - _require(declaration, type, annotation, isString, 'String field'); - addScalarConstraint('.url()'); case 'IsUri': _require(declaration, type, annotation, isString, 'String field'); addScalarConstraint('.uri()'); diff --git a/packages/ack_generator/test/integration/class_model_emitter_test.dart b/packages/ack_generator/test/integration/class_model_emitter_test.dart index 086a240a..55dcb98b 100644 --- a/packages/ack_generator/test/integration/class_model_emitter_test.dart +++ b/packages/ack_generator/test/integration/class_model_emitter_test.dart @@ -370,7 +370,7 @@ final class Formats with _\$FormatsAck { required this.timestamp, }); - @IsUrl() + @IsUri() final String url; @IsUri() final String uri; @@ -386,7 +386,7 @@ final class Formats with _\$FormatsAck { outputs: { 'test_pkg|lib/formats.g.dart': decodedMatches( allOf([ - contains("'url': Ack.string().url()"), + contains("'url': Ack.string().uri()"), contains("'uri': Ack.string().uri()"), contains("'uuid': Ack.string().uuid()"), contains("'date': Ack.string().date()"), @@ -881,7 +881,7 @@ final class CheckedRecord with _\$CheckedRecordAck { @IsUuid() final String id; - @IsUrl() + @IsUri() final String website; @IsUri() @@ -930,7 +930,7 @@ final class CheckedRecord with _\$CheckedRecordAck { allOf([ _containsCode("'email': Ack.string().email()"), _containsCode("'id': Ack.string().uuid()"), - _containsCode("'website': Ack.string().url()"), + _containsCode("'website': Ack.string().uri()"), _containsCode("'resourceUri': Ack.string().uri()"), _containsCode("'birthDate': Ack.string().date()"), _containsCode("'createdAt': Ack.string().datetime()"), diff --git a/packages/ack_generator/test/integration/validate_alias_test.dart b/packages/ack_generator/test/integration/validate_alias_test.dart index 117f7f49..5e152cc7 100644 --- a/packages/ack_generator/test/integration/validate_alias_test.dart +++ b/packages/ack_generator/test/integration/validate_alias_test.dart @@ -25,7 +25,6 @@ final class Profile with _\$ProfileAck { required this.handle, required this.code, required this.email, - required this.website, required this.resource, required this.id, required this.birthDate, @@ -72,9 +71,6 @@ final class Profile with _\$ProfileAck { ${rule('Validate.email()', 'IsEmail()')} final String email; - ${rule('Validate.url()', 'IsUrl()')} - final String website; - ${rule('Validate.uri()', 'IsUri()')} final String resource; @@ -131,7 +127,6 @@ void main() { (Validate.matches('^a'), HasMatch('^a'), 'matches', '^a'), (Validate.notEmpty(), IsNotEmpty(), 'notEmpty', null), (Validate.email(), IsEmail(), 'email', null), - (Validate.url(), IsUrl(), 'url', null), (Validate.uri(), IsUri(), 'uri', null), (Validate.uuid(), IsUuid(), 'uuid', null), (Validate.date(), IsDate(), 'date', null), diff --git a/packages/ack_generator/test/src/ack_exports_test.dart b/packages/ack_generator/test/src/ack_exports_test.dart index eeb6722f..1fb19092 100644 --- a/packages/ack_generator/test/src/ack_exports_test.dart +++ b/packages/ack_generator/test/src/ack_exports_test.dart @@ -65,7 +65,6 @@ void main() { 'IsPositive', 'IsRequired', 'IsUri', - 'IsUrl', 'IsUuid', 'Schemable', 'Validate', diff --git a/packages/ack_json_schema_builder/CHANGELOG.md b/packages/ack_json_schema_builder/CHANGELOG.md index 3b85a862..f871137f 100644 --- a/packages/ack_json_schema_builder/CHANGELOG.md +++ b/packages/ack_json_schema_builder/CHANGELOG.md @@ -1,5 +1,7 @@ ## Unreleased +* Use `Ack.string().uri()` to export the URI format. + ### Changed * Use `minItems` and `maxItems` in the list conversion example. diff --git a/packages/ack_json_schema_builder/README.md b/packages/ack_json_schema_builder/README.md index a626366d..abc57f7f 100644 --- a/packages/ack_json_schema_builder/README.md +++ b/packages/ack_json_schema_builder/README.md @@ -162,7 +162,7 @@ if (errors.isEmpty) { |----------------|---------------------|-------| | `.minLength()` / `.maxLength()` | `minLength` / `maxLength` | String and array support | | `.min()` / `.max()` | `minimum` / `maximum` | Numeric bounds | -| `.email()` / `.uuid()` / `.url()` | `format` | Format hints | +| `.email()` / `.uuid()` / `.uri()` | `format` | Format hints | | `.optional()` | Excluded from `required` | Optional fields | | `.describe()` | `description` | Descriptions | | `.withDefault()` | `default` | JSON-compatible defaults | diff --git a/plugins/ack/skills/build-data-classes-with-ack/SKILL.md b/plugins/ack/skills/build-data-classes-with-ack/SKILL.md index 8a5eebc4..65225531 100644 --- a/plugins/ack/skills/build-data-classes-with-ack/SKILL.md +++ b/plugins/ack/skills/build-data-classes-with-ack/SKILL.md @@ -52,7 +52,7 @@ The rules that make it build: - One `part '.g.dart';`, a `final class` (or `sealed class` for a union) with only final fields, an unnamed or primary constructor, and `with _$Ack`. The examples use Dart 3.13 primary constructors; a classic constructor with annotated fields generates identical code. - **Presence comes from the constructor.** `required T` means required and non-null. `required T?` means required, but may be null. Optional `T?` may be omitted and drops the key on encode when null. A default becomes `withDefault`. Change only the wire contract with `@IsOptional()`, `@IsRequired()`, `@IsNotNull()`. -- **Rules** are top-level `Is…` / `Has…` annotations from `package:ack/ack.dart`: `@HasMin`, `@HasMax`, `@IsPositive`, `@IsNegative`, `@IsMultipleOf`, `@HasMinLength`, `@HasMaxLength`, `@HasMatch` (unanchored), `@IsEmail`, `@IsUrl`, `@IsUri`, `@IsUuid`, `@IsDate`, `@IsDateTime`, `@IsIp`, `@IsNotEmpty`, `@HasMinItems`, `@HasMaxItems`, `@HasUniqueItems`. Write these; `@Validate.*` is deprecated and goes away at 2.0.0. +- **Rules** are top-level `Is…` / `Has…` annotations from `package:ack/ack.dart`: `@HasMin`, `@HasMax`, `@IsPositive`, `@IsNegative`, `@IsMultipleOf`, `@HasMinLength`, `@HasMaxLength`, `@HasMatch` (unanchored), `@IsEmail`, `@IsUri`, `@IsUuid`, `@IsDate`, `@IsDateTime`, `@IsIp`, `@IsNotEmpty`, `@HasMinItems`, `@HasMaxItems`, `@HasUniqueItems`. Write these; `@Validate.*` is deprecated and goes away at 2.0.0. - **Wire names:** `caseStyle:` for the whole model (`snake`, `kebab`, `pascal`, `screamingSnake`), `@AckKey('wire')` for one field. Use `@AckKey`, not `@JsonKey`. - **Descriptions** are exported only from `@Schemable(description:)` or a one-line `/// @description ...` doc tag. - **Unknown keys** are rejected by default. Use `@Schemable(unknownProperties: AckUnknownPropertyPolicy.capture)` with a `Map additionalProperties` field when you need to round-trip them. diff --git a/plugins/ack/skills/using-ack/references/migrate-1x.md b/plugins/ack/skills/using-ack/references/migrate-1x.md index 7bc03a54..46f95c90 100644 --- a/plugins/ack/skills/using-ack/references/migrate-1x.md +++ b/plugins/ack/skills/using-ack/references/migrate-1x.md @@ -35,7 +35,9 @@ Done when `dart pub deps` shows the agreed 2.x release, the build writes one `.g | `@MinLength(n)` / `@MaxLength(n)` | `@HasMinLength(n)` / `@HasMaxLength(n)` | | `@Pattern(r)` / `@Matches(r)` / `@Validate.matches(r)` | `@HasMatch(r)` (unanchored) | | `@NotEmpty()` | `@IsNotEmpty()` | -| `@Email()` `@Url()` `@Uri()` `@Uuid()` | `@IsEmail()` `@IsUrl()` `@IsUri()` `@IsUuid()` | +| `@Email()` | `@IsEmail()` | +| `@Url()` / `@Uri()` | `@IsUri()` | +| `@Uuid()` | `@IsUuid()` | | `@Date()` / `@DateTime()` | `@IsDate()` / `@IsDateTime()` | | `@Ip()` / `@Ipv4()` / `@Ipv6()` | `@IsIp()` / `@IsIp(version: 4)` / `@IsIp(version: 6)` | | `@MinItems(n)` / `@MaxItems(n)` / `@UniqueItems()` | `@HasMinItems(n)` / `@HasMaxItems(n)` / `@HasUniqueItems()` | From 03f3f04fd4059ab63db5589b45fee83e949c9211 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 08:58:08 -0500 Subject: [PATCH 03/57] feat(ack)!: standardize built-in constraint keys Release readiness E2 and decision Q12. --- docs/api-reference/index.mdx | 2 +- docs/getting-started/migration-guide.mdx | 1 + packages/ack/CHANGELOG.md | 3 +++ .../list_unique_items_constraint.dart | 2 +- .../constraints/number_finite_constraint.dart | 2 +- .../number_safe_integer_constraint.dart | 2 +- .../src/constraints/pattern_constraint.dart | 4 ++-- .../src/constraints/string_ip_constraint.dart | 2 +- .../constraints/constraint_equality_test.dart | 23 ++++++++++++++++++- 9 files changed, 33 insertions(+), 8 deletions(-) diff --git a/docs/api-reference/index.mdx b/docs/api-reference/index.mdx index 7c2c321f..9352bc5b 100644 --- a/docs/api-reference/index.mdx +++ b/docs/api-reference/index.mdx @@ -262,7 +262,7 @@ Represents a validation failure. See [Error handling](../core-concepts/error-han Base class for custom validation rules. See [Custom validation](../guides/custom-validation.mdx). -- `String constraintKey`: Unique identifier for the constraint. +- `String constraintKey`: Unique identifier for the constraint. Built-in identifiers use snake_case. - `String description`: Human-readable description. - `Map toMap()`: Serializes the constraint for debugging. diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 267229cb..045e8c51 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -170,6 +170,7 @@ and errors: | `Ack.enumCodec(MyEnum.values)` | `2.0.0` | `Ack.enumValues(MyEnum.values)` | | `ListSchema.minLength`, `maxLength`, `exactLength`, `nonEmpty` | `2.0.0` | Use `minItems`, `maxItems`, `length`, and `notEmpty`, respectively. | | `StringSchema.url()` | Use `StringSchema.uri()` for the same validation and schema export. | +| Code matching a dotted built-in constraint key | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique`, `number.isFinite` → `number_is_finite`, `integer.isSafe` → `integer_is_safe`. | | `schema.toMap()` | `2.0.0` | `schema.toJsonSchema()` or `schema.toSchemaModel()` | | `server.registerAckModelTool(...)` (`ack_mcp_dart`) | `2.0.0` | `server.registerAckTool(name, input: Model.schema, callback: ...)`; return a `CallToolResult` from the callback | | `convertAckSchemaModelToBuilder(model)` (`ack_json_schema_builder`) | `2.0.0` | `schema.toJsonSchemaBuilder()` | diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index d29cffb3..990431a4 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -5,6 +5,9 @@ ### Breaking +* **Breaking:** Built-in constraint keys now use snake_case. Update code + that matches the former dotted string, list, number, or integer keys. + * **Breaking:** Use `minItems`, `maxItems`, `length`, and `notEmpty` for lists. The duplicate list method names are removed. diff --git a/packages/ack/lib/src/constraints/list_unique_items_constraint.dart b/packages/ack/lib/src/constraints/list_unique_items_constraint.dart index 75b85f17..6cf69922 100644 --- a/packages/ack/lib/src/constraints/list_unique_items_constraint.dart +++ b/packages/ack/lib/src/constraints/list_unique_items_constraint.dart @@ -10,7 +10,7 @@ final class ListUniqueItemsConstraint extends Constraint> with Validator>, JsonSchemaSpec> { const ListUniqueItemsConstraint() : super( - constraintKey: 'list.unique', + constraintKey: 'list_unique', description: 'All items in the list must be unique.', ); diff --git a/packages/ack/lib/src/constraints/number_finite_constraint.dart b/packages/ack/lib/src/constraints/number_finite_constraint.dart index 63da6539..7a938da3 100644 --- a/packages/ack/lib/src/constraints/number_finite_constraint.dart +++ b/packages/ack/lib/src/constraints/number_finite_constraint.dart @@ -5,7 +5,7 @@ final class NumberFiniteConstraint extends Constraint with Validator { const NumberFiniteConstraint() : super( - constraintKey: 'number.isFinite', + constraintKey: 'number_is_finite', description: 'Value must be a finite number.', ); diff --git a/packages/ack/lib/src/constraints/number_safe_integer_constraint.dart b/packages/ack/lib/src/constraints/number_safe_integer_constraint.dart index a96eea50..8985a6f9 100644 --- a/packages/ack/lib/src/constraints/number_safe_integer_constraint.dart +++ b/packages/ack/lib/src/constraints/number_safe_integer_constraint.dart @@ -10,7 +10,7 @@ final class NumberSafeIntegerConstraint extends Constraint with Validator { const NumberSafeIntegerConstraint() : super( - constraintKey: 'integer.isSafe', + constraintKey: 'integer_is_safe', description: 'Value must be a safe integer.', ); diff --git a/packages/ack/lib/src/constraints/pattern_constraint.dart b/packages/ack/lib/src/constraints/pattern_constraint.dart index 7b67dedf..d2c8fa72 100644 --- a/packages/ack/lib/src/constraints/pattern_constraint.dart +++ b/packages/ack/lib/src/constraints/pattern_constraint.dart @@ -122,7 +122,7 @@ final class PatternConstraint extends Constraint static PatternConstraint startsWith(String prefix) => PatternConstraint( type: PatternType.regex, pattern: RegExp('^${RegExp.escape(prefix)}'), - constraintKey: 'string.startsWith', + constraintKey: 'string_starts_with', description: 'Value must start with "$prefix".', customMessageBuilder: (v) => '"$v" does not start with "$prefix".', ); @@ -130,7 +130,7 @@ final class PatternConstraint extends Constraint static PatternConstraint endsWith(String suffix) => PatternConstraint( type: PatternType.regex, pattern: RegExp('${RegExp.escape(suffix)}\$'), - constraintKey: 'string.endsWith', + constraintKey: 'string_ends_with', description: 'Value must end with "$suffix".', customMessageBuilder: (v) => '"$v" does not end with "$suffix".', ); diff --git a/packages/ack/lib/src/constraints/string_ip_constraint.dart b/packages/ack/lib/src/constraints/string_ip_constraint.dart index 149b6fdc..506c71b9 100644 --- a/packages/ack/lib/src/constraints/string_ip_constraint.dart +++ b/packages/ack/lib/src/constraints/string_ip_constraint.dart @@ -11,7 +11,7 @@ final class StringIpConstraint extends Constraint const StringIpConstraint({this.version}) : super( - constraintKey: 'string.ip', + constraintKey: 'string_ip', description: 'Value must be a valid IP${version != null ? 'v$version' : ''} address.', ); diff --git a/packages/ack/test/constraints/constraint_equality_test.dart b/packages/ack/test/constraints/constraint_equality_test.dart index ae1416c1..8b189a96 100644 --- a/packages/ack/test/constraints/constraint_equality_test.dart +++ b/packages/ack/test/constraints/constraint_equality_test.dart @@ -10,6 +10,27 @@ import 'package:ack/src/constraints/validators.dart'; import 'package:test/test.dart'; void main() { + test('built-in constraint keys use snake_case', () { + expect( + [ + PatternConstraint.startsWith('prefix').constraintKey, + PatternConstraint.endsWith('suffix').constraintKey, + const StringIpConstraint().constraintKey, + const ListUniqueItemsConstraint().constraintKey, + const NumberFiniteConstraint().constraintKey, + const NumberSafeIntegerConstraint().constraintKey, + ], + [ + 'string_starts_with', + 'string_ends_with', + 'string_ip', + 'list_unique', + 'number_is_finite', + 'integer_is_safe', + ], + ); + }); + group('Constraint Equality', () { group('ComparisonConstraint', () { test('equal stringMinLength are equal', () { @@ -161,7 +182,7 @@ void main() { test('uses generic number constraint key', () { const constraint = NumberFiniteConstraint(); - expect(constraint.constraintKey, 'number.isFinite'); + expect(constraint.constraintKey, 'number_is_finite'); }); }); From 134ac430b6cd636eb9ced8697958192f6df9f6e9 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 08:58:44 -0500 Subject: [PATCH 04/57] fix(ack): export SchemaOperation Release readiness E3. --- docs/core-concepts/error-handling.mdx | 3 +++ packages/ack/CHANGELOG.md | 2 ++ packages/ack/lib/ack.dart | 3 +-- packages/ack/test/annotations/exports_test.dart | 17 +++++++++++++++++ 4 files changed, 23 insertions(+), 2 deletions(-) diff --git a/docs/core-concepts/error-handling.mdx b/docs/core-concepts/error-handling.mdx index 1c0240f2..9bad2364 100644 --- a/docs/core-concepts/error-handling.mdx +++ b/docs/core-concepts/error-handling.mdx @@ -237,6 +237,9 @@ validator: (value) { *See the [Form Validation Guide](../guides/flutter-form-validation.mdx) for details.* +A `SchemaContext.operation` is either `SchemaOperation.parse` or +`SchemaOperation.encode`. Both values are available from `package:ack/ack.dart`. + ## Custom error messages 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). diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 990431a4..0d53bbdb 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -27,6 +27,8 @@ ### Fixed +* Export `SchemaOperation` so callers can read and set `SchemaContext.operation`. + * Report a nonproductive JSON Schema reference cycle at the `$ref` that closes it. The diagnostic pointer no longer names a `$ref` on the schema the reference points to when that schema does not contain one. diff --git a/packages/ack/lib/ack.dart b/packages/ack/lib/ack.dart index 46e970d3..d526b9de 100644 --- a/packages/ack/lib/ack.dart +++ b/packages/ack/lib/ack.dart @@ -56,7 +56,7 @@ export 'src/schemas/extensions/string_schema_extensions.dart'; // Core schemas // `WrapperSchema` is internal infrastructure; users compose wrappers via // `withDefault`, `codec`, `transform`, etc., not by implementing the mixin. -// `Refinement`, `SchemaOperation`, and `AnyAckSchema` are traversal +// `Refinement` and `AnyAckSchema` are traversal // plumbing for subclasses; consumers use `.refine(...)`, `safeParse`, and // concrete schema types instead. export 'src/schemas/schema.dart' @@ -64,7 +64,6 @@ export 'src/schemas/schema.dart' AnyAckSchema, ImportedJsonSchema, Refinement, - SchemaOperation, WrapperSchema, createCodecSchemaInternal, jsonMapOrNull; diff --git a/packages/ack/test/annotations/exports_test.dart b/packages/ack/test/annotations/exports_test.dart index e7ee720d..b04017d1 100644 --- a/packages/ack/test/annotations/exports_test.dart +++ b/packages/ack/test/annotations/exports_test.dart @@ -28,6 +28,23 @@ final class SingleImportContact { } void main() { + test('the public context operation can be named by consumers', () { + final context = SchemaContext( + name: 'value', + schema: Ack.string(), + value: 'a', + operation: SchemaOperation.encode, + ); + final SchemaOperation operation = context.operation; + expect(operation, SchemaOperation.encode); + expect( + context + .createChild(name: 'child', schema: Ack.string(), value: 'b') + .operation, + SchemaOperation.encode, + ); + }); + test('package:ack/ack.dart exports the model and rule annotations', () { const values = [ Schemable(caseStyle: AckCaseStyle.snake), From 4329ccb06a99ce346249eb1c9e7c31cab52e8a5f Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 08:59:57 -0500 Subject: [PATCH 05/57] refactor(ack): keep transparent schema contexts internal Release readiness E4. --- packages/ack/CHANGELOG.md | 3 ++ packages/ack/lib/ack.dart | 2 +- packages/ack/lib/src/context.dart | 43 +++++++++++++------ .../ack/lib/src/schemas/any_of_schema.dart | 7 ++- .../ack/lib/src/schemas/boundary_schema.dart | 4 +- .../schemas/discriminated_object_schema.dart | 17 +++----- packages/ack/lib/src/schemas/lazy_schema.dart | 4 +- .../transparent_context_hidden.dart.txt | 27 ++++++++++++ .../json_schema_import_public_api_test.dart | 14 ++++++ 9 files changed, 90 insertions(+), 31 deletions(-) create mode 100644 packages/ack/test/fixtures/public_api/transparent_context_hidden.dart.txt diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 0d53bbdb..a83d5f1e 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -21,6 +21,9 @@ ### Changed +* Keep wrapper context path handling internal. Empty JSON member keys + still appear as empty tokens in validation paths. + * Remove the `punycoder` and `unorm_dart` dependencies. Ack now has only `meta` and `collection` as runtime dependencies. Punycode conversion for `xn--` labels is built in. diff --git a/packages/ack/lib/ack.dart b/packages/ack/lib/ack.dart index d526b9de..75a160ce 100644 --- a/packages/ack/lib/ack.dart +++ b/packages/ack/lib/ack.dart @@ -39,7 +39,7 @@ export 'src/common_types.dart' show JsonMap; export 'src/constraints/constraint.dart'; export 'src/constraints/duration_constraint.dart'; // Context -export 'src/context.dart'; +export 'src/context.dart' show SchemaContext; // JSON Schema export 'src/json_schema.dart'; // Generated model support diff --git a/packages/ack/lib/src/context.dart b/packages/ack/lib/src/context.dart index e5787107..8d042503 100644 --- a/packages/ack/lib/src/context.dart +++ b/packages/ack/lib/src/context.dart @@ -11,13 +11,7 @@ class SchemaContext { final SchemaContext? parent; final String? pathSegment; - /// When true, [path] does not append a segment for this context. - /// - /// Wrapper contexts such as anyOf branches, lazy recursion, boundary - /// re-parse, and discriminated-object routing set this so they add no JSON - /// Pointer token. An empty [pathSegment] is a real member key and stays in - /// [path] as an empty reference token (`#/`), per RFC 6901. - final bool omitPathSegment; + final bool _omitPathSegment; final SchemaOperation operation; @@ -27,9 +21,19 @@ class SchemaContext { required this.value, this.parent, this.pathSegment, - this.omitPathSegment = false, this.operation = SchemaOperation.parse, - }); + }) : _omitPathSegment = false; + + /// Creates an internal wrapper context without adding a JSON Pointer token. + @internal + const SchemaContext.transparent({ + required this.name, + required this.schema, + required this.value, + required SchemaContext this.parent, + required this.operation, + }) : pathSegment = null, + _omitPathSegment = true; /// Escapes a JSON Pointer segment per RFC 6901. static String _escapeJsonPointerSegment(String segment) { @@ -44,7 +48,7 @@ class SchemaContext { final parentPath = parent!.path; - if (omitPathSegment) { + if (_omitPathSegment) { return parentPath; } @@ -64,7 +68,6 @@ class SchemaContext { required AnyAckSchema schema, required Object? value, String? pathSegment, - bool omitPathSegment = false, SchemaOperation? operation, }) { return SchemaContext( @@ -73,7 +76,6 @@ class SchemaContext { value: value, parent: this, pathSegment: pathSegment, - omitPathSegment: omitPathSegment, operation: operation ?? this.operation, ); } @@ -86,3 +88,20 @@ class SchemaContext { return 'SchemaContext(name: "$name", path: "$path", schema: $schemaTypeString, value: "$valueString", operation: ${operation.name})'; } } + +/// Shared path plumbing for internal wrapper schemas. +@internal +extension SchemaContextTraversal on SchemaContext { + SchemaContext createTransparentChild({ + required String name, + required AnyAckSchema schema, + required Object? value, + SchemaOperation? operation, + }) => SchemaContext.transparent( + name: name, + schema: schema, + value: value, + parent: this, + operation: operation ?? this.operation, + ); +} diff --git a/packages/ack/lib/src/schemas/any_of_schema.dart b/packages/ack/lib/src/schemas/any_of_schema.dart index d75bed99..5288787d 100644 --- a/packages/ack/lib/src/schemas/any_of_schema.dart +++ b/packages/ack/lib/src/schemas/any_of_schema.dart @@ -40,11 +40,10 @@ final class AnyOfSchema extends AckSchema final errors = []; for (final (index, schema) in schemas.indexed) { - final childContext = context.createChild( + final childContext = context.createTransparentChild( name: 'anyOf:$index', schema: schema, value: value, - omitPathSegment: true, ); final result = parse ? schema.parseWithContext(value, childContext) @@ -95,11 +94,11 @@ final class AnyOfSchema extends AckSchema final errors = []; for (final (index, schema) in schemas.indexed) { - final childContext = context.createChild( + final childContext = context.createTransparentChild( name: 'anyOf:$index', schema: schema, value: runtime, - omitPathSegment: true, + operation: SchemaOperation.encode, ); try { diff --git a/packages/ack/lib/src/schemas/boundary_schema.dart b/packages/ack/lib/src/schemas/boundary_schema.dart index 4a39e24c..d2db9186 100644 --- a/packages/ack/lib/src/schemas/boundary_schema.dart +++ b/packages/ack/lib/src/schemas/boundary_schema.dart @@ -46,11 +46,11 @@ final class BoundarySchema extends AckSchema // view accept a value that its parse would reject. final parseContext = context.operation == SchemaOperation.parse ? context - : context.createChild( + : context.createTransparentChild( name: context.name, schema: inner, value: value, - omitPathSegment: true, + operation: SchemaOperation.parse, ); final result = inner.parseWithContext(value, parseContext); diff --git a/packages/ack/lib/src/schemas/discriminated_object_schema.dart b/packages/ack/lib/src/schemas/discriminated_object_schema.dart index 8408a6fb..f86dbaac 100644 --- a/packages/ack/lib/src/schemas/discriminated_object_schema.dart +++ b/packages/ack/lib/src/schemas/discriminated_object_schema.dart @@ -368,11 +368,10 @@ final class DiscriminatedObjectSchema // `effectiveBranch` is always callable here. final effective = effectiveBranch(discValue); - final subSchemaContext = context.createChild( + final subSchemaContext = context.createTransparentChild( name: 'when $discriminatorKey="$discValue"', schema: effective, value: mapValue, - omitPathSegment: true, ); final result = effective.parseWithContext(mapValue, subSchemaContext); @@ -409,11 +408,10 @@ final class DiscriminatedObjectSchema if (discResult.isFail) return SchemaResult.fail(discResult.getError()); final discValue = discResult.getOrNull()!; final effective = effectiveBranch(discValue); - final branchContext = context.createChild( + final branchContext = context.createTransparentChild( name: 'when $discriminatorKey="$discValue"', schema: effective, value: runtime, - omitPathSegment: true, ); final result = effective.validateRuntimeWithContext( runtime, @@ -426,11 +424,10 @@ final class DiscriminatedObjectSchema final errors = []; for (final discValue in schemas.keys) { final effective = effectiveBranch(discValue); - final branchContext = context.createChild( + final branchContext = context.createTransparentChild( name: 'when $discriminatorKey="$discValue"', schema: effective, value: runtime, - omitPathSegment: true, ); final result = effective.validateRuntimeWithContext( runtime, @@ -491,11 +488,11 @@ final class DiscriminatedObjectSchema } final discValue = discResult.getOrNull()!; final effective = effectiveBranch(discValue, optionalDiscriminator: true); - final branchCtx = context.createChild( + final branchCtx = context.createTransparentChild( name: 'when $discriminatorKey="$discValue"', schema: effective, value: runtime, - omitPathSegment: true, + operation: SchemaOperation.encode, ); @@ -525,11 +522,11 @@ final class DiscriminatedObjectSchema // gates selection); the union itself writes the discriminator // onto the encoded boundary in [_encodeBranch]. final effective = effectiveBranch(discValue, optionalDiscriminator: true); - final branchCtx = context.createChild( + final branchCtx = context.createTransparentChild( name: 'when $discriminatorKey="$discValue"', schema: effective, value: runtime, - omitPathSegment: true, + operation: SchemaOperation.encode, ); diff --git a/packages/ack/lib/src/schemas/lazy_schema.dart b/packages/ack/lib/src/schemas/lazy_schema.dart index 3e771e0f..33c86447 100644 --- a/packages/ack/lib/src/schemas/lazy_schema.dart +++ b/packages/ack/lib/src/schemas/lazy_schema.dart @@ -239,12 +239,12 @@ final class _LazyRecursionContext extends SchemaContext { required this.recursionToken, required Object? value, required SchemaContext parent, - }) : super( + }) : super.transparent( name: name, schema: schema, value: value, parent: parent, - omitPathSegment: true, + operation: parent.operation, ); diff --git a/packages/ack/test/fixtures/public_api/transparent_context_hidden.dart.txt b/packages/ack/test/fixtures/public_api/transparent_context_hidden.dart.txt new file mode 100644 index 00000000..c0334b87 --- /dev/null +++ b/packages/ack/test/fixtures/public_api/transparent_context_hidden.dart.txt @@ -0,0 +1,27 @@ +import 'package:ack/ack.dart'; + +SchemaContext makeContext() => SchemaContext( + name: 'item', + schema: Ack.string(), + value: 'value', + omitPathSegment: true, +); + +void checkChild(SchemaContext root) { + root.createChild( + name: 'child', + schema: Ack.string(), + value: 'value', + omitPathSegment: true, + ); +} + +void checkGetter(SchemaContext root) { + print(root.omitPathSegment); +} + +void main() { + final root = makeContext(); + checkChild(root); + checkGetter(root); +} diff --git a/packages/ack/test/json_schema_import_public_api_test.dart b/packages/ack/test/json_schema_import_public_api_test.dart index 5c6a4e8d..485b02cb 100644 --- a/packages/ack/test/json_schema_import_public_api_test.dart +++ b/packages/ack/test/json_schema_import_public_api_test.dart @@ -22,6 +22,20 @@ Future _compileFixture(String name) { } void main() { + test('context path plumbing is hidden from clients', () async { + final result = await _compileFixture('transparent_context_hidden'); + expect(result.exitCode, isNot(0)); + expect( + RegExp("No named parameter with the name 'omitPathSegment'") + .allMatches(result.stderr as String), + hasLength(2), + ); + expect( + result.stderr, + contains("The getter 'omitPathSegment' isn't defined"), + ); + }); + test('the URI rule is the only public name for URI validation', () async { final result = await _compileFixture('uri_aliases_removed'); expect(result.exitCode, isNot(0)); From 697af54aadd5feee929cb05e44ee5e610484a448 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:01:37 -0500 Subject: [PATCH 06/57] feat(ack)!: share the concrete public rule annotation exports Release readiness E5. --- docs/getting-started/migration-guide.mdx | 1 + packages/ack/CHANGELOG.md | 3 ++ packages/ack/lib/ack.dart | 28 +------------------ packages/ack/lib/annotations.dart | 25 ++++++++++++++++- .../ack/test/annotations/ack_model_test.dart | 1 + .../ack/test/annotations/exports_test.dart | 3 +- .../public_api/rule_base_hidden.dart.txt | 10 +++++++ .../json_schema_import_public_api_test.dart | 10 +++++++ 8 files changed, 51 insertions(+), 30 deletions(-) create mode 100644 packages/ack/test/fixtures/public_api/rule_base_hidden.dart.txt diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 045e8c51..a51c97dd 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -171,6 +171,7 @@ and errors: | `ListSchema.minLength`, `maxLength`, `exactLength`, `nonEmpty` | `2.0.0` | Use `minItems`, `maxItems`, `length`, and `notEmpty`, respectively. | | `StringSchema.url()` | Use `StringSchema.uri()` for the same validation and schema export. | | Code matching a dotted built-in constraint key | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique`, `number.isFinite` → `number_is_finite`, `integer.isSafe` → `integer_is_safe`. | +| `AckRule` from `package:ack/annotations.dart` | Use the concrete rule annotation type for rule-specific data, or `Object` for a mixed list. | | `schema.toMap()` | `2.0.0` | `schema.toJsonSchema()` or `schema.toSchemaModel()` | | `server.registerAckModelTool(...)` (`ack_mcp_dart`) | `2.0.0` | `server.registerAckTool(name, input: Model.schema, callback: ...)`; return a `CallToolResult` from the callback | | `convertAckSchemaModelToBuilder(model)` (`ack_json_schema_builder`) | `2.0.0` | `schema.toJsonSchemaBuilder()` | diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index a83d5f1e..5756686a 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -5,6 +5,9 @@ ### Breaking +* **Breaking:** Both public annotation entry points export the same concrete + rules. The base `AckRule` type is internal. + * **Breaking:** Built-in constraint keys now use snake_case. Update code that matches the former dotted string, list, number, or integer keys. diff --git a/packages/ack/lib/ack.dart b/packages/ack/lib/ack.dart index 75a160ce..16a3b527 100644 --- a/packages/ack/lib/ack.dart +++ b/packages/ack/lib/ack.dart @@ -7,32 +7,7 @@ library; // Main API export 'src/ack.dart'; // Model annotations -export 'src/annotations/ack_field.dart'; -export 'src/annotations/constraints.dart' - show - HasMatch, - HasMax, - HasMaxItems, - HasMaxLength, - HasMin, - HasMinItems, - HasMinLength, - HasUniqueItems, - IsDate, - IsDateTime, - IsEmail, - IsIp, - IsMultipleOf, - IsNegative, - IsNotEmpty, - IsNotNull, - IsOptional, - IsPositive, - IsRequired, - IsUri, - IsUuid, - Validate; -export 'src/annotations/schemable.dart'; +export 'annotations.dart'; // Common types export 'src/common_types.dart' show JsonMap; // Constraints @@ -44,7 +19,6 @@ export 'src/context.dart' show SchemaContext; export 'src/json_schema.dart'; // Generated model support export 'src/models/ack_model_adapter.dart'; -export 'src/models/json_maybe.dart'; // Extensions export 'src/schemas/extensions/ack_schema_extensions.dart'; export 'src/schemas/extensions/datetime_schema_extensions.dart'; diff --git a/packages/ack/lib/annotations.dart b/packages/ack/lib/annotations.dart index 33fdda2c..0bdacd9d 100644 --- a/packages/ack/lib/annotations.dart +++ b/packages/ack/lib/annotations.dart @@ -2,6 +2,29 @@ library; export 'src/annotations/ack_field.dart'; -export 'src/annotations/constraints.dart'; +export 'src/annotations/constraints.dart' + show + HasMatch, + HasMax, + HasMaxItems, + HasMaxLength, + HasMin, + HasMinItems, + HasMinLength, + HasUniqueItems, + IsDate, + IsDateTime, + IsEmail, + IsIp, + IsMultipleOf, + IsNegative, + IsNotEmpty, + IsNotNull, + IsOptional, + IsPositive, + IsRequired, + IsUri, + IsUuid, + Validate; export 'src/annotations/schemable.dart'; export 'src/models/json_maybe.dart'; diff --git a/packages/ack/test/annotations/ack_model_test.dart b/packages/ack/test/annotations/ack_model_test.dart index 94b5d4af..c80121ee 100644 --- a/packages/ack/test/annotations/ack_model_test.dart +++ b/packages/ack/test/annotations/ack_model_test.dart @@ -1,4 +1,5 @@ import 'package:ack/annotations.dart'; +import 'package:ack/src/annotations/constraints.dart' show AckRule; import 'package:test/test.dart'; void main() { diff --git a/packages/ack/test/annotations/exports_test.dart b/packages/ack/test/annotations/exports_test.dart index b04017d1..694a7a83 100644 --- a/packages/ack/test/annotations/exports_test.dart +++ b/packages/ack/test/annotations/exports_test.dart @@ -74,7 +74,6 @@ void main() { ]; expect(values, hasLength(24)); - expect(values.skip(2), everyElement(isA())); expect(AckUnknownPropertyPolicy.values, hasLength(3)); }); @@ -126,7 +125,7 @@ void main() { const contact = Contact(Email('ada@example.com')); const schemable = ack.Schemable(name: 'Contact'); const key = ack.AckKey('email_address'); - const rules = [ + const rules = [ ack.IsOptional(), ack.IsRequired(), ack.IsNotNull(), diff --git a/packages/ack/test/fixtures/public_api/rule_base_hidden.dart.txt b/packages/ack/test/fixtures/public_api/rule_base_hidden.dart.txt new file mode 100644 index 00000000..b428f072 --- /dev/null +++ b/packages/ack/test/fixtures/public_api/rule_base_hidden.dart.txt @@ -0,0 +1,10 @@ +import 'package:ack/ack.dart'; +import 'package:ack/annotations.dart' as annotations; + +void checkBarrel(AckRule value) => print(value); +void checkAnnotations(annotations.AckRule value) => print(value); + +void main() { + checkBarrel(const HasMinLength(1)); + checkAnnotations(const annotations.HasMinLength(1)); +} diff --git a/packages/ack/test/json_schema_import_public_api_test.dart b/packages/ack/test/json_schema_import_public_api_test.dart index 485b02cb..7220b27c 100644 --- a/packages/ack/test/json_schema_import_public_api_test.dart +++ b/packages/ack/test/json_schema_import_public_api_test.dart @@ -22,6 +22,16 @@ Future _compileFixture(String name) { } void main() { + test('both annotation entry points hide the rule base type', () async { + final result = await _compileFixture('rule_base_hidden'); + expect(result.exitCode, isNot(0)); + expect( + RegExp("'AckRule' isn't a type").allMatches(result.stderr as String), + hasLength(2), + reason: result.stderr as String, + ); + }); + test('context path plumbing is hidden from clients', () async { final result = await _compileFixture('transparent_context_hidden'); expect(result.exitCode, isNot(0)); From cb1bf687203c65a2babbd116740f800c38d3b56b Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:02:41 -0500 Subject: [PATCH 07/57] docs(ack): clarify which public types support exhaustive switches Release readiness E6 and decision Q13. --- docs/core-concepts/error-handling.mdx | 4 +++- packages/ack/CHANGELOG.md | 3 +++ .../schema_switch_requires_fallback.dart.txt | 21 +++++++++++++++++++ .../json_schema_import_public_api_test.dart | 9 ++++++++ 4 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 packages/ack/test/fixtures/public_api/schema_switch_requires_fallback.dart.txt diff --git a/docs/core-concepts/error-handling.mdx b/docs/core-concepts/error-handling.mdx index 9bad2364..63615bc7 100644 --- a/docs/core-concepts/error-handling.mdx +++ b/docs/core-concepts/error-handling.mdx @@ -195,7 +195,9 @@ Raised when `encode()` or `safeEncode()` can't turn a runtime value back into it ### Working with error types -`SchemaError` (and `AckSchema`) is a `sealed class`, so you can use exhaustive pattern matching without a wildcard branch: +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 final result = schema.safeParse(data); diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 5756686a..6516951d 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -33,6 +33,9 @@ ### Fixed +* Clarify that exhaustive switches are supported for `SchemaError`. A switch + over the public `AckSchema` types needs a fallback branch. + * Export `SchemaOperation` so callers can read and set `SchemaContext.operation`. * Report a nonproductive JSON Schema reference cycle at the `$ref` that diff --git a/packages/ack/test/fixtures/public_api/schema_switch_requires_fallback.dart.txt b/packages/ack/test/fixtures/public_api/schema_switch_requires_fallback.dart.txt new file mode 100644 index 00000000..0592dc1e --- /dev/null +++ b/packages/ack/test/fixtures/public_api/schema_switch_requires_fallback.dart.txt @@ -0,0 +1,21 @@ +import 'package:ack/ack.dart'; + +bool exportedType(AckSchema schema) => switch (schema) { + AnySchema() || + AnyOfSchema() || + BooleanSchema() || + BoundarySchema() || + CodecSchema() || + DefaultSchema() || + DiscriminatedObjectSchema() || + EnumSchema() || + InstanceSchema() || + LazySchema() || + ListSchema() || + MapSchema() || + NumSchema() || + ObjectSchema() || + StringSchema() => true, +}; + +void main() => print(exportedType(Ack.fromJsonSchema({}))); diff --git a/packages/ack/test/json_schema_import_public_api_test.dart b/packages/ack/test/json_schema_import_public_api_test.dart index 7220b27c..67ae6c66 100644 --- a/packages/ack/test/json_schema_import_public_api_test.dart +++ b/packages/ack/test/json_schema_import_public_api_test.dart @@ -22,6 +22,15 @@ Future _compileFixture(String name) { } void main() { + test( + 'schema switches need a fallback for the hidden imported schema', + () async { + final result = await _compileFixture('schema_switch_requires_fallback'); + expect(result.exitCode, isNot(0)); + expect(result.stderr, contains('not exhaustively matched')); + }, + ); + test('both annotation entry points hide the rule base type', () async { final result = await _compileFixture('rule_base_hidden'); expect(result.exitCode, isNot(0)); From db2795d0c22ca6859a2440dccddfa32e180ce9d9 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:03:10 -0500 Subject: [PATCH 08/57] fix(generator): qualify generated model field reads Release readiness C1. --- packages/ack_generator/CHANGELOG.md | 7 ++++ .../lib/src/builders/data_class_emitter.dart | 2 +- .../lib/src/builders/model_emitter.dart | 10 +++--- .../ack_infer_runtime_build_test.dart | 34 +++++++++++++++++++ 4 files changed, 47 insertions(+), 6 deletions(-) diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index cccdff65..15654d6b 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -1,3 +1,10 @@ +## Unreleased + +### Fixed + +* Generated models compare declared fields and encode passthrough JSON + correctly when field names overlap with generator parameters or locals. + ## 2.0.0-beta.3 ### Breaking diff --git a/packages/ack_generator/lib/src/builders/data_class_emitter.dart b/packages/ack_generator/lib/src/builders/data_class_emitter.dart index d097b1b7..5af2b374 100644 --- a/packages/ack_generator/lib/src/builders/data_class_emitter.dart +++ b/packages/ack_generator/lib/src/builders/data_class_emitter.dart @@ -313,7 +313,7 @@ ${_ack('SchemaResult')}> safeToJson() => 'other is $className', 'runtimeType == other.runtimeType', for (final field in fields) - _equals(field.dartName, 'other.${field.dartName}'), + _equals('this.${field.dartName}', 'other.${field.dartName}'), ]; return 'identical(this, other) || (${comparisons.join(' && ')})'; } diff --git a/packages/ack_generator/lib/src/builders/model_emitter.dart b/packages/ack_generator/lib/src/builders/model_emitter.dart index 2f7389cb..bfba2985 100644 --- a/packages/ack_generator/lib/src/builders/model_emitter.dart +++ b/packages/ack_generator/lib/src/builders/model_emitter.dart @@ -646,7 +646,7 @@ ${_ack('AckModelAdapter')}( final allArguments = [ ...arguments, 'additionalProperties: Map.fromEntries(\n' - ' value.entries.where((entry) => !declared.contains(entry.key)),\n' + ' value.entries.where((entry) => !_ackDeclaredKeys.contains(entry.key)),\n' ' )', ]; return Method( @@ -662,7 +662,7 @@ ${_ack('AckModelAdapter')}( ), ) ..body = Code(''' -const declared = ${_dataClasses.declaredKeysLiteral(keys)}; +const _ackDeclaredKeys = ${_dataClasses.declaredKeysLiteral(keys)}; return ${node.className}( ${allArguments.join(',\n ')}, );'''), @@ -701,11 +701,11 @@ return ${node.className}( ); final allEntries = [ 'for (final entry in additionalProperties.entries)\n' - ' if (!declared.contains(entry.key)) entry.key: entry.value', + ' if (!_ackDeclaredKeys.contains(entry.key)) entry.key: entry.value', ...entries, ]; m.body = Code(''' -const declared = $declaredLiteral; +const _ackDeclaredKeys = $declaredLiteral; return $_runtimeMapLiteral{ ${allEntries.join(',\n ')}, };'''); @@ -731,7 +731,7 @@ return $_runtimeMapLiteral{ String _encodeField(AckFieldNode field) => _dataClasses.encodeField( field.runtimeRef, - field.dartName, + 'this.${field.dartName}', nullable: !field.isRequired || field.nullable, ); diff --git a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart index bf73fd0a..e906c0c1 100644 --- a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart @@ -243,6 +243,19 @@ final keywordFieldsSchema = Ack.object({ 'yield': Ack.string(), }); +@Schemable() +final scopedNamesSchema = Ack.object({ + 'other': Ack.string(), + 'declared': Ack.string(), + 'value': Ack.string(), + 'entry': Ack.string(), + 'model': Ack.string(), + 'self': Ack.string(), + 'item': Ack.string(), + 'fieldValue': Ack.string(), + 'key': Ack.string(), +}).passthrough(); + @Schemable() final dollarNamesSchema = Ack.object({ r'$id': Ack.string(), @@ -486,6 +499,27 @@ void main() { expect(KeywordFields.parse({...json}..remove('required')).required, isFalse); }); + test('generated local and parameter names can also be model fields', () { + const fields = ['other', 'declared', 'value', 'entry', 'model', 'self', + 'item', 'fieldValue', 'key']; + final json = { + for (final field in fields) field: field, + 'extra': 'captured', + }; + final first = ScopedNames.parse(json); + final second = ScopedNames.parse(json); + expect(first, second); + expect(first.hashCode, second.hashCode); + expect(first.toJson(), json); + expect(first.copyWith().toJson(), json); + expect(first.copyWith(declared: 'updated').toJson(), { + ...json, 'declared': 'updated', + }); + for (final field in fields) { + expect(first.toString(), contains('$field: $field')); + } + }); + test('toString keeps dollar signs in field names literal', () { final names = DollarNames.parse({r'$id': 'a', r'cost$usd': 2}); expect(names.toString(), r'DollarNames($id: a, cost$usd: 2)'); From 7d960870e7f7b20c3399e81e9afdb127aa2480ab Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:03:10 -0500 Subject: [PATCH 09/57] refactor(ack)!: internalize schema model rendering helpers Release readiness E7. --- docs/getting-started/migration-guide.mdx | 1 + packages/ack/CHANGELOG.md | 3 +++ .../src/schema_model/ack_schema_model.dart | 19 ++++++++++--------- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index a51c97dd..5944ed1c 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -172,6 +172,7 @@ and errors: | `StringSchema.url()` | Use `StringSchema.uri()` for the same validation and schema export. | | Code matching a dotted built-in constraint key | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique`, `number.isFinite` → `number_is_finite`, `integer.isSafe` → `integer_is_safe`. | | `AckRule` from `package:ack/annotations.dart` | Use the concrete rule annotation type for rule-specific data, or `Object` for a mixed list. | +| `AckSchemaModel.withJsonSchemaKeywords`, `finishTypeJson`, or `finishCompositionJson` | Render the public model with `toJsonSchema()` and apply any custom JSON Schema keywords to the resulting map. | | `schema.toMap()` | `2.0.0` | `schema.toJsonSchema()` or `schema.toSchemaModel()` | | `server.registerAckModelTool(...)` (`ack_mcp_dart`) | `2.0.0` | `server.registerAckTool(name, input: Model.schema, callback: ...)`; return a `CallToolResult` from the callback | | `convertAckSchemaModelToBuilder(model)` (`ack_json_schema_builder`) | `2.0.0` | `schema.toJsonSchemaBuilder()` | diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 6516951d..110add11 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -5,6 +5,9 @@ ### Breaking +* **Breaking:** JSON Schema rendering and keyword projection helpers are now + internal to the schema model. Render public models with `toJsonSchema()`. + * **Breaking:** Both public annotation entry points export the same concrete rules. The base `AckRule` type is internal. diff --git a/packages/ack/lib/src/schema_model/ack_schema_model.dart b/packages/ack/lib/src/schema_model/ack_schema_model.dart index 684fe2d3..b061aba7 100644 --- a/packages/ack/lib/src/schema_model/ack_schema_model.dart +++ b/packages/ack/lib/src/schema_model/ack_schema_model.dart @@ -184,6 +184,7 @@ sealed class AckSchemaModel { AckSchemaModel withExtensions(Map extensions) => _rebuildWithCommon(_common.copyWith(extensions: extensions)); + @internal AckSchemaModel withJsonSchemaKeywords(Map keywords) { final commonHandled = {}; var common = _common; @@ -214,7 +215,7 @@ sealed class AckSchemaModel { Set commonHandled, ) => _withUnhandledKeywords(keywords, commonHandled); - Map finishTypeJson(Map typeJson) { + Map _finishTypeJson(Map typeJson) { if (!nullable) { return {...typeJson, ..._common.toJson()}; } @@ -233,7 +234,7 @@ sealed class AckSchemaModel { }; } - Map finishCompositionJson( + Map _finishCompositionJson( String keyword, List schemas, ) { @@ -444,7 +445,7 @@ final class AckRefSchemaModel extends AckSchemaModel { final refJson = { r'$ref': '#/definitions/${escapeJsonPointerToken(refName)}', }; - if (nullable) return finishTypeJson(refJson); + if (nullable) return _finishTypeJson(refJson); final commonJson = _common.toJson(); if (commonJson.isEmpty) return refJson; @@ -498,7 +499,7 @@ final class AckStringSchemaModel extends AckSchemaModel { final String? pattern; @override - Map toJsonSchema() => finishTypeJson({ + Map toJsonSchema() => _finishTypeJson({ 'type': 'string', if (format != null) 'format': format, if (constValue != null) 'const': constValue, @@ -621,7 +622,7 @@ sealed class _AckNumericSchemaModel extends AckSchemaModel { }); @override - Map toJsonSchema() => finishTypeJson({ + Map toJsonSchema() => _finishTypeJson({ 'type': _jsonType, if (format != null) 'format': format, if (constValue != null) 'const': constValue, @@ -824,7 +825,7 @@ final class AckBooleanSchemaModel extends AckSchemaModel { final bool? constValue; @override - Map toJsonSchema() => finishTypeJson({ + Map toJsonSchema() => _finishTypeJson({ 'type': 'boolean', if (constValue != null) 'const': constValue, }); @@ -876,7 +877,7 @@ final class AckArraySchemaModel extends AckSchemaModel { final bool? uniqueItems; @override - Map toJsonSchema() => finishTypeJson({ + Map toJsonSchema() => _finishTypeJson({ 'type': 'array', if (items != null) 'items': items!.toJsonSchema(), if (minItems != null) 'minItems': minItems, @@ -967,7 +968,7 @@ final class AckObjectSchemaModel extends AckSchemaModel { @override Map toJsonSchema() { - return finishTypeJson({ + return _finishTypeJson({ 'type': 'object', if (properties != null) 'properties': properties!.map( @@ -1079,7 +1080,7 @@ sealed class _AckCompositionSchemaModel extends AckSchemaModel { @override Map toJsonSchema() => - finishCompositionJson(_compositionKeyword, schemas); + _finishCompositionJson(_compositionKeyword, schemas); } final class AckAnyOfSchemaModel extends _AckCompositionSchemaModel { From d14c7a5b4d5107cee30a151d9e41c86e24d0e6df Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:04:58 -0500 Subject: [PATCH 10/57] fix(generator): escape discriminator keys in emitted errors Release readiness C2. --- packages/ack_generator/CHANGELOG.md | 2 ++ .../lib/src/builders/class_model_emitter.dart | 2 +- .../lib/src/builders/model_emitter.dart | 2 +- .../src/json_schema/json_schema_emitter.dart | 2 +- .../ack_infer_runtime_build_test.dart | 30 +++++++++++++++++++ 5 files changed, 35 insertions(+), 3 deletions(-) diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 15654d6b..819a2234 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -2,6 +2,8 @@ ### Fixed +* Escape literal dollar signs and quotes in generated discriminator messages. + * Generated models compare declared fields and encode passthrough JSON correctly when field names overlap with generator parameters or locals. diff --git a/packages/ack_generator/lib/src/builders/class_model_emitter.dart b/packages/ack_generator/lib/src/builders/class_model_emitter.dart index 8641d85f..af07586b 100644 --- a/packages/ack_generator/lib/src/builders/class_model_emitter.dart +++ b/packages/ack_generator/lib/src/builders/class_model_emitter.dart @@ -139,7 +139,7 @@ final ${metadata.backingName} = $rawName.codec<${node.className}>( decode: (value) => switch (value[${dartStringLiteral(node.discriminatorKey)}]) { ${decodeCases.join(',\n ')}, final unknown => throw StateError( - 'Unknown ${node.discriminatorKey}: \$unknown', + ${dartStringLiteral('Unknown ${node.discriminatorKey}: ')} '\$unknown', ), }, encode: (model) => switch (model) { diff --git a/packages/ack_generator/lib/src/builders/model_emitter.dart b/packages/ack_generator/lib/src/builders/model_emitter.dart index bfba2985..bd89dddb 100644 --- a/packages/ack_generator/lib/src/builders/model_emitter.dart +++ b/packages/ack_generator/lib/src/builders/model_emitter.dart @@ -218,7 +218,7 @@ final class AckModelEmitter { return switch (value[${dartStringLiteral(node.discriminatorKey)}]) { ${cases.join(',\n ')}, final unknown => throw StateError( - 'Unknown ${node.discriminatorKey}: \$unknown', + ${dartStringLiteral('Unknown ${node.discriminatorKey}: ')} '\$unknown', ), };'''), ), diff --git a/packages/ack_generator/lib/src/json_schema/json_schema_emitter.dart b/packages/ack_generator/lib/src/json_schema/json_schema_emitter.dart index 042007a2..96ce33f0 100644 --- a/packages/ack_generator/lib/src/json_schema/json_schema_emitter.dart +++ b/packages/ack_generator/lib/src/json_schema/json_schema_emitter.dart @@ -28,7 +28,7 @@ String _emit( ..writeln(); if (includeParts) { buffer - ..writeln("part '$partStem.g.dart';") + ..writeln("part ${dartStringLiteral('$partStem.g.dart')};") ..writeln(); } for (final declaration in translator.declarations) { diff --git a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart index e906c0c1..66228a4d 100644 --- a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart @@ -243,6 +243,29 @@ final keywordFieldsSchema = Ack.object({ 'yield': Ack.string(), }); +@Schemable(discriminatorKey: r'$type') +sealed class SpecialPet with _$SpecialPetAck { + const SpecialPet(); +} + +@Schemable(discriminatorValue: 'cat') +final class SpecialCat extends SpecialPet with _$SpecialCatAck { + const SpecialCat({required this.name}); + final String name; +} + +@Schemable() +final specialWireBranchSchema = Ack.object({ + r'$type': Ack.literal('a'), + 'id': Ack.string(), +}); + +@Schemable() +final specialWireChoiceSchema = Ack.discriminated( + discriminatorKey: r'$type', + schemas: {'a': specialWireBranchSchema}, +); + @Schemable() final scopedNamesSchema = Ack.object({ 'other': Ack.string(), @@ -499,6 +522,13 @@ void main() { expect(KeywordFields.parse({...json}..remove('required')).required, isFalse); }); + test('discriminator keys can contain literal dollar signs', () { + const pet = {r'$type': 'cat', 'name': 'Milo'}; + expect(SpecialPetSchema.parse(pet).toJson(), pet); + const wire = {r'$type': 'a', 'id': 'a1'}; + expect(SpecialWireChoice.parse(wire).toJson(), wire); + }); + test('generated local and parameter names can also be model fields', () { const fields = ['other', 'declared', 'value', 'entry', 'model', 'self', 'item', 'fieldValue', 'key']; From c0133ca5a338811ced8b51fbde796e73f804cb71 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:06:09 -0500 Subject: [PATCH 11/57] fix(generator): qualify class statics in constructor defaults Release readiness C3. --- packages/ack_generator/CHANGELOG.md | 2 + .../analyzer/class_model_graph_builder.dart | 63 ++++++++++++++++++- .../ack_infer_runtime_build_test.dart | 22 +++++++ 3 files changed, 84 insertions(+), 3 deletions(-) diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 819a2234..8aeff599 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -2,6 +2,8 @@ ### Fixed +* Qualify references to class statics in generated constructor defaults. + * Escape literal dollar signs and quotes in generated discriminator messages. * Generated models compare declared fields and encode passthrough JSON diff --git a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart index 8203f499..39fce58c 100644 --- a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart @@ -1,5 +1,6 @@ import 'package:ack/annotations.dart' as annotations; import 'package:analyzer/dart/ast/ast.dart'; +import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/constant/value.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; @@ -527,6 +528,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { } final parameters = {}; + final defaultExpressions = {}; final constructorParameters = []; for (final parameter in constructor.formalParameters) { _rejectJsonKey(element, parameter); @@ -540,6 +542,8 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { ); } parameters[fieldName] = parameter; + final defaultExpression = _defaultExpression(element, parameter); + defaultExpressions[fieldName] = defaultExpression; constructorParameters.add( AckConstructorParameter( name: parameter.name!, @@ -550,7 +554,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { typeRef: futureTypes[fieldName]?.runtimeRef ?? _typeRef(parameter.type, field!), - defaultExpression: parameter.defaultValueCode, + defaultExpression: defaultExpression, ), ); } @@ -671,7 +675,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { schema, presence: presence, acceptsNull: acceptsNull, - defaultCode: parameter?.defaultValueCode, + defaultCode: defaultExpressions[name], defaultIsNull: parameter?.computeConstantValue()?.isNull ?? false, ); if (rejectNull) { @@ -686,7 +690,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { acceptsNull: acceptsNull, runtimeRef: futureType?.runtimeRef ?? _typeRef(field.type, field), schemaExpression: schema, - defaultExpression: parameter?.defaultValueCode, + defaultExpression: defaultExpressions[name], ), ); } @@ -1323,6 +1327,32 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { ); } + String? _defaultExpression( + ClassElement owner, + FormalParameterElement parameter, + ) { + final original = parameter.defaultValueCode; + if (original == null) return null; + final declaration = inputResolved?.getFragmentDeclaration( + parameter.firstFragment, + ); + final content = declaration?.resolvedUnit?.content; + final node = declaration?.node; + if (content == null || node is! FormalParameter) return original; + final value = node.defaultClause?.value; + if (value == null) return original; + final visitor = _ClassStaticReferences(owner); + value.accept(visitor); + if (visitor.offsets.isEmpty) return original; + + var qualified = content.substring(value.offset, value.end); + for (final offset in visitor.offsets.reversed) { + final relative = offset - value.offset; + qualified = qualified.replaceRange(relative, relative, '${owner.name}.'); + } + return qualified; + } + _ModelOptions? _options(ClassElement element) { final annotation = ModelGraphBuilderBase.schemableChecker .firstAnnotationOfExact(element); @@ -1490,3 +1520,30 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { declarationName: element.name!, ); } + +/// Marks unqualified references that need the class name in the generated part. +final class _ClassStaticReferences extends RecursiveAstVisitor { + _ClassStaticReferences(this.owner); + + final ClassElement owner; + final offsets = []; + + @override + void visitSimpleIdentifier(SimpleIdentifier node) { + final element = node.element; + if (element is! ExecutableElement || + !element.isStatic || + element.enclosingElement != owner) { + return; + } + final parent = node.parent; + if (parent is PrefixedIdentifier && identical(parent.identifier, node) || + parent is PropertyAccess && identical(parent.propertyName, node) || + parent is MethodInvocation && + parent.target != null && + identical(parent.methodName, node)) { + return; + } + offsets.add(node.offset); + } +} diff --git a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart index 66228a4d..bfc25508 100644 --- a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart @@ -243,6 +243,20 @@ final keywordFieldsSchema = Ack.object({ 'yield': Ack.string(), }); +@Schemable() +final class StaticDefaults with _$StaticDefaultsAck { + const StaticDefaults({ + this.count = defaultCount, + @IsOptional() this.retries = defaultCount + 1, + this.limit = StaticDefaults.defaultCount, + }); + + static const defaultCount = 20; + final int count; + final int retries; + final int limit; +} + @Schemable(discriminatorKey: r'$type') sealed class SpecialPet with _$SpecialPetAck { const SpecialPet(); @@ -522,6 +536,14 @@ void main() { expect(KeywordFields.parse({...json}..remove('required')).required, isFalse); }); + test('constructor defaults can use unqualified class statics', () { + final model = StaticDefaultsSchema.parse({}); + expect(model.count, 20); + expect(model.retries, 21); + expect(model.limit, 20); + expect(model.toJson(), {'count': 20, 'retries': 21, 'limit': 20}); + }); + test('discriminator keys can contain literal dollar signs', () { const pet = {r'$type': 'cat', 'name': 'Milo'}; expect(SpecialPetSchema.parse(pet).toJson(), pet); From 1c09946283421df9923713b8ab1a8ccfb62e909f Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:08:52 -0500 Subject: [PATCH 12/57] fix(generator)!: inherit sealed union branch naming defaults Release readiness C4 and decision Q10. --- docs/core-concepts/typesafe-schemas.mdx | 5 +++ docs/getting-started/migration-guide.mdx | 1 + packages/ack/CHANGELOG.md | 3 ++ .../ack/lib/src/annotations/schemable.dart | 12 +++++- packages/ack_generator/CHANGELOG.md | 5 +++ .../analyzer/class_model_graph_builder.dart | 20 +++++++--- .../ack_infer_runtime_build_test.dart | 38 +++++++++++++++++++ 7 files changed, 77 insertions(+), 7 deletions(-) diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index 4696654e..fd5302f1 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -548,6 +548,11 @@ types because `Ack.list` has no nullable-item contract. ### Class-first unions +Every branch inherits the sealed base’s `caseStyle` by default, including +branches with `@Schemable(discriminatorValue: ...)`. Set a branch’s own +`caseStyle` to override the base. Use `AckCaseStyle.none` to preserve the +branch’s Dart field names. + Annotate a sealed base with a discriminator key. Concrete branches in the same library are included automatically, and inherited constructor fields may use super parameters: diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 9b3d2838..6789fc88 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -88,6 +88,7 @@ Ack is organized into five coordinated packages that share one version number an | **`Is…`/`Has…` rule annotations** | `2.0.0-beta.3` | Field and parameter rules—presence (`@IsRequired()`, `@IsOptional()`), nullability (`@IsNotNull()`), bounds (`@HasMin(0)`), formats (`@IsEmail()`, `@IsDateTime()`, `@IsUri()`), and collection rules (`@IsNotEmpty()`, `@HasUniqueItems()`)—are top-level classes in `package:ack/ack.dart`. The 2.0 beta `Validate` namespace is deprecated and is removed before Ack 2.0.0. | Top-level 1.x classes (`@Required`, `@Email`, `@Uuid`, `@Date`, `@Uri`, `@DateTime`, `@Pattern`) collided with `package:meta` / Flutter (`Required`), `dart:core` (`Uri`, `DateTime`, `Pattern`), and `package:uuid`, forcing import prefixes (`as ack`). The beta `Validate` namespace avoided that with a prefix on every use. The `Is…`/`Has…` names need neither: none of them collides with the Dart SDK, Flutter, or common packages. | | **Single `.g.dart` part & direct JSON emitter** | `2.0.0` | `ack_generator:ack_generator` is a `SharedPartBuilder` that emits `.g.dart` directly with no `json_serializable` or `json_annotation` dependency. | In 1.x, every model required two `part` directives (`.ack.dart` + `.ack.g.dart`) and a second `json_serializable` pass. Direct emission cuts build steps in half, uses standard `part '.g.dart';`, and coexists with Freezed or Riverpod in the same file. | | **Layered custom schema resolution (`T.schema`, `schemas: [...]`)** | `1.7.0` / `2.0.0` | Custom field types resolve via `@Schemable(schemas: [...])` (on classes, unions, or `library;` directives), type-owned `T.schema` / `T.schema()` factories, or automatic detection of a unique top-level `AckSchema` in the current library. | Removed per-field `@AckField(schema: ...)` boilerplate on every field that uses a domain value object, extension type, enum, or generic wrapper. | +| Implicit field style on an annotated branch of a styled sealed class | `2.0.0` | Regenerate to inherit the base’s style. Use `caseStyle: AckCaseStyle.none` on the branch to retain Dart names on the wire. | | **Typed `$ClassCopyWith` getter** | `1.7.0` | `model.copyWith` returns a typed callable interface instead of widening parameters to `Object?`. | Passing `model.copyWith(age: 'wrong')` previously compiled and failed only at runtime (`TypeError`). Now mistyped arguments fail at compile time while `model.copyWith(age: null)` still clears nullable fields. | | **Two-way string normalizers (`.trim()`, `.toLowerCase()`, `.toUpperCase()`)** | `2.0.0` | Normalizers live directly on `StringSchema` and run in declaration order alongside constraints during both `parse` and `encode`. | In 1.x, `.trim()` used a one-way `.transform()`, which failed on `encode()`, was rejected by `@Schemable()`, and emitted `'x-transformed': true` in JSON Schema. | | **`JsonMaybe` (`JsonAbsent` / `JsonValue`)** | `2.0.0` | Tri-state field container for class-first `@Schemable()` models. | A plain `String?` field in Dart cannot distinguish `{"bio": null}` (clear field in a `PATCH` request) from `{}` (leave field unchanged) when encoding back to JSON. | diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 5fa627cc..39b44a46 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -2,6 +2,9 @@ ### Breaking +* **Breaking:** Annotated union branches inherit the base case style when + their own style is omitted. Use `AckCaseStyle.none` to keep Dart names. + * **Breaking:** International hostname and email format checks no longer apply NFKC normalization by default. Pass `unicodeNormalizer: nfkc` from `package:unorm_dart` to `Ack.fromJsonSchema()` to keep the earlier diff --git a/packages/ack/lib/src/annotations/schemable.dart b/packages/ack/lib/src/annotations/schemable.dart index 5a4d2676..fbdfe4fb 100644 --- a/packages/ack/lib/src/annotations/schemable.dart +++ b/packages/ack/lib/src/annotations/schemable.dart @@ -38,13 +38,14 @@ final class Schemable { this.name, this.schemaName, this.description, - this.caseStyle = AckCaseStyle.none, + AckCaseStyle? caseStyle, this.discriminatorKey, this.discriminatorValue, this.unknownProperties = AckUnknownPropertyPolicy.reject, this.captureField = 'additionalProperties', this.schemas, - }); + }) : caseStyle = caseStyle ?? AckCaseStyle.none, + _caseStyleWasSet = caseStyle != null; /// Exact generated model name for a top-level schema declaration. final String? name; @@ -59,8 +60,15 @@ final class Schemable { final String? description; /// JSON field-name style for a class declaration. + /// + /// An omitted style inherits the base style for a sealed union branch. + /// Use [AckCaseStyle.none] to keep the branch's Dart field names as-is. final AckCaseStyle caseStyle; + // The generator distinguishes omission from an explicit none override. + // ignore: unused_field + final bool _caseStyleWasSet; + /// Discriminator key for a sealed class declaration. final String? discriminatorKey; diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 8aeff599..2a540382 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -1,5 +1,10 @@ ## Unreleased +### Breaking + +* **Breaking:** Annotated union branches inherit the base case style when + their own style is omitted. Use `AckCaseStyle.none` to keep Dart names. + ### Fixed * Qualify references to class statics in generated constructor defaults. diff --git a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart index 39fce58c..ad374a82 100644 --- a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart @@ -389,7 +389,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { final valueOwners = {}; for (final branch in candidates) { final branchOptions = - _options(branch) ?? + _options(branch, inheritedCaseStyle: baseOptions.caseStyle) ?? ( schemaName: null, description: null, @@ -1353,17 +1353,27 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { return qualified; } - _ModelOptions? _options(ClassElement element) { + _ModelOptions? _options( + ClassElement element, { + annotations.AckCaseStyle inheritedCaseStyle = annotations.AckCaseStyle.none, + }) { final annotation = ModelGraphBuilderBase.schemableChecker .firstAnnotationOfExact(element); if (annotation == null) return null; final reader = ConstantReader(annotation); - final caseStyle = reader.read('caseStyle').objectValue; - final caseIndex = caseStyle.getField('index')!.toIntValue()!; + final caseStyleWasSet = + annotation.getField('_caseStyleWasSet')?.toBoolValue() ?? true; + final caseIndex = reader + .read('caseStyle') + .objectValue + .getField('index')! + .toIntValue()!; return ( schemaName: _nullableString(reader, 'schemaName'), description: _nullableString(reader, 'description'), - caseStyle: annotations.AckCaseStyle.values[caseIndex], + caseStyle: caseStyleWasSet + ? annotations.AckCaseStyle.values[caseIndex] + : inheritedCaseStyle, discriminatorKey: _nullableString(reader, 'discriminatorKey'), discriminatorValue: _nullableString(reader, 'discriminatorValue'), unknownProperties: diff --git a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart index bfc25508..f221a84c 100644 --- a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart @@ -243,6 +243,34 @@ final keywordFieldsSchema = Ack.object({ 'yield': Ack.string(), }); +@Schemable(discriminatorKey: 'kind', caseStyle: AckCaseStyle.snake) +sealed class StyleAnimal with _$StyleAnimalAck { + const StyleAnimal(); +} + +@Schemable(discriminatorValue: 'cat') +final class StyleCat extends StyleAnimal with _$StyleCatAck { + const StyleCat({required this.livesLeft}); + final int livesLeft; +} + +final class StyleDog extends StyleAnimal with _$StyleDogAck { + const StyleDog({required this.furColor}); + final String furColor; +} + +@Schemable(discriminatorValue: 'bird', caseStyle: AckCaseStyle.none) +final class StyleBird extends StyleAnimal with _$StyleBirdAck { + const StyleBird({required this.wingCount}); + final int wingCount; +} + +@Schemable(discriminatorValue: 'fish', caseStyle: AckCaseStyle.pascal) +final class StyleFish extends StyleAnimal with _$StyleFishAck { + const StyleFish({required this.finCount}); + final int finCount; +} + @Schemable() final class StaticDefaults with _$StaticDefaultsAck { const StaticDefaults({ @@ -536,6 +564,16 @@ void main() { expect(KeywordFields.parse({...json}..remove('required')).required, isFalse); }); + test('union branches inherit the base style and honor explicit overrides', () { + expect(const StyleCat(livesLeft: 9).toJson(), {'kind': 'cat', 'lives_left': 9}); + expect( + const StyleDog(furColor: 'black').toJson(), + {'kind': 'StyleDog', 'fur_color': 'black'}, + ); + expect(const StyleBird(wingCount: 2).toJson(), {'kind': 'bird', 'wingCount': 2}); + expect(const StyleFish(finCount: 2).toJson(), {'kind': 'fish', 'FinCount': 2}); + }); + test('constructor defaults can use unqualified class statics', () { final model = StaticDefaultsSchema.parse({}); expect(model.count, 20); From 57b52ef597c22c0cbb2f91e3c688266813b30ddf Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:09:26 -0500 Subject: [PATCH 13/57] fix(generator): name inline JSON Schema objects in UpperCamelCase Release readiness C5. --- packages/ack_generator/CHANGELOG.md | 2 ++ .../lib/src/analyzer/schema_first_names.dart | 7 +++++++ .../json_schema/json_schema_translator.dart | 2 +- .../json_schema/json_schema_library_test.dart | 21 +++++++++++++++++++ 4 files changed, 31 insertions(+), 1 deletion(-) diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 2a540382..60d5a1f1 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -7,6 +7,8 @@ ### Fixed +* Derive UpperCamelCase model names for inline objects under snake_case keys. + * Qualify references to class statics in generated constructor defaults. * Escape literal dollar signs and quotes in generated discriminator messages. diff --git a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart index a7c05001..31a6e446 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart @@ -45,3 +45,10 @@ String? ackSchemaFirstFieldNameProblem( } return null; } + +/// UpperCamelCase segment for a generated model name derived from a key. +String ackSchemaFirstTypeNameSegment(String key) => key + .split(RegExp(r'[^A-Za-z0-9]+')) + .where((segment) => segment.isNotEmpty) + .map((segment) => '${segment[0].toUpperCase()}${segment.substring(1)}') + .join(); diff --git a/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart b/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart index fd4734f4..d0b60cb1 100644 --- a/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart +++ b/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart @@ -881,7 +881,7 @@ final class _Translator { value, fieldPointer, owner: owner, - hoistName: '$hoistName${key[0].toUpperCase()}${key.substring(1)}', + hoistName: '$hoistName${ackSchemaFirstTypeNameSegment(key)}', ); if (field == null) continue; entries.add( diff --git a/packages/ack_generator/test/json_schema/json_schema_library_test.dart b/packages/ack_generator/test/json_schema/json_schema_library_test.dart index 26dc358e..a8b00c52 100644 --- a/packages/ack_generator/test/json_schema/json_schema_library_test.dart +++ b/packages/ack_generator/test/json_schema/json_schema_library_test.dart @@ -212,6 +212,27 @@ void main() { ); }); + test('snake_case inline object keys produce UpperCamelCase models', () { + final source = _squash( + _generate( + _model({ + 'shipping_address': { + 'type': 'object', + 'properties': { + 'city': {'type': 'string'}, + }, + 'additionalProperties': false, + }, + }), + ).source, + ); + expect(source, contains("@ack.Schemable(name:'ModelShippingAddress')")); + expect( + source, + contains("'shipping_address':modelShippingAddressSchema.optional()"), + ); + }); + test(r'a $ref as the referenced model', () { final source = _squash( _generate({ From 71586722111abf8c7e2599fdf9035499a6104787 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:10:18 -0500 Subject: [PATCH 14/57] fix(generator)!: validate through class-owned schemas Release readiness C6. --- docs/core-concepts/typesafe-schemas.mdx | 5 ++++ docs/getting-started/migration-guide.mdx | 1 + packages/ack_generator/CHANGELOG.md | 3 ++ .../analyzer/class_model_graph_builder.dart | 1 + .../src/analyzer/custom_schema_resolver.dart | 9 ++++-- .../lib/src/builders/class_model_emitter.dart | 16 ++++++---- .../lib/src/models/schema_model_graph.dart | 2 ++ .../ack_infer_runtime_build_test.dart | 29 +++++++++++++++++++ .../build-data-classes-with-ack/SKILL.md | 4 +-- 9 files changed, 60 insertions(+), 10 deletions(-) diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index fd5302f1..dc5f9121 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -546,6 +546,11 @@ static schema; use `Object?` for an open JSON value. Automatic `List` and `Set` inference also requires non-nullable element types because `Ack.list` has no nullable-item contract. +The generated parse and encode helpers, including `toJson()` and +`safeToJson()`, validate with a class's static `schema` when it declares one. +Nested class-first fields also use that schema. Use `ModelSchema.schema` as the +raw generated schema when declaring `Model.schema` with refinements. + ### Class-first unions Every branch inherits the sealed base’s `caseStyle` by default, including diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 6789fc88..48ea2d50 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -89,6 +89,7 @@ Ack is organized into five coordinated packages that share one version number an | **Single `.g.dart` part & direct JSON emitter** | `2.0.0` | `ack_generator:ack_generator` is a `SharedPartBuilder` that emits `.g.dart` directly with no `json_serializable` or `json_annotation` dependency. | In 1.x, every model required two `part` directives (`.ack.dart` + `.ack.g.dart`) and a second `json_serializable` pass. Direct emission cuts build steps in half, uses standard `part '.g.dart';`, and coexists with Freezed or Riverpod in the same file. | | **Layered custom schema resolution (`T.schema`, `schemas: [...]`)** | `1.7.0` / `2.0.0` | Custom field types resolve via `@Schemable(schemas: [...])` (on classes, unions, or `library;` directives), type-owned `T.schema` / `T.schema()` factories, or automatic detection of a unique top-level `AckSchema` in the current library. | Removed per-field `@AckField(schema: ...)` boilerplate on every field that uses a domain value object, extension type, enum, or generic wrapper. | | Implicit field style on an annotated branch of a styled sealed class | `2.0.0` | Regenerate to inherit the base’s style. Use `caseStyle: AckCaseStyle.none` on the branch to retain Dart names on the wire. | +| Class-owned schema refinements | `2.0.0` | Generated helpers and nested fields now enforce them. Compose `ModelSchema.schema` explicitly when you need the raw generated rules. | | **Typed `$ClassCopyWith` getter** | `1.7.0` | `model.copyWith` returns a typed callable interface instead of widening parameters to `Object?`. | Passing `model.copyWith(age: 'wrong')` previously compiled and failed only at runtime (`TypeError`). Now mistyped arguments fail at compile time while `model.copyWith(age: null)` still clears nullable fields. | | **Two-way string normalizers (`.trim()`, `.toLowerCase()`, `.toUpperCase()`)** | `2.0.0` | Normalizers live directly on `StringSchema` and run in declaration order alongside constraints during both `parse` and `encode`. | In 1.x, `.trim()` used a one-way `.transform()`, which failed on `encode()`, was rejected by `@Schemable()`, and emitted `'x-transformed': true` in JSON Schema. | | **`JsonMaybe` (`JsonAbsent` / `JsonValue`)** | `2.0.0` | Tri-state field container for class-first `@Schemable()` models. | A plain `String?` field in Dart cannot distinguish `{"bio": null}` (clear field in a `PATCH` request) from `{}` (leave field unchanged) when encoding back to JSON. | diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 60d5a1f1..285395ed 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -2,6 +2,9 @@ ### Breaking +* **Breaking:** Generated helpers and nested fields enforce class-owned + schema refinements (#263). + * **Breaking:** Annotated union branches inherit the base case style when their own style is omitted. Use `AckCaseStyle.none` to keep Dart names. diff --git a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart index ad374a82..c9f89c7e 100644 --- a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart @@ -1314,6 +1314,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { AckClassModelMetadata( facadeName: facadeName, backingName: backingName, + hasStaticSchema: element.getGetter('schema')?.isStatic ?? false, copyWithSupertypes: { for (final supertype in element.allSupertypes) if (supertype.element case final ClassElement parent) diff --git a/packages/ack_generator/lib/src/analyzer/custom_schema_resolver.dart b/packages/ack_generator/lib/src/analyzer/custom_schema_resolver.dart index 7f65295c..53f81f99 100644 --- a/packages/ack_generator/lib/src/analyzer/custom_schema_resolver.dart +++ b/packages/ack_generator/lib/src/analyzer/custom_schema_resolver.dart @@ -531,8 +531,13 @@ final class CustomSchemaResolver { path: path, context: field, ); - if (target.library != _library.element && - !_isClassFirstFacadeVisible(target, facadeName, prefix: prefix)) { + if (target.getGetter('schema')?.isStatic == true || + target.library != _library.element && + !_isClassFirstFacadeVisible( + target, + facadeName, + prefix: prefix, + )) { final typeOwned = await typeOwnedSchema( interfaceType, field, diff --git a/packages/ack_generator/lib/src/builders/class_model_emitter.dart b/packages/ack_generator/lib/src/builders/class_model_emitter.dart index af07586b..bad01f93 100644 --- a/packages/ack_generator/lib/src/builders/class_model_emitter.dart +++ b/packages/ack_generator/lib/src/builders/class_model_emitter.dart @@ -183,8 +183,11 @@ final $backingName = $input.codec<${node.className}>( String className, AckClassModelMetadata metadata, { required String wireName, - }) => - ''' + }) { + final validationSchema = metadata.hasStaticSchema + ? '$className.schema' + : metadata.backingName; + return ''' /// Parses, validates, and encodes [$className] values. abstract final class ${metadata.facadeName} { /// The typed schema, for composing [$className] into other schemas. @@ -199,13 +202,13 @@ abstract final class ${metadata.facadeName} { /// /// Throws an `AckException` when validation fails. static $className parse(Object? value, {String? debugName}) => - ${metadata.backingName}.parse(value, debugName: debugName)!; + $validationSchema.parse(value, debugName: debugName)!; /// Validates [value] and returns the model or the validation failure. static ${_ack('SchemaResult')}<$className> safeParse( Object? value, { String? debugName, - }) => ${metadata.backingName}.safeParse(value, debugName: debugName); + }) => $validationSchema.safeParse(value, debugName: debugName); /// Validates decoded [json] and creates the model. /// @@ -218,14 +221,14 @@ abstract final class ${metadata.facadeName} { static Map encode( $className value, { String? debugName, - }) => ${metadata.backingName}.encode(value, debugName: debugName)!; + }) => $validationSchema.encode(value, debugName: debugName)!; /// Validates [value] and encodes it as a JSON map, returning the validation /// failure instead of throwing. static ${_ack('SchemaResult')}> safeEncode( $className value, { String? debugName, - }) => ${metadata.backingName}.safeEncode(value, debugName: debugName); + }) => $validationSchema.safeEncode(value, debugName: debugName); /// The JSON Schema that describes [$className]. static Map toJsonSchema() => @@ -235,6 +238,7 @@ abstract final class ${metadata.facadeName} { static ${_ack('AckSchemaModel')} toSchemaModel() => ${_ack('AckSchemaModelExtension')}(${metadata.backingName}).toSchemaModel(); }'''; + } String _objectSchema(AckObjectModelNode node) { final entries = [ diff --git a/packages/ack_generator/lib/src/models/schema_model_graph.dart b/packages/ack_generator/lib/src/models/schema_model_graph.dart index 303ee88b..dc9145c8 100644 --- a/packages/ack_generator/lib/src/models/schema_model_graph.dart +++ b/packages/ack_generator/lib/src/models/schema_model_graph.dart @@ -204,11 +204,13 @@ final class AckClassModelMetadata { const AckClassModelMetadata({ required this.facadeName, required this.backingName, + this.hasStaticSchema = false, this.copyWithSupertypes = const [], }); final String facadeName; final String backingName; + final bool hasStaticSchema; final List copyWithSupertypes; } diff --git a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart index f221a84c..c9a44b13 100644 --- a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart @@ -243,6 +243,23 @@ final keywordFieldsSchema = Ack.object({ 'yield': Ack.string(), }); +@Schemable() +final class RefinedWindow with _$RefinedWindowAck { + const RefinedWindow({required this.start, required this.end}); + final int start; + final int end; + static final schema = RefinedWindowSchema.schema.refine( + (window) => window.start <= window.end, + message: 'start must be before end', + ); +} + +@Schemable() +final class RefinedBooking with _$RefinedBookingAck { + const RefinedBooking({required this.window}); + final RefinedWindow window; +} + @Schemable(discriminatorKey: 'kind', caseStyle: AckCaseStyle.snake) sealed class StyleAnimal with _$StyleAnimalAck { const StyleAnimal(); @@ -564,6 +581,18 @@ void main() { expect(KeywordFields.parse({...json}..remove('required')).required, isFalse); }); + test('class-owned refinements apply at every generated boundary', () { + const window = RefinedWindow(start: 2, end: 1); + const json = {'start': 2, 'end': 1}; + expect(RefinedWindowSchema.schema.safeEncode(window).isOk, isTrue); + expect(RefinedWindow.schema.safeEncode(window).isFail, isTrue); + expect(window.toJson, throwsA(isA())); + expect(window.safeToJson().isFail, isTrue); + expect(RefinedWindowSchema.safeEncode(window).isFail, isTrue); + expect(RefinedWindowSchema.safeParse(json).isFail, isTrue); + expect(RefinedBookingSchema.safeParse({'window': json}).isFail, isTrue); + }); + test('union branches inherit the base style and honor explicit overrides', () { expect(const StyleCat(livesLeft: 9).toJson(), {'kind': 'cat', 'lives_left': 9}); expect( diff --git a/plugins/ack/skills/build-data-classes-with-ack/SKILL.md b/plugins/ack/skills/build-data-classes-with-ack/SKILL.md index 8a5eebc4..4ed5514b 100644 --- a/plugins/ack/skills/build-data-classes-with-ack/SKILL.md +++ b/plugins/ack/skills/build-data-classes-with-ack/SKILL.md @@ -67,7 +67,7 @@ Run `dart run build_runner build`. For a class-first model the build writes `.value(null)` (explicit `null` on the wire). - `copyWith(notes: null)` clears a nullable field; leaving the argument out keeps it. - Compose: `Ack.list(Invoice.schema)`, or a field typed `Invoice` inside another `@Schemable` class. @@ -81,6 +81,6 @@ Run `dart run build_runner build`. For a class-first model the build writes ` Date: Tue, 1 Dec 2026 09:11:36 -0500 Subject: [PATCH 15/57] fix(generator): report invalid rule arguments at their source Release readiness C7. --- packages/ack_generator/CHANGELOG.md | 3 + .../lib/src/inference/schema_inference.dart | 67 +++++++++++++++---- .../integration/class_model_graph_test.dart | 20 ++++++ 3 files changed, 76 insertions(+), 14 deletions(-) diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 285395ed..aa8d3b65 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -10,6 +10,9 @@ ### Fixed +* Report invalid rule arguments on the annotated field, including non-integer + arguments on integer fields, negative lengths, and invalid regular expressions. + * Derive UpperCamelCase model names for inline objects under snake_case keys. * Qualify references to class statics in generated constructor defaults. diff --git a/packages/ack_generator/lib/src/inference/schema_inference.dart b/packages/ack_generator/lib/src/inference/schema_inference.dart index bbf24f90..f45cbbec 100644 --- a/packages/ack_generator/lib/src/inference/schema_inference.dart +++ b/packages/ack_generator/lib/src/inference/schema_inference.dart @@ -107,6 +107,7 @@ final class AckSchemaInference { (_core(scalarType, 'int') || _core(scalarType, 'double') || _core(scalarType, 'num')); + final isInteger = scalarType is InterfaceType && _core(scalarType, 'int'); final isString = scalarType is InterfaceType && _core(scalarType, 'String'); final itemConstraints = []; final setConstraints = []; @@ -142,17 +143,17 @@ final class AckSchemaInference { case 'HasMin': _require(declaration, type, annotation, isNumeric, '@HasMinLength'); addScalarConstraint( - '.min(${_number(declaration, annotation, value, 'min')})', + '.min(${_number(declaration, annotation, value, 'min', requireInteger: isInteger)})', ); case 'HasMax': _require(declaration, type, annotation, isNumeric, '@HasMaxLength'); addScalarConstraint( - '.max(${_number(declaration, annotation, value, 'max')})', + '.max(${_number(declaration, annotation, value, 'max', requireInteger: isInteger)})', ); case 'IsMultipleOf': _require(declaration, type, annotation, isNumeric, 'numeric field'); addScalarConstraint( - '.multipleOf(${_number(declaration, annotation, value, 'divisor')})', + '.multipleOf(${_number(declaration, annotation, value, 'divisor', requireInteger: isInteger)})', ); case 'IsPositive': _require(declaration, type, annotation, isNumeric, 'numeric field'); @@ -162,15 +163,27 @@ final class AckSchemaInference { addScalarConstraint('.negative()'); case 'HasMinLength': _require(declaration, type, annotation, isString, '@HasMin'); - addScalarConstraint('.minLength(${_int(value, 'length')})'); + addScalarConstraint( + '.minLength(${_nonNegativeInt(declaration, annotation, value, 'length')})', + ); case 'HasMaxLength': _require(declaration, type, annotation, isString, '@HasMax'); - addScalarConstraint('.maxLength(${_int(value, 'length')})'); - case 'HasMatch': - _require(declaration, type, annotation, isString, 'String field'); addScalarConstraint( - '.matches(${dartStringLiteral(value.getField('pattern')!.toStringValue()!)})', + '.maxLength(${_nonNegativeInt(declaration, annotation, value, 'length')})', ); + case 'HasMatch': + _require(declaration, type, annotation, isString, 'String field'); + final pattern = value.getField('pattern')!.toStringValue()!; + try { + RegExp(pattern); + } on FormatException catch (error) { + throw InvalidGenerationSource( + '${_qualifiedName(declaration)} has an invalid @HasMatch ' + 'regular expression: ${error.message}', + element: declaration, + ); + } + addScalarConstraint('.matches(${dartStringLiteral(pattern)})'); case 'IsNotEmpty': _require( declaration, @@ -225,7 +238,9 @@ final class AckSchemaInference { isCollection, 'List or Set field', ); - addCollectionConstraint('.minItems(${_int(value, 'count')})'); + addCollectionConstraint( + '.minItems(${_nonNegativeInt(declaration, annotation, value, 'count')})', + ); case 'HasMaxItems': _require( declaration, @@ -234,7 +249,9 @@ final class AckSchemaInference { isCollection, 'List or Set field', ); - addCollectionConstraint('.maxItems(${_int(value, 'count')})'); + addCollectionConstraint( + '.maxItems(${_nonNegativeInt(declaration, annotation, value, 'count')})', + ); case 'HasUniqueItems': _require( declaration, @@ -355,15 +372,30 @@ final class AckSchemaInference { String _ack(String symbol) => qualifySymbol(ackPrefix, symbol); - int _int(DartObject value, String name) => - value.getField(name)!.toIntValue()!; - - String _number( + int _nonNegativeInt( Element declaration, String annotation, DartObject value, String name, ) { + final argument = value.getField(name)!.toIntValue()!; + if (argument < 0) { + throw InvalidGenerationSource( + '${_qualifiedName(declaration)} has $annotation($argument). ' + 'The $name must be nonnegative.', + element: declaration, + ); + } + return argument; + } + + String _number( + Element declaration, + String annotation, + DartObject value, + String name, { + required bool requireInteger, + }) { final field = value.getField(name)!; final number = (field.toIntValue() ?? field.toDoubleValue())!; if (!number.isFinite) { @@ -373,6 +405,13 @@ final class AckSchemaInference { element: declaration, ); } + if (requireInteger && number is! int) { + throw InvalidGenerationSource( + '${_qualifiedName(declaration)} has $annotation($number). ' + 'Use an integer argument on an int field.', + element: declaration, + ); + } return number.toString(); } diff --git a/packages/ack_generator/test/integration/class_model_graph_test.dart b/packages/ack_generator/test/integration/class_model_graph_test.dart index 54cfe8ea..67dcf810 100644 --- a/packages/ack_generator/test/integration/class_model_graph_test.dart +++ b/packages/ack_generator/test/integration/class_model_graph_test.dart @@ -1240,6 +1240,26 @@ final class Address with _\$AddressAck { ); }); + test('reports invalid rule arguments on the annotated field', () async { + for (final (type, annotation, diagnostic) in [ + ('int', '@HasMin(0.5)', 'Use an integer argument on an int field.'), + ('String', '@HasMinLength(-1)', 'The length must be nonnegative.'), + ('List', '@HasMaxItems(-1)', 'The count must be nonnegative.'), + ('String', "@HasMatch('(')", 'invalid @HasMatch regular expression'), + ]) { + await _expectFailure( + ''' +@Schemable() +final class User with _\$UserAck { + const User({$annotation required this.value}); + final $type value; +} +''', + ['User.value', diagnostic], + ); + } + }); + test( 'rejects invalid rule annotations on mismatched field types or values', () async { From 3c81ef906eee32df8b7e705cbd890e12cf9affc3 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:13:24 -0500 Subject: [PATCH 16/57] feat(generator)!: derive Dart field names from schema-first JSON keys Release readiness C8 and decision Q11. --- docs/core-concepts/typesafe-schemas.mdx | 5 ++ docs/getting-started/migration-guide.mdx | 1 + example/lib/schema_types_simple.dart | 1 + example/lib/schema_types_simple.g.dart | 46 +++++++++++++++---- example/test/schema_variable_test.dart | 12 +++++ packages/ack_generator/CHANGELOG.md | 3 ++ .../lib/src/analyzer/schema_first_names.dart | 18 ++++++++ .../analyzer/schema_model_graph_builder.dart | 15 +++++- .../json_schema/json_schema_translator.dart | 2 +- .../integration/ack_infer_graph_test.dart | 18 ++++++-- .../ack_infer_runtime_build_test.dart | 16 +++++++ 11 files changed, 121 insertions(+), 16 deletions(-) diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index dc5f9121..56991028 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -138,6 +138,11 @@ Generation also rejects nullable roots, `Ack.any()` and `Ack.map()` roots, `Ack.anyOf()`, bare `Ack.instance()`, anonymous inline object fields, unresolved dynamic schema factories, and cross-library union branches. +Schema-first JSON keys keep their spelling on the wire. Generated Dart fields +use lowerCamelCase. For example, `first_name` becomes `firstName`, `user-id` +becomes `userId`, and `_nickname` becomes `nickname`. Generation reports +reserved words and keys that map to the same field name. + ### Schema-first unions Each branch must be a named `@Schemable()` object schema in the same library: diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 48ea2d50..81d90cc9 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -90,6 +90,7 @@ Ack is organized into five coordinated packages that share one version number an | **Layered custom schema resolution (`T.schema`, `schemas: [...]`)** | `1.7.0` / `2.0.0` | Custom field types resolve via `@Schemable(schemas: [...])` (on classes, unions, or `library;` directives), type-owned `T.schema` / `T.schema()` factories, or automatic detection of a unique top-level `AckSchema` in the current library. | Removed per-field `@AckField(schema: ...)` boilerplate on every field that uses a domain value object, extension type, enum, or generic wrapper. | | Implicit field style on an annotated branch of a styled sealed class | `2.0.0` | Regenerate to inherit the base’s style. Use `caseStyle: AckCaseStyle.none` on the branch to retain Dart names on the wire. | | Class-owned schema refinements | `2.0.0` | Generated helpers and nested fields now enforce them. Compose `ModelSchema.schema` explicitly when you need the raw generated rules. | +| Schema-first fields using snake_case or another wire spelling | `2.0.0` | Regenerate and use the lowerCamelCase Dart names in field accesses, constructors and `copyWith`. JSON keys keep their original spelling. | | **Typed `$ClassCopyWith` getter** | `1.7.0` | `model.copyWith` returns a typed callable interface instead of widening parameters to `Object?`. | Passing `model.copyWith(age: 'wrong')` previously compiled and failed only at runtime (`TypeError`). Now mistyped arguments fail at compile time while `model.copyWith(age: null)` still clears nullable fields. | | **Two-way string normalizers (`.trim()`, `.toLowerCase()`, `.toUpperCase()`)** | `2.0.0` | Normalizers live directly on `StringSchema` and run in declaration order alongside constraints during both `parse` and `encode`. | In 1.x, `.trim()` used a one-way `.transform()`, which failed on `encode()`, was rejected by `@Schemable()`, and emitted `'x-transformed': true` in JSON Schema. | | **`JsonMaybe` (`JsonAbsent` / `JsonValue`)** | `2.0.0` | Tri-state field container for class-first `@Schemable()` models. | A plain `String?` field in Dart cannot distinguish `{"bio": null}` (clear field in a `PATCH` request) from `{}` (leave field unchanged) when encoding back to JSON. | diff --git a/example/lib/schema_types_simple.dart b/example/lib/schema_types_simple.dart index 7132d1dc..5b1b79be 100644 --- a/example/lib/schema_types_simple.dart +++ b/example/lib/schema_types_simple.dart @@ -8,4 +8,5 @@ final userSchema = Ack.object({ 'name': Ack.string(), 'age': Ack.integer(), 'active': Ack.boolean(), + 'account_id': Ack.string().optional(), }); diff --git a/example/lib/schema_types_simple.g.dart b/example/lib/schema_types_simple.g.dart index 6bc7074c..645a8ad3 100644 --- a/example/lib/schema_types_simple.g.dart +++ b/example/lib/schema_types_simple.g.dart @@ -16,7 +16,12 @@ final class User { /// /// Use `parse` or `fromJson` for untrusted input. `toJson` validates /// the model while encoding it. - User({required this.name, required this.age, required this.active}); + User({ + required this.name, + required this.age, + required this.active, + this.accountId, + }); /// Validates [input] and creates the model. /// @@ -38,6 +43,8 @@ final class User { final bool active; + final String? accountId; + /// The Ack adapter that parses and encodes this model. static final $ack = AckModelAdapter( schema: () => userSchema, @@ -70,9 +77,10 @@ final class User { identical(this, other) || (other is User && runtimeType == other.runtimeType && - deepEquals(name, other.name) && - deepEquals(age, other.age) && - deepEquals(active, other.active)); + deepEquals(this.name, other.name) && + deepEquals(this.age, other.age) && + deepEquals(this.active, other.active) && + deepEquals(this.accountId, other.accountId)); @override int get hashCode => Object.hashAll([ @@ -80,42 +88,60 @@ final class User { deepHashCode(name), deepHashCode(age), deepHashCode(active), + deepHashCode(accountId), ]); @override - String toString() => 'User(name: ${name}, age: ${age}, active: ${active})'; + String toString() => + 'User(name: ${name}, age: ${age}, active: ${active}, accountId: ${accountId})'; static User _fromAckRuntime(Map value) => User( name: value['name'] as String, age: value['age'] as int, active: value['active'] as bool, + accountId: value['account_id'] as String?, ); Map _toAckRuntime() => { - 'name': name, - 'age': age, - 'active': active, + 'name': this.name, + 'age': this.age, + 'active': this.active, + 'account_id': ?this.accountId, }; } +final class _UserCopyWithUnset { + const _UserCopyWithUnset(); +} + /// Creates copies of [User] with selected fields replaced. abstract interface class $UserCopyWith<$Result> { /// Returns a copy with the given fields replaced. /// /// An omitted argument keeps the current value. An explicit `null` clears a /// nullable field. - $Result call({String? name, int? age, bool? active}); + $Result call({String? name, int? age, bool? active, String? accountId}); } final class _$UserCopyWith implements $UserCopyWith { const _$UserCopyWith(this._source); + static const _UserCopyWithUnset _ackCopyWithUnset = _UserCopyWithUnset(); + final User _source; @override - User call({String? name, int? age, bool? active}) => User( + User call({ + String? name, + int? age, + bool? active, + Object? accountId = _ackCopyWithUnset, + }) => User( name: name ?? _source.name, age: age ?? _source.age, active: active ?? _source.active, + accountId: identical(accountId, _ackCopyWithUnset) + ? _source.accountId + : accountId as String?, ); } diff --git a/example/test/schema_variable_test.dart b/example/test/schema_variable_test.dart index 84b36192..a2c01b70 100644 --- a/example/test/schema_variable_test.dart +++ b/example/test/schema_variable_test.dart @@ -14,6 +14,18 @@ void main() { expect(user.active, true); }); + test('User exposes a lowerCamelCase field for a snake_case wire key', () { + final wire = { + 'name': 'Alice', + 'age': 30, + 'active': true, + 'account_id': 'acct-1', + }; + final user = User.parse(wire); + expect(user.accountId, 'acct-1'); + expect(user.toJson(), wire); + }); + test('User validates data through schema', () { final invalidData = { 'name': 'Alice', diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index aa8d3b65..17d5ad86 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -2,6 +2,9 @@ ### Breaking +* **Breaking:** Generate lowerCamelCase Dart fields from schema-first JSON + keys. Wire keys keep their original spelling. + * **Breaking:** Generated helpers and nested fields enforce class-owned schema refinements (#263). diff --git a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart index 31a6e446..3f70946e 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart @@ -52,3 +52,21 @@ String ackSchemaFirstTypeNameSegment(String key) => key .where((segment) => segment.isNotEmpty) .map((segment) => '${segment[0].toUpperCase()}${segment.substring(1)}') .join(); + +/// Dart field name for a schema-first wire key. +String ackSchemaFirstDartFieldName(String key) { + final words = key.split(RegExp(r'[_-]+')).where((word) => word.isNotEmpty); + if (words.isEmpty) return ''; + + String lowerInitial(String word) => word.replaceFirstMapped( + RegExp(r'^[A-Z]+(?=[A-Z][a-z]|[^A-Za-z]|$)|^[A-Z]'), + (match) => match[0]!.toLowerCase(), + ); + + final first = lowerInitial(words.first); + final rest = words.skip(1).map((word) { + final normalized = lowerInitial(word); + return '${normalized[0].toUpperCase()}${normalized.substring(1)}'; + }); + return first + rest.join(); +} diff --git a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart index 8888864b..3c35566f 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart @@ -358,6 +358,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { ); final fields = []; final declaredKeys = {}; + final wireKeysByFieldName = {}; for (final entry in literal.elements) { if (entry is! MapLiteralEntry || entry.key is! SimpleStringLiteral) { throw InvalidGenerationSource( @@ -372,6 +373,16 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { element: declaration.element, ); } + final dartName = ackSchemaFirstDartFieldName(jsonKey); + final previous = wireKeysByFieldName[dartName]; + if (previous != null) { + throw InvalidGenerationSource( + '$path has JSON keys "$previous" and "$jsonKey" that both map to ' + 'the Dart field "$dartName".', + element: declaration.element, + ); + } + wireKeysByFieldName[dartName] = jsonKey; final fieldPath = '$path.$jsonKey'; final fieldChain = parseSchemaChain(entry.value); final fieldMetadata = await _schemaMetadata( @@ -395,7 +406,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { ); fields.add( AckFieldNode( - dartName: jsonKey, + dartName: dartName, jsonKey: jsonKey, presence: fieldMetadata.presence, nullable: fieldMetadata.nullable, @@ -1336,7 +1347,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { ); if (problem != null) { throw InvalidGenerationSource( - '${node.id.declarationName}.${field.dartName} $problem', + '${node.id.declarationName}.${field.jsonKey} $problem', element: declaration.element, ); } diff --git a/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart b/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart index d0b60cb1..6b4648ef 100644 --- a/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart +++ b/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart @@ -870,7 +870,7 @@ final class _Translator { continue; } final problem = ackSchemaFirstFieldNameProblem( - key, + ackSchemaFirstDartFieldName(key), capturesExtras: open, ); if (problem != null) { diff --git a/packages/ack_generator/test/integration/ack_infer_graph_test.dart b/packages/ack_generator/test/integration/ack_infer_graph_test.dart index 05d045ad..f4cdf75d 100644 --- a/packages/ack_generator/test/integration/ack_infer_graph_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_graph_test.dart @@ -1010,16 +1010,28 @@ final userSchema = Ack.object({ ); }); - test('rejects a leading-underscore JSON key', () async { + test('reports collisions between normalized JSON keys', () async { await _expectFailure( ''' $_head @Schemable() final userSchema = Ack.object({ - '_id': Ack.string(), + 'first_name': Ack.string(), + 'firstName': Ack.string(), }); ''', - ['userSchema._id', "cannot start with '_'"], + ['first_name', 'firstName', 'both map to the Dart field'], + ); + }); + + test('reports reserved names after field-name conversion', () async { + await _expectFailure( + ''' +$_head +@Schemable() +final userSchema = Ack.object({'_class': Ack.string()}); +''', + ['userSchema._class', 'cannot be represented as a Dart field name'], ); }); diff --git a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart index c9a44b13..d2767536 100644 --- a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart @@ -325,6 +325,13 @@ final specialWireChoiceSchema = Ack.discriminated( schemas: {'a': specialWireBranchSchema}, ); +@Schemable() +final wireNamesSchema = Ack.object({ + 'first_name': Ack.string(), + 'user-id': Ack.integer(), + '_nickname': Ack.string(), +}); + @Schemable() final scopedNamesSchema = Ack.object({ 'other': Ack.string(), @@ -618,6 +625,15 @@ void main() { expect(SpecialWireChoice.parse(wire).toJson(), wire); }); + test('schema-first JSON keys keep their wire spelling', () { + const json = {'first_name': 'Ada', 'user-id': 7, '_nickname': 'A'}; + final model = WireNames.parse(json); + expect(model.firstName, 'Ada'); + expect(model.userId, 7); + expect(model.nickname, 'A'); + expect(model.toJson(), json); + }); + test('generated local and parameter names can also be model fields', () { const fields = ['other', 'declared', 'value', 'entry', 'model', 'self', 'item', 'fieldValue', 'key']; From d2b87914864940bffd0b888b4115f1587cfd0858 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:18:25 -0500 Subject: [PATCH 17/57] fix(generator)!: normalize union and generated model behavior Release readiness C9. --- docs/core-concepts/typesafe-schemas.mdx | 13 ++ docs/getting-started/migration-guide.mdx | 5 + .../lib/additional_properties_example.g.dart | 65 +++--- example/lib/class_first_models.g.dart | 26 +-- example/lib/pet.g.dart | 14 +- example/lib/schema_types_discriminated.g.dart | 24 +- example/lib/schema_types_edge_cases.g.dart | 141 +++++------ example/lib/schema_types_primitives.g.dart | 29 ++- example/lib/schema_types_simple.g.dart | 1 - example/lib/schema_types_transforms.g.dart | 49 ++-- example/lib/user_with_color.g.dart | 43 ++-- packages/ack/CHANGELOG.md | 2 + packages/ack/lib/src/schemas/schema.dart | 2 +- packages/ack_generator/CHANGELOG.md | 7 + packages/ack_generator/lib/builder.dart | 2 +- .../analyzer/class_model_graph_builder.dart | 62 +++-- .../analyzer/model_graph_builder_base.dart | 3 - .../lib/src/analyzer/schema_first_names.dart | 4 + .../analyzer/schema_model_graph_builder.dart | 53 ++--- .../lib/src/builders/data_class_emitter.dart | 219 ++++++++---------- .../lib/src/builders/model_emitter.dart | 11 +- .../lib/src/inference/schema_inference.dart | 13 +- .../lib/src/model_generator.dart | 1 - .../integration/ack_infer_contract_test.dart | 4 +- .../integration/ack_infer_graph_test.dart | 17 -- .../ack_infer_runtime_build_test.dart | 51 ++++ .../integration/class_model_emitter_test.dart | 4 +- .../generated_names_contract_test.dart | 46 +++- 28 files changed, 485 insertions(+), 426 deletions(-) diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index 56991028..f11883e2 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -671,6 +671,19 @@ declare the same model name. Deferred imports are unsupported. Automatic recursive class-first schemas are not yet defined. For self or mutually recursive contracts, use schema-first named `Ack.lazy` schemas. +### Using Ack models inside json_serializable classes + +When a `@JsonSerializable()` class holds an Ack model, specify the converters +on that field. For an Ack class with an `AccountSchema` facade, use + +```dart +@JsonKey(fromJson: AccountSchema.fromJson, toJson: AccountSchema.encode) +final Account account; +``` + +Use `JsonKey` from `package:json_annotation/json_annotation.dart` on the +container field. + ## Which direction should you choose? Put `@Schemable()` on a top-level schema when you want to design the boundary diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 81d90cc9..31706127 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -127,6 +127,11 @@ Ack is organized into five coordinated packages that share one version number an | `@AckField(description: ...)` | `2.0.0` | `/// @description ...` doc tag | | `@JsonConverter()` on `@Schemable` classes/fields | `1.7.0` (rejected) | Declare `static final schema = ...` on the type or register one in `@Schemable(schemas: [...])` | +Schema-first union discriminator getters use the same lowerCamelCase naming as +other fields. A class-first union emits one discriminator wire key, even when +a branch field uses a different case style. Generated `Set` fields reject +duplicate JSON values. Use `List` when duplicates must be accepted. + ### Validation Annotations The top-level 1.x validation and presence classes were removed in `2.0.0`. diff --git a/example/lib/additional_properties_example.g.dart b/example/lib/additional_properties_example.g.dart index c15758f0..b3f97fca 100644 --- a/example/lib/additional_properties_example.g.dart +++ b/example/lib/additional_properties_example.g.dart @@ -7,7 +7,6 @@ part of 'additional_properties_example.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Immutable model generated from `userConfigSchema`. @@ -76,9 +75,9 @@ final class UserConfig { identical(this, other) || (other is UserConfig && runtimeType == other.runtimeType && - deepEquals(username, other.username) && - deepEquals(email, other.email) && - deepEquals(additionalProperties, other.additionalProperties)); + deepEquals(this.username, other.username) && + deepEquals(this.email, other.email) && + deepEquals(this.additionalProperties, other.additionalProperties)); @override int get hashCode => Object.hashAll([ @@ -93,23 +92,23 @@ final class UserConfig { 'UserConfig(username: ${username}, email: ${email}, additionalProperties: ${additionalProperties})'; static UserConfig _fromAckRuntime(Map value) { - const declared = {'username', 'email'}; + const _ackDeclaredKeys = {'username', 'email'}; return UserConfig( username: value['username'] as String, email: value['email'] as String, additionalProperties: Map.fromEntries( - value.entries.where((entry) => !declared.contains(entry.key)), + value.entries.where((entry) => !_ackDeclaredKeys.contains(entry.key)), ), ); } Map _toAckRuntime() { - const declared = {'username', 'email'}; + const _ackDeclaredKeys = {'username', 'email'}; return { for (final entry in additionalProperties.entries) - if (!declared.contains(entry.key)) entry.key: entry.value, - 'username': username, - 'email': email, + if (!_ackDeclaredKeys.contains(entry.key)) entry.key: entry.value, + 'username': this.username, + 'email': this.email, }; } } @@ -210,9 +209,9 @@ final class ApiRequest { identical(this, other) || (other is ApiRequest && runtimeType == other.runtimeType && - deepEquals(method, other.method) && - deepEquals(url, other.url) && - deepEquals(additionalProperties, other.additionalProperties)); + deepEquals(this.method, other.method) && + deepEquals(this.url, other.url) && + deepEquals(this.additionalProperties, other.additionalProperties)); @override int get hashCode => Object.hashAll([ @@ -227,23 +226,23 @@ final class ApiRequest { 'ApiRequest(method: ${method}, url: ${url}, additionalProperties: ${additionalProperties})'; static ApiRequest _fromAckRuntime(Map value) { - const declared = {'method', 'url'}; + const _ackDeclaredKeys = {'method', 'url'}; return ApiRequest( method: value['method'] as String, url: value['url'] as String, additionalProperties: Map.fromEntries( - value.entries.where((entry) => !declared.contains(entry.key)), + value.entries.where((entry) => !_ackDeclaredKeys.contains(entry.key)), ), ); } Map _toAckRuntime() { - const declared = {'method', 'url'}; + const _ackDeclaredKeys = {'method', 'url'}; return { for (final entry in additionalProperties.entries) - if (!declared.contains(entry.key)) entry.key: entry.value, - 'method': method, - 'url': url, + if (!_ackDeclaredKeys.contains(entry.key)) entry.key: entry.value, + 'method': this.method, + 'url': this.url, }; } } @@ -345,9 +344,9 @@ final class FeatureFlags { identical(this, other) || (other is FeatureFlags && runtimeType == other.runtimeType && - deepEquals(appVersion, other.appVersion) && - deepEquals(environment, other.environment) && - deepEquals(additionalProperties, other.additionalProperties)); + deepEquals(this.appVersion, other.appVersion) && + deepEquals(this.environment, other.environment) && + deepEquals(this.additionalProperties, other.additionalProperties)); @override int get hashCode => Object.hashAll([ @@ -362,23 +361,23 @@ final class FeatureFlags { 'FeatureFlags(appVersion: ${appVersion}, environment: ${environment}, additionalProperties: ${additionalProperties})'; static FeatureFlags _fromAckRuntime(Map value) { - const declared = {'appVersion', 'environment'}; + const _ackDeclaredKeys = {'appVersion', 'environment'}; return FeatureFlags( appVersion: value['appVersion'] as String, environment: value['environment'] as String, additionalProperties: Map.fromEntries( - value.entries.where((entry) => !declared.contains(entry.key)), + value.entries.where((entry) => !_ackDeclaredKeys.contains(entry.key)), ), ); } Map _toAckRuntime() { - const declared = {'appVersion', 'environment'}; + const _ackDeclaredKeys = {'appVersion', 'environment'}; return { for (final entry in additionalProperties.entries) - if (!declared.contains(entry.key)) entry.key: entry.value, - 'appVersion': appVersion, - 'environment': environment, + if (!_ackDeclaredKeys.contains(entry.key)) entry.key: entry.value, + 'appVersion': this.appVersion, + 'environment': this.environment, }; } } @@ -473,7 +472,7 @@ final class DynamicData { identical(this, other) || (other is DynamicData && runtimeType == other.runtimeType && - deepEquals(additionalProperties, other.additionalProperties)); + deepEquals(this.additionalProperties, other.additionalProperties)); @override int get hashCode => @@ -484,19 +483,19 @@ final class DynamicData { 'DynamicData(additionalProperties: ${additionalProperties})'; static DynamicData _fromAckRuntime(Map value) { - const declared = {}; + const _ackDeclaredKeys = {}; return DynamicData( additionalProperties: Map.fromEntries( - value.entries.where((entry) => !declared.contains(entry.key)), + value.entries.where((entry) => !_ackDeclaredKeys.contains(entry.key)), ), ); } Map _toAckRuntime() { - const declared = {}; + const _ackDeclaredKeys = {}; return { for (final entry in additionalProperties.entries) - if (!declared.contains(entry.key)) entry.key: entry.value, + if (!_ackDeclaredKeys.contains(entry.key)) entry.key: entry.value, }; } } diff --git a/example/lib/class_first_models.g.dart b/example/lib/class_first_models.g.dart index d235d521..79251892 100644 --- a/example/lib/class_first_models.g.dart +++ b/example/lib/class_first_models.g.dart @@ -7,7 +7,6 @@ part of 'class_first_models.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file final _catObject = Ack.object({ @@ -102,9 +101,7 @@ mixin _$CatAck { @override bool operator ==(Object other) { if (identical(this, other)) return true; - if (other is! Cat || runtimeType != other.runtimeType) { - return false; - } + if (other is! Cat || runtimeType != other.runtimeType) return false; final self = this as Cat; return deepEquals(self.id, other.id) && deepEquals(self.lives, other.lives); } @@ -230,9 +227,7 @@ mixin _$DogAck { @override bool operator ==(Object other) { if (identical(this, other)) return true; - if (other is! Dog || runtimeType != other.runtimeType) { - return false; - } + if (other is! Dog || runtimeType != other.runtimeType) return false; final self = this as Dog; return deepEquals(self.id, other.id) && deepEquals(self.breed, other.breed); } @@ -277,7 +272,10 @@ final _petSchema = _petObject decode: (value) => switch (value['type']) { 'cat' => _$CatFromRuntime(value), 'Dog' => _$DogFromRuntime(value), - final unknown => throw StateError('Unknown type: $unknown'), + final unknown => throw StateError( + 'Unknown type: ' + '$unknown', + ), }, encode: (model) => switch (model) { Cat() => _$CatToRuntime(model), @@ -371,11 +369,11 @@ abstract final class AccountSchema { /// /// Throws an `AckException` when validation fails. static Account parse(Object? value, {String? debugName}) => - _accountSchema.parse(value, debugName: debugName)!; + Account.schema.parse(value, debugName: debugName)!; /// Validates [value] and returns the model or the validation failure. static SchemaResult safeParse(Object? value, {String? debugName}) => - _accountSchema.safeParse(value, debugName: debugName); + Account.schema.safeParse(value, debugName: debugName); /// Validates decoded [json] and creates the model. /// @@ -386,14 +384,14 @@ abstract final class AccountSchema { /// /// Throws an `AckException` when validation fails. static Map encode(Account value, {String? debugName}) => - _accountSchema.encode(value, debugName: debugName)!; + Account.schema.encode(value, debugName: debugName)!; /// Validates [value] and encodes it as a JSON map, returning the validation /// failure instead of throwing. static SchemaResult> safeEncode( Account value, { String? debugName, - }) => _accountSchema.safeEncode(value, debugName: debugName); + }) => Account.schema.safeEncode(value, debugName: debugName); /// The JSON Schema that describes [Account]. static Map toJsonSchema() => _accountSchema.toJsonSchema(); @@ -457,9 +455,7 @@ mixin _$AccountAck { @override bool operator ==(Object other) { if (identical(this, other)) return true; - if (other is! Account || runtimeType != other.runtimeType) { - return false; - } + if (other is! Account || runtimeType != other.runtimeType) return false; final self = this as Account; return deepEquals(self.displayName, other.displayName) && deepEquals(self.website, other.website) && diff --git a/example/lib/pet.g.dart b/example/lib/pet.g.dart index 7105059f..236ef078 100644 --- a/example/lib/pet.g.dart +++ b/example/lib/pet.g.dart @@ -7,7 +7,6 @@ part of 'pet.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Discriminated model base generated from `petSchema`. @@ -60,7 +59,10 @@ sealed class Pet { return switch (value['type']) { 'cat' => Cat._fromAckRuntime(value), 'dog' => Dog._fromAckRuntime(value), - final unknown => throw StateError('Unknown type: $unknown'), + final unknown => throw StateError( + 'Unknown type: ' + '$unknown', + ), }; } @@ -117,7 +119,7 @@ final class Cat extends Pet { identical(this, other) || (other is Cat && runtimeType == other.runtimeType && - deepEquals(lives, other.lives)); + deepEquals(this.lives, other.lives)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(lives)]); @@ -131,7 +133,7 @@ final class Cat extends Pet { @override Map _toAckRuntime() => { 'type': 'cat', - 'lives': lives, + 'lives': this.lives, }; } @@ -203,7 +205,7 @@ final class Dog extends Pet { identical(this, other) || (other is Dog && runtimeType == other.runtimeType && - deepEquals(breed, other.breed)); + deepEquals(this.breed, other.breed)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(breed)]); @@ -217,7 +219,7 @@ final class Dog extends Pet { @override Map _toAckRuntime() => { 'type': 'dog', - 'breed': breed, + 'breed': this.breed, }; } diff --git a/example/lib/schema_types_discriminated.g.dart b/example/lib/schema_types_discriminated.g.dart index 87e6aa94..385f3773 100644 --- a/example/lib/schema_types_discriminated.g.dart +++ b/example/lib/schema_types_discriminated.g.dart @@ -7,7 +7,6 @@ part of 'schema_types_discriminated.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Discriminated model base generated from `petSchema`. @@ -60,7 +59,10 @@ sealed class Pet { return switch (value['kind']) { 'cat' => Cat._fromAckRuntime(value), 'dog' => Dog._fromAckRuntime(value), - final unknown => throw StateError('Unknown kind: $unknown'), + final unknown => throw StateError( + 'Unknown kind: ' + '$unknown', + ), }; } @@ -117,7 +119,7 @@ final class Cat extends Pet { identical(this, other) || (other is Cat && runtimeType == other.runtimeType && - deepEquals(lives, other.lives)); + deepEquals(this.lives, other.lives)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(lives)]); @@ -131,7 +133,7 @@ final class Cat extends Pet { @override Map _toAckRuntime() => { 'kind': 'cat', - 'lives': lives, + 'lives': this.lives, }; } @@ -209,8 +211,8 @@ final class Dog extends Pet { identical(this, other) || (other is Dog && runtimeType == other.runtimeType && - deepEquals(bark, other.bark) && - deepEquals(additionalProperties, other.additionalProperties)); + deepEquals(this.bark, other.bark) && + deepEquals(this.additionalProperties, other.additionalProperties)); @override int get hashCode => Object.hashAll([ @@ -224,23 +226,23 @@ final class Dog extends Pet { 'Dog(bark: ${bark}, additionalProperties: ${additionalProperties})'; static Dog _fromAckRuntime(Map value) { - const declared = {'kind', 'bark'}; + const _ackDeclaredKeys = {'kind', 'bark'}; return Dog( bark: value['bark'] as bool, additionalProperties: Map.fromEntries( - value.entries.where((entry) => !declared.contains(entry.key)), + value.entries.where((entry) => !_ackDeclaredKeys.contains(entry.key)), ), ); } @override Map _toAckRuntime() { - const declared = {'kind', 'bark'}; + const _ackDeclaredKeys = {'kind', 'bark'}; return { for (final entry in additionalProperties.entries) - if (!declared.contains(entry.key)) entry.key: entry.value, + if (!_ackDeclaredKeys.contains(entry.key)) entry.key: entry.value, 'kind': 'dog', - 'bark': bark, + 'bark': this.bark, }; } } diff --git a/example/lib/schema_types_edge_cases.g.dart b/example/lib/schema_types_edge_cases.g.dart index abff44fd..e82dc73b 100644 --- a/example/lib/schema_types_edge_cases.g.dart +++ b/example/lib/schema_types_edge_cases.g.dart @@ -7,7 +7,6 @@ part of 'schema_types_edge_cases.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Immutable model generated from `productSchema`. @@ -80,10 +79,10 @@ final class Product { identical(this, other) || (other is Product && runtimeType == other.runtimeType && - deepEquals(name, other.name) && - deepEquals(tags, other.tags) && - deepEquals(scores, other.scores) && - deepEquals(flags, other.flags)); + deepEquals(this.name, other.name) && + deepEquals(this.tags, other.tags) && + deepEquals(this.scores, other.scores) && + deepEquals(this.flags, other.flags)); @override int get hashCode => Object.hashAll([ @@ -106,10 +105,10 @@ final class Product { ); Map _toAckRuntime() => { - 'name': name, - 'tags': tags.map((item) => item).toList(growable: false), - 'scores': scores.map((item) => item).toList(growable: false), - 'flags': flags.map((item) => item).toList(growable: false), + 'name': this.name, + 'tags': this.tags.map((item) => item).toList(growable: false), + 'scores': this.scores.map((item) => item).toList(growable: false), + 'flags': this.flags.map((item) => item).toList(growable: false), }; } @@ -207,8 +206,8 @@ final class Grid { identical(this, other) || (other is Grid && runtimeType == other.runtimeType && - deepEquals(name, other.name) && - deepEquals(matrix, other.matrix)); + deepEquals(this.name, other.name) && + deepEquals(this.matrix, other.matrix)); @override int get hashCode => @@ -225,8 +224,8 @@ final class Grid { ); Map _toAckRuntime() => { - 'name': name, - 'matrix': matrix + 'name': this.name, + 'matrix': this.matrix .map((item) => item.map((item) => item).toList(growable: false)) .toList(growable: false), }; @@ -319,10 +318,10 @@ final class Address { identical(this, other) || (other is Address && runtimeType == other.runtimeType && - deepEquals(street, other.street) && - deepEquals(city, other.city) && - deepEquals(zipCode, other.zipCode) && - deepEquals(country, other.country)); + deepEquals(this.street, other.street) && + deepEquals(this.city, other.city) && + deepEquals(this.zipCode, other.zipCode) && + deepEquals(this.country, other.country)); @override int get hashCode => Object.hashAll([ @@ -345,10 +344,10 @@ final class Address { ); Map _toAckRuntime() => { - 'street': street, - 'city': city, - 'zipCode': zipCode, - 'country': country, + 'street': this.street, + 'city': this.city, + 'zipCode': this.zipCode, + 'country': this.country, }; } @@ -452,10 +451,10 @@ final class Person { identical(this, other) || (other is Person && runtimeType == other.runtimeType && - deepEquals(name, other.name) && - deepEquals(email, other.email) && - deepEquals(address, other.address) && - deepEquals(age, other.age)); + deepEquals(this.name, other.name) && + deepEquals(this.email, other.email) && + deepEquals(this.address, other.address) && + deepEquals(this.age, other.age)); @override int get hashCode => Object.hashAll([ @@ -478,10 +477,10 @@ final class Person { ); Map _toAckRuntime() => { - 'name': name, - 'email': email, - 'address': Address.$ack.toRuntime(address), - 'age': age, + 'name': this.name, + 'email': this.email, + 'address': Address.$ack.toRuntime(this.address), + 'age': this.age, }; } @@ -577,10 +576,10 @@ final class Employee { identical(this, other) || (other is Employee && runtimeType == other.runtimeType && - deepEquals(name, other.name) && - deepEquals(employeeId, other.employeeId) && - deepEquals(homeAddress, other.homeAddress) && - deepEquals(workAddress, other.workAddress)); + deepEquals(this.name, other.name) && + deepEquals(this.employeeId, other.employeeId) && + deepEquals(this.homeAddress, other.homeAddress) && + deepEquals(this.workAddress, other.workAddress)); @override int get hashCode => Object.hashAll([ @@ -607,10 +606,10 @@ final class Employee { ); Map _toAckRuntime() => { - 'name': name, - 'employeeId': employeeId, - 'homeAddress': Address.$ack.toRuntime(homeAddress), - 'workAddress': Address.$ack.toRuntime(workAddress), + 'name': this.name, + 'employeeId': this.employeeId, + 'homeAddress': Address.$ack.toRuntime(this.homeAddress), + 'workAddress': Address.$ack.toRuntime(this.workAddress), }; } @@ -718,11 +717,11 @@ final class Modifier { identical(this, other) || (other is Modifier && runtimeType == other.runtimeType && - deepEquals(requiredField, other.requiredField) && - deepEquals(optionalField, other.optionalField) && - deepEquals(nullableField, other.nullableField) && - deepEquals(optionalNullable, other.optionalNullable) && - deepEquals(nullableOptional, other.nullableOptional)); + deepEquals(this.requiredField, other.requiredField) && + deepEquals(this.optionalField, other.optionalField) && + deepEquals(this.nullableField, other.nullableField) && + deepEquals(this.optionalNullable, other.optionalNullable) && + deepEquals(this.nullableOptional, other.nullableOptional)); @override int get hashCode => Object.hashAll([ @@ -747,11 +746,11 @@ final class Modifier { ); Map _toAckRuntime() => { - 'requiredField': requiredField, - 'optionalField': ?optionalField, - 'nullableField': nullableField, - 'optionalNullable': ?optionalNullable, - 'nullableOptional': ?nullableOptional, + 'requiredField': this.requiredField, + 'optionalField': ?this.optionalField, + 'nullableField': this.nullableField, + 'optionalNullable': ?this.optionalNullable, + 'nullableOptional': ?this.nullableOptional, }; } @@ -888,10 +887,10 @@ final class TaggedItem { identical(this, other) || (other is TaggedItem && runtimeType == other.runtimeType && - deepEquals(name, other.name) && - deepEquals(requiredTags, other.requiredTags) && - deepEquals(optionalTags, other.optionalTags) && - deepEquals(nullableTags, other.nullableTags)); + deepEquals(this.name, other.name) && + deepEquals(this.requiredTags, other.requiredTags) && + deepEquals(this.optionalTags, other.optionalTags) && + deepEquals(this.nullableTags, other.nullableTags)); @override int get hashCode => Object.hashAll([ @@ -920,10 +919,16 @@ final class TaggedItem { ); Map _toAckRuntime() => { - 'name': name, - 'requiredTags': requiredTags.map((item) => item).toList(growable: false), - 'optionalTags': ?optionalTags?.map((item) => item).toList(growable: false), - 'nullableTags': nullableTags?.map((item) => item).toList(growable: false), + 'name': this.name, + 'requiredTags': this.requiredTags + .map((item) => item) + .toList(growable: false), + 'optionalTags': ?this.optionalTags + ?.map((item) => item) + .toList(growable: false), + 'nullableTags': this.nullableTags + ?.map((item) => item) + .toList(growable: false), }; } @@ -1031,8 +1036,8 @@ final class ContactList { identical(this, other) || (other is ContactList && runtimeType == other.runtimeType && - deepEquals(name, other.name) && - deepEquals(addresses, other.addresses)); + deepEquals(this.name, other.name) && + deepEquals(this.addresses, other.addresses)); @override int get hashCode => Object.hashAll([ @@ -1052,8 +1057,8 @@ final class ContactList { ); Map _toAckRuntime() => { - 'name': name, - 'addresses': addresses + 'name': this.name, + 'addresses': this.addresses .map((item) => Address.$ack.toRuntime(item)) .toList(growable: false), }; @@ -1218,7 +1223,7 @@ final class Minimal { identical(this, other) || (other is Minimal && runtimeType == other.runtimeType && - deepEquals(id, other.id)); + deepEquals(this.id, other.id)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(id)]); @@ -1229,7 +1234,7 @@ final class Minimal { static Minimal _fromAckRuntime(Map value) => Minimal(id: value['id'] as String); - Map _toAckRuntime() => {'id': id}; + Map _toAckRuntime() => {'id': this.id}; } /// Creates copies of [Minimal] with selected fields replaced. @@ -1307,7 +1312,7 @@ final class NamedItem { identical(this, other) || (other is NamedItem && runtimeType == other.runtimeType && - deepEquals(name, other.name)); + deepEquals(this.name, other.name)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(name)]); @@ -1318,7 +1323,7 @@ final class NamedItem { static NamedItem _fromAckRuntime(Map value) => NamedItem(name: value['name'] as String); - Map _toAckRuntime() => {'name': name}; + Map _toAckRuntime() => {'name': this.name}; } /// Creates copies of [NamedItem] with selected fields replaced. @@ -1395,7 +1400,7 @@ final class Item { identical(this, other) || (other is Item && runtimeType == other.runtimeType && - deepEquals(id, other.id)); + deepEquals(this.id, other.id)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(id)]); @@ -1406,7 +1411,7 @@ final class Item { static Item _fromAckRuntime(Map value) => Item(id: value['id'] as String); - Map _toAckRuntime() => {'id': id}; + Map _toAckRuntime() => {'id': this.id}; } /// Creates copies of [Item] with selected fields replaced. @@ -1485,7 +1490,7 @@ final class MyCustomSchema123 { identical(this, other) || (other is MyCustomSchema123 && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -1496,7 +1501,9 @@ final class MyCustomSchema123 { static MyCustomSchema123 _fromAckRuntime(Map value) => MyCustomSchema123(value: value['value'] as String); - Map _toAckRuntime() => {'value': value}; + Map _toAckRuntime() => { + 'value': this.value, + }; } /// Creates copies of [MyCustomSchema123] with selected fields replaced. diff --git a/example/lib/schema_types_primitives.g.dart b/example/lib/schema_types_primitives.g.dart index 22214895..320dd17d 100644 --- a/example/lib/schema_types_primitives.g.dart +++ b/example/lib/schema_types_primitives.g.dart @@ -7,7 +7,6 @@ part of 'schema_types_primitives.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Immutable value model generated from `passwordSchema`. @@ -68,7 +67,7 @@ final class Password { identical(this, other) || (other is Password && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -156,7 +155,7 @@ final class Age { identical(this, other) || (other is Age && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -244,7 +243,7 @@ final class Price { identical(this, other) || (other is Price && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -332,7 +331,7 @@ final class Active { identical(this, other) || (other is Active && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -421,7 +420,7 @@ final class Tags { identical(this, other) || (other is Tags && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -511,7 +510,7 @@ final class Scores { identical(this, other) || (other is Scores && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -602,7 +601,7 @@ final class StatusLiteral { identical(this, other) || (other is StatusLiteral && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -691,7 +690,7 @@ final class Role { identical(this, other) || (other is Role && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -781,7 +780,7 @@ final class UserRoleModel { identical(this, other) || (other is UserRoleModel && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -872,7 +871,7 @@ final class StatusEnum { identical(this, other) || (other is StatusEnum && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -962,7 +961,7 @@ final class OptionalStatus { identical(this, other) || (other is OptionalStatus && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -1054,7 +1053,7 @@ final class DefaultedEnum { identical(this, other) || (other is DefaultedEnum && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -1146,7 +1145,7 @@ final class ChainedEnumString { identical(this, other) || (other is ChainedEnumString && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -1238,7 +1237,7 @@ final class RefinedAge { identical(this, other) || (other is RefinedAge && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); diff --git a/example/lib/schema_types_simple.g.dart b/example/lib/schema_types_simple.g.dart index 645a8ad3..469c873e 100644 --- a/example/lib/schema_types_simple.g.dart +++ b/example/lib/schema_types_simple.g.dart @@ -7,7 +7,6 @@ part of 'schema_types_simple.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Immutable model generated from `userSchema`. diff --git a/example/lib/schema_types_transforms.g.dart b/example/lib/schema_types_transforms.g.dart index 8ebc55e1..cf183fff 100644 --- a/example/lib/schema_types_transforms.g.dart +++ b/example/lib/schema_types_transforms.g.dart @@ -7,7 +7,6 @@ part of 'schema_types_transforms.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Immutable value model generated from `colorSchema`. @@ -68,7 +67,7 @@ final class ColorModel { identical(this, other) || (other is ColorModel && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -192,17 +191,17 @@ final class Profile { identical(this, other) || (other is Profile && runtimeType == other.runtimeType && - deepEquals(homepage, other.homepage) && - deepEquals(birthday, other.birthday) && - deepEquals(lastLogin, other.lastLogin) && - deepEquals(timeout, other.timeout) && - deepEquals(links, other.links) && - deepEquals(favoriteColor, other.favoriteColor) && - deepEquals(slug, other.slug) && - deepEquals(accent, other.accent) && - deepEquals(colors, other.colors) && - deepEquals(customColors, other.customColors) && - deepEquals(tagList, other.tagList)); + deepEquals(this.homepage, other.homepage) && + deepEquals(this.birthday, other.birthday) && + deepEquals(this.lastLogin, other.lastLogin) && + deepEquals(this.timeout, other.timeout) && + deepEquals(this.links, other.links) && + deepEquals(this.favoriteColor, other.favoriteColor) && + deepEquals(this.slug, other.slug) && + deepEquals(this.accent, other.accent) && + deepEquals(this.colors, other.colors) && + deepEquals(this.customColors, other.customColors) && + deepEquals(this.tagList, other.tagList)); @override int get hashCode => Object.hashAll([ @@ -241,19 +240,21 @@ final class Profile { ); Map _toAckRuntime() => { - 'homepage': homepage, - 'birthday': birthday, - 'lastLogin': lastLogin, - 'timeout': timeout, - 'links': links.map((item) => item).toList(growable: false), - 'favoriteColor': favoriteColor, - 'slug': slug, - 'accent': ColorModel.$ack.toRuntime(accent), - 'colors': colors + 'homepage': this.homepage, + 'birthday': this.birthday, + 'lastLogin': this.lastLogin, + 'timeout': this.timeout, + 'links': this.links.map((item) => item).toList(growable: false), + 'favoriteColor': this.favoriteColor, + 'slug': this.slug, + 'accent': ColorModel.$ack.toRuntime(this.accent), + 'colors': this.colors .map((item) => ColorModel.$ack.toRuntime(item)) .toList(growable: false), - 'customColors': customColors.map((item) => item).toList(growable: false), - 'tagList': tagList, + 'customColors': this.customColors + .map((item) => item) + .toList(growable: false), + 'tagList': this.tagList, }; } diff --git a/example/lib/user_with_color.g.dart b/example/lib/user_with_color.g.dart index 5a4c572a..61bf0105 100644 --- a/example/lib/user_with_color.g.dart +++ b/example/lib/user_with_color.g.dart @@ -7,7 +7,6 @@ part of 'user_with_color.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Immutable value model generated from `colorSchema`. @@ -68,7 +67,7 @@ final class ColorModel { identical(this, other) || (other is ColorModel && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -158,8 +157,8 @@ final class Profile { identical(this, other) || (other is Profile && runtimeType == other.runtimeType && - deepEquals(bio, other.bio) && - deepEquals(website, other.website)); + deepEquals(this.bio, other.bio) && + deepEquals(this.website, other.website)); @override int get hashCode => @@ -172,8 +171,8 @@ final class Profile { Profile(bio: value['bio'] as String, website: value['website'] as Uri?); Map _toAckRuntime() => { - 'bio': bio, - 'website': ?website, + 'bio': this.bio, + 'website': ?this.website, }; } @@ -288,14 +287,14 @@ final class UserWithColor { identical(this, other) || (other is UserWithColor && runtimeType == other.runtimeType && - deepEquals(firstName, other.firstName) && - deepEquals(lastName, other.lastName) && - deepEquals(age, other.age) && - deepEquals(profile, other.profile) && - deepEquals(color, other.color) && - deepEquals(favoriteColor, other.favoriteColor) && - deepEquals(pet, other.pet) && - deepEquals(pets, other.pets)); + deepEquals(this.firstName, other.firstName) && + deepEquals(this.lastName, other.lastName) && + deepEquals(this.age, other.age) && + deepEquals(this.profile, other.profile) && + deepEquals(this.color, other.color) && + deepEquals(this.favoriteColor, other.favoriteColor) && + deepEquals(this.pet, other.pet) && + deepEquals(this.pets, other.pets)); @override int get hashCode => Object.hashAll([ @@ -334,17 +333,17 @@ final class UserWithColor { ); Map _toAckRuntime() => { - 'firstName': firstName, - 'lastName': lastName, - 'age': age, - 'profile': Profile.$ack.toRuntime(profile), - 'color': ColorModel.$ack.toRuntime(color), - 'favoriteColor': ?switch (favoriteColor) { + 'firstName': this.firstName, + 'lastName': this.lastName, + 'age': this.age, + 'profile': Profile.$ack.toRuntime(this.profile), + 'color': ColorModel.$ack.toRuntime(this.color), + 'favoriteColor': ?switch (this.favoriteColor) { null => null, final fieldValue => ColorModel.$ack.toRuntime(fieldValue), }, - 'pet': Pet.$ack.toRuntime(pet), - 'pets': pets + 'pet': Pet.$ack.toRuntime(this.pet), + 'pets': this.pets .map((item) => Pet.$ack.toRuntime(item)) .toList(growable: false), }; diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 39b44a46..b10d9735 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -15,6 +15,8 @@ ### Changed +* Support `AckSchema.forGeneratedField` as a generated-code entry point. + * Remove the `punycoder` and `unorm_dart` dependencies. Ack now has only `meta` and `collection` as runtime dependencies. Punycode conversion for `xn--` labels is built in. diff --git a/packages/ack/lib/src/schemas/schema.dart b/packages/ack/lib/src/schemas/schema.dart index 539b7c74..6fe75bff 100644 --- a/packages/ack/lib/src/schemas/schema.dart +++ b/packages/ack/lib/src/schemas/schema.dart @@ -115,7 +115,7 @@ sealed class AckSchema { /// /// The field declaration supplies optionality, nullability and defaults. /// Non-null values retain the custom schema's validation and encoder. - @internal + /// This entry point is supported for generated model code. static CodecSchema forGeneratedField< B extends Object, R extends Object diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 17d5ad86..663a4c9c 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -2,6 +2,10 @@ ### Breaking +* **Breaking:** Generated `Set` fields reject duplicate JSON values. +* **Breaking:** A stored discriminator uses its configured JSON key once. + Schema-first discriminator getters use lowerCamelCase. + * **Breaking:** Generate lowerCamelCase Dart fields from schema-first JSON keys. Wire keys keep their original spelling. @@ -13,6 +17,9 @@ ### Fixed +* Suggest `@Schemable()` when a union branch cannot resolve to a model. +* Document JSON converters for Ack model fields in json_serializable classes. + * Report invalid rule arguments on the annotated field, including non-integer arguments on integer fields, negative lengths, and invalid regular expressions. diff --git a/packages/ack_generator/lib/builder.dart b/packages/ack_generator/lib/builder.dart index 8a9e071e..384328bb 100644 --- a/packages/ack_generator/lib/builder.dart +++ b/packages/ack_generator/lib/builder.dart @@ -1 +1 @@ -export 'src/builder.dart'; +export 'src/builder.dart' show ackGenerator, ackJsonSchemaBuilder; diff --git a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart index c9f89c7e..7731db2f 100644 --- a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart @@ -107,13 +107,13 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { if (options.discriminatorValue != null) { throw InvalidGenerationSource( '${element.name} sets discriminatorValue but is not a concrete ' - 'branch of an annotated sealed ${annotationName(element)} base.', + 'branch of an annotated sealed @Schemable base.', element: element, ); } if (element.isAbstract || !element.isConstructable) { throw InvalidGenerationSource( - '${annotationName(element)} requires a constructable class; ' + '@Schemable requires a constructable class; ' '${element.name} is abstract.', element: element, ); @@ -176,7 +176,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { final name = element.name ?? ''; if (name.startsWith('_')) { throw InvalidGenerationSource( - '${annotationName(element)} requires a public class; received ' + '@Schemable requires a public class; received ' '"$name".', element: element, todo: 'Annotate a public class.', @@ -197,18 +197,18 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { _requireFinalConcreteClass(element); if (_jsonSerializableChecker.hasAnnotationOfExact(element)) { throw InvalidGenerationSource( - '$name cannot use ${annotationName(element)} and @JsonSerializable ' + '$name cannot use @Schemable and @JsonSerializable ' 'together because both generate the same _\$$name JSON helpers.', element: element, todo: - 'Remove @JsonSerializable; ${annotationName(element)} owns JSON ' + 'Remove @JsonSerializable; @Schemable owns JSON ' 'generation.', ); } final options = _options(element)!; if (element.isSealed && options.discriminatorKey == null) { throw InvalidGenerationSource( - 'Sealed ${annotationName(element)} $name requires discriminatorKey.', + 'Sealed @Schemable $name requires discriminatorKey.', element: element, ); } @@ -220,7 +220,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { } if (element.isSealed && options.discriminatorValue != null) { throw InvalidGenerationSource( - 'Sealed ${annotationName(element)} $name cannot set ' + 'Sealed @Schemable $name cannot set ' 'discriminatorValue.', element: element, ); @@ -328,7 +328,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { final target = node.redirectedConstructor; if (target == null) return; throw InvalidGenerationSource( - '${annotationName(element)} ${element.name} redirects its unnamed ' + '@Schemable ${element.name} redirects its unnamed ' 'constructor to ${target.toSource()}. Redirecting factory models are ' 'not supported; declare a final class whose unnamed generative ' 'constructor initializes its fields.', @@ -341,11 +341,12 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { _rejectGeneratedMemberCollisions(base, includeValueMembers: false); final baseOptions = _options(base)!; final discriminatorKey = baseOptions.discriminatorKey!; - _rejectInvalidMemberName( - discriminatorKey, - base, - memberKind: 'discriminator member', - ); + if (discriminatorKey.isEmpty) { + throw InvalidGenerationSource( + '${base.name} discriminator key must not be empty.', + element: base, + ); + } if (_reservedMembers.contains(discriminatorKey)) { throw InvalidGenerationSource( '${base.name}.$discriminatorKey conflicts with a generated member.', @@ -374,7 +375,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { } if (candidates.isEmpty) { throw InvalidGenerationSource( - 'Sealed ${annotationName(base)} ${base.name} has no concrete ' + 'Sealed @Schemable ${base.name} has no concrete ' 'same-library branches.', element: base, ); @@ -474,7 +475,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { final constructor = element.unnamedConstructor; if (constructor == null || !constructor.isGenerative) { throw InvalidGenerationSource( - '${annotationName(element)} ${element.name} requires an unnamed ' + '@Schemable ${element.name} requires an unnamed ' 'generative constructor.', element: element, ); @@ -488,7 +489,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { if (field.isFinal) continue; throw InvalidGenerationSource( '${element.name}.${field.name} must be final because ' - '${annotationName(element)} generates immutable value semantics.', + '@Schemable generates immutable value semantics.', element: field, todo: 'Declare the stored field as final.', ); @@ -590,14 +591,24 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { if (parameters.containsKey(name)) { throw InvalidGenerationSource( '${element.name}.$name is private and cannot participate in ' - '${annotationName(element)} generation.', + '@Schemable generation.', element: field, ); } continue; } final parameter = parameters[name]; - final isDiscriminator = discriminatorKey == name; + final explicitKey = _jsonKey(field, parameter); + final inferredKey = _rename(name, options.caseStyle); + final isDiscriminator = + discriminatorKey != null && + (explicitKey == discriminatorKey || + explicitKey == null && + (name == discriminatorKey || + inferredKey == discriminatorKey)); + if (isDiscriminator && name != discriminatorKey) { + _validateBranchDiscriminator(element, name, discriminatorValue!); + } if (parameter == null && !isDiscriminator) { throw InvalidGenerationSource( '${element.name}.$name must be initialized by a matching unnamed ' @@ -629,8 +640,9 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { ); } _recordClassFirstDependencies(element, field.type, field); - final jsonKey = - _jsonKey(field, parameter) ?? _rename(name, options.caseStyle); + final jsonKey = isDiscriminator + ? discriminatorKey + : explicitKey ?? inferredKey; final prior = ownerByJsonKey[jsonKey]; if (prior != null) { throw InvalidGenerationSource( @@ -824,7 +836,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { _ => runtimeRef, }; final rendered = _schemaRuntimeRef(setType).render(corePrefix: ackPrefix); - return '$listSchema.codec<$rendered>(' + return '$listSchema.unique().codec<$rendered>(' 'decode: (list) => list.toSet(), ' 'encode: (set) => set.toList(growable: false),' ')'; @@ -1094,7 +1106,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { if (element.isAbstract || element.isSealed || element.isFinal) return; throw InvalidGenerationSource( '${element.name} must be declared as a final class because ' - '${annotationName(element)} generates immutable value semantics.', + '@Schemable generates immutable value semantics.', element: element, todo: 'Add the final class modifier.', ); @@ -1293,7 +1305,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { if (!RegExp(r'^[A-Z][A-Za-z0-9_$]*$').hasMatch(facadeName) || isDartKeyword(facadeName)) { throw InvalidGenerationSource( - 'Invalid ${annotationName(element)} schema facade name "$facadeName" on ' + 'Invalid @Schemable schema facade name "$facadeName" on ' '${element.name}; schemaName must be a public UpperCamel identifier.', element: element, ); @@ -1392,7 +1404,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { final explicit = options.description; if (explicit != null && explicit.trim().isEmpty) { throw InvalidGenerationSource( - '${element.name} ${annotationName(element)}.description must not be ' + '${element.name} @Schemable.description must not be ' 'blank.', element: element, ); @@ -1447,7 +1459,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { if (!_jsonKeyChecker.hasAnnotationOfExact(element)) return; throw InvalidGenerationSource( '${owner.name}.${element.name} uses @JsonKey, which is not supported on ' - '${annotationName(owner)} classes in Ack 2.0. Use @AckKey(...) ' + '@Schemable classes in Ack 2.0. Use @AckKey(...) ' 'instead.', element: element, ); diff --git a/packages/ack_generator/lib/src/analyzer/model_graph_builder_base.dart b/packages/ack_generator/lib/src/analyzer/model_graph_builder_base.dart index 1f947cc1..5b211dec 100644 --- a/packages/ack_generator/lib/src/analyzer/model_graph_builder_base.dart +++ b/packages/ack_generator/lib/src/analyzer/model_graph_builder_base.dart @@ -167,9 +167,6 @@ abstract base class ModelGraphBuilderBase { bool hasSchemable(Element element) => schemableChecker.hasAnnotationOfExact(propertyDeclaration(element)); - /// The annotation spelling that marks [element] or its sealed base. - String annotationName(Element element) => '@Schemable'; - /// Reads the custom `name` override from `@Schemable(name: ...)` on [element]. String? schemableCustomName(Element element) { final declaration = propertyDeclaration(element); diff --git a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart index 3f70946e..b7585f75 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart @@ -70,3 +70,7 @@ String ackSchemaFirstDartFieldName(String key) { }); return first + rest.join(); } + +/// Dart getter name corresponding to a schema-first union's wire discriminator. +String ackSchemaFirstDiscriminatorName(String key) => + ackSchemaFirstDartFieldName(key.replaceFirst(RegExp(r'^@+'), '')); diff --git a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart index 3c35566f..0c79cfc4 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart @@ -7,7 +7,6 @@ import 'package:source_gen/source_gen.dart'; import '../json/helper_names.dart'; import '../models/schema_model_graph.dart'; -import '../utils/string_literal.dart'; import 'model_graph_builder_base.dart'; import 'schema_first_names.dart'; @@ -68,8 +67,6 @@ final class _SchemaMetadata { final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { SchemaModelGraphBuilder(super.library); - static const _reservedMembers = ackSchemaFirstReservedMembers; - static const _anyOfSchemaChecker = TypeChecker.typeNamed( AnyOfSchema, inPackage: 'ack', @@ -227,7 +224,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { _isCrossLibrarySchemable(chain.reference!)) { throw InvalidGenerationSource( '$path aliases a cross-library ' - '${annotationName(referencedElement(chain.reference!)!)} schema. ' + '@Schemable schema. ' 'Use the original model directly.', element: declaration.element, ); @@ -457,9 +454,12 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { element: declaration.element, ); } - _rejectInvalidMemberName(discriminatorKey, path, declaration.element); - if (_reservedMembers.contains(discriminatorKey) || - discriminatorKey == 'additionalProperties') { + final discriminatorName = ackSchemaFirstDiscriminatorName(discriminatorKey); + if (ackSchemaFirstFieldNameProblem( + discriminatorName, + capturesExtras: true, + ) != + null) { throw InvalidGenerationSource( '$path.$discriminatorKey conflicts with a generated member or Dart ' 'keyword.', @@ -481,6 +481,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { throw InvalidGenerationSource( '$path.$value is a cross-library or unresolvable discriminated branch.', element: declaration.element, + todo: 'Reference a same-library object schema annotated with @Schemable().', ); } _validateUnionBranchDiscriminator(target, discriminatorKey, value); @@ -489,10 +490,20 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { if (branch is! AckObjectModelNode) { throw InvalidGenerationSource( '$path.$value must reference an ' - '${annotationName(declaration.element)} object schema.', + '@Schemable object schema.', element: declaration.element, ); } + for (final field in branch.fields) { + if (field.dartName == discriminatorName && + field.jsonKey != discriminatorKey) { + throw InvalidGenerationSource( + '$path.$value JSON key "${field.jsonKey}" conflicts with the ' + 'Dart discriminator getter "$discriminatorName".', + element: declaration.element, + ); + } + } final owner = _unionOwnerByBranch[target.id]; if (owner != null && owner != declaration.id) { throw InvalidGenerationSource( @@ -1113,7 +1124,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { ); if (model == null) { throw InvalidGenerationSource( - '$path Ack.lazy must resolve to a named ${annotationName(context)} ' + '$path Ack.lazy must resolve to a named @Schemable ' 'schema.', element: context, ); @@ -1272,7 +1283,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { if (customName.trim() != customName || !RegExp(r'^[A-Z][A-Za-z0-9]*$').hasMatch(customName)) { throw InvalidGenerationSource( - 'Invalid ${annotationName(element)} name "$customName". Names must ' + 'Invalid @Schemable name "$customName". Names must ' 'be unchanged UpperCamelCase identifiers.', element: element, ); @@ -1299,7 +1310,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { final name = declaration.className; if (!generated.add(name)) { throw InvalidGenerationSource( - 'Multiple ${annotationName(declaration.element)} declarations ' + 'Multiple @Schemable declarations ' 'generate "$name".', element: declaration.element, ); @@ -1336,7 +1347,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { } if (node is AckUnionModelNode) { - checkMember(node.discriminatorKey); + checkMember(ackSchemaFirstDiscriminatorName(node.discriminatorKey)); continue; } if (node is AckObjectModelNode) { @@ -1354,7 +1365,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { checkMember(field.dartName); } if (node.discriminatorKey case final discriminator?) { - checkMember(discriminator); + checkMember(ackSchemaFirstDiscriminatorName(discriminator)); } } validateCopyWithHelperNames( @@ -1416,22 +1427,6 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { }; } - void _rejectInvalidMemberName(String jsonKey, String path, Element element) { - if (jsonKey.startsWith('_')) { - throw InvalidGenerationSource( - "$path.$jsonKey cannot start with '_' (private Dart member).", - element: element, - ); - } - if (!RegExp(r'^[A-Za-z$][A-Za-z0-9_$]*$').hasMatch(jsonKey) || - isDartReservedWord(jsonKey)) { - throw InvalidGenerationSource( - '$path.$jsonKey cannot be represented as a Dart field name.', - element: element, - ); - } - } - void _rejectUnsupportedSchemaType( Expression expression, String path, diff --git a/packages/ack_generator/lib/src/builders/data_class_emitter.dart b/packages/ack_generator/lib/src/builders/data_class_emitter.dart index 5af2b374..538c7643 100644 --- a/packages/ack_generator/lib/src/builders/data_class_emitter.dart +++ b/packages/ack_generator/lib/src/builders/data_class_emitter.dart @@ -75,13 +75,13 @@ final class AckDataClassEmitter { ]; final members = [ if (includeValueMembers) ...[ - copyWithGetter( + for (final method in valueMethods( className: className, + fields: stored, hasParameters: copyWithParameters.isNotEmpty, castSelf: true, - ), - equalityMembers(className: className, fields: stored, castSelf: true), - toStringMethod(className: className, fields: stored, castSelf: true), + )) + '${method.accept(DartEmitter())}${method.lambda == true ? ';' : ''}', ], jsonMembers(className: className, facadeName: facadeName), ]; @@ -93,58 +93,97 @@ ${includeValueMembers ? '${copyWithContract(className: className, parameters: co } /// Emits `copyWith`, `operator ==`, `hashCode`, and `toString` for a - /// schema-first model class. + /// generated model class or mixin. List valueMethods({ required String className, required List fields, required bool hasParameters, - }) => [ - Method( - (m) => m - ..name = 'copyWith' - ..type = MethodType.getter - ..returns = refer('${ackCopyWithInterfaceName(className)}<$className>') - ..docs.add( - '/// Creates a copy of this model with selected fields replaced.', - ) - ..lambda = true - ..body = Code( - _copyWithCreation(className, hasParameters: hasParameters), + bool castSelf = false, + }) { + final castFields = castSelf && fields.isNotEmpty; + final comparisons = [ + for (final field in fields) + _equals( + '${castFields ? 'self' : 'this'}.${field.dartName}', + 'other.${field.dartName}', ), - ), - Method( - (m) => m - ..name = 'operator ==' - ..annotations.add(refer('override')) - ..returns = refer('bool') - ..requiredParameters.add( - Parameter( - (p) => p - ..name = 'other' - ..type = refer('Object'), + ]; + final equalsBody = castFields + ? ''' +if (identical(this, other)) return true; +if (other is! $className || runtimeType != other.runtimeType) return false; +final self = this as $className; +return ${comparisons.join(' && ')}; +''' + : _directEqualsExpression(className, comparisons); + final hash = _hashExpression(fields, receiver: castFields ? 'self' : null); + final preview = _toStringPreview( + className, + fields, + receiver: castFields ? 'self' : null, + ); + return [ + Method( + (m) => m + ..name = 'copyWith' + ..type = MethodType.getter + ..returns = refer( + '${ackCopyWithInterfaceName(className)}<$className>', + ) + ..docs.add( + '/// Creates a copy of this model with selected fields replaced.', + ) + ..lambda = true + ..body = Code( + _copyWithCreation( + className, + hasParameters: hasParameters, + castSelf: castSelf, + ), + ), + ), + Method( + (m) => m + ..name = 'operator ==' + ..annotations.add(refer('override')) + ..returns = refer('bool') + ..requiredParameters.add( + Parameter( + (p) => p + ..name = 'other' + ..type = refer('Object'), + ), + ) + ..lambda = !castFields + ..body = Code(equalsBody), + ), + Method( + (m) => m + ..name = 'hashCode' + ..annotations.add(refer('override')) + ..type = MethodType.getter + ..returns = refer('int') + ..lambda = !castFields + ..body = Code( + castFields + ? 'final self = this as $className; return $hash;' + : hash, + ), + ), + Method( + (m) => m + ..name = 'toString' + ..annotations.add(refer('override')) + ..returns = refer('String') + ..lambda = !castFields + ..body = Code( + castFields + ? "final self = this as $className; return '$preview';" + : "'$preview'", ), - ) - ..lambda = true - ..body = Code(_directEqualsExpression(className, fields)), - ), - Method( - (m) => m - ..name = 'hashCode' - ..annotations.add(refer('override')) - ..type = MethodType.getter - ..returns = refer('int') - ..lambda = true - ..body = Code(_hashExpression(fields)), - ), - Method( - (m) => m - ..name = 'toString' - ..annotations.add(refer('override')) - ..returns = refer('String') - ..lambda = true - ..body = Code("'${_toStringPreview(className, fields)}'"), - ), - ]; + ), + ]; + } /// The typed `copyWith` interface and its implementation, plus the private /// sentinel type when a nullable field needs one. @@ -211,78 +250,6 @@ $sentinelField$sourceField @override }'''; } - /// The `copyWith` getter that exposes [copyWithContract]'s interface. - String copyWithGetter({ - required String className, - required bool hasParameters, - bool castSelf = false, - }) { - final creation = _copyWithCreation( - className, - hasParameters: hasParameters, - castSelf: castSelf, - ); - return ''' -/// Creates a copy of this model with selected fields replaced. -${ackCopyWithInterfaceName(className)}<$className> get copyWith => $creation;'''; - } - - String equalityMembers({ - required String className, - required List fields, - bool castSelf = false, - }) { - if (castSelf && fields.isNotEmpty) { - final fieldEquals = [ - for (final field in fields) - _equals('self.${field.dartName}', 'other.${field.dartName}'), - ]; - final equality = fieldEquals.isEmpty ? 'true' : fieldEquals.join(' && '); - final hashes = _hashExpression(fields, receiver: 'self'); - return ''' -@override -bool operator ==(Object other) { - if (identical(this, other)) return true; - if (other is! $className || runtimeType != other.runtimeType) { - return false; - } - final self = this as $className; - return $equality; -} - -@override -int get hashCode { - final self = this as $className; - return $hashes; -}'''; - } - return ''' -@override -bool operator ==(Object other) => - ${_directEqualsExpression(className, fields)}; - -@override -int get hashCode => ${_hashExpression(fields)};'''; - } - - String toStringMethod({ - required String className, - required List fields, - bool castSelf = false, - }) { - if (castSelf && fields.isNotEmpty) { - return ''' -@override -String toString() { - final self = this as $className; - return '${_toStringPreview(className, fields, receiver: 'self')}'; -}'''; - } - return ''' -@override -String toString() => '${_toStringPreview(className, fields)}';'''; - } - String jsonMembers({required String className, required String facadeName}) { return ''' /// Validates this model and encodes it for JSON. @@ -308,12 +275,14 @@ ${_ack('SchemaResult')}> safeToJson() => : 'const $implementationName()'; } - String _directEqualsExpression(String className, List fields) { + String _directEqualsExpression( + String className, + List fieldComparisons, + ) { final comparisons = [ 'other is $className', 'runtimeType == other.runtimeType', - for (final field in fields) - _equals('this.${field.dartName}', 'other.${field.dartName}'), + ...fieldComparisons, ]; return 'identical(this, other) || (${comparisons.join(' && ')})'; } diff --git a/packages/ack_generator/lib/src/builders/model_emitter.dart b/packages/ack_generator/lib/src/builders/model_emitter.dart index bd89dddb..5b43067d 100644 --- a/packages/ack_generator/lib/src/builders/model_emitter.dart +++ b/packages/ack_generator/lib/src/builders/model_emitter.dart @@ -1,5 +1,6 @@ import 'package:code_builder/code_builder.dart'; +import '../analyzer/schema_first_names.dart'; import '../models/schema_model_graph.dart'; import '../utils/string_literal.dart'; import 'data_class_emitter.dart'; @@ -176,7 +177,9 @@ final class AckModelEmitter { _adapter(node, node.id.declarationName), if (_exposesSchemaShorthand( declarationName: node.id.declarationName, - discriminatorKey: node.discriminatorKey, + discriminatorKey: ackSchemaFirstDiscriminatorName( + node.discriminatorKey, + ), )) _schemaShorthand(node), ]) @@ -194,7 +197,7 @@ final class AckModelEmitter { Method( (m) => m ..type = MethodType.getter - ..name = node.discriminatorKey + ..name = ackSchemaFirstDiscriminatorName(node.discriminatorKey) ..docs.add( '/// The discriminator value that selects this branch.', ) @@ -251,7 +254,7 @@ return switch (value[${dartStringLiteral(node.discriminatorKey)}]) { if (_exposesSchemaShorthand( declarationName: union.id.declarationName, fields: fields, - discriminatorKey: discriminator, + discriminatorKey: ackSchemaFirstDiscriminatorName(discriminator), )) _schemaShorthand(node), ]) @@ -269,7 +272,7 @@ return switch (value[${dartStringLiteral(node.discriminatorKey)}]) { (m) => m ..annotations.add(refer('override')) ..type = MethodType.getter - ..name = discriminator + ..name = ackSchemaFirstDiscriminatorName(discriminator) ..returns = refer('String') ..lambda = true ..body = Code(dartStringLiteral(value)), diff --git a/packages/ack_generator/lib/src/inference/schema_inference.dart b/packages/ack_generator/lib/src/inference/schema_inference.dart index f45cbbec..0d981732 100644 --- a/packages/ack_generator/lib/src/inference/schema_inference.dart +++ b/packages/ack_generator/lib/src/inference/schema_inference.dart @@ -74,7 +74,7 @@ final class AckSchemaInference { typeArguments: type.typeArguments, nullabilitySuffix: NullabilitySuffix.none, ); - return '${_ack('Ack')}.list($itemSchema).codec<${renderType(runtimeType)}>(decode: (list) => list.toSet(), encode: (set) => set.toList(growable: false),)'; + return '${_ack('Ack')}.list($itemSchema).unique().codec<${renderType(runtimeType)}>(decode: (list) => list.toSet(), encode: (set) => set.toList(growable: false),)'; } if (type.isDartCoreMap) { validateMapKey(type); @@ -111,7 +111,6 @@ final class AckSchemaInference { final isString = scalarType is InterfaceType && _core(scalarType, 'String'); final itemConstraints = []; final setConstraints = []; - var hasUniqueConstraint = false; void addScalarConstraint(String constraint) { if (isCollection) { @@ -121,9 +120,8 @@ final class AckSchemaInference { } } - void addCollectionConstraint(String constraint, {bool isUnique = false}) { + void addCollectionConstraint(String constraint) { if (isSet) { - if (isUnique) hasUniqueConstraint = true; setConstraints.add(constraint); } else { output = '$output$constraint'; @@ -260,7 +258,7 @@ final class AckSchemaInference { isCollection, 'List or Set field', ); - addCollectionConstraint('.unique()', isUnique: true); + if (!isSet) addCollectionConstraint('.unique()'); default: throw InvalidGenerationSource( '${_qualifiedName(declaration)} has unsupported rule $annotation.', @@ -272,11 +270,6 @@ final class AckSchemaInference { output = _appendListItemConstraints(output, itemConstraints.join()); } if (setConstraints.isNotEmpty) { - if (isSet && !hasUniqueConstraint) { - // A Set cannot retain duplicate values after decoding. Validate the - // boundary with the same cardinality before the codec runs. - setConstraints.add('.unique()'); - } output = _beforeOuterCodec(output, setConstraints.join()); } return output; diff --git a/packages/ack_generator/lib/src/model_generator.dart b/packages/ack_generator/lib/src/model_generator.dart index 011424db..5cd5bc44 100644 --- a/packages/ack_generator/lib/src/model_generator.dart +++ b/packages/ack_generator/lib/src/model_generator.dart @@ -143,7 +143,6 @@ final class AckModelGenerator extends Generator { final body = output.where((chunk) => chunk.trim().isNotEmpty).join('\n\n'); if (body.isEmpty) return ''; return '// ignore_for_file: type=lint\n' - '// ignore_for_file: invalid_use_of_internal_member\n' '// coverage:ignore-file\n\n' '$body'; } diff --git a/packages/ack_generator/test/integration/ack_infer_contract_test.dart b/packages/ack_generator/test/integration/ack_infer_contract_test.dart index 0dae8eec..f4a86da9 100644 --- a/packages/ack_generator/test/integration/ack_infer_contract_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_contract_test.dart @@ -86,8 +86,8 @@ final userSchema = Ack.object({ contains("value['nickname'] as String?"), contains("value['middleName'] as String?"), contains("value['role'] as String"), - contains("'nickname': ?nickname"), - contains("'middleName': middleName"), + contains("'nickname': ?this.nickname"), + contains("'middleName': this.middleName"), isNot(contains(r'_$UserFromJson')), isNot(contains(r'_$UserToJson')), isNot(contains('_ackFromRuntimeName')), diff --git a/packages/ack_generator/test/integration/ack_infer_graph_test.dart b/packages/ack_generator/test/integration/ack_infer_graph_test.dart index f4cdf75d..4d3f966e 100644 --- a/packages/ack_generator/test/integration/ack_infer_graph_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_graph_test.dart @@ -1035,23 +1035,6 @@ final userSchema = Ack.object({'_class': Ack.string()}); ); }); - test('rejects a leading-underscore discriminator key', () async { - await _expectFailure( - ''' -$_head -@Schemable() -final catSchema = Ack.object({'lives': Ack.integer()}); - -@Schemable() -final petSchema = Ack.discriminated( - discriminatorKey: '_kind', - schemas: {'cat': catSchema}, -); -''', - ['petSchema._kind', "cannot start with '_'"], - ); - }); - test('rejects an anonymous inline object field with the path', () async { await _expectFailure( ''' diff --git a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart index d2767536..1ecda179 100644 --- a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart @@ -325,6 +325,43 @@ final specialWireChoiceSchema = Ack.discriminated( schemas: {'a': specialWireBranchSchema}, ); +@Schemable(discriminatorKey: 'type', caseStyle: AckCaseStyle.pascal) +sealed class StoredAnimal with _$StoredAnimalAck { + const StoredAnimal(); +} + +@Schemable(discriminatorValue: 'cat') +final class StoredCat extends StoredAnimal with _$StoredCatAck { + const StoredCat(); + final String type = 'cat'; +} + +@Schemable(discriminatorKey: '@type') +sealed class AliasAnimal with _$AliasAnimalAck { + const AliasAnimal(); +} + +@Schemable(discriminatorValue: 'cat') +final class AliasCat extends AliasAnimal with _$AliasCatAck { + const AliasCat(); + @AckKey('@type') + final String kind = 'cat'; +} + +@Schemable() +final typenameBranchSchema = Ack.object({'id': Ack.string()}); +@Schemable() +final typenameChoiceSchema = Ack.discriminated( + discriminatorKey: '__typename', + schemas: {'Branch': typenameBranchSchema}, +); + +@Schemable() +final class UniqueTags with _$UniqueTagsAck { + const UniqueTags({required this.tags}); + final Set tags; +} + @Schemable() final wireNamesSchema = Ack.object({ 'first_name': Ack.string(), @@ -625,6 +662,20 @@ void main() { expect(SpecialWireChoice.parse(wire).toJson(), wire); }); + test('stored and nonidentifier discriminators use their wire key', () { + expect(const StoredCat().toJson(), {'type': 'cat'}); + expect(const AliasCat().toJson(), {'@type': 'cat'}); + const json = {'__typename': 'Branch', 'id': 'x'}; + final model = TypenameChoice.parse(json); + expect(model.typename, 'Branch'); + expect(model.toJson(), json); + }); + + test('an unconstrained Set rejects duplicate wire values', () { + expect(UniqueTagsSchema.safeParse({'tags': ['x', 'x']}).isFail, isTrue); + expect(UniqueTagsSchema.safeParse({'tags': ['x', 'y']}).isOk, isTrue); + }); + test('schema-first JSON keys keep their wire spelling', () { const json = {'first_name': 'Ada', 'user-id': 7, '_nickname': 'A'}; final model = WireNames.parse(json); diff --git a/packages/ack_generator/test/integration/class_model_emitter_test.dart b/packages/ack_generator/test/integration/class_model_emitter_test.dart index 086a240a..eb9003e5 100644 --- a/packages/ack_generator/test/integration/class_model_emitter_test.dart +++ b/packages/ack_generator/test/integration/class_model_emitter_test.dart @@ -104,7 +104,7 @@ final class Grid with _\$GridAck { 'test_pkg|lib/grid.g.dart': decodedMatches( allOf( _containsCode( - 'Ack.list(Ack.list(Ack.integer()).codec>(' + 'Ack.list(Ack.list(Ack.integer()).unique().codec>(' 'decode: (list) => list.toSet(), ' 'encode: (set) => set.toList(growable: false),' ')).minItems(2).unique().codec>>(', @@ -437,7 +437,7 @@ final class Envelope with _\$EnvelopeAck { contains("'kind': Ack.any()"), contains("'payload': Ack.any().optional().nullable()"), contains("'items': Ack.list(Ack.any())"), - contains("'tags': Ack.list(Ack.any()).codec>"), + contains("'tags': Ack.list(Ack.any()).unique().codec>"), contains("'values': Ack.map(Ack.any())"), contains("'metadata': Ack.map(Ack.any().nullable())"), contains("'labels': Ack.map(Ack.string().nullable())"), diff --git a/packages/ack_generator/test/integration/generated_names_contract_test.dart b/packages/ack_generator/test/integration/generated_names_contract_test.dart index aa80fa4e..5c131bfa 100644 --- a/packages/ack_generator/test/integration/generated_names_contract_test.dart +++ b/packages/ack_generator/test/integration/generated_names_contract_test.dart @@ -23,6 +23,19 @@ Future _expectFailure(String source, List messages) async { } } +Future _expectOutput(String source, List snippets) async { + await testBuilder( + ackModelBuilder(BuilderOptions.empty), + {'test_pkg|lib/models.dart': source}, + readerWriter: await createTestReaderWriter(), + outputs: { + 'test_pkg|lib/models.g.dart': decodedMatches( + allOf(snippets.map(contains)), + ), + }, + ); +} + const _head = ''' import 'package:ack/ack.dart'; part 'models.g.dart'; @@ -44,20 +57,23 @@ final class $name {} } for (final model in ['User', 'Renamed']) { - test('rejects field matching generated class $model', () async { - await _expectFailure( + test('normalizes wire keys spelled like generated class $model', () async { + await _expectOutput( ''' $_head @Schemable(name: '$model') final userSchema = Ack.object({'$model': Ack.string()}); ''', - ['userSchema.$model', 'class name'], + [ + 'final String ${model.toLowerCase()};', + "'$model': this.${model.toLowerCase()}", + ], ); }); } - test('checks inherited fields against an alias model name', () async { - await _expectFailure( + test('keeps a normalized field when its schema is aliased', () async { + await _expectOutput( ''' $_head @Schemable() @@ -65,7 +81,7 @@ final originalSchema = Ack.object({'Alias': Ack.string()}); @Schemable() final aliasSchema = originalSchema; ''', - ['aliasSchema.Alias', 'class name'], + ['final class Alias', 'final String alias;', "'Alias': this.alias"], ); }); @@ -124,9 +140,11 @@ final aliasSchema = baseSchema$overrides; } for (final discriminator in ['Pet', 'Cat']) { - test('rejects discriminator matching class $discriminator', () async { - await _expectFailure( - ''' + test( + 'normalizes wire discriminator spelled like class $discriminator', + () async { + await _expectOutput( + ''' $_head @Schemable() final catSchema = Ack.object({}); @@ -135,9 +153,13 @@ final petSchema = Ack.discriminated( discriminatorKey: '$discriminator', schemas: {'cat': catSchema}, ); ''', - [discriminator, 'class name'], - ); - }); + [ + "String get ${discriminator.toLowerCase()}", + "value['$discriminator']", + ], + ); + }, + ); } test( From d03b3fab5f1dbbc46d1c27bdd4b4d6e6d6938100 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:18:42 -0500 Subject: [PATCH 18/57] docs(generator): clarify reserved fields and shared builder migration Release readiness C8 and C9. --- docs/getting-started/migration-guide.mdx | 1 + packages/ack_generator/CHANGELOG.md | 3 +++ .../ack_generator/lib/src/analyzer/schema_first_names.dart | 6 ++++-- .../test/integration/ack_infer_graph_test.dart | 2 +- .../ack_generator/test/src/schema_first_names_test.dart | 2 +- 5 files changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 31706127..147830a5 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -91,6 +91,7 @@ Ack is organized into five coordinated packages that share one version number an | Implicit field style on an annotated branch of a styled sealed class | `2.0.0` | Regenerate to inherit the base’s style. Use `caseStyle: AckCaseStyle.none` on the branch to retain Dart names on the wire. | | Class-owned schema refinements | `2.0.0` | Generated helpers and nested fields now enforce them. Compose `ModelSchema.schema` explicitly when you need the raw generated rules. | | Schema-first fields using snake_case or another wire spelling | `2.0.0` | Regenerate and use the lowerCamelCase Dart names in field accesses, constructors and `copyWith`. JSON keys keep their original spelling. | +| The direct `ackModelBuilder` factory | `2.0.0` | Use the shared `ack_generator:ack_generator` builder with source_gen’s combining builder. | | **Typed `$ClassCopyWith` getter** | `1.7.0` | `model.copyWith` returns a typed callable interface instead of widening parameters to `Object?`. | Passing `model.copyWith(age: 'wrong')` previously compiled and failed only at runtime (`TypeError`). Now mistyped arguments fail at compile time while `model.copyWith(age: null)` still clears nullable fields. | | **Two-way string normalizers (`.trim()`, `.toLowerCase()`, `.toUpperCase()`)** | `2.0.0` | Normalizers live directly on `StringSchema` and run in declaration order alongside constraints during both `parse` and `encode`. | In 1.x, `.trim()` used a one-way `.transform()`, which failed on `encode()`, was rejected by `@Schemable()`, and emitted `'x-transformed': true` in JSON Schema. | | **`JsonMaybe` (`JsonAbsent` / `JsonValue`)** | `2.0.0` | Tri-state field container for class-first `@Schemable()` models. | A plain `String?` field in Dart cannot distinguish `{"bio": null}` (clear field in a `PATCH` request) from `{}` (leave field unchanged) when encoding back to JSON. | diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 663a4c9c..b4d70085 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -2,6 +2,9 @@ ### Breaking +* **Breaking:** Use the configured shared part builder instead of the + generator's old direct `ackModelBuilder` export. + * **Breaking:** Generated `Set` fields reject duplicate JSON values. * **Breaking:** A stored discriminator uses its configured JSON key once. Schema-first discriminator getters use lowerCamelCase. diff --git a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart index b7585f75..6f2fad9a 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart @@ -30,10 +30,12 @@ String? ackSchemaFirstFieldNameProblem( if (key.startsWith('_')) { return "cannot start with '_' (private Dart member)."; } - if (!RegExp(r'^[A-Za-z$][A-Za-z0-9_$]*$').hasMatch(key) || - isDartReservedWord(key)) { + if (!RegExp(r'^[A-Za-z$][A-Za-z0-9_$]*$').hasMatch(key)) { return 'cannot be represented as a Dart field name.'; } + if (isDartReservedWord(key)) { + return 'maps to the reserved Dart word "$key".'; + } if (key == 'dynamic') { return 'shadows the dynamic type used by generated JSON methods.'; } diff --git a/packages/ack_generator/test/integration/ack_infer_graph_test.dart b/packages/ack_generator/test/integration/ack_infer_graph_test.dart index 4d3f966e..e2e3c4d0 100644 --- a/packages/ack_generator/test/integration/ack_infer_graph_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_graph_test.dart @@ -1031,7 +1031,7 @@ $_head @Schemable() final userSchema = Ack.object({'_class': Ack.string()}); ''', - ['userSchema._class', 'cannot be represented as a Dart field name'], + ['userSchema._class', 'reserved Dart word'], ); }); diff --git a/packages/ack_generator/test/src/schema_first_names_test.dart b/packages/ack_generator/test/src/schema_first_names_test.dart index 86e5d56e..ccff92c6 100644 --- a/packages/ack_generator/test/src/schema_first_names_test.dart +++ b/packages/ack_generator/test/src/schema_first_names_test.dart @@ -34,7 +34,7 @@ void main() { if (!entry.value.isReservedWord) continue; expect( ackSchemaFirstFieldNameProblem(entry.key, capturesExtras: false), - 'cannot be represented as a Dart field name.', + startsWith('maps to the reserved Dart word'), reason: entry.key, ); } From 5328b43c503fe2c9620019891c55d7a397da76b2 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:19:43 -0500 Subject: [PATCH 19/57] test(generator): pin updated field reads and Set construction Release readiness C1 and C9. --- .../test/integration/ack_infer_data_class_test.dart | 2 +- .../test/integration/inference_library_test.dart | 6 +++--- .../ack_generator/test/integration/library_schema_test.dart | 4 +++- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/ack_generator/test/integration/ack_infer_data_class_test.dart b/packages/ack_generator/test/integration/ack_infer_data_class_test.dart index c5743b29..25293ef5 100644 --- a/packages/ack_generator/test/integration/ack_infer_data_class_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_data_class_test.dart @@ -244,7 +244,7 @@ final userSchema = Ack.object({ '/// Creates a copy of this model with selected fields replaced.', ), contains('User call({'), - contains('deepEquals(name, other.name)'), + contains('deepEquals(this.name, other.name)'), contains('deepHashCode(tags)'), contains(r"toString() => 'User(name: ${name}, tags: ${tags})'"), isNot(contains('class UserType')), diff --git a/packages/ack_generator/test/integration/inference_library_test.dart b/packages/ack_generator/test/integration/inference_library_test.dart index ff27b8bb..bf7db073 100644 --- a/packages/ack_generator/test/integration/inference_library_test.dart +++ b/packages/ack_generator/test/integration/inference_library_test.dart @@ -112,7 +112,7 @@ void widget({@HasMinItems(2) required Set tags}) {} readerWriter: readerWriter, outputs: { 'test_pkg|lib/widget.probe': decodedMatches( - 'Ack.list(Ack.string()).minItems(2).unique().codec>(' + 'Ack.list(Ack.string()).unique().minItems(2).codec>(' 'decode: (list) => list.toSet(), ' 'encode: (set) => set.toList(growable: false),)', ), @@ -135,10 +135,10 @@ void widget({@HasMaxItems(3) required Set> cells}) {} readerWriter: readerWriter, outputs: { 'test_pkg|lib/widget.probe': decodedMatches( - 'Ack.list(Ack.list(Ack.string()).codec>(' + 'Ack.list(Ack.list(Ack.string()).unique().codec>(' 'decode: (list) => list.toSet(), ' 'encode: (set) => set.toList(growable: false),))' - '.maxItems(3).unique().codec>>(' + '.unique().maxItems(3).codec>>(' 'decode: (list) => list.toSet(), ' 'encode: (set) => set.toList(growable: false),)', ), diff --git a/packages/ack_generator/test/integration/library_schema_test.dart b/packages/ack_generator/test/integration/library_schema_test.dart index a253b0d0..65ca1fbf 100644 --- a/packages/ack_generator/test/integration/library_schema_test.dart +++ b/packages/ack_generator/test/integration/library_schema_test.dart @@ -49,7 +49,9 @@ final class Theme with _$ThemeAck { allOf([ containsCode('colorSchema'), containsCode("'palette': Ack.list(colorSchema),"), - containsCode("'swatches': Ack.list(colorSchema).codec>("), + containsCode( + "'swatches': Ack.list(colorSchema).unique().codec>(", + ), containsCode("'namedColors': Ack.map(colorSchema),"), containsCode('Box.schema(colorSchema)'), containsCode('centsSchema'), From acfb12ea974375704a3cb6c5af53329c24dde2b5 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:20:27 -0500 Subject: [PATCH 20/57] test(generator): expect nested generic fields to use model-owned schemas Release readiness C6. --- .../test/integration/type_owned_schema_build_test.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ack_generator/test/integration/type_owned_schema_build_test.dart b/packages/ack_generator/test/integration/type_owned_schema_build_test.dart index 0fabd1f1..641d062c 100644 --- a/packages/ack_generator/test/integration/type_owned_schema_build_test.dart +++ b/packages/ack_generator/test/integration/type_owned_schema_build_test.dart @@ -396,7 +396,7 @@ void main() { .readAsStringSync(); expect(generated, contains('Command.schema()')); expect(generated, contains('Trigger.schema()')); - expect(generated, contains('Box.schema(HabitSchema.schema)')); + expect(generated, contains('Box.schema(Habit.schema)')); expect(generated, contains('Ack.map(Slot.schema)')); _expectSuccess( await _run(temporary, ['analyze', '--fatal-infos']), From cea8b83e87de1409dce242822ff41225be871f7b Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:20:41 -0500 Subject: [PATCH 21/57] docs: complete the public API migration rows Release readiness E1, E2, E5, and E7. --- docs/getting-started/migration-guide.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 5944ed1c..e23799f0 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -169,10 +169,10 @@ and errors: | `@AckType()` `*Type` extension type, `.args`, `ModelType.parse(...)` | `2.0.0` | Generated `Model` class with typed fields, `Model.parse(...)`, `Model.safeParse(...)`, `Model.fromJson(...)`, `model.toJson()` | | `Ack.enumCodec(MyEnum.values)` | `2.0.0` | `Ack.enumValues(MyEnum.values)` | | `ListSchema.minLength`, `maxLength`, `exactLength`, `nonEmpty` | `2.0.0` | Use `minItems`, `maxItems`, `length`, and `notEmpty`, respectively. | -| `StringSchema.url()` | Use `StringSchema.uri()` for the same validation and schema export. | -| Code matching a dotted built-in constraint key | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique`, `number.isFinite` → `number_is_finite`, `integer.isSafe` → `integer_is_safe`. | -| `AckRule` from `package:ack/annotations.dart` | Use the concrete rule annotation type for rule-specific data, or `Object` for a mixed list. | -| `AckSchemaModel.withJsonSchemaKeywords`, `finishTypeJson`, or `finishCompositionJson` | Render the public model with `toJsonSchema()` and apply any custom JSON Schema keywords to the resulting map. | +| `StringSchema.url()` | `2.0.0` | Use `StringSchema.uri()` for the same validation and schema export. | +| Code matching a dotted built-in constraint key | `2.0.0` | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique`, `number.isFinite` → `number_is_finite`, `integer.isSafe` → `integer_is_safe`. | +| `AckRule` from `package:ack/annotations.dart` | `2.0.0` | Use the concrete rule annotation type for rule-specific data, or `Object` for a mixed list. | +| `AckSchemaModel.withJsonSchemaKeywords`, `finishTypeJson`, or `finishCompositionJson` | `2.0.0` | Render the public model with `toJsonSchema()` and apply any custom JSON Schema keywords to the resulting map. | | `schema.toMap()` | `2.0.0` | `schema.toJsonSchema()` or `schema.toSchemaModel()` | | `server.registerAckModelTool(...)` (`ack_mcp_dart`) | `2.0.0` | `server.registerAckTool(name, input: Model.schema, callback: ...)`; return a `CallToolResult` from the callback | | `convertAckSchemaModelToBuilder(model)` (`ack_json_schema_builder`) | `2.0.0` | `schema.toJsonSchemaBuilder()` | From 322f01c176cae6e33e5aca7f18bc0524c830aa4b Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:22:21 -0500 Subject: [PATCH 22/57] test(generator): satisfy linting in wire key assertions Release readiness C8 and C9. --- .../test/integration/generated_names_contract_test.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ack_generator/test/integration/generated_names_contract_test.dart b/packages/ack_generator/test/integration/generated_names_contract_test.dart index 5c131bfa..942ca1c6 100644 --- a/packages/ack_generator/test/integration/generated_names_contract_test.dart +++ b/packages/ack_generator/test/integration/generated_names_contract_test.dart @@ -154,7 +154,7 @@ final petSchema = Ack.discriminated( ); ''', [ - "String get ${discriminator.toLowerCase()}", + 'String get ${discriminator.toLowerCase()}', "value['$discriminator']", ], ); From e7bdaae75a3919593ac67debcdb543f8f838ac11 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:22:22 -0500 Subject: [PATCH 23/57] fix(generator): recognize rules without the public base type Release readiness E5. --- packages/ack/lib/ack.dart | 4 ++-- .../ack_generator/lib/src/inference/schema_inference.dart | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/packages/ack/lib/ack.dart b/packages/ack/lib/ack.dart index 16a3b527..70527fa9 100644 --- a/packages/ack/lib/ack.dart +++ b/packages/ack/lib/ack.dart @@ -4,10 +4,10 @@ /// with a fluent API for runtime data validation and transformation. library; -// Main API -export 'src/ack.dart'; // Model annotations export 'annotations.dart'; +// Main API +export 'src/ack.dart'; // Common types export 'src/common_types.dart' show JsonMap; // Constraints diff --git a/packages/ack_generator/lib/src/inference/schema_inference.dart b/packages/ack_generator/lib/src/inference/schema_inference.dart index 04b47888..6039672c 100644 --- a/packages/ack_generator/lib/src/inference/schema_inference.dart +++ b/packages/ack_generator/lib/src/inference/schema_inference.dart @@ -1,4 +1,3 @@ -import 'package:ack/annotations.dart' as annotations; import 'package:analyzer/dart/analysis/utilities.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/constant/value.dart'; @@ -20,8 +19,8 @@ final class AckSchemaInference { final String? ackPrefix; - static const _rule = TypeChecker.typeNamed( - annotations.AckRule, + static const _rule = TypeChecker.typeNamedLiterally( + 'AckRule', inPackage: 'ack', ); From dccc05ae464d21fc036d38c797420eba52dd770a Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:25:10 -0500 Subject: [PATCH 24/57] test(generator): pin class-owned collection schemas C6, C9. Verify that generated lists honor a declared model schema and generated sets validate uniqueness before decoding. --- .../test/integration/type_owned_schema_test.dart | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/packages/ack_generator/test/integration/type_owned_schema_test.dart b/packages/ack_generator/test/integration/type_owned_schema_test.dart index 2abd419d..59b4d801 100644 --- a/packages/ack_generator/test/integration/type_owned_schema_test.dart +++ b/packages/ack_generator/test/integration/type_owned_schema_test.dart @@ -48,7 +48,7 @@ final class Section with _$SectionAck { allOf( containsCode("'children': Ack.list(Slot.schema),"), containsCode( - "'unique': Ack.list(WidgetId.schema).codec>(", + "'unique': Ack.list(WidgetId.schema).unique().codec>(", ), containsCode("'byName': Ack.map(Slot.schema),"), ), @@ -340,8 +340,7 @@ final class Color { }); test('a Schemable class may expose its backing schema or facade as a static schema', () async { - await expectOutput( - r''' + await expectOutput(r''' @Schemable() final class Habit with _$HabitAck { const Habit({required this.name}); @@ -357,12 +356,7 @@ final class Routine with _$RoutineAck { final List habits; } -''', - allOf( - containsCode("Ack.object({'habits': Ack.list(HabitSchema.schema)})"), - isNot(contains('Habit.schema')), - ), - ); +''', containsCode("Ack.object({'habits': Ack.list(Habit.schema)})")); }); test('a Schemable class rejects a static schema of another type', () async { From 1500d079b1014f293fb25758630bd8c023de6e81 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:27:20 -0500 Subject: [PATCH 25/57] test(ack): exercise legacy aliases through their public base E5. Keep the beta alias fixture compatible until workstream A removes it. --- .../ack_generator/test/integration/validate_alias_test.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ack_generator/test/integration/validate_alias_test.dart b/packages/ack_generator/test/integration/validate_alias_test.dart index 5e152cc7..e9b5626c 100644 --- a/packages/ack_generator/test/integration/validate_alias_test.dart +++ b/packages/ack_generator/test/integration/validate_alias_test.dart @@ -113,7 +113,7 @@ void main() { test('Validate constructors return the rule annotations', () { // Each old constructor, the rule it returns (null when the rule keeps the // old kind), and the deprecated kind and value it exposed before 2.0. - const cases = <(Validate, AckRule?, String, Object?)>[ + const cases = <(Validate, Validate?, String, Object?)>[ (Validate.optional(), IsOptional(), 'optional', null), (Validate.required(), IsRequired(), 'required', null), (Validate.notNull(), IsNotNull(), 'notNull', null), From 548826c8ee314ecb3af6f300b2ff86354128650f Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 09:27:26 -0500 Subject: [PATCH 26/57] test(generator): match each normalized wire key assertion C8. Pass a list of matchers to allOf so each Dart name and wire key is checked independently. --- .../test/integration/generated_names_contract_test.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ack_generator/test/integration/generated_names_contract_test.dart b/packages/ack_generator/test/integration/generated_names_contract_test.dart index 942ca1c6..2032f28a 100644 --- a/packages/ack_generator/test/integration/generated_names_contract_test.dart +++ b/packages/ack_generator/test/integration/generated_names_contract_test.dart @@ -30,7 +30,7 @@ Future _expectOutput(String source, List snippets) async { readerWriter: await createTestReaderWriter(), outputs: { 'test_pkg|lib/models.g.dart': decodedMatches( - allOf(snippets.map(contains)), + allOf(snippets.map(contains).toList()), ), }, ); From 09df6ce0b960aa7ef4cbea57294a5566e04e88f2 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 17:56:59 +0000 Subject: [PATCH 27/57] fix(generator)!: reject custom class-owned schemas in sealed unions --- docs/core-concepts/typesafe-schemas.mdx | 6 ++++ docs/getting-started/migration-guide.mdx | 6 ++++ packages/ack_generator/CHANGELOG.md | 4 +++ .../analyzer/class_model_graph_builder.dart | 32 ++++++++++++++++- .../class_first_runtime_build_test.dart | 6 ++-- .../integration/class_model_graph_test.dart | 36 +++++++++++++++++++ .../build-data-classes-with-ack/SKILL.md | 1 + 7 files changed, 88 insertions(+), 3 deletions(-) diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index f11883e2..1c65f451 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -558,6 +558,12 @@ raw generated schema when declaring `Model.schema` with refinements. ### Class-first unions +The sealed base and its branches may expose a static `schema` only as a +direct alias of their generated facade's `schema`, such as +`static final schema = PetSchema.schema;`. Apply custom validation to the +union schema where you use it, or use a non-union model for a class-owned +schema with refinements. + Every branch inherits the sealed base’s `caseStyle` by default, including branches with `@Schemable(discriminatorValue: ...)`. Set a branch’s own `caseStyle` to override the base. Use `AckCaseStyle.none` to preserve the diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 147830a5..5c788002 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -6,6 +6,12 @@ This guide summarizes **what exists in Ack today**, **what changed in 1.7 and 2. --- +## Beta.3 to 2.0: generated models + +| Affected code | Changed in | Migration | +| --- | --- | --- | +| A custom static `schema` on a class-first sealed union base or branch | `2.0.0` | Expose the generated facade's `schema` directly. Apply custom validation at the union level or use a non-union model. | + ## Beta.2 to beta.3: `Is…`/`Has…` rule annotations 2.0.0-beta.3 replaces the `Validate` namespace with top-level rule diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index b4d70085..9adbbd9d 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -2,6 +2,10 @@ ### Breaking +* **Breaking:** Class-first sealed union bases and branches may declare a + static `schema` only as a direct alias of their generated facade's schema. + Apply custom validation at the union level or use a non-union model. + * **Breaking:** Use the configured shared part builder instead of the generator's old direct `ackModelBuilder` export. diff --git a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart index 7731db2f..6741d6db 100644 --- a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart @@ -118,6 +118,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { element: element, ); } + _validateStaticSchema(element); await _buildObject(element, options: options); } _rejectRecursiveClassFirstGraphs(); @@ -192,7 +193,6 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { ); } _rejectRedirectingFactory(element); - _validateStaticSchema(element); _validateStaticFromJson(element); _requireFinalConcreteClass(element); if (_jsonSerializableChecker.hasAnnotationOfExact(element)) { @@ -251,6 +251,34 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { ); } + void _validateUnionStaticSchema(ClassElement element, _ModelOptions options) { + final getter = element.getGetter('schema'); + final method = element.getMethod('schema'); + final member = switch ((getter, method)) { + (final getter?, _) when getter.isStatic => getter, + (_, final method?) when method.isStatic => method, + _ => null, + }; + if (member == null) return; + + final facadeSchema = '${_facadeName(element, options)}.schema'; + final expression = declarationExpression( + inputResolved!, + propertyDeclaration(member), + ); + if (member is GetterElement && + expression?.unParenthesized.toSource() == facadeSchema) { + _validateStaticSchema(element); + return; + } + + throw InvalidGenerationSource( + '${element.name}.schema must directly expose $facadeSchema ' + 'in a sealed union. Validate at the union level or use a non-union model.', + element: propertyDeclaration(member), + ); + } + /// A model may expose `static final fromJson = XSchema.fromJson;` or a static /// `fromJson` method. Either must accept a JSON map and return the model. /// @@ -340,6 +368,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { _requireMixin(base); _rejectGeneratedMemberCollisions(base, includeValueMembers: false); final baseOptions = _options(base)!; + _validateUnionStaticSchema(base, baseOptions); final discriminatorKey = baseOptions.discriminatorKey!; if (discriminatorKey.isEmpty) { throw InvalidGenerationSource( @@ -406,6 +435,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { element: branch, ); } + _validateUnionStaticSchema(branch, branchOptions); final value = branchOptions.discriminatorValue ?? branch.name!; final prior = valueOwners[value]; if (prior != null) { diff --git a/packages/ack_generator/test/integration/class_first_runtime_build_test.dart b/packages/ack_generator/test/integration/class_first_runtime_build_test.dart index 496df781..3be8c230 100644 --- a/packages/ack_generator/test/integration/class_first_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/class_first_runtime_build_test.dart @@ -484,12 +484,14 @@ final class OptionalCollections with _$OptionalCollectionsAck { @Schemable(discriminatorKey: 'type') sealed class Pet with _$PetAck { const Pet({required this.id}); + static final schema = PetSchema.schema; final String id; } -@Schemable(discriminatorValue: 'cat') +@Schemable(discriminatorValue: 'cat', schemaName: 'PetCatSchema') final class Cat extends Pet with _$CatAck { const Cat({required super.id, required this.lives}); + static get schema => PetCatSchema.schema; final int lives; } @@ -1182,7 +1184,7 @@ void main() { expect(dog, isA()); expect(dog.toJson(), {'type': 'Dog', 'id': 'd1', 'breed': 'lab'}); expect((cat as Cat).copyWith(lives: 8).id, 'c1'); - final direct = CatSchema.parse({'id': 'c2', 'lives': 7}); + final direct = PetCatSchema.parse({'id': 'c2', 'lives': 7}); expect(direct.toJson(), {'type': 'cat', 'id': 'c2', 'lives': 7}); expect(PetSchema.safeParse({'id': 'c2', 'lives': 7}).isFail, isTrue); }); diff --git a/packages/ack_generator/test/integration/class_model_graph_test.dart b/packages/ack_generator/test/integration/class_model_graph_test.dart index 67dcf810..723484bb 100644 --- a/packages/ack_generator/test/integration/class_model_graph_test.dart +++ b/packages/ack_generator/test/integration/class_model_graph_test.dart @@ -51,6 +51,42 @@ part 'model.g.dart'; '''; void main() { + for (final (owner, baseSchema, branchSchema) in [ + ( + 'Shape', + 'static final schema = ShapeSchema.schema.refine((_) => false);', + '', + ), + ( + 'Range', + '', + 'static final schema = RangeSchema.schema.refine((r) => r.lo <= r.hi);', + ), + ]) { + test('rejects a custom schema on union member $owner', () async { + await _expectFailure( + ''' +@Schemable(discriminatorKey: 'kind') +sealed class Shape with _\$ShapeAck { + const Shape(); + $baseSchema +} + +final class Range extends Shape with _\$RangeAck { + const Range({required this.lo, required this.hi}); + final int lo; + final int hi; + $branchSchema +} +''', + [ + '$owner.schema must directly expose ${owner}Schema.schema', + 'Validate at the union level or use a non-union model.', + ], + ); + }); + } + test('rejects a JsonConverter on a field or class', () async { const converter = ''' final class UriText implements JsonConverter { diff --git a/plugins/ack/skills/build-data-classes-with-ack/SKILL.md b/plugins/ack/skills/build-data-classes-with-ack/SKILL.md index 4ed5514b..95ee0eb8 100644 --- a/plugins/ack/skills/build-data-classes-with-ack/SKILL.md +++ b/plugins/ack/skills/build-data-classes-with-ack/SKILL.md @@ -58,6 +58,7 @@ The rules that make it build: - **Unknown keys** are rejected by default. Use `@Schemable(unknownProperties: AckUnknownPropertyPolicy.capture)` with a `Map additionalProperties` field when you need to round-trip them. - **Inferred field types:** `String`, `bool`, `int`, `double`, `num`, `DateTime` (UTC ISO string), `Uri`, `Duration` (ms), enums, `List`, `Set`, `Map`, `Object`/`Object?` (any JSON), nested `@Schemable` classes, `JsonMaybe`. Any other type needs a schema: read [references/custom-types.md](references/custom-types.md). - **Unions:** `@Schemable(discriminatorKey: 'type') sealed class` with `final class` branches in the same library (`@Schemable(discriminatorValue: 'x')` fixes a wire value; otherwise the class name is used). +- **Union schemas:** A static `schema` on the base or a branch must directly expose its generated facade's `schema`. Apply refinements to the union schema where you use it, or use a non-union model. ## 3. Generate From f0f513d31e43cef737e9451d3e0f380103023d1f Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 17:57:17 +0000 Subject: [PATCH 28/57] fix(ack)!: align built-in constraint keys with their rule families --- docs/getting-started/migration-guide.mdx | 2 +- packages/ack/CHANGELOG.md | 9 +++++++-- .../src/constraints/list_unique_items_constraint.dart | 2 +- .../lib/src/constraints/number_finite_constraint.dart | 2 +- .../constraints/number_safe_integer_constraint.dart | 2 +- .../ack/test/constraints/constraint_equality_test.dart | 10 +++++----- 6 files changed, 16 insertions(+), 11 deletions(-) diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index e23799f0..bb8a1d02 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -170,7 +170,7 @@ and errors: | `Ack.enumCodec(MyEnum.values)` | `2.0.0` | `Ack.enumValues(MyEnum.values)` | | `ListSchema.minLength`, `maxLength`, `exactLength`, `nonEmpty` | `2.0.0` | Use `minItems`, `maxItems`, `length`, and `notEmpty`, respectively. | | `StringSchema.url()` | `2.0.0` | Use `StringSchema.uri()` for the same validation and schema export. | -| Code matching a dotted built-in constraint key | `2.0.0` | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique`, `number.isFinite` → `number_is_finite`, `integer.isSafe` → `integer_is_safe`. | +| Code matching a dotted built-in constraint key | `2.0.0` | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique_items`, `number.isFinite` → `number_finite`, `integer.isSafe` → `number_safe_integer`. | | `AckRule` from `package:ack/annotations.dart` | `2.0.0` | Use the concrete rule annotation type for rule-specific data, or `Object` for a mixed list. | | `AckSchemaModel.withJsonSchemaKeywords`, `finishTypeJson`, or `finishCompositionJson` | `2.0.0` | Render the public model with `toJsonSchema()` and apply any custom JSON Schema keywords to the resulting map. | | `schema.toMap()` | `2.0.0` | `schema.toJsonSchema()` or `schema.toSchemaModel()` | diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 110add11..e68df98d 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -11,8 +11,13 @@ * **Breaking:** Both public annotation entry points export the same concrete rules. The base `AckRule` type is internal. -* **Breaking:** Built-in constraint keys now use snake_case. Update code - that matches the former dotted string, list, number, or integer keys. +* **Breaking:** Update code to match the renamed built-in constraint keys. + `string.startsWith` → `string_starts_with`, + `string.endsWith` → `string_ends_with`, + `string.ip` → `string_ip`, + `list.unique` → `list_unique_items`, + `number.isFinite` → `number_finite`, and + `integer.isSafe` → `number_safe_integer`. * **Breaking:** Use `minItems`, `maxItems`, `length`, and `notEmpty` for lists. The duplicate list method names are removed. diff --git a/packages/ack/lib/src/constraints/list_unique_items_constraint.dart b/packages/ack/lib/src/constraints/list_unique_items_constraint.dart index 6cf69922..55f78df5 100644 --- a/packages/ack/lib/src/constraints/list_unique_items_constraint.dart +++ b/packages/ack/lib/src/constraints/list_unique_items_constraint.dart @@ -10,7 +10,7 @@ final class ListUniqueItemsConstraint extends Constraint> with Validator>, JsonSchemaSpec> { const ListUniqueItemsConstraint() : super( - constraintKey: 'list_unique', + constraintKey: 'list_unique_items', description: 'All items in the list must be unique.', ); diff --git a/packages/ack/lib/src/constraints/number_finite_constraint.dart b/packages/ack/lib/src/constraints/number_finite_constraint.dart index 7a938da3..4c06cadb 100644 --- a/packages/ack/lib/src/constraints/number_finite_constraint.dart +++ b/packages/ack/lib/src/constraints/number_finite_constraint.dart @@ -5,7 +5,7 @@ final class NumberFiniteConstraint extends Constraint with Validator { const NumberFiniteConstraint() : super( - constraintKey: 'number_is_finite', + constraintKey: 'number_finite', description: 'Value must be a finite number.', ); diff --git a/packages/ack/lib/src/constraints/number_safe_integer_constraint.dart b/packages/ack/lib/src/constraints/number_safe_integer_constraint.dart index 8985a6f9..6cdbe1f8 100644 --- a/packages/ack/lib/src/constraints/number_safe_integer_constraint.dart +++ b/packages/ack/lib/src/constraints/number_safe_integer_constraint.dart @@ -10,7 +10,7 @@ final class NumberSafeIntegerConstraint extends Constraint with Validator { const NumberSafeIntegerConstraint() : super( - constraintKey: 'integer_is_safe', + constraintKey: 'number_safe_integer', description: 'Value must be a safe integer.', ); diff --git a/packages/ack/test/constraints/constraint_equality_test.dart b/packages/ack/test/constraints/constraint_equality_test.dart index 8b189a96..aa14e06c 100644 --- a/packages/ack/test/constraints/constraint_equality_test.dart +++ b/packages/ack/test/constraints/constraint_equality_test.dart @@ -10,7 +10,7 @@ import 'package:ack/src/constraints/validators.dart'; import 'package:test/test.dart'; void main() { - test('built-in constraint keys use snake_case', () { + test('built-in constraint keys use canonical names', () { expect( [ PatternConstraint.startsWith('prefix').constraintKey, @@ -24,9 +24,9 @@ void main() { 'string_starts_with', 'string_ends_with', 'string_ip', - 'list_unique', - 'number_is_finite', - 'integer_is_safe', + 'list_unique_items', + 'number_finite', + 'number_safe_integer', ], ); }); @@ -182,7 +182,7 @@ void main() { test('uses generic number constraint key', () { const constraint = NumberFiniteConstraint(); - expect(constraint.constraintKey, 'number_is_finite'); + expect(constraint.constraintKey, 'number_finite'); }); }); From 10d95e82f37893063fb6acea85514912d972cbcf Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 17:58:16 +0000 Subject: [PATCH 29/57] fix(generator): qualify constructor defaults inherited through super parameters --- packages/ack_generator/CHANGELOG.md | 2 + .../analyzer/class_model_graph_builder.dart | 63 ++++++++++++------- .../class_first_runtime_build_test.dart | 30 +++++++++ 3 files changed, 72 insertions(+), 23 deletions(-) diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 9adbbd9d..93d1ac69 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -33,6 +33,8 @@ * Derive UpperCamelCase model names for inline objects under snake_case keys. * Qualify references to class statics in generated constructor defaults. +* Preserve constructor defaults inherited through super parameters, including + defaults that refer to statics on the declaring class. * Escape literal dollar signs and quotes in generated discriminator messages. diff --git a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart index 6741d6db..1e5dfa26 100644 --- a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart @@ -573,7 +573,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { ); } parameters[fieldName] = parameter; - final defaultExpression = _defaultExpression(element, parameter); + final defaultExpression = await _defaultExpression(parameter); defaultExpressions[fieldName] = defaultExpression; constructorParameters.add( AckConstructorParameter( @@ -1370,30 +1370,47 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { ); } - String? _defaultExpression( - ClassElement owner, - FormalParameterElement parameter, - ) { + Future _defaultExpression(FormalParameterElement parameter) async { final original = parameter.defaultValueCode; if (original == null) return null; - final declaration = inputResolved?.getFragmentDeclaration( - parameter.firstFragment, - ); - final content = declaration?.resolvedUnit?.content; - final node = declaration?.node; - if (content == null || node is! FormalParameter) return original; - final value = node.defaultClause?.value; - if (value == null) return original; - final visitor = _ClassStaticReferences(owner); - value.accept(visitor); - if (visitor.offsets.isEmpty) return original; - - var qualified = content.substring(value.offset, value.end); - for (final offset in visitor.offsets.reversed) { - final relative = offset - value.offset; - qualified = qualified.replaceRange(relative, relative, '${owner.name}.'); - } - return qualified; + + for ( + FormalParameterElement? source = parameter; + source != null; + source = source is SuperFormalParameterElement + ? source.superConstructorParameter + : null + ) { + final owner = source.enclosingElement?.enclosingElement; + if (owner is! ClassElement) return original; + final resolved = await resolvedLibraryFor(owner.library); + final declaration = resolved.getFragmentDeclaration(source.firstFragment); + final content = declaration?.resolvedUnit?.content; + final node = declaration?.node; + if (content == null || node is! FormalParameter) return original; + final value = node.defaultClause?.value; + if (value == null) continue; + + final visitor = _ClassStaticReferences(owner); + value.accept(visitor); + if (visitor.offsets.isEmpty) return original; + final visibleOwner = visibleTypeNameFor( + owner.thisType, + path: '${owner.name}.${source.name}', + context: parameter, + ); + var qualified = content.substring(value.offset, value.end); + for (final offset in visitor.offsets.reversed) { + final relative = offset - value.offset; + qualified = qualified.replaceRange( + relative, + relative, + '$visibleOwner.', + ); + } + return qualified; + } + return original; } _ModelOptions? _options( diff --git a/packages/ack_generator/test/integration/class_first_runtime_build_test.dart b/packages/ack_generator/test/integration/class_first_runtime_build_test.dart index 3be8c230..83fb1627 100644 --- a/packages/ack_generator/test/integration/class_first_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/class_first_runtime_build_test.dart @@ -517,6 +517,26 @@ final class BabyRabbit extends Rabbit with _$BabyRabbitAck { final String? note; } +@Schemable(discriminatorKey: 'kind') +sealed class NamedAnimal with _$NamedAnimalAck { + const NamedAnimal({this.name = defaultName}); + static const defaultName = 'animal'; + final String name; +} + +final class NamedDog extends NamedAnimal with _$NamedDogAck { + const NamedDog({super.name}); +} + +final class NamedPuppy extends NamedDog with _$NamedPuppyAck { + const NamedPuppy({super.name}); +} + +final class NamedCat extends NamedAnimal with _$NamedCatAck { + const NamedCat({super.name = defaultName}); + static const defaultName = 'cat'; +} + @Schemable() final class Parent with _$ParentAck { const Parent({required this.id}); @@ -1189,6 +1209,16 @@ void main() { expect(PetSchema.safeParse({'id': 'c2', 'lives': 7}).isFail, isTrue); }); + test('super parameters use the default from their declaring constructor', () { + expect(NamedDogSchema.parse({}).name, 'animal'); + expect(NamedPuppySchema.parse({}).name, 'animal'); + expect(NamedCatSchema.parse({}).name, 'cat'); + expect(NamedAnimalSchema.parse({'kind': 'NamedPuppy'}).toJson(), { + 'kind': 'NamedPuppy', + 'name': 'animal', + }); + }); + test('explicit descriptions and tags describe class-first object schemas', () { const task = 'A task the person can complete.'; expect(TaskSchema.toJsonSchema()['description'], task); From ad14c9546f0d133f66c8a64d0a1ff2b9c32f1a02 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 17:58:32 +0000 Subject: [PATCH 30/57] test(ack): cover schema rendering and context internals --- .../public_api/internal_helpers.dart.txt | 14 ++++ .../schema_model_rendering_hidden.dart.txt | 7 ++ .../json_schema_import_public_api_test.dart | 64 +++++++++++++++++-- 3 files changed, 81 insertions(+), 4 deletions(-) create mode 100644 packages/ack/test/fixtures/public_api/internal_helpers.dart.txt create mode 100644 packages/ack/test/fixtures/public_api/schema_model_rendering_hidden.dart.txt diff --git a/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt b/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt new file mode 100644 index 00000000..11016baf --- /dev/null +++ b/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt @@ -0,0 +1,14 @@ +import 'package:ack/ack.dart'; + +void main() { + final schema = Ack.string(); + final parent = SchemaContext(name: 'root', schema: schema, value: 'value'); + schema.toSchemaModel().withJsonSchemaKeywords({'title': 'item'}); + SchemaContext.transparent( + name: 'item', + schema: schema, + value: 'value', + parent: parent, + operation: SchemaOperation.parse, + ); +} diff --git a/packages/ack/test/fixtures/public_api/schema_model_rendering_hidden.dart.txt b/packages/ack/test/fixtures/public_api/schema_model_rendering_hidden.dart.txt new file mode 100644 index 00000000..dc4ae297 --- /dev/null +++ b/packages/ack/test/fixtures/public_api/schema_model_rendering_hidden.dart.txt @@ -0,0 +1,7 @@ +import 'package:ack/ack.dart'; + +void main() { + final model = Ack.string().toSchemaModel(); + model.finishTypeJson({'type': 'string'}); + model.finishCompositionJson('anyOf', [model]); +} diff --git a/packages/ack/test/json_schema_import_public_api_test.dart b/packages/ack/test/json_schema_import_public_api_test.dart index 67ae6c66..70a32194 100644 --- a/packages/ack/test/json_schema_import_public_api_test.dart +++ b/packages/ack/test/json_schema_import_public_api_test.dart @@ -1,26 +1,55 @@ @TestOn('vm') library; +import 'dart:convert'; import 'dart:io'; import 'package:test/test.dart'; -Future _compileFixture(String name) { +final _packageConfig = File('../../.dart_tool/package_config.json').absolute; + +File _copyFixture(String name) { final temporary = Directory.systemTemp.createTempSync('ack-import-api-'); addTearDown(() => temporary.deleteSync(recursive: true)); - final source = File('test/fixtures/public_api/$name.dart.txt') + return File('test/fixtures/public_api/$name.dart.txt') .copySync('${temporary.path}/consumer.dart'); +} +Future _compileFixture(String name) { + final source = _copyFixture(name); return Process.run(Platform.resolvedExecutable, [ 'compile', 'kernel', - '--packages=${File('../../.dart_tool/package_config.json').absolute.path}', + '--packages=${_packageConfig.path}', '-o', - '${temporary.path}/consumer.dill', + '${source.parent.path}/consumer.dill', source.path, ]); } +Future _analyzeFixture(String name) { + final source = _copyFixture(name); + // Analyze outside Ack and keep workspace package URIs valid in the fixture. + final config = + jsonDecode(_packageConfig.readAsStringSync()) as Map; + final packages = (config['packages'] as List) + .cast>(); + for (final package in packages) { + package['rootUri'] = _packageConfig.uri + .resolve(package['rootUri'] as String) + .toString(); + } + File('${source.parent.path}/.dart_tool/package_config.json') + ..createSync(recursive: true) + ..writeAsStringSync(jsonEncode(config)); + + return Process.run(Platform.resolvedExecutable, [ + 'analyze', + '--format=machine', + source.path, + ], workingDirectory: source.parent.path); +} + void main() { test( 'schema switches need a fallback for the hidden imported schema', @@ -55,6 +84,33 @@ void main() { ); }); + test('schema model rendering helpers are private', () async { + final result = await _compileFixture('schema_model_rendering_hidden'); + expect(result.exitCode, isNot(0)); + for (final name in ['finishTypeJson', 'finishCompositionJson']) { + expect(result.stderr, contains("The method '$name' isn't defined")); + } + }); + + test('consumer code gets diagnostics for internal helpers', () async { + final result = await _analyzeFixture('internal_helpers'); + final diagnostics = const LineSplitter().convert(result.stdout as String); + expect(result.exitCode, isNot(0), reason: result.stderr as String); + expect( + diagnostics, + unorderedEquals([ + for (final name in [ + 'withJsonSchemaKeywords', + 'SchemaContext.transparent', + ]) + allOf( + contains('|INVALID_USE_OF_INTERNAL_MEMBER|'), + contains("'$name'"), + ), + ]), + ); + }); + test('the URI rule is the only public name for URI validation', () async { final result = await _compileFixture('uri_aliases_removed'); expect(result.exitCode, isNot(0)); From 0c1e591df318c2e2a38820332b4402e18e973e24 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 17:58:52 +0000 Subject: [PATCH 31/57] docs(ack): clarify internal schema keyword migration --- docs/getting-started/migration-guide.mdx | 8 +++++++- packages/ack/CHANGELOG.md | 5 +++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index bb8a1d02..487d4c39 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -172,13 +172,19 @@ and errors: | `StringSchema.url()` | `2.0.0` | Use `StringSchema.uri()` for the same validation and schema export. | | Code matching a dotted built-in constraint key | `2.0.0` | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique_items`, `number.isFinite` → `number_finite`, `integer.isSafe` → `number_safe_integer`. | | `AckRule` from `package:ack/annotations.dart` | `2.0.0` | Use the concrete rule annotation type for rule-specific data, or `Object` for a mixed list. | -| `AckSchemaModel.withJsonSchemaKeywords`, `finishTypeJson`, or `finishCompositionJson` | `2.0.0` | Render the public model with `toJsonSchema()` and apply any custom JSON Schema keywords to the resulting map. | +| `AckSchemaModel.finishTypeJson` or `AckSchemaModel.finishCompositionJson` | `2.0.0` | Render the public model with `toJsonSchema()` and apply any custom JSON Schema keywords to the resulting map. | | `schema.toMap()` | `2.0.0` | `schema.toJsonSchema()` or `schema.toSchemaModel()` | | `server.registerAckModelTool(...)` (`ack_mcp_dart`) | `2.0.0` | `server.registerAckTool(name, input: Model.schema, callback: ...)`; return a `CallToolResult` from the callback | | `convertAckSchemaModelToBuilder(model)` (`ack_json_schema_builder`) | `2.0.0` | `schema.toJsonSchemaBuilder()` | | `Ack.fromJsonSchema(...)` enforcing `format` by default | `2.0.0` | Pass `Ack.fromJsonSchema(schema, assertFormats: true)` (or declare `format-assertion` in `$vocabulary`) when format assertions are required | | `schema.toJsonSchema()` lowering imported 2020-12 schemas to Draft-7 | `2.0.0` | `schema.toJsonSchema()` now preserves Draft 2020-12 resources by default; call `schema.toJsonSchemaDraft7()` when Draft-7 lowering is required | +### Internal Runtime APIs + +| `1.x` Item | Changed In | Exact `2.0` Substitution | +| --- | --- | --- | +| `AckSchemaModel.withJsonSchemaKeywords` | `2.0.0` | The method remains callable and is marked `@internal`. External calls produce an analyzer warning. Render with `toJsonSchema()` and apply custom keywords to the resulting map. | + --- ## 4. Before & After Migration Examples diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index e68df98d..74f51123 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -5,8 +5,9 @@ ### Breaking -* **Breaking:** JSON Schema rendering and keyword projection helpers are now - internal to the schema model. Render public models with `toJsonSchema()`. +* **Breaking:** `AckSchemaModel.finishTypeJson` and `finishCompositionJson` + are private. `withJsonSchemaKeywords` remains callable and is marked + `@internal`. Render public models with `toJsonSchema()`. * **Breaking:** Both public annotation entry points export the same concrete rules. The base `AckRule` type is internal. From ee1460c628d6ae7e55b94fea3e3058d28e35f972 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 17:59:06 +0000 Subject: [PATCH 32/57] docs: group URI breaking notes under unreleased headings --- packages/ack/CHANGELOG.md | 4 ++-- packages/ack_generator/CHANGELOG.md | 2 ++ packages/ack_json_schema_builder/CHANGELOG.md | 5 ++++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 74f51123..3b0d1c06 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -1,10 +1,10 @@ ## Unreleased +### Breaking + * **Breaking:** Replace `StringSchema.url()` with `uri()`, and `@IsUrl()` with `@IsUri()`. URI validation and JSON Schema output are unchanged. -### Breaking - * **Breaking:** `AckSchemaModel.finishTypeJson` and `finishCompositionJson` are private. `withJsonSchemaKeywords` remains callable and is marked `@internal`. Render public models with `toJsonSchema()`. diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index d80d4356..44344963 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -1,5 +1,7 @@ ## Unreleased +### Breaking + * **Breaking:** Replace `@IsUrl()` with `@IsUri()` and regenerate model parts. ### Changed diff --git a/packages/ack_json_schema_builder/CHANGELOG.md b/packages/ack_json_schema_builder/CHANGELOG.md index f871137f..5943e1a6 100644 --- a/packages/ack_json_schema_builder/CHANGELOG.md +++ b/packages/ack_json_schema_builder/CHANGELOG.md @@ -1,6 +1,9 @@ ## Unreleased -* Use `Ack.string().uri()` to export the URI format. +### Breaking + +* **Breaking:** Replace `Ack.string().url()` with `Ack.string().uri()` to + export the URI format. ### Changed From 3979eddd2838b25d2d0b8988feba24157fc67238 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 17:59:30 +0000 Subject: [PATCH 33/57] docs(ack): move schema operation into error context guidance --- docs/core-concepts/error-handling.mdx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/core-concepts/error-handling.mdx b/docs/core-concepts/error-handling.mdx index 63615bc7..50a199b0 100644 --- a/docs/core-concepts/error-handling.mdx +++ b/docs/core-concepts/error-handling.mdx @@ -50,6 +50,9 @@ if (result.isFail) { - `error.schema`: The schema being validated against. - `error.path`: The RFC 6901 JSON Pointer path to the failure (for example, `#/address/city`). +A `SchemaContext.operation` is either `SchemaOperation.parse` or +`SchemaOperation.encode`. Both values are available from `package:ack/ack.dart`. + ```dart final userSchema = Ack.object({ 'name': Ack.string(), @@ -239,9 +242,6 @@ validator: (value) { *See the [Form Validation Guide](../guides/flutter-form-validation.mdx) for details.* -A `SchemaContext.operation` is either `SchemaOperation.parse` or -`SchemaOperation.encode`. Both values are available from `package:ack/ack.dart`. - ## Custom error messages 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). From b7c92594c5002b1924ca0c138c32315ff7bd6059 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 17:59:52 +0000 Subject: [PATCH 34/57] fix(generator)!: prevent identifier shadowing in generated models --- docs/core-concepts/typesafe-schemas.mdx | 8 ++ docs/getting-started/migration-guide.mdx | 1 + packages/ack_generator/CHANGELOG.md | 6 ++ .../lib/src/analyzer/schema_first_names.dart | 21 ++++- .../analyzer/schema_model_graph_builder.dart | 91 ++++++++++++++----- .../lib/src/builders/class_model_emitter.dart | 45 ++++++--- .../lib/src/model_generator.dart | 9 +- .../ack_infer_runtime_build_test.dart | 30 ++++++ .../class_first_getter_model_refs_test.dart | 2 +- .../integration/class_first_json_test.dart | 14 +-- .../class_first_value_runtime_refs_test.dart | 6 +- .../integration/class_model_emitter_test.dart | 6 +- .../generated_names_contract_test.dart | 50 ++++++++++ 13 files changed, 230 insertions(+), 59 deletions(-) diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index 1c65f451..20525815 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -143,6 +143,14 @@ use lowerCamelCase. For example, `first_name` becomes `firstName`, `user-id` becomes `userId`, and `_nickname` becomes `nickname`. Generation reports reserved words and keys that map to the same field name. +Field and discriminator names also cannot shadow identifiers used by the +generated class. This includes `bool`, `double`, `dynamic`, `int`, `num`, +`override`, `identical`, `deepEquals`, `deepHashCode`, +`deepUnmodifiableCopy`, and `deepUnmodifiableJsonMap`. Generation also checks +the schema declaration name, the Ack import prefix, and names and import +prefixes used in field types. Use a class-first model with `@AckKey` to keep +the wire key and choose a different Dart field name. + ### Schema-first unions Each branch must be a named `@Schemable()` object schema in the same library: diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 5c788002..2c50f912 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -11,6 +11,7 @@ This guide summarizes **what exists in Ack today**, **what changed in 1.7 and 2. | Affected code | Changed in | Migration | | --- | --- | --- | | A custom static `schema` on a class-first sealed union base or branch | `2.0.0` | Expose the generated facade's `schema` directly. Apply custom validation at the union level or use a non-union model. | +| Schema-first keys that shadow a generated reference, such as `override` or `identical` | `2.0.0` | Use a class-first model with `@AckKey` to preserve the wire key and give the Dart field a different name. | ## Beta.2 to beta.3: `Is…`/`Has…` rule annotations diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 93d1ac69..f53b9b1b 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -2,6 +2,9 @@ ### Breaking +* **Breaking:** Reject schema-first field and discriminator names that shadow + generated references such as `override` and `identical`. + * **Breaking:** Class-first sealed union bases and branches may declare a static `schema` only as a direct alias of their generated facade's schema. Apply custom validation at the union level or use a non-union model. @@ -24,6 +27,9 @@ ### Fixed +* Keep generated class-first runtime locals from capturing identifiers used + by constructor defaults. + * Suggest `@Schemable()` when a union branch cannot resolve to a model. * Document JSON converters for Ack model fields in json_serializable classes. diff --git a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart index 6f2fad9a..6d9dcb73 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart @@ -1,10 +1,8 @@ import '../utils/string_literal.dart'; -/// Names that conflict with generated APIs or their unqualified type references. +/// Names that conflict with generated APIs. const ackSchemaFirstReservedMembers = { r'$ack', - // Generated JSON signatures use the unqualified dynamic type. - 'dynamic', 'parse', 'safeParse', 'fromJson', @@ -19,6 +17,19 @@ const ackSchemaFirstReservedMembers = { 'runtimeType', }; +const _generatedReferences = { + 'bool', + 'double', + 'int', + 'num', + 'override', + 'identical', + 'deepEquals', + 'deepHashCode', + 'deepUnmodifiableCopy', + 'deepUnmodifiableJsonMap', +}; + /// Why [key] cannot be a schema-first field name, or `null` when it can. /// /// [capturesExtras] is whether the model stores unknown properties in its @@ -26,6 +37,7 @@ const ackSchemaFirstReservedMembers = { String? ackSchemaFirstFieldNameProblem( String key, { required bool capturesExtras, + Set generatedReferences = const {}, }) { if (key.startsWith('_')) { return "cannot start with '_' (private Dart member)."; @@ -39,6 +51,9 @@ String? ackSchemaFirstFieldNameProblem( if (key == 'dynamic') { return 'shadows the dynamic type used by generated JSON methods.'; } + if (_generatedReferences.contains(key) || generatedReferences.contains(key)) { + return 'shadows the generated reference "$key".'; + } if (ackSchemaFirstReservedMembers.contains(key)) { return 'conflicts with generated/Object member "$key".'; } diff --git a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart index 0c79cfc4..a71840e7 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart @@ -65,7 +65,7 @@ final class _SchemaMetadata { /// Builds the single normalized graph consumed by Ack model emission. final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { - SchemaModelGraphBuilder(super.library); + SchemaModelGraphBuilder(super.library, {super.ackPrefix}); static const _anyOfSchemaChecker = TypeChecker.typeNamed( AnyOfSchema, @@ -455,18 +455,6 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { ); } final discriminatorName = ackSchemaFirstDiscriminatorName(discriminatorKey); - if (ackSchemaFirstFieldNameProblem( - discriminatorName, - capturesExtras: true, - ) != - null) { - throw InvalidGenerationSource( - '$path.$discriminatorKey conflicts with a generated member or Dart ' - 'keyword.', - element: declaration.element, - ); - } - final branches = {}; for (final element in branchesLiteral.elements) { if (element is! MapLiteralEntry || element.key is! SimpleStringLiteral) { @@ -1337,7 +1325,29 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { final declaration = _declarationsById[node.id]; if (declaration == null) continue; - void checkMember(String name) { + final references = { + if (ackPrefix case final prefix?) prefix, + (_unionOwnerByBranch[node.id] ?? node.id).declarationName, + if (node is AckObjectModelNode) + for (final field in node.fields) ..._typeReferences(field.runtimeRef), + }; + + void checkMember( + String key, + String name, { + required bool capturesExtras, + }) { + final problem = ackSchemaFirstFieldNameProblem( + name, + capturesExtras: capturesExtras, + generatedReferences: references, + ); + if (problem != null) { + throw InvalidGenerationSource( + '${node.id.declarationName}.$key $problem', + element: declaration.element, + ); + } if (name != node.className) return; throw InvalidGenerationSource( '${node.id.declarationName}.$name conflicts with the generated ' @@ -1347,25 +1357,27 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { } if (node is AckUnionModelNode) { - checkMember(ackSchemaFirstDiscriminatorName(node.discriminatorKey)); + checkMember( + node.discriminatorKey, + ackSchemaFirstDiscriminatorName(node.discriminatorKey), + capturesExtras: true, + ); continue; } if (node is AckObjectModelNode) { for (final field in node.fields) { - final problem = ackSchemaFirstFieldNameProblem( + checkMember( + field.jsonKey, field.dartName, capturesExtras: node.additionalProperties, ); - if (problem != null) { - throw InvalidGenerationSource( - '${node.id.declarationName}.${field.jsonKey} $problem', - element: declaration.element, - ); - } - checkMember(field.dartName); } if (node.discriminatorKey case final discriminator?) { - checkMember(ackSchemaFirstDiscriminatorName(discriminator)); + checkMember( + discriminator, + ackSchemaFirstDiscriminatorName(discriminator), + capturesExtras: true, + ); } } validateCopyWithHelperNames( @@ -1383,6 +1395,37 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { } } + Iterable _typeReferences(AckInferRef type) sync* { + switch (type) { + case AckExternalTypeRef( + :final name, + :final importPrefix, + :final typeArguments, + ): + yield importPrefix ?? name; + for (final argument in typeArguments) { + yield* _typeReferences(argument); + } + case AckModelTypeRef( + :final className, + :final importPrefix, + :final runtimeRef, + ): + yield importPrefix ?? className; + yield* _typeReferences(runtimeRef); + case AckListTypeRef(:final elementType) || + AckSetTypeRef(:final elementType): + yield* _typeReferences(elementType); + case AckMapTypeRef(:final valueType) || + AckJsonMaybeTypeRef(:final valueType): + yield* _typeReferences(valueType); + case AckNullableTypeRef(:final inner): + yield* _typeReferences(inner); + case AckScalarTypeRef(): + break; + } + } + void _validateUnionBranchDiscriminator( _Declaration branch, String discriminatorKey, diff --git a/packages/ack_generator/lib/src/builders/class_model_emitter.dart b/packages/ack_generator/lib/src/builders/class_model_emitter.dart index bad01f93..5478387c 100644 --- a/packages/ack_generator/lib/src/builders/class_model_emitter.dart +++ b/packages/ack_generator/lib/src/builders/class_model_emitter.dart @@ -261,13 +261,26 @@ abstract final class ${metadata.facadeName} { final fieldsByName = { for (final field in node.fields) field.dartName: field, }; + // Defaults can reference Dart identifiers from the user's library, + // including ones containing a dollar sign. + final defaults = node.constructorParameters + .map((parameter) => parameter.defaultExpression) + .nonNulls; + var prefix = r'$ack'; + while (defaults.any((expression) => expression.contains(prefix))) { + prefix += r'$'; + } + final value = '${prefix}Value'; + final declared = '${prefix}Declared'; + final entry = '${prefix}Entry'; + final fieldValue = '${prefix}FieldValue'; final arguments = []; for (final parameter in node.constructorParameters) { final String expression; if (parameter.fieldName == node.captureFieldName) { expression = '${_ack('deepUnmodifiableJsonMap')}(Map.fromEntries(\n' - ' value.entries.where((entry) => !declared.contains(entry.key)),\n' + ' $value.entries.where(($entry) => !$declared.contains($entry.key)),\n' ' ))'; } else { final field = fieldsByName[parameter.fieldName]; @@ -276,7 +289,7 @@ abstract final class ${metadata.facadeName} { 'Missing field ${parameter.fieldName} on ${node.className}.', ); } - expression = _decodeParameter(parameter, field); + expression = _decodeParameter(parameter, field, value, fieldValue); } arguments.add( parameter.kind == AckConstructorParameterKind.named @@ -287,13 +300,13 @@ abstract final class ${metadata.facadeName} { if (node.captureFieldName == null) { return ''' -${node.className} $function(Map value) => +${node.className} $function(Map $value) => ${node.className}(${arguments.join(', ')});'''; } - final declared = _declaredKeys(node); + final keys = _declaredKeys(node); return ''' -${node.className} $function(Map value) { - const declared = ${_dataClasses.declaredKeysLiteral(declared)}; +${node.className} $function(Map $value) { + const $declared = ${_dataClasses.declaredKeysLiteral(keys)}; return ${node.className}( ${arguments.join(',\n ')}, ); @@ -303,10 +316,12 @@ ${node.className} $function(Map value) { String _decodeParameter( AckConstructorParameter parameter, AckFieldNode field, + String value, + String fieldValue, ) { if (parameter.typeRef case AckJsonMaybeTypeRef(:final valueType)) { final keyLiteral = dartStringLiteral(field.jsonKey); - final raw = 'value[$keyLiteral]'; + final raw = '$value[$keyLiteral]'; final innerType = _type(valueType); final baseValueType = _dataClasses.nonNullable(valueType); final absentExpr = @@ -327,13 +342,13 @@ ${node.className} $function(Map value) { presentExpr = 'switch ($raw) {' ' null => const ${_ack('JsonMaybe')}<$innerType>.value(null),' - ' final fieldValue => ${_ack('JsonMaybe')}<$innerType>.value(' - '${_fromRuntime(baseValueType, 'fieldValue')}),' + ' final $fieldValue => ${_ack('JsonMaybe')}<$innerType>.value(' + '${_fromRuntime(baseValueType, fieldValue)}),' ' }'; } - return '!value.containsKey($keyLiteral) ? $absentExpr : $presentExpr'; + return '!$value.containsKey($keyLiteral) ? $absentExpr : $presentExpr'; } - final raw = 'value[${dartStringLiteral(field.jsonKey)}]'; + final raw = '$value[${dartStringLiteral(field.jsonKey)}]'; final defaultExpr = parameter.defaultExpression != null && parameter.defaultExpression != 'null' @@ -354,7 +369,7 @@ ${node.className} $function(Map value) { final nullBranch = defaultExpr ?? 'null'; return 'switch ($raw) {' ' null => $nullBranch,' - ' final fieldValue => ${_fromRuntime(baseType, 'fieldValue')},' + ' final $fieldValue => ${_fromRuntime(baseType, fieldValue)},' ' }'; } @@ -377,13 +392,13 @@ Map $function(${node.className} model) => {${fieldEntries.join(', ')}};'''; } final entries = [ - 'for (final entry in model.$capture.entries)\n' - ' if (!declared.contains(entry.key)) entry.key: entry.value', + 'for (final \$ackEntry in model.$capture.entries)\n' + ' if (!\$ackDeclared.contains(\$ackEntry.key)) \$ackEntry.key: \$ackEntry.value', ...fieldEntries, ]; return ''' Map $function(${node.className} model) { - const declared = ${_dataClasses.declaredKeysLiteral(_declaredKeys(node))}; + const \$ackDeclared = ${_dataClasses.declaredKeysLiteral(_declaredKeys(node))}; return { ${entries.join(',\n ')}, }; diff --git a/packages/ack_generator/lib/src/model_generator.dart b/packages/ack_generator/lib/src/model_generator.dart index 5cd5bc44..cbedb1e2 100644 --- a/packages/ack_generator/lib/src/model_generator.dart +++ b/packages/ack_generator/lib/src/model_generator.dart @@ -89,10 +89,13 @@ final class AckModelGenerator extends Generator { ({AckModelGraph graph, String? ackPrefix})? schemaFirst; if (annotated.isNotEmpty) { - final graph = await SchemaModelGraphBuilder(library).build(annotated); + final ackPrefix = _ackRuntimeQualifier(library, annotated.first); schemaFirst = ( - graph: graph, - ackPrefix: _ackRuntimeQualifier(library, annotated.first), + graph: await SchemaModelGraphBuilder( + library, + ackPrefix: ackPrefix, + ).build(annotated), + ackPrefix: ackPrefix, ); } ({AckModelGraph graph, String? ackPrefix})? classFirst; diff --git a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart index 1ecda179..15ab97c2 100644 --- a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart @@ -302,6 +302,25 @@ final class StaticDefaults with _$StaticDefaultsAck { final int limit; } +const value = 20; +const declared = 21; +const $ackValue = 22; + +@Schemable(unknownProperties: AckUnknownPropertyPolicy.capture) +final class UnshadowedDefaults with _$UnshadowedDefaultsAck { + const UnshadowedDefaults({ + this.count = value, + this.retries = declared, + this.limit = $ackValue, + this.additionalProperties = const {}, + }); + + final int count; + final int retries; + final int limit; + final Map additionalProperties; +} + @Schemable(discriminatorKey: r'$type') sealed class SpecialPet with _$SpecialPetAck { const SpecialPet(); @@ -655,6 +674,17 @@ void main() { expect(model.toJson(), {'count': 20, 'retries': 21, 'limit': 20}); }); + test('generated runtime locals do not capture constructor defaults', () { + final model = UnshadowedDefaultsSchema.parse({'extra': true}); + expect(model.additionalProperties, {'extra': true}); + expect(model.toJson(), { + 'extra': true, + 'count': 20, + 'retries': 21, + 'limit': 22, + }); + }); + test('discriminator keys can contain literal dollar signs', () { const pet = {r'$type': 'cat', 'name': 'Milo'}; expect(SpecialPetSchema.parse(pet).toJson(), pet); diff --git a/packages/ack_generator/test/integration/class_first_getter_model_refs_test.dart b/packages/ack_generator/test/integration/class_first_getter_model_refs_test.dart index 8af019f6..0651cbcc 100644 --- a/packages/ack_generator/test/integration/class_first_getter_model_refs_test.dart +++ b/packages/ack_generator/test/integration/class_first_getter_model_refs_test.dart @@ -34,7 +34,7 @@ final class Holder with _$HolderAck { 'test_pkg|lib/models.g.dart': decodedMatches( allOf([ contains('final class Label'), - contains(r"Label.$ack.fromRuntime(value['label'] as String)"), + contains(r"Label.$ack.fromRuntime($ackValue['label'] as String)"), contains(r'Label.$ack.fromRuntime(item as String)'), ]), ), diff --git a/packages/ack_generator/test/integration/class_first_json_test.dart b/packages/ack_generator/test/integration/class_first_json_test.dart index 2a2d13d2..04f41e92 100644 --- a/packages/ack_generator/test/integration/class_first_json_test.dart +++ b/packages/ack_generator/test/integration/class_first_json_test.dart @@ -38,9 +38,9 @@ final class User with _\$UserAck { } ''', allOf([ - contains(r'User _$UserFromRuntime(Map value)'), - contains("firstName: value['first_name'] as String"), - contains("nickname: value['nickname'] as String?"), + contains(r'User _$UserFromRuntime(Map $ackValue)'), + contains("firstName: \$ackValue['first_name'] as String"), + contains("nickname: \$ackValue['nickname'] as String?"), contains(r'Map _$UserToRuntime(User model)'), contains("'first_name': model.firstName"), contains("'nickname': ?model.nickname"), @@ -69,8 +69,8 @@ final class Cat extends Pet with _\$CatAck { ''', allOf([ contains(r'Cat _$CatFromRuntime'), - contains("id: value['id'] as String"), - contains("lives: value['lives'] as int"), + contains("id: \$ackValue['id'] as String"), + contains("lives: \$ackValue['lives'] as int"), contains("'id': model.id"), contains("'lives': model.lives"), isNot(contains(r'Pet _$PetFromRuntime')), @@ -95,7 +95,7 @@ final class Cat extends Pet with _\$CatAck { } ''', allOf([ - contains("livesLeft: value['lives_left'] as int"), + contains("livesLeft: \$ackValue['lives_left'] as int"), contains("'lives_left': model.livesLeft"), ]), ); @@ -121,7 +121,7 @@ final class User with _\$UserAck { } ''', allOf([ - contains("firstName: value['$key'] as String"), + contains("firstName: \$ackValue['$key'] as String"), contains("'$key': model.firstName"), ]), ); diff --git a/packages/ack_generator/test/integration/class_first_value_runtime_refs_test.dart b/packages/ack_generator/test/integration/class_first_value_runtime_refs_test.dart index a01a108b..4345468d 100644 --- a/packages/ack_generator/test/integration/class_first_value_runtime_refs_test.dart +++ b/packages/ack_generator/test/integration/class_first_value_runtime_refs_test.dart @@ -49,11 +49,11 @@ final class Holder with _$HolderAck { } ''', allOf([ - contains(r"Scalar.$ack.fromRuntime(value['scalar'] as int)"), + contains(r"Scalar.$ack.fromRuntime($ackValue['scalar'] as int)"), contains( - r"Strings.$ack.fromRuntime(value['strings'] as List)", + r"Strings.$ack.fromRuntime($ackValue['strings'] as List)", ), - contains(r"Encoded.$ack.fromRuntime(value['encoded'] as Token)"), + contains(r"Encoded.$ack.fromRuntime($ackValue['encoded'] as Token)"), ]), ); }, diff --git a/packages/ack_generator/test/integration/class_model_emitter_test.dart b/packages/ack_generator/test/integration/class_model_emitter_test.dart index eb9003e5..8749595b 100644 --- a/packages/ack_generator/test/integration/class_model_emitter_test.dart +++ b/packages/ack_generator/test/integration/class_model_emitter_test.dart @@ -696,7 +696,7 @@ const Type otherAddressType = b.Address; 'test_pkg|lib/order.g.dart': decodedMatches( allOf([ contains("'shipping': a.AddressSchema.schema"), - contains("shipping: value['shipping'] as a.Address"), + contains("shipping: \$ackValue['shipping'] as a.Address"), isNot(contains('b.AddressSchema')), ]), ), @@ -993,9 +993,9 @@ final class UserPatch with _$UserPatchAck { _containsCode( "'tags': Ack.list(Ack.string()).optional().nullable()", ), - _containsCode("value.containsKey('nickname')"), + _containsCode("\$ackValue.containsKey('nickname')"), _containsCode( - "JsonMaybe.value(value['nickname'] as String?)", + "JsonMaybe.value(\$ackValue['nickname'] as String?)", ), _containsCode('const JsonMaybe.absent()'), _containsCode('const JsonMaybe.absent()'), diff --git a/packages/ack_generator/test/integration/generated_names_contract_test.dart b/packages/ack_generator/test/integration/generated_names_contract_test.dart index 2032f28a..c5090a59 100644 --- a/packages/ack_generator/test/integration/generated_names_contract_test.dart +++ b/packages/ack_generator/test/integration/generated_names_contract_test.dart @@ -42,6 +42,56 @@ part 'models.g.dart'; '''; void main() { + for (final name in [ + 'override', + 'identical', + 'bool', + 'int', + 'double', + 'num', + 'deepEquals', + 'deepHashCode', + 'deepUnmodifiableCopy', + 'deepUnmodifiableJsonMap', + ]) { + test('rejects keys that shadow the generated reference $name', () async { + await _expectFailure( + ''' +$_head +@Schemable() +final userSchema = Ack.object({'$name': Ack.integer()}); +''', + ['userSchema.$name', 'shadows', '"$name"'], + ); + }); + } + + test('rejects a field that shadows the adapter schema', () async { + await _expectFailure( + ''' +$_head +@Schemable() +final userSchema = Ack.object({'userSchema': Ack.string()}); +''', + ['userSchema.userSchema', 'shadows', '"userSchema"'], + ); + }); + + test('rejects a discriminator that shadows a generated reference', () async { + await _expectFailure( + ''' +$_head +@Schemable() +final catSchema = Ack.object({}); +@Schemable() +final petSchema = Ack.discriminated( + discriminatorKey: 'identical', schemas: {'cat': catSchema}, +); +''', + ['petSchema.identical', 'shadows', '"identical"'], + ); + }); + for (final name in [r'$TitleCopyWith', r'_$TitleCopyWith']) { test('rejects value-model helper collision $name', () async { await _expectFailure( From a830948e8454b933643c8f7df3e3548f87b206a2 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 18:00:50 +0000 Subject: [PATCH 35/57] fix(generator)!: unify schema-first key tokenization --- docs/core-concepts/typesafe-schemas.mdx | 19 +++++-- docs/getting-started/migration-guide.mdx | 1 + packages/ack_generator/CHANGELOG.md | 5 +- .../lib/src/analyzer/schema_first_names.dart | 36 +++++++------ .../ack_infer_runtime_build_test.dart | 10 ++-- .../test/src/schema_first_names_test.dart | 50 +++++++++++++++++++ 6 files changed, 94 insertions(+), 27 deletions(-) diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index 20525815..ab491e96 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -138,10 +138,21 @@ Generation also rejects nullable roots, `Ack.any()` and `Ack.map()` roots, `Ack.anyOf()`, bare `Ack.instance()`, anonymous inline object fields, unresolved dynamic schema factories, and cross-library union branches. -Schema-first JSON keys keep their spelling on the wire. Generated Dart fields -use lowerCamelCase. For example, `first_name` becomes `firstName`, `user-id` -becomes `userId`, and `_nickname` becomes `nickname`. Generation reports -reserved words and keys that map to the same field name. +Schema-first JSON keys keep their spelling on the wire. Fields, discriminator +getters, and inline JSON Schema model name segments use the same word boundaries. +The generator splits at characters other than ASCII letters and digits +(including `_`, `-`, `.`, `$`, `@`, and non-ASCII characters). It also +splits between a lowercase and an uppercase letter and before a capitalized +word following an acronym, as in `HTTPServer`. An uppercase run and its +optional plural `s` stay together. + +Fields and discriminator getters lowercase each word, capitalize words after +the first, and join them. For example, `UserID` becomes `userId`, `URLs` becomes +`urls`, `user.id` becomes `userId`, and `address_2` becomes `address2`. +Type name segments capitalize each word's first letter and preserve the +remaining letters, so `api_URL` contributes `ApiURL` to a type name. +Generation rejects empty names, names that start with a digit, Dart reserved +words such as `default`, and keys that produce the same Dart member. Field and discriminator names also cannot shadow identifiers used by the generated class. This includes `bool`, `double`, `dynamic`, `int`, `num`, diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 2c50f912..9b008286 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -12,6 +12,7 @@ This guide summarizes **what exists in Ack today**, **what changed in 1.7 and 2. | --- | --- | --- | | A custom static `schema` on a class-first sealed union base or branch | `2.0.0` | Expose the generated facade's `schema` directly. Apply custom validation at the union level or use a non-union model. | | Schema-first keys that shadow a generated reference, such as `override` or `identical` | `2.0.0` | Use a class-first model with `@AckKey` to preserve the wire key and give the Dart field a different name. | +| Schema-first keys and discriminators that generate different Dart names in 2.0 | `2.0.0` | Regenerate and update Dart callers. Keys that worked in beta.3 can now fail if they map to a reserved word such as `Default` → `default` or collide with another key. Use a class-first model with `@AckKey` for those keys. | ## Beta.2 to beta.3: `Is…`/`Has…` rule annotations diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index f53b9b1b..03deedbe 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -17,7 +17,10 @@ Schema-first discriminator getters use lowerCamelCase. * **Breaking:** Generate lowerCamelCase Dart fields from schema-first JSON - keys. Wire keys keep their original spelling. + keys. One naming rule handles field names, discriminator getters, and inline + JSON Schema type names. For example, `UserID` maps to `userId`, `URLs` maps + to `urls`, and punctuation separates words. Generation rejects invalid or + colliding Dart names. Wire keys keep their original spelling. * **Breaking:** Generated helpers and nested fields enforce class-owned schema refinements (#263). diff --git a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart index 6d9dcb73..d53a229d 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart @@ -63,31 +63,29 @@ String? ackSchemaFirstFieldNameProblem( return null; } +final _wordBoundary = RegExp( + r'[^A-Za-z0-9]+|(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])(?![A-Z]s(?![a-z]))', +); + +// The last alternative splits HTTPServer before Server while keeping a plural +// acronym such as URLs together. +Iterable _words(String key) => + key.split(_wordBoundary).where((word) => word.isNotEmpty); + +String _upperInitial(String word) => + '${word[0].toUpperCase()}${word.substring(1)}'; + /// UpperCamelCase segment for a generated model name derived from a key. -String ackSchemaFirstTypeNameSegment(String key) => key - .split(RegExp(r'[^A-Za-z0-9]+')) - .where((segment) => segment.isNotEmpty) - .map((segment) => '${segment[0].toUpperCase()}${segment.substring(1)}') - .join(); +String ackSchemaFirstTypeNameSegment(String key) => + _words(key).map(_upperInitial).join(); /// Dart field name for a schema-first wire key. String ackSchemaFirstDartFieldName(String key) { - final words = key.split(RegExp(r'[_-]+')).where((word) => word.isNotEmpty); + final words = _words(key).map((word) => word.toLowerCase()); if (words.isEmpty) return ''; - - String lowerInitial(String word) => word.replaceFirstMapped( - RegExp(r'^[A-Z]+(?=[A-Z][a-z]|[^A-Za-z]|$)|^[A-Z]'), - (match) => match[0]!.toLowerCase(), - ); - - final first = lowerInitial(words.first); - final rest = words.skip(1).map((word) { - final normalized = lowerInitial(word); - return '${normalized[0].toUpperCase()}${normalized.substring(1)}'; - }); - return first + rest.join(); + return words.first + words.skip(1).map(_upperInitial).join(); } /// Dart getter name corresponding to a schema-first union's wire discriminator. String ackSchemaFirstDiscriminatorName(String key) => - ackSchemaFirstDartFieldName(key.replaceFirst(RegExp(r'^@+'), '')); + ackSchemaFirstDartFieldName(key); diff --git a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart index 15ab97c2..72f4324f 100644 --- a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart @@ -736,9 +736,13 @@ void main() { } }); - test('toString keeps dollar signs in field names literal', () { - final names = DollarNames.parse({r'$id': 'a', r'cost$usd': 2}); - expect(names.toString(), r'DollarNames($id: a, cost$usd: 2)'); + test('dollar signs separate Dart words and round-trip on the wire', () { + const json = {r'$id': 'a', r'cost$usd': 2}; + final names = DollarNames.parse(json); + expect(names.id, 'a'); + expect(names.costUsd, 2); + expect(names.toString(), 'DollarNames(id: a, costUsd: 2)'); + expect(names.toJson(), json); }); test('constructor snapshots Object-valued option maps without validating them', () { diff --git a/packages/ack_generator/test/src/schema_first_names_test.dart b/packages/ack_generator/test/src/schema_first_names_test.dart index ccff92c6..4ebf64b1 100644 --- a/packages/ack_generator/test/src/schema_first_names_test.dart +++ b/packages/ack_generator/test/src/schema_first_names_test.dart @@ -4,6 +4,56 @@ import 'package:analyzer/dart/ast/token.dart'; import 'package:test/test.dart'; void main() { + const names = [ + ('ID', 'id', 'ID'), + ('UserID', 'userId', 'UserID'), + ('HTTPServer', 'httpServer', 'HTTPServer'), + ('URLs', 'urls', 'URLs'), + ('URLsParser', 'urlsParser', 'URLsParser'), + ('api_URL', 'apiUrl', 'ApiURL'), + ('address_2', 'address2', 'Address2'), + ('user.id', 'userId', 'UserId'), + ('x_1_2', 'x12', 'X12'), + ('x_12', 'x12', 'X12'), + ('Name', 'name', 'Name'), + ('name', 'name', 'Name'), + ('_id', 'id', 'Id'), + ('id', 'id', 'Id'), + (r'$id', 'id', 'Id'), + (r'cost$usd', 'costUsd', 'CostUsd'), + ('@type', 'type', 'Type'), + ('@HTTPStatus', 'httpStatus', 'HTTPStatus'), + ('1st_place', '1stPlace', '1stPlace'), + ('123', '123', '123'), + ('naïve_name', 'naVeName', 'NaVeName'), + ('東京', '', ''), + ('Default', 'default', 'Default'), + ('_class', 'class', 'Class'), + ]; + for (final (key, field, type) in names) { + test('uses one naming rule for wire key "$key"', () { + expect(ackSchemaFirstDartFieldName(key), field); + expect(ackSchemaFirstDiscriminatorName(key), field); + expect(ackSchemaFirstTypeNameSegment(key), type); + }); + } + + test( + 'rejects empty, digit-led, and reserved field names after conversion', + () { + for (final key in ['東京', '123', '1st_place', 'Default', '_class']) { + expect( + ackSchemaFirstFieldNameProblem( + ackSchemaFirstDartFieldName(key), + capturesExtras: false, + ), + isNotNull, + reason: key, + ); + } + }, + ); + test('member checks distinguish keywords from generated type collisions', () { for (final entry in Keyword.keywords.entries) { if (entry.value.isReservedWord) continue; From ef694e4e8da458a50853e5e275122c790f73fcb4 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 18:01:14 +0000 Subject: [PATCH 36/57] docs(generator): correct refinement and migration guidance --- docs/getting-started/migration-guide.mdx | 12 ++++++------ packages/ack_generator/CHANGELOG.md | 1 + .../integration/ack_infer_runtime_build_test.dart | 3 +++ .../ack/skills/build-data-classes-with-ack/SKILL.md | 5 ++--- 4 files changed, 12 insertions(+), 9 deletions(-) diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 9b008286..f2876379 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -13,6 +13,11 @@ This guide summarizes **what exists in Ack today**, **what changed in 1.7 and 2. | A custom static `schema` on a class-first sealed union base or branch | `2.0.0` | Expose the generated facade's `schema` directly. Apply custom validation at the union level or use a non-union model. | | Schema-first keys that shadow a generated reference, such as `override` or `identical` | `2.0.0` | Use a class-first model with `@AckKey` to preserve the wire key and give the Dart field a different name. | | Schema-first keys and discriminators that generate different Dart names in 2.0 | `2.0.0` | Regenerate and update Dart callers. Keys that worked in beta.3 can now fail if they map to a reserved word such as `Default` → `default` or collide with another key. Use a class-first model with `@AckKey` for those keys. | +| Implicit field style on an annotated branch of a styled sealed class | `2.0.0` | Regenerate to inherit the base’s style. Use `caseStyle: AckCaseStyle.none` on the branch to retain Dart names on the wire. | +| Class-owned schema refinements | `2.0.0` | Generated helpers and nested fields now enforce them. Compose `ModelSchema.schema` explicitly when you need the raw generated rules. | +| Schema-first fields using snake_case or another wire spelling | `2.0.0` | Regenerate and use the lowerCamelCase Dart names in field accesses, constructors and `copyWith`. JSON keys keep their original spelling. | +| The direct `ackModelBuilder` factory | `2.0.0` | Use the shared `ack_generator:ack_generator` builder with source_gen’s combining builder. | +| Generated `Set` fields that previously accepted duplicate JSON items | `2.0.0` | Remove duplicates or use `List` when duplicates must be accepted. Exported schemas now include `uniqueItems: true` for these fields. | ## Beta.2 to beta.3: `Is…`/`Has…` rule annotations @@ -96,10 +101,6 @@ Ack is organized into five coordinated packages that share one version number an | **`Is…`/`Has…` rule annotations** | `2.0.0-beta.3` | Field and parameter rules—presence (`@IsRequired()`, `@IsOptional()`), nullability (`@IsNotNull()`), bounds (`@HasMin(0)`), formats (`@IsEmail()`, `@IsDateTime()`, `@IsUri()`), and collection rules (`@IsNotEmpty()`, `@HasUniqueItems()`)—are top-level classes in `package:ack/ack.dart`. The 2.0 beta `Validate` namespace is deprecated and is removed before Ack 2.0.0. | Top-level 1.x classes (`@Required`, `@Email`, `@Uuid`, `@Date`, `@Uri`, `@DateTime`, `@Pattern`) collided with `package:meta` / Flutter (`Required`), `dart:core` (`Uri`, `DateTime`, `Pattern`), and `package:uuid`, forcing import prefixes (`as ack`). The beta `Validate` namespace avoided that with a prefix on every use. The `Is…`/`Has…` names need neither: none of them collides with the Dart SDK, Flutter, or common packages. | | **Single `.g.dart` part & direct JSON emitter** | `2.0.0` | `ack_generator:ack_generator` is a `SharedPartBuilder` that emits `.g.dart` directly with no `json_serializable` or `json_annotation` dependency. | In 1.x, every model required two `part` directives (`.ack.dart` + `.ack.g.dart`) and a second `json_serializable` pass. Direct emission cuts build steps in half, uses standard `part '.g.dart';`, and coexists with Freezed or Riverpod in the same file. | | **Layered custom schema resolution (`T.schema`, `schemas: [...]`)** | `1.7.0` / `2.0.0` | Custom field types resolve via `@Schemable(schemas: [...])` (on classes, unions, or `library;` directives), type-owned `T.schema` / `T.schema()` factories, or automatic detection of a unique top-level `AckSchema` in the current library. | Removed per-field `@AckField(schema: ...)` boilerplate on every field that uses a domain value object, extension type, enum, or generic wrapper. | -| Implicit field style on an annotated branch of a styled sealed class | `2.0.0` | Regenerate to inherit the base’s style. Use `caseStyle: AckCaseStyle.none` on the branch to retain Dart names on the wire. | -| Class-owned schema refinements | `2.0.0` | Generated helpers and nested fields now enforce them. Compose `ModelSchema.schema` explicitly when you need the raw generated rules. | -| Schema-first fields using snake_case or another wire spelling | `2.0.0` | Regenerate and use the lowerCamelCase Dart names in field accesses, constructors and `copyWith`. JSON keys keep their original spelling. | -| The direct `ackModelBuilder` factory | `2.0.0` | Use the shared `ack_generator:ack_generator` builder with source_gen’s combining builder. | | **Typed `$ClassCopyWith` getter** | `1.7.0` | `model.copyWith` returns a typed callable interface instead of widening parameters to `Object?`. | Passing `model.copyWith(age: 'wrong')` previously compiled and failed only at runtime (`TypeError`). Now mistyped arguments fail at compile time while `model.copyWith(age: null)` still clears nullable fields. | | **Two-way string normalizers (`.trim()`, `.toLowerCase()`, `.toUpperCase()`)** | `2.0.0` | Normalizers live directly on `StringSchema` and run in declaration order alongside constraints during both `parse` and `encode`. | In 1.x, `.trim()` used a one-way `.transform()`, which failed on `encode()`, was rejected by `@Schemable()`, and emitted `'x-transformed': true` in JSON Schema. | | **`JsonMaybe` (`JsonAbsent` / `JsonValue`)** | `2.0.0` | Tri-state field container for class-first `@Schemable()` models. | A plain `String?` field in Dart cannot distinguish `{"bio": null}` (clear field in a `PATCH` request) from `{}` (leave field unchanged) when encoding back to JSON. | @@ -138,8 +139,7 @@ Ack is organized into five coordinated packages that share one version number an Schema-first union discriminator getters use the same lowerCamelCase naming as other fields. A class-first union emits one discriminator wire key, even when -a branch field uses a different case style. Generated `Set` fields reject -duplicate JSON values. Use `List` when duplicates must be accepted. +a branch field uses a different case style. ### Validation Annotations diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 03deedbe..1a846177 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -13,6 +13,7 @@ generator's old direct `ackModelBuilder` export. * **Breaking:** Generated `Set` fields reject duplicate JSON values. + Their exported JSON Schemas include `uniqueItems: true`. * **Breaking:** A stored discriminator uses its configured JSON key once. Schema-first discriminator getters use lowerCamelCase. diff --git a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart index 72f4324f..dbaf03c8 100644 --- a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart @@ -704,6 +704,9 @@ void main() { test('an unconstrained Set rejects duplicate wire values', () { expect(UniqueTagsSchema.safeParse({'tags': ['x', 'x']}).isFail, isTrue); expect(UniqueTagsSchema.safeParse({'tags': ['x', 'y']}).isOk, isTrue); + final properties = + UniqueTagsSchema.toJsonSchema()['properties'] as Map; + expect(properties['tags'], containsPair('uniqueItems', true)); }); test('schema-first JSON keys keep their wire spelling', () { diff --git a/plugins/ack/skills/build-data-classes-with-ack/SKILL.md b/plugins/ack/skills/build-data-classes-with-ack/SKILL.md index 95ee0eb8..8aa2a74a 100644 --- a/plugins/ack/skills/build-data-classes-with-ack/SKILL.md +++ b/plugins/ack/skills/build-data-classes-with-ack/SKILL.md @@ -66,9 +66,8 @@ Run `dart run build_runner build`. For a class-first model the build writes `.value(null)` (explicit `null` on the wire). - `copyWith(notes: null)` clears a nullable field; leaving the argument out keeps it. - Compose: `Ack.list(Invoice.schema)`, or a field typed `Invoice` inside another `@Schemable` class. From 552fd62639ec811b4137af2f6d473f51f47eca2c Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 18:01:34 +0000 Subject: [PATCH 37/57] test(generator): cover wire keys, field names, and union diagnostics --- .../ack_infer_runtime_build_test.dart | 32 +++++++++++++++++-- .../class_first_runtime_build_test.dart | 22 +++++++++++++ 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart index dbaf03c8..e2e92e2a 100644 --- a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart @@ -386,7 +386,7 @@ final wireNamesSchema = Ack.object({ 'first_name': Ack.string(), 'user-id': Ack.integer(), '_nickname': Ack.string(), -}); +}).passthrough(); @Schemable() final scopedNamesSchema = Ack.object({ @@ -709,12 +709,18 @@ void main() { expect(properties['tags'], containsPair('uniqueItems', true)); }); - test('schema-first JSON keys keep their wire spelling', () { - const json = {'first_name': 'Ada', 'user-id': 7, '_nickname': 'A'}; + test('passthrough excludes declared wire keys from additional properties', () { + const json = { + 'first_name': 'Ada', + 'user-id': 7, + '_nickname': 'A', + 'firstName': 'an extra key', + }; final model = WireNames.parse(json); expect(model.firstName, 'Ada'); expect(model.userId, 7); expect(model.nickname, 'A'); + expect(model.additionalProperties, {'firstName': 'an extra key'}); expect(model.toJson(), json); }); @@ -1377,6 +1383,26 @@ Extras misuse(Extras extras) => extras.copyWith(nickname: const Object()); p.relative(file.path, from: temporary.path): file.readAsStringSync(), }; expect(rebuilt, generated); + + File(p.join(temporary.path, 'lib', 'missing_annotation.dart')) + .writeAsStringSync(''' +import 'package:ack/ack.dart'; + +part 'missing_annotation.g.dart'; + +final branchSchema = Ack.object({'name': Ack.string()}); + +@Schemable() +final unionSchema = Ack.discriminated( + discriminatorKey: 'kind', + schemas: {'branch': branchSchema}, +); +'''); + final rejected = await _run(temporary, ['run', 'build_runner', 'build']); + final diagnostics = '${rejected.stdout}\n${rejected.stderr}'; + expect(rejected.exitCode, isNot(0), reason: diagnostics); + expect(diagnostics, contains('unionSchema.branch')); + expect(diagnostics, contains('annotated with @Schemable()')); } finally { temporary.deleteSync(recursive: true); } diff --git a/packages/ack_generator/test/integration/class_first_runtime_build_test.dart b/packages/ack_generator/test/integration/class_first_runtime_build_test.dart index 83fb1627..035df9a9 100644 --- a/packages/ack_generator/test/integration/class_first_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/class_first_runtime_build_test.dart @@ -472,6 +472,19 @@ final class DollarNames with _$DollarNamesAck { final int cost$usd; } +@Schemable() +final class ScopedFields with _$ScopedFieldsAck { + const ScopedFields({ + required this.other, + required this.value, + required this.model, + }); + + final String other; + final int value; + final bool model; +} + @Schemable() final class OptionalCollections with _$OptionalCollectionsAck { const OptionalCollections({this.headers, this.aliases, this.tags}); @@ -1177,6 +1190,15 @@ void main() { expect(names.toString(), r'DollarNames($id: a, cost$usd: 2)'); }); + test('class-first fields named other, value, and model round-trip', () { + const json = {'other': 'text', 'value': 4, 'model': true}; + final fields = ScopedFieldsSchema.parse(json); + expect(fields, const ScopedFields(other: 'text', value: 4, model: true)); + expect(fields.toJson(), json); + expect(fields.copyWith(value: 7).toJson(), {...json, 'value': 7}); + expect(fields.toString(), 'ScopedFields(other: text, value: 4, model: true)'); + }); + test('optional collections round-trip through null-aware bridges', () { final empty = OptionalCollectionsSchema.parse({}); expect(empty.headers, isNull); From f6c5f7b1a7415661b7adb4d7aecc7eca3cb04601 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 18:03:17 +0000 Subject: [PATCH 38/57] fix(generator): resolve union schema aliases in clean builds --- docs/core-concepts/typesafe-schemas.mdx | 2 +- .../lib/src/analyzer/class_model_graph_builder.dart | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index ab491e96..bb971008 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -578,7 +578,7 @@ raw generated schema when declaring `Model.schema` with refinements. ### Class-first unions The sealed base and its branches may expose a static `schema` only as a -direct alias of their generated facade's `schema`, such as +read-only alias of their generated facade's `schema`, such as `static final schema = PetSchema.schema;`. Apply custom validation to the union schema where you use it, or use a non-union model for a class-owned schema with refinements. diff --git a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart index 1e5dfa26..981fa110 100644 --- a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart @@ -267,8 +267,9 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { propertyDeclaration(member), ); if (member is GetterElement && + element.getSetter('schema')?.isStatic != true && expression?.unParenthesized.toSource() == facadeSchema) { - _validateStaticSchema(element); + // The facade in a clean build has no resolved type yet. return; } From 9b2611482f1d04f329bf244b59a0753b05d0284b Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 18:04:51 +0000 Subject: [PATCH 39/57] fix(generator): use a null-aware prefix set element --- .../lib/src/analyzer/schema_model_graph_builder.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart index a71840e7..110a1bf4 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart @@ -1326,7 +1326,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { if (declaration == null) continue; final references = { - if (ackPrefix case final prefix?) prefix, + ?ackPrefix, (_unionOwnerByBranch[node.id] ?? node.id).declarationName, if (node is AckObjectModelNode) for (final field in node.fields) ..._typeReferences(field.runtimeRef), From e70c6059988730254d2c74d8f7f8d6be552d568a Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 18:06:10 +0000 Subject: [PATCH 40/57] chore(example): regenerate class-first runtime helpers --- example/lib/class_first_models.g.dart | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/example/lib/class_first_models.g.dart b/example/lib/class_first_models.g.dart index 79251892..977d3783 100644 --- a/example/lib/class_first_models.g.dart +++ b/example/lib/class_first_models.g.dart @@ -66,8 +66,8 @@ abstract final class CatSchema { AckSchemaModelExtension(_catSchema).toSchemaModel(); } -Cat _$CatFromRuntime(Map value) => - Cat(id: value['id'] as String, lives: value['lives'] as int); +Cat _$CatFromRuntime(Map $ackValue) => + Cat(id: $ackValue['id'] as String, lives: $ackValue['lives'] as int); Map _$CatToRuntime(Cat model) => { 'id': model.id, @@ -192,8 +192,8 @@ abstract final class DogSchema { AckSchemaModelExtension(_dogSchema).toSchemaModel(); } -Dog _$DogFromRuntime(Map value) => - Dog(id: value['id'] as String, breed: value['breed'] as String); +Dog _$DogFromRuntime(Map $ackValue) => + Dog(id: $ackValue['id'] as String, breed: $ackValue['breed'] as String); Map _$DogToRuntime(Dog model) => { 'id': model.id, @@ -401,10 +401,10 @@ abstract final class AccountSchema { AckSchemaModelExtension(_accountSchema).toSchemaModel(); } -Account _$AccountFromRuntime(Map value) => Account( - displayName: value['display_name'] as String, - website: value['website'] as Uri?, - role: value['role'] as String? ?? 'member', +Account _$AccountFromRuntime(Map $ackValue) => Account( + displayName: $ackValue['display_name'] as String, + website: $ackValue['website'] as Uri?, + role: $ackValue['role'] as String? ?? 'member', ); Map _$AccountToRuntime(Account model) => { From 7e7b3a58e8468cbc584cd5819222b3e79d5c129f Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 18:07:08 +0000 Subject: [PATCH 41/57] fix(generator): show the missing union annotation hint in builds --- packages/ack_generator/CHANGELOG.md | 3 ++- .../lib/src/analyzer/schema_model_graph_builder.dart | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 1a846177..67de6aa0 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -34,7 +34,8 @@ * Keep generated class-first runtime locals from capturing identifiers used by constructor defaults. -* Suggest `@Schemable()` when a union branch cannot resolve to a model. +* Suggest `@Schemable()` in the build error when a union branch cannot resolve + to a model. * Document JSON converters for Ack model fields in json_serializable classes. * Report invalid rule arguments on the annotated field, including non-integer diff --git a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart index 110a1bf4..9d255c87 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart @@ -467,9 +467,9 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { final target = _localDeclaration(element.value); if (target == null) { throw InvalidGenerationSource( - '$path.$value is a cross-library or unresolvable discriminated branch.', + '$path.$value is a cross-library or unresolvable discriminated branch. ' + 'Reference a same-library object schema annotated with @Schemable().', element: declaration.element, - todo: 'Reference a same-library object schema annotated with @Schemable().', ); } _validateUnionBranchDiscriminator(target, discriminatorKey, value); From 568440be6c03a870a0a971d62f8d2a09cfc09476 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 18:16:04 +0000 Subject: [PATCH 42/57] refactor(ack)!: make constraint attachment helpers internal --- docs/api-reference/index.mdx | 6 ++++-- docs/getting-started/migration-guide.mdx | 1 + packages/ack/CHANGELOG.md | 4 ++++ packages/ack/lib/src/schemas/fluent_schema.dart | 2 ++ packages/ack/lib/src/schemas/schema.dart | 2 ++ .../fixtures/public_api/internal_helpers.dart.txt | 12 ++++++++++++ .../ack/test/json_schema_import_public_api_test.dart | 6 ++++++ 7 files changed, 31 insertions(+), 2 deletions(-) diff --git a/docs/api-reference/index.mdx b/docs/api-reference/index.mdx index 9352bc5b..c506ad6f 100644 --- a/docs/api-reference/index.mdx +++ b/docs/api-reference/index.mdx @@ -113,8 +113,10 @@ For non-`num` boundary types (e.g. numeric strings), use ### Custom Validation Methods -- `AckSchema constrain(Constraint constraint, {String? message})`: Adds a constraint and optionally overrides its message. The constraint must mix in `Validator`, or an `ArgumentError` is thrown. -- `AckSchema withConstraint(Constraint constraint)`: Adds a constraint directly (no message override; `constrain` delegates here). +- `AckSchema constrain(Constraint constraint, {String? message})` + adds a custom constraint and optionally overrides its error message. The + constraint must mix in `Validator`, or `constrain` throws an + `ArgumentError`. Chain `constrain` calls to attach multiple constraints. - `AckSchema refine(bool Function(Runtime) validate, {String message = 'The value did not pass the custom validation.'})`: Adds a custom validation predicate with an optional error message. - `CodecSchema transform(R Function(Runtime) transformer)`: Transforms validated runtime values to `R` (parse-only; encode fails). diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 487d4c39..f5fddb31 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -184,6 +184,7 @@ and errors: | `1.x` Item | Changed In | Exact `2.0` Substitution | | --- | --- | --- | | `AckSchemaModel.withJsonSchemaKeywords` | `2.0.0` | The method remains callable and is marked `@internal`. External calls produce an analyzer warning. Render with `toJsonSchema()` and apply custom keywords to the resulting map. | +| `withConstraint(c)` or `withConstraints([a, b])` | `2.0.0` | Use `constrain(c)` or chain `constrain(a).constrain(b)`. Both former methods are marked `@internal`. | --- diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 3b0d1c06..99b64316 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -2,6 +2,10 @@ ### Breaking +* **Breaking:** Use `constrain(constraint)` to attach a custom constraint. + `withConstraint` and `withConstraints` are now marked `@internal`. + Chain `constrain` calls to attach multiple constraints. + * **Breaking:** Replace `StringSchema.url()` with `uri()`, and `@IsUrl()` with `@IsUri()`. URI validation and JSON Schema output are unchanged. diff --git a/packages/ack/lib/src/schemas/fluent_schema.dart b/packages/ack/lib/src/schemas/fluent_schema.dart index bc37e0cd..05624c86 100644 --- a/packages/ack/lib/src/schemas/fluent_schema.dart +++ b/packages/ack/lib/src/schemas/fluent_schema.dart @@ -55,11 +55,13 @@ mixin FluentSchema< Schema describe(String description) => copyWith(description: description); /// Adds a validation constraint to the schema. + @internal @override Schema withConstraint(Constraint constraint) => copyWith(constraints: [...constraints, constraint]); /// Adds a list of validation constraints to the schema. + @internal @override Schema withConstraints(List> newConstraints) => copyWith(constraints: [...constraints, ...newConstraints]); diff --git a/packages/ack/lib/src/schemas/schema.dart b/packages/ack/lib/src/schemas/schema.dart index 539b7c74..c22e4191 100644 --- a/packages/ack/lib/src/schemas/schema.dart +++ b/packages/ack/lib/src/schemas/schema.dart @@ -362,11 +362,13 @@ sealed class AckSchema { } /// Adds a validation constraint to the schema. + @internal AckSchema withConstraint(Constraint constraint) { return withRuntimeConfig(constraints: [...constraints, constraint]); } /// Adds validation constraints to the schema. + @internal AckSchema withConstraints( List> newConstraints, ) { diff --git a/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt b/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt index 11016baf..d035d94c 100644 --- a/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt +++ b/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt @@ -1,5 +1,17 @@ import 'package:ack/ack.dart'; +void checkConstraints( + StringSchema schema, + AckSchema base, + Constraint constraint, +) { + schema.constrain(constraint, message: 'Invalid value'); + schema.withConstraint(constraint); + schema.withConstraints([constraint]); + base.withConstraint(constraint); + base.withConstraints([constraint]); +} + void main() { final schema = Ack.string(); final parent = SchemaContext(name: 'root', schema: schema, value: 'value'); diff --git a/packages/ack/test/json_schema_import_public_api_test.dart b/packages/ack/test/json_schema_import_public_api_test.dart index 70a32194..1859adaf 100644 --- a/packages/ack/test/json_schema_import_public_api_test.dart +++ b/packages/ack/test/json_schema_import_public_api_test.dart @@ -102,6 +102,12 @@ void main() { for (final name in [ 'withJsonSchemaKeywords', 'SchemaContext.transparent', + // Calls through StringSchema reach the mixin declarations. + 'withConstraint', + 'withConstraints', + // Calls through AckSchema reach the base declarations. + 'withConstraint', + 'withConstraints', ]) allOf( contains('|INVALID_USE_OF_INTERNAL_MEMBER|'), From a3dfa0165262583ef8c03f132ebb7ff1ac9088d7 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 18:32:45 +0000 Subject: [PATCH 43/57] fix(generator): report invalid discriminators on the union --- .../lib/src/analyzer/schema_model_graph_builder.dart | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart index 9d255c87..948dd8bb 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart @@ -455,6 +455,18 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { ); } final discriminatorName = ackSchemaFirstDiscriminatorName(discriminatorKey); + final discriminatorProblem = ackSchemaFirstFieldNameProblem( + discriminatorName, + capturesExtras: true, + generatedReferences: {?ackPrefix, declaration.id.declarationName}, + ); + if (discriminatorProblem != null) { + throw InvalidGenerationSource( + '$path.$discriminatorKey $discriminatorProblem', + element: declaration.element, + ); + } + final branches = {}; for (final element in branchesLiteral.elements) { if (element is! MapLiteralEntry || element.key is! SimpleStringLiteral) { From 0d26441dfe47ed5a63a5ac1cc7faede11c68bd2b Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 18:34:55 +0000 Subject: [PATCH 44/57] fix(generator)!: express inherited case style through the public annotation --- docs/getting-started/migration-guide.mdx | 1 + packages/ack/CHANGELOG.md | 3 +++ packages/ack/lib/src/annotations/schemable.dart | 16 ++++++---------- .../ack/test/annotations/ack_model_test.dart | 7 ++++++- packages/ack_generator/CHANGELOG.md | 2 ++ .../src/analyzer/class_model_graph_builder.dart | 14 ++++---------- .../src/analyzer/schema_model_graph_builder.dart | 5 ++--- .../ack_generator/lib/src/model_generator.dart | 5 ++--- 8 files changed, 26 insertions(+), 27 deletions(-) diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index f2876379..80425a95 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -14,6 +14,7 @@ This guide summarizes **what exists in Ack today**, **what changed in 1.7 and 2. | Schema-first keys that shadow a generated reference, such as `override` or `identical` | `2.0.0` | Use a class-first model with `@AckKey` to preserve the wire key and give the Dart field a different name. | | Schema-first keys and discriminators that generate different Dart names in 2.0 | `2.0.0` | Regenerate and update Dart callers. Keys that worked in beta.3 can now fail if they map to a reserved word such as `Default` → `default` or collide with another key. Use a class-first model with `@AckKey` for those keys. | | Implicit field style on an annotated branch of a styled sealed class | `2.0.0` | Regenerate to inherit the base’s style. Use `caseStyle: AckCaseStyle.none` on the branch to retain Dart names on the wire. | +| Code that reads `Schemable.caseStyle` as non-null | `2.0.0` | Handle a null style as unspecified. Use `annotation.caseStyle ?? AckCaseStyle.none` when you need the standalone default. | | Class-owned schema refinements | `2.0.0` | Generated helpers and nested fields now enforce them. Compose `ModelSchema.schema` explicitly when you need the raw generated rules. | | Schema-first fields using snake_case or another wire spelling | `2.0.0` | Regenerate and use the lowerCamelCase Dart names in field accesses, constructors and `copyWith`. JSON keys keep their original spelling. | | The direct `ackModelBuilder` factory | `2.0.0` | Use the shared `ack_generator:ack_generator` builder with source_gen’s combining builder. | diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index b10d9735..e51f3d22 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -2,6 +2,9 @@ ### Breaking +* **Breaking:** `Schemable.caseStyle` is now an `AckCaseStyle?`. An omitted + style is null. Use `AckCaseStyle.none` for an explicit override. + * **Breaking:** Annotated union branches inherit the base case style when their own style is omitted. Use `AckCaseStyle.none` to keep Dart names. diff --git a/packages/ack/lib/src/annotations/schemable.dart b/packages/ack/lib/src/annotations/schemable.dart index fbdfe4fb..c0a16b67 100644 --- a/packages/ack/lib/src/annotations/schemable.dart +++ b/packages/ack/lib/src/annotations/schemable.dart @@ -38,14 +38,13 @@ final class Schemable { this.name, this.schemaName, this.description, - AckCaseStyle? caseStyle, + this.caseStyle, this.discriminatorKey, this.discriminatorValue, this.unknownProperties = AckUnknownPropertyPolicy.reject, this.captureField = 'additionalProperties', this.schemas, - }) : caseStyle = caseStyle ?? AckCaseStyle.none, - _caseStyleWasSet = caseStyle != null; + }); /// Exact generated model name for a top-level schema declaration. final String? name; @@ -61,13 +60,10 @@ final class Schemable { /// JSON field-name style for a class declaration. /// - /// An omitted style inherits the base style for a sealed union branch. - /// Use [AckCaseStyle.none] to keep the branch's Dart field names as-is. - final AckCaseStyle caseStyle; - - // The generator distinguishes omission from an explicit none override. - // ignore: unused_field - final bool _caseStyleWasSet; + /// A null style inherits the base style for a sealed union branch and uses + /// [AckCaseStyle.none] elsewhere. Set [AckCaseStyle.none] explicitly to keep + /// a branch's Dart field names as-is. + final AckCaseStyle? caseStyle; /// Discriminator key for a sealed class declaration. final String? discriminatorKey; diff --git a/packages/ack/test/annotations/ack_model_test.dart b/packages/ack/test/annotations/ack_model_test.dart index 798d7307..8692365f 100644 --- a/packages/ack/test/annotations/ack_model_test.dart +++ b/packages/ack/test/annotations/ack_model_test.dart @@ -8,7 +8,12 @@ void main() { const defaults = Schemable(); expect(defaults.name, isNull); expect(defaults.schemaName, isNull); - expect(defaults.caseStyle, AckCaseStyle.none); + expect(defaults.caseStyle, isNull); + expect(const Schemable(caseStyle: null).caseStyle, isNull); + expect( + const Schemable(caseStyle: AckCaseStyle.none).caseStyle, + AckCaseStyle.none, + ); expect(defaults.discriminatorKey, isNull); expect(defaults.discriminatorValue, isNull); expect(defaults.unknownProperties, AckUnknownPropertyPolicy.reject); diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 67de6aa0..7c6cb89e 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -28,6 +28,8 @@ * **Breaking:** Annotated union branches inherit the base case style when their own style is omitted. Use `AckCaseStyle.none` to keep Dart names. + The generator reads this distinction from the public nullable + `Schemable.caseStyle` option. ### Fixed diff --git a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart index 981fa110..8f400915 100644 --- a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart @@ -1422,19 +1422,13 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { .firstAnnotationOfExact(element); if (annotation == null) return null; final reader = ConstantReader(annotation); - final caseStyleWasSet = - annotation.getField('_caseStyleWasSet')?.toBoolValue() ?? true; - final caseIndex = reader - .read('caseStyle') - .objectValue - .getField('index')! - .toIntValue()!; + final caseIndex = reader.peek('caseStyle')?.read('index').intValue; return ( schemaName: _nullableString(reader, 'schemaName'), description: _nullableString(reader, 'description'), - caseStyle: caseStyleWasSet - ? annotations.AckCaseStyle.values[caseIndex] - : inheritedCaseStyle, + caseStyle: caseIndex == null + ? inheritedCaseStyle + : annotations.AckCaseStyle.values[caseIndex], discriminatorKey: _nullableString(reader, 'discriminatorKey'), discriminatorValue: _nullableString(reader, 'discriminatorValue'), unknownProperties: diff --git a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart index 948dd8bb..b258d9e5 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart @@ -134,12 +134,11 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { .firstAnnotationOfExact(propertyDeclaration(element)); if (annotation == null) return; final reader = ConstantReader(annotation); - int index(String option) => - reader.read(option).objectValue.getField('index')!.toIntValue()!; + int? index(String option) => reader.peek(option)?.read('index').intValue; final configured = [ if (!reader.read('schemaName').isNull) 'schemaName', if (!reader.read('description').isNull) 'description', - if (index('caseStyle') != 0) 'caseStyle', + if ((index('caseStyle') ?? 0) != 0) 'caseStyle', if (!reader.read('discriminatorKey').isNull) 'discriminatorKey', if (!reader.read('discriminatorValue').isNull) 'discriminatorValue', if (index('unknownProperties') != 0) 'unknownProperties', diff --git a/packages/ack_generator/lib/src/model_generator.dart b/packages/ack_generator/lib/src/model_generator.dart index cbedb1e2..bfd915c2 100644 --- a/packages/ack_generator/lib/src/model_generator.dart +++ b/packages/ack_generator/lib/src/model_generator.dart @@ -206,13 +206,12 @@ final class AckModelGenerator extends Generator { final annotation = _schemableChecker.firstAnnotationOfExact(libraryElement); if (annotation == null) return; final reader = ConstantReader(annotation); - int index(String option) => - reader.read(option).objectValue.getField('index')!.toIntValue()!; + int? index(String option) => reader.peek(option)?.read('index').intValue; final configured = [ if (!reader.read('name').isNull) 'name', if (!reader.read('schemaName').isNull) 'schemaName', if (!reader.read('description').isNull) 'description', - if (index('caseStyle') != 0) 'caseStyle', + if ((index('caseStyle') ?? 0) != 0) 'caseStyle', if (!reader.read('discriminatorKey').isNull) 'discriminatorKey', if (!reader.read('discriminatorValue').isNull) 'discriminatorValue', if (index('unknownProperties') != 0) 'unknownProperties', From 2cef326b2f64e00aef598e6441ee2f7a0e5fc5a6 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 18:36:57 +0000 Subject: [PATCH 45/57] fix(ack): expose the abstract generated field schema type --- packages/ack/CHANGELOG.md | 3 ++- packages/ack/lib/src/schemas/schema.dart | 7 +++---- .../test/schemas/generated_field_schema_test.dart | 14 +++++++++++--- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index e51f3d22..2401d388 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -18,7 +18,8 @@ ### Changed -* Support `AckSchema.forGeneratedField` as a generated-code entry point. +* Support `AckSchema.forGeneratedField` as a generated-code entry point + returning `AckSchema`. * Remove the `punycoder` and `unorm_dart` dependencies. Ack now has only `meta` and `collection` as runtime dependencies. Punycode conversion for diff --git a/packages/ack/lib/src/schemas/schema.dart b/packages/ack/lib/src/schemas/schema.dart index 6fe75bff..8a77b5bd 100644 --- a/packages/ack/lib/src/schemas/schema.dart +++ b/packages/ack/lib/src/schemas/schema.dart @@ -116,10 +116,9 @@ sealed class AckSchema { /// The field declaration supplies optionality, nullability and defaults. /// Non-null values retain the custom schema's validation and encoder. /// This entry point is supported for generated model code. - static CodecSchema forGeneratedField< - B extends Object, - R extends Object - >(AckSchema schema) => CodecSchema._( + static AckSchema forGeneratedField( + AckSchema schema, + ) => CodecSchema._( inputSchema: schema, outputSchema: schema, decoder: (value) => value as R, diff --git a/packages/ack/test/schemas/generated_field_schema_test.dart b/packages/ack/test/schemas/generated_field_schema_test.dart index 6d7b9c2a..622f9794 100644 --- a/packages/ack/test/schemas/generated_field_schema_test.dart +++ b/packages/ack/test/schemas/generated_field_schema_test.dart @@ -1,10 +1,18 @@ -// Generated parts use this helper across the package boundary. -// ignore_for_file: invalid_use_of_internal_member - import 'package:ack/ack.dart'; import 'package:test/test.dart'; +typedef _GeneratedFieldFactory = AckSchema Function( + AckSchema, +); + void main() { + test('the generated field factory exposes the abstract schema type', () { + expect( + AckSchema.forGeneratedField.runtimeType, + _GeneratedFieldFactory, + ); + }); + test('field policies replace custom presence while keeping the codec', () { final custom = Ack.string() .minLength(2) From e67856e0519ec357cfd86e6b960ba1aea8d03693 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 19:11:32 +0000 Subject: [PATCH 46/57] fix(generator)!: normalize digits and acronyms in generated names --- docs/core-concepts/typesafe-schemas.mdx | 28 ++++++++------- docs/getting-started/migration-guide.mdx | 2 +- packages/ack_generator/CHANGELOG.md | 6 ++-- .../lib/src/analyzer/schema_first_names.dart | 23 ++++++++---- .../analyzer/schema_model_graph_builder.dart | 14 +++++++- .../integration/ack_infer_graph_test.dart | 23 ++++++++++++ .../test/src/schema_first_names_test.dart | 35 +++++++++++++------ 7 files changed, 98 insertions(+), 33 deletions(-) diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index bb971008..9282666e 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -140,19 +140,21 @@ unresolved dynamic schema factories, and cross-library union branches. Schema-first JSON keys keep their spelling on the wire. Fields, discriminator getters, and inline JSON Schema model name segments use the same word boundaries. -The generator splits at characters other than ASCII letters and digits -(including `_`, `-`, `.`, `$`, `@`, and non-ASCII characters). It also -splits between a lowercase and an uppercase letter and before a capitalized -word following an acronym, as in `HTTPServer`. An uppercase run and its -optional plural `s` stay together. - -Fields and discriminator getters lowercase each word, capitalize words after -the first, and join them. For example, `UserID` becomes `userId`, `URLs` becomes -`urls`, `user.id` becomes `userId`, and `address_2` becomes `address2`. -Type name segments capitalize each word's first letter and preserve the -remaining letters, so `api_URL` contributes `ApiURL` to a type name. -Generation rejects empty names, names that start with a digit, Dart reserved -words such as `default`, and keys that produce the same Dart member. +The generator splits at punctuation, spaces, and other characters outside +ASCII letters and digits. It also starts a word at an uppercase letter after +a lowercase letter or digit, as in `ipv4Address` and `sha256Hash`, and before +a capitalized word following an acronym, as in `HTTPServer` and `URLIsValid`. +A plural acronym such as `URLs` stays together. + +Each word is lowercased, then capitalized where required by the target name. +Fields and discriminator getters leave the first word lowercase. Type name +segments capitalize it too. For example, `UserID`, `userID`, and `user_id` +all become `userId` as a field and `UserId` as a type name segment. `URLs` +becomes `urls` or `Urls`, and `address_2` becomes `address2` or `Address2`. +Generation rejects keys containing non-ASCII letters, such as `café` and +`já_ok`, as well as empty names, field names that start with a digit, Dart +reserved words, and keys that produce the same Dart member. Use a class-first +model with `@AckKey` to keep a key and choose its Dart field name. Field and discriminator names also cannot shadow identifiers used by the generated class. This includes `bool`, `double`, `dynamic`, `int`, `num`, diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 80425a95..587bf298 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -12,7 +12,7 @@ This guide summarizes **what exists in Ack today**, **what changed in 1.7 and 2. | --- | --- | --- | | A custom static `schema` on a class-first sealed union base or branch | `2.0.0` | Expose the generated facade's `schema` directly. Apply custom validation at the union level or use a non-union model. | | Schema-first keys that shadow a generated reference, such as `override` or `identical` | `2.0.0` | Use a class-first model with `@AckKey` to preserve the wire key and give the Dart field a different name. | -| Schema-first keys and discriminators that generate different Dart names in 2.0 | `2.0.0` | Regenerate and update Dart callers. Keys that worked in beta.3 can now fail if they map to a reserved word such as `Default` → `default` or collide with another key. Use a class-first model with `@AckKey` for those keys. | +| Schema-first fields, discriminators, and inline JSON Schema model names | `2.0.0` | Regenerate and update Dart callers. Digits before uppercase letters and acronym boundaries affect names such as `ipv4Address` and `urlIsValid`. Inline model segments normalize acronyms, for example `UserID` → `UserId`. Use a class-first model with `@AckKey` for keys containing non-ASCII letters, keys mapping to a reserved word such as `default`, and collisions. | | Implicit field style on an annotated branch of a styled sealed class | `2.0.0` | Regenerate to inherit the base’s style. Use `caseStyle: AckCaseStyle.none` on the branch to retain Dart names on the wire. | | Code that reads `Schemable.caseStyle` as non-null | `2.0.0` | Handle a null style as unspecified. Use `annotation.caseStyle ?? AckCaseStyle.none` when you need the standalone default. | | Class-owned schema refinements | `2.0.0` | Generated helpers and nested fields now enforce them. Compose `ModelSchema.schema` explicitly when you need the raw generated rules. | diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 7c6cb89e..bf7d55e7 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -20,8 +20,10 @@ * **Breaking:** Generate lowerCamelCase Dart fields from schema-first JSON keys. One naming rule handles field names, discriminator getters, and inline JSON Schema type names. For example, `UserID` maps to `userId`, `URLs` maps - to `urls`, and punctuation separates words. Generation rejects invalid or - colliding Dart names. Wire keys keep their original spelling. + to `urls`, and `ipv4Address` retains its case boundary. Inline type segments + normalize acronyms too, such as `UserID` to `UserId`. Generation rejects keys + containing non-ASCII letters and invalid or colliding Dart names. Wire keys + keep their original spelling. * **Breaking:** Generated helpers and nested fields enforce class-owned schema refinements (#263). diff --git a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart index d53a229d..28883605 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart @@ -63,14 +63,25 @@ String? ackSchemaFirstFieldNameProblem( return null; } +final _nonAsciiLetter = RegExp(r'(?![A-Za-z])\p{L}', unicode: true); + +/// Why a wire key cannot be converted to a schema-first Dart name. +String? ackSchemaFirstWireKeyProblem(String key) => + _nonAsciiLetter.hasMatch(key) + ? 'contains non-ASCII letters. Use a class-first model with @AckKey to ' + 'keep the wire key and choose its Dart name.' + : null; + final _wordBoundary = RegExp( - r'[^A-Za-z0-9]+|(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])(?![A-Z]s(?![a-z]))', + r'[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])|' + // Split HTTPServer and URLIsValid while keeping the plural s in URLs. + r'(?<=[A-Z])(?=[A-Z][a-z])(?![A-HJ-Z]s(?![a-z]))', ); -// The last alternative splits HTTPServer before Server while keeping a plural -// acronym such as URLs together. -Iterable _words(String key) => - key.split(_wordBoundary).where((word) => word.isNotEmpty); +Iterable _words(String key) => key + .split(_wordBoundary) + .where((word) => word.isNotEmpty) + .map((word) => word.toLowerCase()); String _upperInitial(String word) => '${word[0].toUpperCase()}${word.substring(1)}'; @@ -81,7 +92,7 @@ String ackSchemaFirstTypeNameSegment(String key) => /// Dart field name for a schema-first wire key. String ackSchemaFirstDartFieldName(String key) { - final words = _words(key).map((word) => word.toLowerCase()); + final words = _words(key); if (words.isEmpty) return ''; return words.first + words.skip(1).map(_upperInitial).join(); } diff --git a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart index b258d9e5..4c074d47 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart @@ -363,6 +363,13 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { ); } final jsonKey = (entry.key as SimpleStringLiteral).value; + final fieldPath = '$path.$jsonKey'; + if (ackSchemaFirstWireKeyProblem(jsonKey) case final problem?) { + throw InvalidGenerationSource( + '$fieldPath $problem', + element: declaration.element, + ); + } if (!declaredKeys.add(jsonKey)) { throw InvalidGenerationSource( '$path.$jsonKey is a duplicate object field. Declare each key once.', @@ -379,7 +386,6 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { ); } wireKeysByFieldName[dartName] = jsonKey; - final fieldPath = '$path.$jsonKey'; final fieldChain = parseSchemaChain(entry.value); final fieldMetadata = await _schemaMetadata( entry.value, @@ -453,6 +459,12 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { element: declaration.element, ); } + if (ackSchemaFirstWireKeyProblem(discriminatorKey) case final problem?) { + throw InvalidGenerationSource( + '$path.$discriminatorKey $problem', + element: declaration.element, + ); + } final discriminatorName = ackSchemaFirstDiscriminatorName(discriminatorKey); final discriminatorProblem = ackSchemaFirstFieldNameProblem( discriminatorName, diff --git a/packages/ack_generator/test/integration/ack_infer_graph_test.dart b/packages/ack_generator/test/integration/ack_infer_graph_test.dart index e2e3c4d0..ccce55ce 100644 --- a/packages/ack_generator/test/integration/ack_infer_graph_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_graph_test.dart @@ -412,6 +412,29 @@ final userSchema = Ack.object({'firstName': Ack.string()}); ); }); + test('rejects non-ASCII letters in schema-first wire names', () async { + for (final (key, declaration) in [ + ('café', "final modelSchema = Ack.object({'café': Ack.string()});"), + ( + 'já_ok', + "final modelSchema = Ack.discriminated(discriminatorKey: 'já_ok', " + "schemas: {'choice': choiceSchema});", + ), + ]) { + await _expectFailure( + ''' +$_head +@Schemable() +final choiceSchema = Ack.object({'name': Ack.string()}); + +@Schemable() +$declaration +''', + [key, 'non-ASCII letters', 'class-first model with @AckKey'], + ); + } + }); + test('rejects dynamic additionalProperties expressions', () async { await _expectFailure( ''' diff --git a/packages/ack_generator/test/src/schema_first_names_test.dart b/packages/ack_generator/test/src/schema_first_names_test.dart index 4ebf64b1..6a8ec165 100644 --- a/packages/ack_generator/test/src/schema_first_names_test.dart +++ b/packages/ack_generator/test/src/schema_first_names_test.dart @@ -5,12 +5,18 @@ import 'package:test/test.dart'; void main() { const names = [ - ('ID', 'id', 'ID'), - ('UserID', 'userId', 'UserID'), - ('HTTPServer', 'httpServer', 'HTTPServer'), - ('URLs', 'urls', 'URLs'), - ('URLsParser', 'urlsParser', 'URLsParser'), - ('api_URL', 'apiUrl', 'ApiURL'), + ('ID', 'id', 'Id'), + ('UserID', 'userId', 'UserId'), + ('userID', 'userId', 'UserId'), + ('user_id', 'userId', 'UserId'), + ('HTTPServer', 'httpServer', 'HttpServer'), + ('URLIsValid', 'urlIsValid', 'UrlIsValid'), + ('URLs', 'urls', 'Urls'), + ('URLsParser', 'urlsParser', 'UrlsParser'), + ('api_URL', 'apiUrl', 'ApiUrl'), + ('ipv4Address', 'ipv4Address', 'Ipv4Address'), + ('sha256Hash', 'sha256Hash', 'Sha256Hash'), + ('OAuth2Token', 'oAuth2Token', 'OAuth2Token'), ('address_2', 'address2', 'Address2'), ('user.id', 'userId', 'UserId'), ('x_1_2', 'x12', 'X12'), @@ -22,11 +28,9 @@ void main() { (r'$id', 'id', 'Id'), (r'cost$usd', 'costUsd', 'CostUsd'), ('@type', 'type', 'Type'), - ('@HTTPStatus', 'httpStatus', 'HTTPStatus'), + ('@HTTPStatus', 'httpStatus', 'HttpStatus'), ('1st_place', '1stPlace', '1stPlace'), ('123', '123', '123'), - ('naïve_name', 'naVeName', 'NaVeName'), - ('東京', '', ''), ('Default', 'default', 'Default'), ('_class', 'class', 'Class'), ]; @@ -38,10 +42,21 @@ void main() { }); } + test('rejects non-ASCII letters before splitting words', () { + for (final key in ['café', 'já_ok', 'naïve_name', '東京']) { + expect( + ackSchemaFirstWireKeyProblem(key), + allOf(contains('non-ASCII letters'), contains('@AckKey')), + reason: key, + ); + } + expect(ackSchemaFirstWireKeyProblem('😀_hello'), isNull); + }); + test( 'rejects empty, digit-led, and reserved field names after conversion', () { - for (final key in ['東京', '123', '1st_place', 'Default', '_class']) { + for (final key in ['123', '1st_place', 'Default', '_class']) { expect( ackSchemaFirstFieldNameProblem( ackSchemaFirstDartFieldName(key), From 3bd1d7acd7b8c912825037d51d988a8c2025f61c Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 19:11:48 +0000 Subject: [PATCH 47/57] fix(generator): preserve interpolated class-owned defaults --- packages/ack_generator/CHANGELOG.md | 1 + .../analyzer/class_model_graph_builder.dart | 19 +++++++----- .../integration/class_model_emitter_test.dart | 29 +++++++++++++++++++ 3 files changed, 41 insertions(+), 8 deletions(-) diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index bf7d55e7..48ef1676 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -48,6 +48,7 @@ * Derive UpperCamelCase model names for inline objects under snake_case keys. * Qualify references to class statics in generated constructor defaults. +* Preserve short string interpolations when qualifying constructor defaults. * Preserve constructor defaults inherited through super parameters, including defaults that refer to statics on the declaring class. diff --git a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart index 8f400915..f367abec 100644 --- a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart @@ -1394,19 +1394,22 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { final visitor = _ClassStaticReferences(owner); value.accept(visitor); - if (visitor.offsets.isEmpty) return original; + if (visitor.references.isEmpty) return original; final visibleOwner = visibleTypeNameFor( owner.thisType, path: '${owner.name}.${source.name}', context: parameter, ); var qualified = content.substring(value.offset, value.end); - for (final offset in visitor.offsets.reversed) { - final relative = offset - value.offset; + for (final reference in visitor.references.reversed) { + final qualifiedName = '$visibleOwner.${reference.name}'; + final parent = reference.parent; qualified = qualified.replaceRange( - relative, - relative, - '$visibleOwner.', + reference.offset - value.offset, + reference.end - value.offset, + parent is InterpolationExpression && parent.rightBracket == null + ? '{$qualifiedName}' + : qualifiedName, ); } return qualified; @@ -1591,7 +1594,7 @@ final class _ClassStaticReferences extends RecursiveAstVisitor { _ClassStaticReferences(this.owner); final ClassElement owner; - final offsets = []; + final references = []; @override void visitSimpleIdentifier(SimpleIdentifier node) { @@ -1609,6 +1612,6 @@ final class _ClassStaticReferences extends RecursiveAstVisitor { identical(parent.methodName, node)) { return; } - offsets.add(node.offset); + references.add(node); } } diff --git a/packages/ack_generator/test/integration/class_model_emitter_test.dart b/packages/ack_generator/test/integration/class_model_emitter_test.dart index 8749595b..5eb55af8 100644 --- a/packages/ack_generator/test/integration/class_model_emitter_test.dart +++ b/packages/ack_generator/test/integration/class_model_emitter_test.dart @@ -41,6 +41,35 @@ import 'package:ack/annotations.dart'; '''; void main() { + test( + 'braces qualified class statics in constructor default interpolation', + () async { + await _build( + { + 'tag.dart': r''' +import 'package:ack/ack.dart'; +part 'tag.g.dart'; + +@Schemable() +final class Tag with _$TagAck { + static const prefix = 'p'; + const Tag({this.label = '$prefix-x'}); + final String label; +} +''', + }, + outputs: { + 'test_pkg|lib/tag.g.dart': decodedMatches( + allOf([ + _containsCode(r""".withDefault('${Tag.prefix}-x')"""), + _containsCode(r"""?? '${Tag.prefix}-x'"""), + ]), + ), + }, + ); + }, + ); + test( 'prefixed constraint annotations sit beside same-named app types', () async { From 46be36b54b7959fddd2ff81ef521050b594a2eef Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 19:12:07 +0000 Subject: [PATCH 48/57] refactor(ack)!: restrict schema context implementations --- docs/getting-started/migration-guide.mdx | 2 ++ packages/ack/CHANGELOG.md | 3 +++ packages/ack/lib/src/context.dart | 3 ++- .../public_api/context_implementation_rejected.dart.txt | 9 +++++++++ .../test/fixtures/public_api/internal_helpers.dart.txt | 1 + .../ack/test/json_schema_import_public_api_test.dart | 7 +++++++ 6 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 packages/ack/test/fixtures/public_api/context_implementation_rejected.dart.txt diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index f5fddb31..39a6c0dd 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -172,6 +172,7 @@ and errors: | `StringSchema.url()` | `2.0.0` | Use `StringSchema.uri()` for the same validation and schema export. | | Code matching a dotted built-in constraint key | `2.0.0` | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique_items`, `number.isFinite` → `number_finite`, `integer.isSafe` → `number_safe_integer`. | | `AckRule` from `package:ack/annotations.dart` | `2.0.0` | Use the concrete rule annotation type for rule-specific data, or `Object` for a mixed list. | +| `implements SchemaContext` | `2.0.0` | Read the context from `SchemaError.context`. `SchemaContext` is a `base` class, so external subclasses require a `base`, `final`, or `sealed` modifier. | | `AckSchemaModel.finishTypeJson` or `AckSchemaModel.finishCompositionJson` | `2.0.0` | Render the public model with `toJsonSchema()` and apply any custom JSON Schema keywords to the resulting map. | | `schema.toMap()` | `2.0.0` | `schema.toJsonSchema()` or `schema.toSchemaModel()` | | `server.registerAckModelTool(...)` (`ack_mcp_dart`) | `2.0.0` | `server.registerAckTool(name, input: Model.schema, callback: ...)`; return a `CallToolResult` from the callback | @@ -184,6 +185,7 @@ and errors: | `1.x` Item | Changed In | Exact `2.0` Substitution | | --- | --- | --- | | `AckSchemaModel.withJsonSchemaKeywords` | `2.0.0` | The method remains callable and is marked `@internal`. External calls produce an analyzer warning. Render with `toJsonSchema()` and apply custom keywords to the resulting map. | +| `SchemaContext.createChild` | `2.0.0` | Use the nested error's `context` to inspect its value and path. Ack creates child contexts during validation. | | `withConstraint(c)` or `withConstraints([a, b])` | `2.0.0` | Use `constrain(c)` or chain `constrain(a).constrain(b)`. Both former methods are marked `@internal`. | --- diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 99b64316..1cfe817d 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -2,6 +2,9 @@ ### Breaking +* **Breaking:** `SchemaContext` is a `base` class and `createChild` is internal. + Read the context from `SchemaError.context` when handling validation errors. + * **Breaking:** Use `constrain(constraint)` to attach a custom constraint. `withConstraint` and `withConstraints` are now marked `@internal`. Chain `constrain` calls to attach multiple constraints. diff --git a/packages/ack/lib/src/context.dart b/packages/ack/lib/src/context.dart index 8d042503..cb11d9fb 100644 --- a/packages/ack/lib/src/context.dart +++ b/packages/ack/lib/src/context.dart @@ -4,7 +4,7 @@ import 'schemas/schema.dart'; /// Represents the context in which a schema operation is occurring. @immutable -class SchemaContext { +base class SchemaContext { final String name; final Object? value; final AnyAckSchema schema; @@ -63,6 +63,7 @@ class SchemaContext { /// Creates a child context for nested validation. /// /// The child inherits the parent's [operation] unless overridden. + @internal SchemaContext createChild({ required String name, required AnyAckSchema schema, diff --git a/packages/ack/test/fixtures/public_api/context_implementation_rejected.dart.txt b/packages/ack/test/fixtures/public_api/context_implementation_rejected.dart.txt new file mode 100644 index 00000000..2bcbccc5 --- /dev/null +++ b/packages/ack/test/fixtures/public_api/context_implementation_rejected.dart.txt @@ -0,0 +1,9 @@ +import 'package:ack/ack.dart'; + +final class ConsumerContext implements SchemaContext { + @override + dynamic noSuchMethod(Invocation invocation) => + super.noSuchMethod(invocation); +} + +void main() {} diff --git a/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt b/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt index d035d94c..89d200f6 100644 --- a/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt +++ b/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt @@ -15,6 +15,7 @@ void checkConstraints( void main() { final schema = Ack.string(); final parent = SchemaContext(name: 'root', schema: schema, value: 'value'); + parent.createChild(name: 'child', schema: schema, value: 'value'); schema.toSchemaModel().withJsonSchemaKeywords({'title': 'item'}); SchemaContext.transparent( name: 'item', diff --git a/packages/ack/test/json_schema_import_public_api_test.dart b/packages/ack/test/json_schema_import_public_api_test.dart index 1859adaf..4413be32 100644 --- a/packages/ack/test/json_schema_import_public_api_test.dart +++ b/packages/ack/test/json_schema_import_public_api_test.dart @@ -70,6 +70,12 @@ void main() { ); }); + test('consumers cannot implement SchemaContext', () async { + final result = await _compileFixture('context_implementation_rejected'); + expect(result.exitCode, isNot(0)); + expect(result.stderr, contains("can't be implemented outside")); + }); + test('context path plumbing is hidden from clients', () async { final result = await _compileFixture('transparent_context_hidden'); expect(result.exitCode, isNot(0)); @@ -102,6 +108,7 @@ void main() { for (final name in [ 'withJsonSchemaKeywords', 'SchemaContext.transparent', + 'createChild', // Calls through StringSchema reach the mixin declarations. 'withConstraint', 'withConstraints', From 990f8f8888e74ef67be47b279b84fe7301fd0e3a Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 19:13:40 +0000 Subject: [PATCH 49/57] fix(generator)!: resolve inherited defaults in the receiving library --- docs/getting-started/migration-guide.mdx | 1 + packages/ack_generator/CHANGELOG.md | 4 + .../analyzer/class_model_graph_builder.dart | 124 ++++++++++++++---- .../integration/class_model_emitter_test.dart | 41 ++++++ .../integration/class_model_graph_test.dart | 29 ++++ 5 files changed, 177 insertions(+), 22 deletions(-) diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 587bf298..23b1cd8a 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -15,6 +15,7 @@ This guide summarizes **what exists in Ack today**, **what changed in 1.7 and 2. | Schema-first fields, discriminators, and inline JSON Schema model names | `2.0.0` | Regenerate and update Dart callers. Digits before uppercase letters and acronym boundaries affect names such as `ipv4Address` and `urlIsValid`. Inline model segments normalize acronyms, for example `UserID` → `UserId`. Use a class-first model with `@AckKey` for keys containing non-ASCII letters, keys mapping to a reserved word such as `default`, and collisions. | | Implicit field style on an annotated branch of a styled sealed class | `2.0.0` | Regenerate to inherit the base’s style. Use `caseStyle: AckCaseStyle.none` on the branch to retain Dart names on the wire. | | Code that reads `Schemable.caseStyle` as non-null | `2.0.0` | Handle a null style as unspecified. Use `annotation.caseStyle ?? AckCaseStyle.none` when you need the standalone default. | +| A super parameter whose inherited default references a declaration you cannot access | `2.0.0` | Import the declaration used in the default, or give the super parameter an explicit default. | | Class-owned schema refinements | `2.0.0` | Generated helpers and nested fields now enforce them. Compose `ModelSchema.schema` explicitly when you need the raw generated rules. | | Schema-first fields using snake_case or another wire spelling | `2.0.0` | Regenerate and use the lowerCamelCase Dart names in field accesses, constructors and `copyWith`. JSON keys keep their original spelling. | | The direct `ackModelBuilder` factory | `2.0.0` | Use the shared `ack_generator:ack_generator` builder with source_gen’s combining builder. | diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 48ef1676..271273be 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -2,6 +2,10 @@ ### Breaking +* **Breaking:** Inherited constructor defaults from another library must use + declarations visible to the generated part. Import the referenced names or + give the super parameter an explicit default. + * **Breaking:** Reject schema-first field and discriminator names that shadow generated references such as `override` and `identical`. diff --git a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart index f367abec..1940ff8d 100644 --- a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart @@ -1002,6 +1002,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { final resolved = inputResolved; if (resolved == null) return null; for (final element in [field, ?parameter]) { + if (element.library != library.element) continue; final node = declarationNode(resolved, element); if (node is FormalParameter) { final comment = node.documentationComment; @@ -1384,30 +1385,33 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { ) { final owner = source.enclosingElement?.enclosingElement; if (owner is! ClassElement) return original; + final external = owner.library != library.element; final resolved = await resolvedLibraryFor(owner.library); final declaration = resolved.getFragmentDeclaration(source.firstFragment); final content = declaration?.resolvedUnit?.content; final node = declaration?.node; - if (content == null || node is! FormalParameter) return original; + if (content == null || node is! FormalParameter) { + if (external) throw _inaccessibleDefault(parameter, owner.name!); + return original; + } final value = node.defaultClause?.value; if (value == null) continue; - final visitor = _ClassStaticReferences(owner); + final visitor = _ConstructorDefaultReferences(owner, external: external); value.accept(visitor); if (visitor.references.isEmpty) return original; - final visibleOwner = visibleTypeNameFor( - owner.thisType, - path: '${owner.name}.${source.name}', - context: parameter, - ); var qualified = content.substring(value.offset, value.end); for (final reference in visitor.references.reversed) { - final qualifiedName = '$visibleOwner.${reference.name}'; - final parent = reference.parent; + final name = external + ? _visibleDefaultName(parameter, reference.target) + : reference.target.name!; + final qualifiedName = reference.member == null + ? name + : '$name.${reference.member}'; qualified = qualified.replaceRange( reference.offset - value.offset, reference.end - value.offset, - parent is InterpolationExpression && parent.rightBracket == null + reference.shortInterpolation && qualifiedName.contains('.') ? '{$qualifiedName}' : qualifiedName, ); @@ -1417,6 +1421,32 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { return original; } + String _visibleDefaultName(FormalParameterElement parameter, Element target) { + final name = target.name!; + final String? prefix; + try { + prefix = visiblePrefixFor(target, path: name, context: parameter); + } on InvalidGenerationSource { + throw _inaccessibleDefault(parameter, name); + } + if (prefix == null && + library.element.firstFragment.scope.lookup(name).getter?.baseElement != + target.baseElement) { + throw _inaccessibleDefault(parameter, name); + } + return qualifySymbol(prefix, name); + } + + InvalidGenerationSource _inaccessibleDefault( + FormalParameterElement parameter, + String reference, + ) => InvalidGenerationSource( + '${parameter.enclosingElement?.enclosingElement?.name}.${parameter.name} ' + 'inherits a default that references "$reference", which cannot be ' + 'resolved in this library. Declare an explicit default for this parameter.', + element: parameter, + ); + _ModelOptions? _options( ClassElement element, { annotations.AckCaseStyle inheritedCaseStyle = annotations.AckCaseStyle.none, @@ -1589,29 +1619,79 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { ); } -/// Marks unqualified references that need the class name in the generated part. -final class _ClassStaticReferences extends RecursiveAstVisitor { - _ClassStaticReferences(this.owner); +typedef _DefaultReference = ({ + Element target, + String? member, + int offset, + int end, + bool shortInterpolation, +}); + +/// Finds references whose spelling can depend on the declaring scope. +final class _ConstructorDefaultReferences extends RecursiveAstVisitor { + _ConstructorDefaultReferences(this.owner, {required this.external}); final ClassElement owner; - final references = []; + final bool external; + final references = <_DefaultReference>[]; + + void _add(AstNode node, Element target, {String? member, int? end}) { + final parent = node.parent; + references.add(( + target: target, + member: member, + offset: node.offset, + end: end ?? node.end, + shortInterpolation: + parent is InterpolationExpression && parent.rightBracket == null, + )); + } @override - void visitSimpleIdentifier(SimpleIdentifier node) { - final element = node.element; - if (element is! ExecutableElement || - !element.isStatic || - element.enclosingElement != owner) { + void visitNamedType(NamedType node) { + final target = node.element; + if (external && target?.enclosingElement is LibraryElement) { + _add(node, target!, end: node.name.end); + } + super.visitNamedType(node); + } + + @override + void visitPrefixedIdentifier(PrefixedIdentifier node) { + final target = node.identifier.element; + if (external && node.prefix.element is PrefixElement && target != null) { + _add(node, target); return; } + super.visitPrefixedIdentifier(node); + } + + @override + void visitSimpleIdentifier(SimpleIdentifier node) { + final element = node.element; + if (element == null) return; final parent = node.parent; - if (parent is PrefixedIdentifier && identical(parent.identifier, node) || + final isMember = + parent is PrefixedIdentifier && identical(parent.identifier, node) || parent is PropertyAccess && identical(parent.propertyName, node) || parent is MethodInvocation && parent.target != null && - identical(parent.methodName, node)) { + identical(parent.methodName, node) || + parent is ConstructorName && identical(parent.name, node); + if (isMember) { + if (external && node.name.startsWith('_')) _add(node, element); return; } - references.add(node); + if (element is ExecutableElement && + element.isStatic && + element.enclosingElement == owner) { + if (external && node.name.startsWith('_')) { + _add(node, element); + } else { + _add(node, owner, member: node.name); + } + } else if (external && element.enclosingElement is LibraryElement) { + _add(node, element); + } } } diff --git a/packages/ack_generator/test/integration/class_model_emitter_test.dart b/packages/ack_generator/test/integration/class_model_emitter_test.dart index 5eb55af8..4147f0fd 100644 --- a/packages/ack_generator/test/integration/class_model_emitter_test.dart +++ b/packages/ack_generator/test/integration/class_model_emitter_test.dart @@ -41,6 +41,47 @@ import 'package:ack/annotations.dart'; '''; void main() { + test('qualifies inherited defaults through the consumer imports', () async { + await _build( + { + 'base.dart': r''' +import 'values.dart' as source; + +const kRole = 'original'; +class Base { + const Base({this.role = kRole, this.title = source.kTitle, this.ids = const []}); + final String role; + final String title; + final List ids; +} +''', + 'values.dart': "const kTitle = 'title';", + 'model.dart': r''' +import 'package:ack/ack.dart'; +import 'base.dart' as origin show Base, kRole; +import 'values.dart' as values; +part 'model.g.dart'; + +const kRole = 'wrong'; + +@Schemable() +final class Model extends origin.Base with _$ModelAck { + const Model({super.role, super.title, super.ids}); +} +''', + }, + outputs: { + 'test_pkg|lib/model.g.dart': decodedMatches( + allOf([ + _containsCode('.withDefault(origin.kRole)'), + _containsCode('.withDefault(values.kTitle)'), + _containsCode('.withDefault(const [])'), + ]), + ), + }, + ); + }); + test( 'braces qualified class statics in constructor default interpolation', () async { diff --git a/packages/ack_generator/test/integration/class_model_graph_test.dart b/packages/ack_generator/test/integration/class_model_graph_test.dart index 723484bb..5a3ebe3f 100644 --- a/packages/ack_generator/test/integration/class_model_graph_test.dart +++ b/packages/ack_generator/test/integration/class_model_graph_test.dart @@ -51,6 +51,35 @@ part 'model.g.dart'; '''; void main() { + test('reports a hidden constant used by a super-parameter default', () async { + await _expectFailure( + r''' +const kRole = 'wrong'; + +@Schemable() +final class Model extends Base with _$ModelAck { + const Model({super.role}); +} +''', + ['Model.role', 'kRole', 'explicit default'], + head: ''' +import 'package:ack/ack.dart'; +import 'base.dart' show Base; +part 'model.g.dart'; +''', + extraSources: { + 'base.dart': ''' +const kRole = 'right'; + +class Base { + const Base({this.role = kRole}); + final String role; +} +''', + }, + ); + }); + for (final (owner, baseSchema, branchSchema) in [ ( 'Shape', From b161685ef58c26381e4df8a40dfd7e8596c8a2b7 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 19:13:42 +0000 Subject: [PATCH 50/57] refactor(ack)!: make transparent context construction private --- docs/getting-started/migration-guide.mdx | 1 + packages/ack/CHANGELOG.md | 3 + packages/ack/lib/src/context.dart | 60 ++++++++++++++----- packages/ack/lib/src/schemas/lazy_schema.dart | 29 +-------- packages/ack/test/context_test.dart | 32 ++++++++++ .../public_api/internal_helpers.dart.txt | 7 --- .../transparent_context_hidden.dart.txt | 8 +++ .../json_schema_import_public_api_test.dart | 6 +- 8 files changed, 97 insertions(+), 49 deletions(-) create mode 100644 packages/ack/test/context_test.dart diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 39a6c0dd..44830194 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -173,6 +173,7 @@ and errors: | Code matching a dotted built-in constraint key | `2.0.0` | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique_items`, `number.isFinite` → `number_finite`, `integer.isSafe` → `number_safe_integer`. | | `AckRule` from `package:ack/annotations.dart` | `2.0.0` | Use the concrete rule annotation type for rule-specific data, or `Object` for a mixed list. | | `implements SchemaContext` | `2.0.0` | Read the context from `SchemaError.context`. `SchemaContext` is a `base` class, so external subclasses require a `base`, `final`, or `sealed` modifier. | +| `SchemaContext.transparent` | `2.0.0` | Ack creates transparent contexts while validating wrapper schemas. Read the resulting context through `SchemaError.context`. | | `AckSchemaModel.finishTypeJson` or `AckSchemaModel.finishCompositionJson` | `2.0.0` | Render the public model with `toJsonSchema()` and apply any custom JSON Schema keywords to the resulting map. | | `schema.toMap()` | `2.0.0` | `schema.toJsonSchema()` or `schema.toSchemaModel()` | | `server.registerAckModelTool(...)` (`ack_mcp_dart`) | `2.0.0` | `server.registerAckTool(name, input: Model.schema, callback: ...)`; return a `CallToolResult` from the callback | diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 1cfe817d..85456f80 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -5,6 +5,9 @@ * **Breaking:** `SchemaContext` is a `base` class and `createChild` is internal. Read the context from `SchemaError.context` when handling validation errors. +* **Breaking:** `SchemaContext.transparent` is private. Ack creates transparent + contexts when validating wrapper schemas. + * **Breaking:** Use `constrain(constraint)` to attach a custom constraint. `withConstraint` and `withConstraints` are now marked `@internal`. Chain `constrain` calls to attach multiple constraints. diff --git a/packages/ack/lib/src/context.dart b/packages/ack/lib/src/context.dart index cb11d9fb..3396b479 100644 --- a/packages/ack/lib/src/context.dart +++ b/packages/ack/lib/src/context.dart @@ -1,6 +1,7 @@ import 'package:meta/meta.dart'; import 'schemas/schema.dart'; +import 'utils/json_utils.dart'; /// Represents the context in which a schema operation is occurring. @immutable @@ -25,8 +26,7 @@ base class SchemaContext { }) : _omitPathSegment = false; /// Creates an internal wrapper context without adding a JSON Pointer token. - @internal - const SchemaContext.transparent({ + const SchemaContext._transparent({ required this.name, required this.schema, required this.value, @@ -35,11 +35,6 @@ base class SchemaContext { }) : pathSegment = null, _omitPathSegment = true; - /// Escapes a JSON Pointer segment per RFC 6901. - static String _escapeJsonPointerSegment(String segment) { - return segment.replaceAll('~', '~0').replaceAll('/', '~1'); - } - /// The full JSON Pointer path (RFC 6901) from root to this context. String get path { if (parent == null) { @@ -53,7 +48,7 @@ base class SchemaContext { } final segment = pathSegment ?? name; - final escapedSegment = _escapeJsonPointerSegment(segment); + final escapedSegment = escapeJsonPointerToken(segment); return parentPath == '#' ? '#/$escapedSegment' @@ -90,19 +85,54 @@ base class SchemaContext { } } +/// Marks an active lazy invocation separately from other wrapper contexts. +final class _LazyRecursionContext extends SchemaContext { + const _LazyRecursionContext({ + required super.name, + required super.schema, + required super.value, + required SchemaContext super.parent, + required super.operation, + required this.recursionToken, + }) : super._transparent(); + + final Object recursionToken; +} + /// Shared path plumbing for internal wrapper schemas. @internal extension SchemaContextTraversal on SchemaContext { + bool get isTransparent => _omitPathSegment; + + Object? get lazyRecursionToken => switch (this) { + _LazyRecursionContext(:final recursionToken) => recursionToken, + _ => null, + }; + SchemaContext createTransparentChild({ required String name, required AnyAckSchema schema, required Object? value, SchemaOperation? operation, - }) => SchemaContext.transparent( - name: name, - schema: schema, - value: value, - parent: this, - operation: operation ?? this.operation, - ); + Object? lazyRecursionToken, + }) { + final childOperation = operation ?? this.operation; + if (lazyRecursionToken != null) { + return _LazyRecursionContext( + name: name, + schema: schema, + value: value, + parent: this, + operation: childOperation, + recursionToken: lazyRecursionToken, + ); + } + return SchemaContext._transparent( + name: name, + schema: schema, + value: value, + parent: this, + operation: childOperation, + ); + } } diff --git a/packages/ack/lib/src/schemas/lazy_schema.dart b/packages/ack/lib/src/schemas/lazy_schema.dart index 33c86447..149e42c5 100644 --- a/packages/ack/lib/src/schemas/lazy_schema.dart +++ b/packages/ack/lib/src/schemas/lazy_schema.dart @@ -150,20 +150,18 @@ final class LazySchema } SchemaContext _enterRecursion(Object? value, SchemaContext context) { - return _LazyRecursionContext( + return context.createTransparentChild( name: name, schema: this as AnyAckSchema, - recursionToken: _recursionToken, + lazyRecursionToken: _recursionToken, value: value, - parent: context, ); } SchemaResult? _checkMaxDepth(SchemaContext context) { var depth = 0; for (SchemaContext? c = context; c != null; c = c.parent) { - if (c is _LazyRecursionContext && - identical(c.recursionToken, _recursionToken)) { + if (identical(c.lazyRecursionToken, _recursionToken)) { depth++; } } @@ -230,27 +228,6 @@ final class LazySchema } } -/// Marks one active lazy invocation without conflating it with structural -/// child contexts created by object, list, union, or wrapper schemas. -final class _LazyRecursionContext extends SchemaContext { - _LazyRecursionContext({ - required String name, - required AnyAckSchema schema, - required this.recursionToken, - required Object? value, - required SchemaContext parent, - }) : super.transparent( - name: name, - schema: schema, - value: value, - parent: parent, - - operation: parent.operation, - ); - - final Object recursionToken; -} - final class _LazyMaxDepthConstraint extends Constraint { _LazyMaxDepthConstraint(this.maxDepth) : super( diff --git a/packages/ack/test/context_test.dart b/packages/ack/test/context_test.dart new file mode 100644 index 00000000..6edb74c3 --- /dev/null +++ b/packages/ack/test/context_test.dart @@ -0,0 +1,32 @@ +import 'package:ack/ack.dart'; +import 'package:ack/src/context.dart' show SchemaContextTraversal; +import 'package:test/test.dart'; + +void main() { + test('transparent children inherit the pointer and operation', () { + final schema = Ack.string(); + final root = SchemaContext( + name: 'root', + schema: schema, + value: 'value', + operation: SchemaOperation.encode, + ); + final child = root.createChild( + name: 'a~/b', + schema: schema, + value: 'value', + ); + final wrapper = child.createTransparentChild( + name: 'wrapper', + schema: schema, + value: 'value', + ); + + expect(root.isTransparent, isFalse); + expect(child.isTransparent, isFalse); + expect(wrapper.isTransparent, isTrue); + expect(wrapper.parent, same(child)); + expect(wrapper.path, '#/a~0~1b'); + expect(wrapper.operation, SchemaOperation.encode); + }); +} diff --git a/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt b/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt index 89d200f6..7d19213f 100644 --- a/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt +++ b/packages/ack/test/fixtures/public_api/internal_helpers.dart.txt @@ -17,11 +17,4 @@ void main() { final parent = SchemaContext(name: 'root', schema: schema, value: 'value'); parent.createChild(name: 'child', schema: schema, value: 'value'); schema.toSchemaModel().withJsonSchemaKeywords({'title': 'item'}); - SchemaContext.transparent( - name: 'item', - schema: schema, - value: 'value', - parent: parent, - operation: SchemaOperation.parse, - ); } diff --git a/packages/ack/test/fixtures/public_api/transparent_context_hidden.dart.txt b/packages/ack/test/fixtures/public_api/transparent_context_hidden.dart.txt index c0334b87..8e50b78a 100644 --- a/packages/ack/test/fixtures/public_api/transparent_context_hidden.dart.txt +++ b/packages/ack/test/fixtures/public_api/transparent_context_hidden.dart.txt @@ -18,6 +18,14 @@ void checkChild(SchemaContext root) { void checkGetter(SchemaContext root) { print(root.omitPathSegment); + print(root.isTransparent); + SchemaContext.transparent( + name: 'wrapper', + schema: Ack.string(), + value: 'value', + parent: root, + operation: SchemaOperation.parse, + ); } void main() { diff --git a/packages/ack/test/json_schema_import_public_api_test.dart b/packages/ack/test/json_schema_import_public_api_test.dart index 4413be32..3fe71714 100644 --- a/packages/ack/test/json_schema_import_public_api_test.dart +++ b/packages/ack/test/json_schema_import_public_api_test.dart @@ -88,6 +88,11 @@ void main() { result.stderr, contains("The getter 'omitPathSegment' isn't defined"), ); + expect(result.stderr, contains("The getter 'isTransparent' isn't defined")); + expect( + result.stderr, + contains("Member not found: 'SchemaContext.transparent'"), + ); }); test('schema model rendering helpers are private', () async { @@ -107,7 +112,6 @@ void main() { unorderedEquals([ for (final name in [ 'withJsonSchemaKeywords', - 'SchemaContext.transparent', 'createChild', // Calls through StringSchema reach the mixin declarations. 'withConstraint', From 9f03d79d8d9ce0c6018a183ba241e725e358c672 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 19:15:07 +0000 Subject: [PATCH 51/57] fix(ack)!: validate constraints on schema copies --- docs/getting-started/migration-guide.mdx | 1 + packages/ack/CHANGELOG.md | 3 ++ .../ack/lib/src/schemas/any_of_schema.dart | 2 +- packages/ack/lib/src/schemas/any_schema.dart | 2 +- .../ack/lib/src/schemas/boolean_schema.dart | 2 +- .../ack/lib/src/schemas/boundary_schema.dart | 2 +- .../ack/lib/src/schemas/codec_schema.dart | 2 +- .../schemas/discriminated_object_schema.dart | 2 +- packages/ack/lib/src/schemas/enum_schema.dart | 2 +- .../lib/src/schemas/imported_json_schema.dart | 2 +- .../ack/lib/src/schemas/instance_schema.dart | 2 +- packages/ack/lib/src/schemas/lazy_schema.dart | 2 +- packages/ack/lib/src/schemas/list_schema.dart | 2 +- packages/ack/lib/src/schemas/map_schema.dart | 2 +- packages/ack/lib/src/schemas/num_schema.dart | 6 +-- .../ack/lib/src/schemas/object_schema.dart | 2 +- packages/ack/lib/src/schemas/schema.dart | 21 ++++++++-- .../ack/lib/src/schemas/string_schema.dart | 2 +- .../ack/test/reference_semantics_test.dart | 39 +++++++++++++++++++ 19 files changed, 77 insertions(+), 21 deletions(-) diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 44830194..425851d8 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -188,6 +188,7 @@ and errors: | `AckSchemaModel.withJsonSchemaKeywords` | `2.0.0` | The method remains callable and is marked `@internal`. External calls produce an analyzer warning. Render with `toJsonSchema()` and apply custom keywords to the resulting map. | | `SchemaContext.createChild` | `2.0.0` | Use the nested error's `context` to inspect its value and path. Ack creates child contexts during validation. | | `withConstraint(c)` or `withConstraints([a, b])` | `2.0.0` | Use `constrain(c)` or chain `constrain(a).constrain(b)`. Both former methods are marked `@internal`. | +| Raw constraints in `copyWith(constraints:)` or `withRuntimeConfig(constraints:)` | `2.0.0` | Replacement constraints must mix in `Validator`. Use `constrain(c)` to add a custom constraint. | --- diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 85456f80..434e5596 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -12,6 +12,9 @@ `withConstraint` and `withConstraints` are now marked `@internal`. Chain `constrain` calls to attach multiple constraints. +* **Breaking:** `copyWith` and `withRuntimeConfig` reject replacement + constraints that lack a `Validator` and snapshot the supplied list. + * **Breaking:** Replace `StringSchema.url()` with `uri()`, and `@IsUrl()` with `@IsUri()`. URI validation and JSON Schema output are unchanged. diff --git a/packages/ack/lib/src/schemas/any_of_schema.dart b/packages/ack/lib/src/schemas/any_of_schema.dart index 5288787d..600532fd 100644 --- a/packages/ack/lib/src/schemas/any_of_schema.dart +++ b/packages/ack/lib/src/schemas/any_of_schema.dart @@ -152,7 +152,7 @@ final class AnyOfSchema extends AckSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } diff --git a/packages/ack/lib/src/schemas/any_schema.dart b/packages/ack/lib/src/schemas/any_schema.dart index 81f37545..6a5d4970 100644 --- a/packages/ack/lib/src/schemas/any_schema.dart +++ b/packages/ack/lib/src/schemas/any_schema.dart @@ -59,7 +59,7 @@ final class AnySchema extends AckSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } diff --git a/packages/ack/lib/src/schemas/boolean_schema.dart b/packages/ack/lib/src/schemas/boolean_schema.dart index 5008a684..51326998 100644 --- a/packages/ack/lib/src/schemas/boolean_schema.dart +++ b/packages/ack/lib/src/schemas/boolean_schema.dart @@ -46,7 +46,7 @@ final class BooleanSchema extends AckSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } diff --git a/packages/ack/lib/src/schemas/boundary_schema.dart b/packages/ack/lib/src/schemas/boundary_schema.dart index d2db9186..2d71c5ba 100644 --- a/packages/ack/lib/src/schemas/boundary_schema.dart +++ b/packages/ack/lib/src/schemas/boundary_schema.dart @@ -117,7 +117,7 @@ final class BoundarySchema extends AckSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } diff --git a/packages/ack/lib/src/schemas/codec_schema.dart b/packages/ack/lib/src/schemas/codec_schema.dart index c6f3ee4f..6b504773 100644 --- a/packages/ack/lib/src/schemas/codec_schema.dart +++ b/packages/ack/lib/src/schemas/codec_schema.dart @@ -226,7 +226,7 @@ final class CodecSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } diff --git a/packages/ack/lib/src/schemas/discriminated_object_schema.dart b/packages/ack/lib/src/schemas/discriminated_object_schema.dart index f86dbaac..b1d8bcd4 100644 --- a/packages/ack/lib/src/schemas/discriminated_object_schema.dart +++ b/packages/ack/lib/src/schemas/discriminated_object_schema.dart @@ -586,7 +586,7 @@ final class DiscriminatedObjectSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } diff --git a/packages/ack/lib/src/schemas/enum_schema.dart b/packages/ack/lib/src/schemas/enum_schema.dart index e023fc1f..f1438b9e 100644 --- a/packages/ack/lib/src/schemas/enum_schema.dart +++ b/packages/ack/lib/src/schemas/enum_schema.dart @@ -122,7 +122,7 @@ final class EnumSchema extends AckSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } diff --git a/packages/ack/lib/src/schemas/imported_json_schema.dart b/packages/ack/lib/src/schemas/imported_json_schema.dart index 78ef3090..b1d8ac35 100644 --- a/packages/ack/lib/src/schemas/imported_json_schema.dart +++ b/packages/ack/lib/src/schemas/imported_json_schema.dart @@ -402,7 +402,7 @@ final class ImportedJsonSchema extends AckSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); diff --git a/packages/ack/lib/src/schemas/instance_schema.dart b/packages/ack/lib/src/schemas/instance_schema.dart index 978d0cf0..5df5a323 100644 --- a/packages/ack/lib/src/schemas/instance_schema.dart +++ b/packages/ack/lib/src/schemas/instance_schema.dart @@ -54,7 +54,7 @@ final class InstanceSchema extends AckSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } diff --git a/packages/ack/lib/src/schemas/lazy_schema.dart b/packages/ack/lib/src/schemas/lazy_schema.dart index 149e42c5..ec1ffbd2 100644 --- a/packages/ack/lib/src/schemas/lazy_schema.dart +++ b/packages/ack/lib/src/schemas/lazy_schema.dart @@ -198,7 +198,7 @@ final class LazySchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } diff --git a/packages/ack/lib/src/schemas/list_schema.dart b/packages/ack/lib/src/schemas/list_schema.dart index 84d4aca1..086d3230 100644 --- a/packages/ack/lib/src/schemas/list_schema.dart +++ b/packages/ack/lib/src/schemas/list_schema.dart @@ -173,7 +173,7 @@ final class ListSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } diff --git a/packages/ack/lib/src/schemas/map_schema.dart b/packages/ack/lib/src/schemas/map_schema.dart index faf61dc7..d513b598 100644 --- a/packages/ack/lib/src/schemas/map_schema.dart +++ b/packages/ack/lib/src/schemas/map_schema.dart @@ -170,7 +170,7 @@ final class MapSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } diff --git a/packages/ack/lib/src/schemas/num_schema.dart b/packages/ack/lib/src/schemas/num_schema.dart index 7099fa35..a2e6d566 100644 --- a/packages/ack/lib/src/schemas/num_schema.dart +++ b/packages/ack/lib/src/schemas/num_schema.dart @@ -111,7 +111,7 @@ final class IntegerSchema extends NumSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } @@ -195,7 +195,7 @@ final class DoubleSchema extends NumSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } @@ -262,7 +262,7 @@ final class NumberSchema extends NumSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } diff --git a/packages/ack/lib/src/schemas/object_schema.dart b/packages/ack/lib/src/schemas/object_schema.dart index 95097467..0068427d 100644 --- a/packages/ack/lib/src/schemas/object_schema.dart +++ b/packages/ack/lib/src/schemas/object_schema.dart @@ -412,7 +412,7 @@ final class ObjectSchema extends AckSchema isNullable: isNullable ?? this.isNullable, isOptional: isOptional ?? this.isOptional, description: description ?? this.description, - constraints: constraints ?? this.constraints, + constraints: _constraintsForCopy(constraints), refinements: refinements ?? this.refinements, ); } diff --git a/packages/ack/lib/src/schemas/schema.dart b/packages/ack/lib/src/schemas/schema.dart index c22e4191..b7a056b1 100644 --- a/packages/ack/lib/src/schemas/schema.dart +++ b/packages/ack/lib/src/schemas/schema.dart @@ -90,6 +90,15 @@ sealed class AckSchema { /// An unmodifiable view of the constraints for this schema. List> get constraints => List.unmodifiable(_constraints); + List> _constraintsForCopy( + List>? replacements, + ) { + if (replacements == null) return constraints; + final snapshot = List>.unmodifiable(replacements); + snapshot.forEach(_requireValidator); + return snapshot; + } + /// An unmodifiable view of the refinements for this schema. List> get refinements => List.unmodifiable(_refinements); @@ -390,15 +399,19 @@ sealed class AckSchema { Constraint constraint, { String? message, }) { + _requireValidator(constraint); + final effectiveConstraint = message == null + ? constraint + : _ConstraintMessageOverride(constraint, message); + return withConstraint(effectiveConstraint); + } + + void _requireValidator(Constraint constraint) { if (constraint is! Validator) { throw ArgumentError( 'Constraint ${constraint.runtimeType} must implement Validator.', ); } - final effectiveConstraint = message == null - ? constraint - : _ConstraintMessageOverride(constraint, message); - return withConstraint(effectiveConstraint); } // --------------------------------------------------------------------------- diff --git a/packages/ack/lib/src/schemas/string_schema.dart b/packages/ack/lib/src/schemas/string_schema.dart index 6a5ceeb7..6c66a6c1 100644 --- a/packages/ack/lib/src/schemas/string_schema.dart +++ b/packages/ack/lib/src/schemas/string_schema.dart @@ -169,7 +169,7 @@ final class StringSchema extends AckSchema List>? constraints, List>? refinements, }) { - final nextConstraints = constraints ?? this.constraints; + final nextConstraints = _constraintsForCopy(constraints); final nextRefinements = refinements ?? this.refinements; final nextNormalizers = _normalizers.isEmpty || (constraints == null && refinements == null) diff --git a/packages/ack/test/reference_semantics_test.dart b/packages/ack/test/reference_semantics_test.dart index d81f05f2..a4d18fe0 100644 --- a/packages/ack/test/reference_semantics_test.dart +++ b/packages/ack/test/reference_semantics_test.dart @@ -52,6 +52,40 @@ void main() { }); }); + group('constraint replacement', () { + final schema = Ack.string(); + final copyMethods = + >)>{ + 'copyWith': (constraints) => + schema.copyWith(constraints: constraints), + 'withRuntimeConfig': (constraints) => + schema.withRuntimeConfig(constraints: constraints), + }; + for (final MapEntry(key: name, value: copy) in copyMethods.entries) { + test('$name rejects constraints without a Validator', () { + expect( + () => copy([const _MetadataOnlyConstraint()]), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('must implement Validator'), + ), + ), + ); + }); + + test('$name snapshots the validated constraint list', () { + final constraints = [schema.minLength(2).constraints.single]; + final copySchema = copy(constraints); + constraints[0] = const _MetadataOnlyConstraint(); + + expect(copySchema.safeParse('a').isFail, isTrue); + expect(copySchema.safeParse('ab').isOk, isTrue); + }); + } + }); + group('portable schema semantics', () { test('preserves intersecting constraints with duplicate keywords', () { final schema = Ack.string().minLength(10).minLength(5); @@ -178,6 +212,11 @@ void main() { }); } +final class _MetadataOnlyConstraint extends Constraint { + const _MetadataOnlyConstraint() + : super(constraintKey: 'metadata_only', description: 'Test metadata'); +} + final class _ThrowingConstraint extends Constraint with Validator { const _ThrowingConstraint() From 4f68500f40345b41a54eea97c41c4f2b795bbd44 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 19:15:18 +0000 Subject: [PATCH 52/57] fix(generator)!: fall back on invalid translated JSON Schema names --- docs/getting-started/migration-guide.mdx | 2 + packages/ack_generator/CHANGELOG.md | 7 ++++ .../lib/src/analyzer/schema_first_names.dart | 12 ++++++ .../analyzer/schema_model_graph_builder.dart | 8 ++-- .../src/json_schema/json_schema_emitter.dart | 4 ++ .../src/json_schema/json_schema_library.dart | 3 ++ .../json_schema/json_schema_translator.dart | 41 ++++++++++++++----- .../json_schema/json_schema_library_test.dart | 36 ++++++++++++++++ 8 files changed, 97 insertions(+), 16 deletions(-) diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 23b1cd8a..89b8f44f 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -16,6 +16,8 @@ This guide summarizes **what exists in Ack today**, **what changed in 1.7 and 2. | Implicit field style on an annotated branch of a styled sealed class | `2.0.0` | Regenerate to inherit the base’s style. Use `caseStyle: AckCaseStyle.none` on the branch to retain Dart names on the wire. | | Code that reads `Schemable.caseStyle` as non-null | `2.0.0` | Handle a null style as unspecified. Use `annotation.caseStyle ?? AckCaseStyle.none` when you need the standalone default. | | A super parameter whose inherited default references a declaration you cannot access | `2.0.0` | Import the declaration used in the default, or give the super parameter an explicit default. | +| JSON Schema properties that cannot become distinct Dart fields, such as `@id` and `id` | `2.0.0` | Automatic generation uses a validated value model. Read the original keys from `model.value`, or define a class-first model with `@AckKey` for typed fields. | +| A JSON Schema property whose wire spelling matches its model name, such as `Model` | `2.0.0` | Regenerate and use the typed field, such as `model.model`, when the derived Dart name is valid. | | Class-owned schema refinements | `2.0.0` | Generated helpers and nested fields now enforce them. Compose `ModelSchema.schema` explicitly when you need the raw generated rules. | | Schema-first fields using snake_case or another wire spelling | `2.0.0` | Regenerate and use the lowerCamelCase Dart names in field accesses, constructors and `copyWith`. JSON keys keep their original spelling. | | The direct `ackModelBuilder` factory | `2.0.0` | Use the shared `ack_generator:ack_generator` builder with source_gen’s combining builder. | diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 271273be..b0012a4e 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -2,6 +2,10 @@ ### Breaking +* **Breaking:** A JSON Schema property whose wire spelling matches its model + name can now generate a typed field when its Dart field name is distinct. + Regenerate and update callers that used the previous value model. + * **Breaking:** Inherited constructor defaults from another library must use declarations visible to the generated part. Import the referenced names or give the super parameter an explicit default. @@ -53,6 +57,9 @@ * Qualify references to class statics in generated constructor defaults. * Preserve short string interpolations when qualifying constructor defaults. +* Fall back to validated value models when JSON Schema property names collide + in Dart, shadow generated references, or contain non-ASCII letters. + Generated comments identify the properties that led to the fallback. * Preserve constructor defaults inherited through super parameters, including defaults that refer to statics on the declaring class. diff --git a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart index 28883605..17cd2aee 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart @@ -72,6 +72,18 @@ String? ackSchemaFirstWireKeyProblem(String key) => 'keep the wire key and choose its Dart name.' : null; +/// Records a wire key and reports when another key already maps to its name. +String? ackSchemaFirstFieldCollision( + Map wireKeysByFieldName, + String dartName, + String wireKey, +) { + final previous = wireKeysByFieldName.putIfAbsent(dartName, () => wireKey); + if (previous == wireKey) return null; + return 'JSON keys "$previous" and "$wireKey" that both map to ' + 'the Dart field "$dartName".'; +} + final _wordBoundary = RegExp( r'[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])|' // Split HTTPServer and URLIsValid while keeping the plural s in URLs. diff --git a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart index 4c074d47..1363c5ea 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart @@ -377,15 +377,13 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { ); } final dartName = ackSchemaFirstDartFieldName(jsonKey); - final previous = wireKeysByFieldName[dartName]; - if (previous != null) { + if (ackSchemaFirstFieldCollision(wireKeysByFieldName, dartName, jsonKey) + case final collision?) { throw InvalidGenerationSource( - '$path has JSON keys "$previous" and "$jsonKey" that both map to ' - 'the Dart field "$dartName".', + '$path has $collision', element: declaration.element, ); } - wireKeysByFieldName[dartName] = jsonKey; final fieldChain = parseSchemaChain(entry.value); final fieldMetadata = await _schemaMetadata( entry.value, diff --git a/packages/ack_generator/lib/src/json_schema/json_schema_emitter.dart b/packages/ack_generator/lib/src/json_schema/json_schema_emitter.dart index 96ce33f0..c1fde108 100644 --- a/packages/ack_generator/lib/src/json_schema/json_schema_emitter.dart +++ b/packages/ack_generator/lib/src/json_schema/json_schema_emitter.dart @@ -46,6 +46,7 @@ String _emitFallback( required Map documents, required bool assertFormats, required List widened, + required List propertyNameDiagnostics, }) { final defs = document[r'$defs'] as Map? ?? const {}; const rootAnnotations = { @@ -103,6 +104,9 @@ String _emitFallback( ..writeln( '// Complex shapes use Object? values, not inferred typed fields.', ); + for (final diagnostic in propertyNameDiagnostics) { + buffer.writeln('// Property name fallback: ${_commentText('$diagnostic')}'); + } if (widened.isNotEmpty) { buffer.writeln('// unknown_properties: preserve widened these objects:'); for (final pointer in widened) { diff --git a/packages/ack_generator/lib/src/json_schema/json_schema_library.dart b/packages/ack_generator/lib/src/json_schema/json_schema_library.dart index 75529c50..49d15e37 100644 --- a/packages/ack_generator/lib/src/json_schema/json_schema_library.dart +++ b/packages/ack_generator/lib/src/json_schema/json_schema_library.dart @@ -152,6 +152,7 @@ AckJsonSchemaLibrary generateAckSchemaLibrary({ bool includeParts = true, Version? languageVersion, }) { + var propertyNameDiagnostics = const []; if (options.modelMode == AckJsonSchemaModelMode.auto) { final translator = _Translator(documentUri, options, documents); final effective = translator.prepare(document); @@ -172,6 +173,7 @@ AckJsonSchemaLibrary generateAckSchemaLibrary({ widenedPointers: List.unmodifiable(translator.widened), ); } + propertyNameDiagnostics = translator.propertyNameDiagnostics; } // The typed translator is intentionally conservative. A valid document it @@ -197,6 +199,7 @@ AckJsonSchemaLibrary generateAckSchemaLibrary({ documents: fallbackDocuments, assertFormats: options.assertFormats, widened: fallback.widened, + propertyNameDiagnostics: propertyNameDiagnostics, ), ), effectiveDocument: fallbackDocument, diff --git a/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart b/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart index 6b4648ef..262ca423 100644 --- a/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart +++ b/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart @@ -98,6 +98,7 @@ final class _Translator { final AckJsonSchemaLibraryOptions options; final Map documents; final diagnostics = []; + final propertyNameDiagnostics = []; final declarations = <_Declaration>[]; final widened = []; @@ -106,8 +107,15 @@ final class _Translator { final _edgePointers = <(String, String), String>{}; late Map _defs; - void _fail(String pointer, String message) => - diagnostics.add(AckJsonSchemaDiagnostic(pointer, message)); + void _fail( + String pointer, + String message, { + bool explainPropertyNameFallback = false, + }) { + final diagnostic = AckJsonSchemaDiagnostic(pointer, message); + diagnostics.add(diagnostic); + if (explainPropertyNameFallback) propertyNameDiagnostics.add(diagnostic); + } /// Validates the document shape and names, applies widenings, and gates the /// result through `Ack.fromJsonSchema`. Returns `null` on failure. @@ -859,22 +867,33 @@ final class _Translator { final entries = []; if (properties is Map) { + final wireKeysByFieldName = {}; + final generatedReferences = {'ack', _variable(hoistName)}; for (final MapEntry(key: key, value: value) in properties.entries) { final fieldPointer = '$pointer/properties/${_token(key)}'; - if (key == hoistName) { + final dartName = ackSchemaFirstDartFieldName(key); + final problem = + ackSchemaFirstWireKeyProblem(key) ?? + ackSchemaFirstFieldNameProblem( + dartName, + capturesExtras: open, + generatedReferences: generatedReferences, + ); + if (problem != null) { _fail( fieldPointer, - 'Property "$key" would have the same name as its generated ' - 'model class.', + 'Property "$key" $problem', + explainPropertyNameFallback: true, ); continue; } - final problem = ackSchemaFirstFieldNameProblem( - ackSchemaFirstDartFieldName(key), - capturesExtras: open, - ); - if (problem != null) { - _fail(fieldPointer, 'Property "$key" $problem'); + if (ackSchemaFirstFieldCollision(wireKeysByFieldName, dartName, key) + case final collision?) { + _fail( + fieldPointer, + 'Object has $collision', + explainPropertyNameFallback: true, + ); continue; } final field = _expr( diff --git a/packages/ack_generator/test/json_schema/json_schema_library_test.dart b/packages/ack_generator/test/json_schema/json_schema_library_test.dart index a8b00c52..c1fd3e57 100644 --- a/packages/ack_generator/test/json_schema/json_schema_library_test.dart +++ b/packages/ack_generator/test/json_schema/json_schema_library_test.dart @@ -59,6 +59,42 @@ Matcher _diagnostic(String pointer, String message) => .having((d) => d.message, 'message', contains(message)); void main() { + test( + 'uses validated value models when Dart property names collide or shadow', + () { + for (final (keys, diagnostic) in [ + (['@id', 'id'], 'both map to the Dart field "id"'), + (['user_id', 'userId'], 'both map to the Dart field "userId"'), + (['ack'], 'shadows the generated reference "ack"'), + (['modelSchema'], 'shadows the generated reference "modelSchema"'), + (['café'], 'non-ASCII letters'), + ]) { + final result = _generate( + _model({ + for (final key in keys) key: {'type': 'string'}, + }), + ); + expect(result.source, contains('Ack.fromJsonSchema'), reason: '$keys'); + expect(result.source, contains(diagnostic), reason: '$keys'); + expect( + result.source, + isNot(contains('@ack.Schemable')), + reason: '$keys', + ); + } + }, + ); + + test('allows a property whose wire spelling matches its model name', () { + final result = _generate( + _model({ + 'Model': {'type': 'string'}, + }), + ); + expect(result.source, contains("@ack.Schemable(name: 'Model')")); + expect(result.source, contains("'Model': ack.Ack.string().optional()")); + }); + group('maps', () { final rows = { 'a string': ({'type': 'string'}, "'f':ack.Ack.string().optional()"), From 69c958267ff579c645bf16d1444365965e61cf84 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 19:15:49 +0000 Subject: [PATCH 53/57] fix(ack)!: name the local time constraint string_time --- docs/getting-started/migration-guide.mdx | 2 +- packages/ack/CHANGELOG.md | 6 +++-- .../src/constraints/pattern_constraint.dart | 24 +++---------------- .../string_schema_extensions_test.dart | 21 ++++++++++++++++ 4 files changed, 29 insertions(+), 24 deletions(-) diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 425851d8..6d0f6183 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -170,7 +170,7 @@ and errors: | `Ack.enumCodec(MyEnum.values)` | `2.0.0` | `Ack.enumValues(MyEnum.values)` | | `ListSchema.minLength`, `maxLength`, `exactLength`, `nonEmpty` | `2.0.0` | Use `minItems`, `maxItems`, `length`, and `notEmpty`, respectively. | | `StringSchema.url()` | `2.0.0` | Use `StringSchema.uri()` for the same validation and schema export. | -| Code matching a dotted built-in constraint key | `2.0.0` | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique_items`, `number.isFinite` → `number_finite`, `integer.isSafe` → `number_safe_integer`. | +| Code matching a renamed built-in constraint key | `2.0.0` | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique_items`, `number.isFinite` → `number_finite`, `integer.isSafe` → `number_safe_integer`, `string_format_time` → `string_time`. | | `AckRule` from `package:ack/annotations.dart` | `2.0.0` | Use the concrete rule annotation type for rule-specific data, or `Object` for a mixed list. | | `implements SchemaContext` | `2.0.0` | Read the context from `SchemaError.context`. `SchemaContext` is a `base` class, so external subclasses require a `base`, `final`, or `sealed` modifier. | | `SchemaContext.transparent` | `2.0.0` | Ack creates transparent contexts while validating wrapper schemas. Read the resulting context through `SchemaError.context`. | diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 434e5596..8c3421cd 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -30,8 +30,10 @@ `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique_items`, - `number.isFinite` → `number_finite`, and - `integer.isSafe` → `number_safe_integer`. + `number.isFinite` → `number_finite`, + `integer.isSafe` → `number_safe_integer`, and + `string_format_time` → `string_time`. + `time()` exports a pattern for local `HH:MM:SS` values. * **Breaking:** Use `minItems`, `maxItems`, `length`, and `notEmpty` for lists. The duplicate list method names are removed. diff --git a/packages/ack/lib/src/constraints/pattern_constraint.dart b/packages/ack/lib/src/constraints/pattern_constraint.dart index d2c8fa72..8f503bd0 100644 --- a/packages/ack/lib/src/constraints/pattern_constraint.dart +++ b/packages/ack/lib/src/constraints/pattern_constraint.dart @@ -27,11 +27,7 @@ final class PatternConstraint extends Constraint 'string_format_uuid': 'uuid', 'string_format_datetime': 'date-time', 'string_format_date': 'date', - 'string_format_time': 'time', 'string_format_uri': 'uri', - 'string_format_ipv4': 'ipv4', - 'string_format_ipv6': 'ipv6', - 'string_format_hostname': 'hostname', }; const PatternConstraint({ @@ -166,23 +162,9 @@ final class PatternConstraint extends Constraint ); static PatternConstraint time() => PatternConstraint( - type: PatternType.format, - formatValidator: (value) { - final match = RegExp(r'^\d{2}:\d{2}:\d{2}$').firstMatch(value); - if (match == null) return false; - final parts = value.split(':').map(int.parse).toList(); - if (parts.length != 3) return false; - final hours = parts[0]; - final minutes = parts[1]; - final seconds = parts[2]; - return hours >= 0 && - hours < 24 && - minutes >= 0 && - minutes < 60 && - seconds >= 0 && - seconds < 60; - }, - constraintKey: 'string_format_time', + type: PatternType.regex, + pattern: RegExp(r'^(?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$'), + constraintKey: 'string_time', description: 'Must be a valid time in HH:MM:SS format.', example: '23:59:59', customMessageBuilder: (value) => diff --git a/packages/ack/test/schemas/extensions/string_schema_extensions_test.dart b/packages/ack/test/schemas/extensions/string_schema_extensions_test.dart index d6694785..3e3941a8 100644 --- a/packages/ack/test/schemas/extensions/string_schema_extensions_test.dart +++ b/packages/ack/test/schemas/extensions/string_schema_extensions_test.dart @@ -128,6 +128,27 @@ void main() { }); }); + test('time reports the string_time constraint key', () { + final result = Ack.string().time().safeParse('24:00:00'); + final error = result.getError() as SchemaConstraintsError; + expect(error.constraints.single.constraintKey, 'string_time'); + }); + + test('time exports a pattern for a local HH:MM:SS value', () { + final schema = Ack.string().time(); + final json = schema.toJsonSchema(); + expect(json, isNot(contains('format'))); + final pattern = RegExp(json['pattern'] as String); + for (final time in ['00:00:00', '23:59:59']) { + expect(schema.safeParse(time).isOk, isTrue); + expect(pattern.hasMatch(time), isTrue); + } + for (final time in ['24:00:00', '23:59:60', '23:59:59Z']) { + expect(schema.safeParse(time).isFail, isTrue); + expect(pattern.hasMatch(time), isFalse); + } + }); + test('should chain multiple constraints', () { final schema = StringSchema().minLength(10).email(); final result = schema.safeParse('a@b.com'); From c20d8474da88b183e22bac60d41b2ebd50507a45 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 19:16:09 +0000 Subject: [PATCH 54/57] fix(generator)!: validate class-owned schemas before emitting facades --- docs/core-concepts/typesafe-schemas.mdx | 6 +- docs/getting-started/migration-guide.mdx | 1 + packages/ack_generator/CHANGELOG.md | 4 ++ .../analyzer/class_model_graph_builder.dart | 61 ++++++++++++++----- .../integration/class_model_graph_test.dart | 19 ++++++ .../integration/type_owned_schema_test.dart | 5 +- 6 files changed, 78 insertions(+), 18 deletions(-) diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index 9282666e..b5764808 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -574,8 +574,10 @@ types because `Ack.list` has no nullable-item contract. The generated parse and encode helpers, including `toJson()` and `safeToJson()`, validate with a class's static `schema` when it declares one. -Nested class-first fields also use that schema. Use `ModelSchema.schema` as the -raw generated schema when declaring `Model.schema` with refinements. +Nested class-first fields also use that schema. The declaration must have a +non-nullable `AckSchema, Model>` type, or a subtype. +Use `ModelSchema.schema` as the raw generated schema when declaring +`Model.schema` with refinements. ### Class-first unions diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 89b8f44f..d101ac51 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -19,6 +19,7 @@ This guide summarizes **what exists in Ack today**, **what changed in 1.7 and 2. | JSON Schema properties that cannot become distinct Dart fields, such as `@id` and `id` | `2.0.0` | Automatic generation uses a validated value model. Read the original keys from `model.value`, or define a class-first model with `@AckKey` for typed fields. | | A JSON Schema property whose wire spelling matches its model name, such as `Model` | `2.0.0` | Regenerate and use the typed field, such as `model.model`, when the derived Dart name is valid. | | Class-owned schema refinements | `2.0.0` | Generated helpers and nested fields now enforce them. Compose `ModelSchema.schema` explicitly when you need the raw generated rules. | +| A nullable class-owned `schema` or one with a boundary wider than a JSON map | `2.0.0` | Declare a non-nullable `AckSchema, Model>` or a subtype. Use `ModelSchema.schema` as the base for class-owned refinements. | | Schema-first fields using snake_case or another wire spelling | `2.0.0` | Regenerate and use the lowerCamelCase Dart names in field accesses, constructors and `copyWith`. JSON keys keep their original spelling. | | The direct `ackModelBuilder` factory | `2.0.0` | Use the shared `ack_generator:ack_generator` builder with source_gen’s combining builder. | | Generated `Set` fields that previously accepted duplicate JSON items | `2.0.0` | Remove duplicates or use `List` when duplicates must be accepted. Exported schemas now include `uniqueItems: true` for these fields. | diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index b0012a4e..17d5472c 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -2,6 +2,10 @@ ### Breaking +* **Breaking:** A class-owned model `schema` must have a non-nullable + `AckSchema, Model>` type or a subtype. The generator + reports incompatible declarations before emitting code. + * **Breaking:** A JSON Schema property whose wire spelling matches its model name can now generate a typed field when its Dart field name is distinct. Regenerate and update callers that used the previous value model. diff --git a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart index 1940ff8d..6cb80ade 100644 --- a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart @@ -118,7 +118,13 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { element: element, ); } - _validateStaticSchema(element); + if (element.getGetter('schema') case final getter? when getter.isStatic) { + _validateStaticSchema( + element, + getter, + '${_facadeName(element, options)}.schema', + ); + } await _buildObject(element, options: options); } _rejectRecursiveClassFirstGraphs(); @@ -231,22 +237,49 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { /// /// The facade is generated in this build, so the type is checked only once /// it resolves. - void _validateStaticSchema(ClassElement element) { - final getter = element.getGetter('schema'); - if (getter == null || - !getter.isStatic || - containsInvalidType(getter.returnType)) { - return; + void _validateStaticSchema( + ClassElement element, + GetterElement getter, + String facadeSchema, + ) { + final type = getter.returnType; + if (containsInvalidType(type)) return; + if (type is DynamicType) { + final resolved = inputResolved!; + final declaration = propertyDeclaration(getter); + final node = declarationNode(resolved, declaration); + final inferred = switch (node) { + VariableDeclaration(parent: VariableDeclarationList(type: null)) || + MethodDeclaration(returnType: null) => true, + _ => false, + }; + if (inferred && + declarationExpression( + resolved, + declaration, + )?.unParenthesized.toSource() == + facadeSchema) { + return; + } } - final runtime = ackSchemaRuntimeType(getter.returnType); - if (runtime != null && - sameTypeIgnoringNullability(runtime, element.thisType)) { + + final arguments = ackSchemaTypeArguments(type); + final provider = element.library.typeProvider; + final jsonMap = provider.mapType( + provider.stringType, + provider.objectQuestionType, + ); + if (type.nullabilitySuffix == NullabilitySuffix.none && + arguments != null && + element.library.typeSystem.isSubtypeOf(arguments.boundary, jsonMap) && + arguments.runtime.nullabilitySuffix == NullabilitySuffix.none && + sameTypeIgnoringNullability(arguments.runtime, element.thisType)) { return; } throw InvalidGenerationSource( - '${element.name}.schema must be an AckSchema, ' - '${element.name}>; it produces ' - '${runtime?.getDisplayString() ?? 'an untyped value'}.', + '${element.name}.schema must be a non-nullable ' + 'AckSchema, ${element.name}>. ' + 'Its declared type is ${type.getDisplayString()}.', element: getter, ); } @@ -269,7 +302,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { if (member is GetterElement && element.getSetter('schema')?.isStatic != true && expression?.unParenthesized.toSource() == facadeSchema) { - // The facade in a clean build has no resolved type yet. + _validateStaticSchema(element, member, facadeSchema); return; } diff --git a/packages/ack_generator/test/integration/class_model_graph_test.dart b/packages/ack_generator/test/integration/class_model_graph_test.dart index 5a3ebe3f..d398d651 100644 --- a/packages/ack_generator/test/integration/class_model_graph_test.dart +++ b/packages/ack_generator/test/integration/class_model_graph_test.dart @@ -80,6 +80,25 @@ class Base { ); }); + test('rejects class-owned schemas with an incompatible shape', () async { + for (final declaration in [ + 'static final AckSchema schema = BoxSchema.schema;', + 'static AckSchema, Box>? get schema => BoxSchema.schema;', + ]) { + await _expectFailure( + ''' +@Schemable() +final class Box with _\$BoxAck { + const Box({required this.id}); + final int id; + $declaration +} +''', + ['Box.schema', 'non-nullable', 'AckSchema, Box>'], + ); + } + }); + for (final (owner, baseSchema, branchSchema) in [ ( 'Shape', diff --git a/packages/ack_generator/test/integration/type_owned_schema_test.dart b/packages/ack_generator/test/integration/type_owned_schema_test.dart index 59b4d801..4fb87880 100644 --- a/packages/ack_generator/test/integration/type_owned_schema_test.dart +++ b/packages/ack_generator/test/integration/type_owned_schema_test.dart @@ -375,8 +375,9 @@ final class Habit with _$HabitAck { errors, contains( contains( - 'Habit.schema must be an AckSchema, Habit>; ' - 'it produces String.', + 'Habit.schema must be a non-nullable ' + 'AckSchema, Habit>. ' + 'Its declared type is StringSchema.', ), ), ); From 77b9d02b43e04f4e7c95d07d84fa81b854e1c3a6 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 19:16:18 +0000 Subject: [PATCH 55/57] fix(generator)!: reject explicit case style on schemas and libraries --- docs/getting-started/migration-guide.mdx | 1 + packages/ack_generator/CHANGELOG.md | 3 +++ .../analyzer/schema_model_graph_builder.dart | 2 +- .../lib/src/model_generator.dart | 2 +- .../integration/ack_infer_graph_test.dart | 2 +- .../integration/class_model_graph_test.dart | 22 +++++++++++++++++++ 6 files changed, 29 insertions(+), 3 deletions(-) diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index d101ac51..0b03be45 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -15,6 +15,7 @@ This guide summarizes **what exists in Ack today**, **what changed in 1.7 and 2. | Schema-first fields, discriminators, and inline JSON Schema model names | `2.0.0` | Regenerate and update Dart callers. Digits before uppercase letters and acronym boundaries affect names such as `ipv4Address` and `urlIsValid`. Inline model segments normalize acronyms, for example `UserID` → `UserId`. Use a class-first model with `@AckKey` for keys containing non-ASCII letters, keys mapping to a reserved word such as `default`, and collisions. | | Implicit field style on an annotated branch of a styled sealed class | `2.0.0` | Regenerate to inherit the base’s style. Use `caseStyle: AckCaseStyle.none` on the branch to retain Dart names on the wire. | | Code that reads `Schemable.caseStyle` as non-null | `2.0.0` | Handle a null style as unspecified. Use `annotation.caseStyle ?? AckCaseStyle.none` when you need the standalone default. | +| `caseStyle: AckCaseStyle.none` on a top-level schema or library annotation | `2.0.0` | Remove the class-only option from the annotation. | | A super parameter whose inherited default references a declaration you cannot access | `2.0.0` | Import the declaration used in the default, or give the super parameter an explicit default. | | JSON Schema properties that cannot become distinct Dart fields, such as `@id` and `id` | `2.0.0` | Automatic generation uses a validated value model. Read the original keys from `model.value`, or define a class-first model with `@AckKey` for typed fields. | | A JSON Schema property whose wire spelling matches its model name, such as `Model` | `2.0.0` | Regenerate and use the typed field, such as `model.model`, when the derived Dart name is valid. | diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 17d5472c..6a55b028 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -2,6 +2,9 @@ ### Breaking +* **Breaking:** Explicit `caseStyle: AckCaseStyle.none` is rejected on + top-level schema and library annotations. Omit the class-only option there. + * **Breaking:** A class-owned model `schema` must have a non-nullable `AckSchema, Model>` type or a subtype. The generator reports incompatible declarations before emitting code. diff --git a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart index 1363c5ea..95beae7d 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart @@ -138,7 +138,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { final configured = [ if (!reader.read('schemaName').isNull) 'schemaName', if (!reader.read('description').isNull) 'description', - if ((index('caseStyle') ?? 0) != 0) 'caseStyle', + if (!reader.read('caseStyle').isNull) 'caseStyle', if (!reader.read('discriminatorKey').isNull) 'discriminatorKey', if (!reader.read('discriminatorValue').isNull) 'discriminatorValue', if (index('unknownProperties') != 0) 'unknownProperties', diff --git a/packages/ack_generator/lib/src/model_generator.dart b/packages/ack_generator/lib/src/model_generator.dart index bfd915c2..915877ce 100644 --- a/packages/ack_generator/lib/src/model_generator.dart +++ b/packages/ack_generator/lib/src/model_generator.dart @@ -211,7 +211,7 @@ final class AckModelGenerator extends Generator { if (!reader.read('name').isNull) 'name', if (!reader.read('schemaName').isNull) 'schemaName', if (!reader.read('description').isNull) 'description', - if ((index('caseStyle') ?? 0) != 0) 'caseStyle', + if (!reader.read('caseStyle').isNull) 'caseStyle', if (!reader.read('discriminatorKey').isNull) 'discriminatorKey', if (!reader.read('discriminatorValue').isNull) 'discriminatorValue', if (index('unknownProperties') != 0) 'unknownProperties', diff --git a/packages/ack_generator/test/integration/ack_infer_graph_test.dart b/packages/ack_generator/test/integration/ack_infer_graph_test.dart index ccce55ce..b2230fe6 100644 --- a/packages/ack_generator/test/integration/ack_infer_graph_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_graph_test.dart @@ -397,7 +397,7 @@ class Money { ''' $_head @Schemable( - caseStyle: AckCaseStyle.snake, + caseStyle: AckCaseStyle.none, description: 'A user.', schemaName: 'UserWire', ) diff --git a/packages/ack_generator/test/integration/class_model_graph_test.dart b/packages/ack_generator/test/integration/class_model_graph_test.dart index d398d651..dfe05696 100644 --- a/packages/ack_generator/test/integration/class_model_graph_test.dart +++ b/packages/ack_generator/test/integration/class_model_graph_test.dart @@ -51,6 +51,28 @@ part 'model.g.dart'; '''; void main() { + test('rejects explicit caseStyle none on a library annotation', () async { + await _expectFailure( + r''' +AckSchema textSchema() => Ack.string(); + +@Schemable() +final class Model with _$ModelAck { + const Model({required this.id}); + final int id; +} +''', + ['@Schemable on a library directive only supports schemas', 'caseStyle'], + head: ''' +@Schemable(caseStyle: AckCaseStyle.none, schemas: [textSchema]) +library; + +import 'package:ack/ack.dart'; +part 'model.g.dart'; +''', + ); + }); + test('reports a hidden constant used by a super-parameter default', () async { await _expectFailure( r''' From 9dd7f71f8a5d0dcd25518771d4e9f51ccb05d0c9 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 19:17:03 +0000 Subject: [PATCH 56/57] fix(ack): infer the lazy context parent type --- packages/ack/lib/src/context.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ack/lib/src/context.dart b/packages/ack/lib/src/context.dart index 3396b479..b78a1205 100644 --- a/packages/ack/lib/src/context.dart +++ b/packages/ack/lib/src/context.dart @@ -91,7 +91,7 @@ final class _LazyRecursionContext extends SchemaContext { required super.name, required super.schema, required super.value, - required SchemaContext super.parent, + required super.parent, required super.operation, required this.recursionToken, }) : super._transparent(); From d3c8eaa9aad579095a05115ca37e56cb257d826f Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Tue, 1 Dec 2026 19:17:28 +0000 Subject: [PATCH 57/57] docs(generator): clarify class-owned schema type requirements --- docs/core-concepts/typesafe-schemas.mdx | 5 +++-- docs/getting-started/migration-guide.mdx | 2 +- packages/ack_generator/CHANGELOG.md | 7 ++++--- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index b5764808..7e4ea13a 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -574,8 +574,9 @@ types because `Ack.list` has no nullable-item contract. The generated parse and encode helpers, including `toJson()` and `safeToJson()`, validate with a class's static `schema` when it declares one. -Nested class-first fields also use that schema. The declaration must have a -non-nullable `AckSchema, Model>` type, or a subtype. +Nested class-first fields also use that schema. The declaration must be a +non-nullable `AckSchema` with the model as its runtime type and a boundary +type assignable to `Map`. Use `ModelSchema.schema` as the raw generated schema when declaring `Model.schema` with refinements. diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 0b03be45..377e054e 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -20,7 +20,7 @@ This guide summarizes **what exists in Ack today**, **what changed in 1.7 and 2. | JSON Schema properties that cannot become distinct Dart fields, such as `@id` and `id` | `2.0.0` | Automatic generation uses a validated value model. Read the original keys from `model.value`, or define a class-first model with `@AckKey` for typed fields. | | A JSON Schema property whose wire spelling matches its model name, such as `Model` | `2.0.0` | Regenerate and use the typed field, such as `model.model`, when the derived Dart name is valid. | | Class-owned schema refinements | `2.0.0` | Generated helpers and nested fields now enforce them. Compose `ModelSchema.schema` explicitly when you need the raw generated rules. | -| A nullable class-owned `schema` or one with a boundary wider than a JSON map | `2.0.0` | Declare a non-nullable `AckSchema, Model>` or a subtype. Use `ModelSchema.schema` as the base for class-owned refinements. | +| A nullable class-owned `schema` or one with a boundary wider than a JSON map | `2.0.0` | Declare a non-nullable `AckSchema, Model>`. A narrower boundary type is also valid. Use `ModelSchema.schema` as the base for class-owned refinements. | | Schema-first fields using snake_case or another wire spelling | `2.0.0` | Regenerate and use the lowerCamelCase Dart names in field accesses, constructors and `copyWith`. JSON keys keep their original spelling. | | The direct `ackModelBuilder` factory | `2.0.0` | Use the shared `ack_generator:ack_generator` builder with source_gen’s combining builder. | | Generated `Set` fields that previously accepted duplicate JSON items | `2.0.0` | Remove duplicates or use `List` when duplicates must be accepted. Exported schemas now include `uniqueItems: true` for these fields. | diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 6a55b028..a842ffe0 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -5,9 +5,10 @@ * **Breaking:** Explicit `caseStyle: AckCaseStyle.none` is rejected on top-level schema and library annotations. Omit the class-only option there. -* **Breaking:** A class-owned model `schema` must have a non-nullable - `AckSchema, Model>` type or a subtype. The generator - reports incompatible declarations before emitting code. +* **Breaking:** A class-owned model `schema` must be a non-nullable + `AckSchema` with the model as its runtime type and a boundary assignable + to `Map`. The generator reports incompatible declarations + before emitting code. * **Breaking:** A JSON Schema property whose wire spelling matches its model name can now generate a typed field when its Dart field name is distinct.