Generated toJson and safeToJson skip model-level refinements

Open
#263 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
42/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Active
Tech stack
dart

Research direction

Start by tracing how @Schemable() generates WindowSchema, the loader, and toJson/safeToJson; compare that path with Window.schema.safeEncode and its model-level refinement. Identify a generator-supported registration point that avoids a recursive Window.schema reference. Done means the generated loader and encode helpers enforce the refinement, with WindowSchema.schema still usable as a base.

Written by the indexing model from the issue text.

Description

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.

Dominant language
Dart
Stars
64
Forks
3
Avg merge
17h 32m
Merged PRs (30d)
33

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from btwld/ack

All issues in btwld/ack

Similar issues

More Dart issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.