diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1b4f1e03..d82b2881 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,6 +56,7 @@ jobs: test/schemas/extensions/numeric_extensions_test.dart \ test/schemas/extensions/list_schema_extensions_test.dart \ test/utils/collection_utils_test.dart \ + test/json_schema_idna_decode_failure_test.dart \ test/json_schema_import_test.dart \ test/json_schema_bundled_dialect_test.dart \ test/json_schema_vocabulary_contract_test.dart \ diff --git a/docs/core-concepts/validation.mdx b/docs/core-concepts/validation.mdx index 0ee2ae05..3154e584 100644 --- a/docs/core-concepts/validation.mdx +++ b/docs/core-concepts/validation.mdx @@ -163,8 +163,9 @@ These methods live directly on `StringSchema` and normalize the string in declaration order alongside constraints during both `parse` and `encode`. Because they return `StringSchema`, you can continue chaining string constraints (`Ack.string().trim().minLength(2)`), use them inside `@Schemable()` -models, and export them to JSON Schema as `type: 'string'` without -`'x-transformed': true`. +models, and export the string type. The export of +`Ack.string().trim().minLength(2)` is `{ "type": "string" }` because the minimum +applies to the trimmed text. Keep the native schema for that validation. ### `trim()` Removes leading and trailing whitespace on parse and encode. diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index 9a47447d..b4146ba8 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -188,6 +188,11 @@ annotations from `package:ack/ack.dart`. Code that reads a rule’s former | `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)` | +| Draft-7 `dependencies` passed to `Ack.fromJsonSchema` | `2.0.0` | Convert the resource to Draft 2020-12. Use `dependentRequired` for property lists and `dependentSchemas` for schema dependencies. | +| Lowering an imported Draft 2020-12 schema that contains `dependencies` to Draft-7 | `2.0.0` | Use `toJsonSchema()` to preserve the original document, or remove the ignored `dependencies` keyword before calling `toJsonSchemaDraft7()`. | +| A quoted email local part has unbalanced or misplaced quotes | `2.0.0` | Imported `email` and `idn-email` assertions reject it. Provide a valid email address. | +| Imported hostname or email domain assertions that relied on lowercasing non-ASCII labels | `2.0.0` | Ack lowercases ASCII only. Supply labels valid under IDNA2008, such as the permitted lowercase form of a disallowed Unicode capital letter. | +| `AckRawSchemaModel(indexedSchemas: …)` | `2.0.0` | Omit the internal schema index when constructing a raw schema model. | | `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 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`. | diff --git a/docs/guides/json-schema-integration.mdx b/docs/guides/json-schema-integration.mdx index 815a9710..b6673780 100644 --- a/docs/guides/json-schema-integration.mdx +++ b/docs/guides/json-schema-integration.mdx @@ -4,16 +4,27 @@ title: JSON Schema Integration Your Ack [schema](../core-concepts/schemas.mdx) already describes your data's shape — so you can import and export JSON Schema (preserving Draft 2020-12 resources for imported schemas and emitting Draft-7 for native schemas) and reuse it to document an API, drive a form library, or define an LLM tool, all from one source of truth. +Draft-7 imports reject the `dependencies` keyword. Convert the schema to Draft +2020-12 and use `dependentRequired` or `dependentSchemas`. + Imported schemas share the parse input limit of 100 nested lists or maps along any path. ## Importing published schemas +Import schemas from sources you trust. The cost of compiling and validating a +schema can grow with nested composition and repeated references. Reuse the +compiled validator when checking multiple values against the same schema. +A `$dynamicRef` cycle or a schema nested several thousand levels deep can +throw `StackOverflowError` during import +([tracked for 2.0.x in #279](https://github.com/btwld/ack/issues/279)). + Use strict `Ack.fromJsonSchema()` to turn a decoded JSON Schema document (a map or boolean, not a JSON string) into an `AckSchema`. The input dialect is draft 2020-12 or Draft-7 -(`http(s)://json-schema.org/draft-07/schema(#)`), including when `$schema` is -absent. Other explicitly declared dialects are rejected. +(`http(s)://json-schema.org/draft-07/schema(#)`). Ack reads a document without +`$schema` as Draft 2020-12 and ignores `dependencies` in that document. +Other explicitly declared dialects are rejected. Only the declared `$schema` string is checked — a document is never matched against a dialect by shape. Draft-7 documents are evaluated under the same @@ -104,8 +115,10 @@ input mapping. The data is bundled; validation does not fetch it at runtime. Ack does not bundle Unicode normalization tables, so its core has no extra dependencies. ASCII hostnames and email addresses need nothing more, except that `xn--` A-labels are checked for normalized form only when a normalizer is -given. For full IDNA normalization of international names, pass an NFKC -function as `unicodeNormalizer`, for example from `package:unorm_dart`: +given. Pass an NFKC function as `unicodeNormalizer` to map compatibility +forms such as full-width letters. Ack lowercases ASCII letters only. After +normalization, non-ASCII uppercase letters disallowed by IDNA2008 are +rejected. With `unorm.nfkc`, `EXAMPLE.com` passes and `MÜNCHEN.de` fails. ```dart import 'package:unorm_dart/unorm_dart.dart' as unorm; @@ -197,7 +210,8 @@ imported Draft 2020-12 resources by default** (`$defs`, `$dynamicRef`, self-contained Draft-7 document with root-scoped `definitions` and rewritten references, call `schema.toJsonSchemaDraft7()` or `schema.toSchemaModelDraft7()` (which throws `UnsupportedError` if the imported schema relies on 2020-12-only -semantics). +semantics). Format annotations are preserved. An asserted `format` causes +lowering to report the keyword and its JSON Pointer. ### Generating Dart models from `.schema.json` files @@ -215,8 +229,14 @@ targets: - lib/**/*.schema.json options: assert_formats: false + normalize_unicode: false ``` +Set `normalize_unicode: true` to apply NFKC normalization when generated +validators assert international hostname and email formats. Add `unorm_dart` +to the consuming package's runtime `dependencies` with +`dart pub add unorm_dart` before building. + `ack_generator:ack_json_schema` emits `.schema.dart` (declaring `part '.schema.g.dart';`), which `ack_generator:ack_generator` compiles in the same `dart run build_runner build` pass: @@ -355,11 +375,18 @@ Use `toSchemaModel()` for a reusable, target-independent view of an Ack schema: final model = userSchema.toSchemaModel(); final jsonSchemaMap = model.toJsonSchema(); -for (final warning in model.warnings) { - print('${warning.code}: ${warning.message}'); +for (final warning in model.allWarnings) { + print('${warning.path} ${warning.code}: ${warning.message}'); } ``` +`model.warnings` holds the node's own warnings. The builder leaves their +`path` null. `model.allWarnings` yields the node's warnings first, then its +definition warnings, then its descendants' warnings. It fills null paths with +fragment JSON Pointers like `#` and `#/anyOf/0/properties/a~1b`, using RFC 6901 +token escaping without percent-encoding. It rebases any supplied +`#`-prefixed path to the warning's node and passes other paths through unchanged. + `AckSchemaModel` describes the boundary values a schema accepts and exports, keeping adapter metadata such as property ordering and discriminator info. Its JSON Schema renderer emits only generic Draft-7-compatible output; provider-specific hints belong in adapter renderers. **Output JSON (JSON Schema Object):** @@ -542,9 +569,11 @@ The nested nullable-union shape is intentional for generic Draft-7 output and ma - **Date/time range constraints:** Draft-7 has no standard `formatMinimum` or `formatMaximum` keywords. ACK validates `.min()` and `.max()` at runtime and records schema-model warnings instead of rendering non-standard keywords. -- **List item nullability:** `Ack.list(...)` does not support nullable item - schemas yet. Make the list itself nullable with `Ack.list(item).nullable()` - when the whole field may be null. +- **List item nullability:** `Ack.list(item)` requires a schema that rejects + null items. An imported schema without an explicit non-null type may admit + null. Use `Ack.list(item.nullable(value: false))` to explicitly reject null elements, + or import the entire array schema to preserve nullable item behavior. + Use `Ack.list(item).nullable()` when the whole list may be null. - **Discriminated branches:** `Ack.discriminated(...)` owns the discriminator. Branches may omit the discriminator field; compatible `Ack.literal(...)` or `Ack.enumString(...)` fields are accepted; generated branches expose the diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 1619cf24..ee299ad6 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -2,6 +2,17 @@ ### Breaking +* **Breaking:** The public `AckRawSchemaModel` constructor no longer accepts + the importer’s internal schema index. + +* **Breaking:** Imported `email` and `idn-email` format assertions now + reject malformed quoting in the local part. + +* **Breaking:** Draft-7 import rejects `dependencies` with + `unsupported_keyword` instead of silently ignoring the assertion. + Draft-7 lowering also rejects `dependencies` in imported 2020-12 schemas + and reports the keyword's JSON Pointer. + * **Breaking:** `Schemable.caseStyle` is now an `AckCaseStyle?`. An omitted style is null. Use `AckCaseStyle.none` for an explicit override. @@ -92,11 +103,24 @@ pass. This includes `xn--` A-labels in plain `hostname` and `email` values. Other ASCII hostnames and email addresses are not affected. +* **Breaking:** International hostname and email domain assertions lowercase + ASCII letters only. After optional NFKC normalization, non-ASCII uppercase + letters disallowed by IDNA2008 are rejected on every platform. IDNA-valid + Cherokee letters remain valid. + * **Breaking:** An object field with `withDefault` before a transform or codec is omitted from the exported JSON Schema `required` list. ### Changed +* Document trusted sources and validator reuse for JSON Schema imports, the + default Draft 2020-12 dialect, and when imports can overflow the stack. + +* Document the ordering, escaping, and rebasing of schema-model warning paths. + +* Clarify that NFKC maps compatibility forms and IDNA case mapping only + lowercases ASCII letters. + * Support `AckSchema.forGeneratedField` as a generated-code entry point returning `AckSchema`. @@ -112,6 +136,27 @@ ### Fixed +* Collect nested JSON Schema export warnings with JSON Pointers through + `AckSchemaModel.allWarnings`, including warnings from nullable branches and + lazy definitions. +* Export nullable raw schema models without a resource ID, and clarify why + an imported nullable item schema cannot be passed to `Ack.list`. +* Rewrite local references in nullable raw schema models created with the public + constructor, including recursive references and resource IDs ending in `#`. + +* Accept year `0000` in imported `date` assertions, matching `date-time`. + +* Preserve format annotations when lowering an imported schema to Draft-7. + An asserted format reports its keyword and JSON Pointer. +* Include the retrieval URI in Draft-7 lowering errors for external documents + and report unsupported property conversions with a single error prefix. + +* Export `Ack.string().ip()` with `anyOf` so valid IPv4 and IPv6 addresses + pass when `format` is an annotation. + +* Reject hostname labels over 63 Unicode code points before Punycode + conversion in hostname and email format assertions. + * Clarify that exhaustive switches are supported for `SchemaError`. A switch over the public `AckSchema` types needs a fallback branch. @@ -173,6 +218,11 @@ Wrapper contexts such as anyOf, lazy, boundary, and discriminated objects still add no path segment. +### Internal + +* Add the `@internal` constructor `AckRawSchemaModel.indexed` for resources + already indexed by the JSON Schema importer. + ## 2.0.0-beta.3 ### Breaking diff --git a/packages/ack/lib/src/ack.dart b/packages/ack/lib/src/ack.dart index befe34b4..34ccd0c6 100644 --- a/packages/ack/lib/src/ack.dart +++ b/packages/ack/lib/src/ack.dart @@ -15,6 +15,14 @@ final class Ack { /// a supplied dialect requiring the format-assertion vocabulary also enables /// them. Unknown asserted formats are rejected when compiling. /// Unsupported semantics throw [JsonSchemaImportException]. + /// A document without `$schema` is read as Draft 2020-12, which ignores + /// `dependencies`. + /// + /// Import schema documents from sources you trust. Compilation and + /// validation costs depend on the shape of the schema. A `$dynamicRef` + /// cycle or a schema nested several thousand levels deep can throw + /// [StackOverflowError] during import + /// ([tracked for 2.0.x in #279](https://github.com/btwld/ack/issues/279)). /// /// [unicodeNormalizer] supplies Unicode NFKC normalization for the /// international hostname checks used by `hostname`, `idn-hostname`, @@ -26,8 +34,10 @@ final class Ack { /// can pass. Without one, an `xn--` A-label whose decoded label is not /// normalized can also pass; other ASCII hostnames and email addresses do /// not need it. Pass a function such as `nfkc` from `package:unorm_dart` - /// for full IDNA normalization. The normalizer is not part of the exported - /// JSON Schema. + /// to map compatibility forms such as full-width letters. Ack lowercases + /// ASCII letters only. After normalization, non-ASCII uppercase letters + /// disallowed by IDNA2008 are rejected. Exported JSON Schema omits the + /// normalizer. static AckSchema fromJsonSchema( Object document, { Uri? baseUri, diff --git a/packages/ack/lib/src/constraints/string_ip_constraint.dart b/packages/ack/lib/src/constraints/string_ip_constraint.dart index a185605b..336a09f5 100644 --- a/packages/ack/lib/src/constraints/string_ip_constraint.dart +++ b/packages/ack/lib/src/constraints/string_ip_constraint.dart @@ -44,8 +44,9 @@ final class StringIpConstraint extends Constraint if (version == 4) return {'format': 'ipv4'}; if (version == 6) return {'format': 'ipv6'}; + // Both branches can match when format is an annotation. return { - 'oneOf': [ + 'anyOf': [ {'format': 'ipv4'}, {'format': 'ipv6'}, ], diff --git a/packages/ack/lib/src/json_schema/json_schema_compiler.dart b/packages/ack/lib/src/json_schema/json_schema_compiler.dart index c792202b..11602bb8 100644 --- a/packages/ack/lib/src/json_schema/json_schema_compiler.dart +++ b/packages/ack/lib/src/json_schema/json_schema_compiler.dart @@ -175,12 +175,20 @@ final class _ImportedNode { /// The Draft-7 representation of an imported node, used by /// `toJsonSchemaDraft7()`. 2020-12 assertions that cannot be lowered fail. - Map renderDraft7(String Function(_ImportedNode) refOf) { - // Draft-7 silently ignores these keywords (and applies `items` to the - // entire array instead of only the suffix after `prefixItems`). Until a - // semantics-preserving lowering exists, fail instead of changing which - // instances the exported schema accepts. + Map renderDraft7( + String Function(_ImportedNode) refOf, { + required Uri rootDocumentUri, + }) { + String location(String keyword) { + final pointer = _keywordPointer(this, keyword); + return documentUri == rootDocumentUri ? pointer : '$documentUri$pointer'; + } + + // Draft-7 treats `dependencies` as an assertion and ignores the 2020-12 + // keywords below. It also applies `items` to the entire array when + // `prefixItems` is present. Reject lowering that would change validation. const unsupportedKeywords = { + 'dependencies', 'prefixItems', 'dependentRequired', 'dependentSchemas', @@ -193,17 +201,19 @@ final class _ImportedNode { for (final keyword in unsupportedKeywords) { if (isKeywordActive(keyword) && document.containsKey(keyword)) { throw UnsupportedError( - 'Cannot lower "$keyword" at ${_keywordPointer(this, keyword)} ' + 'Cannot lower "$keyword" at ${location(keyword)} ' 'with toJsonSchemaDraft7(); use toJsonSchema() for 2020-12 semantics.', ); } } } - if (dynamicReference != null || - dynamicAnchorName != null || - (isKeywordActive('format') && - source is Map && - (source as Map).containsKey('format'))) { + if (formatAssertion && format != null) { + throw UnsupportedError( + 'Cannot lower asserted "format" at ${location('format')} ' + 'with toJsonSchemaDraft7(); use toJsonSchema() to preserve the assertion.', + ); + } + if (dynamicReference != null || dynamicAnchorName != null) { throw UnsupportedError( 'This imported schema needs 2020-12 semantics and cannot be lowered ' 'with toJsonSchemaDraft7().', @@ -799,6 +809,15 @@ final class _JsonSchemaCompiler { _fail(node, key, 'Expected a positive finite number.'); } node.keywords[key] = node.multipleOf = value; + } else if (key == 'dependencies' && + draft7Dialects.contains(node.dialectUri)) { + _fail( + node, + key, + 'Draft-7 dependencies are unsupported. In Draft 2020-12, use ' + 'dependentRequired for property lists and dependentSchemas for schemas.', + code: 'unsupported_keyword', + ); } else if (key == 'uniqueItems') { if (value is! bool) _fail(node, key, 'Expected a boolean.'); node.keywords[key] = node.uniqueItems = value; diff --git a/packages/ack/lib/src/json_schema/json_schema_formats.dart b/packages/ack/lib/src/json_schema/json_schema_formats.dart index 735ff7d3..752f4585 100644 --- a/packages/ack/lib/src/json_schema/json_schema_formats.dart +++ b/packages/ack/lib/src/json_schema/json_schema_formats.dart @@ -124,7 +124,7 @@ bool _isFullDate(String value) { final year = int.parse(match[1]!); final month = int.parse(match[2]!); final day = int.parse(match[3]!); - if (year == 0 || month < 1 || month > 12 || day < 1) return false; + if (month < 1 || month > 12 || day < 1) return false; final leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); final days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; return day <= days[month - 1]; @@ -234,6 +234,12 @@ bool _isRegex(String value) { } } +// Let the IDNA2008 data decide whether non-ASCII code points are valid. +String _lowercaseIdna(String value) => String.fromCharCodes([ + for (final rune in value.runes) + if (rune >= 0x41 && rune <= 0x5a) rune + 0x20 else rune, +]); + // Without a normalizer, Unicode input is checked as given: IDNA2008 code point // rules, CONTEXTJ/CONTEXTO and Bidi rules still apply, but compatibility // mappings (such as full-width letters) and composition are not applied. @@ -245,13 +251,15 @@ bool _isHostname( if (!international && value.runes.any((rune) => rune > 127)) return false; final nfkc = normalizer ?? _identityNormalizer; final mapped = international - ? nfkc(value.replaceAll(RegExp('[。.。]'), '.').replaceAll('\u200b', '')) - .toLowerCase() + ? _lowercaseIdna( + nfkc(value.replaceAll(RegExp('[。.。]'), '.').replaceAll('\u200b', '')), + ) : value.toLowerCase(); if (mapped.isEmpty) return false; final asciiLabels = []; final unicodeLabels = []; for (final rawLabel in mapped.split('.')) { + if (rawLabel.runes.length > 63) return false; if (rawLabel.isEmpty || rawLabel.startsWith('-') || rawLabel.endsWith('-')) { @@ -270,7 +278,7 @@ bool _isHostname( if (label.isEmpty || label.runes.every((rune) => rune < 128)) { return false; } - label = nfkc(label).toLowerCase(); + label = _lowercaseIdna(nfkc(label)); if (_punycodeEncode(label) != rawLabel.substring(4)) { return false; } @@ -457,7 +465,7 @@ bool _isEmail( required bool international, _UnicodeNormalizer? normalizer, }) { - final match = RegExp(r'^("(?:[^"\\]|\\[\s\S])*"|[^@]+)@(.+)$') + final match = RegExp(r'^("(?:[^"\\]|\\[\s\S])*"|[^"@]+)@(.+)$') .firstMatch(value); if (match == null) return false; final local = match[1]!; @@ -466,7 +474,6 @@ bool _isEmail( return false; } if (local.startsWith('"')) { - if (!local.endsWith('"')) return false; if (RegExp(r'[\u0000-\u001f\u007f]').hasMatch(local)) return false; } else { final atom = international 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 b061aba7..8aebde13 100644 --- a/packages/ack/lib/src/schema_model/ack_schema_model.dart +++ b/packages/ack/lib/src/schema_model/ack_schema_model.dart @@ -34,6 +34,7 @@ final class _AckSchemaModelCommon { this.nullable = false, this.defaultValue, this.warnings = const [], + this.definitionWarnings = const [], this.extensions = const {}, }); @@ -42,6 +43,7 @@ final class _AckSchemaModelCommon { final bool nullable; final Object? defaultValue; final List warnings; + final List definitionWarnings; final Map extensions; _AckSchemaModelCommon copyWith({ @@ -50,6 +52,7 @@ final class _AckSchemaModelCommon { bool? nullable, Object? defaultValue = _unset, List? warnings, + List? definitionWarnings, Map? extensions, }) { return _AckSchemaModelCommon( @@ -62,6 +65,7 @@ final class _AckSchemaModelCommon { ? this.defaultValue : defaultValue, warnings: warnings ?? this.warnings, + definitionWarnings: definitionWarnings ?? this.definitionWarnings, extensions: extensions ?? this.extensions, ); } @@ -134,7 +138,7 @@ sealed class AckSchemaModel { this.defaultValue, this.warnings = const [], this.extensions = const {}, - }); + }) : _definitionWarnings = const []; AckSchemaModel._(_AckSchemaModelCommon common) : title = common.title, @@ -142,21 +146,84 @@ sealed class AckSchemaModel { nullable = common.nullable, defaultValue = common.defaultValue, warnings = common.warnings, + _definitionWarnings = common.definitionWarnings, extensions = common.extensions; final String? title; final String? description; final bool nullable; final Object? defaultValue; + + /// Warnings attached directly to this schema model. Use [allWarnings] to + /// include warnings from definitions and descendants. final List warnings; + final List _definitionWarnings; final Map extensions; + /// Export warnings in order from this node, its definitions, and then its + /// descendants. + /// + /// A null [AckSchemaModelWarning.path] becomes the node's fragment JSON + /// Pointer, such as `#` or `#/anyOf/0/properties/a~1b`. Pointers use RFC + /// 6901 token escaping without percent-encoding. A path starting with `#` + /// is rebased to that node's location. Other paths pass through unchanged. + Iterable get allWarnings => _warningsAt('#'); + + Iterable _warningsAt(String path) sync* { + for (final warning in warnings.followedBy(_definitionWarnings)) { + final localPath = warning.path; + yield AckSchemaModelWarning( + code: warning.code, + message: warning.message, + context: warning.context, + path: localPath == null + ? path + : localPath.startsWith('#') + ? '$path${localPath.substring(1)}' + : localPath, + ); + } + final wrapsNull = switch (this) { + _AckCompositionSchemaModel(:final schemas) => _wrapsNullableComposition( + schemas, + ), + _ => nullable, + }; + final childPath = wrapsNull ? '$path/anyOf/0' : path; + switch (this) { + case AckObjectSchemaModel(:final properties, :final additionalProperties): + for (final entry + in properties?.entries ?? + const >[]) { + final key = escapeJsonPointerToken(entry.key); + yield* entry.value._warningsAt('$childPath/properties/$key'); + } + if (additionalProperties case AckAdditionalPropertiesSchema( + :final schema, + )) { + yield* schema._warningsAt('$childPath/additionalProperties'); + } + case AckArraySchemaModel(:final items?): + yield* items._warningsAt('$childPath/items'); + case _AckCompositionSchemaModel( + :final schemas, + :final _compositionKeyword, + ): + for (var i = 0; i < schemas.length; i++) { + yield* schemas[i]._warningsAt('$childPath/$_compositionKeyword/$i'); + } + default: + break; + } + } + _AckSchemaModelCommon get _common => _AckSchemaModelCommon( title: title, description: description, nullable: nullable, defaultValue: defaultValue, warnings: warnings, + definitionWarnings: _definitionWarnings, extensions: extensions, ); @@ -181,8 +248,35 @@ sealed class AckSchemaModel { AckSchemaModel withWarnings(List warnings) => _rebuildWithCommon(_common.copyWith(warnings: warnings)); + /// Collects warnings from lazy targets before their models are discarded. + @internal + AckSchemaModel withDefinitionWarnings(Map definitions) { + final definitionWarnings = [ + for (final entry in definitions.entries) + if (entry.value case final AckSchemaModel model) + ...model._warningsAt( + '#/definitions/${escapeJsonPointerToken(entry.key)}', + ), + ]; + if (definitionWarnings.isEmpty) return this; + return _rebuildWithCommon( + _common.copyWith(definitionWarnings: definitionWarnings), + ); + } + AckSchemaModel withExtensions(Map extensions) => - _rebuildWithCommon(_common.copyWith(extensions: extensions)); + _rebuildWithCommon( + _common.copyWith( + extensions: extensions, + definitionWarnings: + identical( + extensions['definitions'], + this.extensions['definitions'], + ) + ? null + : const [], + ), + ); @internal AckSchemaModel withJsonSchemaKeywords(Map keywords) { @@ -234,6 +328,9 @@ sealed class AckSchemaModel { }; } + bool _wrapsNullableComposition(List schemas) => + nullable && !schemas.any((schema) => schema is AckNullSchemaModel); + Map _finishCompositionJson( String keyword, List schemas, @@ -243,7 +340,7 @@ sealed class AckSchemaModel { if (keyword == 'allOf') if (extensions['allOf'] case final List extra) ...extra, ]; - if (nullable && !schemas.any((schema) => schema is AckNullSchemaModel)) { + if (_wrapsNullableComposition(schemas)) { // Match Zod v4's Draft-7 nullable-union shape: keep the composition as // one branch, then add null as the other branch. Flattening would validate // the same values but loses the distinction between nullability and the @@ -280,7 +377,8 @@ sealed class AckSchemaModel { return runtimeType == other.runtimeType && deepEq.equals(toJsonSchema(), other.toJsonSchema()) && deepEq.equals(_metadataEquality, other._metadataEquality) && - deepEq.equals(warnings, other.warnings); + deepEq.equals(warnings, other.warnings) && + deepEq.equals(_definitionWarnings, other._definitionWarnings); } @override @@ -291,6 +389,7 @@ sealed class AckSchemaModel { deepEq.hash(toJsonSchema()), deepEq.hash(_metadataEquality), deepEq.hash(warnings), + deepEq.hash(_definitionWarnings), ); } } @@ -298,15 +397,28 @@ sealed class AckSchemaModel { /// A precompiled JSON Schema resource whose 2020-12 keywords must remain /// attached to their original resource instead of being lowered to Draft 7. final class AckRawSchemaModel extends AckSchemaModel { + /// Creates a model from a raw JSON Schema. + /// + /// When nullable, the renderer relocates local references as the original + /// schema moves under `anyOf/0`. It treats nested maps as schemas, skipping + /// the values of `const`, `enum`, `examples`, and `default`. const AckRawSchemaModel({ required this.schema, - this._indexedSchemas = const {}, super.title, super.description, super.nullable, super.defaultValue, super.warnings, super.extensions, + }) : _indexedSchemas = const {}; + + /// Creates a model for a resource already indexed by the importer. + @internal + const AckRawSchemaModel.indexed({ + required this.schema, + required this._indexedSchemas, + super.description, + super.nullable, }); AckRawSchemaModel._( @@ -331,7 +443,7 @@ final class AckRawSchemaModel extends AckSchemaModel { const resourceKeywords = {r'$schema', r'$id', r'$defs', 'definitions'}; final relocated = _relocateRootPointers( body, - Uri.parse(body[r'$id'] as String), + Uri.parse(body[r'$id'] as String? ?? '').removeFragment(), resourceKeywords, _indexedSchemas, ); @@ -364,18 +476,39 @@ Map _relocateRootPointers( Set retainedKeywords, Set> indexedSchemas, ) { + const instanceKeywords = {'const', 'enum', 'examples', 'default'}; + // The keys of these containers are schema names, including names that + // happen to match schema keywords. + const schemaMapKeywords = { + r'$defs', + 'definitions', + 'properties', + 'patternProperties', + 'dependentSchemas', + 'dependencies', + }; late Object? Function(Object?, Uri) visit; - Object? visitExtension(Object? value, Uri base) { + Object? visitNested( + Object? value, + Uri base, { + required bool inferSchemas, + bool schemaMap = false, + }) { if (value is Map) { - if (indexedSchemas.contains(value)) return visit(value, base); + if ((inferSchemas && !schemaMap) || indexedSchemas.contains(value)) { + return visit(value, base); + } return { for (final entry in value.entries) - entry.key: visitExtension(entry.value, base), + entry.key: visitNested(entry.value, base, inferSchemas: inferSchemas), }; } if (value is List) { - return [for (final item in value) visitExtension(item, base)]; + return [ + for (final item in value) + visitNested(item, base, inferSchemas: inferSchemas), + ]; } return value; } @@ -384,7 +517,7 @@ Map _relocateRootPointers( if (value is! Map) return value; final declaredId = value[r'$id']; var currentBase = base; - if (declaredId is String) { + if (!identical(value, source) && declaredId is String) { try { currentBase = base.resolve(declaredId).removeFragment(); } on FormatException { @@ -404,19 +537,21 @@ Map _relocateRootPointers( } final fragment = resolved.fragment; if (resolved.removeFragment() != rootUri) continue; - if (fragment.isEmpty) { - rewritten[key] = rootUri.replace(fragment: '/anyOf/0').toString(); - continue; + if (fragment.isNotEmpty) { + if (!fragment.startsWith('/')) continue; + final first = fragment.substring(1).split('/').first; + if (retainedKeywords.contains(first)) continue; } - if (!fragment.startsWith('/')) continue; - final first = fragment.substring(1).split('/').first; - if (retainedKeywords.contains(first)) continue; - rewritten[key] = rootUri - .replace(fragment: '/anyOf/0$fragment') - .toString(); + final target = rootUri.isAbsolute ? rootUri : Uri.parse(reference); + rewritten[key] = target.replace(fragment: '/anyOf/0$fragment').toString(); } for (final key in rewritten.keys.toList(growable: false)) { - rewritten[key] = visitExtension(rewritten[key], currentBase); + rewritten[key] = visitNested( + rewritten[key], + currentBase, + inferSchemas: indexedSchemas.isEmpty && !instanceKeywords.contains(key), + schemaMap: schemaMapKeywords.contains(key), + ); } return rewritten; }; diff --git a/packages/ack/lib/src/schema_model/ack_schema_model_builder.dart b/packages/ack/lib/src/schema_model/ack_schema_model_builder.dart index 2b2b432b..a61b84e8 100644 --- a/packages/ack/lib/src/schema_model/ack_schema_model_builder.dart +++ b/packages/ack/lib/src/schema_model/ack_schema_model_builder.dart @@ -217,7 +217,7 @@ final class _SchemaModelBuilder { ); return AckAllOfSchemaModel( schemas: [ - AckRawSchemaModel( + AckRawSchemaModel.indexed( schema: _shareImportedResources(document, indexedSchemas), indexedSchemas: indexedSchemas, ), @@ -230,7 +230,7 @@ final class _SchemaModelBuilder { }, ); } - return AckRawSchemaModel( + return AckRawSchemaModel.indexed( schema: schema.export2020Document( importIndex: importIndex, onSchema: indexedSchemas.add, @@ -599,13 +599,17 @@ final class _SchemaModelBuilder { !root.extensions.containsKey(r'$schema'); if (_definitions.isEmpty && !needs2020Dialect) return root; - return root.withExtensions({ - if (needs2020Dialect) - r'$schema': 'https://json-schema.org/draft/2020-12/schema', - ...root.extensions, - if (_definitions.isNotEmpty) - 'definitions': _mergeRootDefinitions(root.extensions['definitions']), - }); + return root + .withExtensions({ + if (needs2020Dialect) + r'$schema': 'https://json-schema.org/draft/2020-12/schema', + ...root.extensions, + if (_definitions.isNotEmpty) + 'definitions': _mergeRootDefinitions( + root.extensions['definitions'], + ), + }) + .withDefinitionWarnings(_definitions); } } @@ -795,7 +799,9 @@ T _wrapPropertyConversion(String key, T Function() fn) { try { return fn(); } catch (e, st) { - final msg = 'Error converting property "$key": $e'; + final detail = e is UnsupportedError ? e.message : e; + final context = 'Error converting property "$key"'; + final msg = detail == null ? context : '$context: $detail'; if (e is UnsupportedError) { Error.throwWithStackTrace(UnsupportedError(msg), st); } else if (e is ArgumentError) { diff --git a/packages/ack/lib/src/schema_model/ack_schema_model_warning.dart b/packages/ack/lib/src/schema_model/ack_schema_model_warning.dart index aabc58c8..4cb3d27a 100644 --- a/packages/ack/lib/src/schema_model/ack_schema_model_warning.dart +++ b/packages/ack/lib/src/schema_model/ack_schema_model_warning.dart @@ -6,6 +6,14 @@ final class AckSchemaModelWarning { final String code; final String message; + + /// Optional location of the warning. The schema-model builder leaves this + /// null on warnings attached to a node. `AckSchemaModel.allWarnings` fills + /// in the node's fragment JSON Pointer using RFC 6901 token escaping + /// without percent-encoding. + /// + /// For an explicitly supplied path, `allWarnings` rebases a `#`-prefixed + /// path to the node's location and passes other values through unchanged. final String? path; final Map context; const AckSchemaModelWarning({ diff --git a/packages/ack/lib/src/schemas/imported_json_schema.dart b/packages/ack/lib/src/schemas/imported_json_schema.dart index 5946c37b..23abffe6 100644 --- a/packages/ack/lib/src/schemas/imported_json_schema.dart +++ b/packages/ack/lib/src/schemas/imported_json_schema.dart @@ -101,7 +101,10 @@ final class ImportedJsonSchema extends AckSchema visit(_root); return { for (final entry in names.entries) - entry.value: entry.key.renderDraft7((node) => refs[node]!), + entry.value: entry.key.renderDraft7( + (node) => refs[node]!, + rootDocumentUri: _root.documentUri, + ), }; } diff --git a/packages/ack/lib/src/schemas/list_schema.dart b/packages/ack/lib/src/schemas/list_schema.dart index 564a473c..ccbedc15 100644 --- a/packages/ack/lib/src/schemas/list_schema.dart +++ b/packages/ack/lib/src/schemas/list_schema.dart @@ -25,7 +25,7 @@ final class ListSchema throw ArgumentError.value( itemSchema, 'itemSchema', - 'Ack.list(...) does not support nullable item schemas yet.', + 'Ack.list does not support nullable item schemas. Use itemSchema.nullable(value: false) to reject null items.', ); } } diff --git a/packages/ack/test/constraints/string_ip_constraint_test.dart b/packages/ack/test/constraints/string_ip_constraint_test.dart index 502f1056..86ba03ab 100644 --- a/packages/ack/test/constraints/string_ip_constraint_test.dart +++ b/packages/ack/test/constraints/string_ip_constraint_test.dart @@ -147,7 +147,7 @@ void main() { test('generates correct schema for any version', () { final schema = const StringIpConstraint().toJsonSchema(); expect(schema, { - 'oneOf': [ + 'anyOf': [ {'format': 'ipv4'}, {'format': 'ipv6'}, ], diff --git a/packages/ack/test/json_schema_draft7_lowering_test.dart b/packages/ack/test/json_schema_draft7_lowering_test.dart index fa9af00a..238616ba 100644 --- a/packages/ack/test/json_schema_draft7_lowering_test.dart +++ b/packages/ack/test/json_schema_draft7_lowering_test.dart @@ -2,6 +2,144 @@ import 'package:ack/ack.dart'; import 'package:test/test.dart'; void main() { + test('version-less IP export round-trips with format annotations', () { + final native = Ack.string().ip(); + final document = native.toJsonSchema(); + final annotated = Ack.fromJsonSchema(document); + final asserted = Ack.fromJsonSchema(document, assertFormats: true); + for (final (value, valid) in [ + ('1.2.3.4', true), + ('2001:db8::1', true), + ('not-an-ip', false), + ]) { + expect(native.safeParse(value).isOk, valid, reason: value); + expect(asserted.safeParse(value).isOk, valid, reason: value); + expect(annotated.safeParse(value).isOk, isTrue, reason: value); + } + + const expected = { + 'type': 'string', + 'anyOf': [ + {'format': 'ipv4'}, + {'format': 'ipv6'}, + ], + }; + expect(document, expected); + expect(native.toJsonSchemaDraft7(), expected); + }); + + test('version-specific IP export keeps a single format', () { + for (final version in [4, 6]) { + final schema = Ack.string().ip(version: version); + final expected = {'type': 'string', 'format': 'ipv$version'}; + expect(schema.toJsonSchema(), expected); + expect(schema.toJsonSchemaDraft7(), expected); + } + }); + + test('lowering preserves format annotations', () { + final schema = Ack.fromJsonSchema({'type': 'string', 'format': 'email'}); + final draft7 = schema.toJsonSchemaDraft7(); + expect(draft7.toString(), contains('format: email')); + expect(Ack.fromJsonSchema(draft7).safeParse('plain text').isOk, isTrue); + }); + + test('lowering names the asserted format keyword and JSON Pointer', () { + final schema = Ack.fromJsonSchema({ + 'properties': { + 'contact/email': {'format': 'email'}, + }, + }, assertFormats: true); + expect( + schema.toJsonSchemaDraft7, + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf( + contains('"format"'), + contains(' at #/properties/contact~1email/format'), + ), + ), + ), + ); + }); + + for (final (keyword, value) in [ + ('unevaluatedItems', false), + ('format', 'email'), + ]) { + test('lowering names the external document and pointer for $keyword', () { + final retrievalUri = Uri.parse('https://example.test/retrieved.json'); + final imported = Ack.fromJsonSchema( + {r'$ref': retrievalUri.toString()}, + baseUri: Uri.parse('https://example.test/root.json'), + documents: { + retrievalUri: { + r'$id': 'https://example.test/canonical.json', + 'properties': { + 'a/b': {keyword: value}, + }, + }, + }, + assertFormats: true, + ); + + final schema = Ack.object({'remote': imported}); + expect( + schema.toJsonSchemaDraft7, + throwsA( + isA().having( + (error) => error.toString(), + 'message', + allOf( + startsWith( + 'Unsupported operation: Error converting property "remote": ' + 'Cannot lower', + ), + contains(' at $retrievalUri#/properties/a~1b/$keyword'), + ), + ), + ), + ); + }); + } + + for (final referenced in [false, true]) { + test( + 'lowering rejects dependencies ${referenced ? 'behind a reference' : 'at the root'}', + () { + final document = { + 'dependencies': { + 'a': ['b'], + }, + }; + final schema = Ack.fromJsonSchema( + referenced + ? { + r'$defs': {'a/b': document}, + r'$ref': r'#/$defs/a~1b', + } + : document, + ); + expect(schema.safeParse({'a': 1}).isOk, isTrue); + final pointer = referenced + ? r'#/$defs/a~1b/dependencies' + : '#/dependencies'; + expect( + schema.toJsonSchemaDraft7, + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('"dependencies" at $pointer'), + ), + ), + ); + }, + ); + } + final cases = < ({ diff --git a/packages/ack/test/json_schema_format_conformance_test.dart b/packages/ack/test/json_schema_format_conformance_test.dart index 171b8406..2a2896e6 100644 --- a/packages/ack/test/json_schema_format_conformance_test.dart +++ b/packages/ack/test/json_schema_format_conformance_test.dart @@ -8,6 +8,28 @@ import 'package:test/test.dart'; import 'package:unorm_dart/unorm_dart.dart' as unorm; void main() { + for (final format in ['hostname', 'email']) { + test( + '$format checks the A-label length before processing the decoded label', + () { + final normalized = []; + final schema = Ack.fromJsonSchema( + {'type': 'string', 'format': format}, + assertFormats: true, + unicodeNormalizer: (value) { + normalized.add(value); + return value; + }, + ); + final label = 'xn--${punycoder.punycode.encode('é' * 64)}'; + expect(label.length, greaterThan(63)); + final input = '${format == 'email' ? 'user@' : ''}$label.example'; + expect(schema.safeParse(input).isFail, isTrue); + expect(normalized, isEmpty); + }, + ); + } + for (final format in ['idn-hostname', 'idn-email', 'hostname', 'email']) { for (final operation in ['parse', 'encode']) { test('$format enforces Unicode Bidi rules during $operation', () { @@ -218,10 +240,10 @@ void main() { assertFormats: true, unicodeNormalizer: unorm.nfkc, ); - expect( - normalized('idn-hostname').safeParse('\uff10\uff11.example').isOk, - isTrue, - ); + final host = normalized('idn-hostname'); + expect(host.safeParse('\uff10\uff11.example').isOk, isTrue); + expect(host.safeParse('EXAMPLE.com').isOk, isTrue); + expect(host.safeParse('MÜNCHEN.de').isFail, isTrue); expect( normalized('hostname') .safeParse('xn--${punycoder.punycode.encode('a\u0301')}.example') diff --git a/packages/ack/test/json_schema_idna_decode_failure_test.dart b/packages/ack/test/json_schema_idna_decode_failure_test.dart index 0e4c523d..e3619e77 100644 --- a/packages/ack/test/json_schema_idna_decode_failure_test.dart +++ b/packages/ack/test/json_schema_idna_decode_failure_test.dart @@ -2,7 +2,55 @@ import 'package:ack/ack.dart'; import 'package:test/test.dart'; void main() { + for (final format in ['hostname', 'email', 'idn-hostname', 'idn-email']) { + test('$format preserves a PVALID Cherokee letter', () { + final schema = Ack.fromJsonSchema({ + 'format': format, + }, assertFormats: true); + final prefix = format.endsWith('email') ? 'user@' : ''; + final labels = ['xn--l9d', if (format.startsWith('idn-')) '\u13af']; + for (final label in labels) { + final input = '$prefix$label.example'; + expect(schema.safeParse(input).isOk, isTrue, reason: input); + expect(schema.safeEncode(input).isOk, isTrue, reason: input); + } + expect(schema.safeParse('${prefix}xn--j4f.example').isFail, isTrue); + }); + } + for (final format in ['idn-hostname', 'idn-email']) { + for (final (rune, valid) in [ + (0x0524, false), // Cyrillic capital Pe with descender. + (0x104b0, false), // Osage capital A. + (0x13af, true), // Cherokee letter Tli is PVALID. + (0x1c90, false), // Georgian Mtavruli capital An. + ]) { + test('$format uses IDNA2008 for U+${rune.toRadixString(16)}', () { + final schema = Ack.fromJsonSchema({ + 'format': format, + }, assertFormats: true); + final prefix = format.endsWith('email') ? 'user@' : ''; + final input = '$prefix${String.fromCharCode(rune)}.EXAMPLE'; + expect(schema.safeParse(input).isOk, valid); + expect(schema.safeEncode(input).isOk, valid); + }); + } + + test('$format rejects oversized Unicode labels', () { + final schema = Ack.fromJsonSchema({ + 'format': format, + }, assertFormats: true); + final prefix = format.endsWith('email') ? 'user@' : ''; + final oversizedLabel = String.fromCharCodes( + List.generate(40000, (index) => 0x4e00 + index % 20000), + ); + expect(schema.safeParse('$prefix$oversizedLabel').isFail, isTrue); + + final supplementaryLabel = '\u{20000}' * 50; + expect(supplementaryLabel.length, greaterThan(63)); + expect(schema.safeParse('$prefix$supplementaryLabel').isOk, isTrue); + }); + for (final encode in [false, true]) { test('$format ${encode ? 'encode' : 'parse'} rejects malformed ACE', () { final schema = Ack.fromJsonSchema({ diff --git a/packages/ack/test/json_schema_import_test.dart b/packages/ack/test/json_schema_import_test.dart index 86212690..573b5150 100644 --- a/packages/ack/test/json_schema_import_test.dart +++ b/packages/ack/test/json_schema_import_test.dart @@ -2,7 +2,57 @@ import 'package:ack/ack.dart'; import 'package:test/test.dart'; void main() { + test('Draft-7 dependencies cannot be silently ignored', () { + expect( + () => Ack.fromJsonSchema({ + r'$schema': 'http://json-schema.org/draft-07/schema#', + 'dependencies': { + 'a': ['b'], + }, + }), + throwsA( + isA().having( + (error) => error.toString(), + 'diagnostic', + allOf(contains('unsupported_keyword'), contains('#/dependencies')), + ), + ), + ); + }); + group('Ack.fromJsonSchema', () { + for (final format in ['email', 'idn-email']) { + test('$format requires balanced quotes around a quoted local part', () { + final schema = Ack.fromJsonSchema({ + 'type': 'string', + 'format': format, + }, assertFormats: true); + + for (final value in ['"@example.com', '"a"b"@example.com']) { + expect(schema.safeParse(value).isFail, isTrue, reason: value); + } + for (final value in ['"user@name"@example.com', '""@example.com']) { + expect(schema.safeParse(value).isOk, isTrue, reason: value); + } + }); + } + + test('asserted date and date-time both admit year 0000', () { + for (final (format, suffix) in [ + ('date', ''), + ('date-time', 'T00:00:00Z'), + ]) { + final schema = Ack.fromJsonSchema({ + 'type': 'string', + 'format': format, + }, assertFormats: true); + + expect(schema.safeParse('0000-01-01$suffix').isOk, isTrue); + expect(schema.safeParse('0000-02-29$suffix').isOk, isTrue); + expect(schema.safeParse('0000-02-30$suffix').isFail, isTrue); + } + }); + test('rejects conflicting documents with equivalent retrieval URIs', () { final base = Uri.parse('https://example.test/root.json'); final entries = [ diff --git a/packages/ack/test/schema_model/ack_schema_model_test.dart b/packages/ack/test/schema_model/ack_schema_model_test.dart index c4e6923d..c12c5f87 100644 --- a/packages/ack/test/schema_model/ack_schema_model_test.dart +++ b/packages/ack/test/schema_model/ack_schema_model_test.dart @@ -2,6 +2,219 @@ import 'package:ack/ack.dart'; import 'package:test/test.dart'; void main() { + test('nullable raw schemas do not require a resource ID', () { + const model = AckRawSchemaModel(schema: {'type': 'string'}, nullable: true); + expect(model.toJsonSchema(), { + 'anyOf': [ + {'type': 'string'}, + {'type': 'null'}, + ], + }); + }); + + for (final keyword in [r'$ref', r'$dynamicRef']) { + test('nullable public raw schema relocates nested $keyword pointers', () { + final model = AckRawSchemaModel( + nullable: true, + schema: { + 'type': 'object', + 'properties': { + 'a': {'type': 'string'}, + 'b': {keyword: '#/properties/a'}, + 'default': {keyword: '#/properties/a'}, + }, + }, + ); + final restored = Ack.fromJsonSchema(model.toJsonSchema()); + expect(restored.safeParse(null).isOk, isTrue); + expect(restored.safeParse({'b': 'ok', 'default': 'ok'}).isOk, isTrue); + expect(restored.safeParse({'b': 1}).isFail, isTrue); + expect(restored.safeParse({'default': 1}).isFail, isTrue); + }); + } + + test('nullable public raw schema keeps recursive refs on the source', () { + const model = AckRawSchemaModel( + nullable: true, + schema: { + 'type': 'object', + 'properties': { + 'child': {r'$ref': '#'}, + }, + }, + ); + final restored = Ack.fromJsonSchema(model.toJsonSchema()); + expect(restored.safeParse(null).isOk, isTrue); + expect(restored.safeParse({'child': {}}).isOk, isTrue); + expect(restored.safeParse({'child': null}).isFail, isTrue); + }); + + for (final id in ['https://example.test/root#', 'nested/root#']) { + test('nullable public raw schema relocates refs at $id', () { + final model = AckRawSchemaModel( + nullable: true, + schema: { + r'$id': id, + r'$ref': '#/allOf/0', + 'allOf': [ + {'type': 'string'}, + ], + }, + ); + final restored = Ack.fromJsonSchema(model.toJsonSchema()); + expect(restored.safeParse(null).isOk, isTrue); + expect(restored.safeParse('ok').isOk, isTrue); + expect(restored.safeParse(1).isFail, isTrue); + }); + } + + test('nullable public raw schema preserves instance keyword values', () { + const literal = {r'$ref': '#', r'$dynamicRef': '#/properties/a'}; + const property = { + 'const': literal, + 'enum': [literal], + 'examples': [literal], + 'default': literal, + }; + const model = AckRawSchemaModel( + nullable: true, + schema: { + 'type': 'object', + 'properties': {'a': property}, + }, + ); + final exported = model.toJsonSchema(); + expect(_resolvePointer(exported, '#/anyOf/0/properties/a'), property); + final restored = Ack.fromJsonSchema(exported); + expect(restored.safeParse({'a': literal}).isOk, isTrue); + }); + + test('nested schema model warnings report their JSON Pointer', () { + final model = Ack.object({ + 'a/b~c': Ack.object({'x': Ack.any()}), + }).toSchemaModel(); + expect(model.allWarnings.single.path, '#/properties/a~1b~0c/properties/x'); + expect(model.allWarnings.single.message, contains('JSON-safe values')); + }); + + test( + 'allWarnings rebases paths and reports definitions before descendants', + () { + final built = + Ack.object({ + 'a/b~ c': Ack.any(), + 'lazy': Ack.lazy( + 'Node', + () => Ack.object({'payload': Ack.any()}), + ), + }).toSchemaModel() + as AckObjectSchemaModel; + expect(built.warnings, isEmpty); + expect(built.properties!['a/b~ c']!.warnings.single.path, isNull); + + final model = AckObjectSchemaModel( + properties: { + 'scope': built.withWarnings([ + const AckSchemaModelWarning( + code: 'local', + message: 'Local warning', + ), + const AckSchemaModelWarning( + code: 'relative', + message: 'Relative warning', + path: '#/properties/a~1b~0 c', + ), + const AckSchemaModelWarning( + code: 'custom', + message: 'Custom warning', + path: 'custom:warning', + ), + ]), + }, + ); + expect(model.allWarnings.map((warning) => (warning.code, warning.path)), [ + ('local', '#/properties/scope'), + ('relative', '#/properties/scope/properties/a~1b~0 c'), + ('custom', 'custom:warning'), + ( + 'ack_any_json_boundary', + '#/properties/scope/definitions/Node/properties/payload', + ), + ('ack_any_json_boundary', '#/properties/scope/properties/a~1b~0 c'), + ( + 'lazy_runtime_checks_not_export_safe', + '#/properties/scope/properties/lazy', + ), + ]); + }, + ); + + final any = Ack.any(); + final warningPaths = { + 'nullable object': ( + Ack.object({'x': any}).nullable().toSchemaModel(), + '#/anyOf/0/properties/x', + ), + 'nullable list': ( + Ack.list(any).nullable().toSchemaModel(), + '#/anyOf/0/items', + ), + 'nullable map': ( + Ack.map(any).nullable().toSchemaModel(), + '#/anyOf/0/additionalProperties', + ), + 'nullable anyOf': ( + Ack.anyOf([Ack.string(), any]).nullable().toSchemaModel(), + '#/anyOf/0/anyOf/1', + ), + 'nullable discriminated union': ( + Ack.discriminated( + discriminatorKey: 'kind', + schemas: { + 'a': Ack.object({'x': any}), + }, + ).nullable().toSchemaModel(), + '#/anyOf/0/anyOf/0/properties/x', + ), + 'nested nullable list': ( + Ack.object({'x': Ack.list(any).nullable()}).toSchemaModel(), + '#/properties/x/anyOf/0/items', + ), + 'nullable composition with explicit null': ( + AckOneOfSchemaModel( + nullable: true, + schemas: [any.toSchemaModel(), const AckNullSchemaModel()], + ), + '#/oneOf/0', + ), + 'nullable lazy target': ( + Ack.lazy( + 'Node/~', + () => Ack.object({'x': any}).nullable(), + ).nullable().toSchemaModel(), + '#/definitions/Node~1~0/anyOf/0/properties/x', + ), + }; + for (final MapEntry(key: shape, value: (model, expectedPath)) + in warningPaths.entries) { + test('$shape warning paths resolve against the rendered schema', () { + final json = model.toJsonSchema(); + expect( + model.allWarnings + .where((warning) => warning.code == 'ack_any_json_boundary') + .map((warning) => warning.path), + [expectedPath], + ); + for (final warning in model.allWarnings) { + expect(_resolvePointer(json, warning.path!), isA()); + } + expect( + model.warnings.map((warning) => warning.code), + isNot(contains('ack_any_json_boundary')), + ); + }); + } + group('AckSchemaModel sealed variants', () { test('renders string constraints and const literals', () { const model = AckStringSchemaModel( @@ -167,3 +380,18 @@ void main() { }); }); } + +Object? _resolvePointer(Map schema, String path) { + final segments = path.split('/'); + expect(segments.first, '#'); + Object? node = schema; + for (final segment in segments.skip(1)) { + final token = segment.replaceAll('~1', '/').replaceAll('~0', '~'); + node = switch (node) { + final Map map => map[token], + final List list => list[int.parse(token)], + _ => fail('Cannot resolve $path at $segment'), + }; + } + return node; +} diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index a7218e5f..7183a465 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -60,8 +60,16 @@ * Expand support to Analyzer 14.x and build 5.x. The generator can resolve with Freezed 4.0.3 and build_runner 2.17.1. +### Added + +* Support `normalize_unicode: true` for international hostname and email + format assertions in generated JSON Schema models. + ### Fixed +* Report a build error when `normalize_unicode: true` is enabled and + `unorm_dart` is missing from the package resolution. + * Keep generated class-first runtime locals from capturing identifiers used by constructor defaults. diff --git a/packages/ack_generator/README.md b/packages/ack_generator/README.md index 4648edf4..4d86e74f 100644 --- a/packages/ack_generator/README.md +++ b/packages/ack_generator/README.md @@ -45,6 +45,7 @@ targets: options: unknown_properties: schema assert_formats: false + normalize_unicode: false model_mode: auto # use validated for exact source-schema parity # Optional offline resources: retrieval URI -> package asset path. # documents: @@ -77,6 +78,9 @@ length and item bounds are normalized to integers; bounds outside the Dart integer range use validated value models. `assert_formats: true` opts into format assertions under the standard dialect; unknown asserted formats and unresolved or malformed schemas fail the build with a JSON-pointer diagnostic. +Set `normalize_unicode: true` and add `unorm_dart` to the consuming package's +runtime dependencies to use NFKC for international hostname labels in generated +format assertions. This also applies to the hostname part of email addresses. External resources are read only from the explicit `documents` mapping; the builder never fetches URLs. The complete required 2020-12 corpus generates offline with its supplied resources. Custom vocabulary support is limited to diff --git a/packages/ack_generator/lib/src/json_schema/json_schema_builder.dart b/packages/ack_generator/lib/src/json_schema/json_schema_builder.dart index eb58e151..b943eeef 100644 --- a/packages/ack_generator/lib/src/json_schema/json_schema_builder.dart +++ b/packages/ack_generator/lib/src/json_schema/json_schema_builder.dart @@ -53,6 +53,12 @@ final class AckJsonSchemaBuilder implements Builder { } } final packageConfig = await buildStep.packageConfig; + if (options.normalizeUnicode && packageConfig['unorm_dart'] == null) { + throw StateError( + 'normalize_unicode: true requires unorm_dart for ${input.uri}. ' + 'Run `dart pub add unorm_dart` in ${input.package}.', + ); + } final language = packageConfig[input.package]?.languageVersion; final library = generateAckSchemaLibrary( document: document, 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 73c48a0c..9d6ad63d 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 @@ -45,6 +45,7 @@ String _emitFallback( required Uri documentUri, required Map documents, required bool assertFormats, + required bool normalizeUnicode, required List widened, required List propertyNameDiagnostics, }) { @@ -117,7 +118,11 @@ String _emitFallback( ..writeln() ..writeln("import 'dart:convert';") ..writeln() - ..writeln("import 'package:ack/ack.dart' as ack;") + ..writeln("import 'package:ack/ack.dart' as ack;"); + if (normalizeUnicode) { + buffer.writeln("import 'package:unorm_dart/unorm_dart.dart' as unorm;"); + } + buffer ..writeln() ..writeln('// dart format off') ..writeln('final Object _jsonSchemaDocument =') @@ -139,16 +144,20 @@ String _emitFallback( for (final (name, definition) in models) { final variable = _variable(name); final formatOption = assertFormats ? ', assertFormats: true' : ''; + final normalizerOption = normalizeUnicode + ? ', unicodeNormalizer: unorm.nfkc' + : ''; + final importOptions = '$formatOption$normalizerOption'; final schemaExpression = definition == null ? 'ack.Ack.fromJsonSchema(_jsonSchemaDocument, ' 'baseUri: Uri.parse($uri), documents: {' 'for (final entry in _jsonSchemaDocuments.entries) ' 'if (entry.key != Uri.parse($uri)) entry.key: entry.value}' - '$formatOption)' + '$importOptions)' : 'ack.Ack.fromJsonSchema(' "{r'\$ref': ${dartStringLiteral(documentUri.replace(fragment: '/\$defs/${_token(definition)}').toString())}}, " 'baseUri: Uri.parse($lookupUri), ' - 'documents: _jsonSchemaDocuments$formatOption)'; + 'documents: _jsonSchemaDocuments$importOptions)'; buffer ..writeln('final $variable = $schemaExpression;') ..writeln() 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 49d15e37..43c1cf78 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 @@ -32,6 +32,7 @@ final class AckJsonSchemaLibraryOptions { this.unknownProperties = AckUnknownPropertiesMode.schema, this.documentPaths = const {}, this.assertFormats = false, + this.normalizeUnicode = false, this.modelMode = AckJsonSchemaModelMode.auto, }); @@ -43,12 +44,14 @@ final class AckJsonSchemaLibraryOptions { 'unknown_properties', 'documents', 'assert_formats', + 'normalize_unicode', 'model_mode', }); if (unknown.isNotEmpty) { throw ArgumentError( 'Unknown ack_json_schema options: ${unknown.join(', ')}. ' - 'Supported: unknown_properties, documents, assert_formats, model_mode.', + 'Supported: unknown_properties, documents, assert_formats, ' + 'normalize_unicode, model_mode.', ); } final mode = config['unknown_properties'] ?? 'schema'; @@ -70,8 +73,17 @@ final class AckJsonSchemaLibraryOptions { 'Must be a boolean.', ); } + final normalizeUnicode = config['normalize_unicode'] ?? false; + if (normalizeUnicode is! bool) { + throw ArgumentError.value( + normalizeUnicode, + 'normalize_unicode', + 'Must be a boolean.', + ); + } return AckJsonSchemaLibraryOptions( assertFormats: assertFormats, + normalizeUnicode: normalizeUnicode, modelMode: switch (config['model_mode'] ?? 'auto') { 'auto' => AckJsonSchemaModelMode.auto, 'validated' => AckJsonSchemaModelMode.validated, @@ -107,6 +119,9 @@ final class AckJsonSchemaLibraryOptions { /// Whether to assert known formats even under the standard 2020-12 dialect. final bool assertFormats; + /// Whether generated value models use NFKC for international hostname labels. + final bool normalizeUnicode; + /// Mode for generated models (`auto` retains typed models where possible; /// `validated` uses exact source-schema value wrappers for every model). final AckJsonSchemaModelMode modelMode; @@ -198,6 +213,7 @@ AckJsonSchemaLibrary generateAckSchemaLibrary({ documentUri: documentUri, documents: fallbackDocuments, assertFormats: options.assertFormats, + normalizeUnicode: options.normalizeUnicode, widened: fallback.widened, propertyNameDiagnostics: propertyNameDiagnostics, ), diff --git a/packages/ack_generator/test/integration/json_schema_runtime_build_test.dart b/packages/ack_generator/test/integration/json_schema_runtime_build_test.dart index 2bf45169..dfeca0c8 100644 --- a/packages/ack_generator/test/integration/json_schema_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/json_schema_runtime_build_test.dart @@ -21,14 +21,76 @@ void _succeeds(ProcessResult result, String command) { } void main() { + var repository = Directory.current; + while (!Directory(p.join(repository.path, 'packages', 'ack_generator')) + .existsSync()) { + repository = repository.parent; + } + + test( + 'normalize_unicode reports a missing runtime dependency during the build', + () async { + final project = await Directory.systemTemp.createTemp('ack_json_schema_'); + addTearDown(() => project.delete(recursive: true)); + Directory(p.join(project.path, 'lib')).createSync(); + File(p.join(project.path, 'pubspec.yaml')).writeAsStringSync(''' +name: ack_json_schema_unicode +publish_to: none +environment: + sdk: '>=3.13.0 <4.0.0' +dependencies: + ack: + path: ${p.join(repository.path, 'packages', 'ack')} +dev_dependencies: + ack_generator: + path: ${p.join(repository.path, 'packages', 'ack_generator')} +$offlineBuildVersions +dependency_overrides: + ack: + path: ${p.join(repository.path, 'packages', 'ack')} +'''); + File(p.join(project.path, 'build.yaml')).writeAsStringSync(r''' +targets: + $default: + builders: + ack_generator:ack_json_schema: + enabled: true + options: + assert_formats: true + normalize_unicode: true +'''); + File(p.join(project.path, 'lib', 'host.schema.json')) + .writeAsStringSync('{"type":"string","format":"idn-hostname"}'); + + _succeeds( + await _run(project, ['pub', 'get', '--offline']), + 'dart pub get --offline', + ); + const build = ['run', 'build_runner', 'build', '--force-jit']; + final missingDependency = await _run(project, build); + final output = '${missingDependency.stdout}\n${missingDependency.stderr}'; + expect(missingDependency.exitCode, isNot(0), reason: output); + expect(output, contains('normalize_unicode: true requires unorm_dart')); + + _succeeds( + await _run(project, ['pub', 'add', '--offline', 'unorm_dart']), + 'dart pub add --offline unorm_dart', + ); + _succeeds( + await _run(project, build), + 'build_runner build with unorm_dart', + ); + _succeeds( + await _run(project, ['analyze', '--fatal-infos']), + 'dart analyze --fatal-infos', + ); + }, + timeout: const Timeout(Duration(minutes: 5)), + ); + test( 'JSON Schema builds into usable models in one deterministic build', () async { - var repository = Directory.current; - while (!Directory(p.join(repository.path, 'packages', 'ack_generator')) - .existsSync()) { - repository = repository.parent; - } final project = await Directory.systemTemp.createTemp('ack_json_schema_'); try { Directory(p.join(project.path, 'lib')).createSync(); 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 c1fd3e57..e774d78e 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 @@ -657,6 +657,31 @@ void main() { }); group('options', () { + test('normalize_unicode opts into NFKC in generated schema imports', () { + final document = {'type': 'string', 'format': 'idn-hostname'}; + final uri = Uri.parse('package:test_pkg/hostname.schema.json'); + final normal = generateAckSchemaLibrary( + document: document, + documentUri: uri, + partStem: 'hostname.schema', + ); + expect(normal.source, isNot(contains('unorm_dart'))); + final normalized = generateAckSchemaLibrary( + document: document, + documentUri: uri, + partStem: 'hostname.schema', + options: AckJsonSchemaLibraryOptions.fromConfig({ + 'assert_formats': true, + 'normalize_unicode': true, + }), + ); + expect( + normalized.source, + contains("import 'package:unorm_dart/unorm_dart.dart' as unorm;"), + ); + expect(normalized.source, contains('unicodeNormalizer: unorm.nfkc')); + }); + test('parse unknown_properties', () { expect( AckJsonSchemaLibraryOptions.fromConfig(const { diff --git a/packages/ack_json_schema_builder/CHANGELOG.md b/packages/ack_json_schema_builder/CHANGELOG.md index 5943e1a6..50c2d670 100644 --- a/packages/ack_json_schema_builder/CHANGELOG.md +++ b/packages/ack_json_schema_builder/CHANGELOG.md @@ -9,6 +9,9 @@ * Use `minItems` and `maxItems` in the list conversion example. +* Forward `unicodeNormalizer` from `toAckSchema` to Ack’s JSON Schema + importer. + ## 2.0.0-beta.3 ### Breaking diff --git a/packages/ack_json_schema_builder/README.md b/packages/ack_json_schema_builder/README.md index abc57f7f..4332e93d 100644 --- a/packages/ack_json_schema_builder/README.md +++ b/packages/ack_json_schema_builder/README.md @@ -29,8 +29,9 @@ Imports use ACK's Draft 2020-12 and Draft-07 importer. Supply cross-document references through `documents: {...}` and an optional `baseUri`; no network requests are made. Imports reject unsupported features with `JsonSchemaImportException`; its diagnostics identify -the source keyword and location. `toAckSchema({baseUri, documents, assertFormats})` -returns the executable validator. Exports preserve imported Draft 2020-12 +the source keyword and location. Pass `unicodeNormalizer: nfkc` from +`package:unorm_dart` to `toAckSchema` to normalize international hostname +labels in format assertions. This applies to hostnames and email domains. Exports preserve imported Draft 2020-12 resources by default (or lower compatible schemas to Draft-07 via `toJsonSchemaBuilderDraft7()`). diff --git a/packages/ack_json_schema_builder/lib/ack_json_schema_builder.dart b/packages/ack_json_schema_builder/lib/ack_json_schema_builder.dart index f29572cc..577c649f 100644 --- a/packages/ack_json_schema_builder/lib/ack_json_schema_builder.dart +++ b/packages/ack_json_schema_builder/lib/ack_json_schema_builder.dart @@ -30,16 +30,20 @@ extension AckSchemaImportExtension on jsb.Schema { /// Converts this draft 2020-12 model to an ACK validator. /// Formats are annotations unless [assertFormats] is true or the model's /// dialect requires format assertions. + /// Pass [unicodeNormalizer] to normalize international hostname labels, + /// including the hostname part of email addresses, before validation. /// Unsupported semantics throw [JsonSchemaImportException]. AckSchema toAckSchema({ Uri? baseUri, Map documents = const {}, bool assertFormats = false, + String Function(String value)? unicodeNormalizer, }) => Ack.fromJsonSchema( value, baseUri: baseUri, documents: documents.map((uri, schema) => MapEntry(uri, schema.value)), assertFormats: assertFormats, + unicodeNormalizer: unicodeNormalizer, ); } diff --git a/packages/ack_json_schema_builder/test/from_json_schema_builder_test.dart b/packages/ack_json_schema_builder/test/from_json_schema_builder_test.dart index 2c511420..63abc08e 100644 --- a/packages/ack_json_schema_builder/test/from_json_schema_builder_test.dart +++ b/packages/ack_json_schema_builder/test/from_json_schema_builder_test.dart @@ -4,6 +4,24 @@ import 'package:json_schema_builder/json_schema_builder.dart' as jsb; import 'package:test/test.dart'; void main() { + test('builder bridge forwards the Unicode normalizer', () { + final model = jsb.Schema.fromMap({ + 'type': 'string', + 'format': 'idn-hostname', + }); + const fullWidth = 'example.com'; + expect( + model.toAckSchema(assertFormats: true).safeParse(fullWidth).isFail, + isTrue, + ); + + final normalized = model.toAckSchema( + assertFormats: true, + unicodeNormalizer: (value) => value.replaceAll('example', 'example'), + ); + expect(normalized.safeParse(fullWidth).isOk, isTrue); + }); + test('imports builder models, including referenced documents', () { final AckSchema strict = jsb.Schema.fromMap({r'$ref': 'types.json'}).toAckSchema( 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 6ae5e3ed..1b333e79 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 @@ -533,7 +533,10 @@ void main() { test('wraps property conversion errors with path', () { final schema = Ack.object({ - 'bad': Ack.fromJsonSchema({'type': 'string', 'format': 'email'}), + 'bad': Ack.fromJsonSchema({ + 'type': 'string', + 'format': 'email', + }, assertFormats: true), }); expect(