diff --git a/.github/workflows/build-github.yml b/.github/workflows/build-github.yml index c9a08a8..42ccecb 100644 --- a/.github/workflows/build-github.yml +++ b/.github/workflows/build-github.yml @@ -38,6 +38,10 @@ jobs: 10.0.x 11.0.x + - name: Restore locked Graphviz build artifacts + shell: pwsh + run: ./ud.ps1 + # 3. Restore dependencies - name: 3) Restore dependencies run: dotnet restore ${{env.PATH_SLNX}} diff --git a/.github/workflows/dotgraph.yml b/.github/workflows/dotgraph.yml index d844031..bfe46e8 100644 --- a/.github/workflows/dotgraph.yml +++ b/.github/workflows/dotgraph.yml @@ -1,4 +1,4 @@ -name: DOT rendering on Windows, Linux, and macOS +name: Bundled DOT rendering on Windows, Linux, and macOS on: push: @@ -11,7 +11,7 @@ jobs: strategy: fail-fast: false matrix: - os: [windows-latest, ubuntu-latest, macos-latest] + os: [windows-latest, windows-11-arm, ubuntu-24.04, ubuntu-24.04-arm, macos-15-intel, macos-15] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 @@ -20,23 +20,17 @@ jobs: dotnet-version: | 10.0.x 11.0.x - - name: Install Graphviz on Windows - if: runner.os == 'Windows' - run: choco install graphviz --no-progress -y - - name: Install Graphviz on Linux - if: runner.os == 'Linux' - run: sudo apt-get update && sudo apt-get install -y graphviz - - name: Install Graphviz on macOS - if: runner.os == 'macOS' - run: brew install graphviz - - name: Test rendering + - name: Restore locked Graphviz build artifacts + shell: pwsh + run: ./ud.ps1 + - name: Test bundled renderer without installing Graphviz + run: dotnet test source/Lite.StateMachine.DotGraph.Tests -c Release --filter TestCategory!=ExternalGraphviz + - name: Test restored NuGet package with an empty PATH + shell: pwsh + run: ./scripts/Test-DotGraphPackage.ps1 + - name: Test sample console and PowerShell entry points shell: pwsh run: | - if ($IsWindows) { - $env:GRAPHVIZ_DOT = 'C:\Program Files\Graphviz\bin\dot.exe' - } else { - $env:GRAPHVIZ_DOT = 'dot' - } - dotnet test source/Lite.StateMachine.DotGraph.Tests -c Release --verbosity normal - - name: Pack standalone renderer - run: dotnet pack source/Lite.StateMachine.DotGraph -c Release --no-build + dotnet run --project samples/Sample11.GenerateDotGraph -c Release -f net10.0 -- ./output/ci-sample11 + if ($LASTEXITCODE -ne 0) { throw 'Console sample failed.' } + ./samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 -SkipBuild -OutputDirectory ./output/ci-sample11-powershell diff --git a/.gitignore b/.gitignore index e8baef7..920dc3a 100644 --- a/.gitignore +++ b/.gitignore @@ -95,3 +95,7 @@ sdkconfig.* /[Dd]ocs/backup /[Ss]andbox /[Tt]ools + +# Graphviz/font binaries are restored from the pinned manifest by ud.ps1. +/source/Lite.StateMachine.DotGraph/Assets/*.wasm +/source/Lite.StateMachine.DotGraph/Assets/*.ttf diff --git a/Directory.Packages.props b/Directory.Packages.props index fa87d25..4ae782e 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -4,6 +4,10 @@ + + + + diff --git a/Lite.StateMachine.slnx b/Lite.StateMachine.slnx index 1ec63a7..ffbad78 100644 --- a/Lite.StateMachine.slnx +++ b/Lite.StateMachine.slnx @@ -9,9 +9,15 @@ + + + + + + @@ -21,10 +27,10 @@ - + - + diff --git a/readme.md b/readme.md index 318c7a1..fedd480 100644 --- a/readme.md +++ b/readme.md @@ -156,9 +156,14 @@ await renderer.RenderAsync(machine.ExportUml(), "machine.svg"); await renderer.RenderFileAsync("machine.dot", "machine.png", DotGraphFormat.Png); ``` -The renderer requires an installed or application-supplied [Graphviz](https://graphviz.org/download/) -executable. It is independent of the core library and uses portable .NET process APIs -for Windows, Linux, and macOS. See the package README for deployment requirements. +The renderer bundles Graphviz and its execution/rasterization dependencies through +NuGet; no Graphviz installation or PATH setup is required. It is independent of the +core library. See the package README for supported platforms and backend limitations. + +When building the renderer from source, PowerShell 7's `./ud.ps1` restores its +locked binary artifacts into the ignored `output` directory. Builds also perform +this restore automatically. Maintainers can explicitly upgrade with `./ud.ps1 -Latest`; +see the renderer README for checksum verification and review steps. ![Sample Composite State Image](https://raw.githubusercontent.com/SuessLabs/Lite.StateMachine/develop/docs/SampleGraphviz-1080.png) diff --git a/samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 b/samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 index c69ac52..d7a0f4e 100644 --- a/samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 +++ b/samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 @@ -2,14 +2,14 @@ .SYNOPSIS Builds the sample, loads its DLL, and renders the same diagrams as the console app. .EXAMPLE -./Generate-Diagrams.ps1 -DotPath 'C:/Program Files/Graphviz/bin/dot.exe' +./Generate-Diagrams.ps1 #> #Requires -Version 7.0 [CmdletBinding()] param( [string] $OutputDirectory = (Join-Path $PSScriptRoot 'diagrams'), - [string] $DotPath = 'dot', + [string] $DotPath, [ValidateSet('Debug', 'Release')] [string] $Configuration = 'Release', [switch] $SkipBuild @@ -23,8 +23,9 @@ if ([Environment]::Version.Major -lt 10) { } $project = Join-Path $PSScriptRoot 'Sample11.GenerateDotGraph.csproj' -if (-not $SkipBuild) { - dotnet build $project -c $Configuration -f net10.0 +if (-not $SkipBuild) +{ + dotnet build $project -c $Configuration -f net10.0 -p:TargetFrameworks=net10.0 if ($LASTEXITCODE -ne 0) { throw 'Sample build failed.' } @@ -34,6 +35,47 @@ if (-not $SkipBuild) { $assemblyDirectory = [IO.Path]::GetFullPath( (Join-Path $PSScriptRoot "../../output/Sample11.GenerateDotGraph/$Configuration/net10.0")) +# PowerShell does not use the sample's .deps.json automatically. These C# callbacks +# resolve its NuGet assemblies/native libraries, including on background render threads. +Add-Type -TypeDefinition @' +using System; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.Loader; +public static class Sample11DependencyLoader +{ + public static void Initialize(string applicationPath) + { + var resolver = new AssemblyDependencyResolver(applicationPath); + AssemblyLoadContext.Default.Resolving += (context, name) => + { + var path = resolver.ResolveAssemblyToPath(name); + return path == null ? null : context.LoadFromAssemblyPath(path); + }; + + AssemblyLoadContext.Default.ResolvingUnmanagedDll += (assembly, name) => + { + var path = resolver.ResolveUnmanagedDllToPath(name); + return path == null ? IntPtr.Zero : NativeLibrary.Load(path); + }; + + // ResolvingUnmanagedDll is a fallback, after PATH lookup. Register a resolver + // on these assemblies first so another installed application's older native + // Skia/HarfBuzz cannot win over the versions in this sample's .deps.json. + foreach (var name in new[] { "SkiaSharp", "HarfBuzzSharp" }) + { + var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(name)); + NativeLibrary.SetDllImportResolver(assembly, (library, importingAssembly, searchPath) => + { + var path = resolver.ResolveUnmanagedDllToPath(library); + return path == null ? IntPtr.Zero : NativeLibrary.Load(path); + }); + } + } +} +'@ +[Sample11DependencyLoader]::Initialize((Join-Path $assemblyDirectory 'Sample11.GenerateDotGraph.dll')) + foreach ($assemblyName in @('Lite.StateMachine.dll', 'Lite.StateMachine.DotGraph.dll', 'Sample11.GenerateDotGraph.dll')) { $assemblyPath = Join-Path $assemblyDirectory $assemblyName @@ -44,23 +86,39 @@ foreach ($assemblyName in @('Lite.StateMachine.dll', 'Lite.StateMachine.DotGraph } $OutputDirectory = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputDirectory) + [void][IO.Directory]::CreateDirectory($OutputDirectory) -$renderer = [Lite.StateMachine.DotGraph.GraphvizRenderer]::new($DotPath, [TimeSpan]::FromSeconds(30)) + +$renderer = if ($DotPath) { + [Lite.StateMachine.DotGraph.GraphvizRenderer]::new($DotPath, [TimeSpan]::FromSeconds(30)) +} else { + [Lite.StateMachine.DotGraph.GraphvizRenderer]::new() +} + $token = [Threading.CancellationToken]::None -foreach ($includeLegend in @($false, $true)) { +foreach ($includeLegend in @($false, $true)) +{ $name = if ($includeLegend) { 'machine-legend' } else { 'machine' } # This calls a public DLL method, not the console application's entry point. - $dot = [Sample11.GenerateDotGraph.WorkflowDiagram]::ExportDot($includeLegend) + $dot = [Sample11.GenerateDotGraph.SampleStateMachine]::ExportDot($includeLegend) [IO.File]::WriteAllText((Join-Path $OutputDirectory "$name.dot"), $dot) - [void]$renderer.RenderAsync($dot, (Join-Path $OutputDirectory "$name.svg"), - [Lite.StateMachine.DotGraph.DotGraphFormat]::Svg, $token).GetAwaiter().GetResult() + try + { + [void]$renderer.RenderAsync($dot, (Join-Path $OutputDirectory "$name.svg"), + [Lite.StateMachine.DotGraph.DotGraphFormat]::Svg, $token).GetAwaiter().GetResult() - [void]$renderer.RenderAsync($dot, (Join-Path $OutputDirectory "$name.png"), - [Lite.StateMachine.DotGraph.DotGraphFormat]::Png, $token).GetAwaiter().GetResult() + [void]$renderer.RenderAsync($dot, (Join-Path $OutputDirectory "$name.png"), + [Lite.StateMachine.DotGraph.DotGraphFormat]::Png, $token).GetAwaiter().GetResult() + } + catch + { + Write-Host $_.Exception.ToString() + throw + } Write-Output "Generated $name.dot, $name.svg, and $name.png in $OutputDirectory" } diff --git a/samples/Sample11.GenerateDotGraph/Program.cs b/samples/Sample11.GenerateDotGraph/Program.cs index acf8488..5d7f0d5 100644 --- a/samples/Sample11.GenerateDotGraph/Program.cs +++ b/samples/Sample11.GenerateDotGraph/Program.cs @@ -24,7 +24,7 @@ private static async Task Main(string[] args) var renderer = new GraphvizRenderer(args.Length > 1 ? args[1] - : "dot"); + : null); Directory.CreateDirectory(outputDirectory); diff --git a/samples/Sample11.GenerateDotGraph/readme.md b/samples/Sample11.GenerateDotGraph/readme.md index 1977b62..718df20 100644 --- a/samples/Sample11.GenerateDotGraph/readme.md +++ b/samples/Sample11.GenerateDotGraph/readme.md @@ -17,8 +17,8 @@ the topology. Neither generation path runs the workflow. ## Requirements * Install .NET 10 or 11 -* Install [Graphviz](https://graphviz.org/download/). -* Add Graphviz's `bin` directory to PATH, or pass its `dot`/`dot.exe` path explicitly. +* No Graphviz installation, PATH changes, or runtime downloads are needed. + The renderer embeds Graphviz and a PNG fallback font; NuGet supplies its runtimes. The project references the local core and renderer projects; it does not reference or reuse the unit-test assembly. @@ -30,7 +30,7 @@ From the repository root: ```powershell dotnet run --project samples/Sample11.GenerateDotGraph -c Release -f net10.0 -- samples/Sample11.GenerateDotGraph/diagrams -# Optional second argument: the Graphviz executable (quote paths with spaces). +# Optional opt-in to your own Graphviz executable instead of the bundled engine: dotnet run --project samples/Sample11.GenerateDotGraph -c Release -f net10.0 -- samples/Sample11.GenerateDotGraph/diagrams 'C:/Program Files/Graphviz/bin/dot.exe' ``` @@ -45,15 +45,19 @@ Run a fresh process to avoid conflicts with previously loaded DLL versions: ```powershell pwsh -NoProfile -File samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 -# Optional output folder and Graphviz path: -pwsh -NoProfile -File samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 -OutputDirectory ./output/sample11-powershell -DotPath 'C:/Program Files/Graphviz/bin/dot.exe' +# Optional output folder (still uses bundled Graphviz): +pwsh -NoProfile -File samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 -OutputDirectory ./output/sample11-powershell ``` The script builds `net10.0`, loads the sample DLL and its libraries, and calls -`WorkflowDiagram.ExportDot(bool)` directly. It then renders the returned DOT through +`SampleStateMachine.ExportDot(bool)` directly. It then renders the returned DOT through `GraphvizRenderer`; it does not launch the sample executable. `-SkipBuild` reuses a previous build, and `-Configuration Debug` selects Debug output instead of Release. By default, the script writes to this sample's `diagrams` directory. +It uses the sample's `.deps.json` to resolve the renderer's NuGet/native dependencies. +SkiaSharp/HarfBuzz native imports are resolved before PATH lookup, so an older DLL +installed by another application cannot override the sample's packaged version. +`-DotPath` is only needed when explicitly opting into an external Graphviz executable. Both generation paths produce six files, replacing existing images on success: @@ -62,6 +66,6 @@ Both generation paths produce six files, replacing existing images on success: | Without legend | `machine.dot` | `machine.svg` | `machine.png` | | With legend | `machine-legend.dot` | `machine-legend.svg` | `machine-legend.png` | -The checked-in `diagrams` directory contains generated examples. DOT text is the -same from both paths; image layout may vary with the installed Graphviz version -and fonts. +The generated `diagrams` directory contains both examples. DOT text is the +same from both paths. Both paths use the same pinned Graphviz engine by default. +See the renderer README for supported platforms and bundled-backend limitations. diff --git a/scripts/Test-DotGraphPackage.ps1 b/scripts/Test-DotGraphPackage.ps1 new file mode 100644 index 0000000..e029496 --- /dev/null +++ b/scripts/Test-DotGraphPackage.ps1 @@ -0,0 +1,78 @@ +#Requires -Version 7.0 +<# +.SYNOPSIS +Packs the renderer, restores a fresh NuGet consumer, and renders with an empty PATH. +#> +[CmdletBinding()] +param() + +$ErrorActionPreference = 'Stop' +$repository = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +# Unix runners commonly expose dotnet through several PATH entries/symlinks. +$dotnet = (Get-Command dotnet -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source +$version = '0.0.0-bundled.' + [DateTime]::UtcNow.Ticks +$scratch = Join-Path ([IO.Path]::GetTempPath()) ('dotgraph-package-' + [Guid]::NewGuid().ToString('N')) +$feed = Join-Path $scratch 'feed' +$consumer = Join-Path $scratch 'consumer' +$publish = Join-Path $scratch 'publish' +[void][IO.Directory]::CreateDirectory($consumer) + +& $dotnet pack (Join-Path $repository 'source/Lite.StateMachine.DotGraph') -c Release "-p:PackageVersion=$version" --output $feed -m:1 -p:UseSharedCompilation=false +if ($LASTEXITCODE -ne 0) { throw 'Renderer packing failed.' } + +$project = @" + + + Exe + net10.0 + enable + enable + + + + + +"@ +[IO.File]::WriteAllText((Join-Path $consumer 'Consumer.csproj'), $project) +[IO.File]::WriteAllText((Join-Path $consumer 'Program.cs'), @' +using Lite.StateMachine.DotGraph; +var renderer = new GraphvizRenderer(); +var directory = Path.Combine(AppContext.BaseDirectory, "images"); +Directory.CreateDirectory(directory); +var dot = "digraph { subgraph cluster_child { label=\"Child\"; a [label=\"Prépare\"]; a -> b [label=\"Success\"]; } b -> c; }"; +await renderer.RenderAsync(dot, Path.Combine(directory, "machine.svg")); +await renderer.RenderAsync(dot, Path.Combine(directory, "machine.png"), DotGraphFormat.Png); +var svg = File.ReadAllText(Path.Combine(directory, "machine.svg")); +var png = File.ReadAllBytes(Path.Combine(directory, "machine.png")); +if (!svg.Contains(" + + + + + + +"@) +& $dotnet restore $consumer --configfile $configPath +if ($LASTEXITCODE -ne 0) { throw 'NuGet consumer restore failed.' } +& $dotnet publish $consumer -c Release --no-restore --self-contained false --output $publish -m:1 -p:UseSharedCompilation=false +if ($LASTEXITCODE -ne 0) { throw 'NuGet consumer publish failed.' } + +$savedPath = $env:PATH +try { + # Nothing, including an existing Graphviz installation, can be resolved on PATH. + $env:PATH = '' + & $dotnet (Join-Path $publish 'Consumer.dll') + if ($LASTEXITCODE -ne 0) { throw 'Published bundled rendering failed.' } +} finally { + $env:PATH = $savedPath +} +Write-Output "Smoke-test files: $scratch" diff --git a/scripts/Update-Graphviz.ps1 b/scripts/Update-Graphviz.ps1 new file mode 100644 index 0000000..7eeede0 --- /dev/null +++ b/scripts/Update-Graphviz.ps1 @@ -0,0 +1,338 @@ +<# +.SYNOPSIS +Restores pinned Graphviz/font build assets, or explicitly upgrades the Graphviz WASI release. +.DESCRIPTION +The default operation downloads only missing or invalid locked assets into the ignored +output/dependencies/graphviz cache. It never selects a newer release implicitly. +Latest/ReleaseTag update the tracked manifest, notices, and source record after validation. +If GitHub has no published asset digest, an upgrade requires an explicit SHA256. +.EXAMPLE +./scripts/Update-Graphviz.ps1 +.EXAMPLE +./scripts/Update-Graphviz.ps1 -Latest -WhatIf +.EXAMPLE +./scripts/Update-Graphviz.ps1 -ReleaseTag v0.1.5 -Sha256 37fafda7f34855e7deffcb7317c1970aeea7b82f7cf191b8919501fcb48e9e3a +#> +#Requires -Version 7.0 + +[CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Restore')] +param( + [Parameter(Mandatory, ParameterSetName = 'Latest')] + [switch] $Latest, + + [Parameter(Mandatory, ParameterSetName = 'Release')] + [ValidatePattern('^v\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$')] + [string] $ReleaseTag, + + [Parameter(ParameterSetName = 'Latest')] + [Parameter(ParameterSetName = 'Release')] + [ValidatePattern('^[a-fA-F0-9]{64}$')] + [string] $Sha256, + + [Parameter(Mandatory, ParameterSetName = 'Verify')] + [switch] $VerifyOnly, + + [Parameter(ParameterSetName = 'Restore')] + [switch] $Force, + + [string] $ManifestPath = (Join-Path $PSScriptRoot '../source/Lite.StateMachine.DotGraph/Assets/graphviz-assets.json'), + [string] $CacheDirectory = (Join-Path $PSScriptRoot '../output/dependencies/graphviz') +) + +Set-StrictMode -Version Latest + +$ErrorActionPreference = 'Stop' +$ManifestPath = [IO.Path]::GetFullPath($ManifestPath) +$CacheDirectory = [IO.Path]::GetFullPath($CacheDirectory) +$assetDirectory = Split-Path $ManifestPath +$headers = @{ + 'User-Agent' = 'Lite.StateMachine.DotGraph-dependency-updater'; + Accept = 'application/vnd.github+json' +} + +function Get-Sha256([string] $Path, [switch] $Text) +{ + if (-not $Text) { + return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() + } + + # Git may convert notice line endings on checkout; compare canonical UTF-8/LF text. + $content = [IO.File]::ReadAllText($Path).Replace("`r`n", "`n") + $algorithm = [Security.Cryptography.SHA256]::Create() + + try { + return ([BitConverter]::ToString($algorithm.ComputeHash([Text.Encoding]::UTF8.GetBytes($content)))).Replace('-', '').ToLowerInvariant() + } finally { + $algorithm.Dispose() + } +} + +function Test-Asset([string] $Path, [string] $ExpectedHash, [switch] $Text) +{ + return (Test-Path -LiteralPath $Path -PathType Leaf) -and ((Get-Sha256 $Path -Text:$Text) -eq $ExpectedHash) +} + +function Assert-Descriptor($Descriptor) +{ + if ($Descriptor.sha256 -notmatch '^[a-fA-F0-9]{64}$') { + throw "Invalid SHA-256 for $($Descriptor.fileName)." + } + + if ($Descriptor.fileName -ne [IO.Path]::GetFileName($Descriptor.fileName) -or + $Descriptor.fileName -match '[/\\:]' -or $Descriptor.fileName -in @('', '.', '..')) { + throw "Asset fileName must be a plain filename: $($Descriptor.fileName)" + } + + $uri = [Uri]$Descriptor.url + if (-not $uri.IsAbsoluteUri -or $uri.Scheme -ne 'https') { + throw "Asset URL must use HTTPS: $($Descriptor.url)" + } +} + +function Write-Utf8([string] $Path, [string] $Content) +{ + [IO.File]::WriteAllText($Path, $Content.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false)) +} + +function Get-Download([string] $Url, [string] $Destination) +{ + Write-Verbose "Downloading $Url" + Invoke-WebRequest -Uri $Url -OutFile $Destination -Headers $headers -TimeoutSec 120 -MaximumRetryCount 2 | Out-Null +} + +function Write-SourceRecord($Manifest) +{ + $graph = $Manifest.graphviz + $font = $Manifest.font + + $record = @" +Bundled build assets (restored by ud.ps1; binaries are not stored in Git) +===================================================================== +Authoritative lock file: graphviz-assets.json + +graphviz.wasm: Graphviz $($graph.version), WASI build $($graph.releaseTag) +SHA-256: $($graph.sha256) +Binary: $($graph.url) +Graphviz source: $($graph.sourceUrl) +Wrapper/build scripts: $($graph.buildUrl) +Licenses: Graphviz-LICENSE.txt, WasiGraphviz-LICENSE.txt, WasiGraphviz-NOTICE.txt +Upstream notices are preserved verbatim and may mention an older upstream version; +the lock file and release build script identify the selected version. + +Tinos-Regular.ttf: Tinos $($font.version) +SHA-256: $($font.sha256) +Binary: $($font.url) +Source: $($font.sourceUrl) +License: Tinos-LICENSE.txt (SIL Open Font License 1.1) + +The build verifies the locked hashes before embedding the binaries. NuGet consumers +receive the embedded assets and runtime dependencies and need no downloader. +Updating the lock file does not verify ABI/plugin compatibility: run the bundled +renderer suite and scripts/Test-DotGraphPackage.ps1 before releasing an update. +Execution dependency versions/licenses are declared in Directory.Packages.props +and their individual NuGet packages (Wasmtime, Svg.Skia, SkiaSharp/native assets). +"@ + + Write-Utf8 (Join-Path $assetDirectory 'SOURCES.txt') ($record + "`n") +} + +$manifest = Get-Content -LiteralPath $ManifestPath -Raw | ConvertFrom-Json +if ($manifest.schemaVersion -ne 1) { + throw 'Unsupported Graphviz asset manifest schema.' } + +if ($manifest.graphviz.fileName -ne 'graphviz.wasm' -or $manifest.font.fileName -ne 'Tinos-Regular.ttf') { + throw 'Unexpected Graphviz/font asset filenames.' +} + +foreach ($descriptor in @($manifest.graphviz, $manifest.font) + @($manifest.graphviz.notices) + @($manifest.font.notices)) { + Assert-Descriptor $descriptor +} + +$upgrading = $Latest -or -not [string]::IsNullOrEmpty($ReleaseTag) +if ($upgrading) +{ + $api = 'https://api.github.com/repos/pablormier/wasi-graphviz/releases/' + $api += if ($Latest) { 'latest' } else { 'tags/' + [Uri]::EscapeDataString($ReleaseTag) } + $release = Invoke-RestMethod -Uri $api -Headers $headers -TimeoutSec 60 -MaximumRetryCount 2 + $tag = [string]$release.tag_name + + if ($tag -notmatch '^v\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$' -or $release.draft) { + throw 'The selected release is not a published semantic-version tag.' + } + + $binaries = @($release.assets | Where-Object { $_.name -eq 'graphviz.wasm' -and $_.state -eq 'uploaded' }) + + if ($binaries.Count -ne 1) { + throw "Release $tag must have exactly one uploaded graphviz.wasm asset." } + + $binary = $binaries[0] + $digestProperty = $binary.PSObject.Properties['digest'] + $publishedHash = if ($null -ne $digestProperty -and $digestProperty.Value -match '^sha256:([a-fA-F0-9]{64})$') { $Matches[1] } else { $null } + + if (-not $Sha256) + { + if (-not $publishedHash) { + throw 'GitHub has no SHA-256 digest for this asset. Review the release and supply -Sha256 explicitly.' } + + $Sha256 = $publishedHash + } + elseif ($publishedHash -and $Sha256 -ne $publishedHash) + { + throw 'The supplied -Sha256 disagrees with the digest published by GitHub.' + } + + $raw = "https://raw.githubusercontent.com/pablormier/wasi-graphviz/$tag/" + $buildScript = (Invoke-WebRequest -Uri ($raw + 'scripts/build_wasm.py') -Headers $headers -TimeoutSec 60).Content + + if ($buildScript -notmatch 'GRAPHVIZ_VERSION\s*=\s*"(?\d+\.\d+\.\d+)"') { + throw 'Could not determine the upstream Graphviz version from the release build script. Review this release manually.' + } + + $version = $Matches.version + Write-Host "Selected WASI $tag / Graphviz $version (currently $($manifest.graphviz.releaseTag) / $($manifest.graphviz.version))." + # Refuse to overwrite local notice edits during a dependency upgrade. + + foreach ($notice in @($manifest.graphviz.notices)) + { + if (-not (Test-Asset (Join-Path $assetDirectory $notice.fileName) $notice.sha256 -Text)) { + throw "Local notice has changes or is missing: $($notice.fileName). Restore or review it before upgrading." + } + } + + $manifest.graphviz.version = $version + $manifest.graphviz.releaseTag = $tag + $manifest.graphviz.url = [string]$binary.browser_download_url + $manifest.graphviz.sha256 = $Sha256.ToLowerInvariant() + $manifest.graphviz.sourceUrl = "https://gitlab.com/graphviz/graphviz/-/tree/$version" + $manifest.graphviz.buildUrl = "https://github.com/pablormier/wasi-graphviz/tree/$tag" + $manifest.graphviz.notices[0].url = $raw + 'src/wasi_graphviz/assets/GRAPHVIZ_LICENSE' + $manifest.graphviz.notices[1].url = $raw + 'LICENSE' + $manifest.graphviz.notices[2].url = $raw + 'NOTICE' + + Assert-Descriptor $manifest.graphviz +} + +if (-not $VerifyOnly -and -not $PSCmdlet.ShouldProcess($CacheDirectory, $(if ($upgrading) + { 'Download and lock selected Graphviz release' } + else {'Restore pinned Graphviz build assets' }))) +{ + return +} + +if ($VerifyOnly) +{ + foreach ($descriptor in @($manifest.graphviz, $manifest.font)) + { + $path = Join-Path $CacheDirectory $descriptor.fileName + if (-not (Test-Asset $path $descriptor.sha256)) { + throw "Missing or invalid cached asset: $path. Run ./ud.ps1 to restore it." } + } + + foreach ($notice in @($manifest.graphviz.notices) + @($manifest.font.notices)) + { + if (-not (Test-Asset (Join-Path $assetDirectory $notice.fileName) $notice.sha256 -Text)) { + throw "Missing or invalid notice: $($notice.fileName)" } + } + + Write-Host "Verified Graphviz $($manifest.graphviz.version) and font assets (offline)." + return +} + +[void][IO.Directory]::CreateDirectory($CacheDirectory) +$lock = $null +$watch = [Diagnostics.Stopwatch]::StartNew() +while ($null -eq $lock) +{ + try + { + $lock = [IO.File]::Open((Join-Path $CacheDirectory '.restore.lock'), 'OpenOrCreate', 'ReadWrite', 'None') + } + catch [IO.IOException] + { + if ($watch.Elapsed.TotalSeconds -ge 60) { + throw 'Timed out waiting for another Graphviz asset restore.' } + + Start-Sleep -Milliseconds 200 + } +} + +$staged = [Collections.Generic.List[object]]::new() + +try +{ + foreach ($descriptor in @($manifest.graphviz, $manifest.font)) + { + $destination = Join-Path $CacheDirectory $descriptor.fileName + if (-not $Force -and (Test-Asset $destination $descriptor.sha256)) { + continue } + + $temporary = Join-Path $CacheDirectory ([IO.Path]::GetRandomFileName()) + $staged.Add(@{ temporary = $temporary; destination = $destination }) + + Get-Download $descriptor.url $temporary + + if (-not (Test-Asset $temporary $descriptor.sha256)) { + throw "SHA-256 verification failed for $($descriptor.fileName). Existing assets/manifest have not been replaced." } + + if ($descriptor.fileName -eq 'graphviz.wasm') + { + $magic = [IO.File]::ReadAllBytes($temporary) + + if ($magic.Length -lt 8 -or [BitConverter]::ToString($magic, 0, 8) -ne '00-61-73-6D-01-00-00-00') { + throw 'The downloaded artifact is not a WASM 1.0 module.' } + } + } + + foreach ($notice in @($manifest.graphviz.notices) + @($manifest.font.notices)) + { + $destination = Join-Path $assetDirectory $notice.fileName + $refresh = $upgrading -and $notice.fileName -ne 'Tinos-LICENSE.txt' + + if (-not $refresh -and (Test-Asset $destination $notice.sha256 -Text)) { + continue } + + if (-not $refresh -and -not $Force -and (Test-Path -LiteralPath $destination)) { + throw "Tracked notice differs from the lock file: $($notice.fileName). Restore/review local changes, or use -Force to restore the pinned notice." + } + + $temporary = Join-Path $CacheDirectory ([IO.Path]::GetRandomFileName()) + $staged.Add(@{ temporary = $temporary; destination = $destination }) + Get-Download $notice.url $temporary + + if ([string]::IsNullOrWhiteSpace([IO.File]::ReadAllText($temporary))) { + throw "Downloaded notice is empty: $($notice.fileName)." } + + if ($refresh) { + $notice.sha256 = Get-Sha256 $temporary -Text } + elseif (-not (Test-Asset $temporary $notice.sha256 -Text)) { + throw "SHA-256 verification failed for notice $($notice.fileName)." } + } + + # All downloads have passed validation before any existing artifact is replaced. + foreach ($file in $staged) { + Move-Item -LiteralPath $file.temporary -Destination $file.destination -Force } + + if ($upgrading) + { + $temporaryManifest = Join-Path $CacheDirectory ([IO.Path]::GetRandomFileName()) + + try { + Write-Utf8 $temporaryManifest (($manifest | ConvertTo-Json -Depth 10) + "`n") + Move-Item -LiteralPath $temporaryManifest -Destination $ManifestPath -Force + } finally { + if (Test-Path -LiteralPath $temporaryManifest) { Remove-Item -LiteralPath $temporaryManifest -Force } + } + + Write-SourceRecord $manifest + } + + Write-Host "Graphviz $($manifest.graphviz.version) and font assets are ready in $CacheDirectory." +} +finally +{ + foreach ($file in $staged) { + if (Test-Path -LiteralPath $file.temporary) { Remove-Item -LiteralPath $file.temporary -Force } + } + + $lock.Dispose() +} diff --git a/source/Lite.StateMachine.DotGraph.Tests/GraphvizRendererTests.cs b/source/Lite.StateMachine.DotGraph.Tests/GraphvizRendererTests.cs index b10a9d6..e189608 100644 --- a/source/Lite.StateMachine.DotGraph.Tests/GraphvizRendererTests.cs +++ b/source/Lite.StateMachine.DotGraph.Tests/GraphvizRendererTests.cs @@ -3,7 +3,9 @@ using System; using System.IO; +using System.Security.Cryptography; using System.Text; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Lite.StateMachine.DotGraph; @@ -68,6 +70,8 @@ public async Task RendersTextAsUtf8SvgAndReplacesExistingImageAsync() await renderer.RenderAsync(Graph, output); var svg = await File.ReadAllTextAsync(output); StringAssert.Contains(svg, "(() => renderer.RenderAsync("invalid dot", output)); - StringAssert.Contains(exception.Message, "Graphviz exited with code"); - StringAssert.Contains(exception.Message, "syntax error"); + StringAssert.Contains(exception.Message, "Graphviz rendering failed"); + StringAssert.Contains(exception.Message, "parse DOT"); Assert.AreEqual("previous image", await File.ReadAllTextAsync(output)); Assert.HasCount(1, Directory.GetFiles(_directory)); } [TestMethod] [TestCategory("Graphviz")] - public async Task LargeInvalidInputDoesNotMaskDiagnosticsWithBrokenPipeAsync() + public async Task LargeInvalidInputReportsBundledDiagnosticsAsync() { var renderer = CreateRenderer(); var dot = "invalid dot " + new string('x', 1024 * 1024); var exception = await Assert.ThrowsAsync(() => renderer.RenderAsync(dot, Output("machine.svg"))); - StringAssert.Contains(exception.Message, "Graphviz exited with code"); + StringAssert.Contains(exception.Message, "Graphviz rendering failed"); Assert.IsEmpty(Directory.GetFiles(_directory)); } @@ -141,15 +145,35 @@ public async Task CancellationStopsRenderingAndCleansTemporaryOutputAsync() Assert.IsEmpty(Directory.GetFiles(_directory)); } - private static GraphvizRenderer CreateRenderer(TimeSpan? timeout = null) + [TestMethod] + public void BundledAssetsMatchPinnedHashes() + { + using var engine = typeof(GraphvizRenderer).Assembly.GetManifestResourceStream("Lite.StateMachine.DotGraph.graphviz.wasm"); + using var font = typeof(GraphvizRenderer).Assembly.GetManifestResourceStream("Lite.StateMachine.DotGraph.Tinos-Regular.ttf"); + Assert.IsNotNull(engine); + Assert.IsNotNull(font); + using var manifest = ReadAssetManifest(); + Assert.AreEqual(manifest.RootElement.GetProperty("graphviz").GetProperty("sha256").GetString()!.ToUpperInvariant(), Convert.ToHexString(SHA256.HashData(engine))); + Assert.AreEqual(manifest.RootElement.GetProperty("font").GetProperty("sha256").GetString()!.ToUpperInvariant(), Convert.ToHexString(SHA256.HashData(font))); + } + + [TestMethod] + [TestCategory("ExternalGraphviz")] + public async Task ExternalExecutablePreservesBrokenPipeDiagnosticsAsync() { var executable = Environment.GetEnvironmentVariable("GRAPHVIZ_DOT"); if (string.IsNullOrWhiteSpace(executable)) - Assert.Inconclusive("Set GRAPHVIZ_DOT to dot or its full path to run Graphviz integration tests."); + Assert.Inconclusive("Optional: set GRAPHVIZ_DOT to test the external executable override."); - return new GraphvizRenderer(executable, timeout); + var renderer = new GraphvizRenderer(executable); + var exception = await Assert.ThrowsAsync(() => renderer.RenderAsync("invalid dot " + new string('x', 1024 * 1024), Output("machine.svg"))); + StringAssert.Contains(exception.Message, "Graphviz exited with code"); + StringAssert.Contains(exception.Message, "syntax error"); + Assert.IsEmpty(Directory.GetFiles(_directory)); } + private static GraphvizRenderer CreateRenderer(TimeSpan? timeout = null) => new(timeout: timeout); + private static string LargeGraph() { var graph = new StringBuilder("digraph {"); @@ -159,5 +183,12 @@ private static string LargeGraph() return graph.Append('}').ToString(); } + private static JsonDocument ReadAssetManifest() + { + using var stream = typeof(GraphvizRenderer).Assembly.GetManifestResourceStream("Lite.StateMachine.DotGraph.graphviz-assets.json"); + Assert.IsNotNull(stream); + return JsonDocument.Parse(stream); + } + private string Output(string name) => Path.Combine(_directory, name); } diff --git a/source/Lite.StateMachine.DotGraph/Assets/Graphviz-LICENSE.txt b/source/Lite.StateMachine.DotGraph/Assets/Graphviz-LICENSE.txt new file mode 100644 index 0000000..e23ece2 --- /dev/null +++ b/source/Lite.StateMachine.DotGraph/Assets/Graphviz-LICENSE.txt @@ -0,0 +1,277 @@ +Eclipse Public License - v 2.0 + + THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE + PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION + OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + +1. DEFINITIONS + +"Contribution" means: + + a) in the case of the initial Contributor, the initial content + Distributed under this Agreement, and + + b) in the case of each subsequent Contributor: + i) changes to the Program, and + ii) additions to the Program; + where such changes and/or additions to the Program originate from + and are Distributed by that particular Contributor. A Contribution + "originates" from a Contributor if it was added to the Program by + such Contributor itself or anyone acting on such Contributor's behalf. + Contributions do not include changes or additions to the Program that + are not Modified Works. + +"Contributor" means any person or entity that Distributes the Program. + +"Licensed Patents" mean patent claims licensable by a Contributor which +are necessarily infringed by the use or sale of its Contribution alone +or when combined with the Program. + +"Program" means the Contributions Distributed in accordance with this +Agreement. + +"Recipient" means anyone who receives the Program under this Agreement +or any Secondary License (as applicable), including Contributors. + +"Derivative Works" shall mean any work, whether in Source Code or other +form, that is based on (or derived from) the Program and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. + +"Modified Works" shall mean any work in Source Code or other form that +results from an addition to, deletion from, or modification of the +contents of the Program, including, for purposes of clarity any new file +in Source Code form that contains any contents of the Program. Modified +Works shall not include works that contain only declarations, +interfaces, types, classes, structures, or files of the Program solely +in each case in order to link to, bind by name, or subclass the Program +or Modified Works thereof. + +"Distribute" means the acts of a) distributing or b) making available +in any manner that enables the transfer of a copy. + +"Source Code" means the form of a Program preferred for making +modifications, including but not limited to software source code, +documentation source, and configuration files. + +"Secondary License" means either the GNU General Public License, +Version 2.0, or any later versions of that license, including any +exceptions or additional permissions as identified by the initial +Contributor. + +2. GRANT OF RIGHTS + + a) Subject to the terms of this Agreement, each Contributor hereby + grants Recipient a non-exclusive, worldwide, royalty-free copyright + license to reproduce, prepare Derivative Works of, publicly display, + publicly perform, Distribute and sublicense the Contribution of such + Contributor, if any, and such Derivative Works. + + b) Subject to the terms of this Agreement, each Contributor hereby + grants Recipient a non-exclusive, worldwide, royalty-free patent + license under Licensed Patents to make, use, sell, offer to sell, + import and otherwise transfer the Contribution of such Contributor, + if any, in Source Code or other form. This patent license shall + apply to the combination of the Contribution and the Program if, at + the time the Contribution is added by the Contributor, such addition + of the Contribution causes such combination to be covered by the + Licensed Patents. The patent license shall not apply to any other + combinations which include the Contribution. No hardware per se is + licensed hereunder. + + c) Recipient understands that although each Contributor grants the + licenses to its Contributions set forth herein, no assurances are + provided by any Contributor that the Program does not infringe the + patent or other intellectual property rights of any other entity. + Each Contributor disclaims any liability to Recipient for claims + brought by any other entity based on infringement of intellectual + property rights or otherwise. As a condition to exercising the + rights and licenses granted hereunder, each Recipient hereby + assumes sole responsibility to secure any other intellectual + property rights needed, if any. For example, if a third party + patent license is required to allow Recipient to Distribute the + Program, it is Recipient's responsibility to acquire that license + before distributing the Program. + + d) Each Contributor represents that to its knowledge it has + sufficient copyright rights in its Contribution, if any, to grant + the copyright license set forth in this Agreement. + + e) Notwithstanding the terms of any Secondary License, no + Contributor makes additional grants to any Recipient (other than + those set forth in this Agreement) as a result of such Recipient's + receipt of the Program under the terms of a Secondary License + (if permitted under the terms of Section 3). + +3. REQUIREMENTS + +3.1 If a Contributor Distributes the Program in any form, then: + + a) the Program must also be made available as Source Code, in + accordance with section 3.2, and the Contributor must accompany + the Program with a statement that the Source Code for the Program + is available under this Agreement, and informs Recipients how to + obtain it in a reasonable manner on or through a medium customarily + used for software exchange; and + + b) the Contributor may Distribute the Program under a license + different than this Agreement, provided that such license: + i) effectively disclaims on behalf of all other Contributors all + warranties and conditions, express and implied, including + warranties or conditions of title and non-infringement, and + implied warranties or conditions of merchantability and fitness + for a particular purpose; + + ii) effectively excludes on behalf of all other Contributors all + liability for damages, including direct, indirect, special, + incidental and consequential damages, such as lost profits; + + iii) does not attempt to limit or alter the recipients' rights + in the Source Code under section 3.2; and + + iv) requires any subsequent distribution of the Program by any + party to be under a license that satisfies the requirements + of this section 3. + +3.2 When the Program is Distributed as Source Code: + + a) it must be made available under this Agreement, or if the + Program (i) is combined with other material in a separate file or + files made available under a Secondary License, and (ii) the initial + Contributor attached to the Source Code the notice described in + Exhibit A of this Agreement, then the Program may be made available + under the terms of such Secondary Licenses, and + + b) a copy of this Agreement must be included with each copy of + the Program. + +3.3 Contributors may not remove or alter any copyright, patent, +trademark, attribution notices, disclaimers of warranty, or limitations +of liability ("notices") contained within the Program from any copy of +the Program which they Distribute, provided that Contributors may add +their own appropriate notices. + +4. COMMERCIAL DISTRIBUTION + +Commercial distributors of software may accept certain responsibilities +with respect to end users, business partners and the like. While this +license is intended to facilitate the commercial use of the Program, +the Contributor who includes the Program in a commercial product +offering should do so in a manner which does not create potential +liability for other Contributors. Therefore, if a Contributor includes +the Program in a commercial product offering, such Contributor +("Commercial Contributor") hereby agrees to defend and indemnify every +other Contributor ("Indemnified Contributor") against any losses, +damages and costs (collectively "Losses") arising from claims, lawsuits +and other legal actions brought by a third party against the Indemnified +Contributor to the extent caused by the acts or omissions of such +Commercial Contributor in connection with its distribution of the Program +in a commercial product offering. The obligations in this section do not +apply to any claims or Losses relating to any actual or alleged +intellectual property infringement. In order to qualify, an Indemnified +Contributor must: a) promptly notify the Commercial Contributor in +writing of such claim, and b) allow the Commercial Contributor to control, +and cooperate with the Commercial Contributor in, the defense and any +related settlement negotiations. The Indemnified Contributor may +participate in any such claim at its own expense. + +For example, a Contributor might include the Program in a commercial +product offering, Product X. That Contributor is then a Commercial +Contributor. If that Commercial Contributor then makes performance +claims, or offers warranties related to Product X, those performance +claims and warranties are such Commercial Contributor's responsibility +alone. Under this section, the Commercial Contributor would have to +defend claims against the other Contributors related to those performance +claims and warranties, and if a court requires any other Contributor to +pay any damages as a result, the Commercial Contributor must pay +those damages. + +5. NO WARRANTY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT +PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS" +BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR +IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF +TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR +PURPOSE. Each Recipient is solely responsible for determining the +appropriateness of using and distributing the Program and assumes all +risks associated with its exercise of rights under this Agreement, +including but not limited to the risks and costs of program errors, +compliance with applicable laws, damage to or loss of data, programs +or equipment, and unavailability or interruption of operations. + +6. DISCLAIMER OF LIABILITY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT +PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS +SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST +PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE +EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + +7. GENERAL + +If any provision of this Agreement is invalid or unenforceable under +applicable law, it shall not affect the validity or enforceability of +the remainder of the terms of this Agreement, and without further +action by the parties hereto, such provision shall be reformed to the +minimum extent necessary to make such provision valid and enforceable. + +If Recipient institutes patent litigation against any entity +(including a cross-claim or counterclaim in a lawsuit) alleging that the +Program itself (excluding combinations of the Program with other software +or hardware) infringes such Recipient's patent(s), then such Recipient's +rights granted under Section 2(b) shall terminate as of the date such +litigation is filed. + +All Recipient's rights under this Agreement shall terminate if it +fails to comply with any of the material terms or conditions of this +Agreement and does not cure such failure in a reasonable period of +time after becoming aware of such noncompliance. If all Recipient's +rights under this Agreement terminate, Recipient agrees to cease use +and distribution of the Program as soon as reasonably practicable. +However, Recipient's obligations under this Agreement and any licenses +granted by Recipient relating to the Program shall continue and survive. + +Everyone is permitted to copy and distribute copies of this Agreement, +but in order to avoid inconsistency the Agreement is copyrighted and +may only be modified in the following manner. The Agreement Steward +reserves the right to publish new versions (including revisions) of +this Agreement from time to time. No one other than the Agreement +Steward has the right to modify this Agreement. The Eclipse Foundation +is the initial Agreement Steward. The Eclipse Foundation may assign the +responsibility to serve as the Agreement Steward to a suitable separate +entity. Each new version of the Agreement will be given a distinguishing +version number. The Program (including Contributions) may always be +Distributed subject to the version of the Agreement under which it was +received. In addition, after a new version of the Agreement is published, +Contributor may elect to Distribute the Program (including its +Contributions) under the new version. + +Except as expressly stated in Sections 2(a) and 2(b) above, Recipient +receives no rights or licenses to the intellectual property of any +Contributor under this Agreement, whether expressly, by implication, +estoppel or otherwise. All rights in the Program not expressly granted +under this Agreement are reserved. Nothing in this Agreement is intended +to be enforceable by any entity that is not a Contributor or Recipient. +No third-party beneficiary rights are created under this Agreement. + +Exhibit A - Form of Secondary Licenses Notice + +"This Source Code may also be made available under the following +Secondary Licenses when the conditions for such availability set forth +in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), +version(s), and exceptions or additional permissions here}." + + Simply including a copy of this Agreement, including this Exhibit A + is not sufficient to license the Source Code under Secondary Licenses. + + If it is not possible or desirable to put the notice in a particular + file, then You may include the notice in a location (such as a LICENSE + file in a relevant directory) where a recipient would be likely to + look for such a notice. + + You may add additional accurate notices of copyright ownership. \ No newline at end of file diff --git a/source/Lite.StateMachine.DotGraph/Assets/SOURCES.txt b/source/Lite.StateMachine.DotGraph/Assets/SOURCES.txt new file mode 100644 index 0000000..c49151c --- /dev/null +++ b/source/Lite.StateMachine.DotGraph/Assets/SOURCES.txt @@ -0,0 +1,25 @@ +Bundled build assets (restored by ud.ps1; binaries are not stored in Git) +===================================================================== +Authoritative lock file: graphviz-assets.json + +graphviz.wasm: Graphviz 16.1.1, WASI build v0.1.5 +SHA-256: 37fafda7f34855e7deffcb7317c1970aeea7b82f7cf191b8919501fcb48e9e3a +Binary: https://github.com/pablormier/wasi-graphviz/releases/download/v0.1.5/graphviz.wasm +Graphviz source: https://gitlab.com/graphviz/graphviz/-/tree/16.1.1 +Wrapper/build scripts: https://github.com/pablormier/wasi-graphviz/tree/v0.1.5 +Licenses: Graphviz-LICENSE.txt, WasiGraphviz-LICENSE.txt, WasiGraphviz-NOTICE.txt +Upstream notices are preserved verbatim and may mention an older upstream version; +the lock file and release build script identify the selected version. + +Tinos-Regular.ttf: Tinos 1.340 +SHA-256: 60a0e8ef0c04dd5dd69ffe91025fa2ae5836cbd35600a82ba031977557e2cb61 +Binary: https://raw.githubusercontent.com/google/fonts/ba95515f1333efe9342c2ad988b9c2f6bef6dbad/ofl/tinos/Tinos-Regular.ttf +Source: https://github.com/googlefonts/tinos/tree/3b4482a99b80ea5fc75f187b1be3120a3f5905b3 +License: Tinos-LICENSE.txt (SIL Open Font License 1.1) + +The build verifies the locked hashes before embedding the binaries. NuGet consumers +receive the embedded assets and runtime dependencies and need no downloader. +Updating the lock file does not verify ABI/plugin compatibility: run the bundled +renderer suite and scripts/Test-DotGraphPackage.ps1 before releasing an update. +Execution dependency versions/licenses are declared in Directory.Packages.props +and their individual NuGet packages (Wasmtime, Svg.Skia, SkiaSharp/native assets). diff --git a/source/Lite.StateMachine.DotGraph/Assets/Tinos-LICENSE.txt b/source/Lite.StateMachine.DotGraph/Assets/Tinos-LICENSE.txt new file mode 100644 index 0000000..e91137c --- /dev/null +++ b/source/Lite.StateMachine.DotGraph/Assets/Tinos-LICENSE.txt @@ -0,0 +1,93 @@ +Copyright 2026 The Tinos Project Authors (https://github.com/googlefonts/tinos) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/source/Lite.StateMachine.DotGraph/Assets/WasiGraphviz-LICENSE.txt b/source/Lite.StateMachine.DotGraph/Assets/WasiGraphviz-LICENSE.txt new file mode 100644 index 0000000..e23ece2 --- /dev/null +++ b/source/Lite.StateMachine.DotGraph/Assets/WasiGraphviz-LICENSE.txt @@ -0,0 +1,277 @@ +Eclipse Public License - v 2.0 + + THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE + PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION + OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + +1. DEFINITIONS + +"Contribution" means: + + a) in the case of the initial Contributor, the initial content + Distributed under this Agreement, and + + b) in the case of each subsequent Contributor: + i) changes to the Program, and + ii) additions to the Program; + where such changes and/or additions to the Program originate from + and are Distributed by that particular Contributor. A Contribution + "originates" from a Contributor if it was added to the Program by + such Contributor itself or anyone acting on such Contributor's behalf. + Contributions do not include changes or additions to the Program that + are not Modified Works. + +"Contributor" means any person or entity that Distributes the Program. + +"Licensed Patents" mean patent claims licensable by a Contributor which +are necessarily infringed by the use or sale of its Contribution alone +or when combined with the Program. + +"Program" means the Contributions Distributed in accordance with this +Agreement. + +"Recipient" means anyone who receives the Program under this Agreement +or any Secondary License (as applicable), including Contributors. + +"Derivative Works" shall mean any work, whether in Source Code or other +form, that is based on (or derived from) the Program and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. + +"Modified Works" shall mean any work in Source Code or other form that +results from an addition to, deletion from, or modification of the +contents of the Program, including, for purposes of clarity any new file +in Source Code form that contains any contents of the Program. Modified +Works shall not include works that contain only declarations, +interfaces, types, classes, structures, or files of the Program solely +in each case in order to link to, bind by name, or subclass the Program +or Modified Works thereof. + +"Distribute" means the acts of a) distributing or b) making available +in any manner that enables the transfer of a copy. + +"Source Code" means the form of a Program preferred for making +modifications, including but not limited to software source code, +documentation source, and configuration files. + +"Secondary License" means either the GNU General Public License, +Version 2.0, or any later versions of that license, including any +exceptions or additional permissions as identified by the initial +Contributor. + +2. GRANT OF RIGHTS + + a) Subject to the terms of this Agreement, each Contributor hereby + grants Recipient a non-exclusive, worldwide, royalty-free copyright + license to reproduce, prepare Derivative Works of, publicly display, + publicly perform, Distribute and sublicense the Contribution of such + Contributor, if any, and such Derivative Works. + + b) Subject to the terms of this Agreement, each Contributor hereby + grants Recipient a non-exclusive, worldwide, royalty-free patent + license under Licensed Patents to make, use, sell, offer to sell, + import and otherwise transfer the Contribution of such Contributor, + if any, in Source Code or other form. This patent license shall + apply to the combination of the Contribution and the Program if, at + the time the Contribution is added by the Contributor, such addition + of the Contribution causes such combination to be covered by the + Licensed Patents. The patent license shall not apply to any other + combinations which include the Contribution. No hardware per se is + licensed hereunder. + + c) Recipient understands that although each Contributor grants the + licenses to its Contributions set forth herein, no assurances are + provided by any Contributor that the Program does not infringe the + patent or other intellectual property rights of any other entity. + Each Contributor disclaims any liability to Recipient for claims + brought by any other entity based on infringement of intellectual + property rights or otherwise. As a condition to exercising the + rights and licenses granted hereunder, each Recipient hereby + assumes sole responsibility to secure any other intellectual + property rights needed, if any. For example, if a third party + patent license is required to allow Recipient to Distribute the + Program, it is Recipient's responsibility to acquire that license + before distributing the Program. + + d) Each Contributor represents that to its knowledge it has + sufficient copyright rights in its Contribution, if any, to grant + the copyright license set forth in this Agreement. + + e) Notwithstanding the terms of any Secondary License, no + Contributor makes additional grants to any Recipient (other than + those set forth in this Agreement) as a result of such Recipient's + receipt of the Program under the terms of a Secondary License + (if permitted under the terms of Section 3). + +3. REQUIREMENTS + +3.1 If a Contributor Distributes the Program in any form, then: + + a) the Program must also be made available as Source Code, in + accordance with section 3.2, and the Contributor must accompany + the Program with a statement that the Source Code for the Program + is available under this Agreement, and informs Recipients how to + obtain it in a reasonable manner on or through a medium customarily + used for software exchange; and + + b) the Contributor may Distribute the Program under a license + different than this Agreement, provided that such license: + i) effectively disclaims on behalf of all other Contributors all + warranties and conditions, express and implied, including + warranties or conditions of title and non-infringement, and + implied warranties or conditions of merchantability and fitness + for a particular purpose; + + ii) effectively excludes on behalf of all other Contributors all + liability for damages, including direct, indirect, special, + incidental and consequential damages, such as lost profits; + + iii) does not attempt to limit or alter the recipients' rights + in the Source Code under section 3.2; and + + iv) requires any subsequent distribution of the Program by any + party to be under a license that satisfies the requirements + of this section 3. + +3.2 When the Program is Distributed as Source Code: + + a) it must be made available under this Agreement, or if the + Program (i) is combined with other material in a separate file or + files made available under a Secondary License, and (ii) the initial + Contributor attached to the Source Code the notice described in + Exhibit A of this Agreement, then the Program may be made available + under the terms of such Secondary Licenses, and + + b) a copy of this Agreement must be included with each copy of + the Program. + +3.3 Contributors may not remove or alter any copyright, patent, +trademark, attribution notices, disclaimers of warranty, or limitations +of liability ("notices") contained within the Program from any copy of +the Program which they Distribute, provided that Contributors may add +their own appropriate notices. + +4. COMMERCIAL DISTRIBUTION + +Commercial distributors of software may accept certain responsibilities +with respect to end users, business partners and the like. While this +license is intended to facilitate the commercial use of the Program, +the Contributor who includes the Program in a commercial product +offering should do so in a manner which does not create potential +liability for other Contributors. Therefore, if a Contributor includes +the Program in a commercial product offering, such Contributor +("Commercial Contributor") hereby agrees to defend and indemnify every +other Contributor ("Indemnified Contributor") against any losses, +damages and costs (collectively "Losses") arising from claims, lawsuits +and other legal actions brought by a third party against the Indemnified +Contributor to the extent caused by the acts or omissions of such +Commercial Contributor in connection with its distribution of the Program +in a commercial product offering. The obligations in this section do not +apply to any claims or Losses relating to any actual or alleged +intellectual property infringement. In order to qualify, an Indemnified +Contributor must: a) promptly notify the Commercial Contributor in +writing of such claim, and b) allow the Commercial Contributor to control, +and cooperate with the Commercial Contributor in, the defense and any +related settlement negotiations. The Indemnified Contributor may +participate in any such claim at its own expense. + +For example, a Contributor might include the Program in a commercial +product offering, Product X. That Contributor is then a Commercial +Contributor. If that Commercial Contributor then makes performance +claims, or offers warranties related to Product X, those performance +claims and warranties are such Commercial Contributor's responsibility +alone. Under this section, the Commercial Contributor would have to +defend claims against the other Contributors related to those performance +claims and warranties, and if a court requires any other Contributor to +pay any damages as a result, the Commercial Contributor must pay +those damages. + +5. NO WARRANTY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT +PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS" +BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR +IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF +TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR +PURPOSE. Each Recipient is solely responsible for determining the +appropriateness of using and distributing the Program and assumes all +risks associated with its exercise of rights under this Agreement, +including but not limited to the risks and costs of program errors, +compliance with applicable laws, damage to or loss of data, programs +or equipment, and unavailability or interruption of operations. + +6. DISCLAIMER OF LIABILITY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT +PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS +SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST +PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE +EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + +7. GENERAL + +If any provision of this Agreement is invalid or unenforceable under +applicable law, it shall not affect the validity or enforceability of +the remainder of the terms of this Agreement, and without further +action by the parties hereto, such provision shall be reformed to the +minimum extent necessary to make such provision valid and enforceable. + +If Recipient institutes patent litigation against any entity +(including a cross-claim or counterclaim in a lawsuit) alleging that the +Program itself (excluding combinations of the Program with other software +or hardware) infringes such Recipient's patent(s), then such Recipient's +rights granted under Section 2(b) shall terminate as of the date such +litigation is filed. + +All Recipient's rights under this Agreement shall terminate if it +fails to comply with any of the material terms or conditions of this +Agreement and does not cure such failure in a reasonable period of +time after becoming aware of such noncompliance. If all Recipient's +rights under this Agreement terminate, Recipient agrees to cease use +and distribution of the Program as soon as reasonably practicable. +However, Recipient's obligations under this Agreement and any licenses +granted by Recipient relating to the Program shall continue and survive. + +Everyone is permitted to copy and distribute copies of this Agreement, +but in order to avoid inconsistency the Agreement is copyrighted and +may only be modified in the following manner. The Agreement Steward +reserves the right to publish new versions (including revisions) of +this Agreement from time to time. No one other than the Agreement +Steward has the right to modify this Agreement. The Eclipse Foundation +is the initial Agreement Steward. The Eclipse Foundation may assign the +responsibility to serve as the Agreement Steward to a suitable separate +entity. Each new version of the Agreement will be given a distinguishing +version number. The Program (including Contributions) may always be +Distributed subject to the version of the Agreement under which it was +received. In addition, after a new version of the Agreement is published, +Contributor may elect to Distribute the Program (including its +Contributions) under the new version. + +Except as expressly stated in Sections 2(a) and 2(b) above, Recipient +receives no rights or licenses to the intellectual property of any +Contributor under this Agreement, whether expressly, by implication, +estoppel or otherwise. All rights in the Program not expressly granted +under this Agreement are reserved. Nothing in this Agreement is intended +to be enforceable by any entity that is not a Contributor or Recipient. +No third-party beneficiary rights are created under this Agreement. + +Exhibit A - Form of Secondary Licenses Notice + +"This Source Code may also be made available under the following +Secondary Licenses when the conditions for such availability set forth +in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), +version(s), and exceptions or additional permissions here}." + + Simply including a copy of this Agreement, including this Exhibit A + is not sufficient to license the Source Code under Secondary Licenses. + + If it is not possible or desirable to put the notice in a particular + file, then You may include the notice in a location (such as a LICENSE + file in a relevant directory) where a recipient would be likely to + look for such a notice. + + You may add additional accurate notices of copyright ownership. \ No newline at end of file diff --git a/source/Lite.StateMachine.DotGraph/Assets/WasiGraphviz-NOTICE.txt b/source/Lite.StateMachine.DotGraph/Assets/WasiGraphviz-NOTICE.txt new file mode 100644 index 0000000..fb07551 --- /dev/null +++ b/source/Lite.StateMachine.DotGraph/Assets/WasiGraphviz-NOTICE.txt @@ -0,0 +1,24 @@ +wasi-graphviz +Copyright 2025-2026 Pablo Rodriguez Mier + +This product is licensed under the Eclipse Public License, Version 2.0 +(EPL-2.0). See LICENSE for the full text. + +------------------------------------------------------------------------ +Bundled third-party software +------------------------------------------------------------------------ + +This product bundles a compiled build of Graphviz (https://graphviz.org/), +which is licensed under the Eclipse Public License, Version 2.0 (EPL-2.0). +The full EPL-2.0 text ships with the wheel as + src/wasi_graphviz/assets/GRAPHVIZ_LICENSE + +Source code for the bundled Graphviz version is available upstream at: + https://gitlab.com/graphviz/graphviz/-/tree/16.1.0 + +Modifications applied to the Graphviz source before compilation are +described in scripts/prepare_graphviz_wasi.py and are themselves +licensed under EPL-2.0. + +wasi-graphviz is an unofficial repackaging and is not affiliated with +or endorsed by the Graphviz project. diff --git a/source/Lite.StateMachine.DotGraph/Assets/graphviz-assets.json b/source/Lite.StateMachine.DotGraph/Assets/graphviz-assets.json new file mode 100644 index 0000000..5c359f3 --- /dev/null +++ b/source/Lite.StateMachine.DotGraph/Assets/graphviz-assets.json @@ -0,0 +1,43 @@ +{ + "schemaVersion": 1, + "graphviz": { + "version": "16.1.1", + "releaseTag": "v0.1.5", + "fileName": "graphviz.wasm", + "url": "https://github.com/pablormier/wasi-graphviz/releases/download/v0.1.5/graphviz.wasm", + "sha256": "37fafda7f34855e7deffcb7317c1970aeea7b82f7cf191b8919501fcb48e9e3a", + "sourceUrl": "https://gitlab.com/graphviz/graphviz/-/tree/16.1.1", + "buildUrl": "https://github.com/pablormier/wasi-graphviz/tree/v0.1.5", + "notices": [ + { + "url": "https://raw.githubusercontent.com/pablormier/wasi-graphviz/v0.1.5/src/wasi_graphviz/assets/GRAPHVIZ_LICENSE", + "sha256": "0becf16567beb77fa252b7664631dd177c8f9a1889e48995b45379c7130e5303", + "fileName": "Graphviz-LICENSE.txt" + }, + { + "url": "https://raw.githubusercontent.com/pablormier/wasi-graphviz/v0.1.5/LICENSE", + "sha256": "0becf16567beb77fa252b7664631dd177c8f9a1889e48995b45379c7130e5303", + "fileName": "WasiGraphviz-LICENSE.txt" + }, + { + "url": "https://raw.githubusercontent.com/pablormier/wasi-graphviz/v0.1.5/NOTICE", + "sha256": "b85fcc49e6a15b53221c88c59cf2033ebd6101da4ea747e832b15d1d479cf359", + "fileName": "WasiGraphviz-NOTICE.txt" + } + ] + }, + "font": { + "version": "1.340", + "fileName": "Tinos-Regular.ttf", + "url": "https://raw.githubusercontent.com/google/fonts/ba95515f1333efe9342c2ad988b9c2f6bef6dbad/ofl/tinos/Tinos-Regular.ttf", + "sha256": "60a0e8ef0c04dd5dd69ffe91025fa2ae5836cbd35600a82ba031977557e2cb61", + "sourceUrl": "https://github.com/googlefonts/tinos/tree/3b4482a99b80ea5fc75f187b1be3120a3f5905b3", + "notices": [ + { + "url": "https://raw.githubusercontent.com/googlefonts/tinos/3b4482a99b80ea5fc75f187b1be3120a3f5905b3/OFL.txt", + "sha256": "cb3382d4643e8b02c12e322c220a3c76a5020d667e4fd4e7c75e744cca6caa6b", + "fileName": "Tinos-LICENSE.txt" + } + ] + } +} diff --git a/source/Lite.StateMachine.DotGraph/BundledGraphviz.cs b/source/Lite.StateMachine.DotGraph/BundledGraphviz.cs new file mode 100644 index 0000000..b331693 --- /dev/null +++ b/source/Lite.StateMachine.DotGraph/BundledGraphviz.cs @@ -0,0 +1,189 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using SkiaSharp; +using Svg.Skia; +using Svg.Skia.TypefaceProviders; +using Wasmtime; + +namespace Lite.StateMachine.DotGraph; + +/// Offline Graphviz WASI execution and PNG encoding. No subprocesses or host filesystem imports. +internal static class BundledGraphviz +{ + internal static async Task RenderAsync( + string? dot, + string? inputPath, + string outputPath, + DotGraphFormat format, + TimeSpan timeout, + CancellationToken cancellationToken) + { + using var deadline = new CancellationTokenSource(timeout); + using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, deadline.Token); + var token = cancellation.Token; + var destination = Path.GetFullPath(outputPath); + var directory = Path.GetDirectoryName(destination)!; + + Directory.CreateDirectory(directory); + var temporary = Path.Combine(directory, Path.GetRandomFileName()); + + try + { + dot ??= await File.ReadAllTextAsync(inputPath!, token).ConfigureAwait(false); + var source = dot; + + await Task.Run( + () => + { + var svg = RenderSvg(source, token); + token.ThrowIfCancellationRequested(); + + if (format == DotGraphFormat.Svg) + File.WriteAllBytes(temporary, svg); + else + WritePng(svg, temporary, token); + }, + token).ConfigureAwait(false); + + token.ThrowIfCancellationRequested(); + File.Move(temporary, destination, overwrite: true); + } + catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested && deadline.IsCancellationRequested) + { + throw new TimeoutException($"Graphviz rendering exceeded {timeout}.", ex); + } + finally + { + File.Delete(temporary); + } + } + + private static Stream OpenAsset(string name) => + typeof(BundledGraphviz).Assembly.GetManifestResourceStream("Lite.StateMachine.DotGraph." + name) + ?? throw new InvalidOperationException("Bundled rendering asset is missing: " + name); + + private static byte[] RenderSvg(string dot, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + + // Each invocation owns its engine/store. Cancellation cannot interrupt another render. + using var configuration = new Config().WithEpochInterruption(true); + using var engine = new Engine(configuration); + using var binary = OpenAsset("graphviz.wasm"); + using var module = Module.FromStream(engine, "bundled-graphviz", binary); + + cancellationToken.ThrowIfCancellationRequested(); + + using var store = new Store(engine); + + store.SetLimits(memorySize: 256 * 1024 * 1024); + store.SetEpochDeadline(1); + store.SetWasiConfiguration(new WasiConfiguration()); + + using var linker = new Linker(engine); + linker.DefineWasi(); + + var instance = linker.Instantiate(store, module); + var memory = instance.GetMemory("memory")!; + var allocate = instance.GetFunction("malloc")!; + var render = instance.GetFunction("graphviz_render")!; + var lastError = instance.GetFunction("graphviz_last_error")!; + + using var registration = cancellationToken.Register(engine.IncrementEpoch); + + try + { + var dotAddress = WriteString(memory, allocate, dot); + var formatAddress = WriteString(memory, allocate, "svg"); + var engineAddress = WriteString(memory, allocate, "dot"); + var lengthAddress = allocate(sizeof(int)); + + if (lengthAddress == 0) + throw new InvalidOperationException("Bundled Graphviz could not allocate memory."); + + var result = render(dotAddress, formatAddress, engineAddress, lengthAddress); + if (result == 0) + { + var errorAddress = lastError(); + var message = memory.GetSpan(errorAddress, 4096); + var end = message.IndexOf((byte)0); + + throw new InvalidOperationException("Graphviz rendering failed: " + Encoding.UTF8.GetString(end < 0 ? message : message[..end])); + } + + cancellationToken.ThrowIfCancellationRequested(); + var length = memory.ReadInt32(lengthAddress); + + if (length <= 0) + throw new InvalidOperationException("Bundled Graphviz produced no image."); + + return memory.GetSpan(result, length).ToArray(); + } + catch (WasmtimeException) when (cancellationToken.IsCancellationRequested) + { + cancellationToken.ThrowIfCancellationRequested(); + throw; + } + } + + private static void WritePng(byte[] data, string path, CancellationToken cancellationToken) + { + using var fontStream = OpenAsset("Tinos-Regular.ttf"); + using var typeface = SKTypeface.FromStream(fontStream); + using var svg = new SKSvg(); + + // A packaged font keeps PNG labels available even in fontless Linux containers. + svg.Settings.TypefaceProviders = [new BundledTypefaceProvider(typeface)]; + + using var stream = new MemoryStream(data, writable: false); + + var picture = svg.Load(stream) ?? throw new InvalidOperationException("Could not rasterize Graphviz SVG."); + var bounds = picture.CullRect; + var width = checked((int)Math.Ceiling(bounds.Width)); + var height = checked((int)Math.Ceiling(bounds.Height)); + + if (width <= 0 || height <= 0 || (long)width * height > 32_000_000) + throw new InvalidOperationException("PNG output must be between 1 and 32 million pixels. Use SVG for larger diagrams."); + + cancellationToken.ThrowIfCancellationRequested(); + + using var surface = SKSurface.Create(new SKImageInfo(width, height)) + ?? throw new InvalidOperationException("Could not allocate the PNG canvas."); + + surface.Canvas.Clear(SKColors.Transparent); + surface.Canvas.Translate(-bounds.Left, -bounds.Top); + surface.Canvas.DrawPicture(picture); + cancellationToken.ThrowIfCancellationRequested(); + + using var image = surface.Snapshot(); + using var png = image.Encode(SKEncodedImageFormat.Png, 100) + ?? throw new InvalidOperationException("Could not encode the PNG image."); + + using var output = File.Create(path); + png.SaveTo(output); + } + + private static int WriteString(Memory memory, Func allocate, string text) + { + var data = Encoding.UTF8.GetBytes(text + '\0'); + var address = allocate(data.Length); + + if (address == 0) + throw new InvalidOperationException("Bundled Graphviz could not allocate memory."); + + data.AsSpan().CopyTo(memory.GetSpan(address, data.Length)); + return address; + } + + private sealed class BundledTypefaceProvider(SKTypeface typeface) : ITypefaceProvider + { + public SKTypeface FromFamilyName(string fontFamily, SKFontStyleWeight fontWeight, SKFontStyleWidth fontWidth, SKFontStyleSlant fontStyle) => + typeface; + } +} diff --git a/source/Lite.StateMachine.DotGraph/GraphvizRenderer.cs b/source/Lite.StateMachine.DotGraph/GraphvizRenderer.cs index 6a3f08c..fde42da 100644 --- a/source/Lite.StateMachine.DotGraph/GraphvizRenderer.cs +++ b/source/Lite.StateMachine.DotGraph/GraphvizRenderer.cs @@ -11,20 +11,23 @@ namespace Lite.StateMachine.DotGraph; -/// Renders DOT using a separately installed or application-supplied Graphviz executable. +/// Renders DOT using bundled Graphviz, or an explicitly supplied executable. public sealed class GraphvizRenderer : IDotGraphRenderer { - private readonly string _executablePath; + private readonly string? _executablePath; private readonly TimeSpan _timeout; /// Initializes a new instance of the class. - /// Graphviz dot executable path, or "dot" to search PATH. + /// Null uses bundled Graphviz. Supply a path or "dot" to opt into an external executable. /// Maximum rendering duration. Defaults to 30 seconds. - public GraphvizRenderer(string executablePath = "dot", TimeSpan? timeout = null) + public GraphvizRenderer(string? executablePath = null, TimeSpan? timeout = null) { - ArgumentException.ThrowIfNullOrWhiteSpace(executablePath); + if (executablePath is not null) + ArgumentException.ThrowIfNullOrWhiteSpace(executablePath); + _executablePath = executablePath; _timeout = timeout ?? TimeSpan.FromSeconds(30); + if (_timeout <= TimeSpan.Zero || _timeout.TotalMilliseconds > uint.MaxValue - 1) throw new ArgumentOutOfRangeException(nameof(timeout)); } @@ -61,8 +64,15 @@ private async Task RenderCoreAsync(string? dot, string? inputPath, string output DotGraphFormat.Png => "png", _ => throw new ArgumentOutOfRangeException(nameof(format)), }; + cancellationToken.ThrowIfCancellationRequested(); + if (_executablePath is null) + { + await BundledGraphviz.RenderAsync(dot, inputPath, outputPath, format, _timeout, cancellationToken).ConfigureAwait(false); + return; + } + var fullOutputPath = Path.GetFullPath(outputPath); var outputDirectory = Path.GetDirectoryName(fullOutputPath)!; diff --git a/source/Lite.StateMachine.DotGraph/Lite.StateMachine.DotGraph.csproj b/source/Lite.StateMachine.DotGraph/Lite.StateMachine.DotGraph.csproj index 3888ec9..b28f77c 100644 --- a/source/Lite.StateMachine.DotGraph/Lite.StateMachine.DotGraph.csproj +++ b/source/Lite.StateMachine.DotGraph/Lite.StateMachine.DotGraph.csproj @@ -1,7 +1,7 @@ Lite State Machine DOT Graph Rendering - Optional cross-platform Graphviz wrapper for rendering DOT text and files as SVG or PNG. Requires a Graphviz executable; independent of Lite.StateMachine. + Offline DOT to SVG and PNG rendering with bundled Graphviz. No Graphviz installation required; independent of Lite.StateMachine. $(AssemblyVersion) true true @@ -13,9 +13,26 @@ true snupkg true + $([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)../../output/dependencies/graphviz')) + pwsh + + + + + + + + + + + + <_GraphvizVerifyOnly Condition="'$(GraphvizAssetsOffline)' == 'true'">-VerifyOnly + + + diff --git a/source/Lite.StateMachine.DotGraph/readme.md b/source/Lite.StateMachine.DotGraph/readme.md index a82f45f..1f6b759 100644 --- a/source/Lite.StateMachine.DotGraph/readme.md +++ b/source/Lite.StateMachine.DotGraph/readme.md @@ -6,18 +6,22 @@ is unchanged and does not depend on this renderer. ## Requirements -.NET 10 or 11 and a separately installed or application-supplied -[Graphviz](https://graphviz.org/download/) `dot` executable. The wrapper uses portable -.NET process APIs and is intended for Windows, Linux, and macOS desktop/server apps. -It does not bundle native binaries, install software, or download anything at runtime. -It is not a browser or mobile rendering backend. +.NET 10 or 11. Restore the NuGet package and run: **no Graphviz installation, +PATH setup, executable path, or first-run download is required.** + +The assembly embeds the locked Graphviz version compiled to WebAssembly/WASI. Wasmtime executes +it in-process; Svg.Skia/SkiaSharp encode its SVG output as PNG, using an embedded +Tinos font. Runtime libraries are delivered as ordinary transitive NuGet assets. +Windows, macOS, and glibc-based Linux have x64 and ARM64 assets and CI coverage. +Linux musl/Alpine, browser/mobile hosts, and NativeAOT are not supported by this backend. +The core state-machine package retains its existing dependencies and AOT behavior. ## Usage ```csharp using Lite.StateMachine.DotGraph; -IDotGraphRenderer renderer = new GraphvizRenderer(); // dot on PATH +IDotGraphRenderer renderer = new GraphvizRenderer(); // bundled, offline renderer // With Lite.StateMachine, pass machine.ExportUml() as the DOT text. await renderer.RenderAsync(machine.ExportUml(), "images/machine.svg"); @@ -26,22 +30,73 @@ await renderer.RenderAsync(machine.ExportUml(), "images/machine.png", DotGraphFo // Or render an existing DOT file from any source. await renderer.RenderFileAsync("machine.dot", "images/machine.svg"); -// Optional application-supplied executable and timeout. +// Optional timeout, still using the bundled renderer. +renderer = new GraphvizRenderer(timeout: TimeSpan.FromMinutes(1)); + +// Explicit opt-in to an externally installed/application-supplied Graphviz instead. renderer = new GraphvizRenderer("/opt/graphviz/bin/dot", TimeSpan.FromMinutes(1)); await renderer.RenderFileAsync("machine.dot", "machine.png", DotGraphFormat.Png, cancellationToken); ``` Output defaults to SVG; the format argument controls encoding rather than the file extension. Parent directories are created automatically. Existing destinations are -replaced only after a successful render. Rendering errors include Graphviz's exit -code and diagnostics. Cancellation or the default 30-second timeout terminates the -Graphviz process and removes temporary output. Input DOT files are never modified. -Relative image references in DOT resolve from the application's working directory. +replaced only after a successful render. Errors include Graphviz diagnostics. +Cancellation or the default 30-second timeout interrupts WASM layout and removes +temporary output. Initial module compilation and native PNG encoding finish before +cancellation is observed. Input DOT files are never modified. Concurrent renders +use isolated engines so cancellation cannot interrupt another request. + +The bundled build includes core rendering and layout plugins. It does not load +host files, external images, or additional Graphviz plugins, and HTML-like labels +requiring Expat are unsupported. PNG output uses the bundled regular font as a +fallback for requested families/styles and is limited to 32 million pixels; WASM +memory is limited to 256 MiB per render. For additional Graphviz plugins, image +assets, or system-font fidelity, explicitly supply your own Graphviz executable. +That override uses the original process-based renderer, including its exit-code +diagnostics and relative-image resolution from the application's working directory. + +The bundled binaries, source/build URLs, SHA-256 hashes, and licenses are recorded +in [Assets/graphviz-assets.json](Assets/graphviz-assets.json), with a generated +summary in [Assets/SOURCES.txt](Assets/SOURCES.txt). License notices and the manifest +are packed under `licenses/` in the NuGet package. Binary assets are downloaded to +an ignored build cache and embedded at compile time. The published renderer itself +contains no downloader or installer. + +## Restore and upgrade build artifacts + +Source builds require PowerShell 7 (`pwsh`). From the repository root: + +```powershell +# Restore the exact locked WASM and font; cached valid files need no network. +./ud.ps1 + +# Verify the cache and tracked notices without downloading or changing anything. +./ud.ps1 -VerifyOnly -`IDotGraphRenderer` keeps consumers independent of executable deployment, leaving -room for a future backend with bundled or embedded rendering. Cross-platform -deployment today still requires compatible Graphviz binaries and their dependencies -on each target OS/architecture. +# Preview the latest stable WASI release, then explicitly choose to upgrade. +./ud.ps1 -Latest -WhatIf +./ud.ps1 -Latest + +# Or choose a specific WASI release tag (not an upstream Graphviz version). +./scripts/Update-Graphviz.ps1 -ReleaseTag v0.1.5 +``` + +`ud.ps1` delegates to `scripts/Update-Graphviz.ps1`. The manifest is the source of +truth for versions, URLs, SHA-256 hashes, and notice files. `-Latest`/`-ReleaseTag` +use GitHub's published asset digest; when one is unavailable, supply a reviewed +64-digit `-Sha256` explicitly. Failed downloads/checksums leave existing artifacts +and the manifest intact. Upgrades refresh Graphviz notices and the source summary; +they do not change the pinned font or NuGet package versions. Review the resulting +text diffs and run the rendering/package tests before releasing. + +WASM and font downloads live in `output/dependencies/graphviz/` and are ignored by +Git. Commit the scripts, manifest, notices, and source record, not the cache. Normal +builds/packing automatically restore and verify locked assets; they never select +the latest release implicitly. `dotnet build -p:GraphvizAssetsOffline=true` permits +only already-cached verified artifacts. `GraphvizAssetPowerShell` can override the +`pwsh` executable path, and `GraphvizAssetCache` can override the cache directory. +CI restores the same manifest. A normal NuGet consumer needs none of this setup: +the downloaded assets are already embedded in the distributed assembly. Build the NuGet package from the repository root: @@ -63,15 +118,21 @@ Prepare the script's environment: `[System.Environment]::Version`; Windows PowerShell 5.1 cannot load these assemblies. For example, load the `net10.0` renderer with a .NET 10 PowerShell host. Installing a newer .NET SDK does not change the runtime used by an existing PowerShell host. -* Build the renderer separately with - `dotnet build source/Lite.StateMachine.DotGraph -c Release -f net10.0`, or extract - `lib/net10.0/Lite.StateMachine.DotGraph.dll` from its `.nupkg` into a tooling folder. - No package reference is needed in the application project. +* Publish a separate tooling project referencing `Lite.StateMachine.DotGraph` into + a `tooling` folder, keeping its `.deps.json`, managed dependencies, and `runtimes` + folders together. Copying just the renderer DLL is insufficient for the embedded + backend. No package reference is needed in the application project. For example, + from a directory beside your script: + + ```powershell + dotnet new console -f net10.0 -o diagram-tooling + dotnet add diagram-tooling package Lite.StateMachine.DotGraph + dotnet publish diagram-tooling -c Release --self-contained false -o tooling + ``` * Use the application's build/publish output, including its matching `Lite.StateMachine.dll` and other dependencies. Load additional factory dependencies explicitly if needed; applications requiring a custom host or DI container may need that setup in the script too. -* Install Graphviz, or supply the path to an application-managed `dot` executable. Save this example as `Export-StateDiagram.ps1`. Replace the example paths, type, and method with an **existing** API in your application. This example assumes a @@ -87,6 +148,44 @@ $rendererDll = (Resolve-Path "$PSScriptRoot/tooling/Lite.StateMachine.DotGraph.d $applicationDirectory = Split-Path $applicationDll $outputDirectory = Join-Path $PSScriptRoot 'diagrams' +# PowerShell does not automatically use another application's .deps.json. +# C# callbacks also work when native libraries load on background render threads. +Add-Type -TypeDefinition @' +using System; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.Loader; +public static class DiagramToolDependencies +{ + public static void Load(string toolingApplication) + { + var resolver = new AssemblyDependencyResolver(toolingApplication); + AssemblyLoadContext.Default.Resolving += (context, name) => + { + var path = resolver.ResolveAssemblyToPath(name); + return path == null ? null : context.LoadFromAssemblyPath(path); + }; + AssemblyLoadContext.Default.ResolvingUnmanagedDll += (assembly, name) => + { + var path = resolver.ResolveUnmanagedDllToPath(name); + return path == null ? IntPtr.Zero : NativeLibrary.Load(path); + }; + // Resolve these before normal PATH probing can find an incompatible version. + foreach (var name in new[] { "SkiaSharp", "HarfBuzzSharp" }) + { + var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(name)); + NativeLibrary.SetDllImportResolver(assembly, (library, importingAssembly, searchPath) => + { + var path = resolver.ResolveUnmanagedDllToPath(library); + return path == null ? IntPtr.Zero : NativeLibrary.Load(path); + }); + } + } +} +'@ +[DiagramToolDependencies]::Load( + (Resolve-Path "$PSScriptRoot/tooling/diagram-tooling.dll").Path) + # Load the application's version of the core library, then the application. [void][System.Reflection.Assembly]::LoadFrom( (Join-Path $applicationDirectory 'Lite.StateMachine.dll')) @@ -108,8 +207,7 @@ $dot = $machine.ExportUml() # Keep DOT as well as both image formats. No changes to the application project. [void][System.IO.Directory]::CreateDirectory($outputDirectory) [System.IO.File]::WriteAllText((Join-Path $outputDirectory 'machine.dot'), $dot) -$renderer = [Lite.StateMachine.DotGraph.GraphvizRenderer]::new( - 'dot', [TimeSpan]::FromSeconds(30)) # Or an absolute path to dot/dot.exe. +$renderer = [Lite.StateMachine.DotGraph.GraphvizRenderer]::new() $token = [System.Threading.CancellationToken]::None [void]$renderer.RenderAsync($dot, (Join-Path $outputDirectory 'machine.svg'), [Lite.StateMachine.DotGraph.DotGraphFormat]::Svg, $token).GetAwaiter().GetResult() @@ -138,15 +236,17 @@ registered; topology that depends on configuration needs the corresponding setup ## Tests -The test project runs against both target frameworks. Set `GRAPHVIZ_DOT` to `dot` -or an executable's full path to enable the real rendering tests: +The default suite tests the bundled renderer against both target frameworks: ```powershell -$env:GRAPHVIZ_DOT = 'dot' -dotnet test source/Lite.StateMachine.DotGraph.Tests -c Release +dotnet test source/Lite.StateMachine.DotGraph.Tests -c Release --filter 'TestCategory!=ExternalGraphviz' +pwsh -NoProfile -File scripts/Test-DotGraphPackage.ps1 ``` -Without this variable, the integration tests are marked inconclusive; argument -validation and missing-executable tests still run. The DOT rendering CI workflow -installs Graphviz and runs the full suite on Windows, Linux, and macOS. This workflow -also builds the NuGet package without publishing it. +The package smoke test restores a fresh NuGet consumer, publishes its runtime +dependencies, and generates both images with an empty PATH. CI runs the bundled +tests, package smoke test, and console/PowerShell samples on all six OS/CPU pairs +without installing Graphviz. These tests do not publish packages. + +The optional `ExternalGraphviz` test retains coverage for the executable override. +Set `GRAPHVIZ_DOT` to a real executable and omit the filter to include that test. diff --git a/ud.ps1 b/ud.ps1 new file mode 100644 index 0000000..cce8674 --- /dev/null +++ b/ud.ps1 @@ -0,0 +1,29 @@ +<# +.SYNOPSIS +Update Dependencies: restore pinned build artifacts, or explicitly upgrade Graphviz. +.EXAMPLE +./ud.ps1 +.EXAMPLE +./ud.ps1 -Latest -WhatIf +#> +#Requires -Version 7.0 + +[CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Restore')] +param( + [Parameter(Mandatory, ParameterSetName = 'Latest')] + [switch] $Latest, + [Parameter(Mandatory, ParameterSetName = 'Release')] + [ValidatePattern('^v\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$')] + [string] $ReleaseTag, + [Parameter(ParameterSetName = 'Latest')] + [Parameter(ParameterSetName = 'Release')] + [ValidatePattern('^[a-fA-F0-9]{64}$')] + [string] $Sha256, + [Parameter(Mandatory, ParameterSetName = 'Verify')] + [switch] $VerifyOnly, + [Parameter(ParameterSetName = 'Restore')] + [switch] $Force +) + +$ErrorActionPreference = 'Stop' +& (Join-Path $PSScriptRoot 'scripts/Update-Graphviz.ps1') @PSBoundParameters