codec_gen 0.3.0 copy "codec_gen: ^0.3.0" to clipboard
codec_gen: ^0.3.0 copied to clipboard

Code generator for the codec package: reads @Codable / @CodecEnum annotations and generates type-safe JSON codec fields with $.path error locations, via build_runner.

Changelog #

0.3.0 #

  • Global field_rename build option: set field_rename in build.yaml (none / snake / kebab / pascal / camel / screamingSnake) to apply a project-wide default field-rename strategy. @Codable(fieldRename: ...) still overrides per class; an explicit FieldRename.none opts a class back out of the global default. Requires codec ≥ 0.3.0 (Codable.fieldRename is now nullable).

0.2.1 #

  • Maintenance release: version alignment with codec 0.2.1. No changes to the generated code or public API.

0.2.0 #

Dependency Upgrades #

  • analyzer 13 / build 4 / source_gen 4 / build_test 3: Migrated to the new analyzer element model (Element2 / LibraryElement2 and related interfaces), aligning with the Dart SDK 3.6+ toolchain.
  • codec dependency bumped to ^0.2.0: Matches the runtime exception system refactor (CodecException as a standalone type, withFormatExceptions() combinator).

Added #

  • build.yaml option exception_style (codec | format, default codec): When set to format, every top-level codec (_$xxxCodec) generated by this builder automatically has .withFormatExceptions() appended, so decode / encode throw Dart's built-in FormatException instead of CodecException. This provides a zero-touch migration path for existing code that catches on FormatException, with no changes required at call sites.

0.1.6 #

Added #

  • @CodecField(enumValueField:) supports unknownEnumValue:: Declare a fallback enum value for unrecognised codes. The generated top-level helper emits Codec.enumOf<E, V>(..., unknownFallback: E.xxx). When omitted the parameter is not emitted, keeping generated code and behaviour identical to 0.1.5 (fully backward-compatible). Runtime support is provided by codec 0.1.6.

Codegen-time validation (new error paths) #

  • unknownEnumValue set without enumValueField (including cases where the field is overridden by codec:) throws InvalidGenerationSourceError during build_runner; it is never silently ignored.
  • unknownEnumValue whose enum type does not match the field's enum type throws InvalidGenerationSourceError, preventing the generation of code that would not compile.

Tests #

  • Added 3 generator golden tests: enumValueField + unknownEnumValue producing unknownFallback:, standalone unknownEnumValue throwing, and mismatched enum type throwing. Total codec_gen test suite: 64 cases.

Version #

  • Generator code changed; version bumped 0.1.5 → 0.1.6, aligned with CHANGELOG and codec 0.1.6.

0.1.5 #

Added #

  • Field-level @CodecField(enumValueField: 'code'): Maps an enum field by the value of a named property on each enum instance. The enum does not need @CodecEnum (keeping core/domain layers free of codec imports and part files). Mirrors the existing dateTime: pattern — declarative field-level codec selection without writing a top-level codec or a codec: '...' string. Priority: codec > enumValueField > dateTime > inferred from type.
  • Generation: CodableGenerator emits a top-level helper codec _$<ClassName><FieldName>EnumCodec = Codec.enumOf<E, V>(...) referenced by the field. The top-level final is constructed only once, avoiding inline reconstruction of the (non-const) mapping map on every encode/decode call. Helpers are named by class name + field name to prevent top-level name collisions when multiple @Codable classes in the same file reference the same enum.
  • naming.dart adds upperFirst (used when assembling helper variable names).

Behaviour change (generated code format) #

  • Codec part files are now formatted with an extra-wide page width (SharedPartBuilder passes a custom formatOutput using DartFormatter(pageWidth: 1 << 16)). Structural blocks inside a codec part (Codec.object / constructor / encode map / enum mapping map) already carry trailing commas that drive line breaks; individual reader calls are single-line expressions. Long type or field names caused reader calls to be soft-wrapped at 80 columns without a trailing comma, triggering the host project's require_trailing_commas lint. With the widened page width, soft wrapping no longer occurs and that lint is truly avoided at the source, without needing ignore_for_file in the consumer's build.yaml.

Codegen-time validation (new error paths) #

  • @CodecField(enumValueField:) applied to a non-enum field, an enum that has no such property, or a target property whose type is not int / String / double / num throws InvalidGenerationSourceError during build_runner, never deferring the error to runtime.

Tests #

  • Added 5 generator golden tests: int / String value-field mapping with helper reference, helper name uniqueness when multiple @Codable classes in the same file reference the same enum, non-enum field error, and illegal value-field type error. codable_generator_test.dart: 14 → 19 cases.

0.1.4 #

Behaviour change (generated code) #

  • All field reader calls now emit explicit type arguments: b.required<T>(...) / b.optional<T>(...) / b.optionalOr<T>(...) always include the type parameter; the Dart compiler's inference from constructor parameters is no longer relied upon. Rationale: the built-in Codec.any is Codec<Object?>, and T itself carries nullability information. When assigned to an Object?-typed field, the compiler inferred T=Object (dropping nullability), causing a type mismatch against the Codec<Object?> argument and a compile error. Explicit type arguments permanently fix this inference ambiguity, and any future nullable T codec will not hit the same issue.
  • CodecResolver.resolve interface change: return type changed from String (a codec expression) to ({String expr, String typeArg}). The typeArg field carries the string representation of T for that codec; the generator injects it directly as the explicit type argument. In nested List<T?> / Map<String, V?> scenarios typeArg and expr keep element nullability in sync.

Tests #

  • Impact: re-running build_runner build --delete-conflicting-outputs regenerates all *.g.dart files; fvm flutter analyze on the host project confirmed zero regressions.
  • New generator golden tests (test/codable_generator_test.dart, 14 cases): uses build_test's resolveSources to obtain a LibraryElement, then calls CodableGenerator.generateForAnnotatedElement directly and asserts on the output string. Locks down the explicit type argument shape for primitives / Object? / dynamic / nested List / Map / enum / dateTime / custom codec / nullable+required combinations — sub-second feedback; regressions in generated code no longer require a full build_runner re-run + analyze to surface.
  • build_test: ^2.2.0 added to dev_dependencies.

Historical debt #

  • pubspec.yaml version field backfilled from the stale 0.1.0 to 0.1.4 in one step, aligned with CHANGELOG. The same version drift existed in the codec runtime pubspec.yaml but was not touched here (left as a separate cleanup task).

Build / workspace #

  • Joined pub workspace: this package's pubspec.yaml adds resolution: workspace; the root project lists this package under workspace:. Test files' package:test/test.dart imports are now resolved by the root analyzer without false errors.
  • SDK lower bound raised: ^3.4.0^3.6.0 (required by pub workspace).
  • Removed sub-package dependency_overrides: previously pinned analyzer 7.3.0 / analyzer_plugin 0.12.0; workspace mode allows overrides only at the root, and the root pubspec.yaml already declared the same values, so removal has no effect.
  • lints downgraded to ^4.0.0: compatible with the root project's flutter_lints ^4.0.0 joint resolution.
  • .gitignore appends build/: sub-package flutter test produces hundreds of asset files that should not be committed.

0.1.3 #

Added #

  • DateTimeMode.millisUtc / DateTimeMode.secondsUtc: dispatches to the new Codec.dateTimeMillisUtc / Codec.dateTimeSecondsUtc. For backends that send millisecond (or second) timestamps where time-zone correctness matters — decodes to a DateTime with isUtc=true, encodes back to a number; fully symmetric.

0.1.2 #

Added #

  • @CodecIgnore() shorthand annotation: equivalent to @CodecField(ignore: true); shorter and more prominent for single-field skip use cases.
  • FieldRename.screamingSnake: userNameUSER_NAME, for interoperability with Java/Spring backends that use SCREAMING_SNAKE_CASE for enums and constants.
  • @CodecField(dateTime: DateTimeMode.local/utc/seconds): lets the new Codec.dateTimeUtc / Codec.dateTimeSeconds be selected via annotation without writing a codec: 'Codec.dateTimeUtc' string reference.
  • @CodecField(defaultValue: ...) supports const List / const Map: nested literals are also supported via recursive parsing. Unsupported element or key/value types raise an explicit codegen error.

Fixes #

  • Field-level CodecField.includeIfNull implemented: fulfils the semantics already documented in dartdoc. The generator buckets fields separately — fields that keep null are emitted directly; fields that omit null use a Dart map literal if element: if (v.x != null) 'x': codec.encode(v.x!). The class-level omitNulls call is no longer emitted by codec_gen (retained for hand-written codecs).

0.1.1 #

Fixes #

  • String literal escaping: @CodecField(defaultValue:) and @CodecValue values containing ' / \ / $ / \n\r\t / Unicode characters no longer cause compile errors from raw string concatenation in the generated code. Added dartStringLiteral utility function.
  • FieldRename.snake/kebab/pascal consecutive-uppercase word splitting: userIDuser_id, URLPathurl_path, userIDValueuser_id_value. The original algorithm only detected lower→upper boundaries; it missed the boundary between a consecutive-uppercase run and a following lowercase letter (behaviour now aligned with Lodash / inflection and similar libraries; a purely consecutive-uppercase sequence with no embedded lowercase is still treated as a single word).
  • @CodecEnum with only partial @CodecValue coverage rejected at codegen time: previously the generated mapping omitted values and only threw EncodeException at runtime on encode; now InvalidGenerationSourceError is raised during generation, listing the unannotated values.

Tests #

  • First unit tests (previously 0): 36 cases covering renameField edge cases, lowerFirst, dartStringLiteral escaping order and Unicode, and full-coverage validation for @CodecEnum.

0.1.0 #

  • Initial release: @Codable / @CodecEnum annotations trigger codegen, generating top-level _$xxxCodec const/final fields.
  • Automatic field-type resolution: primitives / nullable / default values / List / Map<String, V> / nested models (must carry @Codable) / enums (default inline .name; @CodecEnum uses a shared codec) / self-references (automatically uses Codec.lazy).
  • Field-level escape hatch @CodecField(codec: 'xxx') for arbitrary complex scenarios.
  • @Codable(includeIfNull: false) class-level control: toJson automatically appends .omitNulls.
1
likes
160
points
0
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Code generator for the codec package: reads @Codable / @CodecEnum annotations and generates type-safe JSON codec fields with $.path error locations, via build_runner.

Repository (GitHub)
View/report issues

Topics

#json #codec #code-generation #build-runner #serialization

License

MIT (license)

Dependencies

analyzer, build, codec, dart_style, source_gen

More

Packages that depend on codec_gen