diff --git a/changelog.d/explorer-csharp-python.md b/changelog.d/explorer-csharp-python.md new file mode 100644 index 0000000000..203a179c20 --- /dev/null +++ b/changelog.d/explorer-csharp-python.md @@ -0,0 +1,13 @@ +- **C# and Python: the model explorer with no Node.** Both ports build the docs view from their + loaded model (`MetaObjects.DocsView` in C#, `metaobjects.docs_view` in Python), byte for byte + what TypeScript builds for every `fixtures/explorer-conformance/` case. A new `docs-site` + generator in each registry (`DocsSiteGenerator` in `codegen/Generators.cs`; `docs-site` in a + Python target's `generators`) writes `explorer.json`, the explorer app, `explorer-model.js` + and `explorer-stamp.js`. Each object lists the files generated for it: this run's (the runner + runs the generator after every other one) and the committed manifest's outside the directories + the run's orphan sweep clears, so `verify --codegen` renders what `gen` wrote. Options name a + `verify --format json` payload and a routes file. The running application can serve the same + view at `{apiPrefix}/_meta/docs`: `MetaEndpoint.MetaDocs(root)` (C#) and `meta_docs(root)` + (Python) build it once and carry its ETag; the host mounts it as it mounts `/_meta`. + C# and Python provenance now names a generator by its registry name (`entity`, + `filter-allowlist`, `routes`), as TypeScript and the JVM do. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index b0c20a007c..6dbf31b04f 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -73,7 +73,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | — | | [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 88 cases (31 core + 10 TypeScript + 9 Java + 12 Kotlin + 6 C# + 12 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | ✓ (core and Kotlin dialect; `KotlinWriter` in `codegen-kotlin`) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 22 cases (17 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | — | -| [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the docs view: a loaded project + the verify payload, manifest and routes in, one `explorer.json` out) | 3 cases (`shop`, `crm`, `model-alone`) | ✓ | ✓ (`DocsView`, and the `docs-site` generator end to end) | ✓ (the JVM builder, through `codegen-kotlin`'s `docs-site`) | — | — | — | +| [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the docs view: a loaded project + the verify payload, manifest and routes in, one `explorer.json` out) | 3 cases (`shop`, `crm`, `model-alone`) | ✓ | ✓ (`DocsView`, and the `docs-site` generator end to end) | ✓ (the JVM builder, through `codegen-kotlin`'s `docs-site`) | ✓ (`MetaObjects.DocsView`, and the `docs-site` generator end to end) | ✓ (`metaobjects.docs_view`, and the `docs-site` generator end to end) | — | **Rust (ADR-0065)** joined the table with its service stack. Its ledgers (the metamodel corpus's `server/rust/metaobjects/tests/conformance-expected-failures.json`, empty; the YAML @@ -915,6 +915,8 @@ its `expected.json` is the body the running application's `GET {apiPrefix}/_meta Java (`metadata`'s `DocsViewConformanceTest`, and `codegen-base`'s `ExplorerSiteTest` through the generator) and Kotlin (`KotlinDocsSiteConformanceTest`, through its registry's `docs-site`) build every case byte for byte; the JVM has one builder, which Kotlin calls rather than re-implements. +C# (`MetaObjects.DocsView`, through `DocsSiteGenerator` and `MetaEndpoint.MetaDocs`) and Python +(`metaobjects.docs_view`, through `docs-site` and `meta_docs`) build every case byte for byte too. **TypeScript runs it** in `server/typescript/packages/metadata/test/docs-view-conformance.test.ts` (the view) and diff --git a/docs/features/docs-view.md b/docs/features/docs-view.md index dde6a53ae1..da537cdffb 100644 --- a/docs/features/docs-view.md +++ b/docs/features/docs-view.md @@ -13,11 +13,12 @@ writes the same bytes for the same model, and the shared corpus [`fixtures/explorer-conformance/`](../../fixtures/explorer-conformance/) holds them to that. TypeScript builds it today, and so do Java and Kotlin (one JVM builder, `DocsView` in -`metadata`). `buildDocsView` and `serializeDocsView` are exported from `@metaobjectsdev/metadata`, -and `docsSiteFile()` writes the result as the site's `explorer.json` (see -[explorer-site.md](explorer-site.md)). C#, Python and Rust will build it as their own step of the same -plan ([explorer-data.md](explorer-data.md#not-built-yet)). The explorer pages still render their -HTML in TypeScript; the JVM copies the app and writes the same `explorer.json`. +`metadata`), C# (`MetaObjects.DocsView`) and Python (`metaobjects.docs_view`). `buildDocsView` and +`serializeDocsView` are exported from `@metaobjectsdev/metadata`, and `docsSiteFile()` writes the +result as the site's `explorer.json` (see [explorer-site.md](explorer-site.md)). Rust will build +it as its own step of the same plan ([explorer-data.md](explorer-data.md#not-built-yet)). The +explorer pages still render their HTML in TypeScript; the JVM, C# and Python copy the app and +write the same `explorer.json`. A page of your own is a template over the view: the TypeScript `template` generator renders it with the `perNode` and `perRequirement` scopes (and `data: "docsView"` on `perModel` and diff --git a/docs/features/explorer-data.md b/docs/features/explorer-data.md index a653375d57..9e0d247e5f 100644 --- a/docs/features/explorer-data.md +++ b/docs/features/explorer-data.md @@ -116,7 +116,8 @@ A file rendered from the whole model or a whole package keeps the plain `" form, so a project that writes only such files has an unchanged manifest. Every port's manifest reader takes `hash` from either form. -The provenance field is named `generatedBy`, not `generator`. In a Java or Kotlin module's +`generatedBy` is the generator's registry name (`entity`, `filter-allowlist`), the name +`gen --list` shows, in every port. The provenance field is named `generatedBy`, not `generator`. In a Java or Kotlin module's manifest, `generator` means that generator owns the file (ADR-0060), and the orphan sweep acts on that ownership, so a JVM entry carries both: `{ "hash", "generator", "outputDir", "generatedBy", "sourceNode" }`. The four ports that write provenance write the same entry for the @@ -158,8 +159,8 @@ malformed leaves its part of the view empty. optional, and nothing builds it yet. - **Provenance from the Kotlin and Rust generators.** Their manifest entries have no `sourceNode` yet, so for those ports a node lists no files. -- **The docs view in C#, Python and Rust.** TypeScript, Java and Kotlin build it today; the - corpus is what the other ports will be held to. +- **The docs view in Rust.** TypeScript, Java, Kotlin, C# and Python build it today, each held + to the corpus byte for byte; Rust will be held to the same corpus. ## Verified by diff --git a/docs/features/explorer-site.md b/docs/features/explorer-site.md index 48c4990f82..da2f96ce1a 100644 --- a/docs/features/explorer-site.md +++ b/docs/features/explorer-site.md @@ -73,7 +73,9 @@ same model and inputs: every port that builds the docs view is held to | TypeScript | `docsSiteFile()` (`meta gen`) | `output: "app"` (default) or `"static"`; `site: "classic"` for the earlier site | The model, the requirement ledger, the files and routes this run wrote and mounts | | Java | `com.metaobjects.generator.DocsSiteGenerator` (`mvn metaobjects:generate`), no Node | The app only | The model, the files generated per node (this execution's, and what the committed hash manifest records for the module's other executions), and a `verify --format json` payload when you name one (`verifyFile`) | | Kotlin | the same JVM `DocsSiteGenerator`, through `codegen-kotlin`'s registry | The app only | As Java; the Kotlin generators do not record provenance in the manifest yet, so their files are not listed | -| C#, Python, Rust | not yet | | | +| C# | `docs-site` (`dotnet meta gen`, `MetaObjects.Codegen.Generators.DocsSiteGenerator`), no Node | The app only | The model, the files generated per node (this run's, and what the committed hash manifest records outside the directories the run's orphan sweep clears), and a `verify --format json` payload (`VerifyFile`) and a routes file (`RoutesFile`) when you name them | +| Python | `docs-site` (`metaobjects gen`, `metaobjects.codegen.generators.docs_site_generator`), no Node | The app only | As C# (`verify_file`, `routes_file`) | +| Rust | not yet | | | On the JVM, wire it like any other generator, with its own output directory: @@ -297,11 +299,9 @@ a dangling link. `createExplorer` (the page table both outputs draw from) and - An LLM-written summary, a test-result overlay, zoom levels and lenses on the map, and publishing the site. -- The docs view route in C#, Python and Rust: the contract is in - [metadata-api.md](metadata-api.md#the-docs-view-endpoint-get-_metadocs), and each port serves - it once it has its docs view builder. Java and Kotlin ship it (`MetaEndpoint.docs(root)`). -- The app in C#, Python and Rust: its files are in each port's package already (see - `explorer-app/README.md`), and each port's docs-site generator is still to write them. +- The docs view route and the app in Rust: the contract is in + [metadata-api.md](metadata-api.md#the-docs-view-endpoint-get-_metadocs). Java, Kotlin, C# + and Python ship both. - The static export and the classic site outside TypeScript. - "Hand-written code that imports it": the site reads no import graph, so the object pages say it was not scanned. diff --git a/docs/features/metadata-api.md b/docs/features/metadata-api.md index fd4d35ca69..ea0617de68 100644 --- a/docs/features/metadata-api.md +++ b/docs/features/metadata-api.md @@ -258,8 +258,12 @@ Kotlin calls the same symbols through `metadata-ktx`. To let the explorer read t `file://`, add `Access-Control-Allow-Origin: null` and `Access-Control-Expose-Headers: ETag` to that response, or use Spring's CORS configuration. -C#, Python and Rust serve the route once each has its docs view builder, with the -body that builder writes; their `/_meta` sections above show where each mounts it. +C# and Python ship the same helper beside their `/_meta` one, and like it, mount it yourself +under the same guard. C#: `MetaEndpoint.MetaDocs(root)` gives the body, `ETag` and +`Matches(ifNoneMatch)` (`MetaEndpoint.MetaDocsRoutePath`, `MetaDocsJson(root, routes)`). +Python: `meta_docs(root)` gives `body`, `etag` and `matches(if_none_match)` +(`META_DOCS_ROUTE_PATH`, `meta_docs_json(root, routes)`). Each helper's doc comment shows the +ASP.NET or FastAPI mount. Rust serves the route once it has its docs view builder. ## Browser consumption diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index f0546ce187..85ffaded4c 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -1290,6 +1290,8 @@ generated code), and no `migrate` surface (EF Core Migrations, or the Node `meta | Migrations | EF Core Migrations is the native path; the Node `meta migrate` is the reference helper, one option (ADR-0015 Amendments 1 and 2) — no C# migrate surface | | Drift verify | `dotnet meta verify` (template drift, FR-004; `--codegen` regenerates the list in `codegen/Generators.cs` and diffs it) | | API reference docs | Yes — the `ApiDocsGenerator` entry in `codegen/Generators.cs` (`OutDir`, `ApiSubDir`, `ProjectName`, `ModelBaseUrl`); `dotnet meta docs` was removed in 1.1.0 ([migration](../features/migrations/docs-are-generators.md#c)) | +| Model explorer | Yes, with no Node — a `DocsSiteGenerator` entry in `codegen/Generators.cs` (registry name `docs-site`): under `/` (default `site`) it writes the explorer app (`index.html` and `assets/`, the same bytes in every port, embedded in `MetaObjects.Codegen`), `explorer.json` (the docs view, built from the loaded model by `MetaObjects.DocsView`; byte-identical to TypeScript's for the same inputs, gated by `fixtures/explorer-conformance/`), `explorer-model.js` and `explorer-stamp.js`. Each object lists the files generated for it, recorded under each generator's registry name: this run's, laid over what the committed hash manifest records outside the directories the run's orphan sweep clears, so it never lists a file the run deletes. The runner runs it after every other entry, so `gen` and `verify --codegen` list the same files. Options: `SubDir`, `Title` (default: the project directory's name), `Stamp` (footer text), `Prompts` (a directory of prompt `.mustache` sources beside the metadata and `templates/`), `VerifyFile` (a `verify --format json` payload from the Node CLI, for the requirement verdicts), `RoutesFile` (`[{ node, method, path }]`, `node` a resolution key). An owned theme under `codegen/docs-site/` (`assets/explorer.css`, `assets/explorer.js`, `templates/explorer-*.mustache`) wins over the embedded one. Not ejectable: the builder is engine, the theme is what you own. The page-per-screen static export and the classic site stay TypeScript's | +| Docs view endpoint | `MetaEndpoint.MetaDocsRoutePath` (`/_meta/docs`), `MetaDocsJson(root, routes)` and `MetaDocs(root, routes)` (like `/_meta`, a helper you mount, not a mount): the body is the docs view of the loaded model alone, byte-identical to every other port's (`fixtures/explorer-conformance/model-alone/`); `MetaDocs` builds it once with a strong `ETag` and `Matches(ifNoneMatch)` for the `304`. Contract: [metadata-api.md](../features/metadata-api.md#the-docs-view-endpoint-get-_metadocs) | | Requirement gate + requirement tests | Yes (`dotnet meta verify`, on every run; `requirement-tests` emits xUnit and is ejectable) | | Business-rules gate (ADR-0066, experimental) | Yes (`dotnet meta verify`, on every run; see [business rules](../features/business-rules.md)) | | Runtime metadata | Loader API + render engine; ObjectManager-style runtime tier on the roadmap | diff --git a/docs/ports/python.md b/docs/ports/python.md index ede38a0985..1400063391 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -1088,6 +1088,8 @@ definitions, and import lines are stable. | API reference docs | Yes — `api-docs` in a target's `generators`, options in the top-level `apiDocs` block (`apiSubDir`, `projectName`, `modelBaseUrl`); `metaobjects docs` was removed in 1.1.0 ([migration](../features/migrations/docs-are-generators.md#python)) | | Requirements and agent pages | Yes — `requirements` (`requirements.md`, `requirements.toon`) and `agent-docs` (`agent/requirements.md` and the model-only `agent/schema.md`: no SQL types, defaults, indexes or checks; `agent/ui.md` is TypeScript-only) in a target's `generators`, rendered from the shared templates bundled in the package; a same-named file under the project's templates directory overrides a page; both ejectable | | Metamodel reference | Yes — `metamodel-docs` in a target's `generators` (`INDEX.md`, `providers.md` and `types/.md` under `metamodel/`; option `subDir`), rendered from the shared templates bundled in the package over the port's own registry manifest and embedded provider definitions; reads no model objects; a same-named file under the project's templates directory overrides a page; ejectable | +| Model explorer | Yes, with no Node — `docs-site` in a target's `generators`: under `/` (default `site`) it writes the explorer app (`index.html` and `assets/`, the same bytes in every port, shipped as package data), `explorer.json` (the docs view, built from the model the run loaded by `metaobjects.docs_view.build_docs_view`; byte-identical to TypeScript's for the same inputs, gated by `fixtures/explorer-conformance/`), `explorer-model.js` and `explorer-stamp.js`. Each object lists the files generated for it (`generatedBy`, `sourceNode`): the run's own, laid over what the committed hash manifest records. The runner runs it after every other generator, so a write run and `verify --codegen` list the same files. Options: `subDir`, `title` (default: the project directory's name), `stamp` (footer text, default none), `prompts` (a directory of prompt `.mustache` sources beside the metadata and `templates/`), `verifyFile` (a `verify --format json` payload from the Node CLI, for the requirement verdicts), `routesFile` (the routes the application mounts, `[{ node, method, path }]`, `node` a resolution key). An owned theme under `codegen/docs-site/` (`assets/explorer.css`, `assets/explorer.js`, `templates/explorer-*.mustache`) wins over the packaged one. Not ejectable: the builder is engine, the theme is what you own. The page-per-screen static export and the classic site stay TypeScript's | +| Docs view endpoint | `META_DOCS_ROUTE_PATH` (`/_meta/docs`), `meta_docs_json(root, routes=None)` and `meta_docs(root, routes=None)` in `metaobjects` (like `/_meta`, a framework-free helper, not a mount): the body is the docs view of the loaded model alone, byte-identical to every other port's (`fixtures/explorer-conformance/model-alone/`); `meta_docs` builds it once with a strong `ETag` and `matches(if_none_match)` for the `304`. Contract: [metadata-api.md](../features/metadata-api.md#the-docs-view-endpoint-get-_metadocs) | | Requirement gate + requirement tests | Yes (`metaobjects verify`, on every run; `requirement-tests` emits pytest and is ejectable) | | Business-rules gate (ADR-0066, experimental) | Yes (`metaobjects verify`, on every run; see [business rules](../features/business-rules.md)) | | Runtime metadata | Yes (`metaobjects.runtime.ObjectManagerDb` — DB-API 2 drivers: Postgres via pg8000/psycopg, `SqliteDriver` over the standard library's `sqlite3`, `MySqlDriver` over PyMySQL with the `mysql` extra) + loader API + render engine | diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index a6d513edba..dd2577efa5 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -357,12 +357,12 @@ "concept": "The browsable HTML site of the model: navigation, search, a page per package and per object, ER diagrams.", "tier": "neutral", "layer": "docs", - "note": "It was `meta docs --site` until 1.1.0 (ADR-0034 Amendment 9). Java and Kotlin write the model explorer app over the docs view, with no Node (both run the JVM DocsSiteGenerator); the classic site and the page-per-screen static export stay TypeScript's.", + "note": "It was `meta docs --site` until 1.1.0 (ADR-0034 Amendment 9). C#, Java, Kotlin and Python write the model explorer app over the docs view, with no Node (C# its DocsSiteGenerator, Java and Kotlin the JVM DocsSiteGenerator, Python its docs-site generator); the classic site and the page-per-screen static export stay TypeScript's.", "eject": { "exempt": "The site builder is engine: it assembles the page data the site's templates read, and what an adopter changes is those templates and the assets beside them, which `meta eject docs-site` copies into codegen/docs-site/ and the generator reads from there.", "ruling": "ADR-0034 Amendment 9 (restating Amendment 8, ruling 3)" }, - "ports": ["typescript", "java", "kotlin"] + "ports": ["typescript", "csharp", "java", "kotlin", "python"] }, "plantuml": { "concept": "PlantUML class diagram of the object model.", diff --git a/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs index e332ddc08f..e6a4389706 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs @@ -47,7 +47,7 @@ public void ListHeader_says_generators_are_owned_via_eject() public void ListLines_prints_all_generators_with_stable_names_and_descriptions() { var lines = GenCommand.ListLines(_tmp); - Assert.Equal(19, lines.Count); + Assert.Equal(20, lines.Count); foreach (var name in new[] { "entity", "db-context", "routes", "output-parser", "extractor", @@ -66,6 +66,8 @@ public void ListLines_prints_all_generators_with_stable_names_and_descriptions() // ADR-0025 — the api reference, an ordinary entry since ADR-0034 Amendment 9. "api-docs", "metamodel-docs", + // The model explorer, written with no Node. + "docs-site", // The @expr indexes the EF model cannot carry, as SQL. "expression-indexes", }) diff --git a/server/csharp/MetaObjects.Codegen.Tests/DependencyCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DependencyCodegenTests.cs index 806115e403..ea3e1ad32f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/DependencyCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/DependencyCodegenTests.cs @@ -22,7 +22,10 @@ public sealed class DependencyCodegenTests : IDisposable // shared-model publishes the files its options name and writes no code; a bare fixture names none. // metamodel-docs documents the built-in vocabulary, not the model, so it reads no node at all // (its pages name vocabulary words such as "address" that the imported fixture also uses). - private static readonly string[] Excluded = ["render-helper", "template", "shared-model", "metamodel-docs"]; + // docs-site documents the WHOLE loaded model, imported packages included (the docs view marks + // each node's package; fixtures/explorer-conformance/ pins that), so naming an imported node is + // its contract, not a leak. + private static readonly string[] Excluded = ["render-helper", "template", "shared-model", "metamodel-docs", "docs-site"]; public void Dispose() { try { Directory.Delete(_tmp, recursive: true); } catch { } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/DocsSiteGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DocsSiteGeneratorTests.cs new file mode 100644 index 0000000000..ff42a522b5 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/DocsSiteGeneratorTests.cs @@ -0,0 +1,191 @@ +// docs-site: the model explorer this port writes with no Node. The docs view's bytes are held to +// fixtures/explorer-conformance/ by MetaObjects.Conformance.Tests; these tests hold what the generator +// adds: the shared app's bytes, the run's own files listed in the view (so the generator runs after +// every other entry), the drift gate rendering what gen wrote, the owned theme and templates, the +// prompt-text path rules, and the model script pinned to TypeScript's. + +using System.Security.Cryptography; +using System.Text; +using System.Text.Json.Nodes; +using MetaObjects.Codegen.Docs; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public sealed class DocsSiteGeneratorTests : IDisposable +{ + private readonly string _project = Path.Combine( + Environment.GetEnvironmentVariable("DEV_SCRATCH") is { Length: > 0 } s ? s : Path.GetTempPath(), + "mo-docs-site-" + Guid.NewGuid().ToString("N")); + + public void Dispose() { try { Directory.Delete(_project, recursive: true); } catch { } } + + private static string RepoRoot() + { + for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent) + if (Directory.Exists(Path.Combine(dir.FullName, "fixtures", "explorer-conformance"))) return dir.FullName; + throw new InvalidOperationException("repository root not found"); + } + + /// The shop fixture's project, copied into a scratch directory. + private MetaRoot ShopProject() + { + Copy(Path.Combine(RepoRoot(), "fixtures", "explorer-conformance", "shop", "project"), _project); + var load = MetaDataLoader.FromDirectory(Path.Combine(_project, "metaobjects"), strict: true); + Assert.Empty(load.Errors); + return load.Root; + } + + private static void Copy(string from, string to) + { + Directory.CreateDirectory(to); + foreach (var f in Directory.GetFiles(from)) File.Copy(f, Path.Combine(to, Path.GetFileName(f))); + foreach (var d in Directory.GetDirectories(from)) Copy(d, Path.Combine(to, Path.GetFileName(d))); + } + + private GenConfig Config() => new() + { + OutDir = Path.Combine(_project, "gen"), + ProjectRoot = _project, + GenStateDir = Path.Combine(_project, ".metaobjects", ".gen-state"), + Namespace = "Shop", + }; + + private string Site(string file) => File.ReadAllText(Path.Combine(_project, "gen", "site", file)); + + [Fact] + public void Writes_the_shared_app_and_the_three_data_files() + { + CodegenRunner.Run(Config(), ShopProject(), [new DocsSiteGenerator()]); + var app = Path.Combine(RepoRoot(), "explorer-app"); + foreach (var f in ExplorerSite.AppFiles) + Assert.True(File.ReadAllText(Path.Combine(app, f)) == Site(f), $"{f} differs from explorer-app/"); + var view = (JsonObject)JsonNode.Parse(Site(ExplorerSite.ViewFile))!; + Assert.Equal(DocsView.Format, view["format"]!.GetValue()); + var stamp = Site(ExplorerSite.StampFile); + Assert.Matches("^window\\.MO_STAMP = \"[0-9a-f]{16}\";\n$", stamp); + Assert.StartsWith("window.MO_MODEL = {\"stamp\":" + stamp["window.MO_STAMP = ".Length..^2] + ",\"title\":", + Site(ExplorerSite.ModelFile)); + } + + [Fact] + public void Lists_the_files_the_run_generated_even_when_declared_first() + { + // Declared before the allowlist generator: the runner runs it last, so it sees the allowlist files. + CodegenRunner.Run(Config(), ShopProject(), [new DocsSiteGenerator(), new FilterAllowlistGenerator()]); + var view = (JsonObject)JsonNode.Parse(Site(ExplorerSite.ViewFile))!; + Assert.True(view["sources"]!["files"]!.GetValue()); + var listed = view["nodes"]!.AsArray() + .SelectMany(n => n!["files"]!.AsArray()) + .Where(g => g!["generatedBy"]!.GetValue() == "filter-allowlist") + .SelectMany(g => g!["paths"]!.AsArray().Select(p => p!.GetValue())) + .ToList(); + Assert.NotEmpty(listed); + foreach (var p in listed) + { + Assert.StartsWith("gen/", p); + Assert.True(File.Exists(Path.Combine(_project, p)), $"listed {p}, which the run did not write"); + } + } + + [Fact] + public void The_drift_gate_renders_what_gen_wrote() + { + var root = ShopProject(); + IReadOnlyList suite = [new FilterAllowlistGenerator(), new DocsSiteGenerator()]; + CodegenRunner.Run(Config(), root, suite); + var drift = CodegenDrift.Compute(Config(), root, suite); + Assert.True(drift.Clean, string.Join("\n", drift.Lines)); + } + + [Fact] + public void A_file_the_run_deletes_is_not_listed() + { + // A generator dropped from the list: the run's orphan sweep deletes its files, so the site + // the same run writes must not list them, and the drift gate must render that same site. + var root = ShopProject(); + var config = Config() with { SweepOrphans = true }; + CodegenRunner.Run(config, root, [new EntityGenerator(), new FilterAllowlistGenerator(), new DocsSiteGenerator()]); + Assert.Contains(HashManifest.LoadProvenance(config.GenStateDir!), e => e.Value.GeneratedBy == "filter-allowlist"); + IReadOnlyList suite = [new EntityGenerator(), new DocsSiteGenerator()]; + CodegenRunner.Run(config, root, suite); + var view = (JsonObject)JsonNode.Parse(Site(ExplorerSite.ViewFile))!; + var listed = view["nodes"]!.AsArray() + .SelectMany(n => n!["files"]!.AsArray()) + .SelectMany(g => g!["paths"]!.AsArray().Select(p => p!.GetValue())) + .ToList(); + Assert.NotEmpty(listed); + foreach (var p in listed) Assert.True(File.Exists(Path.Combine(_project, p)), $"listed {p}, which the run deleted"); + var drift = CodegenDrift.Compute(config, root, suite); + Assert.True(drift.Clean, string.Join("\n", drift.Lines)); + } + + [Fact] + public void A_site_generated_alone_lists_no_files_but_knows_the_run() + { + var root = ShopProject(); + var config = Config() with { SweepOrphans = true }; + CodegenRunner.Run(config, root, [new EntityGenerator(), new DocsSiteGenerator()]); + IReadOnlyList suite = [new DocsSiteGenerator()]; + CodegenRunner.Run(config, root, suite); + var view = (JsonObject)JsonNode.Parse(Site(ExplorerSite.ViewFile))!; + // TypeScript's runDocsView: a run always knows its files, so an empty list is still a list. + Assert.True(view["sources"]!["files"]!.GetValue()); + Assert.Empty(view["nodes"]!.AsArray().SelectMany(n => n!["files"]!.AsArray())); + var drift = CodegenDrift.Compute(config, root, suite); + Assert.True(drift.Clean, string.Join("\n", drift.Lines)); + } + + [Fact] + public void An_owned_theme_and_template_replace_the_shipped_ones() + { + var root = ShopProject(); + var owned = Path.Combine(_project, DocsSiteGenerator.OwnedDocsSiteDir); + Directory.CreateDirectory(Path.Combine(owned, "assets")); + Directory.CreateDirectory(Path.Combine(owned, "templates")); + File.WriteAllText(Path.Combine(owned, "assets", "explorer.css"), "/* owned */\n"); + File.WriteAllText(Path.Combine(owned, "templates", "explorer-card.mustache"), "{{name}}"); + CodegenRunner.Run(Config(), root, [new DocsSiteGenerator()]); + Assert.Equal("/* owned */\n", Site("assets/explorer.css")); + Assert.Contains("\"templates\":{\"explorer-card.mustache\":\"{{name}}\"}", Site(ExplorerSite.ModelFile)); + } + + [Fact] + public void A_prompt_text_is_read_only_through_a_safe_reference() + { + var dir = Path.Combine(_project, "prompts"); + Directory.CreateDirectory(Path.Combine(dir, "sub")); + File.WriteAllText(Path.Combine(dir, "sub", "ok.mustache"), "hello"); + File.WriteAllText(Path.Combine(_project, "secret.mustache"), "no"); + JsonObject Node(string id, string textRef) => new() + { + ["id"] = id, + ["attrs"] = new JsonArray(new JsonObject { ["name"] = "textRef", ["value"] = textRef }), + }; + var view = new JsonObject + { + ["nodes"] = new JsonArray(Node("a", "sub/ok"), Node("b", "../secret"), Node("c", "sub//ok"), Node("d", "/etc/passwd")), + }; + var texts = ExplorerSite.ReadPromptTexts(view, [dir]); + Assert.Equal(["a"], texts.Keys.ToList()); + Assert.Equal("hello", texts["a"]); + } + + [Fact] + public void The_model_script_matches_TypeScript() + { + // Pinned from TypeScript's explorerModelScript over the model-alone fixture's view, with + // title "T \u2028", footer "f" and texts { b: "2", a: "1" } (keys written sorted). + var view = (JsonObject)JsonNode.Parse(File.ReadAllText( + Path.Combine(RepoRoot(), "fixtures", "explorer-conformance", "model-alone", "expected.json")))!; + var m = ExplorerModelScript.Of("T \u2028", "f", new Dictionary { ["b"] = "2", ["a"] = "1" }, null, view); + Assert.Equal("8ae24964eac47e67", m.Stamp); + Assert.Equal(10014, m.Script.Length); + Assert.Equal("3ae42a3977b053c76481fd1d5e7ca83f5f84fc1902608dbaec21bfe2cdc3019e", + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(m.Script))).ToLowerInvariant()); + Assert.Equal("window.MO_STAMP = \"8ae24964eac47e67\";\n", ExplorerModelScript.StampScript(m.Stamp)); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs index 2788d7b726..d24c802eea 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs @@ -94,6 +94,7 @@ public class EjectedGeneratorsAloneTests internal static readonly IReadOnlyDictionary NotEjectable = new Dictionary(StringComparer.Ordinal) { ["template"] = "the Mustache primitive has no emit logic of its own to own (ADR-0034 Amendment 3, ruled again for 1.1.0)", + ["docs-site"] = "the site builder is engine: a project owns the explorer's theme and page templates under codegen/docs-site/, which the generator reads (ADR-0034 Amendment 9, restating Amendment 8, ruling 3)", }; // The SDK generates these for every project that sets enable, which the diff --git a/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs index 5d2d1426b6..f0e87c32f2 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs @@ -20,6 +20,8 @@ public sealed class GeneratorRegistryTests "output-prompt", "render-helper", "filter-allowlist", "template", // FR-015 — per-entity callable wrapper (storedProc / tableFunction). "callable", + // The model explorer over the docs view, written with no Node. + "docs-site", // Program A / §A5 — per-object physical database name constants. "names", "rules-names", diff --git a/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs b/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs index 3e311abf92..1bf10f59ff 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs @@ -167,7 +167,7 @@ public void The_real_entity_generator_stamps_its_entity_file_with_provenance() using var shop = JsonDocument.Parse(File.ReadAllText(Path.Combine(HashesDir, "acme.shop.json"))); var entry = shop.RootElement.EnumerateObject().Single(p => p.Name.EndsWith("Order.g.cs")).Value; Assert.Equal(JsonValueKind.Object, entry.ValueKind); - Assert.Equal("entity-generator", entry.GetProperty("generatedBy").GetString()); + Assert.Equal("entity", entry.GetProperty("generatedBy").GetString()); Assert.Equal("acme::shop::Order", entry.GetProperty("sourceNode").GetString()); Assert.True(entry.TryGetProperty("hash", out _)); } @@ -213,14 +213,14 @@ public void The_names_filter_allowlist_and_routes_generators_stamp_each_object_f : "(plain)"); Assert.Equal(new Dictionary { - ["gen/AuthFilterAllowlist.g.cs"] = "filter-allowlist-generator acme::shop::Auth", + ["gen/AuthFilterAllowlist.g.cs"] = "filter-allowlist acme::shop::Auth", ["gen/AuthNames.g.cs"] = "names acme::shop::Auth", - ["gen/AuthRoutes.g.cs"] = "routes-generator acme::shop::Auth", - ["gen/BridgeAuthFilterAllowlist.g.cs"] = "filter-allowlist-generator acme::shop::BridgeAuth", + ["gen/AuthRoutes.g.cs"] = "routes acme::shop::Auth", + ["gen/BridgeAuthFilterAllowlist.g.cs"] = "filter-allowlist acme::shop::BridgeAuth", ["gen/BridgeAuthNames.g.cs"] = "names acme::shop::BridgeAuth", - ["gen/OrderFilterAllowlist.g.cs"] = "filter-allowlist-generator acme::shop::Order", + ["gen/OrderFilterAllowlist.g.cs"] = "filter-allowlist acme::shop::Order", ["gen/OrderNames.g.cs"] = "names acme::shop::Order", - ["gen/OrderRoutes.g.cs"] = "routes-generator acme::shop::Order", + ["gen/OrderRoutes.g.cs"] = "routes acme::shop::Order", ["gen/StampedNames.g.cs"] = "names acme::shop::Stamped", }, stamped); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs index 93c885b6b1..fa6e6ba675 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs @@ -396,10 +396,12 @@ private static readonly (string Literal, string ShouldUse, Reach Reach, string W /// says what replaces it: the whole registry, so a NEW generator is covered the day it /// is registered instead of the day someone remembers this list. /// render-helper needs a --template-root and template is a - /// primitive with no default walk; neither can emit here. + /// primitive with no default walk; neither can emit here. docs-site writes the model + /// explorer's data, which shows each field's physical column as documentation: it is data the + /// page displays, not code that could reference a constant. /// private static readonly IReadOnlyList GeneratorNames = - [.. GeneratorRegistry.Entries.Keys.Where(n => n is not ("render-helper" or "template" or "shared-model"))]; + [.. GeneratorRegistry.Entries.Keys.Where(n => n is not ("render-helper" or "template" or "shared-model" or "docs-site"))]; /// Run the generator suite over the fixture. private static IReadOnlyList Generate() diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs index f5b52d7cca..da7a9a1cb5 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs @@ -85,7 +85,7 @@ private static IGenerator Build(GeneratorRegistryEntry entry) => public static TheoryData GeneratorNames() { var data = new TheoryData(); - foreach (var name in GeneratorRegistry.Entries.Keys.Where(n => n != SharedModelTestSupport.Name)) data.Add(name); + foreach (var name in GeneratorRegistry.Entries.Keys.Where(n => n != SharedModelTestSupport.Name && n != "docs-site")) data.Add(name); return data; } @@ -325,8 +325,9 @@ public void Exactly_these_generators_cannot_run_from_a_bare_model() [Fact] public void Every_runnable_generator_in_one_run_emits_the_same_files() { + // docs-site is held by Docs_site_changes_only_its_data_files_for_a_report below. var runnable = GeneratorRegistry.Entries - .Where(e => !Emit(Load("without"), [Build(e.Value)]).ContainsKey("")) + .Where(e => e.Key != "docs-site" && !Emit(Load("without"), [Build(e.Value)]).ContainsKey("")) .ToList(); var generators = runnable.Select(e => Build(e.Value)).ToList(); var expected = Emit(Load("without"), generators); @@ -337,10 +338,29 @@ public void Every_runnable_generator_in_one_run_emits_the_same_files() AssertSameExceptTheReportRow(expected, actual, runnable.Select(e => e.Key).ToList()); } + /// + /// docs-site documents every node the model declares, a report included, by design; the report + /// reaches only its data files (the docs view, the model script and the stamp), never the app. + /// + [Fact] + public void Docs_site_changes_only_its_data_files_for_a_report() + { + var entry = GeneratorRegistry.Get("docs-site")!; + var expected = Emit(Load("without"), [Build(entry)]); + var actual = Emit(Load("with"), [Build(entry)]); + Assert.False(actual.ContainsKey(""), actual.GetValueOrDefault("")); + Assert.Equal(expected.Keys.ToList(), actual.Keys.ToList()); + var changed = expected.Keys.Where(k => expected[k] != actual[k]).Select(k => k.Replace('\\', '/')).ToList(); + Assert.Equal(["site/explorer-model.js", "site/explorer-stamp.js", "site/explorer.json"], changed); + } + [Fact] public void A_report_reaches_no_tier_but_its_row_its_mapping_its_allowlist_and_its_routes() { - var files = Emit(Load("with"), GeneratorRegistry.Entries.Values.Where(e => e.Name != SharedModelTestSupport.Name).Select(Build).ToList()); + // docs-site documents every node the model declares, a report included, by design: it is held + // to the docs view corpus (fixtures/explorer-conformance/) instead. + var files = Emit(Load("with"), GeneratorRegistry.Entries.Values + .Where(e => e.Name != SharedModelTestSupport.Name && e.Name != "docs-site").Select(Build).ToList()); Assert.False(files.ContainsKey(""), files.GetValueOrDefault("")); // The view-backed report: its row, its allowlist and its routes file; nothing in the diff --git a/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs b/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs index fc4e23e6ff..66f183696b 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs @@ -67,9 +67,11 @@ private static SortedDictionary Emit(MetaRoot root, IReadOnlyLis /// /// The layer generators (ADR-0067 §5.2). They act on the rules vocabulary by design, so they are not held /// to identical output; the flat generators they sit beside are, and that is what this test guards. + /// docs-site is here for the same reason: the model explorer documents every node, the rules + /// vocabulary's included (its view is pinned by fixtures/explorer-conformance/). /// Pinned by name so a flat generator cannot be excused by being added here. /// - private static readonly HashSet LayerGenerators = new(StringComparer.Ordinal) { "rules-names" }; + private static readonly HashSet LayerGenerators = new(StringComparer.Ordinal) { "rules-names", "docs-site" }; /// The registry's flat generators: every entry but the layer ones. private static IEnumerable> Flat() => diff --git a/server/csharp/MetaObjects.Codegen/CodegenDrift.cs b/server/csharp/MetaObjects.Codegen/CodegenDrift.cs index 7553e37984..41a8a36bee 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenDrift.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenDrift.cs @@ -101,7 +101,12 @@ public static Result Compute(GenConfig config, MetaRoot root, IReadOnlyList temps[roots.FindIndex(r => r.Committed == Path.GetFullPath(realRootFor(g)))], rendered); + g => temps[roots.FindIndex(r => r.Committed == Path.GetFullPath(realRootFor(g)))], rendered, + // Key the rendered files as gen keys them, so a generator listing the run's output + // (the docs site) renders what gen wrote. + config.ProjectRoot is { } project + ? new CodegenRunner.CaptureKeys(project, realRootFor, config.GenStateDir, config.OutDir, !narrowed) + : null); } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or MetaModelException) { diff --git a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs index ef62b5c25b..4df44858e7 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs @@ -57,10 +57,22 @@ internal static Func OutRootFor(GenConfig config) => /// every entry at a temporary tree of its own. internal static RunResult Run( GenConfig config, MetaRoot root, IReadOnlyList generators, Func outRoot, - IDictionary? capture = null) + IDictionary? capture = null, CaptureKeys? captureKeys = null) { config = PackageBindingResolver.WithDerivedHome(config, root); var warnings = new List(); + // The files this run generates, keyed as the manifest keys them: what a generator reading the + // run's output (the docs site) lists. A capture run keys each file by the real directory it + // stands in for, so the drift gate renders what gen writes. Files this run does not render + // (an entry another run writes, an object --entities leaves out) are carried from the manifest. + var keyRoot = captureKeys?.ProjectRoot ?? config.ProjectRoot; + var sweeps = config.SweepOrphans && config.GenStateDir is not null && config.ProjectRoot is not null + && config.Baseline != "adopt"; + var sweepDirs = SweepDirs(generators, outRoot, config.OutDir); + var generatedFiles = keyRoot is null ? null : CarriedFiles(captureKeys?.GenStateDir ?? config.GenStateDir, keyRoot, + captureKeys is { } ck + ? (ck.Sweeps ? OrphanSweep.Scope(SweepDirs(generators, ck.RealOutRoot, ck.RealOutDir)) : []) + : (sweeps ? OrphanSweep.Scope(sweepDirs) : [])); var ctx = new GenContext { // FR-044: an object.report is never in the entity set. Dropped here, at the set @@ -82,6 +94,7 @@ internal static RunResult Run( Config = config, Warn = warnings.Add, Generators = generators, + GeneratedFiles = generatedFiles, }; // No run-wide name-collision check: each generator refuses a name two objects claim in @@ -122,9 +135,12 @@ internal static RunResult Run( // Saved even when a generator throws, so the manifest keeps matching the files already written. try { - foreach (var generator in generators) + // An entry that reads the run's output runs after every other one (IGenerator.ReadsRunOutput). + foreach (var generator in generators.Where(g => !g.ReadsRunOutput).Concat(generators.Where(g => g.ReadsRunOutput))) { var genRoot = outRoot(generator); + // The manifest's generatedBy: the stable registry name, as every port records it. + var generatedBy = GeneratorRegistry.StableNameOf(generator); // An entry with its own directory reports its files by that directory, so a reader // can tell the api reference's README.md from one under --out. var shown = generator.OutDir is { Length: > 0 } own ? own.TrimEnd('/', '\\') + "/" : ""; @@ -139,6 +155,9 @@ internal static RunResult Run( if (generator.HandEdits == HandEdits.Overwrite) overwritePaths.Add(full); if (capture is not null) { + if (generatedFiles is not null && captureKeys is not null + && KeyUnder(captureKeys.ProjectRoot, Path.Combine(captureKeys.RealOutRoot(generator), file.Path)) is { } capturedKey) + generatedFiles[capturedKey] = new HashManifest.Provenance(generatedBy, file.SourceNode); capture[full] = file.Content; results.Add(new WriteResult(shown + file.Path, "written")); continue; @@ -165,6 +184,7 @@ internal static RunResult Run( var outside = config.ProjectRoot is not null && (key.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(key)); if (outside) { untracked++; outsidePaths.Add(full); } + else if (generatedFiles is not null) generatedFiles[key] = new HashManifest.Provenance(generatedBy, file.SourceNode); if (HelperRuntimeReference.Imports(file.Content)) helperImports.Add((full, shown + file.Path)); else if (HelperRuntimeReference.ImportsFormer(file.Content)) formerImports.Add(shown + file.Path); var status = WriteOne( @@ -180,7 +200,7 @@ internal static RunResult Run( status = "written"; } if (!outside && manifest is not null) - provenance[key] = new HashManifest.Provenance(generator.Name, file.SourceNode); + provenance[key] = new HashManifest.Provenance(generatedBy, file.SourceNode); results.Add(new WriteResult(reported, status)); if (status == "refused") refused.Add(reported); else if (status == "adopted") adopted.Add(reported); @@ -199,15 +219,9 @@ internal static RunResult Run( warnings.AddRange(HelperRuntimeReference.WarningsForImporting(helperImports)); if (HelperRuntimeReference.FormerImportWarning(formerImports) is { } former) warnings.Add(former); - if (config.SweepOrphans && config.GenStateDir is { } genState && config.ProjectRoot is { } project - && config.Baseline != "adopt") + if (sweeps && config.GenStateDir is { } genState && config.ProjectRoot is { } project) { - // Every directory a generator of this run wrote into, labelled as its files are - // reported. The run's own --out is always one of them. - var dirs = new List<(string Dir, string Label)> { (config.OutDir, "") }; - foreach (var g in generators) - dirs.Add((outRoot(g), g.OutDir is { Length: > 0 } own ? own.TrimEnd('/', '\\') + "/" : "")); - var swept = OrphanSweep.Sweep(genState, project, dirs, emitted.Keys.ToHashSet(StringComparer.Ordinal), + var swept = OrphanSweep.Sweep(genState, project, sweepDirs, emitted.Keys.ToHashSet(StringComparer.Ordinal), OverwriteDirs(generators, outRoot, config.OutDir)); foreach (var path in swept.Removed) results.Add(new WriteResult(path, "removed")); foreach (var path in swept.Discarded) @@ -232,6 +246,45 @@ internal static RunResult Run( }; } + /// How a capture run (the drift gate) keys the files it renders: relative to + /// , each at the real output directory + /// names for its generator, with the committed manifest under . + /// is the run's real --out, and + /// whether the gen it stands in for sweeps orphans. + internal sealed record CaptureKeys(string ProjectRoot, Func RealOutRoot, string? GenStateDir, + string RealOutDir, bool Sweeps); + + /// Every directory a generator of this run writes into, labelled as its files are reported: + /// the directories the orphan sweep walks. The run's own --out is always one of them. + private static List<(string Dir, string Label)> SweepDirs( + IReadOnlyList generators, Func outRoot, string outDir) + { + var dirs = new List<(string Dir, string Label)> { (outDir, "") }; + foreach (var g in generators) + dirs.Add((outRoot(g), g.OutDir is { Length: > 0 } own ? own.TrimEnd('/', '\\') + "/" : "")); + return dirs; + } + + /// The manifest's files the docs site still lists beside this run's: those the run's orphan + /// sweep (, empty when it sweeps nothing) leaves alone. A recorded file inside + /// it is either emitted again, and so listed, or deleted. + private static Dictionary CarriedFiles( + string? genStateDir, string projectRoot, IReadOnlyList<(string Dir, string Label, List Nested)> swept) + { + var files = new Dictionary(StringComparer.Ordinal); + if (genStateDir is null || !HashManifest.Exists(genStateDir)) return files; + foreach (var (key, prov) in HashManifest.LoadProvenance(genStateDir)) + if (!OrphanSweep.InScope(Path.Combine(projectRoot, key), swept)) files[key] = prov; + return files; + } + + /// relative to , or null outside it. + private static string? KeyUnder(string projectRoot, string path) + { + var key = Path.GetRelativePath(Path.GetFullPath(projectRoot), Path.GetFullPath(path)); + return key.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(key) ? null : key; + } + /// /// What emits, narrowed to (the /// --entities short names) when there is one. diff --git a/server/csharp/MetaObjects.Codegen/Docs/ExplorerSite.cs b/server/csharp/MetaObjects.Codegen/Docs/ExplorerSite.cs new file mode 100644 index 0000000000..f816227fa7 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Docs/ExplorerSite.cs @@ -0,0 +1,132 @@ +// The model explorer site every port's docs-site generator writes (docs/features/explorer-site.md): +// the shared explorer app (the same bytes in every port, synced from explorer-app/ by +// scripts/sync-explorer-app.sh and embedded in this package), the explorer's theme pair, which a +// project may own under codegen/docs-site/assets/, and three data files built from the docs view: +// explorer.json, explorer-model.js and explorer-stamp.js. Mirrors the Java port's ExplorerSite. + +using System.Text.Json.Nodes; +using static MetaObjects.Template.TemplateConstants; + +namespace MetaObjects.Codegen.Docs; + +/// The files of the model explorer site, by path under the site directory. +public static class ExplorerSite +{ + public const string ModelFile = "explorer-model.js"; + public const string StampFile = "explorer-stamp.js"; + public const string ViewFile = "explorer.json"; + + /// The app's files, as the shared copy holds them. + public static readonly IReadOnlyList AppFiles = + [ + "index.html", + "assets/explorer-app.js", + "assets/explorer.css", + "assets/explorer.js", + "assets/cytoscape.min.js", + "assets/3d-force-graph.min.js", + ]; + + /// The theme pair: an owned copy under codegen/docs-site/assets/ replaces the shipped one. + public static readonly IReadOnlyList ThemeAssets = ["explorer.css", "explorer.js"]; + + /// The page templates a project may own under codegen/docs-site/templates/; the app reads them from the model script. + public static readonly IReadOnlyList TemplateNames = + [ + "explorer-head.mustache", + "explorer-foot.mustache", + "explorer-card.mustache", + "explorer-overview.html.mustache", + "explorer-map.html.mustache", + "explorer-object.html.mustache", + "explorer-node.html.mustache", + "explorer-prompt.html.mustache", + "explorer-prompts.html.mustache", + "explorer-requirements.html.mustache", + "explorer-requirement.html.mustache", + "explorer-matrix.html.mustache", + "explorer-trace.html.mustache", + "explorer-gaps.html.mustache", + "explorer-api.html.mustache", + "explorer-model.html.mustache", + "explorer-package.html.mustache", + ]; + + private const string ResourceRoot = "explorer-app/"; + + /// What the site is built from. and + /// are the project's owned copies, or null. + public sealed record Input(JsonObject View, string Title, string Footer, IReadOnlyDictionary Texts, + string? AssetsDir, string? TemplatesDir); + + /// Every file of the site, path to content, in a fixed order. + public static IReadOnlyList> Emit(Input input) + { + var files = new List>(); + foreach (var f in AppFiles) + { + if (f.StartsWith("assets/", StringComparison.Ordinal) && ThemeAssets.Contains(f["assets/".Length..])) continue; + files.Add(new(f, Resource(f))); + } + foreach (var a in ThemeAssets) + files.Add(new("assets/" + a, ReadIfPresent(input.AssetsDir, a) ?? Resource("assets/" + a))); + var templates = new SortedDictionary(StringComparer.Ordinal); + foreach (var name in TemplateNames) + if (ReadIfPresent(input.TemplatesDir, name) is { } owned) templates[name] = owned; + var model = ExplorerModelScript.Of(input.Title, input.Footer, input.Texts, templates, input.View); + files.Add(new(ModelFile, model.Script)); + files.Add(new(StampFile, ExplorerModelScript.StampScript(model.Stamp))); + files.Add(new(ViewFile, DocsView.Serialize(input.View))); + return files; + } + + /// + /// Each template node's prompt text, by node id: the file its @textRef names (with + /// .mustache appended), found in the first of that holds it. A + /// reference that is absolute or has an empty or .. segment is never read. + /// + public static SortedDictionary ReadPromptTexts(JsonObject view, IReadOnlyList dirs) + { + var texts = new SortedDictionary(StringComparer.Ordinal); + foreach (var node in view["nodes"]!.AsArray()) + { + string? textRef = null; + foreach (var attr in node!["attrs"]!.AsArray()) + { + if (attr!["name"]!.GetValue() == TEMPLATE_ATTR_TEXT_REF + && attr["value"] is JsonValue v && v.TryGetValue(out var s)) + textRef = s; + } + if (textRef is null) continue; + var segments = textRef.Split('/', '\\'); + bool unsafeRef = Path.IsPathRooted(textRef) || textRef.StartsWith('/') || textRef.StartsWith('\\') + || segments.Any(seg => seg.Length == 0 || seg == ".."); + if (unsafeRef) continue; + foreach (var dir in dirs) + { + var parts = segments.ToArray(); + parts[^1] += ".mustache"; + var p = Path.Combine([dir, .. parts]); + if (!File.Exists(p)) continue; + texts[node["id"]!.GetValue()] = File.ReadAllText(p); + break; + } + } + return texts; + } + + private static string? ReadIfPresent(string? dir, string name) + { + if (dir is null) return null; + var p = Path.Combine(dir, name); + return File.Exists(p) ? File.ReadAllText(p) : null; + } + + private static string Resource(string rel) + { + using var stream = typeof(ExplorerSite).Assembly.GetManifestResourceStream(ResourceRoot + rel) + ?? throw new InvalidOperationException($"docs-site: the explorer app file {rel} is not embedded in MetaObjects.Codegen"); + using var reader = new StreamReader(stream); + return reader.ReadToEnd(); + } +} diff --git a/server/csharp/MetaObjects.Codegen/Generator.cs b/server/csharp/MetaObjects.Codegen/Generator.cs index b41c6c0191..36fffe6a4b 100644 --- a/server/csharp/MetaObjects.Codegen/Generator.cs +++ b/server/csharp/MetaObjects.Codegen/Generator.cs @@ -479,6 +479,14 @@ public sealed class GenContext /// public NameClaims Claims { get; init; } = new(); + /// + /// The files this run has generated so far, keyed as the hash manifest keys them (relative to + /// the project root), with the generator and node each came from; null when the run has no + /// project root to key them by. A generator answering + /// runs after every other one, so it sees the whole run's output (the docs site lists it). + /// + public IReadOnlyDictionary? GeneratedFiles { get; init; } + /// /// Claim in for , as /// it is emitted. The first claimant owns the name; another claimant of the same name in the @@ -545,6 +553,7 @@ public GenContext Narrow(Func? include) => Warn = Warn, Claims = Claims, Generators = Generators, + GeneratedFiles = GeneratedFiles, Applicability = Applicability, Scope = Scope is null ? include : o => Scope(o) && include(o), }; @@ -563,6 +572,7 @@ internal GenContext NarrowForProbe(Func include) => Warn = _ => { }, Claims = new NameClaims(), Generators = Generators, + GeneratedFiles = GeneratedFiles, Applicability = Applicability, Scope = Scope is null ? include : o => Scope(o) && include(o), }; @@ -657,6 +667,12 @@ public interface IGenerator /// editing one renders again. Empty by default. /// IReadOnlyList ExtraInputs => []; + + /// + /// Whether this entry reads the files the run generated (). + /// The runner runs every such entry after every other one, keeping their declared order. + /// + bool ReadsRunOutput => false; } /// A generator entry's handEdits setting: what a run does with a hand-edited file. @@ -696,6 +712,7 @@ internal sealed class HandEditsGenerator(IGenerator inner, HandEdits handEdits) public bool Cacheable => Inner.Cacheable; /// public IReadOnlyList ExtraInputs => Inner.ExtraInputs; + public bool ReadsRunOutput => Inner.ReadsRunOutput; /// public IEnumerable Generate(GenContext ctx) => Inner.Generate(ctx); } diff --git a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs index 13365fbf5e..79d331c560 100644 --- a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs +++ b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs @@ -328,6 +328,18 @@ private static IGenerator RenderHelper(GeneratorBuildContext ctx) => Note = "Reads no model objects. A project's metamodel/.mustache under the template root overrides the shipped template.", SourceFileName = "MetamodelDocsGenerator.cs", }, + // The model explorer over the docs view (no Node). Exempt from eject (registry.json): the site + // builder is engine; a project owns the explorer's theme and page templates under codegen/docs-site/. + ["docs-site"] = new() + { + Name = "docs-site", + Description = "The model explorer: one browser app over the project's docs view (explorer.json), with the requirement tree, the model map, a page per object, prompt and requirement, the coverage matrix and the generated files the hash manifest records. Needs no Node.", + Tier = GeneratorTier.Neutral, + Layer = GeneratorLayer.Docs, + Factory = _ => new DocsSiteGenerator(), + Options = "OutDir, SubDir (default \"site\"), Title, Stamp, Prompts, VerifyFile, RoutesFile (init properties on the entry in codegen/Generators.cs)", + Note = "Lists the files the run generated, so it runs after every other entry. A project's codegen/docs-site/assets/explorer.{css,js} and templates/*.mustache override the shipped theme and pages.", + }, ["template"] = new() { Name = "template", @@ -433,6 +445,24 @@ public static string ListEntry(GeneratorRegistryEntry entry) public static GeneratorRegistryEntry? Get(string id) => Entries.TryGetValue(id, out var e) ? e : null; + // Each registered generator's Name (what a packaged or an owned copy answers), to its stable name. + private static readonly Lazy> StableByName = new(() => + { + var map = new Dictionary(StringComparer.Ordinal); + foreach (var (id, entry) in Entries) map.TryAdd(entry.Factory(new GeneratorBuildContext()).Name, id); + return map; + }); + + /// + /// The stable name of , as the hash manifest's generatedBy + /// provenance names it in every port (filter-allowlist, not the class-style + /// filter-allowlist-generator its answers). An ejected copy + /// keeps the Name it was copied with, so it maps too; a generator the registry does not know + /// (a project's own, a template entry) keeps its Name. + /// + public static string StableNameOf(IGenerator generator) => + StableByName.Value.TryGetValue(generator.Name, out var id) ? id : generator.Name; + /// /// C1 — the ONE place that decides from a /// resolved generator-name selection: true iff the stable id "names" diff --git a/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs new file mode 100644 index 0000000000..3bc5525f09 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs @@ -0,0 +1,130 @@ +// docs-site — the model explorer (docs/features/explorer-site.md): one browser app over the +// project's docs view, written with no Node. This port builds the docs view in memory from the +// loaded model (MetaObjects.DocsView), lists the files the run generated (with the generator and +// node each came from), and writes it as explorer.json beside the model script, the stamp and the +// shared explorer app. Mirrors the Java/Kotlin DocsSiteGenerator and TypeScript's docsSiteFile(). +// +// An ordinary entry in codegen/Generators.cs (ADR-0034 Amendment 9). Exempt from eject: the site +// builder is engine; what a project changes is the explorer's theme (codegen/docs-site/assets/) +// and page templates (codegen/docs-site/templates/), which it owns and this generator reads. + +using System.Text.Json.Nodes; +using MetaObjects.Codegen.Docs; +using MetaObjects.Config; + +namespace MetaObjects.Codegen.Generators; + +public sealed class DocsSiteGenerator : IGenerator +{ + public const string DefaultSubDir = "site"; + + /// Where a project keeps its owned theme (assets/) and page templates (templates/). + public const string OwnedDocsSiteDir = "codegen/docs-site"; + + private const string DefaultGenStateDir = ".metaobjects/.gen-state"; + + public string Name => "docs-site"; + + /// + public string? OutDir { get; init; } + + /// The site's directory under the output directory; "" writes at its root. + public string SubDir { get; init; } = DefaultSubDir; + + /// The explorer's title; the project directory's name when unset ("Metadata" in a run that names no project). + public string? Title { get; init; } + + /// The footer line (a build stamp, a version). + public string Stamp { get; init; } = ""; + + /// A directory of prompt texts, searched after the metadata directory, templates/ and prompts/. + public string? Prompts { get; init; } + + /// A dotnet meta verify --format json payload: adds the requirement ledger and its advisories. + public string? VerifyFile { get; init; } + + /// A routes file ([{ node, method, path }]): adds each object's served routes. + public string? RoutesFile { get; init; } + + public bool WholeModel => true; + + /// The docs site lists the files the run generated, so it runs after every other entry. + public bool ReadsRunOutput => true; + + public IReadOnlyList ExtraInputs => + new[] { OwnedDocsSiteDir, Prompts, VerifyFile, RoutesFile }.OfType().ToList(); + + public IEnumerable Generate(GenContext ctx) + { + // A run that names no project reads nothing beside the model it was handed: no committed + // manifest, owned theme or prompt directory is found through the process's working + // directory, which a host (or a parallel test) may change between gen and verify. Paths the + // options name explicitly still resolve against it. + var known = ctx.Config.InputRoot ?? ctx.Config.ProjectRoot; + var project = Path.GetFullPath(known ?? Directory.GetCurrentDirectory()); + string Abs(string p) => Path.GetFullPath(Path.Combine(project, p)); + var verify = VerifyFile is null ? null : ReadJson(Abs(VerifyFile)); + var routes = RoutesFile is null ? null : ReadJson(Abs(RoutesFile)); + var genState = ctx.Config.GenStateDir ?? (known is null ? null : Path.Combine(project, DefaultGenStateDir)); + IReadOnlyDictionary? files = ctx.GeneratedFiles + ?? (genState is not null && HashManifest.Exists(genState) ? HashManifest.LoadProvenance(genState) : null); + var view = DocsView.Build(ctx.Root, verify, files is null ? null : ProvenanceJson(files), routes); + + var owned = Path.Combine(project, OwnedDocsSiteDir); + var assets = Path.Combine(owned, "assets"); + var templates = Path.Combine(owned, "templates"); + var site = ExplorerSite.Emit(new ExplorerSite.Input( + view, + Title ?? (known is not null && Path.GetFileName(project.TrimEnd(Path.DirectorySeparatorChar)) is { Length: > 0 } dir ? dir : "Metadata"), + Stamp, + ExplorerSite.ReadPromptTexts(view, PromptDirs(ctx, project, known is not null)), + known is not null && Directory.Exists(assets) ? assets : null, + known is not null && Directory.Exists(templates) ? templates : null)); + var prefix = SubDir.TrimEnd('/') is { Length: > 0 } sub ? sub + "/" : ""; + foreach (var (path, content) in site) + yield return new EmittedFile(prefix + path, content) { WholeModel = true }; + } + + private static JsonObject ProvenanceJson(IReadOnlyDictionary files) + { + var o = new JsonObject(); + foreach (var key in files.Keys.Order(StringComparer.Ordinal)) + { + var entry = new JsonObject { ["generatedBy"] = files[key].GeneratedBy }; + if (files[key].SourceNode is { } node) entry["sourceNode"] = node; + o[key] = entry; + } + return o; + } + + /// Where a template's @textRef is looked up: the metadata directory, the + /// project's templates/ and prompts/, then . + private List PromptDirs(GenContext ctx, string project, bool projectKnown) + { + var dirs = new List(); + void Add(string? d) + { + if (d is null) return; + var full = Path.GetFullPath(Path.Combine(project, d)); + if (Directory.Exists(full) && !dirs.Contains(full)) dirs.Add(full); + } + if (projectKnown) + { + try { Add(MetadataLocation.Resolve(null, project).Directory); } + // A project whose sources do not resolve still searches the other directories. + catch (Exception e) when (e is MetadataLocationException or MetaModelException) { } + Add(CodegenCli.LegacyTemplatesDir); + Add(CodegenCli.DefaultPromptsDir); + } + if (Prompts is not null) + { + if (Directory.Exists(Path.Combine(project, Prompts))) Add(Prompts); + else ctx.Warn($"docs-site: the prompts directory does not exist: {Prompts}"); + } + return dirs; + } + + private static JsonNode? ReadJson(string path) => + File.Exists(path) ? JsonNode.Parse(File.ReadAllText(path)) + : throw new InvalidOperationException($"docs-site: could not read {path}"); +} diff --git a/server/csharp/MetaObjects.Codegen/HashManifest.cs b/server/csharp/MetaObjects.Codegen/HashManifest.cs index fd7de3a717..eeed5f0bed 100644 --- a/server/csharp/MetaObjects.Codegen/HashManifest.cs +++ b/server/csharp/MetaObjects.Codegen/HashManifest.cs @@ -455,6 +455,27 @@ public static bool IsRecorded(string genStateDir, string relPath, string? legacy private static readonly string[] ProvenanceFields = ["generatedBy", "sourceNode"]; + /// + /// Every recorded path with the generator and node the manifest says it came from, in key order: + /// what the docs view lists when the run that wrote them is not the one asking. A plain-hash + /// entry (no node) reads as generated by nothing named, with no source node. An absent manifest + /// reads as empty. + /// + public static SortedDictionary LoadProvenance(string genStateDir) + { + var outMap = new SortedDictionary(StringComparer.Ordinal); + foreach (var (key, value) in ReadRaw(genStateDir)) + { + if (EntryHash(value) is null) continue; + string by = value.ValueKind == JsonValueKind.Object && value.TryGetProperty("generatedBy", out var g) + && g.ValueKind == JsonValueKind.String ? g.GetString()! : ""; + string? node = value.ValueKind == JsonValueKind.Object && value.TryGetProperty("sourceNode", out var n) + && n.ValueKind == JsonValueKind.String ? n.GetString() : null; + outMap[key] = new Provenance(by, node); + } + return outMap; + } + /// /// Record, on each recorded path's entry, the generator and node it came from. An entry with a /// source node becomes { hash, ...other fields, generatedBy, sourceNode }; one without diff --git a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj index f300283ca8..10664c0b39 100644 --- a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj +++ b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj @@ -69,6 +69,12 @@ + + + + + diff --git a/server/csharp/MetaObjects.Codegen/OrphanSweep.cs b/server/csharp/MetaObjects.Codegen/OrphanSweep.cs index af3ab1565f..b4ecee9423 100644 --- a/server/csharp/MetaObjects.Codegen/OrphanSweep.cs +++ b/server/csharp/MetaObjects.Codegen/OrphanSweep.cs @@ -111,6 +111,24 @@ private static bool IsUnder(string path, string dir) => Path.TrimEndingDirectorySeparator(Path.GetFullPath(dir)) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); + /// Each directory a sweep over walks, as a full path, with its label + /// and the swept directories nested in it, whose files it leaves alone. + internal static List<(string Dir, string Label, List Nested)> Scope(IReadOnlyList<(string Dir, string Label)> dirs) + { + var distinct = dirs.DistinctBy(d => Path.GetFullPath(d.Dir)).ToList(); + var all = distinct.Select(d => Path.GetFullPath(d.Dir)).ToList(); + return distinct.Select(d => + { + var full = Path.GetFullPath(d.Dir); + return (full, d.Label, all.Where(o => o != full && IsUnder(o, full)).ToList()); + }).ToList(); + } + + /// Whether a sweep over removes when no + /// generator of the run emits it. + internal static bool InScope(string path, IReadOnlyList<(string Dir, string Label, List Nested)> scope) => + scope.Any(s => IsUnder(path, s.Dir) && !s.Nested.Any(n => IsUnder(path, n))); + /// /// Delete the untouched files under that the manifest records and /// (absolute paths this run produced, refused ones included) does @@ -144,12 +162,8 @@ public static Result Sweep( var forget = new HashSet(StringComparer.Ordinal); var root = Path.GetFullPath(projectRoot); - var distinct = dirs.DistinctBy(d => Path.GetFullPath(d.Dir)).ToList(); - var all = distinct.Select(d => Path.GetFullPath(d.Dir)).ToList(); - foreach (var (dir, label) in distinct) + foreach (var (full, label, nested) in Scope(dirs)) { - var full = Path.GetFullPath(dir); - var nested = all.Where(o => o != full && IsUnder(o, full)).ToList(); var prefix = KeyFor(root, full); if (prefix is null) continue; // nothing outside the project is ours to delete var overwrite = overwriteDirs?.Contains(full) == true; diff --git a/server/csharp/MetaObjects.Conformance.Tests/DocsViewConformanceTests.cs b/server/csharp/MetaObjects.Conformance.Tests/DocsViewConformanceTests.cs new file mode 100644 index 0000000000..5bb18de644 --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/DocsViewConformanceTests.cs @@ -0,0 +1,143 @@ +// The docs view corpus (fixtures/explorer-conformance/, docs/features/docs-view.md): each fixture's +// project is loaded strictly, its committed optional inputs are read, and DocsView must reproduce +// the fixture's expected.json byte for byte, as the TypeScript reference does. A fixture's +// provider.json is applied before loading, every type it declares a plain node. + +using System.Text.Json; +using System.Text.Json.Nodes; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +public sealed class DocsViewConformanceTests +{ + /// A node of a type a fixture's provider.json declares: no behaviour beyond MetaData's own. + private sealed class FixtureNode(TypeId typeId, string name) : MetaData(typeId, name); + + /// A provider for a fixture's provider.json: every type a plain node, its attrs and child slots as declared. + private sealed class FixtureProvider(JsonElement def) : IMetaDataTypeProvider + { + public string Id => def.GetProperty("provider").GetString()!; + public IReadOnlyList Dependencies => ["metaobjects-core-types"]; + + public void RegisterTypes(TypeRegistry registry) + { + foreach (var type in def.GetProperty("types").EnumerateArray()) + { + var (rules, attrs) = Slots(type.GetProperty("children")); + registry.Register(new TypeDefinition( + typeId: new TypeId(type.GetProperty("type").GetString()!, type.GetProperty("subType").GetString()!), + description: type.GetProperty("description").GetString()!, + childRules: rules, + factory: (typeId, name) => new FixtureNode(typeId, name), + attributes: attrs)); + } + foreach (var ext in def.GetProperty("extends").EnumerateArray()) + { + var (rules, attrs) = Slots(ext.GetProperty("children")); + registry.Extend(ext.GetProperty("type").GetString()!, ext.GetProperty("subType").GetString()!, attrs, rules); + } + } + + private static (List, List) Slots(JsonElement children) + { + var rules = new List(); + var attrs = new List(); + foreach (var slot in children.EnumerateArray()) + { + string type = slot.GetProperty("type").GetString()!; + string name = slot.GetProperty("name").GetString()!; + if (type == TYPE_ATTR) + { + attrs.Add(new AttrSchema(name, slot.GetProperty("subType").GetString(), + Required: slot.GetProperty("min").GetInt32() > 0, + Description: slot.TryGetProperty("description", out var d) ? d.GetString()! : "", + IsArray: slot.TryGetProperty("isArray", out var a) && a.GetBoolean())); + } + else + { + rules.Add(new ChildRule(type, slot.GetProperty("subType").GetString()!, name)); + } + } + return (rules, attrs); + } + } + + internal static string Corpus() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null && !Directory.Exists(Path.Combine(dir.FullName, "fixtures", "explorer-conformance"))) + dir = dir.Parent; + Assert.NotNull(dir); + return Path.Combine(dir!.FullName, "fixtures", "explorer-conformance"); + } + + private static List FixtureNames() => + Directory.GetDirectories(Corpus()).Select(d => Path.GetFileName(d)).Order(StringComparer.Ordinal).ToList(); + + public static TheoryData Fixtures() + { + var data = new TheoryData(); + foreach (var d in FixtureNames()) data.Add(d); + return data; + } + + private static JsonNode? ReadJson(string dir, string name) + { + string p = Path.Combine(dir, name); + return File.Exists(p) ? JsonNode.Parse(File.ReadAllText(p)) : null; + } + + /// A fixture's project, loaded strictly with its provider.json applied. + internal static MetaRoot Load(string name) + { + string dir = Path.Combine(Corpus(), name); + var providers = new List(CoreTypes.LibraryProviders); + string providerFile = Path.Combine(dir, "provider.json"); + if (File.Exists(providerFile)) + { + using var doc = JsonDocument.Parse(File.ReadAllText(providerFile)); + providers.Add(new FixtureProvider(doc.RootElement.Clone())); + } + var result = MetaDataLoader.FromDirectory(Path.Combine(dir, "project", "metaobjects"), + Provider.ComposeRegistry(providers), strict: true); + Assert.True(result.Errors.Count == 0, + $"{name}: expected a clean strict load, got: {string.Join("; ", result.Errors.Select(e => e.Message))}"); + return result.Root; + } + + [Fact] + public void CorpusHoldsTheFixturesTheReadmeDescribes() => + Assert.Equal(["crm", "model-alone", "shop"], FixtureNames()); + + [Theory] + [MemberData(nameof(Fixtures))] + public void ReproducesExpectedJson(string name) + { + string dir = Path.Combine(Corpus(), name); + string expected = File.ReadAllText(Path.Combine(dir, "expected.json")); + string actual = DocsView.Serialize(DocsView.Build(Load(name), + ReadJson(dir, "verify.json"), ReadJson(dir, "hashes.json"), ReadJson(dir, "routes.json"))); + if (expected != actual && Environment.GetEnvironmentVariable("DOCS_VIEW_ACTUAL_DIR") is { Length: > 0 } scratch) + File.WriteAllText(Path.Combine(scratch, name + ".json"), actual); + Assert.True(expected == actual, + $"{name}: docs view differs from expected.json (set DOCS_VIEW_ACTUAL_DIR to write what this port builds)"); + } + + [Fact] + public void JsonWriterMatchesJavaScript() + { + Assert.Equal("1.5", DocsViewJson.Number(1.5)); + Assert.Equal("3", DocsViewJson.Number(3.0)); + Assert.Equal("1e+21", DocsViewJson.Number(1e21)); + Assert.Equal("100000000000000000000", DocsViewJson.Number(1e20)); + Assert.Equal("0.000001", DocsViewJson.Number(0.000001)); + Assert.Equal("1e-7", DocsViewJson.Number(1e-7)); + Assert.Equal("-12.25", DocsViewJson.Number(-12.25)); + Assert.Equal("123.456", DocsViewJson.Number(123.456)); + Assert.Equal("9007199254740992", DocsViewJson.Number(1L << 53)); + Assert.Equal("\"a\\u0001<>& \\ud800\u2028\"", DocsViewJson.Quote("a\u0001<>& \ud800\u2028")); + } +} diff --git a/server/csharp/MetaObjects.Conformance.Tests/MetaEndpointTests.cs b/server/csharp/MetaObjects.Conformance.Tests/MetaEndpointTests.cs index ecfdd14304..9e5eb72e8e 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/MetaEndpointTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/MetaEndpointTests.cs @@ -24,6 +24,44 @@ public void MetaJson_returns_the_effective_canonical_serialization() Assert.Equal(expected, actual); } + [Fact] + public void MetaDocsRoutePath_sits_beside_meta() => + Assert.Equal("/_meta/docs", MetaEndpoint.MetaDocsRoutePath); + + [Fact] + public void MetaDocs_body_is_the_model_alone_docs_view() + { + var expected = File.ReadAllText(Path.Combine(DocsViewConformanceTests.Corpus(), "model-alone", "expected.json")); + var root = DocsViewConformanceTests.Load("model-alone"); + Assert.Equal(expected, MetaEndpoint.MetaDocsJson(root)); + var docs = MetaEndpoint.MetaDocs(root); + Assert.Equal(expected, docs.Body); + Assert.Equal(MetaEndpoint.MetaDocsETag(expected), docs.ETag); + } + + [Fact] + public void MetaDocsETag_is_the_cross_port_value() + { + // metaDocsEtag(...) in @metaobjectsdev/runtime-ts (and the Java port) gives these for the same strings. + Assert.Equal("\"5-4f9f2cab\"", MetaEndpoint.MetaDocsETag("hello")); + Assert.Equal("\"0-811c9dc5\"", MetaEndpoint.MetaDocsETag("")); + Assert.Equal("\"7-0579d2da\"", MetaEndpoint.MetaDocsETag("h\u00e9llo \u2713")); + Assert.Equal("\"2-cb31c4b8\"", MetaEndpoint.MetaDocsETag("\U0001F600")); + } + + [Fact] + public void If_none_match_names_the_tag_or_star() + { + const string tag = "\"5-4f9f2cab\""; + Assert.True(MetaEndpoint.ETagMatches(tag, tag)); + Assert.True(MetaEndpoint.ETagMatches("\"x\", W/" + tag, tag)); + Assert.True(MetaEndpoint.ETagMatches("*", tag)); + Assert.False(MetaEndpoint.ETagMatches(null, tag)); + Assert.False(MetaEndpoint.ETagMatches("", tag)); + Assert.False(MetaEndpoint.ETagMatches("\"other\"", tag)); + Assert.True(MetaEndpoint.MetaDocs(DocsViewConformanceTests.Load("model-alone")).Matches("W/\"nope\", *")); + } + private static LoadResult LoadExtendsFixture() { // Load the extends-abstract-base conformance fixture. diff --git a/server/csharp/MetaObjects/DocsView/DocsView.cs b/server/csharp/MetaObjects/DocsView/DocsView.cs new file mode 100644 index 0000000000..59cf72c2ee --- /dev/null +++ b/server/csharp/MetaObjects/DocsView/DocsView.cs @@ -0,0 +1,828 @@ +// DocsView — the docs view of a loaded model: one port-neutral document, the facts every +// documentation page reads, and what the model explorer draws (docs/features/docs-view.md). +// +// The C# port of TypeScript's buildDocsView (@metaobjectsdev/metadata, src/docs-view/build.ts), +// held to the same bytes by fixtures/explorer-conformance/. It reads the model the loader built +// and resolved, and re-derives none of it: +// +// ids and pages from the effective tree (Children()), walked once in declaration order; +// inheritance an effective child whose Parent is another node is inherited, and that +// parent is where it is declared; +// references the loader's own resolution (ResolvedTargetOf / ResolvedTargetsOf on every +// attribute it treats as a reference, SuperData for extends); +// claims @implementedBy, through the resolver the requirement gate uses. +// +// Three optional inputs add what the model does not hold, each as parsed JSON and each left out +// when null or malformed: the `verify --format json` payload, the generation manifest +// (path -> { generatedBy, sourceNode }) and the routes ([{ node, method, path }]). +// +// DETERMINISTIC: the same inputs give the same bytes (Serialize). + +using System.Text.Json; +using System.Text.Json.Nodes; +using MetaObjects.Core.Requirement; +using MetaObjects.Meta; + +namespace MetaObjects; + +/// The docs view of a loaded model (docs/features/docs-view.md). +public static class DocsView +{ + /// Bumped when a field changes meaning or is removed. + public const string Format = "metaobjects-docs-view/1"; + + private const string ExtendsAttr = "extends"; + private const string Nul = "\u0000"; + + /// The file's bytes: two-space JSON and one trailing newline. + public static string Serialize(JsonObject view) => DocsViewJson.Pretty(view) + "\n"; + + /// + /// Build the docs view. , and + /// are optional; a malformed one only leaves its part out. + /// + public static JsonObject Build(MetaData root, JsonNode? verify = null, JsonNode? manifest = null, JsonNode? routes = null) => + (JsonObject)ToNode(new Builder(root).Run(Element(verify), Element(manifest), Element(routes)))!; + + private static JsonElement? Element(JsonNode? n) => + n is null ? null : JsonDocument.Parse(n.ToJsonString()).RootElement.Clone(); + + // ------------------------------------------------------------------ + // the ordered value model the builder writes (converted once at the end, so one object may + // appear in several places, as it does in TypeScript) + // ------------------------------------------------------------------ + + private sealed class J + { + public readonly List> Props = []; + + public J Set(string key, object? value) + { + int i = Props.FindIndex(p => p.Key == key); + if (i >= 0) Props[i] = new(key, value); + else Props.Add(new(key, value)); + return this; + } + + public object? Get(string key) => Props.First(p => p.Key == key).Value; + public string Str(string key) => (string)Get(key)!; + } + + private static JsonNode? ToNode(object? v) => v switch + { + null => null, + J j => ToObject(j), + string s => JsonValue.Create(s), + bool b => JsonValue.Create(b), + int i => JsonValue.Create((long)i), + long l => JsonValue.Create(l), + double d => JsonValue.Create(d), + JsonElement e => JsonNode.Parse(e.GetRawText()), + System.Collections.IEnumerable list => new JsonArray(list.Cast().Select(ToNode).ToArray()), + _ => JsonValue.Create(v.ToString()), + }; + + private static JsonObject ToObject(J j) + { + var o = new JsonObject(); + foreach (var (k, v) in j.Props) o.Add(k, ToNode(v)); + return o; + } + + // ------------------------------------------------------------------ + // the walk + // ------------------------------------------------------------------ + + /// A node as walked: where it sits, and the ids and pages it gets. + private sealed class Walked + { + public required MetaData Md; + public required string Id; + /// The id before any type qualifier: what a dotted reference spells. + public required string Plain; + public Walked Top = null!; + public Walked? Parent; + /// The direct member of Top it sits in (itself, for a direct member); null at the top. + public Walked? Direct; + /// The nearest requirement at or above it. + public Walked? Requirement; + public int Order; + /// On the walk path that physically holds the node: the one place a reference to it resolves to. + public bool Canonical; + /// The node that declares it, when it is inherited through extends. + public MetaData? DeclaredOn; + public string Anchor = ""; + public string Path = ""; + public readonly List Children = []; + /// Requirement address (dotted requirement names), set on requirements. + public string Address = ""; + } + + private sealed record Ledger( + string QualifiedPath, string Digest, string Verdict, List Diagnostics, + bool HasSup, string SupRef, bool SupResolves, string SupTarget); + + private sealed class Builder + { + private readonly MetaData _root; + private readonly List _walked = []; + private readonly List _tops = []; + private readonly Dictionary _byId = new(StringComparer.Ordinal); + private readonly Dictionary _canonical = new(ReferenceEqualityComparer.Instance); + /// Plain path -> walked node: the first holder of a plain path under a top-level node that holds its plain id. + private readonly Dictionary _byPlain = new(StringComparer.Ordinal); + private readonly List _requirements = []; + + public Builder(MetaData root) + { + _root = root; + Walk(); + } + + private static string PlainOf(MetaData md) + { + string pkg = NamingRefs.EffectivePackageOf(md); + return pkg.Length == 0 ? md.Name : pkg + PACKAGE_SEPARATOR + md.Name; + } + + private void Walk() + { + var topLevel = _root.Children(); + // Top-level nodes of different types may share a package and a name (an entity `Lead` and + // an application's page `Lead`). The object keeps the plain id, since every reference in + // the model names an object, else the first declared; each other one is qualified by type. + var holder = new Dictionary(StringComparer.Ordinal); + foreach (var md in topLevel) + { + string id = PlainOf(md); + if (!holder.TryGetValue(id, out var held) || (held.Type != TYPE_OBJECT && md.Type == TYPE_OBJECT)) holder[id] = md; + } + var seen = new HashSet(StringComparer.Ordinal); + for (int i = 0; i < topLevel.Count; i++) Visit(topLevel[i], i, null, "", holder, seen); + foreach (var w in _walked) w.Path = PathOf(w); + } + + private void Visit(MetaData md, int index, Walked? parent, string reqPrefix, + Dictionary holder, HashSet seen) + { + string id; + string plain; + if (parent is null) + { + plain = md.Name.Length == 0 ? $"#{index}" : PlainOf(md); + id = plain; + holder.TryGetValue(plain, out var held); + if (md.Name.Length != 0 && !ReferenceEquals(held, md) && held?.Type != md.Type) id = Qualified(plain, md); + } + else + { + plain = md.Name.Length == 0 ? $"{parent.Plain}#{index}" : parent.Plain + CHILD_REF_SEPARATOR + md.Name; + id = md.Name.Length == 0 ? $"{parent.Id}#{index}" : parent.Id + CHILD_REF_SEPARATOR + md.Name; + // The first sibling of a name keeps the plain id: it is the one a dotted reference + // resolves to. A later sibling of another type sharing the name is qualified by type. + if (md.Name.Length != 0 && seen.Contains(id)) id = Qualified(id, md); + } + if (!seen.Add(id)) + throw new InvalidOperationException($"docs view: two nodes share the id \"{id}\" — the model names two siblings alike"); + bool isReq = md.Type == TYPE_REQUIREMENT; + string address = isReq ? (reqPrefix.Length == 0 ? md.Name : reqPrefix + CHILD_REF_SEPARATOR + md.Name) : reqPrefix; + bool inherited = parent is not null && !ReferenceEquals(md.Parent, parent.Md); + var w = new Walked + { + Md = md, + Id = id, + Plain = plain, + Parent = parent, + Order = index, + Canonical = parent is null || (parent.Canonical && !inherited), + DeclaredOn = inherited ? md.Parent : null, + Address = isReq ? address : "", + }; + w.Top = parent is null ? w : parent.Top; + w.Direct = parent is null ? null : parent.Parent is null ? w : parent.Direct; + w.Requirement = isReq ? w : parent?.Requirement; + if (ReferenceEquals(w.Direct, w)) w.Anchor = MemberAnchor(md, index); + _walked.Add(w); + _byId[id] = w; + if (w.Top.Id == w.Top.Plain) _byPlain.TryAdd(plain, w); + if (w.Canonical) _canonical[md] = w; + if (parent is null) _tops.Add(w); + else parent.Children.Add(w); + if (isReq) _requirements.Add(w); + var kids = md.Children(); + for (int i = 0; i < kids.Count; i++) Visit(kids[i], i, w, address, holder, seen); + } + + private static string PathOf(Walked w) + { + if (w.Requirement is { } r) + return $"requirements/{PackageDir(NamingRefs.EffectivePackageOf(r.Top.Md))}/{PageStem(r.Address)}.html"; + var top = w.Top; + string qualifier = $"[{top.Md.Type}{TYPE_SUBTYPE_SEPARATOR}{top.Md.SubType}]"; + string typed = top.Id.EndsWith(qualifier, StringComparison.Ordinal) ? $".{top.Md.Type}-{top.Md.SubType}" : ""; + string page = $"model/{PackageDir(NamingRefs.EffectivePackageOf(top.Md))}/{PageStem(top.Md.Name)}{typed}.html"; + return w.Direct is null ? page : $"{page}#{w.Direct.Anchor}"; + } + + private J Link(Walked w) + { + string label = ReferenceEquals(w.Requirement, w) + ? (Str(w.Md.Attr(DOC_ATTR_TITLE)) is { Length: > 0 } t ? t : w.Md.Name) + : ReferenceEquals(w, w.Top) + ? w.Md.Name + : w.Top.Md.Name + w.Id[w.Top.Id.Length..]; + return new J().Set("label", label).Set("id", w.Id).Set("path", w.Path) + .Set("kind", $"{w.Md.Type}{TYPE_SUBTYPE_SEPARATOR}{w.Md.SubType}").Set("unresolved", false); + } + + private J LinkTo(MetaData? md, string text) => + md is not null && _canonical.TryGetValue(md, out var w) ? Link(w) : Unresolved(text); + + /// The link a reference value lands on: the owner's row for the member its dotted + /// tail names (the owner's own row of an inherited member, as a claim lands), else the owner + /// the loader bound. + private J RefLink(MetaData? owner, string value) + { + if (owner is null) return Unresolved(value); + var (_, tail) = NamingRefs.SplitChildTail(value); + Walked? row = tail.Length == 0 ? null : _byPlain.GetValueOrDefault(owner.ResolutionKey() + tail); + return row is not null ? Link(row) : LinkTo(owner, value); + } + + // -------------------------------------------------------------- + // the build + // -------------------------------------------------------------- + + public J Run(JsonElement? verifyIn, JsonElement? manifest, JsonElement? routesIn) + { + var ledger = LedgerRows(verifyIn); + bool hasVerify = ledger is not null; + JsonElement? verify = verifyIn is { ValueKind: JsonValueKind.Object } ? verifyIn : null; + + // ── Requirements: claims first, since nodes and members list them. ── + var claimsOn = new Dictionary>(ReferenceEqualityComparer.Instance); + var reqLinks = new Dictionary>(ReferenceEqualityComparer.Instance); + var reqTargets = new Dictionary>(ReferenceEqualityComparer.Instance); + foreach (var r in _requirements) + { + var req = (MetaRequirement)r.Md; + string referrerPkg = RequirementCheck.EffectivePackage(req); + var links = new List(); + var targets = new List(); + foreach (var reference in req.ImplementedBy) + { + var split = RequirementClaims.SplitMemberRef(reference); + var node = RequirementClaims.ResolveClaimTarget(_root, split.Owner, referrerPkg); + var member = node is not null && split.Path.Count > 0 ? RequirementClaims.ResolveMember(node, split.Path) : node; + string key = node is null ? "" + : split.Path.Count == 0 ? node.ResolutionKey() + : node.ResolutionKey() + CHILD_REF_SEPARATOR + string.Join(CHILD_REF_SEPARATOR, split.Path); + Walked? w = member is not null ? _byPlain.GetValueOrDefault(key) : null; + if (w is null) + { + links.Add(ReqLink(reference, false, Unresolved(reference))); + continue; + } + links.Add(ReqLink(reference, true, Link(w))); + targets.Add(w); + var claim = new J() + .Set("requirement", Link(r)) + .Set("member", ReferenceEquals(w, w.Top) ? "" : MemberPath(w)) + .Set("status", req.Status ?? "") + .Set("level", req.Level); + // The claim is on the top-level node and on every member down to the one it names. + for (Walked? x = w; x is not null; x = x.Parent) Add(claimsOn, x, claim); + } + reqLinks[r] = links; + reqTargets[r] = targets; + } + + // ── Files and routes. ── + var filesOf = new Dictionary>>(ReferenceEqualityComparer.Instance); + bool hasManifest = manifest is { ValueKind: JsonValueKind.Object }; + if (hasManifest) + { + foreach (var e in manifest!.Value.EnumerateObject()) + { + if (e.Value.ValueKind != JsonValueKind.Object) continue; + string? sourceNode = StringOrNull(e.Value, "sourceNode"); + if (sourceNode is null || !_byPlain.TryGetValue(sourceNode, out var w)) continue; + if (!filesOf.TryGetValue(w.Top, out var by)) filesOf[w.Top] = by = new Dictionary>(StringComparer.Ordinal); + Add(by, StringOrNull(e.Value, "generatedBy") ?? "", e.Name); + } + } + var routesOf = new Dictionary>(ReferenceEqualityComparer.Instance); + bool hasRoutes = routesIn is { ValueKind: JsonValueKind.Array }; + if (hasRoutes) + { + foreach (var el in routesIn!.Value.EnumerateArray()) + { + if (el.ValueKind != JsonValueKind.Object) continue; + string? node = StringOrNull(el, "node"); + string? method = StringOrNull(el, "method"); + string? path = StringOrNull(el, "path"); + if (node is null || method is null || path is null || !_byPlain.TryGetValue(node, out var w)) continue; + // JavaScript's toUpperCase, locale-independent. + string upper = method.ToUpperInvariant(); + if (!routesOf.TryGetValue(w.Top, out var m)) routesOf[w.Top] = m = new Dictionary(StringComparer.Ordinal); + m[path + Nul + upper] = new J().Set("method", upper).Set("path", path); + } + } + + // ── Advisories. ── + var advisories = new List(); + if (hasVerify && verify is { } v + && v.TryGetProperty("requirements", out var reqsEl) && reqsEl.ValueKind == JsonValueKind.Object + && reqsEl.TryGetProperty("rows", out var rows) && rows.ValueKind == JsonValueKind.Array) + { + foreach (var d in rows.EnumerateArray()) + { + if (d.ValueKind != JsonValueKind.Object) continue; + string node = StringOrNull(d, "node") ?? ""; + J? subject = node.Length == 0 ? null : _byPlain.TryGetValue(node, out var w) ? Link(w.Top) : Unresolved(node); + advisories.Add(new J() + .Set("code", StringOrNull(d, "code") ?? "") + .Set("path", StringOrNull(d, "path") ?? "") + .Set("subject", subject) + .Set("severity", StringOrNull(d, "severity") ?? "") + .Set("source", StringOrNull(d, "source") ?? "") + .Set("message", StringOrNull(d, "message") ?? "")); + } + } + var unclaimedIds = new HashSet( + advisories.Where(a => a.Str("code") == RequirementCheck.WARN_REQUIREMENT_OBJECT_UNCLAIMED && a.Get("subject") is J) + .Select(a => ((J)a.Get("subject")!).Str("id")), + StringComparer.Ordinal); + + // ── Members and references. ── + var refsFrom = new Dictionary>(ReferenceEqualityComparer.Instance); + J Member(Walked w) + { + var (attrs, refs) = AttrsOf(w.Md); + J? ext = ExtendsLink(w.Md); + var own = new List(); + if (ext is not null && !(bool)ext.Get("unresolved")!) own.Add(Ref(ExtendsAttr, Link(w), ext)); + foreach (var (attr, target) in refs) own.Add(Ref(attr, Link(w), target)); + refsFrom[w] = own; + return new J() + .Set("id", w.Id) + .Set("name", w.Md.Name) + .Set("type", w.Md.Type) + .Set("subType", w.Md.SubType) + .Set("order", w.Order) + .Set("anchor", w.Anchor) + .Set("path", w.Path) + .Set("abstract", w.Md.IsAbstract) + .Set("isArray", w.Md.ResolvedIsArray()) + .Set("extends", ext) + .Set("declaredOn", w.DeclaredOn is not null ? LinkTo(w.DeclaredOn, w.DeclaredOn.Name) : null) + .Set("attrs", attrs) + .Set("refs", own) + .Set("claims", claimsOn.GetValueOrDefault(w) ?? []) + .Set("memberGroups", GroupMembers(w.Children.Select(Member).ToList())); + } + + var nodes = new List(); + var nodeRefs = new Dictionary>(ReferenceEqualityComparer.Instance); + foreach (var t in _tops) + { + var (attrs, refs) = AttrsOf(t.Md); + J? ext = ExtendsLink(t.Md); + var memberGroups = GroupMembers(t.Children.Select(Member).ToList()); + var all = new List(); + if (ext is not null && !(bool)ext.Get("unresolved")!) all.Add(Ref(ExtendsAttr, null, ext)); + foreach (var (attr, target) in refs) all.Add(Ref(attr, null, target)); + void Below(Walked w) + { + foreach (var c in w.Children) + { + all.AddRange(refsFrom.GetValueOrDefault(c) ?? []); + Below(c); + } + } + Below(t); + nodeRefs[t] = all; + var files = (filesOf.GetValueOrDefault(t) ?? new()) + .OrderBy(g => g.Key, StringComparer.Ordinal) + .Select(g => new J().Set("generatedBy", g.Key).Set("paths", g.Value.OrderBy(p => p, StringComparer.Ordinal).ToList())) + .ToList(); + int fileCount = (filesOf.GetValueOrDefault(t) ?? new()).Sum(g => g.Value.Count); + var routes = (routesOf.GetValueOrDefault(t) ?? new()).OrderBy(e => e.Key, StringComparer.Ordinal).Select(e => e.Value).ToList(); + var claims = claimsOn.GetValueOrDefault(t) ?? []; + nodes.Add(new J() + .Set("id", t.Id) + .Set("name", t.Md.Name) + .Set("package", NamingRefs.EffectivePackageOf(t.Md)) + .Set("type", t.Md.Type) + .Set("subType", t.Md.SubType) + .Set("order", t.Order) + .Set("path", t.Path) + .Set("title", Str(t.Md.Attr(DOC_ATTR_TITLE))) + .Set("description", Str(t.Md.Attr(DOC_ATTR_DESCRIPTION))) + .Set("summary", Str(t.Md.Attr(DOC_ATTR_SUMMARY))) + .Set("abstract", t.Md.IsAbstract) + .Set("extends", ext) + .Set("attrs", attrs) + .Set("memberGroups", memberGroups) + .Set("refs", all) + .Set("referencedBy", new List()) + .Set("claims", claims) + .Set("files", files) + .Set("routes", routes) + .Set("unclaimed", unclaimedIds.Contains(t.Id)) + .Set("counts", new J() + .Set("members", t.Children.Count) + .Set("refs", all.Count) + .Set("referencedBy", 0) + .Set("claims", claims.Count) + .Set("files", fileCount) + .Set("routes", routes.Count))); + } + + // referencedBy: every reference into a top-level node (or a member of it) from another one. + var nodeById = nodes.ToDictionary(n => n.Str("id"), StringComparer.Ordinal); + var incoming = new Dictionary>(StringComparer.Ordinal); + foreach (var t in _tops) + { + foreach (var r in nodeRefs.GetValueOrDefault(t) ?? []) + { + var target = (J)r.Get("target")!; + if (!_byId.TryGetValue(target.Str("id"), out var tw) || ReferenceEquals(tw.Top, t)) continue; + var via = r.Get("via") as J; + var referrer = new J().Set("attr", r.Get("attr")).Set("from", Link(t)).Set("via", via).Set("target", target); + string key = string.Join(Nul, t.Id, r.Str("attr"), via?.Str("id") ?? "", target.Str("id")); + if (!incoming.TryGetValue(tw.Top.Id, out var m)) incoming[tw.Top.Id] = m = new Dictionary(StringComparer.Ordinal); + m[key] = referrer; + } + } + foreach (var (id, m) in incoming) + { + if (!nodeById.TryGetValue(id, out var n)) continue; + var by = m.OrderBy(e => e.Key, StringComparer.Ordinal).Select(e => e.Value).ToList(); + n.Set("referencedBy", by); + ((J)n.Get("counts")!).Set("referencedBy", by.Count); + } + nodes.Sort((a, c) => string.CompareOrdinal(a.Str("id"), c.Str("id"))); + + // ── The requirement list, flat, in document order. ── + var reqChildren = new Dictionary>(ReferenceEqualityComparer.Instance); + static Walked? ReqParent(Walked r) => r.Parent?.Requirement; + foreach (var r in _requirements) + if (ReqParent(r) is { } p) Add(reqChildren, p, r); + void Subtree(Walked r, List outList) + { + outList.Add(r); + foreach (var c in reqChildren.GetValueOrDefault(r) ?? []) Subtree(c, outList); + } + string QualifiedPathOf(Walked x) + { + string p = RequirementCheck.EffectivePackage(x.Md); + return p.Length == 0 ? x.Address : p + PACKAGE_SEPARATOR + x.Address; + } + var requirements = new List(); + foreach (var r in _requirements) + { + var req = (MetaRequirement)r.Md; + string pkg = RequirementCheck.EffectivePackage(req); + string qualifiedPath = pkg.Length == 0 ? r.Address : pkg + PACKAGE_SEPARATOR + r.Address; + Ledger? row = null; + if (ledger is not null && ledger.TryGetValue(qualifiedPath, out var q) && q.Count > 0) row = q.Dequeue(); + var chain = new List(); + for (var p = ReqParent(r); p is not null; p = ReqParent(p)) chain.Insert(0, p); + var sub = new List(); + Subtree(r, sub); + var linked = sub.Where(x => + { + var xr = (MetaRequirement)x.Md; + int? level = xr.Level; + return (level ?? 0) >= REQUIREMENT_LEVEL_OBJECT || (level is null && xr.ImplementedBy.Count > 0); + }).ToList(); + List counted = linked.Count > 0 ? linked : [r]; + var statuses = counted.Select(x => ((MetaRequirement)x.Md).Status ?? "").Where(s => s.Length != 0).ToList(); + var targetTops = new SortedDictionary(StringComparer.Ordinal); + foreach (var x in sub) + foreach (var w in reqTargets.GetValueOrDefault(x) ?? []) targetTops.TryAdd(w.Top.Id, w.Top); + var children = reqChildren.GetValueOrDefault(r) ?? []; + J? supersededBy = null; + if (row is { HasSup: true }) + { + Walked? supTarget = row.SupTarget.Length == 0 ? null : _requirements.FirstOrDefault(x => QualifiedPathOf(x) == row.SupTarget); + supersededBy = ReqLink(row.SupRef, row.SupResolves, supTarget is not null ? Link(supTarget) : Unresolved(row.SupRef)); + } + requirements.Add(new J() + .Set("id", r.Id) + .Set("name", r.Md.Name) + .Set("label", Link(r).Str("label")) + .Set("path", r.Path) + .Set("address", r.Address) + .Set("package", pkg) + .Set("qualifiedPath", qualifiedPath) + .Set("subType", r.Md.SubType) + .Set("level", req.Level) + .Set("status", req.Status ?? "") + .Set("disposition", req.Disposition ?? "") + .Set("statement", Str(req.Attr(REQUIREMENT_ATTR_STATEMENT))) + .Set("counterexample", Str(req.Attr(REQUIREMENT_ATTR_COUNTEREXAMPLE))) + .Set("title", Str(req.Attr(DOC_ATTR_TITLE))) + .Set("description", Str(req.Attr(DOC_ATTR_DESCRIPTION))) + .Set("trackedBy", req.TrackedBy.ToList()) + .Set("depth", chain.Count) + .Set("parent", chain.Count > 0 ? Link(chain[^1]) : null) + .Set("breadcrumbs", chain.Select(Link).ToList()) + .Set("children", children.Select(Link).ToList()) + .Set("implementedBy", reqLinks.GetValueOrDefault(r) ?? []) + .Set("supersededBy", supersededBy) + .Set("inLedger", row is not null) + .Set("verdict", row?.Verdict ?? "") + .Set("digest", row?.Digest ?? "") + .Set("diagnostics", row?.Diagnostics ?? []) + .Set("rollup", StatusCounts(statuses)) + .Set("rollupTotal", statuses.Count) + .Set("belowCount", sub.Count - 1) + .Set("childCount", children.Count) + .Set("targets", targetTops.Values.Select(Link).ToList()) + .Set("targetCount", targetTops.Count)); + } + + // ── Packages, counts, slices. ── + var pkgNames = nodes.Select(n => n.Str("package")).Distinct().OrderBy(s => s, StringComparer.Ordinal).ToList(); + var packages = new List(); + foreach (var name in pkgNames) + { + var inPkg = nodes.Where(n => n.Str("package") == name).ToList(); + var groups = new SortedDictionary(StringComparer.Ordinal); + foreach (var n in inPkg) + { + string key = n.Str("type") + TYPE_SUBTYPE_SEPARATOR + n.Str("subType"); + if (!groups.TryGetValue(key, out var g)) + groups[key] = g = new J().Set("type", n.Str("type")).Set("subType", n.Str("subType")).Set("count", 0).Set("nodes", new List()); + g.Set("count", (int)g.Get("count")! + 1); + ((List)g.Get("nodes")!).Add(Link(_byId[n.Str("id")])); + } + packages.Add(new J().Set("name", name).Set("count", inPkg.Count).Set("groups", groups.Values.ToList())); + } + + JsonElement? vc = verify is { } vv && vv.TryGetProperty("requirementCounts", out var rc) && rc.ValueKind == JsonValueKind.Object ? rc : null; + object Num(string k) => vc is { } c && c.TryGetProperty(k, out var x) && x.ValueKind == JsonValueKind.Number ? x : 0; + var allFiles = new HashSet(StringComparer.Ordinal); + int routeCount = 0; + foreach (var n in nodes) + { + foreach (var g in (List)n.Get("files")!) foreach (var p in (List)g.Get("paths")!) allFiles.Add(p); + routeCount += ((List)n.Get("routes")!).Count; + } + var counts = new J() + .Set("nodes", nodes.Count) + .Set("packages", packages.Count) + .Set("requirements", requirements.Count) + .Set("functional", requirements.Count(r => r.Str("subType") == REQUIREMENT_SUBTYPE_FUNCTIONAL)) + .Set("architectural", requirements.Count(r => r.Str("subType") == REQUIREMENT_SUBTYPE_ARCHITECTURAL)) + .Set("byStatus", StatusCounts(requirements.Select(r => r.Str("status")).ToList())) + .Set("claims", requirements.Sum(r => ((List)r.Get("implementedBy")!).Count(l => (bool)l.Get("resolves")!))) + .Set("files", allFiles.Count) + .Set("routes", routeCount) + .Set("undecided", Num("undecided")) + .Set("coverageMeasured", Num("entitiesTotal") is JsonElement) + .Set("entitiesClaimed", Num("entitiesClaimed")) + .Set("entitiesTotal", Num("entitiesTotal")); + + return new J() + .Set("format", Format) + .Set("sources", new J().Set("requirements", hasVerify).Set("files", hasManifest).Set("routes", hasRoutes)) + .Set("counts", counts) + .Set("packages", packages) + .Set("nodes", nodes) + .Set("requirements", requirements) + .Set("advisories", advisories) + .Set("slices", Slices(nodes, requirements)); + } + + private List Slices(List nodes, List requirements) + { + var slices = new List(); + static List Sorted(IEnumerable s) => s.Distinct().OrderBy(x => x, StringComparer.Ordinal).ToList(); + foreach (var pkg in Sorted(nodes.Select(n => n.Str("package")))) + slices.Add(Slice("package", pkg, Sorted(nodes.Where(n => n.Str("package") == pkg).Select(n => n.Str("id"))))); + // A requirement with requirements below it: the subtree, each node it claims, and the + // top-level node holding a claimed member. + var byId = requirements.ToDictionary(r => r.Str("id"), StringComparer.Ordinal); + foreach (var r in requirements) + { + if ((int)r.Get("childCount")! == 0) continue; + var ids = new List(); + void Visit(J x) + { + ids.Add(x.Str("id")); + foreach (var l in (List)x.Get("implementedBy")!) + { + if (!(bool)l.Get("resolves")!) continue; + string tid = ((J)l.Get("target")!).Str("id"); + ids.Add(tid); + if (_byId.TryGetValue(tid, out var w)) ids.Add(w.Top.Id); + } + foreach (var c in (List)x.Get("children")!) + if (byId.TryGetValue(c.Str("id"), out var child)) Visit(child); + } + Visit(r); + slices.Add(Slice("requirement", r.Str("id"), Sorted(ids))); + } + // A template: itself and what its own attributes reference. + foreach (var n in nodes) + { + if (n.Str("type") != TYPE_TEMPLATE) continue; + var ids = new List { n.Str("id") }; + foreach (var r in (List)n.Get("refs")!) + { + if (r.Get("via") is not null) continue; + string tid = ((J)r.Get("target")!).Str("id"); + ids.Add(_byId.TryGetValue(tid, out var w) ? w.Top.Id : tid); + } + slices.Add(Slice("prompt", n.Str("id"), Sorted(ids))); + } + slices.Sort((a, c) => string.CompareOrdinal(a.Str("id"), c.Str("id"))); + return slices; + } + + private static J Slice(string kind, string anchor, List ids) => + new J().Set("id", $"{kind}:{anchor}").Set("kind", kind).Set("anchor", anchor).Set("nodes", ids); + + private J? ExtendsLink(MetaData md) + { + if (md.SuperData is null && md.SuperRef is null) return null; + return LinkTo(md.SuperData, md.AuthoredSuperRef ?? md.SuperRef ?? ""); + } + + /// A node's effective attributes, by name, each value linked where the loader resolved it. + private (List Attrs, List<(string Attr, J Target)> Refs) AttrsOf(MetaData md) + { + var attrs = new List(); + var refs = new List<(string, J)>(); + var map = md.Attrs(); + foreach (var name in map.Keys.OrderBy(k => k, StringComparer.Ordinal)) + { + object? value = CanonicalValue(map[name]); + bool isRef = NamingRefs.IsRefBearingAttr(md, name); + MetaData? declarer = isRef ? DeclaringLayer(md, name) : null; + var values = new List(); + if (value is string s) + { + J? link = isRef ? RefLink(declarer?.ResolvedTargetOf(name), s) : null; + values.Add(new J().Set("text", s).Set("link", link)); + if (link is not null && !(bool)link.Get("unresolved")!) refs.Add((name, link)); + } + else if (value is List list && list.All(x => x is string)) + { + var owners = declarer?.ResolvedTargetsOf(name); + for (int i = 0; i < list.Count; i++) + { + string item = (string)list[i]!; + MetaData? owner = owners is not null && i < owners.Count ? owners[i] : null; + J? link = isRef ? RefLink(owner, item) : null; + values.Add(new J().Set("text", item).Set("link", link)); + if (link is not null && !(bool)link.Get("unresolved")!) refs.Add((name, link)); + } + } + else + { + values.Add(new J().Set("text", DocsViewJson.Compact(ToNode(value))).Set("link", null)); + } + attrs.Add(new J().Set("name", name).Set("value", value).Set("values", values)); + } + return (attrs, refs); + } + } + + // ------------------------------------------------------------------ + // helpers + // ------------------------------------------------------------------ + + private static void Add(Dictionary> map, TK key, TV value) where TK : notnull + { + if (!map.TryGetValue(key, out var list)) map[key] = list = []; + list.Add(value); + } + + /// The layer that declares for : its own, + /// else the nearest extends ancestor's — where the loader recorded what the reference resolved to. + private static MetaData? DeclaringLayer(MetaData md, string name) + { + var seen = new HashSet(ReferenceEqualityComparer.Instance); + for (MetaData? n = md; n is not null && seen.Add(n); n = n.SuperData) + { + // ADR-0039: own — locating the layer that declares the attr, walking the super chain. + if (n.OwnHasAttr(name)) return n; + } + return null; + } + + /// An attribute value in the view's model, every object's keys in code-unit order, as + /// the canonical serializer writes them: a map attribute's key order must not depend on a + /// port's map type. + private static object? CanonicalValue(object? v) => v switch + { + null => null, + string or bool or long or double => v, + int i => (long)i, + float f => (double)f, + IReadOnlyDictionary map => map.Keys.OrderBy(k => k, StringComparer.Ordinal) + .Aggregate(new J(), (j, k) => j.Set(k, CanonicalValue(map[k]))), + IReadOnlyList strings => strings.Cast().ToList(), + System.Collections.IEnumerable list when v is not string => list.Cast().Select(CanonicalValue).ToList(), + _ => v.ToString(), + }; + + private static string Str(object? v) => v as string ?? ""; + + private static string Qualified(string id, MetaData md) => $"{id}[{md.Type}{TYPE_SUBTYPE_SEPARATOR}{md.SubType}]"; + + /// A direct member's anchor: m-<name> for a field, m-<type>-<name> + /// for anything else, m-<type>-<order> for one with no name. + private static string MemberAnchor(MetaData md, int order) + { + if (md.Name.Length == 0) return $"m-{md.Type}-{order}"; + return md.Type == TYPE_FIELD ? $"m-{md.Name}" : $"m-{md.Type}-{md.Name}"; + } + + /// A member's id after its top-level node's: email, items.price, or #3 with no name. + private static string MemberPath(Walked w) + { + string rest = w.Id[w.Top.Id.Length..]; + return rest.StartsWith(CHILD_REF_SEPARATOR, StringComparison.Ordinal) ? rest[CHILD_REF_SEPARATOR.Length..] : rest; + } + + /// The directory of a package's pages; -root for the empty package. + private static string PackageDir(string pkg) => + pkg.Length == 0 ? "-root" : string.Join("/", pkg.Split(PACKAGE_SEPARATOR)); + + /// A page's file stem: the name, unless it would take the package page's index.html. + private static string PageStem(string name) => + name.ToLowerInvariant() == "index" ? name + ".node" : name; + + private static J Unresolved(string text) => + new J().Set("label", text).Set("id", "").Set("path", "").Set("kind", "").Set("unresolved", true); + + private static J ReqLink(string reference, bool resolves, J target) => + new J().Set("ref", reference).Set("resolves", resolves).Set("target", target); + + private static J Ref(string attr, J? via, J target) => + new J().Set("attr", attr).Set("via", via).Set("target", target); + + private static List GroupMembers(List members) + { + var groups = new List(); + var byType = new Dictionary(StringComparer.Ordinal); + foreach (var m in members) + { + string type = m.Str("type"); + if (!byType.TryGetValue(type, out var g)) + { + byType[type] = g = new J().Set("type", type).Set("count", 0).Set("members", new List()); + groups.Add(g); + } + g.Set("count", (int)g.Get("count")! + 1); + ((List)g.Get("members")!).Add(m); + } + return groups; + } + + private static List StatusCounts(List statuses) => + REQUIREMENT_STATUSES.Select(status => new J().Set("status", status).Set("count", statuses.Count(s => s == status))).ToList(); + + private static Dictionary>? LedgerRows(JsonElement? verify) + { + if (verify is not { ValueKind: JsonValueKind.Object } v + || !v.TryGetProperty("requirementLedger", out var led) || led.ValueKind != JsonValueKind.Array) return null; + var outMap = new Dictionary>(StringComparer.Ordinal); + foreach (var raw in led.EnumerateArray()) + { + if (raw.ValueKind != JsonValueKind.Object) continue; + string? qp = StringOrNull(raw, "qualifiedPath"); + if (qp is null) continue; + var diags = new List(); + if (raw.TryGetProperty("diagnostics", out var ds) && ds.ValueKind == JsonValueKind.Array) + { + foreach (var d in ds.EnumerateArray()) + { + if (d.ValueKind != JsonValueKind.Object) continue; + diags.Add(new J() + .Set("code", StringOrNull(d, "code") ?? "") + .Set("severity", StringOrNull(d, "severity") ?? "") + .Set("source", StringOrNull(d, "source") ?? "") + .Set("message", StringOrNull(d, "message") ?? "")); + } + } + bool hasSup = raw.TryGetProperty("supersededBy", out var sup) && sup.ValueKind == JsonValueKind.Object && StringOrNull(sup, "ref") is not null; + var row = new Ledger(qp, StringOrNull(raw, "digest") ?? "", StringOrNull(raw, "verdict") ?? "", diags, + hasSup, + hasSup ? StringOrNull(sup, "ref") ?? "" : "", + hasSup && sup.TryGetProperty("resolves", out var res) && res.ValueKind == JsonValueKind.True, + hasSup ? StringOrNull(sup, "target") ?? "" : ""); + if (!outMap.TryGetValue(qp, out var q)) outMap[qp] = q = new Queue(); + q.Enqueue(row); + } + return outMap; + } + + private static string? StringOrNull(JsonElement o, string key) => + o.TryGetProperty(key, out var e) && e.ValueKind == JsonValueKind.String ? e.GetString() : null; +} diff --git a/server/csharp/MetaObjects/DocsView/DocsViewJson.cs b/server/csharp/MetaObjects/DocsView/DocsViewJson.cs new file mode 100644 index 0000000000..edf1967a85 --- /dev/null +++ b/server/csharp/MetaObjects/DocsView/DocsViewJson.cs @@ -0,0 +1,190 @@ +// JSON text exactly as JavaScript's JSON.stringify writes it, which is what the docs view contract +// states its bytes in (docs/features/docs-view.md): Pretty is JSON.stringify(v, null, 2), Compact +// is JSON.stringify(v). +// +// System.Text.Json's writer differs where byte parity matters: it escapes some characters +// JSON.stringify leaves alone and writes numbers in .NET's form. This writer escapes only what +// JSON.stringify escapes (the quote, the backslash, control characters and lone surrogates) and +// writes a number as a JavaScript Number prints. Mirrors the Java port's DocsViewJson. + +using System.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace MetaObjects; + +/// JSON text as JavaScript's JSON.stringify writes it. +public static class DocsViewJson +{ + /// Two-space indented JSON, as JSON.stringify(v, null, 2). + public static string Pretty(JsonNode? value) + { + var sb = new StringBuilder(); + Write(sb, value, "", pretty: true); + return sb.ToString(); + } + + /// JSON with no whitespace, as JSON.stringify(v). + public static string Compact(JsonNode? value) + { + var sb = new StringBuilder(); + Write(sb, value, "", pretty: false); + return sb.ToString(); + } + + /// A string as a JSON string literal, as JSON.stringify(s). + public static string Quote(string s) + { + var sb = new StringBuilder(s.Length + 2); + WriteString(sb, s); + return sb.ToString(); + } + + private static void Write(StringBuilder sb, JsonNode? value, string indent, bool pretty) + { + switch (value) + { + case null: + sb.Append("null"); + return; + case JsonObject obj: + { + if (obj.Count == 0) { sb.Append("{}"); return; } + string inner = indent + " "; + sb.Append('{'); + bool first = true; + foreach (var (k, v) in obj) + { + if (!first) sb.Append(','); + first = false; + if (pretty) sb.Append('\n').Append(inner); + WriteString(sb, k); + sb.Append(pretty ? ": " : ":"); + Write(sb, v, inner, pretty); + } + if (pretty) sb.Append('\n').Append(indent); + sb.Append('}'); + return; + } + case JsonArray arr: + { + if (arr.Count == 0) { sb.Append("[]"); return; } + string inner = indent + " "; + sb.Append('['); + for (int i = 0; i < arr.Count; i++) + { + if (i > 0) sb.Append(','); + if (pretty) sb.Append('\n').Append(inner); + Write(sb, arr[i], inner, pretty); + } + if (pretty) sb.Append('\n').Append(indent); + sb.Append(']'); + return; + } + case JsonValue v: + switch (v.GetValueKind()) + { + case JsonValueKind.String: WriteString(sb, v.GetValue()); return; + case JsonValueKind.True: sb.Append("true"); return; + case JsonValueKind.False: sb.Append("false"); return; + case JsonValueKind.Null: sb.Append("null"); return; + case JsonValueKind.Number: + if (v.TryGetValue(out long l)) sb.Append(Number(l)); + else if (v.TryGetValue(out int i)) sb.Append(Number(i)); + else sb.Append(Number(v.GetValue())); + return; + default: + sb.Append(v.ToJsonString()); + return; + } + } + } + + private static void WriteString(StringBuilder sb, string s) + { + sb.Append('"'); + for (int i = 0; i < s.Length; i++) + { + char c = s[i]; + switch (c) + { + case '"': sb.Append("\\\""); break; + case '\\': sb.Append("\\\\"); break; + case '\b': sb.Append("\\b"); break; + case '\f': sb.Append("\\f"); break; + case '\n': sb.Append("\\n"); break; + case '\r': sb.Append("\\r"); break; + case '\t': sb.Append("\\t"); break; + default: + if (c < 0x20) UnicodeEscape(sb, c); + else if (char.IsHighSurrogate(c)) + { + if (i + 1 < s.Length && char.IsLowSurrogate(s[i + 1])) sb.Append(c).Append(s[++i]); + else UnicodeEscape(sb, c); + } + else if (char.IsLowSurrogate(c)) UnicodeEscape(sb, c); + else sb.Append(c); + break; + } + } + sb.Append('"'); + } + + private static void UnicodeEscape(StringBuilder sb, char c) => + sb.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture)); + + /// An integer as a JavaScript Number prints it: exact up to 2^53, else the nearest double. + public static string Number(long v) => + Math.Abs(v) <= (1L << 53) ? v.ToString(CultureInfo.InvariantCulture) : Number((double)v); + + /// A number as JavaScript's Number.prototype.toString writes it. + public static string Number(double d) + { + if (double.IsNaN(d) || double.IsInfinity(d)) return "null"; + if (d == 0) return "0"; + // "R" gives the shortest digits that round-trip (.NET Core 3.0+), as JavaScript does. + string r = Math.Abs(d).ToString("R", CultureInfo.InvariantCulture); + int exp = 0; + int ePos = r.IndexOfAny(['E', 'e']); + if (ePos >= 0) + { + exp = int.Parse(r[(ePos + 1)..], NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture); + r = r[..ePos]; + } + int dot = r.IndexOf('.'); + string intPart = dot < 0 ? r : r[..dot]; + string fracPart = dot < 0 ? "" : r[(dot + 1)..]; + string all = intPart + fracPart; + // The decimal exponent n of ECMA-262 Number::toString: value = 0.digits x 10^n. + int e = intPart.Length + exp; + int lead = 0; + while (lead < all.Length - 1 && all[lead] == '0') lead++; + e -= lead; + string digits = all[lead..].TrimEnd('0'); + if (digits.Length == 0) return "0"; + int k = digits.Length; + var sb = new StringBuilder(); + if (d < 0) sb.Append('-'); + if (k <= e && e <= 21) + { + sb.Append(digits).Append('0', e - k); + } + else if (0 < e && e <= 21) + { + sb.Append(digits, 0, e).Append('.').Append(digits, e, k - e); + } + else if (-6 < e && e <= 0) + { + sb.Append("0.").Append('0', -e).Append(digits); + } + else + { + int x = e - 1; + sb.Append(digits[0]); + if (k > 1) sb.Append('.').Append(digits, 1, k - 1); + sb.Append('e').Append(x < 0 ? '-' : '+').Append(Math.Abs(x).ToString(CultureInfo.InvariantCulture)); + } + return sb.ToString(); + } +} diff --git a/server/csharp/MetaObjects/DocsView/ExplorerModelScript.cs b/server/csharp/MetaObjects/DocsView/ExplorerModelScript.cs new file mode 100644 index 0000000000..03df8ab05c --- /dev/null +++ b/server/csharp/MetaObjects/DocsView/ExplorerModelScript.cs @@ -0,0 +1,44 @@ +// The model explorer's data script (explorer-model.js) and its stamp (explorer-stamp.js), as every +// port writes them: `window.MO_MODEL = {"stamp":"",};`, +// where the stamp is the first 16 hex digits of the SHA-256 of that object's compact JSON without +// the stamp. Mirrors TypeScript's explorer-model script and the Java port's ExplorerModelScript. + +using System.Security.Cryptography; +using System.Text; +using System.Text.Json.Nodes; + +namespace MetaObjects; + +/// The explorer's model script and the stamp that names its content. +public sealed record ExplorerModelScript(string Script, string Stamp) +{ + /// Build the script for ; (prompt + /// texts by node id) and (owned page templates by file name) are + /// written in code-unit key order. + public static ExplorerModelScript Of(string title, string? footer, IReadOnlyDictionary? texts, + IReadOnlyDictionary? templates, JsonObject view) + { + var rest = new JsonObject + { + ["title"] = title, + ["footer"] = footer ?? "", + ["texts"] = Sorted(texts), + ["templates"] = Sorted(templates), + ["view"] = view.DeepClone(), + }; + string json = DocsViewJson.Compact(rest); + string stamp = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(json))).ToLowerInvariant()[..16]; + return new ExplorerModelScript("window.MO_MODEL = {\"stamp\":" + DocsViewJson.Quote(stamp) + "," + json[1..] + ";\n", stamp); + } + + /// The stamp script: window.MO_STAMP = "<stamp>";. + public static string StampScript(string stamp) => "window.MO_STAMP = " + DocsViewJson.Quote(stamp) + ";\n"; + + private static JsonObject Sorted(IReadOnlyDictionary? m) + { + var o = new JsonObject(); + if (m is null) return o; + foreach (var k in m.Keys.Order(StringComparer.Ordinal)) o[k] = m[k]; + return o; + } +} diff --git a/server/csharp/MetaObjects/MetaEndpoint.cs b/server/csharp/MetaObjects/MetaEndpoint.cs index 1af3a9bfe4..b87713def1 100644 --- a/server/csharp/MetaObjects/MetaEndpoint.cs +++ b/server/csharp/MetaObjects/MetaEndpoint.cs @@ -1,3 +1,4 @@ +using System.Text.Json.Nodes; using MetaObjects.Meta; namespace MetaObjects; @@ -17,6 +18,23 @@ namespace MetaObjects; /// Guard that route with your own authorization — /_meta publishes the /// shape of the model (entity and field names, types, validators, layouts), /// though no row data. +/// +/// Beside it, serves the same model as its docs view, the +/// document the model explorer reads (docs/features/metadata-api.md), under the same +/// opt-in and the same guard. Build one per loaded model, keep it, and +/// answer from it: +/// +/// +/// var docs = MetaEndpoint.MetaDocs(root); +/// app.MapGet($"/api{MetaEndpoint.MetaDocsRoutePath}", (HttpContext http) => +/// { +/// http.Response.Headers.ETag = docs.ETag; +/// http.Response.Headers.CacheControl = "no-cache"; +/// return docs.Matches(http.Request.Headers.IfNoneMatch) +/// ? Results.StatusCode(304) +/// : Results.Text(docs.Body, "application/json"); +/// }); +/// /// public static class MetaEndpoint { @@ -27,4 +45,65 @@ public static class MetaEndpoint /// The response body: the model as EFFECTIVE canonical JSON, so a browser /// reading it never has to resolve extends itself. public static string MetaJson(MetaData root) => SerializerJson.CanonicalSerializeEffective(root); + + /// The docs view endpoint's path, mounted under the host's API prefix beside + /// : a cross-port contract value, so the explorer reads + /// GET {apiPrefix}/_meta/docs from any backend. + public const string MetaDocsRoutePath = MetaRoutePath + "/docs"; + + /// The GET {apiPrefix}/_meta/docs response body: the loaded model's docs view, + /// built from the model alone, with the routes the application mounts when it passes them + /// ([{ node, method, path }]). + public static string MetaDocsJson(MetaData root, JsonNode? routes = null) => + DocsView.Serialize(DocsView.Build(root, null, null, routes)); + + /// The docs view of one loaded model, built once: the model is immutable after load. + public static Docs MetaDocs(MetaData root, JsonNode? routes = null) => new(MetaDocsJson(root, routes)); + + /// A built docs view body and its strong ETag. + public sealed class Docs + { + internal Docs(string body) + { + Body = body; + ETag = MetaDocsETag(body); + } + + /// The response body. + public string Body { get; } + + /// The strong ETag to send with it. + public string ETag { get; } + + /// Whether a request's If-None-Match names this body (answer 304). + public bool Matches(string? ifNoneMatch) => ETagMatches(ifNoneMatch, ETag); + } + + /// A strong ETag for a docs view body: its length and the 32-bit FNV-1a hash of its + /// UTF-16 code units, both in hex, quoted, the value every port's mount sends. The contract is + /// only that the tag changes when the body does; a client compares it and never parses it. + public static string MetaDocsETag(string body) + { + uint h = 0x811c9dc5; + foreach (char c in body) + { + h ^= c; + h = unchecked(h * 0x01000193); + } + return $"\"{body.Length:x}-{h:x8}\""; + } + + /// Whether an If-None-Match header value names , or is *. + /// A weak validator (W/) and a comma-separated list are accepted. + public static bool ETagMatches(string? ifNoneMatch, string etag) + { + if (string.IsNullOrEmpty(ifNoneMatch)) return false; + foreach (var t in ifNoneMatch.Split(',')) + { + var v = t.Trim(); + if (v.StartsWith("W/", StringComparison.Ordinal)) v = v[2..]; + if (v == "*" || v == etag) return true; + } + return false; + } } diff --git a/server/python/src/metaobjects/__init__.py b/server/python/src/metaobjects/__init__.py index dc77cedaba..4b5f0328d5 100644 --- a/server/python/src/metaobjects/__init__.py +++ b/server/python/src/metaobjects/__init__.py @@ -35,7 +35,15 @@ extract_schema_for, ) from .meta.core.object.value_object import ValueObject -from .meta_endpoint import META_ROUTE_PATH, meta_json +from .meta_endpoint import ( + META_DOCS_ROUTE_PATH, + META_ROUTE_PATH, + MetaDocs, + meta_docs, + meta_docs_etag, + meta_docs_json, + meta_json, +) from .naming import resolve_column_name from .serializer_json import canonical_serialize_effective @@ -65,6 +73,12 @@ # UI-1 — the metadata API contract (GET /_meta) "META_ROUTE_PATH", "meta_json", + # The docs view endpoint (GET /_meta/docs) and the docs view the model explorer reads + "META_DOCS_ROUTE_PATH", + "MetaDocs", + "meta_docs", + "meta_docs_etag", + "meta_docs_json", "canonical_serialize_effective", # Runtime object model (Phase A) "ValueObject", diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index 2b4fbaf273..536fc3f7f4 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -111,7 +111,7 @@ scan_requirements, summarise_requirements, ) -from metaobjects.codegen.config import DEFAULT_API_PREFIX, GenConfig +from metaobjects.codegen.config import DEFAULT_API_PREFIX, CaptureKeys, GenConfig, PlanRecord from metaobjects.codegen.overwrite_policy import ( STATUS_SKIPPED, STATUS_UNCHANGED, @@ -162,7 +162,7 @@ unsatisfied_requires, ) from metaobjects.codegen.project_import import import_project_symbol -from metaobjects.codegen.orphan_sweep import refused_orphan_message, sweep_orphans +from metaobjects.codegen.orphan_sweep import refused_orphan_message, sweep_orphans, sweep_scope from metaobjects.codegen.runner import run_gen from metaobjects.codegen import eject as owned from metaobjects.codegen.generators.render_helper_generator import ( @@ -1066,6 +1066,8 @@ def _run_suite( entity_scope: list[str] | None = None, manifest: HashManifest | None = None, sink: dict[str, str] | None = None, + capture_keys: CaptureKeys | None = None, + plan: PlanRecord | None = None, ) -> list[tuple[str, str]]: """Run a generator suite against an ALREADY-LOADED ``root`` into ``out_dir``. @@ -1121,6 +1123,8 @@ def _run_suite( overwrite_hand_edits=overwrite_hand_edits, manifest=manifest, sink=sink, + capture_keys=capture_keys, + plan=plan, ) # No default suite — see NO_GENERATORS_SELECTED. A caller that names none gets a # usage error and an empty out dir, never a shape this CLI picked. @@ -1717,6 +1721,7 @@ def _run_gen_targets( emitted_out: set[str] | None = None, skip_info: skip.SkipRunInfo | None = None, sink: dict[str, str] | None = None, + capture_for: Callable[[str], CaptureKeys] | None = None, ) -> tuple[list[str], list[str]]: """Run each target's declared generators into its ``outDir``. Returns (all_written, errors). @@ -1842,6 +1847,17 @@ def selected(gen: Generator, token: str) -> bool: skip_info.extra_entries = skip.extras_entries( Path(project_root or "."), skip_info.extras) + # The scope of the orphan sweep `gen` runs after this plan, in the real output directories + # (a verify render's slots stand in for them): the committed files a generator reading the + # run's output still lists are those it leaves alone. + real_dir = (lambda d: capture_for(d).out_dir) if capture_for is not None else (lambda d: d) + narrowed = selection is not None or any(t.run_selection is not None for t, *_ in plan) + swept = [] if narrowed or baseline == "adopt" else _sweep_dirs( + config, {t.name for t, *_ in plan}, + {real_dir(config.out_dir_for(t)) for t, gens, spec_gens, _o in plan if gens or spec_gens}, + ) + record = PlanRecord(swept=sweep_scope(swept, frozenset(config.out_dir_for(t) for t in config.targets))) + # ONE manifest session for the whole run (ADR-0064 decision 1), saved once at the end # and only when an entry changed. session = HashManifest(gen_state_dir) if gen_state_dir is not None else None @@ -1849,7 +1865,7 @@ def selected(gen: Generator, token: str) -> bool: return _run_plan( config, plan, root, seen, all_written, errors, session, template_root, gen_state_dir, project_root, baseline, refused_out, select, column_naming, - targeted_out, overwrite_paths_out, emitted_out, sink, in_ledger, + targeted_out, overwrite_paths_out, emitted_out, record, sink, in_ledger, capture_for, ) finally: if session is not None: @@ -1874,11 +1890,19 @@ def _run_plan( targeted_out: set[str] | None, overwrite_paths_out: set[str] | None, emitted_out: set[str] | None, + record: PlanRecord, sink: dict[str, str] | None = None, in_ledger: Callable[[str], bool] | None = None, + capture_for: Callable[[str], CaptureKeys] | None = None, ) -> tuple[list[str], list[str]]: from metaobjects.render.renderer import RenderError + # A target holding a generator that reads the run's output runs after every other target, + # so it lists the whole plan's files whatever the declared order (the stable sort keeps it). + plan = sorted( + plan, + key=lambda p: any(getattr(g, "reads_run_output", False) for g in (*p[1], *p[2])), + ) for t, gens, spec_gens, overwrite in plan: if not gens and not spec_gens: print(f"target '{t.name}' declares no generators; nothing written") @@ -1886,6 +1910,7 @@ def _run_plan( out_dir = config.out_dir_for(t) if targeted_out is not None: targeted_out.add(out_dir) + capture = capture_for(out_dir) if capture_for is not None else None results: list[tuple[str, str]] = [] try: if gens: @@ -1895,7 +1920,8 @@ def _run_plan( refused_out=refused_out, select=select, in_ledger=in_ledger, api_prefix=config.api_prefix, output_layout=config.output_layout, overwrite_hand_edits=overwrite, overwrite_paths_out=overwrite_paths_out, - manifest=session, sink=sink, entity_scope=t.entities, + manifest=session, sink=sink, entity_scope=t.entities, capture_keys=capture, + plan=record, ) if spec_gens: results = results + _run_suite( @@ -1904,7 +1930,7 @@ def _run_plan( project_root=project_root, baseline=baseline, refused_out=refused_out, select=select, in_ledger=in_ledger, api_prefix=config.api_prefix, output_layout=config.output_layout, manifest=session, sink=sink, - entity_scope=t.entities, + entity_scope=t.entities, capture_keys=capture, plan=record, ) except ValueError as exc: # intra-target run_gen collision → clean error errors.append(f"target '{t.name}': {exc}") @@ -2294,11 +2320,7 @@ def _sweep_orphans_after_gen( """ if baseline == "adopt": return [] - ran = {t.name for t in targets} - out_dirs = sorted( - out for out in targeted - if all(t.name in ran for t in config.targets if config.out_dir_for(t) == out) - ) + out_dirs = _sweep_dirs(config, {t.name for t in targets}, targeted) configured = frozenset(config.out_dir_for(t) for t in config.targets) narrowed = selection is not None or _parse_entities(getattr(args, "entities", None)) is not None if narrowed: @@ -2329,6 +2351,15 @@ def _sweep_orphans_after_gen( return result.removed +def _sweep_dirs(config: ProjectConfig, ran: set[str], targeted: set[str]) -> list[str]: + """The output directories a run of the targets named ``ran`` sweeps: each of ``targeted`` + (written into by a declared entry) whose every writing target ran.""" + return sorted( + out for out in targeted + if all(t.name in ran for t in config.targets if config.out_dir_for(t) == out) + ) + + def _overwrites_hand_edits(config: ProjectConfig, out_dir: str) -> bool: """True when every generator writing into ``out_dir`` is declared ``handEdits: overwrite``. @@ -2628,6 +2659,13 @@ def compare(naming: str) -> tuple[list[str], list[_DirReport]]: remapped = [ dataclasses.replace(t, out_dir=temp_for[config.out_dir_for(t)]) for t in closure ] + # Each slot keys its files at the real outDir it stands in for, against the real + # project, carrying what it does not render from the committed manifest (read only): + # what a generator reading the run's output (docs-site) lists is then what gen listed. + real_for = {str(Path(slot).resolve()): real for real, slot in temp_for.items()} + + def capture_for(slot: str) -> CaptureKeys: + return CaptureKeys(real_for[slot], gen_state_dir_for(config.metadata_dir())) # The exact gen pipeline, rendered into the in-memory sink — verify rejects exactly # what gen rejects (incl. the cross-target duplicate-output-path guard). @@ -2645,6 +2683,8 @@ def compare(naming: str) -> tuple[list[str], list[_DirReport]]: # R31: the `names` generator's constants are strategy-dependent, so the regen # must use the strategy `gen` wrote with, or every constant reads as drift. column_naming=naming, + project_root=str(project_root_for(config.metadata_dir())), + capture_for=capture_for, ) _written, errors = _run_gen_targets( config, remapped, root, selection=selection, targeted_out=targeted, @@ -2656,6 +2696,7 @@ def compare(naming: str) -> tuple[list[str], list[_DirReport]]: unnarrowed = [t for t in config.targets if config.out_dir_for(t) in temp_for] for real in temp_for: declared_for[real] = _temp_slot_for(Path(declared_root), real, config.config_dir) + real_for[str(Path(declared_for[real]).resolve())] = real _written, errors = _run_gen_targets( config, [dataclasses.replace(t, out_dir=declared_for[config.out_dir_for(t)]) diff --git a/server/python/src/metaobjects/codegen/config.py b/server/python/src/metaobjects/codegen/config.py index 09d6d48093..d6e7dd092c 100644 --- a/server/python/src/metaobjects/codegen/config.py +++ b/server/python/src/metaobjects/codegen/config.py @@ -2,6 +2,7 @@ from __future__ import annotations from dataclasses import dataclass, field +from pathlib import Path from metaobjects.naming import DEFAULT_COLUMN_NAMING @@ -11,6 +12,27 @@ DEFAULT_API_PREFIX = "/api" +@dataclass(frozen=True) +class CaptureKeys: + """How a run that writes nothing (``verify --codegen``) keys what it renders, so it renders + what ``gen`` writes: each file at the real ``out_dir`` it stands in for, and the files it + does not render carried from the committed manifest under ``gen_state_dir``, read only.""" + + out_dir: str + gen_state_dir: str | None + + +@dataclass +class PlanRecord: + """What the runs of one plan (``gen``'s targets, or ``verify --codegen``'s render of them) + have emitted so far, keyed as the manifest keys it, and the scope of the orphan sweep that + follows the plan (``orphan_sweep.sweep_scope``; empty when it sweeps nothing). A generator + reading the run's output lists these over the committed files the sweep leaves alone.""" + + files: dict[str, tuple[str, str | None]] = field(default_factory=dict) + swept: list[tuple[Path, list[Path]]] = field(default_factory=list) + + @dataclass class GenConfig: out_dir: str @@ -84,9 +106,17 @@ class GenConfig: # ``{path: content}`` instead. ``verify --codegen`` renders into it and compares the bytes # with disk in memory, so it creates no temp tree. sink: dict[str, str] | None = None + capture_keys: CaptureKeys | None = None + plan: PlanRecord | None = None provided_enum_namespace: str | None = None provided_enum_packages: dict[str, str] = field(default_factory=dict) + def committed_gen_state_dir(self) -> str | None: + """Where the committed manifest is read from: the run's gen-state dir, or a capture run's.""" + if self.gen_state_dir is not None: + return self.gen_state_dir + return self.capture_keys.gen_state_dir if self.capture_keys is not None else None + def __post_init__(self) -> None: """Refuse a value this port cannot honour, instead of accepting it and ignoring it. diff --git a/server/python/src/metaobjects/codegen/generator.py b/server/python/src/metaobjects/codegen/generator.py index bf85edc254..ea689e7d65 100644 --- a/server/python/src/metaobjects/codegen/generator.py +++ b/server/python/src/metaobjects/codegen/generator.py @@ -52,6 +52,10 @@ class GenContext: #: run; a per-entity file honours this as well (``per_entity`` applies it). ``None``: #: every entity is selected. selected: Callable[[MetaObject], bool] | None = None + #: For a generator with ``reads_run_output = True`` (the runner runs it after every other + #: one): what the others emitted in this run, ``manifest key -> (generated_by, + #: source_node)``, keyed as the hash manifest keys it. ``None`` for any other generator. + run_provenance: dict[str, tuple[str, str | None]] | None = None def is_selected(self, entity: MetaObject) -> bool: return self.selected is None or self.selected(entity) @@ -69,6 +73,9 @@ class Generator(Protocol): - ``cacheable: bool`` (default ``True``). ``False`` means the generator reads something nobody can declare; a run that includes it never skips. + - ``reads_run_output: bool`` (default ``False``). ``True`` means the generator lists the + files the other generators emitted (``GenContext.run_provenance``); the runner runs + every such generator after all the others. - ``declared_extra_inputs: tuple[str, ...]`` (default ``()``). Project-relative paths the generator reads beyond the model, the config and the template roots; their content is part of the run's key. diff --git a/server/python/src/metaobjects/codegen/generator_registry.py b/server/python/src/metaobjects/codegen/generator_registry.py index da2287b029..4d7d0caa3b 100644 --- a/server/python/src/metaobjects/codegen/generator_registry.py +++ b/server/python/src/metaobjects/codegen/generator_registry.py @@ -30,6 +30,7 @@ from metaobjects.codegen.project_config import DEFAULT_REQUIREMENT_WITNESS_MODULE, ApiDocsConfig from metaobjects.codegen.generators.agent_docs_generator import agent_docs_generator from metaobjects.codegen.generators.api_docs_generator import api_docs_generator +from metaobjects.codegen.generators.docs_site_generator import docs_site_generator from metaobjects.codegen.generators.entity_model import entity_model, model_import_closure from metaobjects.codegen.generators.extractor_generator import extractor_generator from metaobjects.codegen.generators.filter_allowlist_generator import ( @@ -563,6 +564,28 @@ def _render_helper_default(ctx: GeneratorBuildContext) -> Generator: source=agent_docs_generator, runtime=(_DOCS_REQUIREMENTS, _DOCS_SCHEMA), ), + "docs-site": GeneratorEntry( + name="docs-site", + description=( + "The model explorer: one browser app over the project's docs view (the app, its data " + "script, its stamp and explorer.json under site/), written with no Node on the path. " + "A project that owns the theme (codegen/docs-site/) has it used in place of the packaged one." + ), + tier="neutral", + layer="docs", + factory=lambda ctx: docs_site_generator(**ctx.options), + # Not ejectable: the site builder is engine (ADR-0034 Amendment 9); what an adopter owns + # is the theme under codegen/docs-site/. + source=None, + options=( + GeneratorOption("subDir", "string", description="The directory under the target the site lands in (default site; empty writes at the target's root)."), + GeneratorOption("title", "string", description="The project's name as the header prints it (default: the project directory's name)."), + GeneratorOption("stamp", "string", description="Footer text (default none, so the site depends on the model alone)."), + GeneratorOption("prompts", "string", description="A directory, relative to the project, holding prompt .mustache sources outside the metadata directories and templates/."), + GeneratorOption("verifyFile", "string", description="A `verify --format json` payload, relative to the project, whose requirement rows the explorer shows."), + GeneratorOption("routesFile", "string", description="The routes the application mounts, [{ node, method, path }], relative to the project."), + ), + ), } @@ -571,6 +594,27 @@ def list_generators() -> list[GeneratorEntry]: return sorted(GENERATOR_REGISTRY.values(), key=lambda e: e.name) +_STABLE_BY_NAME: dict[str, str] | None = None + + +def stable_name_of(generator_name: str) -> str: + """The stable registry name of the generator whose ``name`` is ``generator_name``, as the + hash manifest's ``generatedBy`` provenance names it in every port (``filter-allowlist``, + not the ``filter-allowlist-generator`` its ``name`` answers). An ejected copy keeps the name + it was copied with, so it maps too; a name the registry does not know (a project's own + generator, a template entry) is returned as it is.""" + global _STABLE_BY_NAME + if _STABLE_BY_NAME is None: + mapping: dict[str, str] = {} + for key, entry in GENERATOR_REGISTRY.items(): + try: + mapping.setdefault(entry.factory(GeneratorBuildContext()).name, key) + except Exception: # noqa: BLE001 - an entry that needs options has no default name to map + continue + _STABLE_BY_NAME = mapping + return _STABLE_BY_NAME.get(generator_name, generator_name) + + def get_generator(name: str) -> GeneratorEntry | None: """Resolve a generator entry by its stable id, or ``None`` if unknown.""" return GENERATOR_REGISTRY.get(name) diff --git a/server/python/src/metaobjects/codegen/generators/docs_site_generator.py b/server/python/src/metaobjects/codegen/generators/docs_site_generator.py new file mode 100644 index 0000000000..e0626101f9 --- /dev/null +++ b/server/python/src/metaobjects/codegen/generators/docs_site_generator.py @@ -0,0 +1,262 @@ +"""``docs-site`` -- the model explorer: one browser app over the project's docs view, written +with no Node on the path (the Python side of TypeScript's ``docsSiteFile()``, ``output: "app"``). + +It builds the docs view from the loaded model (:func:`metaobjects.docs_view.build_docs_view`), +lists the files generated for each node (``generatedBy`` and ``sourceNode``: this run's output, +laid over what the committed hash manifest already records), and writes under ``site/``: + + index.html, assets/explorer-app.js, the app: the same bytes in every port, from the + assets/cytoscape.min.js, package data ``documentation/explorer_app/`` + assets/3d-force-graph.min.js (``scripts/sync-explorer-app.sh`` refreshes it) + assets/explorer.css, assets/explorer.js the theme, or the project's owned copy + explorer-model.js the docs view, the prompt texts, the title, the + footer and any owned templates, as one script + explorer-stamp.js the model's hash, which the open app polls + explorer.json the docs view itself, byte for byte + +The runner runs it after every other generator (``reads_run_output``), so it sees the whole +run's output. A project that owns the explorer's theme (``meta eject docs-site`` copies it into +``codegen/docs-site/``) has its ``assets/explorer.css``, ``assets/explorer.js`` and +``templates/explorer-*.mustache`` used in place of the packaged ones. The page-per-screen static +export (``output: "static"``) draws its pages with the TypeScript page code and stays there. + +Options (``options:`` on the ``generators`` entry): ``subDir`` (default ``site``; empty writes at +the target's root), ``title`` (default: the project directory's name), ``stamp`` (footer text, +default none, so the site depends on the model alone), ``prompts`` (a directory, relative to the +project, holding prompt ``.mustache`` sources outside the metadata directories and ``templates/``), +``verifyFile`` (a ``verify --format json`` payload whose requirement rows the explorer shows) and +``routesFile`` (the routes the application mounts, ``[{ node, method, path }]``, ``node`` a +resolution key). +""" +from __future__ import annotations + +import json +import os +from importlib import resources +from pathlib import Path +from typing import Any + +from metaobjects.codegen.generator import EmittedFile, GenContext, Generator +from metaobjects.codegen.overwrite_policy import _read_union +from metaobjects.docs_view import ( + build_docs_view, + explorer_model_script, + explorer_stamp_script, + serialize_docs_view, +) +from metaobjects.meta.template.template_constants import TEMPLATE_ATTR_TEXT_REF + +DEFAULT_SUB_DIR = "site" +#: Where an owned explorer theme lives, under the project (TypeScript's ``OWNED_DOCS_SITE_DIR``). +OWNED_DOCS_SITE_DIR = "codegen/docs-site" + +MODEL_FILE = "explorer-model.js" +STAMP_FILE = "explorer-stamp.js" +VIEW_FILE = "explorer.json" + +#: The app's files: every port ships the same bytes (TypeScript's ``EXPLORER_APP_FILES``). +APP_FILES = ( + "index.html", + "assets/explorer-app.js", + "assets/explorer.css", + "assets/explorer.js", + "assets/cytoscape.min.js", + "assets/3d-force-graph.min.js", +) +#: The theme pair a project may own (``assets/`` under the owned docs-site directory). +THEME_ASSETS = ("explorer.css", "explorer.js") +#: The templates an owned theme may replace; the app uses an owned one in place of its own. +TEMPLATE_NAMES = ( + "explorer-head.mustache", + "explorer-foot.mustache", + "explorer-card.mustache", + "explorer-overview.html.mustache", + "explorer-map.html.mustache", + "explorer-object.html.mustache", + "explorer-node.html.mustache", + "explorer-prompt.html.mustache", + "explorer-prompts.html.mustache", + "explorer-requirements.html.mustache", + "explorer-requirement.html.mustache", + "explorer-matrix.html.mustache", + "explorer-trace.html.mustache", + "explorer-gaps.html.mustache", + "explorer-api.html.mustache", + "explorer-model.html.mustache", + "explorer-package.html.mustache", +) + + +def _app_resource(rel: str) -> str: + node = resources.files("metaobjects.documentation").joinpath("explorer_app") + for part in rel.split("/"): + node = node.joinpath(part) + return node.read_text(encoding="utf-8") + + +def _read_if_present(directory: Path | None, name: str) -> str | None: + if directory is None: + return None + p = directory / name + return p.read_text(encoding="utf-8") if p.is_file() else None + + +def read_prompt_texts(view: dict[str, Any], dirs: list[Path]) -> dict[str, str]: + """Each prompt's ``.mustache`` text from the directories its ``@textRef`` resolves in, by + template node id. A ref that is absolute or climbs out with ``..`` is not read, so a model + cannot pull an arbitrary file into a published page.""" + out: dict[str, str] = {} + for n in view["nodes"]: + ref: str | None = None + for a in n["attrs"]: + if a["name"] == TEMPLATE_ATTR_TEXT_REF and isinstance(a["value"], str): + ref = a["value"] + if ref is None: + continue + segments = ref.replace("\\", "/").split("/") + if ref.startswith(("/", "\\")) or os.path.isabs(ref) or any(s in ("", "..") for s in segments): + continue + for d in dirs: + p = d.joinpath(*segments[:-1], segments[-1] + ".mustache") + if p.is_file(): + out[n["id"]] = p.read_text(encoding="utf-8") + break + return dict(sorted(out.items())) + + +def emit_site( + view: dict[str, Any], + title: str, + footer: str, + texts: dict[str, str], + assets_dir: Path | None, + templates_dir: Path | None, +) -> dict[str, str]: + """Every file of the site, site-relative, in write order.""" + files: dict[str, str] = {} + for f in APP_FILES: + if f.startswith("assets/") and f[len("assets/"):] in THEME_ASSETS: + continue + files[f] = _app_resource(f) + for a in THEME_ASSETS: + owned = _read_if_present(assets_dir, a) + files["assets/" + a] = owned if owned is not None else _app_resource("assets/" + a) + templates: dict[str, str] = {} + for name in TEMPLATE_NAMES: + owned = _read_if_present(templates_dir, name) + if owned is not None: + templates[name] = owned + script, stamp = explorer_model_script(title, footer, texts, templates, view) + files[MODEL_FILE] = script + files[STAMP_FILE] = explorer_stamp_script(stamp) + files[VIEW_FILE] = serialize_docs_view(view) + return files + + +def _read_json(path: Path) -> Any: + try: + return json.loads(path.read_text(encoding="utf-8")) + except OSError as e: + raise ValueError(f"docs-site: could not read {path}: {e}") from e + + +class DocsSiteGenerator: + """Writes the model explorer site.""" + + name = "docs-site" + #: The runner runs a generator that reads the run's output after every other one. + reads_run_output = True + + def __init__( + self, + sub_dir: str = DEFAULT_SUB_DIR, + title: str | None = None, + stamp: str = "", + prompts: str | None = None, + verify_file: str | None = None, + routes_file: str | None = None, + ) -> None: + self.sub_dir = sub_dir.strip("/") + self.title = title + self.stamp = stamp + self.prompts = prompts + self.verify_file = verify_file + self.routes_file = routes_file + #: The owned theme, the prompts directory and the verify and routes files are read beside + #: the model (ADR-0064): editing one regenerates. The hash manifest is not an input: the + #: files the site lists are this run's and the manifest's, and the whole-run skip already + #: re-runs when the manifest gains, loses or changes a file. + self.declared_extra_inputs: tuple[str, ...] = tuple( + p for p in (OWNED_DOCS_SITE_DIR, prompts, verify_file, routes_file) if p + ) + + def generate(self, ctx: GenContext) -> list[EmittedFile]: + config = ctx.config + # A run that names no project finds no owned theme or templates through the process's + # working directory, which may change between gen and verify; paths the options name + # explicitly still resolve against it. + known = bool(config.project_root) + project = Path(config.project_root or os.getcwd()).resolve() + verify = _read_json(project / self.verify_file) if self.verify_file else None + routes = _read_json(project / self.routes_file) if self.routes_file else None + generated = self._provenance(ctx) + root = ctx.loaded_root + if root is None: + raise ValueError("docs-site: needs a loaded model") + view = build_docs_view(root, verify, generated, routes) + + owned = project / OWNED_DOCS_SITE_DIR + files = emit_site( + view, + self.title if self.title is not None else ((project.name if known else "") or "Metadata"), + self.stamp, + read_prompt_texts(view, self._prompt_dirs(root, project, known)), + owned / "assets" if known and (owned / "assets").is_dir() else None, + owned / "templates" if known and (owned / "templates").is_dir() else None, + ) + prefix = f"{self.sub_dir}/" if self.sub_dir else "" + return [EmittedFile(path=prefix + rel, content=content) for rel, content in files.items()] + + @staticmethod + def _provenance(ctx: GenContext) -> dict[str, Any] | None: + """``path -> { generatedBy, sourceNode }`` as the docs view reads it. In a run, the + runner's list (this run's files, after the committed ones its orphan sweep leaves alone), + even when empty; outside a run, what the committed hash manifest records. ``None`` with + no manifest.""" + out: dict[str, Any] = {} + if ctx.run_provenance is not None: + for path, (by, node) in ctx.run_provenance.items(): + if node is not None: + out[path] = {"generatedBy": by, "sourceNode": node} + return out + gen_state = ctx.config.committed_gen_state_dir() + if gen_state is None: + return None + raw, _where = _read_union(gen_state) + for path, entry in raw.items(): + if isinstance(entry, dict) and isinstance(entry.get("sourceNode"), str): + out[path] = {"generatedBy": entry.get("generatedBy", ""), "sourceNode": entry["sourceNode"]} + return out if raw else None + + def _prompt_dirs(self, root: Any, project: Path, config_known: bool = True) -> list[Path]: + """Where prompt ``.mustache`` sources are looked for: the directories the model was + loaded from, the project's ``templates/`` and the ``prompts`` directory, each once.""" + dirs: dict[Path, None] = {} + for node in root.children(): + for f in getattr(node.source, "files", ()) or (): + parent = Path(f).resolve().parent + dirs.setdefault(parent, None) + templates = project / "templates" + if config_known and templates.is_dir(): + dirs.setdefault(templates, None) + if self.prompts: + p = (project / self.prompts).resolve() + if p.is_dir(): + dirs.setdefault(p, None) + return list(dirs) + + +def docs_site_generator(**options: Any) -> Generator: + """The registry's ``source=``, and so the symbol an ejected copy is wired by. Takes the + entry's options as keyword arguments (``verifyFile`` -> ``verify_file``).""" + return DocsSiteGenerator(**options) diff --git a/server/python/src/metaobjects/codegen/orphan_sweep.py b/server/python/src/metaobjects/codegen/orphan_sweep.py index c630568596..b7a78a27cd 100644 --- a/server/python/src/metaobjects/codegen/orphan_sweep.py +++ b/server/python/src/metaobjects/codegen/orphan_sweep.py @@ -71,6 +71,21 @@ def _walk(out_dir: Path, nested: list[Path] | None = None) -> list[Path]: return files +def sweep_scope( + out_dirs: list[str], exclude_nested: frozenset[str] = frozenset() +) -> list[tuple[Path, list[Path]]]: + """Each directory a sweep over ``out_dirs`` walks, with the output directories nested in it + (swept ones and ``exclude_nested``), whose files it leaves alone.""" + resolved = list(dict.fromkeys(Path(out).resolve() for out in out_dirs)) + every_dir = set(resolved) | {Path(out).resolve() for out in exclude_nested} + return [(o, [n for n in every_dir if n != o and n.is_relative_to(o)]) for o in resolved] + + +def in_sweep_scope(path: Path, scope: list[tuple[Path, list[Path]]]) -> bool: + """Whether a sweep over ``scope`` removes ``path`` when no generator of the run emits it.""" + return any(path.is_relative_to(out) and not _under(path, nested) for out, nested in scope) + + def _remove_empty_parents(path: Path, out_dirs: list[Path]) -> None: """After deleting *path*, remove the subpackage directories it leaves empty (the package output layout puts files in ``acme/alpha/``), never an output directory itself.""" @@ -113,10 +128,9 @@ def sweep_orphans( emitted_real = {os.path.realpath(p) for p in emitted} forget: set[str] = set() - resolved = list(dict.fromkeys(Path(out).resolve() for out in out_dirs)) - every_dir = set(resolved) | {Path(out).resolve() for out in exclude_nested} - for out_path in resolved: - nested = [o for o in every_dir if o != out_path and o.is_relative_to(out_path)] + scope = sweep_scope(out_dirs, exclude_nested) + resolved = [out for out, _nested in scope] + for out_path, nested in scope: # The out dir relative to the project: the prefix that turns an out-dir-relative # name into a manifest key. Both sides resolved, as `cli._out_prefix` does. prefix = os.path.relpath(out_path, root) diff --git a/server/python/src/metaobjects/codegen/overwrite_policy.py b/server/python/src/metaobjects/codegen/overwrite_policy.py index 2fa432370b..20c788fd1a 100644 --- a/server/python/src/metaobjects/codegen/overwrite_policy.py +++ b/server/python/src/metaobjects/codegen/overwrite_policy.py @@ -282,6 +282,16 @@ def _read_manifest_file(gen_state_dir: str) -> dict[str, object]: return _read_union(gen_state_dir)[0] +def read_recorded_provenance(gen_state_dir: str) -> dict[str, tuple[str, str]]: + """``path -> (generatedBy, sourceNode)`` for every committed entry that names its node.""" + out: dict[str, tuple[str, str]] = {} + for path, entry in _read_union(gen_state_dir)[0].items(): + if isinstance(entry, dict) and isinstance(entry.get("sourceNode"), str): + by = entry.get("generatedBy", "") + out[path] = (by if isinstance(by, str) else "", entry["sourceNode"]) + return out + + def _entry_hash(value: object) -> str | None: if isinstance(value, str): return value diff --git a/server/python/src/metaobjects/codegen/runner.py b/server/python/src/metaobjects/codegen/runner.py index a1f1da37bf..b7e8794795 100644 --- a/server/python/src/metaobjects/codegen/runner.py +++ b/server/python/src/metaobjects/codegen/runner.py @@ -3,6 +3,7 @@ import os import re +from pathlib import Path from dataclasses import dataclass, field from typing import Callable @@ -13,11 +14,12 @@ from metaobjects.meta.core.reporting.report_read_model import report_read_model from metaobjects.shared.base_types import TYPE_OBJECT from .collection_name_collision import assert_no_collection_name_collisions -from .config import GenConfig +from .config import GenConfig, PlanRecord from .constants import generated_package_init from .generator import GenContext, Generator from .import_path import OUTPUT_LAYOUT_PACKAGE from .name_claims import NameClaims, assert_importable_package_tree +from .orphan_sweep import in_sweep_scope from .instance_artifacts import is_served_report from .overwrite_policy import ( STATUS_OVERWROTE_EDIT, @@ -26,6 +28,7 @@ has_hash_manifest, manifest_batch, objects_of_root, + read_recorded_provenance, set_placement_objects, ) @@ -73,6 +76,46 @@ def warn(msg: str) -> None: return warn +def _manifest_key(config: GenConfig, full: str) -> str: + """The key the hash manifest records ``full`` under (see ``_write_all``); a capture run's + file is keyed at the real output directory it stands in for.""" + if config.capture_keys is not None: + full = os.path.join(config.capture_keys.out_dir, os.path.relpath(full, config.out_dir)) + if config.project_root: + return os.path.relpath(os.path.realpath(full), config.project_root).replace(os.sep, "/") + return os.path.relpath(full, config.out_dir).replace(os.sep, "/") + + +def _run_provenance( + config: GenConfig, + emitted: dict[str, tuple[str, str]], + sources: dict[str, str], +) -> dict[str, tuple[str, str | None]]: + """What the generators that ran before this one emitted, in this run and in the earlier runs + of its plan, keyed as the manifest keys it, after the committed manifest's files the plan's + orphan sweep leaves alone. A recorded file inside the sweep is either emitted again (and so + listed) or deleted, so the list never names a file the run removes.""" + plan = config.plan or PlanRecord() + committed = config.committed_gen_state_dir() + recorded = read_recorded_provenance(committed) if committed is not None else {} + project = Path(config.project_root).resolve() if config.project_root else None + carried: dict[str, tuple[str, str | None]] = { + path: prov for path, prov in recorded.items() + if project is None or not in_sweep_scope((project / path).resolve(), plan.swept) + } + carried.update(plan.files) + for full, (_c, by) in emitted.items(): + carried[_manifest_key(config, full)] = (_stable_name(by), sources.get(full)) + return carried + + +def _stable_name(generator_name: str) -> str: + """What the manifest's ``generatedBy`` calls a generator: its stable registry name.""" + from .generator_registry import stable_name_of # the registry imports the generators + + return stable_name_of(generator_name) + + def run_gen( config: GenConfig, metadata: MetaData, @@ -196,7 +239,11 @@ def is_selected(o: MetaObject) -> bool: emitted: dict[str, tuple[str, str]] = {} # full_path -> (content, generated_by) # full_path -> the resolution key of the node the file was rendered from, when it was. sources: dict[str, str] = {} - for gen in generators: + # A generator that reads the run's output runs after every other one, so it sees all of it + # (the stable sort keeps the declared order among the rest). + ordered = sorted(generators, key=lambda g: bool(getattr(g, "reads_run_output", False))) + for gen in ordered: + reads_output = bool(getattr(gen, "reads_run_output", False)) ctx = GenContext( entities=safe, loaded_root=metadata, @@ -207,6 +254,9 @@ def is_selected(o: MetaObject) -> bool: in_ledger=in_ledger, claims=claims, selected=is_selected if narrowed else None, + run_provenance=( + _run_provenance(config, emitted, sources) if reads_output else None + ), ) for f in gen.generate(ctx): full = os.path.join(config.out_dir, f.path) @@ -218,6 +268,11 @@ def is_selected(o: MetaObject) -> bool: emitted[full] = (f.content, gen.name) if f.source_node is not None: sources[full] = f.source_node + if config.plan is not None: + config.plan.files.update( + (_manifest_key(config, full), (_stable_name(by), sources.get(full))) + for full, (_c, by) in emitted.items() + ) if config.output_layout == OUTPUT_LAYOUT_PACKAGE: assert_importable_package_tree( @@ -334,7 +389,7 @@ def _write_all( # Only with a real project root, as codegen-ts: the entry is keyed by the same key # the write used, and the session's save applies it to entries that hold a hash. if session is not None and not outside and config.project_root: - session.note_provenance(key, by, sources.get(full)) + session.note_provenance(key, _stable_name(by), sources.get(full)) if status == STATUS_OVERWROTE_EDIT: result.warnings.append( f"overwrote hand-edited {rel} with fresh output (handEdits: overwrite on {by})" diff --git a/server/python/src/metaobjects/docs_view.py b/server/python/src/metaobjects/docs_view.py new file mode 100644 index 0000000000..f3909fe8f9 --- /dev/null +++ b/server/python/src/metaobjects/docs_view.py @@ -0,0 +1,850 @@ +"""The docs view of a loaded model: one port-neutral document, the facts every documentation +page reads and what the model explorer draws (``docs/features/docs-view.md``). + +The Python port of TypeScript's ``buildDocsView`` (``@metaobjectsdev/metadata``, +``src/docs-view/build.ts``), held to the same bytes by ``fixtures/explorer-conformance/``. +It reads the model the loader built and resolved and re-derives none of it: ids and pages +from the effective tree walked once in declaration order, inheritance from a child whose +parent is another node, references from the loader's own resolution +(``MetaAttr.resolved_target``, ``MetaData.super_data``) and claims through the resolver the +requirement gate uses. + +Three optional inputs add what the model does not hold, each as parsed JSON and each left +out when ``None`` or malformed: the ``meta verify --format json`` payload, the generation +manifest (``path -> { generatedBy, sourceNode }``) and the routes (``[{ node, method, path }]``). + +Deterministic: :func:`serialize_docs_view` gives the same bytes for the same inputs, and +those bytes equal JavaScript's ``JSON.stringify(view, null, 2) + "\\n"``. Sorting is by UTF-16 +code unit, as in the other ports. +""" +from __future__ import annotations + +import math +from typing import Any + +from .meta.core.requirement.requirement_constants import ( + REQUIREMENT_ATTR_COUNTEREXAMPLE, + REQUIREMENT_ATTR_STATEMENT, + REQUIREMENT_LEVEL_OBJECT, + REQUIREMENT_STATUSES, + REQUIREMENT_SUBTYPE_ARCHITECTURAL, + REQUIREMENT_SUBTYPE_FUNCTIONAL, +) +from .meta.core.requirement.resolve_claim import resolve_claim_target, resolve_member, split_member_ref +from .meta.meta_data import MetaData +from .requirement_check import effective_package +from .naming_refs import effective_package_of, is_ref_bearing_attr, split_child_tail +from .documentation.doc_constants import DOC_ATTR_DESCRIPTION, DOC_ATTR_SUMMARY, DOC_ATTR_TITLE +from .serializer_json import _normalize +from .shared.base_types import TYPE_FIELD, TYPE_OBJECT, TYPE_REQUIREMENT, TYPE_TEMPLATE +from .shared.separators import PACKAGE_SEP + +#: Bumped when a field changes meaning or is removed. +DOCS_VIEW_FORMAT = "metaobjects-docs-view/1" + +_CODE_OBJECT_UNCLAIMED = "WARN_REQUIREMENT_OBJECT_UNCLAIMED" +_EXTENDS = "extends" +_DOT = "." +_NUL = "\u0000" + + +# --------------------------------------------------------------------------- +# JavaScript-compatible JSON +# --------------------------------------------------------------------------- + + +def _cu(s: str) -> bytes: + """Sort key: UTF-16 code-unit order (astral characters sort by surrogate pair).""" + return s.encode("utf-16-be", "surrogatepass") + + +def _js_number(v: int | float) -> str: + """A number as JavaScript's ``Number`` prints it.""" + if isinstance(v, int): + return str(v) + if math.isnan(v) or math.isinf(v): + return "null" + if v == 0: + return "0" + if v.is_integer() and abs(v) < 1e21: + return str(int(v)) + r = repr(v) + if "e" in r: + mant, exp = r.split("e") + sign = exp[0] if exp[0] in "+-" else "+" + digits = exp.lstrip("+-").lstrip("0") or "0" + if mant.endswith(".0"): + mant = mant[:-2] + return f"{mant}e{sign}{digits}" + return r + + +_ESCAPES = {'"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t"} + + +def _js_string(s: str) -> str: + """A string as ``JSON.stringify`` writes it: only ``"``, ``\\``, control characters and + lone surrogates are escaped.""" + out = ['"'] + for ch in s: + o = ord(ch) + if ch in _ESCAPES: + out.append(_ESCAPES[ch]) + elif o < 0x20 or 0xD800 <= o <= 0xDFFF: + out.append(f"\\u{o:04x}") + else: + out.append(ch) + out.append('"') + return "".join(out) + + +def js_json(v: object, indent: int | None = None, _level: int = 0) -> str: + """``JSON.stringify(v, null, indent)`` for plain Python values (insertion-ordered dicts).""" + if v is None: + return "null" + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, (int, float)): + return _js_number(v) + if isinstance(v, str): + return _js_string(v) + if isinstance(v, (list, tuple)): + if not v: + return "[]" + if indent is None: + return "[" + ",".join(js_json(x, None) for x in v) + "]" + pad = " " * (indent * (_level + 1)) + end = " " * (indent * _level) + return "[\n" + ",\n".join(pad + js_json(x, indent, _level + 1) for x in v) + "\n" + end + "]" + if isinstance(v, dict): + if not v: + return "{}" + if indent is None: + return "{" + ",".join(_js_string(str(k)) + ":" + js_json(x, None) for k, x in v.items()) + "}" + pad = " " * (indent * (_level + 1)) + end = " " * (indent * _level) + return ( + "{\n" + + ",\n".join(pad + _js_string(str(k)) + ": " + js_json(x, indent, _level + 1) for k, x in v.items()) + + "\n" + + end + + "}" + ) + raise TypeError(f"not JSON serializable: {type(v).__name__}") + + +def serialize_docs_view(view: dict[str, Any]) -> str: + """The file's bytes: two-space JSON and one trailing newline.""" + return js_json(view, 2) + "\n" + + +# --------------------------------------------------------------------------- +# helpers +# --------------------------------------------------------------------------- + +Json = dict[str, Any] + + +def _is_record(v: object) -> bool: + return isinstance(v, dict) + + +def _str(v: object) -> str: + return v if isinstance(v, str) else "" + + +def _package_dir(pkg: str) -> str: + return "-root" if pkg == "" else "/".join(pkg.split(PACKAGE_SEP)) + + +def _page_stem(name: str) -> str: + return f"{name}.node" if name.lower() == "index" else name + + +def _qualified(id_: str, md: MetaData) -> str: + return f"{id_}[{md.type}.{md.sub_type}]" + + +def _member_anchor(md: MetaData, order: int) -> str: + if md.name == "": + return f"m-{md.type}-{order}" + return f"m-{md.name}" if md.type == TYPE_FIELD else f"m-{md.type}-{md.name}" + + +def _unresolved(text: str) -> Json: + return {"label": text, "id": "", "path": "", "kind": "", "unresolved": True} + + +def _declaring_attr(md: MetaData, name: str) -> Any: + """The attribute node that declares ``name`` for ``md``: its own, else the nearest + ``extends`` ancestor's, where the loader recorded what the reference resolved to.""" + seen: set[int] = set() + n: MetaData | None = md + while n is not None and id(n) not in seen: + seen.add(id(n)) + # ADR-0039: own - locating the layer that declares the attr, walking the super chain. + a = n.own_meta_attr(name) + if a is not None: + return a + n = n.super_data + return None + + +def _canonical_value(v: object) -> object: + """A value with every object's keys in code-unit order, as the canonical serializer writes them.""" + if isinstance(v, list): + return [_canonical_value(x) for x in v] + if isinstance(v, dict): + return {k: _canonical_value(v[k]) for k in sorted(v, key=_cu)} + return v + + +def _is_num(v: object) -> bool: + return isinstance(v, (int, float)) and not isinstance(v, bool) + + +class _Walked: + __slots__ = ( + "md", "id", "plain", "top", "parent", "direct", "requirement", "order", "canonical", + "declared_on", "anchor", "path", "children", "address", + ) + + def __init__(self, md: MetaData, id_: str, plain: str, parent: "_Walked | None", order: int) -> None: + self.md = md + self.id = id_ + self.plain = plain + self.parent = parent + self.order = order + self.top: _Walked = self + self.direct: _Walked | None = None + self.requirement: _Walked | None = None + self.canonical = True + self.declared_on: MetaData | None = None + self.anchor = "" + self.path = "" + self.children: list[_Walked] = [] + self.address = "" + + +def _plain_of(md: MetaData) -> str: + pkg = effective_package_of(md) + return md.name if pkg == "" else f"{pkg}{PACKAGE_SEP}{md.name}" + + +class _Builder: + def __init__(self, root: MetaData) -> None: + self.root = root + self.walked: list[_Walked] = [] + self.tops: list[_Walked] = [] + self.by_id: dict[str, _Walked] = {} + self.canonical: dict[int, _Walked] = {} + self.by_plain: dict[str, _Walked] = {} + self.requirements: list[_Walked] = [] + self._walk() + + def _walk(self) -> None: + top_level = list(self.root.children()) + holder: dict[str, MetaData] = {} + for md in top_level: + id_ = _plain_of(md) + held = holder.get(id_) + if held is None or (held.type != TYPE_OBJECT and md.type == TYPE_OBJECT): + holder[id_] = md + seen: set[str] = set() + + def visit(md: MetaData, index: int, parent: _Walked | None, req_prefix: str) -> None: + if parent is None: + plain = f"#{index}" if md.name == "" else _plain_of(md) + id_ = plain + held = holder.get(plain) + if md.name != "" and held is not md and (held is None or held.type != md.type): + id_ = _qualified(plain, md) + else: + plain = f"{parent.plain}#{index}" if md.name == "" else f"{parent.plain}{_DOT}{md.name}" + id_ = f"{parent.id}#{index}" if md.name == "" else f"{parent.id}{_DOT}{md.name}" + if md.name != "" and id_ in seen: + id_ = _qualified(id_, md) + if id_ in seen: + raise ValueError(f'docs view: two nodes share the id "{id_}" - the model names two siblings alike') + seen.add(id_) + is_req = md.type == TYPE_REQUIREMENT + address = (md.name if req_prefix == "" else f"{req_prefix}{_DOT}{md.name}") if is_req else req_prefix + inherited = parent is not None and md.parent is not parent.md + w = _Walked(md, id_, plain, parent, index) + w.canonical = True if parent is None else (parent.canonical and not inherited) + w.declared_on = md.parent if inherited else None + w.address = address if is_req else "" + w.top = w if parent is None else parent.top + w.direct = None if parent is None else (w if parent.parent is None else parent.direct) + w.requirement = w if is_req else (parent.requirement if parent is not None else None) + if w.direct is w: + w.anchor = _member_anchor(md, index) + self.walked.append(w) + self.by_id[id_] = w + if w.top.id == w.top.plain and plain not in self.by_plain: + self.by_plain[plain] = w + if w.canonical: + self.canonical[id(md)] = w + if parent is None: + self.tops.append(w) + else: + parent.children.append(w) + if is_req: + self.requirements.append(w) + for i, c in enumerate(md.children()): + visit(c, i, w, address) + + for i, md in enumerate(top_level): + visit(md, i, None, "") + for w in self.walked: + w.path = self._path_of(w) + + def _path_of(self, w: _Walked) -> str: + if w.requirement is not None: + r = w.requirement + return f"requirements/{_package_dir(effective_package_of(r.top.md))}/{_page_stem(r.address)}.html" + top = w.top + qualifier = f"[{top.md.type}.{top.md.sub_type}]" + typed = f".{top.md.type}-{top.md.sub_type}" if top.id.endswith(qualifier) else "" + page = f"model/{_package_dir(effective_package_of(top.md))}/{_page_stem(top.md.name)}{typed}.html" + return page if w.direct is None else f"{page}#{w.direct.anchor}" + + def link(self, w: _Walked) -> Json: + if w.requirement is w: + label = _str(w.md.get_meta_attr(DOC_ATTR_TITLE)) or w.md.name + elif w is w.top: + label = w.md.name + else: + label = f"{w.top.md.name}{w.id[len(w.top.id):]}" + return {"label": label, "id": w.id, "path": w.path, "kind": f"{w.md.type}.{w.md.sub_type}", "unresolved": False} + + def link_to(self, md: MetaData | None, text: str) -> Json: + w = None if md is None else self.canonical.get(id(md)) + return self.link(w) if w is not None else _unresolved(text) + + def ref_link(self, owner: MetaData | None, value: str) -> Json: + """The link a reference value lands on: the owner's row for the member its dotted tail + names, else the owner the loader bound.""" + if owner is None: + return _unresolved(value) + _, tail = split_child_tail(value) + row = None if tail == "" else self.by_plain.get(f"{owner.resolution_key()}{tail}") + return self.link(row) if row is not None else self.link_to(owner, value) + + +def _member_path(w: _Walked) -> str: + rest = w.id[len(w.top.id):] + return rest[len(_DOT):] if rest.startswith(_DOT) else rest + + +def _text_of(v: object) -> str: + return v if isinstance(v, str) else js_json(v) + + +def _attrs_of(b: _Builder, md: MetaData) -> tuple[list[Json], list[tuple[str, Json]]]: + attrs: list[Json] = [] + refs: list[tuple[str, Json]] = [] + m = md.attrs() + for name in sorted(m, key=_cu): + if name in ("isAbstract", "isArray"): + continue + value = _canonical_value(_normalize(m[name])) + is_ref = is_ref_bearing_attr(md, name) + da = _declaring_attr(md, name) if is_ref else None + resolved = getattr(da, "resolved_target", None) if da is not None else None + values: list[Json] = [] + if isinstance(value, str): + link = b.ref_link(None if isinstance(resolved, list) else resolved, value) if is_ref else None + values.append({"text": value, "link": link}) + if link is not None and not link["unresolved"]: + refs.append((name, link)) + elif isinstance(value, list) and all(isinstance(x, str) for x in value): + for i, item in enumerate(value): + owner = resolved[i] if isinstance(resolved, list) and i < len(resolved) else None + link = b.ref_link(owner, item) if is_ref else None + values.append({"text": item, "link": link}) + if link is not None and not link["unresolved"]: + refs.append((name, link)) + else: + values.append({"text": _text_of(value), "link": None}) + attrs.append({"name": name, "value": value, "values": values}) + return attrs, refs + + +def _group_members(members: list[Json]) -> list[Json]: + groups: dict[str, Json] = {} + for m in members: + g = groups.get(m["type"]) + if g is None: + g = {"type": m["type"], "count": 0, "members": []} + groups[m["type"]] = g + g["count"] += 1 + g["members"].append(m) + return list(groups.values()) + + +def _status_counts(statuses: list[str]) -> list[Json]: + return [{"status": s, "count": sum(1 for x in statuses if x == s)} for s in REQUIREMENT_STATUSES] + + +def _ledger_rows(verify: object) -> dict[str, list[Json]] | None: + if not isinstance(verify, dict) or not isinstance(verify.get("requirementLedger"), list): + return None + out: dict[str, list[Json]] = {} + for raw in verify["requirementLedger"]: + if not isinstance(raw, dict) or not isinstance(raw.get("qualifiedPath"), str): + continue + s = raw.get("supersededBy") + sup = s if isinstance(s, dict) and isinstance(s.get("ref"), str) else None + diags = raw.get("diagnostics") + row: Json = { + "qualifiedPath": raw["qualifiedPath"], + "digest": _str(raw.get("digest")), + "verdict": _str(raw.get("verdict")), + "diagnostics": [ + {k: _str(d.get(k)) for k in ("code", "severity", "source", "message")} + for d in diags + if isinstance(d, dict) + ] + if isinstance(diags, list) + else [], + "supersededBy": None + if sup is None + else {"ref": _str(sup.get("ref")), "resolves": sup.get("resolves") is True, "target": _str(sup.get("target"))}, + } + out.setdefault(row["qualifiedPath"], []).append(row) + return out + + +def build_docs_view( + root: MetaData, + verify: object = None, + manifest: object = None, + routes: object = None, +) -> Json: + """Build the docs view of a loaded model. A missing or malformed optional input only + leaves its part out. The result is a plain ``dict`` in the on-disk key order.""" + b = _Builder(root) + ledger = _ledger_rows(verify) + has_verify = ledger is not None + + # -- Requirements: claims first, since nodes and members list them. -- + claims_on: dict[int, list[Json]] = {} + req_links: dict[int, list[Json]] = {} + req_targets: dict[int, list[_Walked]] = {} + for r in b.requirements: + req: Any = r.md + referrer_pkg = effective_package(req) + links: list[Json] = [] + targets: list[_Walked] = [] + for ref in req.implemented_by(): + owner, path = split_member_ref(ref) + node = resolve_claim_target(b.root, owner, referrer_pkg) + claimed = resolve_member(node, path) if node is not None and path else node + if node is None: + key = "" + elif not path: + key = node.resolution_key() + else: + key = f"{node.resolution_key()}{_DOT}{_DOT.join(path)}" + w = b.by_plain.get(key) if claimed is not None else None + if w is None: + links.append({"ref": ref, "resolves": False, "target": _unresolved(ref)}) + continue + links.append({"ref": ref, "resolves": True, "target": b.link(w)}) + targets.append(w) + claim: Json = { + "requirement": b.link(r), + "member": "" if w is w.top else _member_path(w), + "status": _str(req.status()), + "level": req.level(), + } + x: _Walked | None = w + while x is not None: + claims_on.setdefault(id(x), []).append(claim) + x = x.parent + req_links[id(r)] = links + req_targets[id(r)] = targets + + # -- Files and routes. -- + files_of: dict[int, dict[str, list[str]]] = {} + if isinstance(manifest, dict): + for path, entry in manifest.items(): + if not isinstance(entry, dict) or not isinstance(entry.get("sourceNode"), str): + continue + w = b.by_plain.get(entry["sourceNode"]) + if w is None: + continue + files_of.setdefault(id(w.top), {}).setdefault(_str(entry.get("generatedBy")), []).append(path) + routes_of: dict[int, dict[str, Json]] = {} + if isinstance(routes, list): + for r in routes: + if not (isinstance(r, dict) and isinstance(r.get("node"), str) and isinstance(r.get("method"), str) + and isinstance(r.get("path"), str)): + continue + w = b.by_plain.get(r["node"]) + if w is None: + continue + route = {"method": r["method"].upper(), "path": r["path"]} + routes_of.setdefault(id(w.top), {})[f"{route['path']}{_NUL}{route['method']}"] = route + + # -- Advisories. -- + advisories: list[Json] = [] + if has_verify and isinstance(verify, dict) and isinstance(verify.get("requirements"), dict) \ + and isinstance(verify["requirements"].get("rows"), list): + for d in verify["requirements"]["rows"]: + if not isinstance(d, dict): + continue + row_node = _str(d.get("node")) + if row_node == "": + subject = None + elif row_node in b.by_plain: + subject = b.link(b.by_plain[row_node].top) + else: + subject = _unresolved(row_node) + advisories.append({ + "code": _str(d.get("code")), "path": _str(d.get("path")), "subject": subject, + "severity": _str(d.get("severity")), "source": _str(d.get("source")), + "message": _str(d.get("message")), + }) + unclaimed_ids = {a["subject"]["id"] for a in advisories if a["code"] == _CODE_OBJECT_UNCLAIMED and a["subject"] is not None} + + # -- Members and references. -- + refs_from: dict[int, list[Json]] = {} + + def extends_link(md: MetaData) -> Json | None: + if md.super_data is None and md.super_ref is None: + return None + return b.link_to(md.super_data, md.super_ref or "") + + def member(w: _Walked) -> Json: + attrs, refs = _attrs_of(b, w.md) + ext = extends_link(w.md) + own: list[Json] = [] + if ext is not None and not ext["unresolved"]: + own.append({"attr": _EXTENDS, "via": b.link(w), "target": ext}) + own.extend({"attr": a, "via": b.link(w), "target": t} for a, t in refs) + refs_from[id(w)] = own + return { + "id": w.id, + "name": w.md.name, + "type": w.md.type, + "subType": w.md.sub_type, + "order": w.order, + "anchor": w.anchor, + "path": w.path, + "abstract": w.md.is_abstract is True, + "isArray": w.md.resolved_is_array(), + "extends": ext, + "declaredOn": b.link_to(w.declared_on, w.declared_on.name) if w.declared_on is not None else None, + "attrs": attrs, + "refs": own, + "claims": claims_on.get(id(w), []), + "memberGroups": _group_members([member(c) for c in w.children]), + } + + nodes: list[Json] = [] + node_refs: dict[int, list[Json]] = {} + for t in b.tops: + attrs, refs = _attrs_of(b, t.md) + ext = extends_link(t.md) + member_groups = _group_members([member(c) for c in t.children]) + all_refs: list[Json] = [] + if ext is not None and not ext["unresolved"]: + all_refs.append({"attr": _EXTENDS, "via": None, "target": ext}) + all_refs.extend({"attr": a, "via": None, "target": tg} for a, tg in refs) + + def below(w: _Walked, acc: list[Json] = all_refs) -> None: + for c in w.children: + acc.extend(refs_from.get(id(c), [])) + below(c, acc) + + below(t) + node_refs[id(t)] = all_refs + files = [ + {"generatedBy": g, "paths": sorted(paths, key=_cu)} + for g, paths in sorted(files_of.get(id(t), {}).items(), key=lambda kv: _cu(kv[0])) + ] + route_list = [r for _, r in sorted(routes_of.get(id(t), {}).items(), key=lambda kv: _cu(kv[0]))] + t_claims = claims_on.get(id(t), []) + nodes.append({ + "id": t.id, + "name": t.md.name, + "package": effective_package_of(t.md), + "type": t.md.type, + "subType": t.md.sub_type, + "order": t.order, + "path": t.path, + "title": _str(t.md.get_meta_attr(DOC_ATTR_TITLE)), + "description": _str(t.md.get_meta_attr(DOC_ATTR_DESCRIPTION)), + "summary": _str(t.md.get_meta_attr(DOC_ATTR_SUMMARY)), + "abstract": t.md.is_abstract is True, + "extends": ext, + "attrs": attrs, + "memberGroups": member_groups, + "refs": all_refs, + "referencedBy": [], + "claims": t_claims, + "files": files, + "routes": route_list, + "unclaimed": t.id in unclaimed_ids, + "counts": { + "members": len(t.children), + "refs": len(all_refs), + "referencedBy": 0, + "claims": len(t_claims), + "files": sum(len(g["paths"]) for g in files), + "routes": len(route_list), + }, + }) + + # referencedBy: every reference into a top-level node (or a member of it) from another one. + node_by_id = {n["id"]: n for n in nodes} + incoming: dict[str, dict[str, Json]] = {} + for t in b.tops: + for out_ref in node_refs.get(id(t), []): + hit = b.by_id.get(out_ref["target"]["id"]) + if hit is None or hit.top is t: + continue + referrer = {"attr": out_ref["attr"], "from": b.link(t), "via": out_ref["via"], "target": out_ref["target"]} + via_id = out_ref["via"]["id"] if out_ref["via"] is not None else "" + key = _NUL.join([t.id, out_ref["attr"], via_id, out_ref["target"]["id"]]) + incoming.setdefault(hit.top.id, {})[key] = referrer + for id_, m in incoming.items(): + n = node_by_id.get(id_) + if n is None: + continue + n["referencedBy"] = [r for _, r in sorted(m.items(), key=lambda kv: _cu(kv[0]))] + n["counts"]["referencedBy"] = len(n["referencedBy"]) + nodes.sort(key=lambda n: _cu(n["id"])) + + # -- The requirement list, flat, in document order. -- + req_children: dict[int, list[_Walked]] = {} + + def req_parent(r: _Walked) -> _Walked | None: + return r.parent.requirement if r.parent is not None else None + + for r in b.requirements: + p = req_parent(r) + if p is not None: + req_children.setdefault(id(p), []).append(r) + + def subtree(r: _Walked) -> list[_Walked]: + out = [r] + for c in req_children.get(id(r), []): + out.extend(subtree(c)) + return out + + def qpath(x: _Walked) -> str: + p = effective_package(x.md) # type: ignore[arg-type] + return x.address if p == "" else f"{p}{PACKAGE_SEP}{x.address}" + + requirements: list[Json] = [] + for r in b.requirements: + req = r.md + pkg = effective_package(req) + qualified_path = qpath(r) + rows = ledger.get(qualified_path) if ledger is not None else None + row = rows.pop(0) if rows else None + chain: list[_Walked] = [] + p = req_parent(r) + while p is not None: + chain.insert(0, p) + p = req_parent(p) + sub = subtree(r) + linked = [ + x for x in sub + if (lambda level, xm: (level if level is not None else 0) >= REQUIREMENT_LEVEL_OBJECT + or (level is None and len(xm.implemented_by()) > 0))(x.md.level(), x.md) # type: ignore[attr-defined] + ] + counted = linked if linked else [r] + statuses = [s for s in (_str(x.md.status()) for x in counted) if s != ""] # type: ignore[attr-defined] + tmap: dict[str, _Walked] = {} + for x in sub: + for w in req_targets.get(id(x), []): + tmap[w.top.id] = w.top + tlist = sorted(tmap.values(), key=lambda w: _cu(w.id)) + children = req_children.get(id(r), []) + sup = row["supersededBy"] if row is not None else None + sup_target = None + if sup is not None and sup["target"] != "": + sup_target = next((x for x in b.requirements if qpath(x) == sup["target"]), None) + requirements.append({ + "id": r.id, + "name": r.md.name, + "label": b.link(r)["label"], + "path": r.path, + "address": r.address, + "package": pkg, + "qualifiedPath": qualified_path, + "subType": r.md.sub_type, + "level": req.level(), + "status": _str(req.status()), + "disposition": _str(req.disposition()), + "statement": _str(req.get_meta_attr(REQUIREMENT_ATTR_STATEMENT)), + "counterexample": _str(req.get_meta_attr(REQUIREMENT_ATTR_COUNTEREXAMPLE)), + "title": _str(req.get_meta_attr(DOC_ATTR_TITLE)), + "description": _str(req.get_meta_attr(DOC_ATTR_DESCRIPTION)), + "trackedBy": list(req.tracked_by()), + "depth": len(chain), + "parent": b.link(chain[-1]) if chain else None, + "breadcrumbs": [b.link(x) for x in chain], + "children": [b.link(x) for x in children], + "implementedBy": req_links.get(id(r), []), + "supersededBy": None if sup is None else { + "ref": sup["ref"], + "resolves": sup["resolves"], + "target": b.link(sup_target) if sup_target is not None else _unresolved(sup["ref"]), + }, + "inLedger": row is not None, + "verdict": row["verdict"] if row is not None else "", + "digest": row["digest"] if row is not None else "", + "diagnostics": row["diagnostics"] if row is not None else [], + "rollup": _status_counts(statuses), + "rollupTotal": len(statuses), + "belowCount": len(sub) - 1, + "childCount": len(children), + "targets": [b.link(w) for w in tlist], + "targetCount": len(tlist), + }) + + # -- Packages, counts, slices. -- + packages: list[Json] = [] + for name in sorted({n["package"] for n in nodes}, key=_cu): + in_pkg = [n for n in nodes if n["package"] == name] + groups: dict[str, Json] = {} + for n in in_pkg: + key = f"{n['type']}.{n['subType']}" + g = groups.get(key) + if g is None: + g = {"type": n["type"], "subType": n["subType"], "count": 0, "nodes": []} + groups[key] = g + g["count"] += 1 + g["nodes"].append(b.link(b.by_id[n["id"]])) + packages.append({ + "name": name, + "count": len(in_pkg), + "groups": [g for _, g in sorted(groups.items(), key=lambda kv: _cu(kv[0]))], + }) + + vc = verify.get("requirementCounts") if isinstance(verify, dict) and isinstance(verify.get("requirementCounts"), dict) else None + + def num(k: str) -> int | float | None: + return vc[k] if vc is not None and _is_num(vc.get(k)) else None + + all_files = {p for n in nodes for g in n["files"] for p in g["paths"]} + entities_total = num("entitiesTotal") + counts: Json = { + "nodes": len(nodes), + "packages": len(packages), + "requirements": len(requirements), + "functional": sum(1 for r in requirements if r["subType"] == REQUIREMENT_SUBTYPE_FUNCTIONAL), + "architectural": sum(1 for r in requirements if r["subType"] == REQUIREMENT_SUBTYPE_ARCHITECTURAL), + "byStatus": _status_counts([r["status"] for r in requirements]), + "claims": sum(1 for r in requirements for lk in r["implementedBy"] if lk["resolves"]), + "files": len(all_files), + "routes": sum(len(n["routes"]) for n in nodes), + "undecided": num("undecided") or 0, + "coverageMeasured": entities_total is not None, + "entitiesClaimed": num("entitiesClaimed") or 0, + "entitiesTotal": entities_total or 0, + } + + return { + "format": DOCS_VIEW_FORMAT, + "sources": {"requirements": has_verify, "files": isinstance(manifest, dict), "routes": isinstance(routes, list)}, + "counts": counts, + "packages": packages, + "nodes": nodes, + "requirements": requirements, + "advisories": advisories, + "slices": _slices_of(b, nodes, requirements), + } + + +def _slices_of(b: _Builder, nodes: list[Json], requirements: list[Json]) -> list[Json]: + slices: list[Json] = [] + + def sorted_ids(s: Any) -> list[str]: + return sorted(set(s), key=_cu) + + for pkg in sorted_ids(n["package"] for n in nodes): + slices.append({ + "id": f"package:{pkg}", "kind": "package", "anchor": pkg, + "nodes": sorted_ids(n["id"] for n in nodes if n["package"] == pkg), + }) + by_id = {r["id"]: r for r in requirements} + for r in requirements: + if r["childCount"] == 0: + continue + ids: list[str] = [] + + def visit(x: Json) -> None: + ids.append(x["id"]) + for lk in x["implementedBy"]: + if not lk["resolves"]: + continue + ids.append(lk["target"]["id"]) + w = b.by_id.get(lk["target"]["id"]) + if w is not None: + ids.append(w.top.id) + for c in x["children"]: + child = by_id.get(c["id"]) + if child is not None: + visit(child) + + visit(r) + slices.append({"id": f"requirement:{r['id']}", "kind": "requirement", "anchor": r["id"], "nodes": sorted_ids(ids)}) + for n in nodes: + if n["type"] != TYPE_TEMPLATE: + continue + ids2 = [n["id"]] + for rf in n["refs"]: + if rf["via"] is None: + w = b.by_id.get(rf["target"]["id"]) + ids2.append(w.top.id if w is not None else rf["target"]["id"]) + slices.append({"id": f"prompt:{n['id']}", "kind": "prompt", "anchor": n["id"], "nodes": sorted_ids(ids2)}) + return sorted(slices, key=lambda s: _cu(s["id"])) + + +# --------------------------------------------------------------------------- +# the explorer app's data scripts +# --------------------------------------------------------------------------- + + +def _sorted_strings(m: "dict[str, str] | None") -> dict[str, str]: + src = m or {} + return {k: src[k] for k in sorted(src, key=_cu)} + + +def explorer_model_script( + title: str, + footer: str | None, + texts: "dict[str, str] | None", + templates: "dict[str, str] | None", + view: dict[str, Any], +) -> tuple[str, str]: + """The explorer app's data file and its stamp: ``(script, stamp)``. + + One script setting ``window.MO_MODEL``. Its ``stamp`` is the first 16 hex digits of the + SHA-256 of the model's compact JSON without the stamp, and the stamp file repeats it. The + same shape and bytes as TypeScript's ``explorerModelScript`` (``@metaobjectsdev/docs-site``). + """ + import hashlib + + rest = js_json({ + "title": title, + "footer": footer or "", + "texts": _sorted_strings(texts), + "templates": _sorted_strings(templates), + "view": view, + }) + stamp = hashlib.sha256(rest.encode("utf-8", "surrogatepass")).hexdigest()[:16] + return f'window.MO_MODEL = {{"stamp":{js_json(stamp)},{rest[1:]};\n', stamp + + +def explorer_stamp_script(stamp: str) -> str: + """The file the open app polls: ``window.MO_STAMP = "";``.""" + return f"window.MO_STAMP = {js_json(stamp)};\n" diff --git a/server/python/src/metaobjects/meta_endpoint.py b/server/python/src/metaobjects/meta_endpoint.py index ed849fea7f..5693532992 100644 --- a/server/python/src/metaobjects/meta_endpoint.py +++ b/server/python/src/metaobjects/meta_endpoint.py @@ -8,11 +8,27 @@ def meta() -> Response: return Response(meta_json(root), media_type="application/json") +The docs view route (``GET /_meta/docs``, the document the model explorer reads) is the +same kind of helper: :func:`meta_docs` builds the body once with its strong ``ETag`` and +answers ``If-None-Match``:: + + docs = meta_docs(root) + + @app.get(f"/api{META_DOCS_ROUTE_PATH}") + def meta_docs_route(request: Request) -> Response: + headers = {"ETag": docs.etag, "Cache-Control": "no-cache"} + if docs.matches(request.headers.get("if-none-match")): + return Response(status_code=304, headers=headers) + return Response(docs.body, media_type="application/json", headers=headers) + Guard that route with your own authorization — ``/_meta`` publishes the shape of the model (entity and field names, types, validators, layouts), though no row data. """ from __future__ import annotations +from typing import Any + +from metaobjects.docs_view import build_docs_view, serialize_docs_view from metaobjects.meta.meta_data import MetaData from metaobjects.serializer_json import canonical_serialize_effective @@ -28,3 +44,61 @@ def meta_json(root: MetaData) -> str: a browser reading it never resolves ``extends`` itself. """ return canonical_serialize_effective(root) + + +#: The docs view endpoint's path, mounted under the host's API prefix beside +#: :data:`META_ROUTE_PATH`. A cross-port contract value: the model explorer reads +#: ``GET {apiPrefix}/_meta/docs`` from any backend. +META_DOCS_ROUTE_PATH = META_ROUTE_PATH + "/docs" + + +def meta_docs_json(root: MetaData, routes: Any = None) -> str: + """The ``GET {apiPrefix}/_meta/docs`` response body: the loaded model's docs view, built + from the model alone (no verify payload, no generation manifest, which a running + application does not hold), with the same bytes every port writes for the same model. + + ``routes`` (``[{ node, method, path }]``, ``node`` a resolution key) are listed on each node. + """ + return serialize_docs_view(build_docs_view(root, None, None, routes)) + + +def meta_docs_etag(body: str) -> str: + """A strong ETag for a docs view body: its length and the 32-bit FNV-1a hash of its UTF-16 + code units, quoted, the same value TypeScript's mount and the JVM helper send. The contract + is only that the tag changes when the body does; a client compares it and never parses it.""" + units = body.encode("utf-16-le", "surrogatepass") + h = 0x811C9DC5 + for i in range(0, len(units), 2): + h ^= units[i] | (units[i + 1] << 8) + h = (h * 0x01000193) & 0xFFFFFFFF + return f'"{len(units) // 2:x}-{h:08x}"' + + +def etag_matches(if_none_match: str | None, etag: str) -> bool: + """Whether an ``If-None-Match`` header value names ``etag`` (or is ``*``): answer 304.""" + if not if_none_match: + return False + for token in if_none_match.split(","): + v = token.strip() + if v.startswith("W/"): + v = v[2:] + if v == "*" or v == etag: + return True + return False + + +class MetaDocs: + """A built docs view body and its strong ``ETag``: build once, the model is immutable after load.""" + + def __init__(self, body: str) -> None: + self.body = body + self.etag = meta_docs_etag(body) + + def matches(self, if_none_match: str | None) -> bool: + """Whether ``if_none_match`` names this body's tag (or is ``*``): answer 304.""" + return etag_matches(if_none_match, self.etag) + + +def meta_docs(root: MetaData, routes: Any = None) -> MetaDocs: + """The docs view of one loaded model, built once, with its ``ETag``.""" + return MetaDocs(meta_docs_json(root, routes)) diff --git a/server/python/tests/codegen/test_cli_registry.py b/server/python/tests/codegen/test_cli_registry.py index 3e78f9d06e..e6ff3d1ef8 100644 --- a/server/python/tests/codegen/test_cli_registry.py +++ b/server/python/tests/codegen/test_cli_registry.py @@ -40,8 +40,8 @@ def test_gen_list_prints_all_and_exits_zero(capsys, tmp_path: Path) -> None: # Every registered stable name appears in the listing. for name in GENERATOR_REGISTRY: assert name in out, f"--list omitted {name!r}" - # Exactly the 17 registered names (`metamodel-docs` joined in MO-130; `requirements` and `agent-docs` joined in G-PY-1; ADR-0056 removed `payload`; FR-023 added `shared-model`) - assert len(GENERATOR_REGISTRY) == 17 + # Exactly the 18 registered names (`docs-site` joined in MO-130; `metamodel-docs` joined in MO-130; `requirements` and `agent-docs` joined in G-PY-1; ADR-0056 removed `payload`; FR-023 added `shared-model`) + assert len(GENERATOR_REGISTRY) == 18 assert "payload" not in GENERATOR_REGISTRY # A template-tier generator says it needs the entity generator's models. assert "output-parser — " in out diff --git a/server/python/tests/codegen/test_docs_site_generator.py b/server/python/tests/codegen/test_docs_site_generator.py new file mode 100644 index 0000000000..13494a8447 --- /dev/null +++ b/server/python/tests/codegen/test_docs_site_generator.py @@ -0,0 +1,236 @@ +"""The ``docs-site`` generator (the model explorer): the same files, and the same data script +bytes, as TypeScript's ``generateExplorerSite`` (``output: "app"``), written with no Node.""" +from __future__ import annotations + +import hashlib +import json +import os +import shutil +from pathlib import Path + +import pytest + +from metaobjects.codegen.config import GenConfig +from metaobjects.codegen.generator import EmittedFile, GenContext +from metaobjects.codegen.generator_registry import GENERATOR_REGISTRY, GeneratorBuildContext +from metaobjects.codegen.generators.docs_site_generator import ( + APP_FILES, + DocsSiteGenerator, + emit_site, + read_prompt_texts, +) +from metaobjects.codegen.overwrite_policy import HASHES_FILE +from metaobjects.codegen.runner import run_gen +from metaobjects.docs_view import explorer_model_script, explorer_stamp_script + +from tests.docs_view_support import corpus, fixtures, load_case + + +def repo() -> Path: + for p in Path(__file__).resolve().parents: + if (p / "fixtures" / "explorer-conformance").is_dir() and (p / "explorer-app").is_dir(): + return p + raise RuntimeError("repository root not found") + + +def expected_view(name: str) -> dict: + return json.loads((corpus() / name / "expected.json").read_text(encoding="utf-8")) + + +def test_registry_entry() -> None: + entry = GENERATOR_REGISTRY["docs-site"] + assert (entry.tier, entry.layer, entry.source) == ("neutral", "docs", None) + assert entry.factory(GeneratorBuildContext()).name == "docs-site" # type: ignore[attr-defined] + + +def test_model_script_is_typescripts_bytes() -> None: + # explorerModelScript({ title: "Shop ", footer: "v1", texts, templates, view }) in + # @metaobjectsdev/docs-site (run with bun over fixtures/explorer-conformance/shop/expected.json) + # gives this stamp and these bytes. + script, stamp = explorer_model_script( + "Shop ", "v1", {"b": "B\n", "a": "A é"}, {"explorer-head.mustache": ""}, expected_view("shop") + ) + assert stamp == "2600a8bb3cb5d29d" + assert len(script) == 50657 + assert hashlib.sha256(script.encode("utf-8")).hexdigest() == "87643095df7b9c679871c21420f8a3ae71128ba60f71f97b2b8bc99dfc482cfb" + assert explorer_stamp_script(stamp) == 'window.MO_STAMP = "2600a8bb3cb5d29d";\n' + + +def test_app_files_are_the_canonical_copy() -> None: + files = emit_site(expected_view("model-alone"), "t", "", {}, None, None) + for f in APP_FILES: + assert files[f] == (repo() / "explorer-app" / f).read_text(encoding="utf-8"), f + assert files["explorer.json"] == (corpus() / "model-alone" / "expected.json").read_text(encoding="utf-8") + assert list(files) == [ + "index.html", "assets/explorer-app.js", "assets/cytoscape.min.js", "assets/3d-force-graph.min.js", + "assets/explorer.css", "assets/explorer.js", "explorer-model.js", "explorer-stamp.js", "explorer.json", + ] + + +def test_an_owned_theme_and_template_win(tmp_path: Path) -> None: + (tmp_path / "assets").mkdir() + (tmp_path / "templates").mkdir() + (tmp_path / "assets/explorer.css").write_text("body{}") + (tmp_path / "templates/explorer-head.mustache").write_text("") + (tmp_path / "templates/not-a-template.mustache").write_text("ignored") + files = emit_site(expected_view("model-alone"), "t", "", {}, tmp_path / "assets", tmp_path / "templates") + assert files["assets/explorer.css"] == "body{}" + assert files["assets/explorer.js"] == (repo() / "explorer-app/assets/explorer.js").read_text(encoding="utf-8") + assert '"templates":{"explorer-head.mustache":""}' in files["explorer-model.js"] + + +def test_prompt_texts_read_below_the_directories_only(tmp_path: Path) -> None: + view = expected_view("shop") + prompts = corpus() / "shop/project/prompts" + texts = read_prompt_texts(view, [tmp_path, prompts]) + assert len(texts) == 1 + assert next(iter(texts.values())) == (prompts / "shop/order-note.mustache").read_text(encoding="utf-8") + climbing = json.loads(json.dumps(view).replace('"shop/order-note"', '"../order-note"')) + assert read_prompt_texts(climbing, [prompts / "shop"]) == {} + + +def _case(name: str, tmp_path: Path, sink: dict[str, str] | None = None) -> tuple[GenConfig, DocsSiteGenerator]: + """A corpus case's project, with its committed manifest, verify and routes files when it has them.""" + case = corpus() / name + gen_state = tmp_path / "gen-state" + gen_state.mkdir() + if (case / "hashes.json").is_file(): + shutil.copy(case / "hashes.json", gen_state / HASHES_FILE) + options: dict[str, str] = {} + if (case / "verify.json").is_file(): + options["verify_file"] = "../verify.json" + if (case / "routes.json").is_file(): + options["routes_file"] = "../routes.json" + config = GenConfig( + out_dir=str(case / "project" / "gen"), project_root=str(case / "project"), + gen_state_dir=str(gen_state), sink=sink, + ) + return config, DocsSiteGenerator(**options) + + +def _run(name: str, tmp_path: Path, extra: list) -> dict[str, str]: + """The generator in a run beside ``extra``.""" + sink: dict[str, str] = {} + config, docs = _case(name, tmp_path, sink) + run_gen(config, load_case(name), generators=[docs, *extra]) + prefix = config.out_dir + os.sep + return {k[len(prefix):]: v for k, v in sink.items() if k.startswith(prefix)} + + +def _outside_run(name: str, tmp_path: Path) -> dict[str, str]: + """The generator called outside a run (no run list), reading the case's committed manifest + when it has one, as Java's corpus test and C#'s conformance test reach the builder.""" + config, docs = _case(name, tmp_path) + ctx = GenContext(entities=[], loaded_root=load_case(name), matches=lambda _o: True, config=config, + warn=lambda _m: None) + return {f.path: f.content for f in docs.generate(ctx)} + + +@pytest.mark.parametrize("name", fixtures()) +def test_generator_writes_every_corpus_case_byte_for_byte(name: str, tmp_path: Path) -> None: + out = _outside_run(name, tmp_path) + assert out["site/explorer.json"] == (corpus() / name / "expected.json").read_text(encoding="utf-8") + model = out["site/explorer-model.js"] + assert model.startswith('window.MO_MODEL = {"stamp":') + assert '"title":"project"' in model + for f in APP_FILES: + assert "site/" + f in out + + +def test_generator_lists_this_runs_files_after_every_other_generator(tmp_path: Path) -> None: + key = next(c for c in load_case("model-alone").children() if c.name == "Book").resolution_key() + + class Stub: + name = "stub" + + def generate(self, ctx: GenContext) -> list[EmittedFile]: + return [EmittedFile("stub/book.txt", "x", source_node=key)] + + # Declared AFTER docs-site on purpose: the runner still runs docs-site last. + out = _run("model-alone", tmp_path, extra=[Stub()]) + view = json.loads(out["site/explorer.json"]) + assert view["sources"]["files"] is True + book = next(n for n in view["nodes"] if n["name"] == "Book") + assert book["files"] == [{"generatedBy": "stub", "paths": ["gen/stub/book.txt"]}] + + +def test_generator_falls_back_to_the_committed_manifest(tmp_path: Path) -> None: + out = _outside_run("shop", tmp_path) + order = next(n for n in json.loads(out["site/explorer.json"])["nodes"] if n["name"] == "Order") + assert any(g["generatedBy"] == "queries" for g in order["files"]) + + +ONE_TARGET = "targets:\n app:\n outDir: gen\n generators: [docs-site, entity]\n" +APP = " app:\n outDir: gen\n generators: [entity]\n" +DOCS = " docs:\n outDir: docs\n generators: [docs-site]\n" +TWO_TARGETS = "targets:\n" + APP + DOCS +DOCS_FIRST = "targets:\n" + DOCS + APP +WITH_NAMES = "targets:\n app:\n outDir: gen\n generators: [entity, names, docs-site]\n" +WITHOUT_NAMES = "targets:\n app:\n outDir: gen\n generators: [entity, docs-site]\n" +DOCS_ONLY = "targets:\n app:\n outDir: gen\n generators: [docs-site]\n" +SAME_GENERATOR = ( + "targets:\n app1:\n outDir: gen1\n generators: [entity, docs-site]\n entities: [Order]\n" + " app2:\n outDir: gen2\n generators: [entity]\n entities: [Telemetry]\n" +) + + +@pytest.mark.parametrize( + "config,site,then,args,owner", + [ + (ONE_TARGET, "gen", None, [], "gen/"), + (TWO_TARGETS, "docs", None, [], "gen/"), + (DOCS_FIRST, "docs", None, [], "gen/"), + (TWO_TARGETS, "docs", "outputLayout: package\n" + TWO_TARGETS, [], "gen/"), + (WITH_NAMES, "gen", WITHOUT_NAMES, [], "gen/"), + (SAME_GENERATOR, "gen1", None, ["--target", "app1"], "gen2/"), + (WITHOUT_NAMES, "gen", DOCS_ONLY, [], None), + ], + ids=["one", "two", "docs-first", "removed-file", "removed-generator", "same-generator", "docs-alone"], +) +def test_the_drift_gate_renders_what_gen_wrote( + config: str, site: str, then: str | None, args: list[str], owner: str | None, + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + from metaobjects.cli import main + + project = tmp_path / "shop" + (project / "metaobjects").mkdir(parents=True) + (project / "metaobjects" / "meta.acme.json").write_text(json.dumps({"metadata.root": { + "package": "acme", + "children": [ + {"object.value": {"name": "Telemetry", "children": [{"field.string": {"name": "reading"}}]}}, + {"object.entity": {"name": "Order", "children": [ + {"source.rdb": {"@table": "orders"}}, + {"field.long": {"name": "id"}}, + {"identity.primary": {"name": "pk", "@fields": ["id"]}}, + ]}}, + ], + }}), encoding="utf-8") + (project / "metaobjects.config.yaml").write_text(config, encoding="utf-8") + monkeypatch.chdir(project) + + assert main(["gen"]) == 0 + before = {p.relative_to(project) for p in project.rglob("*.py")} + (project / "metaobjects.config.yaml").write_text(then or config, encoding="utf-8") + assert main(["gen", *args]) == 0 + if then is not None: + assert {p.relative_to(project) for p in project.rglob("*.py")} != before + view_file = project / site / "site" / "explorer.json" + first = view_file.read_text(encoding="utf-8") + view = json.loads(first) + listed = [p for n in view["nodes"] for g in n["files"] for p in g["paths"]] + missing = [p for p in listed if not (project / p).is_file()] + assert not missing, f"listed files that do not exist: {missing}" + if owner is None: + # TypeScript's runDocsView: a run always knows its files, so an empty list is still a list. + assert listed == [] and view["sources"]["files"] is True + else: + assert listed + node = next(n for n in view["nodes"] if n["name"] == "Telemetry") + paths = [p for g in node["files"] if g["generatedBy"] == "entity" for p in g["paths"]] + assert paths and all(p.startswith(owner) for p in paths) + assert '"title":"shop"' in (project / site / "site" / "explorer-model.js").read_text(encoding="utf-8") + + assert main(["gen", "--force", *args]) == 0 + assert view_file.read_text(encoding="utf-8") == first + assert main(["verify", "--codegen", "--full"]) == 0 diff --git a/server/python/tests/codegen/test_eject_alone.py b/server/python/tests/codegen/test_eject_alone.py index ca3849ef10..bb2af6c589 100644 --- a/server/python/tests/codegen/test_eject_alone.py +++ b/server/python/tests/codegen/test_eject_alone.py @@ -224,6 +224,9 @@ def test_every_generator_module_is_a_registry_entry_or_a_model_walk() -> None: registered = {e.source_module for e in GENERATOR_REGISTRY.values() if e.source_module} # The primitive: exempt, it has no emit logic of its own. registered |= {f"{package}.template_generator"} + # Exempt too: the site builder is engine (ADR-0034 Amendment 9), an adopter owns the theme + # under codegen/docs-site/ rather than a copy of the generator. + registered |= {f"{package}.docs_site_generator"} walks = {m for m in contract.EngineSurface().engine if m.startswith(f"{package}.")} on_disk = {f"{package}.{p.stem}" for p in (CODEGEN / "generators").glob("*.py") if p.stem != "__init__"} diff --git a/server/python/tests/codegen/test_manifest_store.py b/server/python/tests/codegen/test_manifest_store.py index 411d9eb595..26d0d38467 100644 --- a/server/python/tests/codegen/test_manifest_store.py +++ b/server/python/tests/codegen/test_manifest_store.py @@ -233,7 +233,7 @@ def test_gen_records_the_generator_and_node_of_each_per_entity_file(tmp_path: Pa model = entries["gen/Order.py"] assert isinstance(model, dict) assert list(model) == ["hash", "generatedBy", "sourceNode"] - assert (model["generatedBy"], model["sourceNode"]) == ("entity-model", "acme::shop::Order") + assert (model["generatedBy"], model["sourceNode"]) == ("entity", "acme::shop::Order") # A file of no one node (a package __init__) stays a plain hash. inits = [v for k, v in entries.items() if k.endswith("__init__.py")] assert inits and all(isinstance(v, str) for v in inits) diff --git a/server/python/tests/docs_view_support.py b/server/python/tests/docs_view_support.py new file mode 100644 index 0000000000..0d91cef9a5 --- /dev/null +++ b/server/python/tests/docs_view_support.py @@ -0,0 +1,74 @@ +"""Shared helpers for the docs view tests: load a ``fixtures/explorer-conformance`` case.""" +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from metaobjects import MetaDataLoader +from metaobjects.core_types import core_providers +from metaobjects.meta.meta_data import MetaData +from metaobjects.provider import Provider +from metaobjects.registry import AttrSchema, ChildRule, TypeDefinition, TypeRegistry + + +def corpus() -> Path: + for parent in Path(__file__).resolve().parents: + c = parent / "fixtures" / "explorer-conformance" + if c.is_dir(): + return c + raise RuntimeError("fixtures/explorer-conformance not found") + + +def fixtures() -> list[str]: + return sorted(p.name for p in corpus().iterdir() if p.is_dir()) + + +def read_json(case: Path, name: str) -> Any: + p = case / name + return json.loads(p.read_text(encoding="utf-8")) if p.is_file() else None + + +def _slots(children: list[dict[str, Any]]) -> tuple[list[AttrSchema], list[ChildRule]]: + attrs: list[AttrSchema] = [] + rules: list[ChildRule] = [] + for slot in children: + if slot["type"] == "attr": + attrs.append(AttrSchema( + name=slot["name"], value_type="string", required=slot.get("min", 0) > 0, + is_array=bool(slot.get("isArray")), description=slot.get("description", "an attribute"), + )) + else: + rules.append(ChildRule(child_type=slot["type"], child_sub_type=slot["subType"], child_name=slot["name"])) + return attrs, rules + + +def fixture_provider(definition: dict[str, Any]) -> Provider: + """A provider for a fixture's provider.json: every type a plain node.""" + p = Provider(definition["provider"], ("metaobjects-core-types",)) + for t in definition["types"]: + attrs, rules = _slots(t["children"]) + p.add(TypeDefinition( + type=t["type"], sub_type=t["subType"], factory=lambda ty, st, n: MetaData(ty, st, n), + attrs=attrs, child_rules=rules, description=t.get("description", "a node"), + )) + + def extend(registry: TypeRegistry) -> None: + for e in definition["extends"]: + _, rules = _slots(e["children"]) + registry.extend(e["type"], e["subType"], child_rules=rules) + + p.on_register(extend) + return p + + +def load_case(name: str) -> MetaData: + """The case's project, loaded strictly with its provider.json applied.""" + case = corpus() / name + definition = read_json(case, "provider.json") + providers = list(core_providers) + if definition is not None: + providers.append(fixture_provider(definition)) + result = MetaDataLoader.from_directory(case / "project" / "metaobjects", providers=providers, strict=True, discover_naming=False) + assert not result.errors, f"{name}: expected a clean strict load, got {result.errors}" + return result.root diff --git a/server/python/tests/test_docs_view_conformance.py b/server/python/tests/test_docs_view_conformance.py new file mode 100644 index 0000000000..2a55b9a4db --- /dev/null +++ b/server/python/tests/test_docs_view_conformance.py @@ -0,0 +1,38 @@ +"""The docs view corpus (``fixtures/explorer-conformance/``, ``docs/features/docs-view.md``): +each case's project is loaded strictly, its committed optional inputs are read, and +``build_docs_view`` must reproduce ``expected.json`` byte for byte, as the TypeScript +reference does.""" +from __future__ import annotations + +import pytest + +from metaobjects.docs_view import build_docs_view, js_json, serialize_docs_view + +from tests.docs_view_support import corpus, fixtures, load_case, read_json + + +def view_of(name: str) -> dict: + case = corpus() / name + return build_docs_view( + load_case(name), read_json(case, "verify.json"), read_json(case, "hashes.json"), read_json(case, "routes.json") + ) + + +def test_corpus_holds_the_fixtures_the_readme_describes() -> None: + assert fixtures() == ["crm", "model-alone", "shop"] + + +@pytest.mark.parametrize("name", ["crm", "model-alone", "shop"]) +def test_fixture_reproduces_expected_json(name: str) -> None: + expected = (corpus() / name / "expected.json").read_text(encoding="utf-8") + assert serialize_docs_view(view_of(name)) == expected + + +def test_json_writer_matches_javascript() -> None: + assert js_json(1.5) == "1.5" + assert js_json(3.0) == "3" + assert js_json(1e21) == "1e+21" + assert js_json(1e-7) == "1e-7" + assert js_json("a\"b\\c\n\x01é
") == '"a\\"b\\\\c\\n\\u0001é
"' + assert js_json("\ud800") == '"\\ud800"' + assert js_json({"a": [], "b": {}, "c": [1, None, True]}, 2) == '{\n "a": [],\n "b": {},\n "c": [\n 1,\n null,\n true\n ]\n}' diff --git a/server/python/tests/test_meta_endpoint.py b/server/python/tests/test_meta_endpoint.py index 9756594ea8..1906fc9110 100644 --- a/server/python/tests/test_meta_endpoint.py +++ b/server/python/tests/test_meta_endpoint.py @@ -67,3 +67,28 @@ def test_meta_json_inlines_a_member_inherited_via_extends() -> None: assert "createdAt" in effective_subscriber assert "createdAt" not in raw_subscriber + + +def test_docs_route_path_and_body_are_the_cross_port_contract() -> None: + from metaobjects import META_DOCS_ROUTE_PATH, meta_docs_json + from tests.docs_view_support import corpus, load_case + + assert META_DOCS_ROUTE_PATH == "/_meta/docs" + expected = (corpus() / "model-alone" / "expected.json").read_text(encoding="utf-8") + assert meta_docs_json(load_case("model-alone")) == expected + + +def test_docs_etag_and_if_none_match() -> None: + from metaobjects import meta_docs, meta_docs_etag + from tests.docs_view_support import load_case + + # metaDocsEtag(...) in @metaobjectsdev/runtime-ts (and the Java and C# ports) gives these for the same strings. + assert meta_docs_etag("hello") == '"5-4f9f2cab"' + assert meta_docs_etag("") == '"0-811c9dc5"' + assert meta_docs_etag("h\u00e9llo \u2713") == '"7-0579d2da"' + assert meta_docs_etag("\U0001f600") == '"2-cb31c4b8"' + docs = meta_docs(load_case("model-alone")) + assert docs.etag == meta_docs_etag(docs.body) + assert docs.matches(docs.etag) and docs.matches("*") and docs.matches("W/" + docs.etag) + assert docs.matches('"x", ' + docs.etag) + assert not docs.matches('"other"') and not docs.matches(None) and not docs.matches("") diff --git a/server/python/tests/test_rules_inert.py b/server/python/tests/test_rules_inert.py index bf01538658..52fb39e780 100644 --- a/server/python/tests/test_rules_inert.py +++ b/server/python/tests/test_rules_inert.py @@ -14,6 +14,7 @@ """ from __future__ import annotations +import json from pathlib import Path import pytest @@ -88,7 +89,28 @@ def test_the_with_model_really_carries_the_vocabulary() -> None: assert entity_transitions(request) == [] -@pytest.mark.parametrize("entry", list_generators(), ids=lambda e: e.name) +#: The explorer documents every node, so a declared API and each transition are more nodes in it: +#: held to its own test below (only the model-derived files move), not to byte equality. +DOCS_SITE = "docs-site" +MODEL_FILES = {"site/explorer.json", "site/explorer-model.js", "site/explorer-stamp.js"} + + +def _inert_generators() -> list[GeneratorEntry]: + return [e for e in list_generators() if e.name != DOCS_SITE] + + +def test_docs_site_differs_only_in_the_model_derived_files(tmp_path: Path) -> None: + entry = next(e for e in list_generators() if e.name == DOCS_SITE) + without = _emit("without", [entry], tmp_path / "a") + with_ = _emit("with", [entry], tmp_path / "b") + assert THREW not in without, without.get(THREW) + assert set(without) == set(with_) + assert {k for k in without if without[k] != with_[k]} == MODEL_FILES + nodes = lambda files: len(json.loads(files["site/explorer.json"])["nodes"]) # noqa: E731 + assert nodes(with_) > nodes(without) + + +@pytest.mark.parametrize("entry", _inert_generators(), ids=lambda e: e.name) def test_generator_emits_the_same_files_with_and_without_rules_nodes( entry: GeneratorEntry, tmp_path: Path ) -> None: @@ -101,7 +123,7 @@ def test_generator_emits_the_same_files_with_and_without_rules_nodes( def test_every_runnable_generator_in_one_run_emits_the_same_files(tmp_path: Path) -> None: runnable = [ - e for i, e in enumerate(list_generators()) + e for i, e in enumerate(_inert_generators()) if THREW not in _emit("without", [e], tmp_path / f"probe-{i}") ] expected = _emit("without", runnable, tmp_path / "a") @@ -133,7 +155,7 @@ def test_exactly_these_generators_cannot_run_from_a_bare_model(tmp_path: Path) - # Pinned so a generator that starts throwing cannot drop out of the comparison silently; # the list may only shrink. threw = sorted( - e.name for i, e in enumerate(list_generators()) + e.name for i, e in enumerate(_inert_generators()) if THREW in _emit("without", [e], tmp_path / f"probe-{i}") ) assert threw == []