Zorphy Entity Model Layer and Code Generation
The Zorphy Entity Model Layer is the data backbone of zikzak_inappwebview_platform_interface: every value object and enum that crosses the platform-channel boundary is defined once as a Zorphy entity and expanded by build_runner into immutable Dart classes with JSON serialization, copyWith, field descriptors, patch objects, and structural comparison. This page explains what the layer is, how the two-generator pipeline (zorphy + json_serializable) turns a compact @Zorphy declaration into a fully-featured concrete class, how wire-format fidelity is preserved through hand-written @JsonKey glue, and which model families deliberately remain hand-written outside the generator. It is the code-generation counterpart to the contract seam described in The Platform Interface: The Contract Seam.
Why a Code-Generation Layer Exists
Section titled “Why a Code-Generation Layer Exists”The platform interface is a federated contract: the Flutter-facing package defines the shapes, and each native package (Android, iOS/macOS, Linux, Windows, Web, OpenHarmony) serializes them across a method channel. Hand-writing toJson/fromJson, equality, and copy semantics for over a hundred model classes is error-prone and drifts from the wire format. Zorphy replaces the fork’s former in-house @ExchangeableObject/@ExchangeableEnum toolchain with an off-the-shelf generator, so the model layer is now declarative: authors write an abstract $-prefixed class of getters, and the generator supplies the concrete implementation. The migration was tracked phase-by-phase and is now complete, with all @ExchangeableObject/@ExchangeableEnum models converted.
Sources: GENERATOR_NOTES.md, PROGRESS.md
The Two-Generator Pipeline
Section titled “The Two-Generator Pipeline”Code generation is driven by build.yaml, which scopes two builders to the entity directory lib/src/domain/entities/**. The zorphy:zorphy builder produces the .zorphy.dart part (the concrete class, copyWith, patches, field descriptors, comparison), and json_serializable produces the .g.dart part (the _$FromJson/_$ToJson functions). Regeneration is a single command run from the package directory. The toolchain is declared so the package stays publishable: zorphy_annotation is a normal dependency, while zorphy, json_serializable, and build_runner are dev dependencies.
The following diagram shows how a single entity source file fans out into its generated parts and how the barrel re-exports the concrete class to consumers.
graph TD A["cookie.dart<br/>@Zorphy abstract \$Cookie"] --> B["zorphy builder"] A --> C["json_serializable builder"] B --> D["cookie.zorphy.dart<br/>concrete Cookie + copyWith<br/>+ CookiePatch + CookieFields<br/>+ compareToCookie"] C --> E["cookie.g.dart<br/>_\$CookieFromJson / _\$CookieToJson"] D --> F["types/main.dart barrel<br/>export ...cookie.dart"] E --> F F --> G["zikzak_inappwebview_platform_interface.dart<br/>(public import surface)"]Sources: build.yaml, pubspec.yaml, GENERATOR_NOTES.md
Anatomy of an Entity
Section titled “Anatomy of an Entity”An entity is authored as an abstract class whose name is prefixed with $ and decorated with @Zorphy. Fields are declared as getters; the annotation’s kind: ZorphyKind.valueObject, generateJson: true, and generateCompareTo: true request the full feature set. The concrete class drops the $ prefix — $Cookie becomes Cookie. Two part directives wire in the generated files. Cookie is the canonical minimal example: a required name, a mix of nullable scalars, and one enum field (sameSite) that needs custom wire translation.
| Declaration element | Role | Example (Cookie) |
|---|---|---|
abstract class $Cookie |
Authoring shape; $ is stripped in output |
becomes class Cookie |
@Zorphy(kind: valueObject, …) |
Requests concrete class + JSON + compare | top of file |
part 'cookie.zorphy.dart' |
Binds generator output #1 | required |
part 'cookie.g.dart' |
Binds json_serializable output #2 | required |
@JsonKey(fromJson:, toJson:) |
Per-field wire glue | sameSite |
Sources: cookie.dart
What the Generator Emits
Section titled “What the Generator Emits”The .zorphy.dart part is where the model layer’s power lives. From the single $Cookie declaration the generator emits a concrete Cookie class annotated @JsonSerializable(explicitToJson: true, checked: true), a copyWith, a copyWithField<T>(Field, T) method, a CookiePatch builder (with withX setters and a patchWithCookie applier), a CookieFields descriptor class (typed Field<Cookie, T> constants plus extractor functions), and a CookieCompareE extension providing compareToCookie that returns a diff map of changed fields. The table below maps each generated artifact to its purpose.
| Generated artifact | Kind | Purpose |
|---|---|---|
class Cookie |
concrete class | The instantiable value object (immutable, final fields) |
Cookie.fromJson / toJson |
JSON | Wire serialization, delegates to _$Cookie* |
copyWith({...}) |
method | Field-wise copy; null keeps current value |
copyWithField<T>(field, value) |
method | Generic single-field copy via Field descriptor |
CookiePatch / patchWithCookie |
builder | Accumulate withX mutations, apply as a patch |
CookieFields |
descriptors | Field<Cookie,T> constants for query/reflection |
CookieCompareE.compareToCookie |
extension | Structural diff as Map<String, dynamic> |
The .g.dart part is smaller and mechanical: _$CookieFromJson uses $checkedCreate/$checkedConvert for null-tolerant, type-checked parsing (a missing required name throws), and _$CookieToJson emits the map, routing sameSite through the same _sameSiteToJson glue.
Sources: cookie.zorphy.dart, cookie.zorphy.dart, cookie.g.dart
Preserving the Wire Format with Glue
Section titled “Preserving the Wire Format with Glue”The generator handles JSON-native scalars automatically, but the fork’s wire contract predates Zorphy and includes types the generator cannot serialize by default. These are bridged with hand-written @JsonKey(fromJson:, toJson:) glue — top-level or static helper functions referenced from the getter. Three recurring glue patterns cover almost every case, and each is illustrated by a real entity.
The first pattern is enum wire translation. Enums serialize either as their .index int, as a non-sequential int table, or as a native string. HTTPCookieSameSitePolicy uses a string table ('Lax'/'Strict'/'None'); CacheMode uses a non-sequential int table (-1, 1, 2, 3) because its .index does not match the historical _value; AjaxRequestEventType uses explicit string cases ('loadstart' ↔ LOADSTART). The second pattern is nested-entity and non-JSON-type glue: NavigationAction routes its URLRequest, FrameInfo, and platform-dependent NavigationType fields through fromJson/toJson helpers, with NavigationType even switching on defaultTargetPlatform to reproduce the old native-value dispatch (iOS/macOS WKNavigationType raw values vs. Windows WebView2 ints). The third pattern is default injection via @JsonKey(defaultValue:), used pervasively in large settings entities like InAppWebViewSettings and IOSProxySettings to preserve constructor call shapes.
| Glue pattern | When used | Example |
|---|---|---|
| String-table enum | Native sends strings | HTTPCookieSameSitePolicy ('Lax'…) |
| Non-sequential int enum | .index ≠ wire value |
CacheMode (-1,1,2,3) |
| Platform-switched enum | Wire differs per OS | NavigationType in NavigationAction |
| Nested entity | Field is another entity | URLRequest/FrameInfo |
@JsonKey(defaultValue:) |
Preserve ctor defaults | InAppWebViewSettings.userAgent |
Sources: enums/http_cookie_same_site_policy.dart, enums/cache_mode.dart, navigation_action.dart, in_app_webview_settings.dart
The Authoring and Regeneration Workflow
Section titled “The Authoring and Regeneration Workflow”Entities are not created by hand in a vacuum — they are scaffolded by the Zuraffa CLI (zfa), which writes the $-prefixed abstract class into the fixed layout lib/src/domain/entities/<snake>/, then zfa build runs build_runner. A per-model recipe then post-processes the scaffold: adding @JsonKey(defaultValue:) for defaults, @JsonKey glue for non-native types and enums, and fixing imports for external types (e.g. WebUri) via --allow-forward-refs. The workflow diagram below traces a single model from CLI scaffold to committed, wired-up entity.
graph LR A["zfa entity create<br/>(scaffold \$Name)"] --> B["post-process<br/>@JsonKey glue + defaults"] B --> C["zfa build<br/>(zorphy + json_serializable)"] C --> D["patch *.zorphy.dart<br/>(InvalidType → real type)"] D --> E["delete old @ExchangeableObject<br/>update barrels"] E --> F["glue controllers<br/>fromMap→fromJson, toMap→toJson"] F --> G["build + analyze + tests green"]The public API is preserved by design: class and enum names are unchanged, fields become final, constructor shapes are kept via defaults, and the JSON map keys are identical — the barrel (types/main.dart, re-exported by the package root) remains the only import surface consumers use. The migration map records 105 @ExchangeableObject classes and 94 @ExchangeableEnum enums processed across phases, with a Phase 4 conformance suite (138 → 268 tests) pinning every entity’s wire contract.
Sources: PROGRESS.md, PROGRESS.md, types/main.dart
Skip/Fork: What Stays Hand-Written
Section titled “Skip/Fork: What Stays Hand-Written”Not every model fits the value-object mold, and the migration explicitly skips/forks those into hand-written plain Dart with identical public API and wire format. A Zorphy value object cannot express three things the fork needs: mutability with a method surface (AjaxRequestHeaders accumulates new headers via setRequestHeader and serializes that accumulator, not its fields), polymorphic inheritance (FetchRequestCredential and the URLAuthenticationChallenge hierarchy dispatch on a wire type key), and function-typed callbacks (ContextMenu, InAppBrowserMenuItem, and the Chrome/Safari menu items carry onClick-style callbacks — tracked as zorphy #89). SslCertificate was forked to preserve custom iOS/Android fromMap. These classes keep fromMap/toMap (and often a toJson alias) so the surrounding controllers and platform channels are untouched.
| Skip/fork reason | Representative class(es) |
|---|---|
| Mutable + method surface | AjaxRequestHeaders |
Polymorphic hierarchy (type key) |
FetchRequestCredential, URLAuthenticationChallenge |
| Function-typed callbacks | ContextMenu, InAppBrowserMenuItem |
Custom per-platform fromMap |
SslCertificate |
Sources: types/ajax_request_headers.dart, types/fetch_request_credential.dart, PROGRESS.md, PROGRESS.md
Where to Go Next
Section titled “Where to Go Next”Having seen how the entity layer generates and preserves the wire contract, continue into the surrounding architecture: The Platform Interface: The Contract Seam for how these entities form the channel contract, Domain Controller Facades: Navigation, JavaScript, Cookies, Settings for the controllers that serialize them, and Two-Tier Core/Module Split and the Grep Gate for how the generated surface is enforced across packages. For the concrete consumption of these settings and cookies at runtime, see Cookies, Web Storage, and Credential Management.