Skip to content

Generated toJson and safeToJson skip model-level refinements #263

Open

Description

@leoafarias

Reproduction

Verified on Ack and ack_generator 2.0.0-beta.3 from main at b8eb8eb with Dart 3.14.0. Put this in lib/encode_repro.dart in a package with ack, ack_generator, and build_runner, then run dart run build_runner build and dart run lib/encode_repro.dart.

import 'package:ack/ack.dart';

part 'encode_repro.g.dart';

@Schemable()
final class const Window({required final int start, required final int end})
    with _$WindowAck {
  static final schema = WindowSchema.schema.refine(
    (window) => window.start <= window.end,
    message: 'start must not exceed end',
  );
}

void main() {
  const invalid = Window(start: 2, end: 1);
  print(invalid.toJson());
  print(invalid.safeToJson().isOk);
  final checked = Window.schema.safeEncode(invalid);
  print(checked.isOk);
  print(checked.getError().runtimeType);
}

Actual

toJson() returns {start: 2, end: 1} and safeToJson().isOk is true. The same instance sent through Window.schema.safeEncode fails with SchemaValidationError. The generated helpers go through WindowSchema, which knows the field rules but not the cross-field refinement on Window.schema.

Suggested change

Provide an explicit generator-supported way to register a model-level refinement so it is part of the schema used by both the generated loader and the generated encode helpers. Keep WindowSchema.schema usable as a base without introducing a recursive reference to Window.schema. Until then, callers can use Window.schema.safeParse and Window.schema.safeEncode explicitly.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions