From 5b06230ce099f68e01b64c173810fc24ce51d353 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Sat, 21 Nov 2026 04:24:45 +0100 Subject: [PATCH 1/8] =?UTF-8?q?=F0=9F=93=9D=20make=20docfx=20type=20exampl?= =?UTF-8?q?es=20runnable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Type page examples now expose a Main entry point with public models, drop the redundant availability includes, and link to generated native and Docker run actions so readers can execute each sample. --- ...ewtonsoft.Json.NewtonsoftJsonNegotiator.md | 14 +++++++----- ...etCore.Text.Json.JsonResponseNegotiator.md | 19 +++++++++++----- ...etCore.Text.Yaml.YamlResponseNegotiator.md | 12 ++++++---- ...er.AspNetCore.Xml.XmlResponseNegotiator.md | 22 ++++++++++++++----- ...ter.EndpointConventionBuilderExtensions.md | 14 +++++++----- 5 files changed, 54 insertions(+), 27 deletions(-) diff --git a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json.NewtonsoftJsonNegotiator.md b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json.NewtonsoftJsonNegotiator.md index 0f24d57..ff35902 100644 --- a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json.NewtonsoftJsonNegotiator.md +++ b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json.NewtonsoftJsonNegotiator.md @@ -1,15 +1,13 @@ --- uid: Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json.NewtonsoftJsonNegotiator -summary: *content +example: [*content] --- The `NewtonsoftJsonNegotiator` integrates Newtonsoft.Json serialization into the Carter response pipeline. Register it as the response negotiator to have all `HttpResponse.Negotiate()` calls produce JSON output using Newtonsoft.Json's configurable serializer. -[!INCLUDE [availability-modern](../../includes/availability-modern.md)] - ### Example -The following example demonstrates how to register `NewtonsoftJsonNegotiator` with a custom converter and negotiate a response model. +To inspect the JSON a Carter client would receive, pass the requested media type to the negotiator and serialize a response into a memory stream. The stream makes the response body readable without starting a server. ```csharp using System; @@ -27,14 +25,16 @@ namespace DocfxExample; public static class NewtonsoftJsonNegotiatorExample { - public static async Task DemonstrateAsync() + public static async Task Main() { var options = Options.Create(new NewtonsoftJsonFormatterOptions()); var negotiator = new NewtonsoftJsonNegotiator(options); var acceptHeader = MediaTypeHeaderValue.Parse("application/json"); if (negotiator.CanHandle(acceptHeader)) { + using var body = new MemoryStream(); var context = new DefaultHttpContext(); + context.Response.Body = body; context.Request.Headers.Accept = "application/json"; var model = new { Name = "Newtonsoft", Value = 42 }; await negotiator.Handle(context.Request, context.Response, model, CancellationToken.None); @@ -45,3 +45,7 @@ public static class NewtonsoftJsonNegotiatorExample } } ``` + + +
View Native Script · View Docker Script
+ diff --git a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Json.JsonResponseNegotiator.md b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Json.JsonResponseNegotiator.md index 180f2fd..66d4681 100644 --- a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Json.JsonResponseNegotiator.md +++ b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Json.JsonResponseNegotiator.md @@ -1,20 +1,19 @@ --- uid: Codebelt.Extensions.Carter.AspNetCore.Text.Json.JsonResponseNegotiator -summary: *content +example: [*content] --- The `JsonResponseNegotiator` integrates System.Text.Json serialization into the Carter response pipeline. Register it as the response negotiator to have all `HttpResponse.Negotiate()` calls produce JSON output using the modern, high-performance System.Text.Json serializer. -[!INCLUDE [availability-modern](../../includes/availability-modern.md)] - ### Example -The following example demonstrates how to register `JsonResponseNegotiator` and negotiate a response model with custom options. +To inspect the System.Text.Json output for a response model, pass the requested media type to the negotiator and serialize into a memory stream. The explicit type information resolver allows the formatter to serialize the anonymous model even when the host disables reflection-based serialization by default. ```csharp using System; using System.IO; using System.Text; +using System.Text.Json.Serialization.Metadata; using System.Threading; using System.Threading.Tasks; using Codebelt.Extensions.Carter.AspNetCore.Text.Json; @@ -27,14 +26,18 @@ namespace DocfxExample; public static class JsonResponseNegotiatorExample { - public static async Task DemonstrateAsync() + public static async Task Main() { - var options = Options.Create(new JsonFormatterOptions()); + var formatterOptions = new JsonFormatterOptions(); + formatterOptions.Settings.TypeInfoResolver = new DefaultJsonTypeInfoResolver(); + var options = Options.Create(formatterOptions); var negotiator = new JsonResponseNegotiator(options); var acceptHeader = MediaTypeHeaderValue.Parse("application/json"); if (negotiator.CanHandle(acceptHeader)) { + using var body = new MemoryStream(); var context = new DefaultHttpContext(); + context.Response.Body = body; context.Request.Headers.Accept = "application/json"; var model = new { Name = "System.Text.Json", Value = 42 }; await negotiator.Handle(context.Request, context.Response, model, CancellationToken.None); @@ -45,3 +48,7 @@ public static class JsonResponseNegotiatorExample } } ``` + + +
View Native Script · View Docker Script
+ diff --git a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Yaml.YamlResponseNegotiator.md b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Yaml.YamlResponseNegotiator.md index 0c4aa58..9f848f2 100644 --- a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Yaml.YamlResponseNegotiator.md +++ b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Yaml.YamlResponseNegotiator.md @@ -1,12 +1,10 @@ --- uid: Codebelt.Extensions.Carter.AspNetCore.Text.Yaml.YamlResponseNegotiator -summary: *content +example: [*content] --- The `YamlResponseNegotiator` integrates YamlDotNet serialization into the Carter response pipeline. Register it as the response negotiator to have all `HttpResponse.Negotiate()` calls produce YAML output—ideal for tooling, configuration, and DevOps-focused APIs. -[!INCLUDE [availability-modern](../../includes/availability-modern.md)] - ### Example `YamlResponseNegotiator` is constructed with an `IOptions` that controls supported media types and YamlDotNet serialization settings. Before serializing a model, the negotiator tests the client's `Accept` header via `CanHandle`; only when it returns `true` is `Handle` called to produce YAML output. `Handle` resolves the character encoding from the `Accept-Charset` header (falling back to `YamlFormatterOptions.Encoding`), sets the `Content-Type` response header, and streams the serialized YAML directly to the response body. @@ -29,14 +27,16 @@ namespace DocfxExample; public static class YamlResponseNegotiatorExample { - public static async Task DemonstrateAsync() + public static async Task Main() { var options = Options.Create(new YamlFormatterOptions()); var negotiator = new YamlResponseNegotiator(options); var acceptHeader = MediaTypeHeaderValue.Parse("application/yaml"); if (negotiator.CanHandle(acceptHeader)) { + using var body = new MemoryStream(); var context = new DefaultHttpContext(); + context.Response.Body = body; context.Request.Headers.Accept = "application/yaml"; var model = new { Name = "YamlDotNet", Value = 42 }; await negotiator.Handle(context.Request, context.Response, model, CancellationToken.None); @@ -47,3 +47,7 @@ public static class YamlResponseNegotiatorExample } } ``` + + + + diff --git a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Xml.XmlResponseNegotiator.md b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Xml.XmlResponseNegotiator.md index 1ada18e..e073923 100644 --- a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Xml.XmlResponseNegotiator.md +++ b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Xml.XmlResponseNegotiator.md @@ -1,17 +1,15 @@ --- uid: Codebelt.Extensions.Carter.AspNetCore.Xml.XmlResponseNegotiator -summary: *content +example: [*content] --- The `XmlResponseNegotiator` integrates System.Xml XML serialization into the Carter response pipeline. Register it as the response negotiator to have all `HttpResponse.Negotiate()` calls produce standards-compliant XML output—suitable for legacy interoperability and enterprise integration scenarios. -[!INCLUDE [availability-modern](../../includes/availability-modern.md)] - ### Example `XmlResponseNegotiator` is constructed with an `IOptions` that controls supported media types and System.Xml serialization settings, including writer encoding. Before serializing a model, the negotiator tests the client's `Accept` header via `CanHandle`; only when it returns `true` is `Handle` called to produce XML output. `Handle` resolves the character encoding from the `Accept-Charset` header (falling back to `XmlFormatterOptions.Settings.Writer.Encoding`), sets the `Content-Type` response header, and streams the serialized XML directly to the response body. -The following example constructs the negotiator with default options, confirms that the `application/xml` media type is accepted, then writes an anonymous object to an in-memory response stream and reads back the serialized output: +The following example constructs the negotiator with default options, confirms that the `application/xml` media type is accepted, then writes a public model to an in-memory response stream and reads back the serialized output: ```csharp using System; @@ -29,16 +27,18 @@ namespace DocfxExample; public static class XmlResponseNegotiatorExample { - public static async Task DemonstrateAsync() + public static async Task Main() { var options = Options.Create(new XmlFormatterOptions()); var negotiator = new XmlResponseNegotiator(options); var acceptHeader = MediaTypeHeaderValue.Parse("application/xml"); if (negotiator.CanHandle(acceptHeader)) { + using var body = new MemoryStream(); var context = new DefaultHttpContext(); + context.Response.Body = body; context.Request.Headers.Accept = "application/xml"; - var model = new { Name = "XML", Value = 42 }; + var model = new Report { Name = "XML", Value = 42 }; await negotiator.Handle(context.Request, context.Response, model, CancellationToken.None); context.Response.Body.Position = 0; using var reader = new StreamReader(context.Response.Body, Encoding.UTF8); @@ -46,4 +46,14 @@ public static class XmlResponseNegotiatorExample } } } + +public sealed class Report +{ + public string Name { get; set; } = string.Empty; + public int Value { get; set; } +} ``` + + + + diff --git a/.docfx/api/types/Codebelt.Extensions.Carter.EndpointConventionBuilderExtensions.md b/.docfx/api/types/Codebelt.Extensions.Carter.EndpointConventionBuilderExtensions.md index 55002cb..318a611 100644 --- a/.docfx/api/types/Codebelt.Extensions.Carter.EndpointConventionBuilderExtensions.md +++ b/.docfx/api/types/Codebelt.Extensions.Carter.EndpointConventionBuilderExtensions.md @@ -1,19 +1,17 @@ --- uid: Codebelt.Extensions.Carter.EndpointConventionBuilderExtensions -summary: *content +example: [*content] --- Attach typed response metadata to any Carter or minimal API endpoint by calling `Produces` or `Produces` on an `IEndpointConventionBuilder`. Each call records an `IProducesResponseTypeMetadata` entry that OpenAPI tooling reads to document the endpoint's response shape and status codes. -[!INCLUDE [availability-modern](../../includes/availability-modern.md)] - > **Note:** DocFX does not yet generate complete API metadata for C# 14 extension block members ([docfx#11010](https://github.com/dotnet/docfx/issues/11010)). The extension methods themselves are fully functional; the limitation is cosmetic in generated API docs only. ### Example `Produces` and `Produces` attach `IProducesResponseTypeMetadata` directly to an endpoint builder. `Produces` records the response body type, HTTP status code, and accepted content types; `Produces` (no type parameter) records a status-only response with no body—useful for `404`, `401`, and similar cases. Both are chainable and are typically called on a `RouteHandlerBuilder` inside a Carter module or minimal API route definition. -The following example constructs an endpoint builder directly, calls the extension members through their declaring type, and reads back the attached metadata to show what each call contributes: +The following example constructs an endpoint builder directly, applies both extension members to the convention builder, and reads back the attached metadata to show what each call contributes: ```csharp using System; @@ -31,7 +29,7 @@ namespace DocfxExample; public static class ProducesExtensionExample { - public static void Demonstrate() + public static void Main() { var endpointBuilder = new RouteEndpointBuilder( context => Task.CompletedTask, @@ -40,7 +38,7 @@ public static class ProducesExtensionExample var fakeBuilder = new FakeEndpointConventionBuilder(); EndpointConventionBuilderExtensions.Produces(fakeBuilder, StatusCodes.Status200OK, "application/json"); - EndpointConventionBuilderExtensions.Produces(fakeBuilder, StatusCodes.Status404NotFound); + fakeBuilder.Produces(StatusCodes.Status404NotFound); foreach (var convention in fakeBuilder.Conventions) { @@ -66,5 +64,9 @@ public static class ProducesExtensionExample public sealed record OrderSummary(int Id, string Name); ``` + + + + The `Produces` and `Produces` extension members are the same methods used when chaining on a `RouteHandlerBuilder` inside a Carter module: `app.MapGet("/orders/{id}", ...).Produces().Produces(404)`. From a6f52cf517e019ce939188700686200dc54cd74c Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Sat, 21 Nov 2026 04:24:50 +0100 Subject: [PATCH 2/8] =?UTF-8?q?=F0=9F=94=A8=20add=20docfx=20run-actions=20?= =?UTF-8?q?build=20script?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the run-actions manifest, settings and build script, and wires the run-actions content and template into docfx.json so example pages can publish native and Docker run scripts. --- .docfx/BuildRunActions.ps1 | 283 +++++++++++++++++++++++++++++++ .docfx/docfx.json | 11 +- .docfx/run-actions.manifest.json | 115 +++++++++++++ .docfx/run-actions.settings.json | 84 +++++++++ 4 files changed, 491 insertions(+), 2 deletions(-) create mode 100644 .docfx/BuildRunActions.ps1 create mode 100644 .docfx/run-actions.manifest.json create mode 100644 .docfx/run-actions.settings.json diff --git a/.docfx/BuildRunActions.ps1 b/.docfx/BuildRunActions.ps1 new file mode 100644 index 0000000..7a2680b --- /dev/null +++ b/.docfx/BuildRunActions.ps1 @@ -0,0 +1,283 @@ +#requires -Version 7.0 +[CmdletBinding()] +param( + [string] $ManifestPath = (Join-Path $PSScriptRoot 'run-actions.manifest.json'), + [string] $OutputRoot = (Join-Path $PSScriptRoot 'run-actions') +) +$ErrorActionPreference = 'Stop' +$PSNativeCommandUseErrorActionPreference = $false +Set-StrictMode -Version Latest + +if (-not (Test-Path -LiteralPath $ManifestPath -PathType Leaf)) { + if ($PSBoundParameters.ContainsKey('ManifestPath')) { + throw "Run-actions manifest not found: $ManifestPath" + } + Write-Host "No run-actions manifest found at $ManifestPath; skipping." + return +} + +$CsrunTestVerificationTemplate = @' +function Assert-CsrunTestOutput([string] $Output) { + $lines = @($Output -split '\r?\n') + $headers = @($lines | Where-Object { $_ -match '^Test run summary: Passed! - .+\)$' }) + if ($headers.Count -ne 1) { throw 'Expected exactly one completed xUnit test summary.' } + $headerIndex = [Array]::IndexOf($lines, $headers[0]) + $summaryLines = @($lines | Select-Object -Skip ($headerIndex + 1) -First 4) + $counts = @{} + foreach ($line in $summaryLines) { + if ($line -match '^\s*(total|failed|succeeded|skipped):\s*(\d+)\s*$') { $counts[$Matches[1]] = [int]$Matches[2] } + } + if ($counts.Count -ne 4) { throw 'The xUnit test summary counts are incomplete or ambiguous.' } + $failed = $counts.failed + $passed = $counts.succeeded + $skipped = $counts.skipped + $total = $counts.total + if ($total -lt 1 -or $passed -lt 1 -or $failed -ne 0 -or $skipped -ne 0 -or $passed -ne $total) { + throw 'Tests must execute at least once, all pass, and none fail or skip.' + } +} +'@ + +function Normalize([string] $Text) { $Text.Replace("`r`n", "`n").TrimEnd("`n", "`r") } +function Quote-Literal([string] $Value) { "'" + $Value.Replace("'", "''") + "'" } + +function Sort-ManifestValue($Value) { + if ($Value -is [System.Collections.IDictionary]) { + $ordered = [ordered]@{} + [string[]] $keys = @($Value.Keys) + [Array]::Sort($keys, [StringComparer]::Ordinal) + foreach ($key in $keys) { $ordered[$key] = Sort-ManifestValue $Value[$key] } + return $ordered + } + if ($Value -is [array]) { return ,@($Value | ForEach-Object { Sort-ManifestValue $_ }) } + return $Value +} + +function New-StandalonePair { + param( + [Parameter(Mandatory)][hashtable] $Manifest, + [Parameter(Mandatory)][string] $Image + ) + $ordered = Sort-ManifestValue $Manifest + $manifestJson = ConvertTo-Json -InputObject $ordered -Depth 100 + $verifyTests = $ordered.mode -eq 'test' + $prefix = "#requires -Version 7.0`n`$ErrorActionPreference = 'Stop'`n`$PSNativeCommandUseErrorActionPreference = `$false`n`$manifest = @'`n" + $manifestJson + "`n'@`n" + $suffix = @' +if ($process.ExitCode -ne 0) { throw "csrun execution failed with exit code $($process.ExitCode). $diagnostics" } +if ($verifyTests) { Assert-CsrunTestOutput $output } +'@ + $engineSetup = @' +# Downloads and executes the latest stable csrun release with your permissions. +# Source and release history: https://github.com/codebeltnet/csrun +$engineDirectory = Join-Path ([IO.Path]::GetTempPath()) ('csrun-' + [guid]::NewGuid().ToString('N')) +$null = New-Item -ItemType Directory -Path $engineDirectory +$enginePath = Join-Path $engineDirectory 'csrun.ps1' +$process = $null +try { + $release = Invoke-RestMethod 'https://api.github.com/repos/codebeltnet/csrun/releases/latest' + $assets = @($release.assets | Where-Object name -CEQ 'csrun.ps1') + if ($assets.Count -ne 1 -or $assets[0].digest -notmatch '^sha256:[0-9a-f]{64}$') { + throw "csrun release $($release.tag_name) must publish one csrun.ps1 asset with a SHA-256 digest." + } + $asset = $assets[0] + Invoke-WebRequest $asset.browser_download_url -OutFile $enginePath + $actualHash = (Get-FileHash -LiteralPath $enginePath -Algorithm SHA256).Hash + if ("sha256:$actualHash" -ne $asset.digest) { throw "csrun asset checksum mismatch: $actualHash" } +'@ + $nativeInvoke = @' +$startInfo = [Diagnostics.ProcessStartInfo]::new('pwsh') +foreach ($argument in @('-NoProfile','-NonInteractive','-File')) { $startInfo.ArgumentList.Add($argument) } +$startInfo.ArgumentList.Add($enginePath) +$startInfo.ArgumentList.Add('-ManifestJson') +$startInfo.ArgumentList.Add($manifest) +$startInfo.RedirectStandardOutput = $true +$startInfo.RedirectStandardError = $true +$startInfo.UseShellExecute = $false +$process = [Diagnostics.Process]::new() +$process.StartInfo = $startInfo +if (-not $process.Start()) { throw 'Could not start csrun.' } +$stdoutTask = $process.StandardOutput.ReadToEndAsync() +$stderrTask = $process.StandardError.ReadToEndAsync() +$process.WaitForExit() +$output = $stdoutTask.GetAwaiter().GetResult() +$diagnostics = $stderrTask.GetAwaiter().GetResult() +Write-Output $output +if ($diagnostics) { [Console]::Error.Write($diagnostics) } +'@ + $dockerInvoke = (@' +$enginePayload = [Convert]::ToBase64String([IO.File]::ReadAllBytes($enginePath)) +$containerInput = $enginePayload + "`n" + $manifest +$command = ' +$ErrorActionPreference = "Stop" +$enginePath = Join-Path ([IO.Path]::GetTempPath()) ("csrun-release-" + [guid]::NewGuid().ToString("N") + ".ps1") +$engineBytes = [Convert]::FromBase64String([Console]::In.ReadLine()) +[IO.File]::WriteAllBytes($enginePath, $engineBytes) +$manifest = [Console]::In.ReadToEnd() +& $enginePath -ManifestJson $manifest +exit $LASTEXITCODE +' +$output = (@($containerInput | & docker run --rm -i --entrypoint pwsh __IMAGE__ -NoProfile -NonInteractive -Command $command) -join [Environment]::NewLine) +$process = [pscustomobject]@{ ExitCode = $LASTEXITCODE } +$diagnostics = '' +Write-Output $output +'@).Replace('__IMAGE__', (Quote-Literal $Image)) + $engineCleanup = @' +} catch { + [Console]::Error.WriteLine("csrun diagnostics retained in: $engineDirectory") + throw +} finally { + $resolvedTemp = [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetFullPath([IO.Path]::GetTempPath())) + $resolvedEngineDirectory = [IO.Path]::GetFullPath($engineDirectory) + if ([IO.Path]::GetDirectoryName($resolvedEngineDirectory) -ne $resolvedTemp -or + [IO.Path]::GetFileName($resolvedEngineDirectory) -cnotmatch '^csrun-[a-f0-9]{32}$') { throw 'Unsafe cleanup path.' } + if ($process -and $process.ExitCode -eq 0) { Remove-Item -LiteralPath $resolvedEngineDirectory -Recurse -Force } +} +'@ + $encoding = '$OutputEncoding = [Text.UTF8Encoding]::new($false)' + "`n" + '[Console]::OutputEncoding = $OutputEncoding' + "`n" + $native = "& {`n" + ($prefix + $encoding + '$verifyTests = $' + $verifyTests.ToString().ToLowerInvariant() + "`n" + $CsrunTestVerificationTemplate + "`n" + $engineSetup + "`n" + $nativeInvoke + "`n" + $engineCleanup + "`n" + $suffix).TrimEnd() + "`n}`n" + $docker = "& {`n" + ($prefix + $encoding + '$verifyTests = $' + $verifyTests.ToString().ToLowerInvariant() + "`n" + $CsrunTestVerificationTemplate + "`n" + $engineSetup + "`n" + $dockerInvoke + "`n" + $engineCleanup + "`n" + $suffix).TrimEnd() + "`n}`n" + return @{ native = $native; docker = $docker } +} + +function New-RepositoryPair { + param( + [Parameter(Mandatory)][string] $Repository, + [Parameter(Mandatory)][string] $Commit, + [Parameter(Mandatory)][string] $Project, + [Parameter(Mandatory)][string] $Test, + [Parameter(Mandatory)][string] $Framework, + [Parameter(Mandatory)][string] $Image + ) + if ($Repository -notmatch '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$' -or $Commit -notmatch '^[a-fA-F0-9]{40}$' -or + $Project -notmatch '^[A-Za-z0-9_./-]+\.csproj$' -or $Project.Split('/') -contains '..' -or $Project.StartsWith('/') -or + $Test -notmatch '^[A-Za-z0-9_.+]+$' -or $Framework -notmatch '^net\d+\.\d+$' -or + $Image -notmatch '^mcr\.microsoft\.com/dotnet/sdk:[A-Za-z0-9_.-]+$') { + throw 'Expected a pinned GitHub repository, relative project, exact xUnit method, TFM and official SDK image.' + } + $template = @' +& { +#requires -Version 7.0 + $ErrorActionPreference = 'Stop' + $PSNativeCommandUseErrorActionPreference = $false + # Executes trusted repository build tasks and NuGet packages with your permissions. + # Review the pinned source before running; a container is not a security sandbox. + __PREREQUISITE__ + $work = Join-Path ([IO.Path]::GetTempPath()) ('dx-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) + $null = New-Item -ItemType Directory -Path $work + try { + $commit = '__COMMIT__' + Invoke-WebRequest "https://codeload.github.com/__REPOSITORY__/zip/$commit" -OutFile "$work/source.zip" + Expand-Archive -LiteralPath "$work/source.zip" -DestinationPath "$work/extracted" + Move-Item -LiteralPath "$work/extracted/__ARCHIVE__-$commit" -Destination "$work/repo" + $project = '__PROJECT__' + $test = '__TEST__' + __EXECUTE__ + $code = $LASTEXITCODE + if ($code -ne 0) { throw "Repository test failed with exit code $code. See $work/run.log" } + # Require exactly the original test, executed and passing, with no runner errors. + [xml] $report = Get-Content -LiteralPath "$work/results/result.xml" -Raw + $tests = @($report.SelectNodes('/assemblies/assembly/collection/test')) + $assemblies = @($report.SelectNodes('/assemblies/assembly')) + if ($assemblies.Count -ne 1 -or $assemblies[0].total -ne '1' -or $assemblies[0].passed -ne '1' -or + $assemblies[0].errors -ne '0' -or $tests.Count -ne 1 -or $tests[0].name -cne $test -or $tests[0].result -cne 'Pass') { + throw "Expected exactly one passing $test; inspect $work/results/result.xml" + } + Write-Host "Verified: $test (1 executed, 1 passed)." + } + catch { + # Preserve diagnostics outside the repository even though downloaded source is cleaned. + $diagnostics = "$work-diagnostics" + $null = New-Item -ItemType Directory -Path $diagnostics -Force + foreach ($name in @('run.log', 'results')) { + if (Test-Path -LiteralPath "$work/$name") { Copy-Item -LiteralPath "$work/$name" -Destination $diagnostics -Recurse } + } + Write-Warning "Execution not verified. Diagnostics: $diagnostics" + throw + } + finally { + $resolved = [IO.Path]::GetFullPath($work) + $temp = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('/','\') + [IO.Path]::DirectorySeparatorChar + if (-not $resolved.StartsWith($temp, [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe cleanup path.' } + Remove-Item -LiteralPath $resolved -Recurse -Force + } +} +'@ + $native = (@' +Push-Location "$work/repo" + try { + dotnet run --project $project --framework __FRAMEWORK__ -p:SkipSignAssembly=true -- --filter-method $test --report-xunit-xml --report-xunit-xml-filename result.xml --results-directory "$work/results" 2>&1 | Tee-Object -FilePath "$work/run.log" + } + finally { Pop-Location } +'@).Replace('__FRAMEWORK__', $Framework) + $docker = (@' +$dockerUser = @() + if ($IsLinux) { + # Keep bind-mounted build output removable by the host user. + $hostUid = id -u + if ($LASTEXITCODE -ne 0) { throw 'Cannot resolve host UID.' } + $hostGid = id -g + if ($LASTEXITCODE -ne 0) { throw 'Cannot resolve host GID.' } + $dockerUser = @('--user', "${hostUid}:${hostGid}") + } + # Let Docker's init reap orphaned build processes and keep build servers disposable. + docker run --rm --init @dockerUser --env HOME=/tmp --env DOTNET_CLI_HOME=/tmp --env MSBUILDDISABLENODEREUSE=1 --mount "type=bind,source=$work,target=/work" --workdir /work/repo __IMAGE__ dotnet run --disable-build-servers --project $project --framework __FRAMEWORK__ -p:SkipSignAssembly=true -- --filter-method $test --report-xunit-xml --report-xunit-xml-filename result.xml --results-directory /work/results 2>&1 | Tee-Object -FilePath "$work/run.log" +'@).Replace('__FRAMEWORK__', $Framework).Replace('__IMAGE__', $Image) + $template = $template.Replace('__COMMIT__', $Commit).Replace('__REPOSITORY__', $Repository).Replace('__ARCHIVE__', $Repository.Split('/')[1]).Replace('__PROJECT__', $Project).Replace('__TEST__', $Test) + return @{ + native = $template.Replace('__PREREQUISITE__', "`$null = Get-Command dotnet -ErrorAction Stop").Replace('__EXECUTE__', $native) + docker = $template.Replace('__PREREQUISITE__', "`$null = Get-Command docker -ErrorAction Stop`n docker info *> `$null`n if (`$LASTEXITCODE -ne 0) { throw 'Docker daemon unavailable.' }").Replace('__EXECUTE__', $docker) + } +} + +$doc = Get-Content -LiteralPath $ManifestPath -Raw | ConvertFrom-Json -AsHashtable +if ($doc.schemaVersion -ne 1) { throw "Unsupported run-actions manifest schemaVersion: $($doc.schemaVersion)" } +$examples = @($doc.examples) +$utf8NoBom = [Text.UTF8Encoding]::new($false) +$expectedScripts = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) +$written = 0 + +foreach ($example in $examples) { + $id = [string] $example.id + if ($id -cnotmatch '^[a-f0-9]{24}$') { throw "Invalid run-action id: $id" } + $pair = if ($example.strategy -ceq 'repository') { + New-RepositoryPair -Repository $example.repository -Commit $example.commit -Project $example.project -Test $example.test -Framework $example.framework -Image $example.image + } elseif ($example.strategy -ceq 'standalone') { + New-StandalonePair -Manifest $example.manifest -Image $example.image + } else { + throw "Unsupported run-action strategy '$($example.strategy)' for $id" + } + $dir = Join-Path $OutputRoot $id + foreach ($transport in @($example.transports)) { + if ($transport -notin @('native', 'docker')) { throw "Unsupported transport '$transport' for $id" } + $scriptText = Normalize $pair[$transport] + $tokens = $null; $errors = $null + $null = [Management.Automation.Language.Parser]::ParseInput($scriptText, [ref]$tokens, [ref]$errors) + if ($errors.Count) { throw "Materialized $transport script for $id has syntax errors: $errors" } + $path = Join-Path $dir "$transport.ps1" + if (-not (Test-Path -LiteralPath $path) -or [IO.File]::ReadAllText($path) -cne $scriptText) { + $null = [IO.Directory]::CreateDirectory($dir) + [IO.File]::WriteAllText($path, $scriptText, $utf8NoBom) + } + $null = $expectedScripts.Add("$id/$transport.ps1") + $written++ + } +} + +if (Test-Path -LiteralPath $OutputRoot -PathType Container) { + foreach ($exampleDir in @(Get-ChildItem -LiteralPath $OutputRoot -Directory)) { + if ($exampleDir.Name -cnotmatch '^[a-f0-9]{24}$' -or + ($exampleDir.Attributes -band [IO.FileAttributes]::ReparsePoint)) { continue } + foreach ($name in @('native.ps1', 'docker.ps1')) { + if ($expectedScripts.Contains("$($exampleDir.Name)/$name")) { continue } + $stalePath = Join-Path $exampleDir.FullName $name + if (Test-Path -LiteralPath $stalePath -PathType Leaf) { + Remove-Item -LiteralPath $stalePath -Force + } + } + if (-not @(Get-ChildItem -LiteralPath $exampleDir.FullName -Force).Count) { + Remove-Item -LiteralPath $exampleDir.FullName + } + } +} + +Write-Host "Materialized $written run-action script(s) for $($examples.Count) example(s) into $OutputRoot." diff --git a/.docfx/docfx.json b/.docfx/docfx.json index 7ebdab2..37709e0 100644 --- a/.docfx/docfx.json +++ b/.docfx/docfx.json @@ -24,7 +24,8 @@ "build": { "sitemap": { "changefreq": "monthly", - "baseUrl": "https://carter.codebelt.net/"}, + "baseUrl": "https://carter.codebelt.net/" + }, "xref": [ "https://docs.cuemon.net/xrefmap.yml?v=20260120", "https://newtonsoft.codebelt.net/xrefmap.yml", @@ -52,6 +53,11 @@ "files": [ "images/**" ] + }, + { + "files": [ + "run-actions/**" + ] } ], "globalMetadata": { @@ -74,7 +80,8 @@ "template": [ "default", "modern", - "templates/ms-style" + "templates/ms-style", + "run-actions-template" ], "overwrite": [ { diff --git a/.docfx/run-actions.manifest.json b/.docfx/run-actions.manifest.json new file mode 100644 index 0000000..d53dbef --- /dev/null +++ b/.docfx/run-actions.manifest.json @@ -0,0 +1,115 @@ +{ + "schemaVersion": 1, + "examples": [ + { + "id": "6352b06e7d9ea46088bd7abf", + "strategy": "standalone", + "transports": [ + "native", + "docker" + ], + "image": "codebeltnet/csrun:10", + "manifest": { + "schemaVersion": 1, + "mode": "console", + "framework": "net10.0", + "sdk": "Microsoft.NET.Sdk.Web", + "frameworkReferences": [ + "Microsoft.AspNetCore.App" + ], + "dependsOn": [ + "Codebelt.Extensions.Carter.AspNetCore.Text.Json@1.1.0" + ], + "source": "using System;\nusing System.IO;\nusing System.Text;\nusing System.Text.Json.Serialization.Metadata;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Codebelt.Extensions.Carter.AspNetCore.Text.Json;\nusing Cuemon.Extensions.Text.Json.Formatters;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.Extensions.Options;\nusing Microsoft.Net.Http.Headers;\n\nnamespace DocfxExample;\n\npublic static class JsonResponseNegotiatorExample\n{\n public static async Task Main()\n {\n var formatterOptions = new JsonFormatterOptions();\n formatterOptions.Settings.TypeInfoResolver = new DefaultJsonTypeInfoResolver();\n var options = Options.Create(formatterOptions);\n var negotiator = new JsonResponseNegotiator(options);\n var acceptHeader = MediaTypeHeaderValue.Parse(\"application/json\");\n if (negotiator.CanHandle(acceptHeader))\n {\n using var body = new MemoryStream();\n var context = new DefaultHttpContext();\n context.Response.Body = body;\n context.Request.Headers.Accept = \"application/json\";\n var model = new { Name = \"System.Text.Json\", Value = 42 };\n await negotiator.Handle(context.Request, context.Response, model, CancellationToken.None);\n context.Response.Body.Position = 0;\n using var reader = new StreamReader(context.Response.Body, Encoding.UTF8);\n Console.WriteLine(await reader.ReadToEndAsync());\n }\n }\n}" + } + }, + { + "id": "83888118c4da05f5423d7ce9", + "strategy": "standalone", + "transports": [ + "native", + "docker" + ], + "image": "codebeltnet/csrun:10", + "manifest": { + "schemaVersion": 1, + "mode": "console", + "framework": "net10.0", + "sdk": "Microsoft.NET.Sdk.Web", + "frameworkReferences": [ + "Microsoft.AspNetCore.App" + ], + "dependsOn": [ + "Codebelt.Extensions.Carter@1.1.0" + ], + "source": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Codebelt.Extensions.Carter;\nusing Microsoft.AspNetCore.Builder;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.AspNetCore.Http.Metadata;\nusing Microsoft.AspNetCore.Routing;\nusing Microsoft.AspNetCore.Routing.Patterns;\n\nnamespace DocfxExample;\n\npublic static class ProducesExtensionExample\n{\n public static void Main()\n {\n var endpointBuilder = new RouteEndpointBuilder(\n context => Task.CompletedTask,\n RoutePatternFactory.Parse(\"/api/orders\"),\n 0);\n\n var fakeBuilder = new FakeEndpointConventionBuilder();\n EndpointConventionBuilderExtensions.Produces(fakeBuilder, StatusCodes.Status200OK, \"application/json\");\n fakeBuilder.Produces(StatusCodes.Status404NotFound);\n\n foreach (var convention in fakeBuilder.Conventions)\n {\n convention(endpointBuilder);\n }\n\n foreach (var metadata in endpointBuilder.Metadata.OfType())\n {\n Console.WriteLine(\n $\"Status: {metadata.StatusCode}, \" +\n $\"Type: {metadata.Type?.Name ?? \"(none)\"}, \" +\n $\"ContentTypes: {string.Join(\", \", metadata.ContentTypes)}\");\n }\n }\n\n private sealed class FakeEndpointConventionBuilder : IEndpointConventionBuilder\n {\n public List> Conventions { get; } = [];\n public void Add(Action convention) => Conventions.Add(convention);\n }\n}\n\npublic sealed record OrderSummary(int Id, string Name);" + } + }, + { + "id": "93c4f046477745c9b8272f18", + "strategy": "standalone", + "transports": [ + "native", + "docker" + ], + "image": "codebeltnet/csrun:10", + "manifest": { + "schemaVersion": 1, + "mode": "console", + "framework": "net10.0", + "sdk": "Microsoft.NET.Sdk.Web", + "frameworkReferences": [ + "Microsoft.AspNetCore.App" + ], + "dependsOn": [ + "Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json@1.1.0" + ], + "source": "using System;\nusing System.IO;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json;\nusing Codebelt.Extensions.Newtonsoft.Json.Formatters;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.Extensions.Options;\nusing Microsoft.Net.Http.Headers;\n\nnamespace DocfxExample;\n\npublic static class NewtonsoftJsonNegotiatorExample\n{\n public static async Task Main()\n {\n var options = Options.Create(new NewtonsoftJsonFormatterOptions());\n var negotiator = new NewtonsoftJsonNegotiator(options);\n var acceptHeader = MediaTypeHeaderValue.Parse(\"application/json\");\n if (negotiator.CanHandle(acceptHeader))\n {\n using var body = new MemoryStream();\n var context = new DefaultHttpContext();\n context.Response.Body = body;\n context.Request.Headers.Accept = \"application/json\";\n var model = new { Name = \"Newtonsoft\", Value = 42 };\n await negotiator.Handle(context.Request, context.Response, model, CancellationToken.None);\n context.Response.Body.Position = 0;\n using var reader = new StreamReader(context.Response.Body, Encoding.UTF8);\n Console.WriteLine(await reader.ReadToEndAsync());\n }\n }\n}" + } + }, + { + "id": "bf3b685f7384b7944901e7d0", + "strategy": "standalone", + "transports": [ + "native", + "docker" + ], + "image": "codebeltnet/csrun:10", + "manifest": { + "schemaVersion": 1, + "mode": "console", + "framework": "net10.0", + "sdk": "Microsoft.NET.Sdk.Web", + "frameworkReferences": [ + "Microsoft.AspNetCore.App" + ], + "dependsOn": [ + "Codebelt.Extensions.Carter.AspNetCore.Text.Yaml@1.1.0" + ], + "source": "using System;\nusing System.IO;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Codebelt.Extensions.Carter.AspNetCore.Text.Yaml;\nusing Codebelt.Extensions.YamlDotNet.Formatters;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.Extensions.Options;\nusing Microsoft.Net.Http.Headers;\n\nnamespace DocfxExample;\n\npublic static class YamlResponseNegotiatorExample\n{\n public static async Task Main()\n {\n var options = Options.Create(new YamlFormatterOptions());\n var negotiator = new YamlResponseNegotiator(options);\n var acceptHeader = MediaTypeHeaderValue.Parse(\"application/yaml\");\n if (negotiator.CanHandle(acceptHeader))\n {\n using var body = new MemoryStream();\n var context = new DefaultHttpContext();\n context.Response.Body = body;\n context.Request.Headers.Accept = \"application/yaml\";\n var model = new { Name = \"YamlDotNet\", Value = 42 };\n await negotiator.Handle(context.Request, context.Response, model, CancellationToken.None);\n context.Response.Body.Position = 0;\n using var reader = new StreamReader(context.Response.Body, Encoding.UTF8);\n Console.WriteLine(await reader.ReadToEndAsync());\n }\n }\n}" + } + }, + { + "id": "f53010d9cc9ec55bc07adac2", + "strategy": "standalone", + "transports": [ + "native", + "docker" + ], + "image": "codebeltnet/csrun:10", + "manifest": { + "schemaVersion": 1, + "mode": "console", + "framework": "net10.0", + "sdk": "Microsoft.NET.Sdk.Web", + "frameworkReferences": [ + "Microsoft.AspNetCore.App" + ], + "dependsOn": [ + "Codebelt.Extensions.Carter.AspNetCore.Xml@1.1.0" + ], + "source": "using System;\nusing System.IO;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Codebelt.Extensions.Carter.AspNetCore.Xml;\nusing Cuemon.Xml.Serialization.Formatters;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.Extensions.Options;\nusing Microsoft.Net.Http.Headers;\n\nnamespace DocfxExample;\n\npublic static class XmlResponseNegotiatorExample\n{\n public static async Task Main()\n {\n var options = Options.Create(new XmlFormatterOptions());\n var negotiator = new XmlResponseNegotiator(options);\n var acceptHeader = MediaTypeHeaderValue.Parse(\"application/xml\");\n if (negotiator.CanHandle(acceptHeader))\n {\n using var body = new MemoryStream();\n var context = new DefaultHttpContext();\n context.Response.Body = body;\n context.Request.Headers.Accept = \"application/xml\";\n var model = new Report { Name = \"XML\", Value = 42 };\n await negotiator.Handle(context.Request, context.Response, model, CancellationToken.None);\n context.Response.Body.Position = 0;\n using var reader = new StreamReader(context.Response.Body, Encoding.UTF8);\n Console.WriteLine(await reader.ReadToEndAsync());\n }\n }\n}\n\npublic sealed class Report\n{\n public string Name { get; set; } = string.Empty;\n public int Value { get; set; }\n}" + } + } + ] +} diff --git a/.docfx/run-actions.settings.json b/.docfx/run-actions.settings.json new file mode 100644 index 0000000..40fd133 --- /dev/null +++ b/.docfx/run-actions.settings.json @@ -0,0 +1,84 @@ +{ + "examples": [ + { + "uid": "Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json.NewtonsoftJsonNegotiator", + "sourceSha256": "92F45867B2ACED88DFAC3237C8078AB7D5740E2C766F18819B44AF5DD86CF414", + "manifest": { + "schemaVersion": 1, + "mode": "console", + "framework": "net10.0", + "sdk": "Microsoft.NET.Sdk.Web", + "frameworkReferences": [ + "Microsoft.AspNetCore.App" + ], + "dependsOn": [ + "Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json@1.1.0" + ] + } + }, + { + "uid": "Codebelt.Extensions.Carter.AspNetCore.Text.Json.JsonResponseNegotiator", + "sourceSha256": "59D8AA9487D73D42F132C0D0E4E7D568A23E924797411166D38B8DA293E90388", + "manifest": { + "schemaVersion": 1, + "mode": "console", + "framework": "net10.0", + "sdk": "Microsoft.NET.Sdk.Web", + "frameworkReferences": [ + "Microsoft.AspNetCore.App" + ], + "dependsOn": [ + "Codebelt.Extensions.Carter.AspNetCore.Text.Json@1.1.0" + ] + } + }, + { + "uid": "Codebelt.Extensions.Carter.AspNetCore.Text.Yaml.YamlResponseNegotiator", + "sourceSha256": "12FDEB7A288A3A5581D52D9E4FFDCC881D112427B7BFE229C2C9C0F47DC79C85", + "manifest": { + "schemaVersion": 1, + "mode": "console", + "framework": "net10.0", + "sdk": "Microsoft.NET.Sdk.Web", + "frameworkReferences": [ + "Microsoft.AspNetCore.App" + ], + "dependsOn": [ + "Codebelt.Extensions.Carter.AspNetCore.Text.Yaml@1.1.0" + ] + } + }, + { + "uid": "Codebelt.Extensions.Carter.AspNetCore.Xml.XmlResponseNegotiator", + "sourceSha256": "E8B778859FF1625021C115F06D3589CD83F01FDEF3BD0419C1FC4CE74F3FC23B", + "manifest": { + "schemaVersion": 1, + "mode": "console", + "framework": "net10.0", + "sdk": "Microsoft.NET.Sdk.Web", + "frameworkReferences": [ + "Microsoft.AspNetCore.App" + ], + "dependsOn": [ + "Codebelt.Extensions.Carter.AspNetCore.Xml@1.1.0" + ] + } + }, + { + "uid": "Codebelt.Extensions.Carter.EndpointConventionBuilderExtensions", + "sourceSha256": "17A00BE8109C9F8F2554F1DFBBAABCBFCB7F238601BD5DCA8559A69EC4B2D56E", + "manifest": { + "schemaVersion": 1, + "mode": "console", + "framework": "net10.0", + "sdk": "Microsoft.NET.Sdk.Web", + "frameworkReferences": [ + "Microsoft.AspNetCore.App" + ], + "dependsOn": [ + "Codebelt.Extensions.Carter@1.1.0" + ] + } + } + ] +} From 13350d771dc28d2418327c87b2b5290cffa36179 Mon Sep 17 00:00:00 2001 From: gimlichael Date: Sat, 21 Nov 2026 04:31:57 +0100 Subject: [PATCH 3/8] =?UTF-8?q?=F0=9F=94=A7=20update=20changelog=20with=20?= =?UTF-8?q?docfx=20run-actions=20and=20example=20improvements?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da94fbb..aaeaab3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,8 @@ This is a minor release adding .NET 11 targets alongside .NET 10, updating depen ### Added - .NET 11 targets for all Codebelt.Extensions.Carter packages, -- `SonarAnalyzer.CSharp` 10.36.0.15337 to source project builds. +- `SonarAnalyzer.CSharp` 10.36.0.15337 to source project builds, +- DocFX run-actions build script, manifest, and settings for generating native and Docker run scripts for API example pages. ### Changed @@ -23,7 +24,8 @@ This is a minor release adding .NET 11 targets alongside .NET 10, updating depen - Updated package and contributor guidance for the supported frameworks and test environments, - Updated service-update automation to preserve planned releases ahead of the latest tag and validate release dates, - Pinned and updated the Scorecard workflow actions, -- Changed fingerprinted documentation asset caching to use immutable caching for successful and 304 responses, no-store for errors, and complete responses instead of ranges. +- Changed fingerprinted documentation asset caching to use immutable caching for successful and 304 responses, no-store for errors, and complete responses instead of ranges, +- Updated DocFX type page examples to expose runnable `Main` entry points with public models, removed redundant availability includes, and wired run-actions content and templates into `docfx.json`. ## [1.0.9] - 2026-10-17 From 023d74fbbf4b2b787f89e2641ebbca8d55f0046a Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Sat, 21 Nov 2026 06:41:45 +0100 Subject: [PATCH 4/8] =?UTF-8?q?=F0=9F=94=A8=20clean=20up=20run-actions=20i?= =?UTF-8?q?n=20docfx=20image=20build?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The image build script now generates run-actions via BuildRunActions.ps1 and removes generated artifacts in a finally block so failed builds leave no residue. --- .docfx/BuildDocfxImage.ps1 | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/.docfx/BuildDocfxImage.ps1 b/.docfx/BuildDocfxImage.ps1 index 20935a4..bf68ff7 100644 --- a/.docfx/BuildDocfxImage.ps1 +++ b/.docfx/BuildDocfxImage.ps1 @@ -1,4 +1,12 @@ $version = minver -i -t v -v w docfx metadata docfx.json -docker buildx build -t carter-docfx:$version --platform linux/arm64,linux/amd64 --load -f Dockerfile.docfx . -get-childItem -recurse -path api -include *.yml, .manifest | remove-item +& (Join-Path $PSScriptRoot 'BuildRunActions.ps1') +try { + docker buildx build -t carter-docfx:$version --platform linux/arm64,linux/amd64 --load -f Dockerfile.docfx . +} +finally { + get-childItem -recurse -path api -include *.yml, .manifest | remove-item + if (Test-Path -LiteralPath (Join-Path $PSScriptRoot 'run-actions')) { + Remove-Item -LiteralPath (Join-Path $PSScriptRoot 'run-actions') -Recurse -Force + } +} From b88ae1591c9803a97e168b34d07c35601402bd01 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Sat, 21 Nov 2026 06:41:46 +0100 Subject: [PATCH 5/8] =?UTF-8?q?=F0=9F=92=84=20add=20run-actions=20template?= =?UTF-8?q?=20for=20docfx=20examples?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Registers the modern template overlay and adds the run-actions script so published examples can be run natively or in Docker. --- .docfx/docfx.json | 4 +- .docfx/templates/modern/public/main.js | 3 + .docfx/templates/modern/public/run-actions.js | 270 ++++++++++++++++++ 3 files changed, 275 insertions(+), 2 deletions(-) create mode 100644 .docfx/templates/modern/public/main.js create mode 100644 .docfx/templates/modern/public/run-actions.js diff --git a/.docfx/docfx.json b/.docfx/docfx.json index 37709e0..c015817 100644 --- a/.docfx/docfx.json +++ b/.docfx/docfx.json @@ -80,8 +80,8 @@ "template": [ "default", "modern", - "templates/ms-style", - "run-actions-template" + "templates/modern", + "templates/ms-style" ], "overwrite": [ { diff --git a/.docfx/templates/modern/public/main.js b/.docfx/templates/modern/public/main.js new file mode 100644 index 0000000..6624cf4 --- /dev/null +++ b/.docfx/templates/modern/public/main.js @@ -0,0 +1,3 @@ +export default {}; + +import './run-actions.js'; diff --git a/.docfx/templates/modern/public/run-actions.js b/.docfx/templates/modern/public/run-actions.js new file mode 100644 index 0000000..6f57db6 --- /dev/null +++ b/.docfx/templates/modern/public/run-actions.js @@ -0,0 +1,270 @@ +// Optional modern-template enhancement. The association remains usable without JavaScript. +const icons = { + native: '' + + '', + docker: '' + + '', +}; +const waitingForCopy = new WeakSet(); +// Generated scripts are one complete `& { ... }` paste unit, so execution and verification run together. +const executionScript = /^& \{\r?\n#requires -Version 7\.0\r?\n[\s\S]*\r?\n\}\r?\n?$/; + +async function fetchScript(link) { + const url = new URL(link.href); + if (url.origin !== location.origin) throw new Error('Script must be hosted on this site.'); + // Asset URLs are stable per example, so always revalidate rather than copy a stale cached script. + const response = await fetch(url, { mode: 'same-origin', cache: 'no-cache' }); + if (!response.ok) throw new Error('Script unavailable.'); + const script = await response.text(); + if (!executionScript.test(script)) throw new Error('Response is not an execution script.'); + return script; +} + +function previewScript(script, label) { + const dialog = document.createElement('dialog'); + dialog.className = 'docfx-run-preview'; + dialog.setAttribute('aria-label', label + ' run script'); + const heading = document.createElement('h2'); + heading.textContent = label + ' run script'; + const source = document.createElement('pre'); + source.tabIndex = 0; + source.textContent = script; + const close = document.createElement('button'); + close.type = 'button'; + close.className = 'btn btn-secondary'; + close.textContent = 'Close'; + close.addEventListener('click', () => dialog.close()); + dialog.addEventListener('close', () => dialog.remove(), { once: true }); + dialog.append(heading, source, close); + document.body.append(dialog); + dialog.showModal(); +} + +function createAction(link, report, onCopyFailure) { + const transport = link.dataset.transport; + const label = transport === 'native' ? 'Native' : 'Docker'; + const name = 'Copy ' + label + ' run script'; + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'btn border-0 docfx-run-copy'; + button.title = name + '\nShift-click or right-click to preview'; + button.setAttribute('aria-label', name); + button.setAttribute('aria-description', 'Press Shift+Enter to preview the PowerShell script.'); + button.innerHTML = ''; + const icon = button.firstElementChild; + const check = document.createElement('i'); + check.className = 'bi bi-check-lg'; + check.setAttribute('aria-hidden', 'true'); + + let pending = false; + let resetIcon; + async function act(preview) { + if (pending) return; + pending = true; + report(''); + try { + const script = fetchScript(link); + if (preview) { + previewScript(await script, label); + } else { + // Start the clipboard write during the user's gesture, including while the fetch is pending. + const clipboard = navigator.clipboard; + if (clipboard?.write && typeof ClipboardItem === 'function') { + const text = script.then(value => new Blob([value], { type: 'text/plain' })); + await Promise.all([text, clipboard.write([new ClipboardItem({ 'text/plain': text })])]); + } else { + const text = await script; + await clipboard.writeText(text); + } + clearTimeout(resetIcon); + // Measure DocFX's success markup in the same code block so template overrides apply. + const reference = document.createElement('a'); + reference.className = 'btn border-0 link-success code-action'; + reference.hidden = true; + reference.setAttribute('aria-hidden', 'true'); + reference.style.transition = 'none'; + const referenceIcon = check.cloneNode(false); + referenceIcon.removeAttribute('style'); + reference.append(referenceIcon); + button.closest('pre').prepend(reference); + const appearance = getComputedStyle(referenceIcon, '::before'); + check.style.color = appearance.color; + check.style.fontSize = appearance.fontSize; + reference.remove(); + button.replaceChildren(check); + resetIcon = setTimeout(() => button.replaceChildren(icon), 1000); + report(label + ' script copied.', true); + } + } catch { + if (!preview) onCopyFailure?.(); + report('Could not ' + (preview ? 'preview ' : 'copy ') + label + ' script.'); + } finally { + pending = false; + } + } + + button.addEventListener('click', event => { void act(event.shiftKey); }); + button.addEventListener('contextmenu', event => { + event.preventDefault(); + void act(true); + }); + button.addEventListener('keydown', event => { + if (event.shiftKey && event.key === 'Enter') { + event.preventDefault(); + void act(true); + } + }); + return button; +} + +export function enhanceRunActions(root = document) { + for (const links of root.querySelectorAll('.docfx-run-actions:not([data-enhanced])')) { + const previous = links.previousElementSibling; + const pre = previous?.matches('pre') ? previous : previous?.querySelector('pre'); + if (!pre?.querySelector(':scope > code:is(.lang-csharp, .language-csharp, .lang-cs, .language-cs)')) continue; + const assets = [...links.querySelectorAll('a[data-transport="native"], a[data-transport="docker"]')]; + if (!assets.length) continue; + + // DocFX imports the custom module before rendering its Lit-managed copy anchor. + if (!pre.querySelector(':scope > a.code-action')) { + if (waitingForCopy.has(pre)) continue; + waitingForCopy.add(pre); + const observer = new MutationObserver(() => { + if (!pre.querySelector(':scope > a.code-action')) return; + observer.disconnect(); + waitingForCopy.delete(pre); + attachToolbar(pre, links, assets); + }); + observer.observe(pre, { childList: true }); + continue; + } + + attachToolbar(pre, links, assets); + } +} + +function attachToolbar(pre, links, assets) { + if ('enhanced' in links.dataset) return; + const toolbar = document.createElement('span'); + toolbar.className = 'docfx-run-toolbar'; + toolbar.setAttribute('role', 'group'); + toolbar.setAttribute('aria-label', 'Run scripts'); + const status = document.createElement('span'); + status.setAttribute('role', 'status'); + status.className = 'docfx-run-status'; + let clearStatus; + function report(message, visuallyHidden = false) { + clearTimeout(clearStatus); + status.classList.toggle('visually-hidden', visuallyHidden); + status.textContent = message; + if (message) clearStatus = setTimeout(() => { status.textContent = ''; }, 3000); + } + toolbar.append(...assets.map(link => createAction(link, report, () => { links.hidden = false; }))); + // Keep our nodes before DocFX's Lit render range, which replaces the original anchor on copy. + pre.prepend(toolbar, status); + pre.classList.add('docfx-runnable'); + links.dataset.enhanced = 'true'; + // Keep the recipe explanation visible when the toolbar replaces the fallback links. + links.after(...links.querySelectorAll(':scope > p')); + links.hidden = true; +} + +if (typeof document !== 'undefined') { + const style = document.createElement('style'); + style.textContent = ` +pre.docfx-runnable { + --run-action-size: 2.25rem; +} +.docfx-run-icon-native { + color: #926bbb; +} +.docfx-run-icon-docker { + color: #4d79d7; +} +.docfx-run-play { + color: #628b2f; +} +pre.docfx-runnable > .code-action, +.docfx-run-toolbar { + display: flex; + position: absolute; + top: .25rem; + opacity: 0; + pointer-events: none; + z-index: 1; +} +pre.docfx-runnable > .code-action, +.docfx-run-copy { + align-items: center; + justify-content: center; + inline-size: var(--run-action-size); + block-size: var(--run-action-size); + padding: 0; + background-color: var(--bs-body-bg); +} +.docfx-run-toolbar { + right: calc(.35rem + var(--run-action-size)); + gap: .15rem; +} +.docfx-run-copy { + display: inline-flex; +} +.docfx-run-copy .bi-check-lg { + pointer-events: none; +} +.docfx-run-copy:hover { + background-color: var(--bs-tertiary-bg); +} +pre.docfx-runnable:hover > :is(.code-action, .docfx-run-toolbar), +pre.docfx-runnable:focus-within > :is(.code-action, .docfx-run-toolbar) { + opacity: 1; + pointer-events: auto; +} +pre.docfx-runnable > .code-action:focus-visible, +.docfx-run-copy:focus-visible { + outline: 2px solid currentColor; + outline-offset: -2px; +} +.docfx-run-status { + position: absolute; + z-index: 1; + top: .25rem; + left: .25rem; + max-inline-size: calc(100% - 3 * var(--run-action-size) - 1rem); + white-space: normal; + pointer-events: none; +} +.docfx-run-status:not(:empty) { + padding: .3rem .5rem; + border-radius: .25rem; + background: var(--bs-body-bg); + color: var(--bs-body-color); +} +.docfx-run-preview { + inline-size: min(52rem, 94vw); + padding: 1rem; + color: var(--bs-body-color); + background: var(--bs-body-bg); + border: 1px solid var(--bs-border-color); + border-radius: .5rem; +} +.docfx-run-preview::backdrop { + background: rgb(0 0 0 / 45%); +} +.docfx-run-preview pre { + max-block-size: 65vh; + padding: .75rem; + background: var(--bs-tertiary-bg); +} +@media (hover: none), (any-pointer: coarse) { + pre.docfx-runnable > :is(.code-action, .docfx-run-toolbar) { + opacity: 1; + pointer-events: auto; + } +} +`; + document.head.append(style); + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => enhanceRunActions(), { once: true }); + else enhanceRunActions(); +} From ff55117edb92668ead778b09edc2613cc7472017 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Sat, 21 Nov 2026 06:41:46 +0100 Subject: [PATCH 6/8] =?UTF-8?q?=F0=9F=93=9D=20drop=20manual=20example=20he?= =?UTF-8?q?adings=20from=20type=20pages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DocFX renders the Examples heading automatically from the example front matter mapping, so the manual heading produced a duplicate section. --- ...arter.AspNetCore.Newtonsoft.Json.NewtonsoftJsonNegotiator.md | 2 -- ...nsions.Carter.AspNetCore.Text.Json.JsonResponseNegotiator.md | 2 -- ...nsions.Carter.AspNetCore.Text.Yaml.YamlResponseNegotiator.md | 2 -- ...lt.Extensions.Carter.AspNetCore.Xml.XmlResponseNegotiator.md | 2 -- ...elt.Extensions.Carter.EndpointConventionBuilderExtensions.md | 2 -- 5 files changed, 10 deletions(-) diff --git a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json.NewtonsoftJsonNegotiator.md b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json.NewtonsoftJsonNegotiator.md index ff35902..612cb09 100644 --- a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json.NewtonsoftJsonNegotiator.md +++ b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json.NewtonsoftJsonNegotiator.md @@ -5,8 +5,6 @@ example: [*content] The `NewtonsoftJsonNegotiator` integrates Newtonsoft.Json serialization into the Carter response pipeline. Register it as the response negotiator to have all `HttpResponse.Negotiate()` calls produce JSON output using Newtonsoft.Json's configurable serializer. -### Example - To inspect the JSON a Carter client would receive, pass the requested media type to the negotiator and serialize a response into a memory stream. The stream makes the response body readable without starting a server. ```csharp diff --git a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Json.JsonResponseNegotiator.md b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Json.JsonResponseNegotiator.md index 66d4681..a75b463 100644 --- a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Json.JsonResponseNegotiator.md +++ b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Json.JsonResponseNegotiator.md @@ -5,8 +5,6 @@ example: [*content] The `JsonResponseNegotiator` integrates System.Text.Json serialization into the Carter response pipeline. Register it as the response negotiator to have all `HttpResponse.Negotiate()` calls produce JSON output using the modern, high-performance System.Text.Json serializer. -### Example - To inspect the System.Text.Json output for a response model, pass the requested media type to the negotiator and serialize into a memory stream. The explicit type information resolver allows the formatter to serialize the anonymous model even when the host disables reflection-based serialization by default. ```csharp diff --git a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Yaml.YamlResponseNegotiator.md b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Yaml.YamlResponseNegotiator.md index 9f848f2..09f0e9e 100644 --- a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Yaml.YamlResponseNegotiator.md +++ b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Text.Yaml.YamlResponseNegotiator.md @@ -5,8 +5,6 @@ example: [*content] The `YamlResponseNegotiator` integrates YamlDotNet serialization into the Carter response pipeline. Register it as the response negotiator to have all `HttpResponse.Negotiate()` calls produce YAML output—ideal for tooling, configuration, and DevOps-focused APIs. -### Example - `YamlResponseNegotiator` is constructed with an `IOptions` that controls supported media types and YamlDotNet serialization settings. Before serializing a model, the negotiator tests the client's `Accept` header via `CanHandle`; only when it returns `true` is `Handle` called to produce YAML output. `Handle` resolves the character encoding from the `Accept-Charset` header (falling back to `YamlFormatterOptions.Encoding`), sets the `Content-Type` response header, and streams the serialized YAML directly to the response body. The following example constructs the negotiator with default options, confirms that the `application/yaml` media type is accepted, then writes an anonymous object to an in-memory response stream and reads back the serialized output: diff --git a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Xml.XmlResponseNegotiator.md b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Xml.XmlResponseNegotiator.md index e073923..ef03322 100644 --- a/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Xml.XmlResponseNegotiator.md +++ b/.docfx/api/types/Codebelt.Extensions.Carter.AspNetCore.Xml.XmlResponseNegotiator.md @@ -5,8 +5,6 @@ example: [*content] The `XmlResponseNegotiator` integrates System.Xml XML serialization into the Carter response pipeline. Register it as the response negotiator to have all `HttpResponse.Negotiate()` calls produce standards-compliant XML output—suitable for legacy interoperability and enterprise integration scenarios. -### Example - `XmlResponseNegotiator` is constructed with an `IOptions` that controls supported media types and System.Xml serialization settings, including writer encoding. Before serializing a model, the negotiator tests the client's `Accept` header via `CanHandle`; only when it returns `true` is `Handle` called to produce XML output. `Handle` resolves the character encoding from the `Accept-Charset` header (falling back to `XmlFormatterOptions.Settings.Writer.Encoding`), sets the `Content-Type` response header, and streams the serialized XML directly to the response body. The following example constructs the negotiator with default options, confirms that the `application/xml` media type is accepted, then writes a public model to an in-memory response stream and reads back the serialized output: diff --git a/.docfx/api/types/Codebelt.Extensions.Carter.EndpointConventionBuilderExtensions.md b/.docfx/api/types/Codebelt.Extensions.Carter.EndpointConventionBuilderExtensions.md index 318a611..bce79fc 100644 --- a/.docfx/api/types/Codebelt.Extensions.Carter.EndpointConventionBuilderExtensions.md +++ b/.docfx/api/types/Codebelt.Extensions.Carter.EndpointConventionBuilderExtensions.md @@ -7,8 +7,6 @@ Attach typed response metadata to any Carter or minimal API endpoint by calling > **Note:** DocFX does not yet generate complete API metadata for C# 14 extension block members ([docfx#11010](https://github.com/dotnet/docfx/issues/11010)). The extension methods themselves are fully functional; the limitation is cosmetic in generated API docs only. -### Example - `Produces` and `Produces` attach `IProducesResponseTypeMetadata` directly to an endpoint builder. `Produces` records the response body type, HTTP status code, and accepted content types; `Produces` (no type parameter) records a status-only response with no body—useful for `404`, `401`, and similar cases. Both are chainable and are typically called on a `RouteHandlerBuilder` inside a Carter module or minimal API route definition. The following example constructs an endpoint builder directly, applies both extension members to the convention builder, and reads back the attached metadata to show what each call contributes: From 8c4face6ef6a5b4a82f112c3d3a835285e0b03f5 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Sat, 21 Nov 2026 06:41:46 +0100 Subject: [PATCH 7/8] =?UTF-8?q?=F0=9F=93=9D=20document=20docfx=20example?= =?UTF-8?q?=20heading=20and=20include=20rules?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Clarifies that example headings are generated by DocFX and that INCLUDE directives are only allowed on namespace pages. --- AGENTS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cc24482..c83c222 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -86,7 +86,7 @@ Public non-abstraction types — including enums, structs, records, plain classe For public non-abstraction types, include at least one realistic, copy/paste-ready usage example on the generated type page/overwrite section for that type UID. For example, a public `Class1` requires an example on the `Class1` API page, not only on the namespace page. Prefer deriving examples from existing unit, functional, or integration tests, but convert test code into real-life consumer-oriented usage. -Missing type examples must be added through per-type DocFX overwrite files under `.docfx/api/types/{TypeUid}.md` in Codebelt repositories. Namespace overview text and `Extension Members` tables are not substitutes for type-page examples. +Missing type examples must be added through per-type DocFX overwrite files under `.docfx/api/types/{TypeUid}.md` in Codebelt repositories. Namespace overview text and `Extension Members` tables are not substitutes for type-page examples. When front matter maps the body to `example` (`example: *content`, `example: [*content]`, or `example:\n- *content`), DocFX renders the `Examples` section heading automatically — never add a manual `## Example`, `### Example`, or `### Examples` heading in the body; place the complementary explanatory prose directly before the C# fence instead. Public extension methods must have examples too. Listing an extension method in an `Extension Members` table is required, but it is not enough. @@ -104,7 +104,7 @@ Both namespace overwrite files and type overwrite files are required deliverable `docfx.json` must keep namespace and type overwrite files in separate subdirectories. `build.overwrite` must include both `api/namespaces/**/*.md` (for namespace pages) and `api/types/**/*.md` (for type pages). `build.content` must exclude both `api/namespaces/**` and `api/types/**` to prevent overwrite Markdown from being treated as conceptual content. Do not use `api/**/*.md` under `build.overwrite` or `build.content`. -Availability must be documented by referencing the appropriate include file when one exists, or by adding explicit availability text when no suitable include exists. Availability must reflect the actual target frameworks, conditional compilation, and project configuration. +Availability must be documented on namespace overview pages under `.docfx/api/namespaces/*` by referencing the appropriate `[!INCLUDE ...]` file when one exists, or by adding explicit availability text when no suitable include exists. Under `.docfx/api/`, `[!INCLUDE ...]` directives are only allowed in `.docfx/api/namespaces/*` — never on type pages (`.docfx/api/types/*`), never in other files under `.docfx/api/`, and never after examples. Only modify DocFX Markdown files under `.docfx/api/`; leave Markdown files outside `.docfx/api/` untouched. Availability must reflect the actual target frameworks, conditional compilation, and project configuration. For conditionally compiled APIs, choose the executable test framework from the asset that contains the API. Inspect the preprocessor condition, project TFMs, package `lib/` assets, and resolved consumer asset before changing a sample. For APIs under `NETSTANDARD2_0` or `NETSTANDARD2_0_OR_GREATER`, when modern `lib/netX.0/` assets also exist, use `net48` (or another supported .NET Framework target from `net462` onward) so the consumer selects `lib/netstandard2.0/`. Never use `netstandard*` as an executable target, and never use a modern `netX.0` target when it selects an asset where the API is absent. For other TFM guards, select a runnable consumer TFM that resolves to the containing asset and confirm that selection from restore or build evidence. From e9a86a9a93b78f6b1bab8ff2fcf74566407c7547 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Sat, 21 Nov 2026 21:41:07 +0100 Subject: [PATCH 8/8] =?UTF-8?q?=F0=9F=94=A8=20update=20docfx=20run-actions?= =?UTF-8?q?=20materializer=20and=20manifest?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Regenerate DocFX run-actions artifacts to sync host-harness support in BuildRunActions.ps1 and add exampleId, uid, and fenceOrdinal metadata to run-actions.manifest.json. --- .docfx/BuildRunActions.ps1 | 220 +++++++++++++++++++++++++++++++ .docfx/run-actions.manifest.json | 15 +++ 2 files changed, 235 insertions(+) diff --git a/.docfx/BuildRunActions.ps1 b/.docfx/BuildRunActions.ps1 index 7a2680b..c82b506 100644 --- a/.docfx/BuildRunActions.ps1 +++ b/.docfx/BuildRunActions.ps1 @@ -229,6 +229,210 @@ $dockerUser = @() } } +function New-HostPair { + param( + [Parameter(Mandatory)][string] $Source, + [string] $Framework = 'net10.0', + [string] $Sdk = 'Microsoft.NET.Sdk.Web', + [string[]] $DependsOn = @(), + [string] $ProbePath = '/', + [string] $ProbeMethod = 'GET', + [int] $TimeoutSeconds = 15, + [int] $ExpectedStatusCode = 0, + [string] $ExpectedBodyContains = '', + [int] $StartupDelayMs = 1000, + [string] $Image = 'codebeltnet/csrun:10' + ) + if ($Framework -notmatch '^net\d+\.\d+$') { throw "Invalid host framework: $Framework" } + if ($Sdk -notmatch '^[A-Za-z0-9_.]+$') { throw "Invalid host SDK: $Sdk" } + if ($ProbeMethod -notmatch '^(GET|HEAD|POST|PUT|DELETE|OPTIONS|PATCH)$') { throw "Invalid host probeMethod: $ProbeMethod" } + if ($TimeoutSeconds -lt 3 -or $TimeoutSeconds -gt 300) { throw "Host timeoutSeconds must be between 3 and 300." } + $cleanDependsOn = @($DependsOn | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) }) + foreach ($pin in $cleanDependsOn) { + if ($pin -notmatch '^[A-Za-z0-9_.-]+@[A-Za-z0-9_.-]+$') { throw "Invalid host dependsOn pin: $pin" } + } + $pkgLines = @($cleanDependsOn | ForEach-Object { + $parts = $_ -split '@', 2 + " " + }) + $itemGroup = if ($pkgLines.Count) { "`n `n" + ($pkgLines -join "`n") + "`n " } else { '' } + $csproj = "`n `n Exe`n $Framework`n enable`n enable`n $itemGroup`n`n" + $payloadJson = ([ordered]@{ + csproj = $csproj + source = $Source.Replace("`r`n", "`n").TrimEnd("`r", "`n") + "`n" + probePath = $ProbePath + probeMethod = $ProbeMethod + timeoutSeconds = $TimeoutSeconds + expectedStatusCode = $ExpectedStatusCode + expectedBodyContains = $ExpectedBodyContains + startupDelayMs = $StartupDelayMs + } | ConvertTo-Json -Depth 10).Replace("`r`n", "`n") + $payloadB64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($payloadJson)) + $runnerBody = @' +$payload = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($payloadB64)) | ConvertFrom-Json +$work = Join-Path ([IO.Path]::GetTempPath()) ('dx-host-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) +$null = New-Item -ItemType Directory -Path $work +$buildProcess = $null +$hostProcess = $null +$deadline = [DateTimeOffset]::UtcNow.AddSeconds([int]$payload.timeoutSeconds) +try { + $utf8NoBom = [Text.UTF8Encoding]::new($false) + $csprojPath = Join-Path $work 'HostSample.csproj' + [IO.File]::WriteAllText($csprojPath, $payload.csproj, $utf8NoBom) + [IO.File]::WriteAllText((Join-Path $work 'Program.cs'), $payload.source, $utf8NoBom) + $buildStartInfo = [Diagnostics.ProcessStartInfo]::new('dotnet') + foreach ($a in @('build', $csprojPath, '-c', 'Release', '--nologo', '-v', 'quiet')) { $buildStartInfo.ArgumentList.Add($a) } + $buildStartInfo.WorkingDirectory = $work + $buildStartInfo.RedirectStandardOutput = $true + $buildStartInfo.RedirectStandardError = $true + $buildStartInfo.UseShellExecute = $false + $buildProcess = [Diagnostics.Process]::new() + $buildProcess.StartInfo = $buildStartInfo + if (-not $buildProcess.Start()) { throw 'Could not start host sample build.' } + $buildStdoutTask = $buildProcess.StandardOutput.ReadToEndAsync() + $buildStderrTask = $buildProcess.StandardError.ReadToEndAsync() + $buildRemainingMs = [int][Math]::Ceiling(($deadline - [DateTimeOffset]::UtcNow).TotalMilliseconds) + if ($buildRemainingMs -le 0 -or -not $buildProcess.WaitForExit($buildRemainingMs)) { + try { if (-not $buildProcess.HasExited) { $buildProcess.Kill($true) } } catch {} + $null = $buildProcess.WaitForExit(5000) + throw "Host sample build timed out after $($payload.timeoutSeconds)s." + } + $buildOut = $buildStdoutTask.GetAwaiter().GetResult() + $buildErr = $buildStderrTask.GetAwaiter().GetResult() + if ($buildProcess.ExitCode -ne 0) { + $buildText = ($buildOut + "`n" + $buildErr).Trim() + throw "Host sample build failed (exit $($buildProcess.ExitCode)): $buildText" + } + if ([DateTimeOffset]::UtcNow -ge $deadline) { + throw "Host sample timed out after $($payload.timeoutSeconds)s before starting host." + } + $listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, 0) + $listener.Start() + $port = $listener.LocalEndpoint.Port + $listener.Stop() + $baseUrl = "http://127.0.0.1:$port" + $startInfo = [Diagnostics.ProcessStartInfo]::new('dotnet') + foreach ($a in @('run','--no-build','-c','Release','--project',$csprojPath)) { $startInfo.ArgumentList.Add($a) } + $startInfo.Environment['ASPNETCORE_URLS'] = $baseUrl + $startInfo.Environment['DOTNET_ENVIRONMENT'] = 'Development' + $startInfo.RedirectStandardOutput = $true + $startInfo.RedirectStandardError = $true + $startInfo.UseShellExecute = $false + $hostProcess = [Diagnostics.Process]::new() + $hostProcess.StartInfo = $startInfo + if (-not $hostProcess.Start()) { throw 'Could not start host process.' } + $stdoutTask = $hostProcess.StandardOutput.ReadToEndAsync() + $stderrTask = $hostProcess.StandardError.ReadToEndAsync() + if ($payload.probePath) { + $probeUrl = $baseUrl + $payload.probePath + $probed = $false + $lastError = '' + $httpClient = [Net.Http.HttpClient]::new() + $httpClient.Timeout = [TimeSpan]::FromSeconds(3) + try { + while ([DateTimeOffset]::UtcNow -lt $deadline) { + if ($hostProcess.HasExited) { + $stdOut = $stdoutTask.GetAwaiter().GetResult() + $errOut = $stderrTask.GetAwaiter().GetResult() + throw "Host exited before probe succeeded (exit $($hostProcess.ExitCode)). $stdOut $errOut" + } + $probeRemainingMs = [int][Math]::Ceiling(($deadline - [DateTimeOffset]::UtcNow).TotalMilliseconds) + if ($probeRemainingMs -le 0) { break } + $cts = [Threading.CancellationTokenSource]::new([Math]::Min(3000, $probeRemainingMs)) + try { + $req = [Net.Http.HttpRequestMessage]::new([Net.Http.HttpMethod]::new([string]$payload.probeMethod), $probeUrl) + $resp = $httpClient.Send($req, $cts.Token) + $statusCode = [int]$resp.StatusCode + $body = $resp.Content.ReadAsStringAsync($cts.Token).GetAwaiter().GetResult() + if ([int]$payload.expectedStatusCode -gt 0 -and $statusCode -ne [int]$payload.expectedStatusCode) { + throw "Expected HTTP $($payload.expectedStatusCode) from $($payload.probePath), got HTTP $statusCode. Body: $body" + } + if ($payload.expectedBodyContains -and -not $body.Contains([string]$payload.expectedBodyContains, [StringComparison]::Ordinal)) { + throw "Expected response body to contain '$($payload.expectedBodyContains)'. Body: $body" + } + Write-Output "HTTP $statusCode $($payload.probeMethod) $($payload.probePath)" + if ($body) { Write-Output $body } + $probed = $true + break + } catch [Net.Http.HttpRequestException] { + $lastError = $_.Exception.Message + Start-Sleep -Milliseconds 200 + } catch [Threading.Tasks.TaskCanceledException] { + $lastError = $_.Exception.Message + Start-Sleep -Milliseconds 200 + } catch [OperationCanceledException] { + $lastError = $_.Exception.Message + Start-Sleep -Milliseconds 200 + } finally { + $cts.Dispose() + } + } + } finally { + $httpClient.Dispose() + } + if (-not $probed) { throw "Host probe '$($payload.probeMethod) $($payload.probePath)' timed out after $($payload.timeoutSeconds)s. Last error: $lastError" } + } else { + $requiredDelayMs = [Math]::Max([int]$payload.startupDelayMs, 0) + $delayRemainingMs = [int][Math]::Floor(($deadline - [DateTimeOffset]::UtcNow).TotalMilliseconds) + $sleepMs = [Math]::Min($requiredDelayMs, [Math]::Max($delayRemainingMs, 0)) + if ($sleepMs -gt 0) { $null = $hostProcess.WaitForExit($sleepMs) } + if ($hostProcess.HasExited -and $hostProcess.ExitCode -ne 0) { + $stdOut = $stdoutTask.GetAwaiter().GetResult() + $errOut = $stderrTask.GetAwaiter().GetResult() + throw "Host exited with code $($hostProcess.ExitCode). $stdOut $errOut" + } + if ($delayRemainingMs -lt $requiredDelayMs) { + throw "Host startup observation (${requiredDelayMs}ms) timed out after $($payload.timeoutSeconds)s with only $([Math]::Max($delayRemainingMs, 0))ms remaining." + } + Write-Output "Host started cleanly and ran for ${requiredDelayMs}ms." + } +} finally { + if ($buildProcess) { + try { + if (-not $buildProcess.HasExited) { $buildProcess.Kill($true) } + $null = $buildProcess.WaitForExit(5000) + } catch {} + $buildProcess.Dispose() + } + if ($hostProcess) { + try { + if (-not $hostProcess.HasExited) { $hostProcess.Kill($true) } + $null = $hostProcess.WaitForExit(5000) + } catch {} + $hostProcess.Dispose() + } + $resolved = [IO.Path]::GetFullPath($work) + $temp = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('/','\') + [IO.Path]::DirectorySeparatorChar + if ($resolved.StartsWith($temp, [StringComparison]::OrdinalIgnoreCase) -and (Test-Path -LiteralPath $resolved)) { + Remove-Item -LiteralPath $resolved -Recurse -Force -ErrorAction SilentlyContinue + } +} +'@ + $runnerNorm = $runnerBody.Replace("`r`n", "`n").TrimEnd() + $native = "& {`n#requires -Version 7.0`n`$ErrorActionPreference = 'Stop'`n`$PSNativeCommandUseErrorActionPreference = `$false`n`$OutputEncoding = [Text.UTF8Encoding]::new(`$false)`n[Console]::OutputEncoding = `$OutputEncoding`n`$null = Get-Command dotnet -ErrorAction Stop`n`$payloadB64 = '$payloadB64'`n" + $runnerNorm + "`n}`n" + $runnerB64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("`$ErrorActionPreference = 'Stop'`n`$PSNativeCommandUseErrorActionPreference = `$false`n`$payloadB64 = '$payloadB64'`n" + $runnerNorm + "`n")) + $quotedImage = Quote-Literal $Image + $docker = @" +& { +#requires -Version 7.0 + `$ErrorActionPreference = 'Stop' + `$PSNativeCommandUseErrorActionPreference = `$false + `$OutputEncoding = [Text.UTF8Encoding]::new(`$false) + [Console]::OutputEncoding = `$OutputEncoding + `$null = Get-Command docker -ErrorAction Stop + docker info *> `$null + if (`$LASTEXITCODE -ne 0) { throw 'Docker daemon unavailable.' } + `$runnerB64 = '$runnerB64' + `$command = '`$ErrorActionPreference = "Stop"; `$s = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Console]::In.ReadToEnd())); `$p = Join-Path ([IO.Path]::GetTempPath()) ("dx-host-runner-" + [guid]::NewGuid().ToString("N") + ".ps1"); [IO.File]::WriteAllText(`$p, `$s); try { & pwsh -NoProfile -NonInteractive -File `$p; exit `$LASTEXITCODE } finally { Remove-Item -LiteralPath `$p -Force -ErrorAction SilentlyContinue }' + `$output = (@(`$runnerB64 | & docker run --rm -i --init --entrypoint pwsh $quotedImage -NoProfile -NonInteractive -Command `$command) -join [Environment]::NewLine) + `$code = `$LASTEXITCODE + Write-Output `$output + if (`$code -ne 0) { throw "Host execution failed in Docker with exit code `$code." } +} +"@ + "`n" + return @{ native = $native; docker = $docker } +} + $doc = Get-Content -LiteralPath $ManifestPath -Raw | ConvertFrom-Json -AsHashtable if ($doc.schemaVersion -ne 1) { throw "Unsupported run-actions manifest schemaVersion: $($doc.schemaVersion)" } $examples = @($doc.examples) @@ -243,6 +447,22 @@ foreach ($example in $examples) { New-RepositoryPair -Repository $example.repository -Commit $example.commit -Project $example.project -Test $example.test -Framework $example.framework -Image $example.image } elseif ($example.strategy -ceq 'standalone') { New-StandalonePair -Manifest $example.manifest -Image $example.image + } elseif ($example.strategy -ceq 'host') { + $hh = if ($example.ContainsKey('hostHarness') -and $example.hostHarness) { $example.hostHarness } else { @{} } + $hostParams = @{ + Source = [string]$example.source + Framework = if ($hh.ContainsKey('framework') -and $hh.framework) { [string]$hh.framework } elseif ($example.ContainsKey('framework') -and $example.framework) { [string]$example.framework } else { 'net10.0' } + Sdk = if ($hh.ContainsKey('sdk') -and $hh.sdk) { [string]$hh.sdk } else { 'Microsoft.NET.Sdk.Web' } + DependsOn = if ($hh.ContainsKey('dependsOn') -and $hh.dependsOn) { [string[]]@($hh.dependsOn) } else { @() } + ProbePath = if ($hh.ContainsKey('probePath')) { [string]$hh.probePath } else { '/' } + ProbeMethod = if ($hh.ContainsKey('probeMethod') -and $hh.probeMethod) { [string]$hh.probeMethod } else { 'GET' } + TimeoutSeconds = if ($hh.ContainsKey('timeoutSeconds') -and $hh.timeoutSeconds) { [int]$hh.timeoutSeconds } else { 15 } + ExpectedStatusCode = if ($hh.ContainsKey('expectedStatusCode') -and $hh.expectedStatusCode) { [int]$hh.expectedStatusCode } else { 0 } + ExpectedBodyContains = if ($hh.ContainsKey('expectedBodyContains') -and $hh.expectedBodyContains) { [string]$hh.expectedBodyContains } else { '' } + StartupDelayMs = if ($hh.ContainsKey('startupDelayMs') -and $hh.startupDelayMs) { [int]$hh.startupDelayMs } else { 1000 } + Image = if ($example.ContainsKey('image') -and $example.image) { [string]$example.image } else { 'codebeltnet/csrun:10' } + } + New-HostPair @hostParams } else { throw "Unsupported run-action strategy '$($example.strategy)' for $id" } diff --git a/.docfx/run-actions.manifest.json b/.docfx/run-actions.manifest.json index d53dbef..f7fe102 100644 --- a/.docfx/run-actions.manifest.json +++ b/.docfx/run-actions.manifest.json @@ -3,6 +3,9 @@ "examples": [ { "id": "6352b06e7d9ea46088bd7abf", + "exampleId": "Codebelt.Extensions.Carter.AspNetCore.Text.Json.JsonResponseNegotiator#1", + "uid": "Codebelt.Extensions.Carter.AspNetCore.Text.Json.JsonResponseNegotiator", + "fenceOrdinal": 1, "strategy": "standalone", "transports": [ "native", @@ -25,6 +28,9 @@ }, { "id": "83888118c4da05f5423d7ce9", + "exampleId": "Codebelt.Extensions.Carter.EndpointConventionBuilderExtensions#1", + "uid": "Codebelt.Extensions.Carter.EndpointConventionBuilderExtensions", + "fenceOrdinal": 1, "strategy": "standalone", "transports": [ "native", @@ -47,6 +53,9 @@ }, { "id": "93c4f046477745c9b8272f18", + "exampleId": "Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json.NewtonsoftJsonNegotiator#1", + "uid": "Codebelt.Extensions.Carter.AspNetCore.Newtonsoft.Json.NewtonsoftJsonNegotiator", + "fenceOrdinal": 1, "strategy": "standalone", "transports": [ "native", @@ -69,6 +78,9 @@ }, { "id": "bf3b685f7384b7944901e7d0", + "exampleId": "Codebelt.Extensions.Carter.AspNetCore.Text.Yaml.YamlResponseNegotiator#1", + "uid": "Codebelt.Extensions.Carter.AspNetCore.Text.Yaml.YamlResponseNegotiator", + "fenceOrdinal": 1, "strategy": "standalone", "transports": [ "native", @@ -91,6 +103,9 @@ }, { "id": "f53010d9cc9ec55bc07adac2", + "exampleId": "Codebelt.Extensions.Carter.AspNetCore.Xml.XmlResponseNegotiator#1", + "uid": "Codebelt.Extensions.Carter.AspNetCore.Xml.XmlResponseNegotiator", + "fenceOrdinal": 1, "strategy": "standalone", "transports": [ "native",