From 67622a861a57e61b6e4c6a8991d03be74f66e4f9 Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Tue, 10 Nov 2026 23:02:50 +0000 Subject: [PATCH 1/9] feat: unions! v1-ish --- .config/dotnet-tools.json | 4 +- .editorconfig | 2 +- .github/workflows/pr.yml | 8 ++-- .github/workflows/release.yml | 2 +- AGENTS.md | 38 +++++++++++----- CHANGELOG.md | 43 +++++++++++++++++++ Directory.Packages.props | 25 ++++------- Justfile | 2 +- README.md | 8 +++- commitlint.config.mts | 2 +- docs/Entity-Framework.md | 22 +++++----- docs/Trimming-AOT-and-Blazor.md | 7 +-- docs/ZodSharp-Validation.md | 4 +- global.json | 7 ++- package.json | 4 +- .../Net10Console.csproj} | 12 +++--- .../{Net8Console => Net10Console}/Program.cs | 12 +++--- scripts/test-packed-consumers.ps1 | 26 +++++------ skills/purview-value-objects-efcore/SKILL.md | 10 ++--- .../purview-value-objects-zodsharp/SKILL.md | 4 +- src/Directory.Build.props | 20 +++++++-- src/Directory.Build.targets | 5 ++- .../EFDomainSample.Persistence.csproj | 2 +- src/src/Sample/Sample.csproj | 6 +-- .../CompatibilitySuppressions.xml | 12 ++++++ src/src/ValueObjects/Sdk/README.md | 4 +- .../Serialization/ScalarOptionsAttribute.cs | 6 +++ src/src/ValueObjects/ValueObjects.csproj | 9 ++-- .../ZodSharp.AspNetCoreSample.csproj | 4 +- src/src/ZodSharpSample/ZodSharpSample.csproj | 4 +- .../Repository.UnitTests.csproj | 2 +- .../SharedTestingInfra.csproj | 2 +- .../CompatibilityModels.cs | 10 ++--- .../EntityFrameworkCompatibilityTests.cs | 34 ++++++--------- ...ts.EFCompatibility.IntegrationTests.csproj | 41 +++++++----------- 35 files changed, 235 insertions(+), 168 deletions(-) rename scripts/packed-consumers/{Net8Console/Net8Console.csproj => Net10Console/Net10Console.csproj} (64%) rename scripts/packed-consumers/{Net8Console => Net10Console}/Program.cs (74%) create mode 100644 src/src/ValueObjects/CompatibilitySuppressions.xml diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 4bb5cb6..ae7b773 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -10,14 +10,14 @@ "rollForward": false }, "dotnet-inspect": { - "version": "0.26.0", + "version": "0.27.0", "commands": [ "dotnet-inspect" ], "rollForward": false }, "purview.build": { - "version": "0.8.1", + "version": "0.9.0", "commands": [ "purview-build" ], diff --git a/.editorconfig b/.editorconfig index f8b3050..a9b39cb 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,4 +1,4 @@ -# Purview.BuildSdk 1.3.0 - managed file, do not edit +# Purview.BuildSdk 2.0.0 - managed file, do not edit # # This file is written by Purview.BuildSdk and is replaced whenever the SDK version changes. The version # on the first line is how the SDK recognises a file it owns: a .editorconfig without that marker is diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index dbd9ee1..d286bfa 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -15,7 +15,7 @@ jobs: with: # The shared workflow defaults to the 10.0.x SDK, which cannot build the net11.0 target this # repository gained (NETSDK1045). Keep in sync with `sdk.version` in global.json. - dotnet-version: "11.0.100-rc.3.26522.148" + dotnet-version: "11.0.100" run-pack: true validate-pack: true secrets: inherit @@ -23,7 +23,7 @@ jobs: # Every other job builds against ProjectReferences; this one builds what ships. It packs Purview.ValueObjects to an # isolated feed and package cache, then publishes and runs consumers that reference the package only - a Native AOT # console, a Blazor WebAssembly app (trimmed and RunAOTCompilation, run in headless Chrome), a Blazor Server app - # and a net8.0 console - and leak-scans every bin and publish folder for compiler-host assemblies. It then proves + # and a net10.0 console - and leak-scans every bin and publish folder for compiler-host assemblies. It then proves # every PackValidation ForbiddenContent rule rejects a package. `just smoke-packed-consumers` and # `just verify-pack-rules` run the same locally. packed-consumers: @@ -36,11 +36,11 @@ jobs: steps: - uses: actions/checkout@v7 - # The SDK from global.json, plus the .NET 8 runtime the net8.0 consumer runs on. + # The SDK from global.json, plus the .NET 10 runtime the oldest consumer runs on. - uses: actions/setup-dotnet@v6 with: global-json-file: global.json - dotnet-version: 8.0.x + dotnet-version: 10.0.x # First, before any toolchain is installed: the generator is built against the Purview.SourceGeneratorFramework # version Directory.Packages.props pins, and the consumers use the pinned Purview.ZodSharp. Until both are on diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6cef1b9..cb9d2c7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -30,7 +30,7 @@ jobs: with: release-mode: NuGet # Keep in sync with `sdk.version` in global.json (and with .github/workflows/pr.yml). - dotnet-version: "11.0.100-rc.3.26522.148" + dotnet-version: "11.0.100" trusted-publishing: true # The nuget.org profile name, not the sign-in email. nuget-user: kieronlanning diff --git a/AGENTS.md b/AGENTS.md index 40b6cf4..d6e9a47 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -75,14 +75,30 @@ a diagnostic analyzer, a code fix, tests, samples, and documentation for scalar ## Runtime project rules -- The runtime targets `net8.0;net9.0;net10.0;net11.0`, selected through `PurviewTargetFrameworkSet=All` rather - than a literal list, so the set moves with `Purview.BuildSdk`. Static abstract interface members - (`IScalarValueObject`) require a net7+ floor. +- The runtime targets `net10.0;net11.0`, selected through `PurviewTargetFrameworkSet=Supported` rather + than a literal list, so the set moves with `Purview.BuildSdk`. .NET 8 and .NET 9 were dropped at the + .NET 11 GA: they are out of support and the package's minimum is the current LTS. Static abstract + interface members (`IScalarValueObject`) require a net7+ floor, which this preserves. +- C# 15 language features are available only on the `net11.0` leg, so do not put C# 15 syntax in + generated output, which has to compile on both targets. `closed` was evaluated for + `ScalarOptionsAttribute` and is not applicable: a generic descendant's type parameter must appear in + the closed base's specification, and `ScalarAttribute` derives from that non-generic base + (CS9383). A future fixed hierarchy can use it behind `#if NET11_0_OR_GREATER`, keeping the `net10.0` + declaration equivalent. +- A C# `union` declaration always boxes value-type cases. If the public surface ever needs a union, use + the custom non-boxing pattern (`[Union]` plus `HasValue` and `TryGetValue` overloads) rather than the + `union` keyword, and keep the net10.0 polyfill honest. No union is required by the current API: the + `Create`/`Hydrate`/`TryCreate` contract is deliberately unchanged. +- The `.NET 11` **updated memory-safety rules** stay off repo-wide (`MemorySafetyRules=0`): they are a + preview feature, the repository has no unsafe code, and the in-box System.Text.Json source generator + emits the preview `safe` modifier when they are on, which fails with `CS8652` unless every consuming + project selects `LangVersion=preview`. Runtime Async stays on (`PurviewRuntimeAsync=true`). Do not flip + either without reproving the System.Text.Json source-generated contexts on `net11.0`. - `ScalarJsonConverterFactory` uses only reflection over `ScalarAttribute` + `Create`/`Hydrate`/constructor; keep it free of event-sourcing dependencies. - Keep the runtime package dependency-free (System.Text.Json is in-box for the supported TFMs). -- Purview.ZodSharp 3 ships `net10.0`/`net11.0` only. A project that references it selects - `PurviewTargetFrameworkSet=Supported`; the runtime package does not reference it and keeps `All`. +- Purview.ZodSharp 3 ships `net10.0`/`net11.0` only, the same set as the runtime. A project that + references it uses `PurviewTargetFrameworkSet=Supported`; the runtime package does not reference it. ## Trimming and Native AOT (non-negotiable) @@ -116,10 +132,10 @@ a diagnostic analyzer, a code fix, tests, samples, and documentation for scalar - Unit tests should cover domain logic, contracts, failure behavior, and regressions without external infrastructure. - Entity Framework Core version differences are covered by - `src/tests/ValueObjects.EFCompatibility.IntegrationTests`, which targets `net8.0` with EF Core 7, `net9.0` - with EF Core 9, and `net10.0` with EF Core 10. Add version-dependent behavior there (and, where a synthetic - reference set is enough, to `SourceGenerator.IntegrationTests`) rather than weakening generated output gated - on `IsEF8Referenced`. + `src/tests/ValueObjects.EFCompatibility.IntegrationTests`, which targets `net10.0` with EF Core 10 and + `net11.0` with EF Core 11. Add version-dependent behavior there (and, where a synthetic reference set is + enough, to `SourceGenerator.IntegrationTests`) rather than weakening generated output gated on + `IsEF8Referenced`. - Source-generator tests assert generated code and diagnostics using the existing testing framework (`Purview.SourceGeneratorFramework.Testing.TUnit`). @@ -146,7 +162,7 @@ just verify-pack-rules ``` `just smoke-packed-consumers` is the packed-consumer gate (Native AOT, Blazor WebAssembly trimmed and AOT in a -headless browser, Blazor Server, net8.0, compiler-host leak scan). It needs the Native AOT toolchain, the +headless browser, Blazor Server, net10.0, compiler-host leak scan). It needs the Native AOT toolchain, the `wasm-tools` workload and Chrome or Edge; dependency versions not yet on nuget.org restore from `LOCAL_NUGET_FEED_PATH`. Run it when generated code, the runtime, packaging or a dependency version changes. @@ -271,7 +287,7 @@ collides and the loser is whichever installed second. `Purview.Skills.Testing`'s rule set (the Agent Skills specification: frontmatter fields, name and description constraints, bundled links, body size). The `[InheritsTests]` attribute on that class is load-bearing — TUnit does not walk base types during discovery, so without it the run is green and -nothing is checked. That project pins `net10.0` rather than taking the repository's `All` set, +nothing is checked. That project pins `net10.0` rather than taking the repository's `Supported` set, because it asserts something about the repository rather than about the runtime's reach. A relative link from one `SKILL.md` into another skill's folder is a rule violation: only a skill's diff --git a/CHANGELOG.md b/CHANGELOG.md index a4dc66c..b708ba5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,49 @@ Released versions correspond to `v` GitHub releases. `package.json` is newest heading below is the version in development. Earlier releases are listed under [releases](https://github.com/purview-dev/value-objects/releases). +## 2.0.0-prerelease.1 + +A major release for the .NET 11 GA. It drops the two out-of-support target frameworks and modernises the build; +the generated API and the serialized payload shapes are unchanged. + +### Breaking + +- **`net8.0` and `net9.0` are no longer supported.** The runtime now targets `net10.0` (the current LTS) and + `net11.0`. A consumer on .NET 8 or .NET 9 must stay on the 1.x line. `Purview.ValueObjects` was the only + package in this repository; the source generator and code fixes still target `netstandard2.0`, so they load in + every compiler host. +- **The Entity Framework Core compatibility matrix is now EF Core 10 (`net10.0`) and EF Core 11 (`net11.0`).** + The EF Core 7 and EF Core 9 legs, and the `VO1019` suppression that the EF Core 7 leg needed, are gone. The + generated EF members are unchanged; `VO1019` is still reported for a project that references EF Core 7. +- **The packed-consumer gate's oldest consumer is now `net10.0`**, replacing the `net8.0` console. + +### Changed + +- **Package validation now records the dropped frameworks.** The baseline is the last stable release (1.2.3) and + `CompatibilitySuppressions.xml` suppresses only `PKV006` for `net8.0` and `net9.0`, so any future public API + regression is still a `dotnet pack` failure. +- Built and tested against Purview.BuildSdk 2.0.0, Purview.SourceGeneratorFramework 2.0.0 and + Purview.ZodSharp 3.0.0-prerelease.5 on the .NET 11 GA SDK (11.0.100), TUnit 1.81.16, + Microsoft.SourceLink.GitHub 11.0.100, and EF Core 10.0.15 and 11.0.0. +- The `net11.0` leg compiles with Runtime Async (`runtime-async=on`) and C# 15 as the default language version. + The updated memory-safety rules are deliberately left off: they are preview, this repository has no unsafe + code, and the .NET 11 System.Text.Json source generator emits the preview `safe` modifier when they are on, + which fails with CS8652 unless every consuming project also selects `LangVersion=preview`. +- The EF compatibility tests read an identifier's RFC 9562 version with `Guid.Version` (available since .NET 9) + instead of the hand-rolled nibble. + +### Evaluated and not adopted + +- **`closed` hierarchies.** `ScalarOptionsAttribute` is the only fixed hierarchy in the runtime, but its generic + descendant `ScalarAttribute` cannot derive from a non-generic closed base (CS9383: the type parameter + must appear in the base specification). The API was left unchanged rather than reshaped to satisfy the + modifier. A future hierarchy with only non-generic descendants can adopt it behind + `#if NET11_0_OR_GREATER`. +- **Union types.** No union is required by the current API. The `TryCreate` contract stays the documented + `bool`/`out` shape. If a union is ever added, the `union` keyword is not suitable: it always stores + `object?` and boxes value-type cases. The public surface will use the custom non-boxing pattern + (`[Union]` with `HasValue` and `TryGetValue`) described in the C# union reference. + ## 1.3.0-prerelease.2 A prerelease of fixes and guidance: no target framework is dropped and the public API only grows. diff --git a/Directory.Packages.props b/Directory.Packages.props index 36fed52..66f5b80 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -1,20 +1,16 @@ - - true - true 5.9.0 - 1.76.0 - 1.2.2 - 3.0.0-prerelease.2 + 1.81.16 + 2.0.0 + 3.0.0-prerelease.5 - + @@ -25,16 +21,13 @@ - + - - - - - + + + diff --git a/Justfile b/Justfile index aa723e1..52e7731 100644 --- a/Justfile +++ b/Justfile @@ -101,7 +101,7 @@ pack *args: # Prove the packed package works for real consumers: packs Purview.ValueObjects to an isolated feed, then publishes # and runs a Native AOT console, a Blazor WebAssembly app (trimmed and RunAOTCompilation, run in a headless browser), -# a Blazor Server app and a net8.0 console against it, and leak-scans every output for compiler-host assemblies. +# a Blazor Server app and a net10.0 console against it, and leak-scans every output for compiler-host assemblies. # Needs the Native AOT toolchain, the wasm-tools workload for the WebAssembly AOT step, and Chrome or Edge for the # browser steps. Purview.ZodSharp/Purview.SourceGeneratorFramework versions not yet on nuget.org restore from # LOCAL_NUGET_FEED_PATH (or VALUEOBJECTS_DEPENDENCY_FEED). See scripts/test-packed-consumers.ps1 for the options. diff --git a/README.md b/README.md index dcc05cf..dee47d4 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,10 @@ incremental source generator produces: dotnet add package Purview.ValueObjects ``` +The package targets `net10.0` (LTS) and `net11.0`. .NET 8 and .NET 9 are no longer supported. The `net11.0` +build uses C# 15 as its default language version and compiles with Runtime Async (`runtime-async=on`); the +generated code is identical on both targets. + The package ships the runtime contracts (`[Scalar]`, `[ValueObject]`, `IValueObject`, ...), the source generator, the diagnostic analyzer, and code fixes for the analyzer's diagnostics (for example `VO1001` offers **Add 'partial' modifier**). There is no dependency on any event-sourcing library. @@ -172,7 +176,7 @@ var result = EmailAddressSchema.Validate(EmailAddress.Create("demo@example.com") See [ZodSharp Validation](docs/ZodSharp-Validation.md), the `src/src/ZodSharpSample` project, and the `src/src/ZodSharp.AspNetCoreSample` project (ASP.NET Core Problem Details for a request of value objects, each invalid member reported under its own path). -Purview.ZodSharp 3 targets `net10.0`/`net11.0` (this package still ships `net8.0`-`net11.0` and does not depend on +Purview.ZodSharp 3 targets `net10.0`/`net11.0` (this package ships the same two targets and does not depend on it); `Purview.ZodSharp.Blazor` validates Blazor forms over value objects - see [Trimming, Native AOT and Blazor](docs/Trimming-AOT-and-Blazor.md#blazor). @@ -180,7 +184,7 @@ it); `Purview.ZodSharp.Blazor` validates Blazor forms over value objects - see Generated code uses no reflection, so trimmed, Native AOT and Blazor WebAssembly applications get no IL2xxx/IL3xxx warning from it. `just smoke-packed-consumers` proves it against the packed package: a Native AOT console, a Blazor -WebAssembly app (trimmed and `RunAOTCompilation`, run in a headless browser), a Blazor Server app and a `net8.0` +WebAssembly app (trimmed and `RunAOTCompilation`, run in a headless browser), a Blazor Server app and a `net10.0` console, all built with warnings as errors and scanned for compiler-host assemblies. The generated Entity Framework Core mapping, JSON-column converters included, adds no warning either, though EF Core diff --git a/commitlint.config.mts b/commitlint.config.mts index 533eb7f..00420ab 100644 --- a/commitlint.config.mts +++ b/commitlint.config.mts @@ -14,7 +14,7 @@ export default { 'type-enum': [ 2, 'always', - ['build', 'chore', 'ci', 'docs', 'feat', 'fix', 'perf', 'refactor', 'revert', 'style', 'test'], + ['build', 'chore', 'ci', 'docs', 'feat', 'fix', 'perf', 'refactor', 'revert', 'style', 'test', 'qol'], ], }, }; \ No newline at end of file diff --git a/docs/Entity-Framework.md b/docs/Entity-Framework.md index be4b3a0..481154e 100644 --- a/docs/Entity-Framework.md +++ b/docs/Entity-Framework.md @@ -22,10 +22,10 @@ For the examples below, also add a provider such as SQLite: dotnet add package Microsoft.EntityFrameworkCore.Sqlite ``` -The generated integration is compiled and tested against EF Core **7, 9, and 10** (EF Core 7 needs `net8.0`), -so version-specific API differences are resolved by the generator rather than surfacing in your build. EF Core -7 has no complex-type mapping, which is the one feature difference: a complex value object reports `VO1019` -there. See [Notes](#notes) for the full version matrix. +The generated integration is compiled and tested against EF Core **10 and 11**, the versions that pair with the +package's `net10.0` and `net11.0` targets, so version-specific API differences are resolved by the generator +rather than surfacing in your build. Both support complex-type mapping. See [Notes](#notes) for the full +version matrix. ## Automatic mapping @@ -559,17 +559,17 @@ value-object provider assemblies referenced by EF consumers: - Only `[Scalar]`/`[ValueObject]` types are given a conversion; a plain `enum` property keeps Entity Framework Core's own enum mapping untouched. -- EF Core 8+ is required for **complex type mapping**. An EF Core 7 reference set reports `VO1019` and leaves - complex value objects unmapped; use `EFMapping = Json` (a value converter, so it works on every version) or - configure the property manually. The complex-type block in the registry and the compiled-model members the - generated converters expose (`JsonReaderWriter`) are EF Core 8+ only as well. Everything else the generator - emits — converters, the key value generator, the convention, and `ValueObjectSequentialGuid` — works on - EF Core 7 and later. +- EF Core 8+ is required for **complex type mapping**; the supported versions (10 and 11) both have it. A + project still referencing EF Core 7 reports `VO1019` and leaves complex value objects unmapped; use + `EFMapping = Json` (a value converter) or configure the property manually. The complex-type block in the + registry and the compiled-model members the generated converters expose (`JsonReaderWriter`) are EF Core 8+ + only as well. Everything else the generator emits — converters, the key value generator, the convention, and + `ValueObjectSequentialGuid` — works on EF Core 8 and later. - A generated key value generator is typed as the **value object**, not as its provider value, because Entity Framework Core assigns what a generator returns straight to the property. Application code that mints keys before `SaveChanges` calls the generated `ValueObjectSequentialGuid` helper, which is public in the `Microsoft.EntityFrameworkCore` namespace and produces the same values the convention would assign. -- The generated code is compiled against EF Core 7, 9, and 10 in +- The generated code is compiled against EF Core 10 (`net10.0`) and EF Core 11 (`net11.0`) in `src/tests/ValueObjects.EFCompatibility.IntegrationTests`, so version-specific API shifts (for example `ValueGeneratorFactory.Create`'s second parameter changing to `ITypeBase`) are caught by the build rather than by a consumer. diff --git a/docs/Trimming-AOT-and-Blazor.md b/docs/Trimming-AOT-and-Blazor.md index 50a5121..0c2dcb2 100644 --- a/docs/Trimming-AOT-and-Blazor.md +++ b/docs/Trimming-AOT-and-Blazor.md @@ -7,19 +7,20 @@ from it. That is proven against the packed package, not the repository's own projects: `just smoke-packed-consumers` packs `Purview.ValueObjects`, then publishes and runs a Native AOT console, a Blazor WebAssembly app (trimmed, and -with `RunAOTCompilation=true`, loaded in a headless browser), a Blazor Server app and a `net8.0` console against +with `RunAOTCompilation=true`, loaded in a headless browser), a Blazor Server app and a `net10.0` console against it, every one with warnings as errors, and scans every output for compiler-host assemblies. ## Target frameworks | Package | Target frameworks | | --- | --- | -| `Purview.ValueObjects` | `net8.0`, `net9.0`, `net10.0`, `net11.0` | +| `Purview.ValueObjects` | `net10.0`, `net11.0` | | `Purview.ZodSharp` 3.x (optional) | `net10.0`, `net11.0` | | `Purview.ZodSharp.Blazor` 3.x (optional) | `net11.0` | +.NET 8 and .NET 9 were dropped at the .NET 11 GA; `net10.0` is the current LTS and is the package's floor. `Purview.ValueObjects` has no dependency on ZodSharp. A project that adds the ZodSharp integration needs the -target frameworks ZodSharp supports; a project that does not keeps the full range. +target frameworks ZodSharp supports; a project that does not keeps the same two targets. The runtime assembly declares `browser` as a supported platform, so the platform compatibility analyzer (CA1416) reports any API it calls that is unsupported in Blazor WebAssembly. diff --git a/docs/ZodSharp-Validation.md b/docs/ZodSharp-Validation.md index 80f9ee5..33258b9 100644 --- a/docs/ZodSharp-Validation.md +++ b/docs/ZodSharp-Validation.md @@ -22,8 +22,8 @@ against the underlying value. ```text dotnet add package Purview.ZodSharp ``` -Purview.ZodSharp 3 targets `net10.0` and `net11.0` only, so a project that uses this integration must target -`net10.0` or later; `Purview.ValueObjects` itself still ships `net8.0` to `net11.0` and does not depend on ZodSharp. +Purview.ZodSharp 3 targets `net10.0` and `net11.0` only, the same two targets as `Purview.ValueObjects`, which +does not depend on ZodSharp. .NET 8 and .NET 9 are no longer supported by either package. The value object generator's output is the same for ZodSharp 2.x and 3.x. Two 3.x behaviour changes show up first in value object code: built-in rules report a structured `Origin` (the Zod type name of the underlying value, so `"string"` for a `Guid`) and `Category`, and generated schemas gain `ValidateAsync`, so CA1849 flags a synchronous diff --git a/global.json b/global.json index 1f30df0..20be547 100644 --- a/global.json +++ b/global.json @@ -1,11 +1,10 @@ { "sdk": { - "version": "11.0.100-rc.3.26522.148", - "rollForward": "latestMajor", - "allowPrerelease": true + "version": "11.0.100", + "rollForward": "latestMajor" }, "msbuild-sdks": { - "Purview.BuildSdk": "1.3.0" + "Purview.BuildSdk": "2.0.0" }, "test": { "runner": "Microsoft.Testing.Platform" diff --git a/package.json b/package.json index 0ea6533..0609891 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "value-objects", - "version": "1.3.0-prerelease.4", + "version": "2.0.0-prerelease.1", "license": "MIT", "author": { "name": "Kieron Lanning", @@ -14,4 +14,4 @@ "type": "git", "url": "git+https://github.com/purview-dev/value-objects.git" } -} \ No newline at end of file +} diff --git a/scripts/packed-consumers/Net8Console/Net8Console.csproj b/scripts/packed-consumers/Net10Console/Net10Console.csproj similarity index 64% rename from scripts/packed-consumers/Net8Console/Net8Console.csproj rename to scripts/packed-consumers/Net10Console/Net10Console.csproj index 1f2879d..9d375c4 100644 --- a/scripts/packed-consumers/Net8Console/Net8Console.csproj +++ b/scripts/packed-consumers/Net10Console/Net10Console.csproj @@ -1,14 +1,14 @@ Exe - net8.0 - PackedValueObjectsNet8 - PackedValueObjectsNet8 + net10.0 + PackedValueObjectsNet10 + PackedValueObjectsNet10 enable enable true diff --git a/scripts/packed-consumers/Net8Console/Program.cs b/scripts/packed-consumers/Net10Console/Program.cs similarity index 74% rename from scripts/packed-consumers/Net8Console/Program.cs rename to scripts/packed-consumers/Net10Console/Program.cs index ac3defd..685256e 100644 --- a/scripts/packed-consumers/Net8Console/Program.cs +++ b/scripts/packed-consumers/Net10Console/Program.cs @@ -1,5 +1,5 @@ -// Packed-consumer gate, consumer (d): the net8.0 target of the runtime package, with the trim and AOT analyzers on -// (IsAotCompatible), so the generated code is analyzed for that target too. +// Packed-consumer gate, consumer (d): the net10.0 target of the runtime package, with the trim and AOT analyzers on +// (IsAotCompatible), so the generated code is analyzed for the package's oldest supported target too. using System.Text.Json; using System.Text.Json.Serialization; using Purview.ValueObjects.Serialization; @@ -12,14 +12,14 @@ void Check(bool condition, string description) failures++; } -Console.WriteLine($"net8.0 consumer on {System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription}"); -Check(Environment.Version.Major == 8, "running on the .NET 8 runtime"); +Console.WriteLine($"net10.0 consumer on {System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription}"); +Check(Environment.Version.Major == 10, "running on the .NET 10 runtime"); var sku = Sku.Create(" abc-1234 "); Check(sku.Value == "ABC-1234", $"Create normalizes (got '{sku.Value}')"); Check(!Sku.TryCreate("nope", out _), "TryCreate rejects an invalid value"); -JsonSerializerOptions options = new(Net8JsonContext.Default.Options) +JsonSerializerOptions options = new(Net10JsonContext.Default.Options) { Converters = { new Sku.SkuJsonConverter(), new Price.PriceJsonConverter() }, }; @@ -57,4 +57,4 @@ public readonly partial record struct Price [JsonSerializable(typeof(Price))] [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] -partial class Net8JsonContext : JsonSerializerContext; +partial class Net10JsonContext : JsonSerializerContext; diff --git a/scripts/test-packed-consumers.ps1 b/scripts/test-packed-consumers.ps1 index 5b28f2b..6edf2bc 100644 --- a/scripts/test-packed-consumers.ps1 +++ b/scripts/test-packed-consumers.ps1 @@ -32,8 +32,8 @@ the outcome in the DOM. (c) BlazorServer - a Blazor Web App. Published and started: a statically rendered form is posted invalid and valid, and an interactive-server page is prerendered and then run over a live circuit in the browser. - (d) Net8Console - a net8.0 console without ZodSharp, built and (when the runtime is installed) run: the runtime - package still serves every target framework it ships. + (d) Net10Console - a net10.0 console without ZodSharp, built and (when the runtime is installed) run: the oldest + target framework the runtime package ships. 4. Scans every consumer bin and publish folder with scripts/assert-no-compiler-host-assemblies.ps1. Every check is a hard failure, including the ones that exercise Purview.ZodSharp behaviour the consumers rely on. @@ -707,22 +707,22 @@ try { Assert-NoLeaks @((Join-Path $consumers 'BlazorServer/bin'), $publish) } - Invoke-Step '(d) net8.0 console without ZodSharp: build and run' { - $project = Join-Path $consumers 'Net8Console/Net8Console.csproj' - Invoke-Dotnet 'net8-console-build' (@('build', $project, '--configuration', 'Release', '-warnaserror') + $consumerProperties) - $bin = Join-Path $consumers 'Net8Console/bin/Release/net8.0' + Invoke-Step '(d) net10.0 console without ZodSharp: build and run' { + $project = Join-Path $consumers 'Net10Console/Net10Console.csproj' + Invoke-Dotnet 'net10-console-build' (@('build', $project, '--configuration', 'Release', '-warnaserror') + $consumerProperties) + $bin = Join-Path $consumers 'Net10Console/bin/Release/net10.0' - $net8 = [bool] (& dotnet --list-runtimes 2>$null | Select-String -Pattern '^Microsoft\.NETCore\.App 8\.') - if ($net8) { - & dotnet (Join-Path $bin 'PackedValueObjectsNet8.dll') | Out-Host - if ($LASTEXITCODE -ne 0) { throw "The net8.0 console exited with ${LASTEXITCODE}." } + $net10 = [bool] (& dotnet --list-runtimes 2>$null | Select-String -Pattern '^Microsoft\.NETCore\.App 10\.') + if ($net10) { + & dotnet (Join-Path $bin 'PackedValueObjectsNet10.dll') | Out-Host + if ($LASTEXITCODE -ne 0) { throw "The net10.0 console exited with ${LASTEXITCODE}." } } else { - Write-Host ' the .NET 8 runtime is not installed: built for net8.0 but NOT run.' -ForegroundColor Yellow - if ($env:GITHUB_ACTIONS) { Write-Host '::warning::The net8.0 consumer was built but not run: no .NET 8 runtime.' } + Write-Host ' the .NET 10 runtime is not installed: built for net10.0 but NOT run.' -ForegroundColor Yellow + if ($env:GITHUB_ACTIONS) { Write-Host '::warning::The net10.0 consumer was built but not run: no .NET 10 runtime.' } } - Assert-NoLeaks @((Join-Path $consumers 'Net8Console/bin')) + Assert-NoLeaks @((Join-Path $consumers 'Net10Console/bin')) } } catch { diff --git a/skills/purview-value-objects-efcore/SKILL.md b/skills/purview-value-objects-efcore/SKILL.md index d1ce2ae..2d3bfa3 100644 --- a/skills/purview-value-objects-efcore/SKILL.md +++ b/skills/purview-value-objects-efcore/SKILL.md @@ -304,15 +304,15 @@ public readonly partial record struct Notes { } ## Version support -Compiled and tested against EF Core **7, 9 and 10** (EF Core 7 needs `net8.0`), in +Compiled and tested against EF Core **10** (`net10.0`) and **11** (`net11.0`), in `src/tests/ValueObjects.EFCompatibility.IntegrationTests`, so version-specific API shifts are caught by this build rather than by a consumer. EF Core 8+ is required for **complex type mapping**, the complex-type block in the registry, and the -compiled-model `JsonReaderWriter` members. On EF Core 7, a complex value object reports `VO1019` and -is left unmapped — use `EFMapping = Json` or configure the property manually. Everything else -(converters, the key value generator, the convention, `ValueObjectSequentialGuid`) works on EF Core 7 -and later. +compiled-model `JsonReaderWriter` members; both supported versions have it. On EF Core 7, a complex +value object reports `VO1019` and is left unmapped — use `EFMapping = Json` or configure the property +manually. Everything else (converters, the key value generator, the convention, +`ValueObjectSequentialGuid`) works on EF Core 8 and later. ## Trimming and Native AOT diff --git a/skills/purview-value-objects-zodsharp/SKILL.md b/skills/purview-value-objects-zodsharp/SKILL.md index 3a28585..3b1568b 100644 --- a/skills/purview-value-objects-zodsharp/SKILL.md +++ b/skills/purview-value-objects-zodsharp/SKILL.md @@ -23,8 +23,8 @@ ZodSharp source generator is active in any project that references the package. ```text dotnet add package Purview.ZodSharp ``` -**Purview.ZodSharp 3** targets `net10.0`/`net11.0` only, so a project using the integration needs -`net10.0`+ (Purview.ValueObjects itself still ships `net8.0`-`net11.0`). The generated integration works +**Purview.ZodSharp 3** targets `net10.0`/`net11.0` only, the same two targets as Purview.ValueObjects +(.NET 8 and .NET 9 are no longer supported). The generated integration works with 2.x and 3.x. In 3.x built-in rules report `Origin`/`Category`, paths render as `Items[0].Name` (`FullPath.ToDottedString()`), and generated schemas gain `ValidateAsync` (CA1849 flags a synchronous `Validate` in async code). diff --git a/src/Directory.Build.props b/src/Directory.Build.props index ae66414..b8c8a45 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -5,9 +5,23 @@ - All + itself. 'Supported' is net10.0 and net11.0: .NET 8 and .NET 9 are out of support, and both + were dropped alongside the .NET 11 GA. Roslyn components are excluded by the SDK, which + targets them at netstandard2.0. --> + Supported + + true + 0 true - 1.0.1 + + 1.2.3 diff --git a/src/src/EFDomainSample.Persistence/EFDomainSample.Persistence.csproj b/src/src/EFDomainSample.Persistence/EFDomainSample.Persistence.csproj index a861e0d..eb80e0b 100644 --- a/src/src/EFDomainSample.Persistence/EFDomainSample.Persistence.csproj +++ b/src/src/EFDomainSample.Persistence/EFDomainSample.Persistence.csproj @@ -3,7 +3,7 @@ Exe false + takes the runtime's supported set. --> Supported diff --git a/src/src/Sample/Sample.csproj b/src/src/Sample/Sample.csproj index d94eb06..c3084d9 100644 --- a/src/src/Sample/Sample.csproj +++ b/src/src/Sample/Sample.csproj @@ -2,10 +2,8 @@ Exe false - + Supported diff --git a/src/src/ValueObjects/CompatibilitySuppressions.xml b/src/src/ValueObjects/CompatibilitySuppressions.xml new file mode 100644 index 0000000..3301894 --- /dev/null +++ b/src/src/ValueObjects/CompatibilitySuppressions.xml @@ -0,0 +1,12 @@ + + + + + PKV006 + net8.0 + + + PKV006 + net9.0 + + diff --git a/src/src/ValueObjects/Sdk/README.md b/src/src/ValueObjects/Sdk/README.md index 88a00ae..3d5de2f 100644 --- a/src/src/ValueObjects/Sdk/README.md +++ b/src/src/ValueObjects/Sdk/README.md @@ -143,8 +143,8 @@ indexes, generated key values, query filters, schema/migrations, assembly defaul Generated code uses no reflection, so trimmed, Native AOT and Blazor WebAssembly applications get no IL2xxx/IL3xxx warning from it, including the Entity Framework Core JSON-column converters (EF Core itself is not fully trim- or AOT-compatible). The runtime declares `browser` as a supported platform. The package targets -`net8.0`-`net11.0`; the optional Purview.ZodSharp 3 integration needs `net10.0`+, and `Purview.ZodSharp.Blazor` -validates Blazor forms over value objects. See the +`net10.0` and `net11.0` (.NET 8 and .NET 9 are no longer supported); the optional Purview.ZodSharp 3 integration +needs `net10.0`+, and `Purview.ZodSharp.Blazor` validates Blazor forms over value objects. See the [Trimming, Native AOT and Blazor](https://github.com/purview-dev/value-objects/blob/main/docs/Trimming-AOT-and-Blazor.md) guide. diff --git a/src/src/ValueObjects/Serialization/ScalarOptionsAttribute.cs b/src/src/ValueObjects/Serialization/ScalarOptionsAttribute.cs index 2c84a2d..b341d7c 100644 --- a/src/src/ValueObjects/Serialization/ScalarOptionsAttribute.cs +++ b/src/src/ValueObjects/Serialization/ScalarOptionsAttribute.cs @@ -9,6 +9,12 @@ namespace Purview.ValueObjects.Serialization; /// () scalar declarations configure the generator identically without /// duplicating the option set. It is abstract and is never applied directly. /// +/// +/// It is deliberately not declared : C# 15 requires every type parameter of a +/// generic descendant to appear in a closed base's specification, and +/// derives from this non-generic base (CS9383). The two forms are therefore kept in step by their shared +/// base rather than by the compiler's hierarchy check. +/// /// /// /// Initializes the attribute. diff --git a/src/src/ValueObjects/ValueObjects.csproj b/src/src/ValueObjects/ValueObjects.csproj index 6dd13b7..9bd8e18 100644 --- a/src/src/ValueObjects/ValueObjects.csproj +++ b/src/src/ValueObjects/ValueObjects.csproj @@ -1,11 +1,12 @@ true - - All + Supported Purview Value Objects Source-generated scalar and complex value objects for .NET. Brings F#-style single-case types to C# with Create/Hydrate factories, normalization, validation, equality, comparison, implicit conversions, JSON serialization, and the underlying value's formatting and parsing interfaces for DTOs, Entity Framework, and domain models. $(PackageTags);purview;dotnet;value-objects;value-object;scalar;source-generator;domain-driven-design;dto;serialization;json;entity-framework;formatting;parsing; diff --git a/src/src/ZodSharp.AspNetCoreSample/ZodSharp.AspNetCoreSample.csproj b/src/src/ZodSharp.AspNetCoreSample/ZodSharp.AspNetCoreSample.csproj index 487733b..bc6d121 100644 --- a/src/src/ZodSharp.AspNetCoreSample/ZodSharp.AspNetCoreSample.csproj +++ b/src/src/ZodSharp.AspNetCoreSample/ZodSharp.AspNetCoreSample.csproj @@ -1,8 +1,8 @@  false - + Supported $(NoWarn);CA1506 diff --git a/src/src/ZodSharpSample/ZodSharpSample.csproj b/src/src/ZodSharpSample/ZodSharpSample.csproj index 68f46f1..5e4a8c8 100644 --- a/src/src/ZodSharpSample/ZodSharpSample.csproj +++ b/src/src/ZodSharpSample/ZodSharpSample.csproj @@ -2,8 +2,8 @@ Exe false - + Supported diff --git a/src/tests/Repository.UnitTests/Repository.UnitTests.csproj b/src/tests/Repository.UnitTests/Repository.UnitTests.csproj index 3511327..b5410e7 100644 --- a/src/tests/Repository.UnitTests/Repository.UnitTests.csproj +++ b/src/tests/Repository.UnitTests/Repository.UnitTests.csproj @@ -1,6 +1,6 @@ - diff --git a/src/tests/SharedTestingInfra/SharedTestingInfra.csproj b/src/tests/SharedTestingInfra/SharedTestingInfra.csproj index 3d2c752..469d964 100644 --- a/src/tests/SharedTestingInfra/SharedTestingInfra.csproj +++ b/src/tests/SharedTestingInfra/SharedTestingInfra.csproj @@ -8,7 +8,7 @@ + span net10.0-net11.0 with a per-target EF pin. --> Supported diff --git a/src/tests/ValueObjects.EFCompatibility.IntegrationTests/CompatibilityModels.cs b/src/tests/ValueObjects.EFCompatibility.IntegrationTests/CompatibilityModels.cs index 0012c2b..d93de27 100644 --- a/src/tests/ValueObjects.EFCompatibility.IntegrationTests/CompatibilityModels.cs +++ b/src/tests/ValueObjects.EFCompatibility.IntegrationTests/CompatibilityModels.cs @@ -85,8 +85,8 @@ public readonly partial record struct CompatibilityStamp } /// -/// A complex value object mapped as an Entity Framework Core complex type, which needs EF Core 8 or later. -/// Against EF Core 7 the generator reports VO1019 and leaves the mapping out. +/// A complex value object mapped as an Entity Framework Core complex type. EF Core 10 and 11 both support +/// complex types, so every reference set in this project maps it to columns. /// [ValueObject] public readonly partial record struct CompatibilityMoney @@ -100,7 +100,7 @@ public readonly partial record struct CompatibilityMoney /// /// An entity that uses every value object mapping this project declares, so one model exercises the -/// converters, the JSON column, and - from EF Core 8 - the complex type. +/// converters, the JSON column, and the complex type. /// sealed class CompatibilityEntity { @@ -149,10 +149,8 @@ sealed class CompatibilityEntity /// Gets or sets the JSON column. public CompatibilityStamp Stamp { get; set; } -#if !NET8_0 - /// Gets or sets the complex type mapped to columns, which needs EF Core 8 or later. + /// Gets or sets the complex type mapped to columns. public CompatibilityMoney Total { get; set; } -#endif } /// diff --git a/src/tests/ValueObjects.EFCompatibility.IntegrationTests/EntityFrameworkCompatibilityTests.cs b/src/tests/ValueObjects.EFCompatibility.IntegrationTests/EntityFrameworkCompatibilityTests.cs index 3025686..7e477ba 100644 --- a/src/tests/ValueObjects.EFCompatibility.IntegrationTests/EntityFrameworkCompatibilityTests.cs +++ b/src/tests/ValueObjects.EFCompatibility.IntegrationTests/EntityFrameworkCompatibilityTests.cs @@ -5,10 +5,9 @@ namespace Purview.ValueObjects.EFCompatibility; /// -/// Proves the generated Entity Framework Core integration compiles and runs against EF Core 7, 9, and 10. -/// Each target framework resolves a different EF Core version, so assertions that depend on EF Core 8 APIs -/// are guarded per target: the complex type is mapped from EF Core 8, and the compiled-model members the -/// generated converters expose exist only there. +/// Proves the generated Entity Framework Core integration compiles and runs against EF Core 10 and 11. +/// Each target framework resolves a different EF Core version. Both support complex types and the +/// compiled-model members the generated converters expose, so those assertions are unconditional. /// public sealed class EntityFrameworkCompatibilityTests { @@ -250,26 +249,20 @@ public async Task ComplexTypeValueObjectMappedToJsonColumn_RoundTrips() } [Test] - public async Task CompiledModelMembers_AreEmittedOnlyWhenEntityFramework8IsReferenced() + public async Task CompiledModelMembers_AreEmittedForEverySupportedEntityFrameworkVersion() { - // The compiled-model members use Entity Framework Core 8's JsonValueReaderWriter, so their presence - // is the observable difference between the two generations of the API. The design-time model - // generator reads the member by reflection, which is what this test does. + // The compiled-model members use Entity Framework Core's JsonValueReaderWriter, which every + // supported version provides. The design-time model generator reads the member by reflection, + // which is what this test does. var idReaderWriter = CompiledModelReaderWriter(CompatibilityId.EF.Converter); var stampReaderWriter = CompiledModelReaderWriter(CompatibilityStamp.EF.Converter); -#if NET8_0 - await Assert.That(idReaderWriter).IsNull(); - await Assert.That(stampReaderWriter).IsNull(); -#else await Assert.That(idReaderWriter).IsNotNull(); await Assert.That(stampReaderWriter).IsNotNull(); -#endif } -#if !NET8_0 [Test] - public async Task ComplexTypeValueObject_GivenEntityFramework8OrLater_IsMappedToColumns() + public async Task ComplexTypeValueObject_IsMappedToColumns() { // Arrange await using var connection = await OpenConnectionAsync(); @@ -289,7 +282,7 @@ public async Task ComplexTypeValueObject_GivenEntityFramework8OrLater_IsMappedTo } [Test] - public async Task ComplexTypeValueObject_GivenEntityFramework8OrLater_RoundTrips() + public async Task ComplexTypeValueObject_RoundTrips() { // Arrange await using var connection = await OpenConnectionAsync(); @@ -308,7 +301,6 @@ public async Task ComplexTypeValueObject_GivenEntityFramework8OrLater_RoundTrips // Assert await Assert.That(found.Total).IsEqualTo(total); } -#endif /// /// A value object column declared by a base type that is not an entity type is mapped on the entity type @@ -361,10 +353,10 @@ public async Task InheritedValueObjectColumn_GivenRowWithInheritedValue_RoundTri converter.GetType().GetProperty("JsonReaderWriter"); /// - /// Reads the RFC 9562 version nibble from an identifier's bytes. Guid.Version needs net9.0, and - /// this project deliberately spans earlier frameworks. + /// Reads the RFC 9562 version from an identifier. Guid.Version has been in the BCL since + /// .NET 9, and the runtime's floor is now .NET 10, so the property replaces the hand-rolled nibble. /// - static int GuidVersion(Guid value) => (value.ToByteArray(bigEndian: true)[6] & 0xF0) >> 4; + static int GuidVersion(Guid value) => value.Version; static CompatibilityStamp CreateStamp() => CompatibilityStamp.Create(new DateTimeOffset(2026, 3, 4, 5, 6, 7, TimeSpan.Zero), "compatibility"); @@ -379,9 +371,7 @@ static CompatibilityEntity CreateEntity(string code) => RecordedAt = CompatibilityRecordedAt.Create(new DateTimeOffset(2026, 3, 4, 5, 6, 7, TimeSpan.Zero)), Count = CompatibilityCount.Create(0), Stamp = CreateStamp(), -#if !NET8_0 Total = CompatibilityMoney.Create(1250.75m, CompatibilityCode.Create("GBP")), -#endif }; static async Task OpenConnectionAsync() diff --git a/src/tests/ValueObjects.EFCompatibility.IntegrationTests/ValueObjects.EFCompatibility.IntegrationTests.csproj b/src/tests/ValueObjects.EFCompatibility.IntegrationTests/ValueObjects.EFCompatibility.IntegrationTests.csproj index 26273c6..a02591a 100644 --- a/src/tests/ValueObjects.EFCompatibility.IntegrationTests/ValueObjects.EFCompatibility.IntegrationTests.csproj +++ b/src/tests/ValueObjects.EFCompatibility.IntegrationTests/ValueObjects.EFCompatibility.IntegrationTests.csproj @@ -1,44 +1,33 @@ - - net8.0;net9.0;net10.0;net11.0 + runtime's set ('Supported') in src/src/ValueObjects/ValueObjects.csproj. --> + net10.0;net11.0 - - - - - - - - - - - - - + + - - $(NoWarn);VO1019 - + + + + + + spans two of them, so the SDK's automatic reference is dropped. --> From 78951da632c96922f8386a02b2ad32a042e549ac Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Wed, 11 Nov 2026 09:48:03 +0000 Subject: [PATCH 2/9] chore: formatting --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 0609891..16de3f6 100644 --- a/package.json +++ b/package.json @@ -14,4 +14,4 @@ "type": "git", "url": "git+https://github.com/purview-dev/value-objects.git" } -} +} \ No newline at end of file From 2fa2c9daae23618d2fdbfd556e8c2899524c2bd4 Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Wed, 11 Nov 2026 22:34:16 +0000 Subject: [PATCH 3/9] chore: bumped csharpier --- .config/dotnet-tools.json | 6 +- .../packed-consumers/AotConsole/Program.cs | 260 ++++++++---------- .../ValueObjectDiagnosticAnalyzer.cs | 3 +- .../Generators/ValueObjectSourceGenerator.cs | 108 ++++---- .../ComplexValueObjectEmitter.Equality.cs | 10 +- ...ComplexValueObjectEmitter.Serialization.cs | 66 +++-- .../ComplexValueObjectModelBuilder.cs | 3 +- .../ScalarValueObjectEmitter.Comparison.cs | 10 +- .../ScalarValueObjectEmitter.Equality.cs | 29 +- .../ScalarValueObjectEmitter.Mirroring.cs | 13 +- .../ValueObject/ScalarValueObjectEmitter.cs | 39 +-- .../ValueObjectEFConverterEmitter.cs | 5 +- .../ValueObjectEFRegistryEmitter.cs | 178 ++++++------ .../ValueObject/ValueObjectEmitterHelpers.cs | 5 +- .../ScalarJsonConverterFactory.cs | 24 +- src/src/ZodSharp.AspNetCoreSample/Program.cs | 47 ++-- .../StringNormalizationGeneratorTests.cs | 28 +- .../ZodSchemaValidationGeneratorTests.cs | 4 +- 18 files changed, 378 insertions(+), 460 deletions(-) diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index ae7b773..7f1f239 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,7 +3,7 @@ "isRoot": true, "tools": { "csharpier": { - "version": "1.3.0", + "version": "1.4.0", "commands": [ "csharpier" ], @@ -17,9 +17,9 @@ "rollForward": false }, "purview.build": { - "version": "0.9.0", + "version": "0.9.1", "commands": [ - "purview-build" + "dotnet-inspect" ], "rollForward": false } diff --git a/scripts/packed-consumers/AotConsole/Program.cs b/scripts/packed-consumers/AotConsole/Program.cs index 42405c8..5b98838 100644 --- a/scripts/packed-consumers/AotConsole/Program.cs +++ b/scripts/packed-consumers/AotConsole/Program.cs @@ -104,157 +104,139 @@ static Order ValidOrder() => Check(System.Runtime.JitInfo.GetCompiledMethodCount() == 0, "the process is a Native AOT image (no JIT)") ); -Section( - "generated scalar factories", - () => - { - var email = EmailAddress.Create(" Buyer@Example.COM "); - Check(email.Value == "buyer@example.com", $"Create normalizes before validating (got '{email.Value}')"); - Check( - EmailAddress.Hydrate("not-an-email").Value == "not-an-email", - "Hydrate is replay-safe and does not validate" - ); - Check(!EmailAddress.TryCreate("not-an-email", out _), "TryCreate returns false for a schema failure"); - Check(Quantity.Create(5).Value == 5, "a hook-validated scalar creates"); - Check( - Catch(() => Quantity.Create(0)) is not null, - "a hook-validated scalar rejects an invalid value with ArgumentOutOfRangeException" - ); - Check(Money.Create(1.5m, "EUR").Amount == 1.5m, "a complex value object creates"); - Check( - Catch(() => Money.Create(-1m, "EUR")) is not null, - "a complex value object runs its OnValidate hook" - ); - Check(EmailAddress.Create("a@b.co") == EmailAddress.Create("A@B.CO"), "equality is by normalized value"); - } -); - -Section( - "Create routes through the ZodSharp schema", - () => - { - var email = Catch(() => EmailAddress.Create("not-an-email")); - Check(email is { Errors.Length: > 0 }, "EmailAddress.Create throws ZodException for an invalid address"); - if (email is not null) - CheckPaths(email.Errors, ["Value"], "the scalar's member rule reports the Value path"); +Section("generated scalar factories", () => +{ + var email = EmailAddress.Create(" Buyer@Example.COM "); + Check(email.Value == "buyer@example.com", $"Create normalizes before validating (got '{email.Value}')"); + Check(EmailAddress.Hydrate("not-an-email").Value == "not-an-email", "Hydrate is replay-safe and does not validate"); + Check(!EmailAddress.TryCreate("not-an-email", out _), "TryCreate returns false for a schema failure"); + Check(Quantity.Create(5).Value == 5, "a hook-validated scalar creates"); + Check( + Catch(() => Quantity.Create(0)) is not null, + "a hook-validated scalar rejects an invalid value with ArgumentOutOfRangeException" + ); + Check(Money.Create(1.5m, "EUR").Amount == 1.5m, "a complex value object creates"); + Check( + Catch(() => Money.Create(-1m, "EUR")) is not null, + "a complex value object runs its OnValidate hook" + ); + Check(EmailAddress.Create("a@b.co") == EmailAddress.Create("A@B.CO"), "equality is by normalized value"); +}); - var customer = Catch(() => CustomerId.Create(Guid.Empty)); - ValidationError? error = customer is null ? null : customer.Errors.Single(); - Check( - error is { Code: NonSentinelRule.ErrorCode, Message: "CustomerId must not be empty." }, - $"a type-level [NonSentinel] rejects Guid.Empty (got {error?.Code}: {error?.Message})" - ); - Check( - error?.Path.IsEmpty == true, - "a type-level rule reports an empty path: the scalar is validated as a unit" - ); - Check( - error?.Origin == ZodTypeNames.String, - $"ZodSharp 3 reports the rule's structured origin (got '{error?.Origin}')" - ); - } -); +Section("Create routes through the ZodSharp schema", () => +{ + var email = Catch(() => EmailAddress.Create("not-an-email")); + Check(email is { Errors.Length: > 0 }, "EmailAddress.Create throws ZodException for an invalid address"); + if (email is not null) + CheckPaths(email.Errors, ["Value"], "the scalar's member rule reports the Value path"); -Section( - "generated DTO validation over value objects", - () => - { - Check(OrderSchema.Validate(ValidOrder()).IsSuccess, "a valid order passes"); + var customer = Catch(() => CustomerId.Create(Guid.Empty)); + ValidationError? error = customer is null ? null : customer.Errors.Single(); + Check( + error is { Code: NonSentinelRule.ErrorCode, Message: "CustomerId must not be empty." }, + $"a type-level [NonSentinel] rejects Guid.Empty (got {error?.Code}: {error?.Message})" + ); + Check(error?.Path.IsEmpty == true, "a type-level rule reports an empty path: the scalar is validated as a unit"); + Check( + error?.Origin == ZodTypeNames.String, + $"ZodSharp 3 reports the rule's structured origin (got '{error?.Origin}')" + ); +}); - Order invalid = new() - { - Customer = null, - ContactEmail = EmailAddress.Hydrate("not-an-email"), - Lines = - [ - new() - { - Sku = "abc", - Quantity = Quantity.Hydrate(1), - Price = Money.Hydrate(1m, "GBP"), - }, - ], - }; - var errors = OrderSchema.Validate(invalid).Errors; - foreach (var e in errors) - Console.WriteLine($" {e.FullPath.ToDottedString()}: {e.Code} - {e.Message}"); +Section("generated DTO validation over value objects", () => +{ + Check(OrderSchema.Validate(ValidOrder()).IsSuccess, "a valid order passes"); - CheckPaths( - errors, - ["Customer", "ContactEmail.Value", "Lines[0].Sku"], - "a missing value object, a nested value object's own rule and a collection element report typed paths" - ); + Order invalid = new() + { + Customer = null, + ContactEmail = EmailAddress.Hydrate("not-an-email"), + Lines = + [ + new() + { + Sku = "abc", + Quantity = Quantity.Hydrate(1), + Price = Money.Hydrate(1m, "GBP"), + }, + ], + }; + var errors = OrderSchema.Validate(invalid).Errors; + foreach (var e in errors) + Console.WriteLine($" {e.FullPath.ToDottedString()}: {e.Code} - {e.Message}"); + + CheckPaths( + errors, + ["Customer", "ContactEmail.Value", "Lines[0].Sku"], + "a missing value object, a nested value object's own rule and a collection element report typed paths" + ); - var nested = errors.Where(static e => e.FullPath.ToDottedString() == "ContactEmail.Value").ToArray(); - Check( - nested is [{ Message: "Field 'ContactEmail' must be a valid email address." }], - $"a nested scalar's message names the owning member (got '{string.Join("', '", nested.Select(static e => e.Message))}')" - ); + var nested = errors.Where(static e => e.FullPath.ToDottedString() == "ContactEmail.Value").ToArray(); + Check( + nested is [{ Message: "Field 'ContactEmail' must be a valid email address." }], + $"a nested scalar's message names the owning member (got '{string.Join("', '", nested.Select(static e => e.Message))}')" + ); - var missingEmail = ValidOrder(); - missingEmail.ContactEmail = null; - var required = OrderSchema.Validate(missingEmail).Errors; - Check( - required is [{ Code: RequiredRule.ErrorCode }] - && required[0].FullPath.ToDottedString() == "ContactEmail", - $"[Required] on a nullable scalar member rejects a missing address at the member (got {string.Join(", ", required.Select(static e => $"{e.Code} at {e.FullPath.ToDottedString()}"))})" - ); + var missingEmail = ValidOrder(); + missingEmail.ContactEmail = null; + var required = OrderSchema.Validate(missingEmail).Errors; + Check( + required is [{ Code: RequiredRule.ErrorCode }] + && required[0].FullPath.ToDottedString() == "ContactEmail", + $"[Required] on a nullable scalar member rejects a missing address at the member (got {string.Join(", ", required.Select(static e => $"{e.Code} at {e.FullPath.ToDottedString()}"))})" + ); - var empty = ValidOrder(); - empty.Lines = []; - var tooFew = OrderSchema.Validate(empty).Errors.Single(); - Check( - tooFew is { Code: "too_small", Minimum: 1 } && tooFew.FullPath.ToDottedString() == "Lines", - $"[MinCount] reports too_small at the member (got {tooFew.Code} at {tooFew.FullPath.ToDottedString()})" - ); - } -); + var empty = ValidOrder(); + empty.Lines = []; + var tooFew = OrderSchema.Validate(empty).Errors.Single(); + Check( + tooFew is { Code: "too_small", Minimum: 1 } && tooFew.FullPath.ToDottedString() == "Lines", + $"[MinCount] reports too_small at the member (got {tooFew.Code} at {tooFew.FullPath.ToDottedString()})" + ); +}); -Section( - "System.Text.Json with a source-generated context", - () => - { - var emailInfo = (JsonTypeInfo)JsonOptions.GetTypeInfo(typeof(EmailAddress)); - var moneyInfo = (JsonTypeInfo)JsonOptions.GetTypeInfo(typeof(Money)); - var orderInfo = (JsonTypeInfo)JsonOptions.GetTypeInfo(typeof(Order)); +Section("System.Text.Json with a source-generated context", () => +{ + var emailInfo = (JsonTypeInfo)JsonOptions.GetTypeInfo(typeof(EmailAddress)); + var moneyInfo = (JsonTypeInfo)JsonOptions.GetTypeInfo(typeof(Money)); + var orderInfo = (JsonTypeInfo)JsonOptions.GetTypeInfo(typeof(Order)); - var json = JsonSerializer.Serialize(EmailAddress.Create("demo@example.com"), emailInfo); - Check(json == "\"demo@example.com\"", $"a scalar serializes as its underlying value (got {json})"); + var json = JsonSerializer.Serialize(EmailAddress.Create("demo@example.com"), emailInfo); + Check(json == "\"demo@example.com\"", $"a scalar serializes as its underlying value (got {json})"); - var moneyJson = JsonSerializer.Serialize(Money.Create(12.5m, "USD"), moneyInfo); - Check( - moneyJson == """{"amount":12.5,"currency":"USD"}""", - $"a complex value object writes its members (got {moneyJson})" - ); - Check( - JsonSerializer.Deserialize(moneyJson, moneyInfo) == Money.Create(12.5m, "USD"), - "a complex value object round-trips" - ); + var moneyJson = JsonSerializer.Serialize(Money.Create(12.5m, "USD"), moneyInfo); + Check( + moneyJson == """{"amount":12.5,"currency":"USD"}""", + $"a complex value object writes its members (got {moneyJson})" + ); + Check( + JsonSerializer.Deserialize(moneyJson, moneyInfo) == Money.Create(12.5m, "USD"), + "a complex value object round-trips" + ); - var order = ValidOrder(); - var orderJson = JsonSerializer.Serialize(order, orderInfo); - Console.WriteLine($" {orderJson}"); - var roundTripped = JsonSerializer.Deserialize(orderJson, orderInfo); - Check( - roundTripped is not null - && roundTripped.ContactEmail == order.ContactEmail - && roundTripped.Customer == order.Customer - && roundTripped.Lines.Single().Quantity == Quantity.Create(2), - "a DTO of value objects round-trips through the generated converters" - ); + var order = ValidOrder(); + var orderJson = JsonSerializer.Serialize(order, orderInfo); + Console.WriteLine($" {orderJson}"); + var roundTripped = JsonSerializer.Deserialize(orderJson, orderInfo); + Check( + roundTripped is not null + && roundTripped.ContactEmail == order.ContactEmail + && roundTripped.Customer == order.Customer + && roundTripped.Lines.Single().Quantity == Quantity.Create(2), + "a DTO of value objects round-trips through the generated converters" + ); - var validator = new OrderSchemaValidator(); - var invalid = validator.DeserializeAndValidate( - """{"customer":"3f2504e0-4f89-11d3-9a0c-0305e82c3301","contactEmail":"not-an-email","lines":[]}""", - orderInfo - ); - CheckPaths( - invalid.Errors, - ["ContactEmail.Value", "Lines"], - "DeserializeAndValidate validates the value objects it read" - ); - } -); + var validator = new OrderSchemaValidator(); + var invalid = validator.DeserializeAndValidate( + """{"customer":"3f2504e0-4f89-11d3-9a0c-0305e82c3301","contactEmail":"not-an-email","lines":[]}""", + orderInfo + ); + CheckPaths( + invalid.Errors, + ["ContactEmail.Value", "Lines"], + "DeserializeAndValidate validates the value objects it read" + ); +}); Console.WriteLine(); if (failures.Count == 0) diff --git a/src/src/SourceGenerator/Analyzers/ValueObjectDiagnosticAnalyzer.cs b/src/src/SourceGenerator/Analyzers/ValueObjectDiagnosticAnalyzer.cs index a38e817..f2136e4 100644 --- a/src/src/SourceGenerator/Analyzers/ValueObjectDiagnosticAnalyzer.cs +++ b/src/src/SourceGenerator/Analyzers/ValueObjectDiagnosticAnalyzer.cs @@ -529,8 +529,7 @@ configuredOptions is not null continue; } - var location = - GetArgumentLocation(attribute, optionName, cancellationToken) + var location = GetArgumentLocation(attribute, optionName, cancellationToken) ?? attribute.ApplicationSyntaxReference?.GetSyntax(cancellationToken).GetLocation(); if (location is null) continue; diff --git a/src/src/SourceGenerator/Generators/ValueObjectSourceGenerator.cs b/src/src/SourceGenerator/Generators/ValueObjectSourceGenerator.cs index a985078..22d8258 100644 --- a/src/src/SourceGenerator/Generators/ValueObjectSourceGenerator.cs +++ b/src/src/SourceGenerator/Generators/ValueObjectSourceGenerator.cs @@ -148,19 +148,16 @@ IncrementalValueProvider generationContext static (compilation, _) => ZodSharpScalarRuleAdapterEmitter.ResolveState(compilation) ); - context.RegisterSourceOutput( - adapterState.Combine(generationContext), - static (spc, tuple) => - { - var (state, generationContext) = tuple; - if (generationContext.Settings.IsSourceGeneratorDisabled || !state.ShouldEmit) - return; - - var writer = generationContext.CreateCodeWriter(); - ZodSharpScalarRuleAdapterEmitter.Emit(writer); - spc.AddSource(TypeLibrary.ScalarRuleAdapterHintName, writer); - } - ); + context.RegisterSourceOutput(adapterState.Combine(generationContext), static (spc, tuple) => + { + var (state, generationContext) = tuple; + if (generationContext.Settings.IsSourceGeneratorDisabled || !state.ShouldEmit) + return; + + var writer = generationContext.CreateCodeWriter(); + ZodSharpScalarRuleAdapterEmitter.Emit(writer); + spc.AddSource(TypeLibrary.ScalarRuleAdapterHintName, writer); + }); } static void RegisterEFRegistryOutput( @@ -216,52 +213,49 @@ IncrementalValueProvider generationContext .Combine(generationContext) .Combine(isEF8Referenced); - context.RegisterSourceOutput( - registryInput, - static (spc, tuple) => + context.RegisterSourceOutput(registryInput, static (spc, tuple) => + { + var (left, isEF8Referenced) = tuple; + var (leftInner, generationContext) = left; + var (anyEF, combined) = leftInner; + var (anyValueObject, efOptions) = anyEF; + var (efDisabled, registryDisabled) = efOptions; + if (generationContext.Settings.IsSourceGeneratorDisabled) + return; + + if (!anyValueObject || efDisabled || registryDisabled) + return; + + var scalars = ImmutableArray.CreateBuilder(); + var complex = ImmutableArray.CreateBuilder(); + foreach (var descriptor in combined.Left.Left.Left) { - var (left, isEF8Referenced) = tuple; - var (leftInner, generationContext) = left; - var (anyEF, combined) = leftInner; - var (anyValueObject, efOptions) = anyEF; - var (efDisabled, registryDisabled) = efOptions; - if (generationContext.Settings.IsSourceGeneratorDisabled) - return; - - if (!anyValueObject || efDisabled || registryDisabled) - return; - - var scalars = ImmutableArray.CreateBuilder(); - var complex = ImmutableArray.CreateBuilder(); - foreach (var descriptor in combined.Left.Left.Left) - { - if (descriptor is not null) - scalars.Add(descriptor.Value); - } - - foreach (var descriptor in combined.Left.Left.Right) - { - if (descriptor is not null) - scalars.Add(descriptor.Value); - } - - foreach (var descriptor in combined.Left.Right) - { - if (descriptor is not null) - complex.Add(descriptor.Value); - } - - scalars.AddRange(combined.Right.Scalars); - complex.AddRange(combined.Right.Complex); - - if (scalars.Count == 0 && complex.Count == 0) - return; - - var writer = generationContext.CreateCodeWriter(); - ValueObjectEFRegistryEmitter.Emit(writer, scalars, complex, isEF8Referenced); - spc.AddSource($"{TypeLibrary.EFValueObjectExtensionsClassName}.g.cs", writer); + if (descriptor is not null) + scalars.Add(descriptor.Value); } - ); + + foreach (var descriptor in combined.Left.Left.Right) + { + if (descriptor is not null) + scalars.Add(descriptor.Value); + } + + foreach (var descriptor in combined.Left.Right) + { + if (descriptor is not null) + complex.Add(descriptor.Value); + } + + scalars.AddRange(combined.Right.Scalars); + complex.AddRange(combined.Right.Complex); + + if (scalars.Count == 0 && complex.Count == 0) + return; + + var writer = generationContext.CreateCodeWriter(); + ValueObjectEFRegistryEmitter.Emit(writer, scalars, complex, isEF8Referenced); + spc.AddSource($"{TypeLibrary.EFValueObjectExtensionsClassName}.g.cs", writer); + }); } static EFScalarDescriptor? BuildScalarEFDescriptor(ScalarValueObjectModel model) diff --git a/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Equality.cs b/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Equality.cs index b8a625c..d0b0d57 100644 --- a/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Equality.cs +++ b/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Equality.cs @@ -122,9 +122,8 @@ static void EmitComparison(CodeWriter writer, ComplexValueObjectModel model) $"compare{property.Name}", $"global::System.Collections.Generic.Comparer<{property.TypeName}>.Default.Compare({property.Name}, other.{property.Name})" ); - body.IfBlock( - $"compare{property.Name} != 0", - ifBody => ifBody.Return($"compare{property.Name}") + body.IfBlock($"compare{property.Name} != 0", ifBody => + ifBody.Return($"compare{property.Name}") ); } @@ -143,9 +142,8 @@ static void EmitComparison(CodeWriter writer, ComplexValueObjectModel model) body => { body.IfBlock("obj is null", ifBody => ifBody.Return("1")); - body.IfBlock( - $"obj is {model.TypeName} otherValueObject", - ifBody => ifBody.Return("CompareTo(otherValueObject)") + body.IfBlock($"obj is {model.TypeName} otherValueObject", ifBody => + ifBody.Return("CompareTo(otherValueObject)") ); body.Throw( $"new global::System.ArgumentException($\"Object must be of type {{nameof({model.TypeModel.Name})}}.\", nameof(obj))" diff --git a/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Serialization.cs b/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Serialization.cs index 7670768..8f4c269 100644 --- a/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Serialization.cs +++ b/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Serialization.cs @@ -76,44 +76,40 @@ static void EmitJsonConverter(CodeWriter writer, ComplexValueObjectModel model) for (var index = 0; index < properties.Length; index++) methodBody.Line($"{properties[index].TypeName} {MemberLocal(index)} = default!;"); - methodBody.While( - "reader.Read()", - loop => + methodBody.While("reader.Read()", loop => + { + loop.IfBlock( + "reader.TokenType == global::System.Text.Json.JsonTokenType.EndObject", + ifBody => + ValueObjectEmitterHelpers.EmitJsonFactoryReturn( + ifBody, + $"{model.HydrateFactoryName}({hydrateArgs})", + model.Options.DeserializationMode == ValueObjectSymbolInspector.StrictModeName, + model.TypeModel.FullyQualifiedName + ) + ); + + loop.Line("var jsonName = reader.GetString();"); + loop.Line("reader.Read();"); + + for (var index = 0; index < properties.Length; index++) { - loop.IfBlock( - "reader.TokenType == global::System.Text.Json.JsonTokenType.EndObject", - ifBody => - ValueObjectEmitterHelpers.EmitJsonFactoryReturn( - ifBody, - $"{model.HydrateFactoryName}({hydrateArgs})", - model.Options.DeserializationMode - == ValueObjectSymbolInspector.StrictModeName, - model.TypeModel.FullyQualifiedName - ) - ); - - loop.Line("var jsonName = reader.GetString();"); - loop.Line("reader.Read();"); - - for (var index = 0; index < properties.Length; index++) - { - var property = properties[index]; - var condition = $"{helper}.IsMember(jsonName, \"{property.Name}\", options)"; - var statement = - $"{MemberLocal(index)} = {helper}.Read<{property.TypeName}>(ref reader, options{ConverterArgument(property, index)})!;"; - - if (index == 0) - loop.IfBlock(condition, branch => branch.Line(statement)); - else - loop.ElseIf(condition, branch => branch.Line(statement)); - } - - if (properties.Length == 0) - loop.Line("reader.Skip();"); + var property = properties[index]; + var condition = $"{helper}.IsMember(jsonName, \"{property.Name}\", options)"; + var statement = + $"{MemberLocal(index)} = {helper}.Read<{property.TypeName}>(ref reader, options{ConverterArgument(property, index)})!;"; + + if (index == 0) + loop.IfBlock(condition, branch => branch.Line(statement)); else - loop.Else(static branch => branch.Line("reader.Skip();")); + loop.ElseIf(condition, branch => branch.Line(statement)); } - ); + + if (properties.Length == 0) + loop.Line("reader.Skip();"); + else + loop.Else(static branch => branch.Line("reader.Skip();")); + }); methodBody.Line($"throw new global::System.Text.Json.JsonException({unableToDeserialize});"); } diff --git a/src/src/SourceGenerator/ValueObject/ComplexValueObjectModelBuilder.cs b/src/src/SourceGenerator/ValueObject/ComplexValueObjectModelBuilder.cs index 60e0557..fbc7871 100644 --- a/src/src/SourceGenerator/ValueObject/ComplexValueObjectModelBuilder.cs +++ b/src/src/SourceGenerator/ValueObject/ComplexValueObjectModelBuilder.cs @@ -272,8 +272,7 @@ ValueObjectDefaultsAttributeData assemblyDefaults if (type is not INamedTypeSymbol { IsGenericType: false } named) return null; - var converterTypeName = - ResolveDeclaredJsonConverterTypeName(named) + var converterTypeName = ResolveDeclaredJsonConverterTypeName(named) ?? ResolveGeneratedJsonConverterTypeName(named, compilationAssembly, assemblyDefaults); if (converterTypeName is null) return null; diff --git a/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.Comparison.cs b/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.Comparison.cs index 2f2ceef..db2cdfe 100644 --- a/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.Comparison.cs +++ b/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.Comparison.cs @@ -82,13 +82,11 @@ static void EmitComparison(CodeWriter writer, ScalarValueObjectModel model) body => { body.IfBlock("obj is null", ifBody => ifBody.Return("1")); - body.IfBlock( - $"obj is {model.TypeName} otherValueObject", - ifBody => ifBody.Return("CompareTo(otherValueObject)") + body.IfBlock($"obj is {model.TypeName} otherValueObject", ifBody => + ifBody.Return("CompareTo(otherValueObject)") ); - body.IfBlock( - $"obj is {ScalarPatternTypeName(model)} primitive", - ifBody => ifBody.Return($"CompareTo({ScalarPatternArgument(model)})") + body.IfBlock($"obj is {ScalarPatternTypeName(model)} primitive", ifBody => + ifBody.Return($"CompareTo({ScalarPatternArgument(model)})") ); body.Throw( $"new global::System.ArgumentException($\"Object must be of type {{nameof({model.TypeModel.Name})}} or {model.ScalarTypeName}.\", nameof(obj))" diff --git a/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.Equality.cs b/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.Equality.cs index 06be68f..36c0a0c 100644 --- a/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.Equality.cs +++ b/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.Equality.cs @@ -317,29 +317,24 @@ static void EmitJsonConverter(CodeWriter writer, ScalarValueObjectModel model) // every trimmed or Native AOT consumer got IL2026/IL3050 from this generated code. The // helper resolves the same metadata from the options, and falls back to the built-in // converter for a primitive that a source-generated context never listed. - methodBody.Assignment( - "var", - "value", - writeValue => - writeValue.MethodCall( - "Read", - [new MethodCallArgumentOptions("reader", ParameterModifier.Ref), "options"], - receiver: TypeLibrary.ValueObjectJsonGlobalName, - genericArguments: [model.ScalarTypeReference] - ) + methodBody.Assignment("var", "value", writeValue => + writeValue.MethodCall( + "Read", + [new MethodCallArgumentOptions("reader", ParameterModifier.Ref), "options"], + receiver: TypeLibrary.ValueObjectJsonGlobalName, + genericArguments: [model.ScalarTypeReference] + ) ); // A nullable scalar (`string?`, `int?`) round-trips JSON null; only a non-nullable // reference scalar rejects it. if (model.ScalarCanBeNull && !model.IsNullable) { - methodBody.IfBlock( - "value is null", - ifBody => - ifBody.Throw( - TypeLibrary.System.Text.Json.JsonException, - $"{model.TypeModel.Name} cannot be null." - ) + methodBody.IfBlock("value is null", ifBody => + ifBody.Throw( + TypeLibrary.System.Text.Json.JsonException, + $"{model.TypeModel.Name} cannot be null." + ) ); } diff --git a/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.Mirroring.cs b/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.Mirroring.cs index 2f6d22d..ee740f2 100644 --- a/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.Mirroring.cs +++ b/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.Mirroring.cs @@ -75,14 +75,11 @@ static void EmitTryFormat(CodeWriter writer, ScalarValueObjectModel model, bool // ToString override returning the empty string. if (model.IsNullable) { - body.IfBlock( - $"{model.ScalarPropertyName} is null", - ifBody => - { - ifBody.Assignment(writtenName, "0"); - ifBody.Return("true"); - } - ); + body.IfBlock($"{model.ScalarPropertyName} is null", ifBody => + { + ifBody.Assignment(writtenName, "0"); + ifBody.Return("true"); + }); } body.Return( diff --git a/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.cs b/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.cs index 9bbcec5..23158b8 100644 --- a/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.cs +++ b/src/src/SourceGenerator/ValueObject/ScalarValueObjectEmitter.cs @@ -367,36 +367,27 @@ static void EmitTryCreate(CodeWriter writer, ScalarValueObjectModel model) }, body => { - body.Block( - "try", - tryBlock => - { - tryBlock.Assignment("result", "Create(value)"); - tryBlock.Return("true"); - } - ); - body.Block( - "catch (global::System.ArgumentException)", - catchBlock => - { - catchBlock.Assignment("result", "default!"); - catchBlock.Return("false"); - } - ); + body.Block("try", tryBlock => + { + tryBlock.Assignment("result", "Create(value)"); + tryBlock.Return("true"); + }); + body.Block("catch (global::System.ArgumentException)", catchBlock => + { + catchBlock.Assignment("result", "default!"); + catchBlock.Return("false"); + }); // A ZodSharp-validated Create throws ZodException, not ArgumentException, so without this // catch TryCreate threw for every [ZodSchema] value object instead of returning false — // the documented "try" contract did not hold for a headline feature. if (model.HasZodSchemaValidation) { - body.Block( - $"catch (global::{TypeLibrary.ZodExceptionTypeName})", - catchBlock => - { - catchBlock.Assignment("result", "default!"); - catchBlock.Return("false"); - } - ); + body.Block($"catch (global::{TypeLibrary.ZodExceptionTypeName})", catchBlock => + { + catchBlock.Assignment("result", "default!"); + catchBlock.Return("false"); + }); } } ); diff --git a/src/src/SourceGenerator/ValueObject/ValueObjectEFConverterEmitter.cs b/src/src/SourceGenerator/ValueObject/ValueObjectEFConverterEmitter.cs index 328e3ac..2b4a3c3 100644 --- a/src/src/SourceGenerator/ValueObject/ValueObjectEFConverterEmitter.cs +++ b/src/src/SourceGenerator/ValueObject/ValueObjectEFConverterEmitter.cs @@ -300,9 +300,8 @@ TypeReference nullableObject { method.IfBlock("value is null", branch => branch.Return("null")); method.Assignment("var", "providerType", providerTypeExpression); - method.IfBlock( - "value.GetType() == providerType", - branch => branch.Return("base.ConvertFromProvider(value)") + method.IfBlock("value.GetType() == providerType", branch => + branch.Return("base.ConvertFromProvider(value)") ); method.IfBlock($"value is {valueObjectTypeName} model", branch => branch.Return("model")); method.Return("base.ConvertFromProvider(value)"); diff --git a/src/src/SourceGenerator/ValueObject/ValueObjectEFRegistryEmitter.cs b/src/src/SourceGenerator/ValueObject/ValueObjectEFRegistryEmitter.cs index 0b33939..633b0b7 100644 --- a/src/src/SourceGenerator/ValueObject/ValueObjectEFRegistryEmitter.cs +++ b/src/src/SourceGenerator/ValueObject/ValueObjectEFRegistryEmitter.cs @@ -301,9 +301,8 @@ static void EmitMappablePropertyPredicate(CodeWriter writer) static body => { body.Comment("Not readable, or not an instance member: never mapped."); - body.IfBlock( - "property.GetMethod is null || property.GetMethod.IsStatic", - static ifBody => ifBody.Return("false") + body.IfBlock("property.GetMethod is null || property.GetMethod.IsStatic", static ifBody => + ifBody.Return("false") ); body.Comment("The author excluded it with [NotMapped]."); @@ -346,89 +345,80 @@ static void EmitScalarConversionLoop(CodeWriter writer) // The entity types are snapshotted: configuring a property adds it to the model, and an enumerator // over the live collection throws as soon as the set of entity types changes underneath it. - writer.Block( - "foreach (var entityType in modelBuilder.Model.GetEntityTypes().ToList())", - entityType => - entityType.Block( - "foreach (var property in entityType.ClrType.GetProperties().Where(p => IsMappableValueObjectProperty(entityType, p)))", - property => - { - // A nullable value object property is Nullable; match the underlying type so the - // same T converter maps both T and T? properties. - property.Comment( - "A T? property arrives as Nullable; match the underlying type so the same", - "converter maps both T and T? properties." - ); - property.Assignment( - "var", - "propertyType", - "global::System.Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType" - ); - property.IfElse( - "scalarMappings.TryGetValue(propertyType, out var scalar) && scalar.Converter is not null && scalar.ProviderMappable", - scalar => - ApplyConverterAndComparer( - writer, - "scalar", - "property", - "entityType.ClrType!", - nullabilityExpression: "scalar.IsNullable" - ), - elseBody => - elseBody.IfBlock( - "jsonMappings.TryGetValue(propertyType, out var json) && json.Converter is not null", - json => ApplyConverterAndComparer(writer, "json", "property", "entityType.ClrType!") - ) - ); - } - ) + writer.Block("foreach (var entityType in modelBuilder.Model.GetEntityTypes().ToList())", entityType => + entityType.Block( + "foreach (var property in entityType.ClrType.GetProperties().Where(p => IsMappableValueObjectProperty(entityType, p)))", + property => + { + // A nullable value object property is Nullable; match the underlying type so the + // same T converter maps both T and T? properties. + property.Comment( + "A T? property arrives as Nullable; match the underlying type so the same", + "converter maps both T and T? properties." + ); + property.Assignment( + "var", + "propertyType", + "global::System.Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType" + ); + property.IfElse( + "scalarMappings.TryGetValue(propertyType, out var scalar) && scalar.Converter is not null && scalar.ProviderMappable", + scalar => + ApplyConverterAndComparer( + writer, + "scalar", + "property", + "entityType.ClrType!", + nullabilityExpression: "scalar.IsNullable" + ), + elseBody => + elseBody.IfBlock( + "jsonMappings.TryGetValue(propertyType, out var json) && json.Converter is not null", + json => ApplyConverterAndComparer(writer, "json", "property", "entityType.ClrType!") + ) + ); + } + ) ); } static void EmitComplexMappingBlock(CodeWriter writer) { - writer.IfBlock( - "complexTypeMappings.Length > 0", - complex => - { - // Declaring a complex property can add complex types to the model, so the entity types are - // snapshotted before the loop mutates the model it is walking. - complex.Block( - "foreach (var entityType in modelBuilder.Model.GetEntityTypes().ToList())", - entityType => - entityType.Block( - "foreach (var property in entityType.ClrType.GetProperties().Where(p => p.GetMethod is not null && !p.GetMethod.IsStatic))", - property => - property.IfBlock( - "global::System.Array.IndexOf(complexTypeMappings, property.PropertyType) >= 0", - isComplex => - isComplex.IfBlock( - "!entityType.GetComplexProperties().Any(cp => cp.Name == property.Name)", - notMapped => - notMapped.MethodCall( - "ComplexProperty", - ["property.PropertyType", "property.Name"], - receiver: "modelBuilder.Entity(entityType.ClrType!)" - ) + writer.IfBlock("complexTypeMappings.Length > 0", complex => + { + // Declaring a complex property can add complex types to the model, so the entity types are + // snapshotted before the loop mutates the model it is walking. + complex.Block("foreach (var entityType in modelBuilder.Model.GetEntityTypes().ToList())", entityType => + entityType.Block( + "foreach (var property in entityType.ClrType.GetProperties().Where(p => p.GetMethod is not null && !p.GetMethod.IsStatic))", + property => + property.IfBlock( + "global::System.Array.IndexOf(complexTypeMappings, property.PropertyType) >= 0", + isComplex => + isComplex.IfBlock( + "!entityType.GetComplexProperties().Any(cp => cp.Name == property.Name)", + notMapped => + notMapped.MethodCall( + "ComplexProperty", + ["property.PropertyType", "property.Name"], + receiver: "modelBuilder.Entity(entityType.ClrType!)" ) ) ) - ); + ) + ); - complex.Block( - "foreach (var entityType in modelBuilder.Model.GetEntityTypes().ToList())", - entityType => - entityType.Block( - "foreach (var complexProperty in entityType.GetComplexProperties())", - complexProperty => - complexProperty.Block( - "foreach (var member in complexProperty.ComplexType.ClrType.GetProperties().Where(p => p.GetMethod is not null && !p.GetMethod.IsStatic))", - member => EmitComplexMember(member) - ) + complex.Block("foreach (var entityType in modelBuilder.Model.GetEntityTypes().ToList())", entityType => + entityType.Block( + "foreach (var complexProperty in entityType.GetComplexProperties())", + complexProperty => + complexProperty.Block( + "foreach (var member in complexProperty.ComplexType.ClrType.GetProperties().Where(p => p.GetMethod is not null && !p.GetMethod.IsStatic))", + member => EmitComplexMember(member) ) - ); - } - ); + ) + ); + }); } /// @@ -473,9 +463,8 @@ static void ApplyConverterAndComparer( if (nullabilityExpression is not null) { - writer.IfBlock( - EmittedNullabilityCondition(nullabilityExpression, propertyName, builderName), - body => body.MethodCall("IsRequired", ["false"], receiver: builderName) + writer.IfBlock(EmittedNullabilityCondition(nullabilityExpression, propertyName, builderName), body => + body.MethodCall("IsRequired", ["false"], receiver: builderName) ); } } @@ -521,9 +510,8 @@ static void EmitComplexMember(CodeWriter writer) withoutComparer => withoutComparer.MethodCall("HasConversion", ["scalar.Converter"], receiver: "memberBuilder") ); - scalar.IfBlock( - EmittedNullabilityCondition("scalar.IsNullable", "member", "memberBuilder"), - body => body.MethodCall("IsRequired", ["false"], receiver: "memberBuilder") + scalar.IfBlock(EmittedNullabilityCondition("scalar.IsNullable", "member", "memberBuilder"), body => + body.MethodCall("IsRequired", ["false"], receiver: "memberBuilder") ); }, elseBody => @@ -1051,14 +1039,11 @@ static void EmitTimestampMethods(CodeWriter body) method => { EmitReadTimestampFromBytes(method, 0); - method.IfBlock( - "(bytes[6] & 0xF0) != 0x70", - rejected => - { - rejected.Assignment("timestamp", "default"); - rejected.Return("false"); - } - ); + method.IfBlock("(bytes[6] & 0xF0) != 0x70", rejected => + { + rejected.Assignment("timestamp", "default"); + rejected.Return("false"); + }); EmitAcceptTimestamp(method); } ); @@ -1104,14 +1089,11 @@ static void EmitReadTimestampFromBytes(CodeWriter method, int offset) /// Emits the range check and the timestamp a reader assigns once the value is known good. static void EmitAcceptTimestamp(CodeWriter method) { - method.IfBlock( - "unixMilliseconds < 0L || unixMilliseconds > MaxUnixMilliseconds", - rejected => - { - rejected.Assignment("timestamp", "default"); - rejected.Return("false"); - } - ); + method.IfBlock("unixMilliseconds < 0L || unixMilliseconds > MaxUnixMilliseconds", rejected => + { + rejected.Assignment("timestamp", "default"); + rejected.Return("false"); + }); method.Assignment("timestamp", "global::System.DateTimeOffset.FromUnixTimeMilliseconds(unixMilliseconds)"); method.Return("true"); } diff --git a/src/src/SourceGenerator/ValueObject/ValueObjectEmitterHelpers.cs b/src/src/SourceGenerator/ValueObject/ValueObjectEmitterHelpers.cs index f106949..909aa77 100644 --- a/src/src/SourceGenerator/ValueObject/ValueObjectEmitterHelpers.cs +++ b/src/src/SourceGenerator/ValueObject/ValueObjectEmitterHelpers.cs @@ -101,9 +101,8 @@ public static class ZodRefinement public static void EmitCreateValidation(CodeWriter body, string schemaReference) { body.Assignment("var", "result", $"{schemaReference}.Validate(instance)"); - body.IfBlock( - "!result.IsSuccess", - ifBody => ifBody.Throw($"new global::{TypeLibrary.ZodExceptionTypeName}(result.Errors)") + body.IfBlock("!result.IsSuccess", ifBody => + ifBody.Throw($"new global::{TypeLibrary.ZodExceptionTypeName}(result.Errors)") ); } } diff --git a/src/src/ValueObjects/Serialization/ScalarJsonConverterFactory.cs b/src/src/ValueObjects/Serialization/ScalarJsonConverterFactory.cs index 8bfef15..63ac2e4 100644 --- a/src/src/ValueObjects/Serialization/ScalarJsonConverterFactory.cs +++ b/src/src/ValueObjects/Serialization/ScalarJsonConverterFactory.cs @@ -99,21 +99,15 @@ public override bool CanConvert(Type typeToConvert) => Justification = "Only reachable through the annotated ScalarJsonConverterFactory constructor." )] public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) => - Cache.GetOrAdd( - typeToConvert, - static t => - { - var attr = t.GetCustomAttribute()!; - var scalarProp = - t.GetProperty(attr.PropertyName, BindingFlags.Instance | BindingFlags.Public) - ?? throw new InvalidOperationException( - $"'{t.Name}' missing scalar property '{attr.PropertyName}'." - ); - - var converterType = typeof(ScalarJsonConverter<,>).MakeGenericType(t, scalarProp.PropertyType); - return (JsonConverter)Activator.CreateInstance(converterType, scalarProp, attr.DeserializationMode)!; - } - ); + Cache.GetOrAdd(typeToConvert, static t => + { + var attr = t.GetCustomAttribute()!; + var scalarProp = t.GetProperty(attr.PropertyName, BindingFlags.Instance | BindingFlags.Public) + ?? throw new InvalidOperationException($"'{t.Name}' missing scalar property '{attr.PropertyName}'."); + + var converterType = typeof(ScalarJsonConverter<,>).MakeGenericType(t, scalarProp.PropertyType); + return (JsonConverter)Activator.CreateInstance(converterType, scalarProp, attr.DeserializationMode)!; + }); // Instances are only ever created by CreateConverter, which is itself only reachable through the // annotated constructor, so the requirement is already declared to the consumer at the opt-in point. diff --git a/src/src/ZodSharp.AspNetCoreSample/Program.cs b/src/src/ZodSharp.AspNetCoreSample/Program.cs index a1fa481..63d95cb 100644 --- a/src/src/ZodSharp.AspNetCoreSample/Program.cs +++ b/src/src/ZodSharp.AspNetCoreSample/Program.cs @@ -32,10 +32,8 @@ // HttpValidationProblemDetails response listing every invalid member under its own path // (CustomerEmail.Value, Quantity.Value). Strict deserialization reports the same path (on .NET 10 with // AddZodSharpProblemDetails(o => o.HandleBindingFailures = true)), but stops at the first invalid member. -app.MapPost( - "/orders", - (PlaceOrderRequest request) => - Results.Ok(new { Email = request.CustomerEmail.Value, Quantity = request.Quantity.Value }) +app.MapPost("/orders", (PlaceOrderRequest request) => + Results.Ok(new { Email = request.CustomerEmail.Value, Quantity = request.Quantity.Value }) ) .WithZodSharpValidation(); @@ -49,29 +47,26 @@ // Demonstrates on-demand mapping: a ZodException caught in the handler is converted explicitly // with ErrorType resolution, without relying on the exception-handling middleware. -app.MapGet( - "/orders/{orderId}/email", - (string orderId, string email, HttpContext httpContext) => +app.MapGet("/orders/{orderId}/email", (string orderId, string email, HttpContext httpContext) => +{ + try { - try - { - var parsed = EmailAddress.Create(email); - return Results.Ok(new { Email = parsed.Value, OrderId = orderId }); - } - catch (ZodException ex) - { - var problem = ex.ToHttpValidationProblemDetails( - new ZodProblemDetailsOptions { Registry = ErrorTypeRegistry.Default }, - httpContext - ); - return Results.Problem( - problem.Detail, - statusCode: problem.Status, - title: problem.Title, - extensions: new Dictionary { ["issues"] = problem.Extensions["issues"] } - ); - } + var parsed = EmailAddress.Create(email); + return Results.Ok(new { Email = parsed.Value, OrderId = orderId }); } -); + catch (ZodException ex) + { + var problem = ex.ToHttpValidationProblemDetails( + new ZodProblemDetailsOptions { Registry = ErrorTypeRegistry.Default }, + httpContext + ); + return Results.Problem( + problem.Detail, + statusCode: problem.Status, + title: problem.Title, + extensions: new Dictionary { ["issues"] = problem.Extensions["issues"] } + ); + } +}); app.Run(); diff --git a/src/tests/SourceGenerator.UnitTests/Generators/StringNormalizationGeneratorTests.cs b/src/tests/SourceGenerator.UnitTests/Generators/StringNormalizationGeneratorTests.cs index 531c42b..a48b143 100644 --- a/src/tests/SourceGenerator.UnitTests/Generators/StringNormalizationGeneratorTests.cs +++ b/src/tests/SourceGenerator.UnitTests/Generators/StringNormalizationGeneratorTests.cs @@ -31,8 +31,8 @@ public static class NameHarness cancellationToken ); - var createBody = - result.Generated().GetRecord("Name", "Testing").GetMethod("Create").Node.Body?.ToString() ?? string.Empty; + var createBody = result.Generated().GetRecord("Name", "Testing").GetMethod("Create").Node.Body?.ToString() + ?? string.Empty; await Assert.That(createBody).Contains("value = value?.Trim()!;"); var assembly = await Assert.That(result.CompilationResult.Assembly).IsNotNull(); @@ -64,8 +64,8 @@ public static class EmailHarness cancellationToken ); - var createBody = - result.Generated().GetRecord("Email", "Testing").GetMethod("Create").Node.Body?.ToString() ?? string.Empty; + var createBody = result.Generated().GetRecord("Email", "Testing").GetMethod("Create").Node.Body?.ToString() + ?? string.Empty; await Assert.That(createBody).Contains("value = value?.ToLowerInvariant()!;"); var assembly = await Assert.That(result.CompilationResult.Assembly).IsNotNull(); @@ -98,8 +98,11 @@ public static class CurrencyHarness cancellationToken ); - var createBody = - result.Generated().GetRecord("CurrencyCode", "Testing").GetMethod("Create").Node.Body?.ToString() + var createBody = result + .Generated() + .GetRecord("CurrencyCode", "Testing") + .GetMethod("Create") + .Node.Body?.ToString() ?? string.Empty; await Assert.That(createBody).Contains("value = value?.Trim().ToUpperInvariant()!;"); @@ -207,8 +210,7 @@ public static string CreateNormalized() cancellationToken ); - var createBody = - result.Generated().GetRecord("Contact", "Testing").GetMethod("Create").Node.Body?.ToString() + var createBody = result.Generated().GetRecord("Contact", "Testing").GetMethod("Create").Node.Body?.ToString() ?? string.Empty; await Assert.That(createBody).Contains("email = email?.Trim().ToLowerInvariant()!;"); await Assert.That(createBody).DoesNotContain("name = name?"); @@ -260,8 +262,7 @@ public static string CreateTrimmed() cancellationToken ); - var createBody = - result.Generated().GetRecord("Contact", "Testing").GetMethod("Create").Node.Body?.ToString() + var createBody = result.Generated().GetRecord("Contact", "Testing").GetMethod("Create").Node.Body?.ToString() ?? string.Empty; await Assert.That(createBody).Contains("email = email?.Trim()!;"); await Assert.That(createBody).Contains("name = name?.Trim()!;"); @@ -299,8 +300,8 @@ public static class NameHarness cancellationToken ); - var createBody = - result.Generated().GetRecord("Name", "Testing").GetMethod("Create").Node.Body?.ToString() ?? string.Empty; + var createBody = result.Generated().GetRecord("Name", "Testing").GetMethod("Create").Node.Body?.ToString() + ?? string.Empty; await Assert.That(createBody).DoesNotContain("value = value?.Trim()"); var assembly = await Assert.That(result.CompilationResult.Assembly).IsNotNull(); @@ -351,8 +352,7 @@ public static string CreateNormalized() cancellationToken ); - var createBody = - result.Generated().GetRecord("Contact", "Testing").GetMethod("Create").Node.Body?.ToString() + var createBody = result.Generated().GetRecord("Contact", "Testing").GetMethod("Create").Node.Body?.ToString() ?? string.Empty; await Assert.That(createBody).DoesNotContain("email = email?.Trim()"); diff --git a/src/tests/SourceGenerator.UnitTests/Generators/ZodSchemaValidationGeneratorTests.cs b/src/tests/SourceGenerator.UnitTests/Generators/ZodSchemaValidationGeneratorTests.cs index 8ff8981..e552ae0 100644 --- a/src/tests/SourceGenerator.UnitTests/Generators/ZodSchemaValidationGeneratorTests.cs +++ b/src/tests/SourceGenerator.UnitTests/Generators/ZodSchemaValidationGeneratorTests.cs @@ -387,8 +387,8 @@ public static bool CreateRejectsInvalid() var query = result.Generated(); await Assert.That(query.GetClass("CorporateEmailSchema", "Testing").Node).IsNotNull(); - var createBody = - query.GetRecord("CorporateEmail", "Testing").GetMethod("Create").Node.Body?.ToString() ?? string.Empty; + var createBody = query.GetRecord("CorporateEmail", "Testing").GetMethod("Create").Node.Body?.ToString() + ?? string.Empty; await Assert.That(createBody).Contains("CorporateEmailSchema.Validate(instance)"); var assembly = await Assert.That(result.CompilationResult.Assembly).IsNotNull(); From d637b1a45d1abf22f7b67981a0390477f8d37c48 Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Wed, 11 Nov 2026 22:38:11 +0000 Subject: [PATCH 4/9] chore: bumped versions --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 66f5b80..29d8f24 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -1,7 +1,7 @@ 5.9.0 - 1.81.16 + 1.83.0 2.0.0 3.0.0-prerelease.5 From 338ffc583a183495cb808d0cff8cbfe9b33a7fdc Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Wed, 11 Nov 2026 22:41:07 +0000 Subject: [PATCH 5/9] build: dotnet-config --- .config/dotnet-tools.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 7f1f239..1978504 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -19,7 +19,7 @@ "purview.build": { "version": "0.9.1", "commands": [ - "dotnet-inspect" + "purview-build" ], "rollForward": false } From cc3df7ad119e14cffa4c4e3d0668bf97b9ae0050 Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Wed, 11 Nov 2026 22:55:49 +0000 Subject: [PATCH 6/9] fix(ci): install the pinned .NET 11 SDK in the packed-consumer gate actions/setup-dotnet reads a global.json whose rollForward is latestMajor as "the latest" and installs the LTS channel, so `global-json-file: global.json` plus `dotnet-version: 10.0.x` installed only 8/9/10. Every later `dotnet` command then failed with "A compatible .NET SDK was not found" for the 11.0.100 pin, and the preflight reported it as an unrestorable dependency. Name both SDKs in the workflow, and make the preflight tell the two failures apart instead of blaming nuget.org for an unmet SDK pin. --- .github/workflows/pr.yml | 11 ++++++++--- scripts/test-packed-consumers.ps1 | 22 ++++++++++++++++++---- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index d286bfa..64e0deb 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -36,11 +36,16 @@ jobs: steps: - uses: actions/checkout@v7 - # The SDK from global.json, plus the .NET 10 runtime the oldest consumer runs on. + # The SDK global.json pins, plus the .NET 10 SDK and runtime the oldest consumer builds and runs on. The pin is + # named here rather than left to global-json-file: setup-dotnet reads a global.json whose rollForward is + # latestMajor as "the latest" and installs the LTS channel, so global-json-file alone installs 10.0.x and every + # later `dotnet` command fails with "A compatible .NET SDK was not found" for the 11.x pin. + # Keep both versions in sync with `sdk.version` in global.json. - uses: actions/setup-dotnet@v6 with: - global-json-file: global.json - dotnet-version: 10.0.x + dotnet-version: | + 11.0.100 + 10.0.x # First, before any toolchain is installed: the generator is built against the Purview.SourceGeneratorFramework # version Directory.Packages.props pins, and the consumers use the pinned Purview.ZodSharp. Until both are on diff --git a/scripts/test-packed-consumers.ps1 b/scripts/test-packed-consumers.ps1 index 6edf2bc..e243fba 100644 --- a/scripts/test-packed-consumers.ps1 +++ b/scripts/test-packed-consumers.ps1 @@ -14,8 +14,9 @@ This gate consumes the package exactly as a user does: - 1. Preflight: checks the build-time Purview.SourceGeneratorFramework and the Purview.ZodSharp packages the - consumers use can be restored, and fails early, with what to do, if they cannot. + 1. Preflight: checks the SDK global.json pins is installed, and that the build-time + Purview.SourceGeneratorFramework and the Purview.ZodSharp packages the consumers use can be restored, failing + early, with what to do, if either is not. 2. Packs every shipping package (the ids in .config/purview-build.json PackValidation.RequiredContent) to an isolated feed, with an isolated NUGET_PACKAGES, so no previously extracted package of the same version can be reused. Package validation against the API baseline runs as part of the pack. The feed must hold exactly the @@ -428,9 +429,22 @@ try { "@ | Set-Content (Join-Path $probe 'probe.csproj') -Encoding utf8 - & dotnet restore (Join-Path $probe 'probe.csproj') "-p:RestoreConfigFile=$packConfig" 2>&1 | - Tee-Object -FilePath (Join-Path $logs 'dependency-probe.log') | Out-Host + $restoreOutput = & dotnet restore (Join-Path $probe 'probe.csproj') "-p:RestoreConfigFile=$packConfig" 2>&1 + $restoreOutput | Set-Content (Join-Path $logs 'dependency-probe.log') + $restoreOutput | Out-Host if ($LASTEXITCODE -ne 0) { + # An unsatisfied global.json pin fails here too, with a non-zero exit and no package resolution at all. + # Reporting it as a missing dependency would send the reader to nuget.org for nothing. + if (($restoreOutput | Out-String) -match 'A compatible \.NET SDK was not found') { + throw ( + "No .NET SDK satisfies the $($sdk.version) pin in global.json, so the dependency probe cannot be " + + 'restored and nothing can be checked. This is not a missing package: no package resolution ran. ' + + 'Install that SDK (or a newer one, which rollForward allows) before this gate. actions/setup-dotnet ' + + 'must name it explicitly: it reads a global.json with rollForward latestMajor as "the latest" and ' + + "installs the LTS channel, so global-json-file alone does not install $($sdk.version)." + ) + } + $from = ((@($nugetOrg) + $dependencySources) | ForEach-Object Value) -join ', ' throw ( "Purview.SourceGeneratorFramework $sgfVersion or Purview.ZodSharp $zodSharpVersion (Directory.Packages.props) " + From 661877785ef74816fc22666c4df56e0fb11d2d17 Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Thu, 12 Nov 2026 08:44:47 +0000 Subject: [PATCH 7/9] test(gate): report the self-test exception stack, not just its message A failing self-test printed "FAIL the self-test threw : ". The exception that broke the trimmed Blazor WebAssembly consumer was an InvalidProgramException, which carries no message at all, so the gate reported an empty line and nothing to act on. The stack is what identified the offending frame in Purview.ZodSharp.Blazor. The stack is only written when the self-test already fails, so a passing gate reports exactly what it did before. --- scripts/packed-consumers/Shared/RegistrationSelfTest.razor | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/packed-consumers/Shared/RegistrationSelfTest.razor b/scripts/packed-consumers/Shared/RegistrationSelfTest.razor index 7f66b21..04662b1 100644 --- a/scripts/packed-consumers/Shared/RegistrationSelfTest.razor +++ b/scripts/packed-consumers/Shared/RegistrationSelfTest.razor @@ -79,6 +79,7 @@ { failures++; report.AppendLine($"FAIL the self-test threw {ex.GetType().Name}: {ex.Message}"); + report.AppendLine(ex.ToString()); } _result = failures == 0 ? "passed" : "failed"; From e2b32e078acf81e3f593d1804bb05169107f5796 Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Thu, 12 Nov 2026 10:53:06 +0000 Subject: [PATCH 8/9] chore: bumped nuget version --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 29d8f24..f6f2738 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -3,7 +3,7 @@ 5.9.0 1.83.0 2.0.0 - 3.0.0-prerelease.5 + 3.0.0-prerelease.6 From ed908e40eac7767de7612636f7f96ef2c91e6d5e Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Thu, 12 Nov 2026 11:06:39 +0000 Subject: [PATCH 9/9] chore: bumped nuget version --- global.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/global.json b/global.json index 20be547..4975af0 100644 --- a/global.json +++ b/global.json @@ -4,7 +4,7 @@ "rollForward": "latestMajor" }, "msbuild-sdks": { - "Purview.BuildSdk": "2.0.0" + "Purview.BuildSdk": "2.0.1" }, "test": { "runner": "Microsoft.Testing.Platform"