From 96e66178f3b585f96fc3b14c74d24a2b7ecb9df7 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 5 Dec 2026 00:13:16 -0500 Subject: [PATCH 01/10] feat(metadata): add eventing and batch APIs, carries, provides and extracts in every port Registers api.eventing (operation.event, binding.messaging) and api.batch (operation.export, operation.import, binding.file) beside api.operational, experimental since 1.4.0, in TypeScript, C#, Java and Kotlin, Python and Rust. In the systems vocabulary, resource.stream and resource.queue carry eventing APIs and resource.objectStore batch APIs (a resource carrying the other kind is ERR_REF_WRONG_KIND), app.service and app.job provide APIs, and app.job extracts an entity or projection. The file conventions are pinned: {date} and {timestamp} in UTC are the only @fileName placeholders, a marker completion is the file's name plus .done, csv is RFC 4180 with a header row, and fixedWidth is not offered. @availableBy has one form per frequency, with a day for weekly and monthly files (rules D1 and D2, ERR_BAD_ATTR_VALUE). The ADR-0066 operation rules and every generator that reads operations now take only api.operational, and the TypeScript and Rust service generators pick the binding.rest by subtype. The inert-codegen corpus gains with-delivery/, held in every port's test: the new APIs add no output. Also: the ERR_TRANSITION_NOT_ON_ENTITY text matches TypeScript in every port; the document/search store recipe names the provider that registers those sources; the metamodel-version gate no longer reads a member moved off an abstract anchor, or a wildcard narrowed to its existing subtypes, as breaking; requirements for the seven new subtypes. --- .claude/rules/cross-language-porting.md | 2 +- AGENTS.md | 2 +- changelog.d/api-eventing-and-batch.md | 33 ++ docs/CONFORMANCE.md | 11 +- docs/features/business-rules.md | 56 ++- .../document-graph-and-wide-column-stores.md | 21 +- examples/showcase/site-payload.json | 2 +- explorer-app/assets/explorer-app.js | 2 +- fixtures/codegen-noop/rules/README.md | 14 + .../rules/with-delivery/meta.purchasing.json | 251 ++++++++++++ .../expected-errors.json | 15 + .../input/meta.parcels.json | 25 ++ .../expected-errors.json | 15 + .../input/meta.parcels.json | 16 + .../expected-errors.json | 15 + .../input/meta.ledger.json | 16 + .../expected-errors.json | 15 + .../input/meta.parcels.json | 24 ++ .../systems-api-eventing-batch/expected.json | 291 ++++++++++++++ .../input/meta.parcels.json | 142 +++++++ fixtures/metamodel-docs/data/INDEX.md.json | 37 +- .../metamodel-docs/data/providers.md.json | 40 +- .../metamodel-docs/data/types/api.md.json | 44 ++- .../metamodel-docs/data/types/app.md.json | 27 ++ .../metamodel-docs/data/types/binding.md.json | 108 ++++++ .../data/types/operation.md.json | 141 +++++-- .../data/types/resource.md.json | 27 ++ fixtures/metamodel-docs/expected/INDEX.md | 9 +- fixtures/metamodel-docs/expected/providers.md | 21 +- fixtures/metamodel-docs/expected/types/api.md | 40 +- fixtures/metamodel-docs/expected/types/app.md | 3 + .../metamodel-docs/expected/types/binding.md | 42 ++ .../expected/types/operation.md | 74 +++- .../metamodel-docs/expected/types/resource.md | 3 + .../expected-registry.json | 355 +++++++++++++++-- .../csharp/RequirementHarnessTests.cs | 30 +- .../java/RequirementHarnessTest.java | 37 +- .../kotlin/RequirementHarnessTest.kt | 37 +- .../python/test_requirement_harness.py | 37 +- .../typescript/requirement-harness.test.ts | 37 +- metaobjects/meta.requirements.yaml | 85 +++++ scripts/check-metamodel-version.mjs | 45 ++- scripts/check-requirements-ledger.ts | 2 +- scripts/test-metamodel-version.mjs | 54 +++ .../RulesInertTests.cs | 44 +++ .../ExplorerApp/assets/explorer-app.js | 2 +- .../ReferenceFacetTests.cs | 8 +- .../MetaObjects/Core/Api/ApiConstants.cs | 66 +++- .../csharp/MetaObjects/Core/Api/ApiSchema.cs | 45 ++- .../Core/Rules/RulesMetaDataProvider.cs | 9 +- .../MetaObjects/Core/Transition/RulesCheck.cs | 2 +- .../Loader/ValidationPasses.Rules.cs | 107 ++++-- .../csharp/MetaObjects/SpecMetamodel/api.json | 112 +++++- .../MetaObjects/SpecMetamodel/systems.json | 18 +- .../explorer-app/assets/explorer-app.js | 2 +- .../generator/kotlin/RulesInertTest.kt | 39 ++ .../generator/spring/RulesInertTest.java | 50 +++ .../com/metaobjects/api/ApiConstants.java | 36 ++ .../com/metaobjects/api/CommandOperation.java | 20 +- .../com/metaobjects/api/DeliveryNode.java | 32 ++ .../com/metaobjects/api/DeliveryTypes.java | 92 +++++ .../com/metaobjects/api/OperationalApi.java | 3 +- .../java/com/metaobjects/api/RulesCheck.java | 3 +- .../api/RulesTypesMetaDataProvider.java | 1 + .../metaobjects/loader/RulesValidation.java | 99 +++-- .../systems/SystemsTypesMetaDataProvider.java | 23 +- .../validation/ReferenceFacetTest.java | 6 +- .../explorer_app/assets/explorer-app.js | 2 +- .../src/metaobjects/loader/validate_rules.py | 129 +++++-- .../meta/core/api/api_constants.py | 71 +++- .../meta/core/rules/rules_provider.py | 145 ++++++- server/python/src/metaobjects/rules_check.py | 3 +- .../src/metaobjects/spec_metamodel/api.json | 112 +++++- .../metaobjects/spec_metamodel/systems.json | 18 +- server/python/tests/test_rules_inert.py | 49 ++- .../python/tests/unit/test_reference_facet.py | 5 +- .../explorer-app/assets/explorer-app.js | 2 +- .../metaobjects-codegen/src/service_routes.rs | 5 +- .../metaobjects-codegen/tests/rules_inert.rs | 27 +- .../rust/metaobjects/data/metamodel/api.json | 112 +++++- .../metaobjects/data/metamodel/systems.json | 18 +- server/rust/metaobjects/src/rules_check.rs | 3 +- server/rust/metaobjects/src/validate/rules.rs | 235 ++++++++++-- .../tests/conformance-expected-failures.json | 2 +- .../cli/test/unit/rules-inert.test.ts | 33 +- .../packages/codegen-ts/src/service-walk.ts | 5 +- .../docs-site/app/assets/explorer-app.js | 2 +- .../metadata/src/core/api/api-constants.ts | 75 +++- .../src/core/api/api-definition.embedded.ts | 361 +++++++++++++++++- .../src/core/systems/systems-constants.ts | 7 + .../systems/systems-definition.embedded.ts | 88 ++++- .../metadata/src/core/transition/commands.ts | 8 +- .../metadata/src/loader/rules-validation.ts | 108 ++++-- .../metadata/test/definition-schema.test.ts | 6 + .../metadata/test/reference-facet.test.ts | 6 + site-reference/index.html | 37 +- site-reference/providers.html | 21 +- site-reference/types/api.html | 26 +- site-reference/types/app.html | 27 ++ site-reference/types/binding.html | 112 ++++++ site-reference/types/operation.html | 132 +++++-- site-reference/types/resource.html | 27 ++ spec/metamodel/api.json | 112 +++++- spec/metamodel/systems.json | 18 +- 104 files changed, 4837 insertions(+), 434 deletions(-) create mode 100644 changelog.d/api-eventing-and-batch.md create mode 100644 fixtures/codegen-noop/rules/with-delivery/meta.purchasing.json create mode 100644 fixtures/conformance/error-api-binding-file-unknown-placeholder/expected-errors.json create mode 100644 fixtures/conformance/error-api-binding-file-unknown-placeholder/input/meta.parcels.json create mode 100644 fixtures/conformance/error-api-event-under-operational/expected-errors.json create mode 100644 fixtures/conformance/error-api-event-under-operational/input/meta.parcels.json create mode 100644 fixtures/conformance/error-api-export-available-by-weekly-no-day/expected-errors.json create mode 100644 fixtures/conformance/error-api-export-available-by-weekly-no-day/input/meta.ledger.json create mode 100644 fixtures/conformance/error-ref-wrong-kind-carries-batch-on-stream/expected-errors.json create mode 100644 fixtures/conformance/error-ref-wrong-kind-carries-batch-on-stream/input/meta.parcels.json create mode 100644 fixtures/conformance/systems-api-eventing-batch/expected.json create mode 100644 fixtures/conformance/systems-api-eventing-batch/input/meta.parcels.json create mode 100644 server/java/metadata/src/main/java/com/metaobjects/api/DeliveryNode.java create mode 100644 server/java/metadata/src/main/java/com/metaobjects/api/DeliveryTypes.java diff --git a/.claude/rules/cross-language-porting.md b/.claude/rules/cross-language-porting.md index 94060bc6f1..ab7ea5168f 100644 --- a/.claude/rules/cross-language-porting.md +++ b/.claude/rules/cross-language-porting.md @@ -26,7 +26,7 @@ Preserve the following contracts exactly across all language ports: - Relationship subtypes: `association`, `aggregation`, `composition`. Cardinality via `@cardinality: one|many`; target via `@objectRef`. **M:N (FR-018) slim vocabulary:** `@cardinality: "many"` + `@objectRef` (target) + `@through` (the junction/through entity — a third entity that MUST declare two `identity.reference` children, one per FK side). The relationship's FK fields are **derived** from those references (the `identity.reference` SSOT for FK direction), never restated. `@sourceRefField` (optional) disambiguates a *directed* self-join by naming the source-side FK field on the junction (the other reference is the target side); on a `@cardinality: one` relationship it instead names which of several `identity.reference` nodes onto the same target this relationship navigates, short-circuiting the unique-candidate/`@sourceRefField`/name-pairing ladder (#368, [ADR-0029](spec/decisions/ADR-0029-entity-child-extends-and-via-inference.md) Amendment 1) — an unresolvable 1:N reference set is `ERR_INVALID_RELATIONSHIP` at load. `@symmetric` (optional boolean) marks an *undirected* self-join (union-on-read) — valid only when `@objectRef` == the declaring entity, and mutually exclusive with `@sourceRefField`. The pre-FR-018 `@joinEntity`/`@joinFields` attrs are REMOVED. Validation errors: symmetric-on-hetero / symmetric+sourceRefField → `ERR_BAD_ATTR_VALUE`; junction-missing-two-references / sourceRefField-not-matching / M:N-attr-on-1:N / **junction-unpairable** → `ERR_INVALID_RELATIONSHIP`. **Unpairable means the junction declares its two references but neither resolves to the navigating entity, or neither to the `@objectRef` target** — declaring two references is NOT enough, and the loader now checks WHAT they point at (owner ruling 2026-09-20). It does so by running the real FK derivation and converting its failure, never a parallel re-implementation, so the loader and the derivation cannot drift; scope mirrors codegen's own iteration exactly — every CONCRETE, non-projection object crossed with its EFFECTIVE relationships, NOT deduped by declaration, because pairing is a property of the navigating entity and an inherited M:N can pair from one subtype and not another. Before the ruling this loaded clean and then diverged: TS and C# warned and emitted no traversal route (a silent 404), while Java, Kotlin and Python failed the build. Gated by `fixtures/conformance/error-relationship-m2m-junction-unpairable/`. - Index subtypes: `index.lookup` (non-unique retrieval index; uniqueness is encoded in the **type**: `identity.secondary` = unique alternate key, `index.lookup` = non-unique; `@unique` is REMOVED from `identity.secondary` — `ERR_UNKNOWN_ATTR` on any legacy `@unique`). RDB-physical escapes `@using`/`@expr`/`@where`/`@orders` are registered by the db provider on **both** `identity.secondary` and `index.lookup`. `index.fulltext` / `index.vector` / `index.spatial` are reserved on the subtype axis — documented, NOT registered (YAGNI + 1.0 vocab freeze). See [ADR-0040](spec/decisions/ADR-0040-index-type-and-secondary-key-purity.md). - Layout subtypes: `dataGrid` -- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`) now, `messaging`/`grpc` reserved; the event/streaming sibling of `api.operational` is reserved). Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (`rules-names` and `contract-types` in TypeScript and C#; the TypeScript `service`, `service-routes` and `service-routes-hono` for derived CRUD, transitions, declared operations and the rules' checks). +- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`), `binding.messaging` and `binding.file`; `grpc` reserved). `api.eventing` (`operation.event` + `binding.messaging`) and `api.batch` (`operation.export`/`.import` + `binding.file`) are registered since 1.4.0, experimental: only O1 and the delivery rules D1/D2 read them, and every port's API generators select `binding.rest` by subtype and skip them. Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (`rules-names` and `contract-types` in TypeScript and C#; the TypeScript `service`, `service-routes` and `service-routes-hono` for derived CRUD, transitions, declared operations and the rules' checks). - Transition subtypes: `transition.action` (a child of `field.enum` on an `object.entity`: `@from`, `@to`, `@condition` in the validators' grammar, `@permission`, `@public`); `transition.base` is the abstract root and `transition.timed` is reserved, not registered. An enum with a transition IS a lifecycle — states, initial state (`@default`), terminal states and each unclaimed transition's command are derived, never declared (ADR-0066). A transition's `@from` lists enum members, not object references: every port's ref-bearing-attr check excludes `transition.*` nodes. A lifecycle belongs to the declaring entity and its `extends` descendants, NEVER to an entity whose field merely `extends` the lifecycle field (filter by the declaring field's owner); a command claims a transition NODE for its target and every entity extending it. Transition and operation names compare case-insensitively; operation names are unique per PACKAGE across its APIs, except one operation declared identically in two APIs (a versioned API). A lifecycle on an entity with no source loads and is inert (no derived command, no permission checks); the writable-source check applies once a source exists. A `@permission` is a dotted identifier path (a package prefix may use `::`); an absent one derives `.` for an operation and `..` for a transition's command. - Currency attrs: `@currency` (ISO 4217), `@locale` (BCP 47) - Schema attrs: `@schema` on `source.rdb` (DB schema name; Postgres default `public`, SQLite rejects non-default values) diff --git a/AGENTS.md b/AGENTS.md index 354172e3ff..cce1264123 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,7 +74,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (laid out by `KotlinWriter`, ADR-0063, on the JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (614 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (619 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / Java / Kotlin / Python / C# / Rust byte-identical; the C# and Rust drift ledgers are empty (`docs/CONFORMANCE.md`). - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python; `op: guardedUpdate` is TS-only until each port's 1.3.0 guarded update lands), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (the Node reference helper writes them; a native tool is equally first-class, ADR-0015 Amendment 2). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/changelog.d/api-eventing-and-batch.md b/changelog.d/api-eventing-and-batch.md new file mode 100644 index 0000000000..5a5bfde833 --- /dev/null +++ b/changelog.d/api-eventing-and-batch.md @@ -0,0 +1,33 @@ +- **Eventing and batch APIs, what a resource carries and what an app provides, in every port + (experimental).** Two API kinds join `api.operational`, registered in TypeScript, C#, Java + and Kotlin, Python and Rust. An `api.eventing` holds `operation.event` children (`@outputRef`, + the payload; `@key`, the field whose events stay in order), each with an optional `binding.messaging` + (`@protocol` of `kafka`, `amqp`, `mqtt` or `sqs`). An `api.batch` holds `operation.export` + (`@outputRef`, one row of the file; `@frequency` of `hourly`, `daily`, `weekly` or `monthly`; + `@availableBy`, when the file is ready, in UTC) and `operation.import` (`@inputRef`, + `@frequency`), each with an optional `binding.file`: `@transport` (`sftp` or `objectStore`), + `@path`, `@fileName`, `@format` (`csv`, `jsonLines` or `parquet`), `@compression`, + `@completion` and `@encryption`. The file conventions are pinned: `{date}` is the run's + start date as `YYYY-MM-DD` and `{timestamp}` is `YYYYMMDDTHHMMSSZ`, both UTC, and are the only + placeholders; a `marker` completion is an empty file named the data file's name plus `.done`; + `csv` is RFC 4180 with a header row. `@availableBy` is written `:MM` for an hourly file, + `HH:MM` for daily, `Ddd HH:MM` for weekly and `D HH:MM` (day 1 to 28) for monthly; another form + is `ERR_BAD_ATTR_VALUE` (`error-api-export-available-by-weekly-no-day`), and so is any other + `@fileName` placeholder (`error-api-binding-file-unknown-placeholder`). An event, export or + import under an `api.operational`, or a command or query under the new kinds, is + `ERR_CHILD_NOT_ALLOWED` (`error-api-event-under-operational`), and so is a `binding.rest` on + them. In a system, `resource.stream` and `resource.queue` take `@carries` naming eventing APIs + and `resource.objectStore` names batch APIs; a resource carrying the other kind is + `ERR_REF_WRONG_KIND` (`error-ref-wrong-kind-carries-batch-on-stream`). `app.service` and + `app.job` take `@provides` naming the APIs they host, and `app.job` takes `@extracts` naming + the entity or projection it reads (`systems-api-eventing-batch`). + Nothing is generated from the new kinds yet. The operation rules of ADR-0066 (claims, + transitions, permissions, errors and routes) apply to an `api.operational` only, and every + generator that reads operations reads only those and takes an operation's `binding.rest` by + subtype, so a model gains no output from an eventing or batch API + (`fixtures/codegen-noop/rules/with-delivery/`, held in every port's inert-codegen test). + `metamodelVersion` stays at `1.4`. + + Upgrading: `operation.base` no longer declares attributes; a command and a query declare the + same ones themselves, so a model loads as before. The `ERR_TRANSITION_NOT_ON_ENTITY` message in + C#, Java and Kotlin, Python and Rust now reads as the TypeScript one does. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 9908b0257f..1e4da01500 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | Rust | |---|---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 614 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (614 / 614, empty ledger) | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 619 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (619 / 619, empty ledger) | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | 19 / 19 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | — | @@ -82,7 +82,7 @@ and render ledgers; the api-contract runner's list of sub-corpora not built yet) shrink, and the corpora without one assert each case outright. A new fixture that fails in Rust and is not on the ledger prints a warning and does not fail the lane; it becomes a hard failure when ADR-0065 turns the warning off. A regression still fails: the ledger's -`minPassing` (614) is the number of fixtures known to pass, and the run fails when fewer do. +`minPassing` (619) is the number of fixtures known to pass, and the run fails when fewer do. Beside the corpora it runs the codegen-compile gate (below) with every shipped generator, a scale gate over twenty copies of the fitness model, and `examples/rust-service/`'s HTTP test. [The Rust port page](ports/rust.md#conformance) has the detail. @@ -445,7 +445,7 @@ carry it, and a model that uses it fails there by name. There is no row per pack ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (614) +### `fixtures/conformance/` — metamodel loader + canonical serializer (619) | Fixture prefix | Feature doc | |---|---| @@ -468,8 +468,9 @@ carry it, and a model that uses it fails there by name. There is no row per pack | `origin-*`, `error-origin-*` | [features/templates-and-payloads.md](features/templates-and-payloads.md) (payload origins) | | `projection-*`, `error-projection-*`, `field-readonly-on-view-projection` | [features/source-kinds.md](features/source-kinds.md) (projections + the object taxonomy, ADR-0028) | | `requirement-*`, `error-unknown-attr-requirement` | [features/requirements.md](features/requirements.md) (vocabulary only — the gate has its own corpus, `requirement-check-conformance/`; see "Split coverage" above) | -| `systems-vocabulary`, `error-ref-wrong-kind-runsas`, `error-ref-unresolved-runsas`, `ref-target-type-list-heldby`, `error-ref-wrong-kind-heldby`, `error-ref-ambiguous-heldby`, `error-resource-residency-bad-value`, `error-app-two-builds`, `error-app-three-builds`, `error-app-build-beside-inherited`, `systems-grants-and-sources`, `error-ref-unresolved-grant-resource`, `error-ref-wrong-kind-grant-rdb-on-queue`, `error-ref-wrong-kind-source-rdb-on-document`, `error-ref-wrong-kind-grant-stream-on-other-system-queue`, `error-grant-crosses-system`, `error-runsas-other-system`, `error-duplicate-name-in-system`, `systems-duplicate-name-overlay-in-system`, `error-ref-ambiguous-heldby-bare-name`, `systems-rdb-with-search-copy`, `systems-role-grants-across-files`, `systems-document-only-lifecycle-inert`, `systems-sql-view-with-search-copy`, `systems-payload-ref-search-only-projection` | [spec/metamodel-definitions.md](../spec/metamodel-definitions.md) (the systems vocabulary, ADR-0070: the reference facet's worked cases, including the target type list behind `@heldBy`, the closed `@residency` set, an app's one build, counting a build it inherits, the grants and their same-system rule, `@resource` on a source, one name per type within a system, a role redeclared in a second file keeping every grant, a search copy beside a SQL view leaving its columns unchecked, a lifecycle that stays inert when its entity has no relational source, and a projection kept only in a search index still serving as a template payload) | +| `systems-vocabulary`, `error-ref-wrong-kind-runsas`, `error-ref-unresolved-runsas`, `ref-target-type-list-heldby`, `error-ref-wrong-kind-heldby`, `error-ref-ambiguous-heldby`, `error-resource-residency-bad-value`, `error-app-two-builds`, `error-app-three-builds`, `error-app-build-beside-inherited`, `systems-grants-and-sources`, `error-ref-unresolved-grant-resource`, `error-ref-wrong-kind-grant-rdb-on-queue`, `error-ref-wrong-kind-source-rdb-on-document`, `error-ref-wrong-kind-grant-stream-on-other-system-queue`, `error-grant-crosses-system`, `error-runsas-other-system`, `error-duplicate-name-in-system`, `systems-duplicate-name-overlay-in-system`, `error-ref-ambiguous-heldby-bare-name`, `systems-rdb-with-search-copy`, `systems-role-grants-across-files`, `systems-document-only-lifecycle-inert`, `systems-sql-view-with-search-copy`, `systems-payload-ref-search-only-projection`, `error-ref-wrong-kind-carries-batch-on-stream` | [spec/metamodel-definitions.md](../spec/metamodel-definitions.md) (the systems vocabulary, ADR-0070: the reference facet's worked cases, including the target type list behind `@heldBy`, the closed `@residency` set, an app's one build, counting a build it inherits, the grants and their same-system rule, `@resource` on a source, one name per type within a system, a role redeclared in a second file keeping every grant, a search copy beside a SQL view leaving its columns unchecked, a lifecycle that stays inert when its entity has no relational source, and a projection kept only in a search index still serving as a template payload) | | `reporting-*`, `error-dimension-*`, `error-measure-*`, `error-ratio-*`, `error-segment-*`, `error-report-*`, `error-relative-date-*` | [features/reporting.md](features/reporting.md) (the `dimension` / `measure` / `segment` / `object.report` vocabulary and its load-time rules; design in the [FR-044 spec](superpowers/specs/2026-10-02-fr-044-core-reporting-design.md)) | +| `systems-api-eventing-batch`, `error-api-export-available-by-weekly-no-day`, `error-api-binding-file-unknown-placeholder`, `error-api-event-under-operational` | [features/business-rules.md](features/business-rules.md) ("Eventing and batch APIs": `api.eventing` and `api.batch`, their operations and bindings, what a resource carries and an app provides, and the `@availableBy` and `@fileName` rules D1 and D2) | | `rules-*`, `error-rules-*` | [features/business-rules.md](features/business-rules.md) (operations, permission names and lifecycles: the vocabulary and its load-time rules, ADR-0066; the `verify` gate has its own corpus, `rules-check-conformance/`) | | `provider-extension-*`, `provider-custom-vocabulary-*` | [features/extending-with-providers.md](features/extending-with-providers.md) (a project's own provider: a new subtype plus attributes on an existing type load with it and are refused without it, every port writing the provider in its own language) | | `error-packs-left-out-*` | [features/extending-with-providers.md](features/extending-with-providers.md) ([Where vocabulary lives](features/extending-with-providers.md#where-vocabulary-lives): a model that uses a left-out pack's type fails to load, naming the unknown type or subtype) | @@ -961,7 +962,7 @@ shared input. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 614 + yaml 19 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 619 + yaml 19 + verify 45 + render 26 + persistence 68 + api-contract 191 + source-resolution 30 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `rules-check-conformance`, `shared-model-conformance`, the `cube-model` corpus, `explorer-conformance` and `list-query-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 989b965c9b..e920b70b64 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -132,6 +132,58 @@ binding: Most models never write a binding. +## Eventing and batch APIs + +Two more API kinds sit beside `api.operational`, experimental since 1.4.0. The `api` subtype is +the interaction model and the binding is the protocol (ADR-0030). None of the operation rules +above, except O1, reads them: an event, export or import is not a command or a query, has no +target entity, claims no transition and derives no permission name. Nothing is generated from +them yet, and every port's API generators skip them. + +| API | Operations | Binding | +|---|---|---| +| `api.eventing`: the provider publishes that something happened | `operation.event` (`outputRef` is the payload; `key` is the payload field whose events stay in order) | `binding.messaging` (`protocol`, optional: `kafka`, `amqp`, `mqtt`, `sqs`) | +| `api.batch`: a dataset delivered as a file on a schedule | `operation.export` (`outputRef`, `frequency`, `availableBy`), `operation.import` (`inputRef`, `frequency`) | `binding.file` | + +An app names the APIs it hosts with `provides`. A `resource.stream` or `resource.queue` names the +eventing APIs that travel on it with `carries`, and a `resource.objectStore` names the batch APIs +whose files it holds; a `carries` that names the other kind is `ERR_REF_WRONG_KIND`. An `app.job` +names the entity or projection it reads its rows from with `extracts`. + +`frequency` is `hourly`, `daily`, `weekly` or `monthly`. `availableBy` is the UTC time each new +file is in place by, and its form follows the frequency: + +| `frequency` | `availableBy` | Example | +|---|---|---| +| `hourly` | `:MM`, minutes past each hour | `:15` | +| `daily` | `HH:MM` | `03:00` | +| `weekly` | `Ddd HH:MM`, the day one of `Mon` to `Sun` | `Mon 06:00` | +| `monthly` | `D HH:MM`, the day of the month from 1 to 28 | `1 06:00` | + +**The file conventions of `binding.file`.** No standard covers them, so they are pinned here: + +- `transport`: `sftp` or `objectStore`. The provider always hosts the files, in the object store + that carries the API; the transport is how the other party reaches them. `path` is the folder. +- `fileName` may hold two placeholders. `{date}` is the UTC date on which the run that writes + the file started, `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time that run started, + to the second, `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses + that day's date. +- `format`: `csv`, `jsonLines` or `parquet`. A CSV file is RFC 4180: a comma between fields, CRLF + after every line, UTF-8 with no byte order mark, and a first line of field names. A field is + quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is + an empty field, a date is `YYYY-MM-DD`, a timestamp is UTC ending in `Z`, a decimal is plain + digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, + and a double is the shortest text that reads back to the same value, with no exponent. + `jsonLines` is one JSON object per line, UTF-8, LF after each. +- `compression`: `none` (the default) or `gzip`. +- `completion`: how a reader knows a file is whole. `rename`: it appears under its final name + only once complete. `marker`: an empty object named the file's name plus `.done` is put beside + it afterwards. `none` (the default): nothing. +- `encryption`: `none` (the default) or `pgp`. + +A fixed-width format is not offered: nothing can yet state a column's width, padding or +alignment. + ## Lifecycles A `transition.action` is a child of a `field.enum` on an `object.entity`. An enum field with at @@ -185,7 +237,7 @@ setting `rules.permissions.names` makes `verify` warn about derived names, or fa | Rule | Code | When | |---|---|---| | L1 | `ERR_TRANSITION_NOT_ON_ENTITY` | A transition on a field that is not a field of an `object.entity`: a document-root field, or a field of a value, projection or report. | -| L2 | `ERR_TRANSITION_NOT_ON_ENTITY` | A concrete entity has a lifecycle and a source, but no writable one. An entity with no source is not refused: its lifecycle is inert. | +| L2 | `ERR_TRANSITION_NOT_ON_ENTITY` | A concrete entity has a lifecycle and a source, but no writable one. An entity with no relational source (none, or only `source.document` / `source.search`) is not refused: its lifecycle is inert. | | L3 | `ERR_LIFECYCLE_NO_INITIAL` | An enum field with transitions has no `default`. | | L4 | `ERR_TRANSITION_UNKNOWN_STATE` | A `from` or `to` value is not one of the enum's `values`. | | L5, O0 | `ERR_TRANSITION_NAME_COLLISION` | A transition or an operation is named `create`, `get`, `list`, `update` or `delete`, in any case. | @@ -205,6 +257,8 @@ setting `rules.permissions.names` makes `verify` warn about derived names, or fa | P3 | `ERR_TRANSITION_NAME_COLLISION` | Two permission points ask about one permission name and at least one name is derived: an operation named `Order.open`, or one declaring `permission: p.Order.open`, beside the `open` transition of `Order` in `p`. Names are compared exactly as the policy receives them: `::` and `.` are different things in the metadata, so an `open` operation in package `p::Order` (`p::Order.open`) does not collide with that transition (`p.Order.open`). Two declared `permission` values may be equal. | | B1 | `ERR_BINDING_PATH_MISMATCH` | A `binding.rest` `path` has the wrong placeholders. | | B2 | `ERR_BINDING_PATH_MISMATCH` | Two declared bindings of one API have the same method (declared or derived) and the same path, ignoring placeholder names. | +| D1 | `ERR_BAD_ATTR_VALUE` | An `operation.export` `availableBy` does not have the form its `frequency` gives. | +| D2 | `ERR_BAD_ATTR_VALUE` | A `binding.file` `fileName` holds a placeholder other than `{date}` or `{timestamp}`, or an unmatched brace. | Names are compared without case (L5 and O0, L6, O6) because each one becomes a command, a permission constant and a file, and those collide on a case-folding target. P3 compares permission names diff --git a/docs/recipes/document-graph-and-wide-column-stores.md b/docs/recipes/document-graph-and-wide-column-stores.md index fb31793bb0..18c448c811 100644 --- a/docs/recipes/document-graph-and-wide-column-stores.md +++ b/docs/recipes/document-graph-and-wide-column-stores.md @@ -132,11 +132,16 @@ exists, because the two records live in different stores. ## Why this is not new vocabulary -ADR-0007 designs `source.document`, `source.graph` and the other paradigm subtypes. Core's -systems provider registers `source.document` and `source.search` (ADR-0070), so an object can -name its document store or search index, but no generator writes from them yet. `source.graph` -and the rest stay unregistered until a shipping consumer dispatches on them. That is the bar ADR-0007 Amendment 2 set for `@role` members, applied to -paradigms. Registering one today would make `Order` persistable to -every tier in all five ports, and each tier would then need to learn to skip it. A -sourceless entity with a property bag gives an adopter everything a store-specific -generator needs, and it changes nothing in the metamodel. +ADR-0007 designs `source.document`, `source.graph` and the other paradigm subtypes. The +systems provider (`metaobjects-systems-core`, ADR-0070) registers `source.document` and +`source.search`; core's type provider (`metaobjects-core-types`) does not. An object can name its +document store or search index with them, but no generator writes from them yet. `source.graph` +and the rest stay unregistered until a shipping consumer dispatches on them. That is the bar +ADR-0007 Amendment 2 set for `@role` members, applied to paradigms. + +Registering a paradigm subtype does not make an object persistable. Every tier in all five ports +decides that from `source.rdb` alone, so an entity whose only sources are `source.document` or +`source.search` is treated like a sourceless one: it gets no table, no migration and no +relational routes, and a lifecycle on it is inert. A sourceless entity with a property bag still +gives an adopter everything a store-specific generator needs, and it changes nothing in the +metamodel. diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index a001915d05..3694438925 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.4" }, "counts": { - "fixtures": 614, + "fixtures": 619, "corpora": 49, "baseTypes": 28 }, diff --git a/explorer-app/assets/explorer-app.js b/explorer-app/assets/explorer-app.js index a2681492a9..ec81740b86 100644 --- a/explorer-app/assets/explorer-app.js +++ b/explorer-app/assets/explorer-app.js @@ -265,5 +265,5 @@ `);for(var i=0;i0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(` `)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",` `,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(``)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(` -`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'
';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return``}function pct(x){return`${(Math.round(x*1e4)/100).toString()}%`}function legendHtml(withUnclaimed){return`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
${values.map(esc).join(" | ")}
`:"",column:esc(str(f.attrs[FIELD_ATTR_COLUMN])??""),flagsHtml:flags.map((x)=>`${esc(x)}`).join(""),claimsHtml:claims.map((c)=>`${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
")}}keyRow(from,c){let fields=strs(c.attrs[IDENTITY_ATTR_FIELDS]),target=this.refHtml(from,c,IDENTITY_REFERENCE_ATTR_REFERENCES)||this.refHtml(from,c,RELATIONSHIP_ATTR_OBJECT_REF),through=str(c.attrs[RELATIONSHIP_ATTR_THROUGH]),card=str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]),shape=c.type===TYPE_RELATIONSHIP?[card,through!==void 0?`through ${localName(through)}`:void 0].filter((x)=>x!==void 0).join(", "):`(${fields.join(", ")})`;return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),inheritedHtml:c.inheritedFrom!==void 0?'inherited':"",shape:esc(shape),targetHtml:target!==""?`→ ${target}`:""}}reportingRow(from,c){let a=c.attrs,parts=[],agg=str(a[REPORTING_ATTR_AGG]),of=this.refHtml(from,c,REPORTING_ATTR_OF,localName);if(agg!==void 0)parts.push(`${esc(agg)}(${of})`);else if(of!=="")parts.push(`of ${of}`);let num=str(a[REPORTING_ATTR_NUMERATOR]),den=str(a[REPORTING_ATTR_DENOMINATOR]);if(num!==void 0&&den!==void 0)parts.push(`${esc(num)} ÷ ${esc(den)}`);let via=str(a[REPORTING_ATTR_VIA]);if(via!==void 0)parts.push(`via ${esc(localName(via))}`);let grains=strs(a[REPORTING_ATTR_GRAINS]);if(grains.length>0)parts.push(`grains ${grains.map((g)=>`${esc(g)}`).join(" ")}`);let seg=str(a[REPORTING_ATTR_SEGMENT]);if(seg!==void 0)parts.push(`segment ${esc(seg)}`);if(a[REPORTING_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`);if(a[REPORTING_ATTR_DEFAULT]!==void 0)parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`);return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),definitionHtml:parts.join(" · ")}}layoutRow(l){let parts=[],cols=strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]);if(cols.length>0)parts.push(`columns ${cols.map((c)=>`${esc(c)}`).join(", ")}`);let sort=str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]);if(sort!==void 0)parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER])!==void 0?` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}`:""}`);if(typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]==="number")parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`);return{kind:esc(`${l.type}.${l.subType}`),name:esc(l.name),detailHtml:parts.join(", ")}}projectionBlock(from,n){let ix=this.ix,rows=[],bases=new Set;for(let f of ix.fields(n.id)){if(f.extends!==void 0)bases.add(ix.ownerOf(f.extends));for(let o of ix.children(f.id).filter((c)=>c.type===TYPE_ORIGIN)){let def=this.originDefinition(from,o);for(let src of this.refLinks(o,ORIGIN_PASSTHROUGH_ATTR_FROM))bases.add(ix.ownerOf(src.id));rows.push({field:esc(f.name),origin:esc(`origin.${o.subType}`),definitionHtml:def})}}return{basesHtml:[...bases].filter((b)=>b!==n.id).sort(byCodeUnit2).map((b)=>this.link(from,b)).join(", "),origins:rows,hasOrigins:rows.length>0}}originDefinition(from,o){let a=o.attrs,ref=(name)=>this.attrValues(o,name).map((v)=>v.link!==null&&!v.link.unresolved?this.link(from,v.link.id,localName(v.text)):`${esc(localName(v.text))}`).join(", "),parts=[],agg=str(a[ORIGIN_AGGREGATE_ATTR_AGG]);if(agg!==void 0)parts.push(`${esc(agg)}(${ref(ORIGIN_AGGREGATE_ATTR_OF)})`);else if(a[ORIGIN_AGGREGATE_ATTR_OF]!==void 0)parts.push(`of ${ref(ORIGIN_AGGREGATE_ATTR_OF)}`);if(a[ORIGIN_PASSTHROUGH_ATTR_FROM]!==void 0)parts.push(`from ${ref(ORIGIN_PASSTHROUGH_ATTR_FROM)}`);if(a[ORIGIN_AGGREGATE_ATTR_VIA]!==void 0)parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`);if(a[ORIGIN_COMPUTED_ATTR_EXPR]!==void 0)parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`);if(a[ORIGIN_AGGREGATE_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`);return parts.join(" · ")}reportBlock(from,n){let a=n.attrs,fromId=this.refLinks(n,OBJECT_REPORT_ATTR_FROM)[0]?.id??str(a[OBJECT_REPORT_ATTR_FROM]),resolve2=(name,kindType)=>{let hit=[fromId!==void 0?`${fromId}.${name}`:void 0,`${n.package===""?"":`${n.package}::`}${name}`].filter((x)=>x!==void 0).find((c)=>this.ix.byId.get(c)?.type===kindType||this.ix.byId.has(c)&&name.includes("."));return hit!==void 0?this.link(from,hit,name):`${esc(name)}`},spine=str(a[OBJECT_REPORT_ATTR_SPINE]);return{fromHtml:this.refHtml(from,n,OBJECT_REPORT_ATTR_FROM),spineHtml:spine!==void 0?`${esc(spine)}`:"",dimensionsHtml:strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d)=>resolve2(d,TYPE_DIMENSION)).join(", "),measuresHtml:strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m)=>resolve2(m,TYPE_MEASURE)).join(", "),segmentHtml:strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s)=>resolve2(s,TYPE_SEGMENT)).join(", "),filterHtml:a[OBJECT_REPORT_ATTR_FILTER]!==void 0?`${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}`:""}}generatedGroups(id){let groups=new Map;for(let f of this.ix.generated(id))groups.set(f.generatedBy,[...groups.get(f.generatedBy)??[],f.path]);return[...groups.keys()].sort(byCodeUnit2).map((g)=>({generator:esc(g),files:(groups.get(g)??[]).map((p)=>esc(p))}))}node(n){let ix=this.ix,from=this.objectPage(n),kindLabel=`${n.type}.${n.subType}`,whyRows=this.whyRows(from,n),attrs=this.attrRows(from,n),referrers=[...(ix.top(n.id)?.referencedBy??[]).map((e)=>e.from.id),...ix.claims(n.id).map((c)=>this.topOf(c.req).node.id)],refBy=[...new Set(referrers.filter((id)=>id!==n.id))].sort(byCodeUnit2).map((id)=>this.link(from,id));return{id:esc(n.id),name:esc(n.name),kindLabel:esc(kindLabel),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › ${esc(kindLabel)}`,isAbstract:n.abstract===!0,description:this.description(n),extendsHtml:n.extends!==void 0?this.link(from,n.extends):"",attrs,hasAttrs:attrs.length>0,members:ix.children(n.id).map((c)=>({anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),nameHtml:ix.reqById.has(c.id)?this.link(from,c.id):esc(c.name===""?`#${c.order}`:c.name),attrsHtml:this.attrRows(from,c).map((a)=>`@${a.name} ${a.valueHtml}`).join("
"),below:ix.children(c.id).length})),hasMembers:ix.children(n.id).length>0,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(from,n){return n.view.attrs.map((a)=>{let links=a.values.filter((v)=>v.link!==null&&!v.link.unresolved);return{name:esc(a.name),valueHtml:links.length>0&&links.length===a.values.length?links.map((v)=>this.link(from,v.link.id)).join(", "):`${esc(fmt(a.value))}`}})}prompt(n,text){let ix=this.ix,from=this.objectPage(n),payloadId=this.refLinks(n,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id,replyId=this.refLinks(n,TEMPLATE_ATTR_RESPONSE_REF)[0]?.id,vars=text!==void 0?templateVariables(text):void 0,payload=payloadId!==void 0?ix.byId.get(payloadId):void 0,reply=replyId!==void 0?ix.byId.get(replyId):void 0,payloadRows=payload!==void 0?ix.fields(payload.id).map((f)=>({name:esc(f.name),requiredHtml:f.attrs[FIELD_ATTR_REQUIRED]===!0?'required':"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)!==""?` → ${this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)}`:"",usedHtml:vars===void 0?'text not read':vars.has(f.name)?"yes":'no'})):[],replyRows=reply!==void 0?ix.fields(reply.id).map((f)=>({name:esc(f.name),type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),valuesHtml:f.subType===FIELD_SUBTYPE_ENUM?`
${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
`:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(` +`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var FREQUENCY_HOURLY="hourly",FREQUENCY_DAILY="daily",FREQUENCY_WEEKLY="weekly",FREQUENCY_MONTHLY="monthly";var AVAILABLE_BY_PATTERNS={[FREQUENCY_HOURLY]:/^:[0-5][0-9]$/,[FREQUENCY_DAILY]:/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/,[FREQUENCY_WEEKLY]:/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/,[FREQUENCY_MONTHLY]:/^(?:[1-9]|1[0-9]|2[0-8]) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/},AVAILABLE_BY_EXAMPLES={[FREQUENCY_HOURLY]:":15",[FREQUENCY_DAILY]:"03:00",[FREQUENCY_WEEKLY]:"Mon 06:00",[FREQUENCY_MONTHLY]:"1 06:00"};var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'
';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return``}function pct(x){return`${(Math.round(x*1e4)/100).toString()}%`}function legendHtml(withUnclaimed){return`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
${values.map(esc).join(" | ")}
`:"",column:esc(str(f.attrs[FIELD_ATTR_COLUMN])??""),flagsHtml:flags.map((x)=>`${esc(x)}`).join(""),claimsHtml:claims.map((c)=>`${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
")}}keyRow(from,c){let fields=strs(c.attrs[IDENTITY_ATTR_FIELDS]),target=this.refHtml(from,c,IDENTITY_REFERENCE_ATTR_REFERENCES)||this.refHtml(from,c,RELATIONSHIP_ATTR_OBJECT_REF),through=str(c.attrs[RELATIONSHIP_ATTR_THROUGH]),card=str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]),shape=c.type===TYPE_RELATIONSHIP?[card,through!==void 0?`through ${localName(through)}`:void 0].filter((x)=>x!==void 0).join(", "):`(${fields.join(", ")})`;return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),inheritedHtml:c.inheritedFrom!==void 0?'inherited':"",shape:esc(shape),targetHtml:target!==""?`→ ${target}`:""}}reportingRow(from,c){let a=c.attrs,parts=[],agg=str(a[REPORTING_ATTR_AGG]),of=this.refHtml(from,c,REPORTING_ATTR_OF,localName);if(agg!==void 0)parts.push(`${esc(agg)}(${of})`);else if(of!=="")parts.push(`of ${of}`);let num=str(a[REPORTING_ATTR_NUMERATOR]),den=str(a[REPORTING_ATTR_DENOMINATOR]);if(num!==void 0&&den!==void 0)parts.push(`${esc(num)} ÷ ${esc(den)}`);let via=str(a[REPORTING_ATTR_VIA]);if(via!==void 0)parts.push(`via ${esc(localName(via))}`);let grains=strs(a[REPORTING_ATTR_GRAINS]);if(grains.length>0)parts.push(`grains ${grains.map((g)=>`${esc(g)}`).join(" ")}`);let seg=str(a[REPORTING_ATTR_SEGMENT]);if(seg!==void 0)parts.push(`segment ${esc(seg)}`);if(a[REPORTING_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`);if(a[REPORTING_ATTR_DEFAULT]!==void 0)parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`);return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),definitionHtml:parts.join(" · ")}}layoutRow(l){let parts=[],cols=strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]);if(cols.length>0)parts.push(`columns ${cols.map((c)=>`${esc(c)}`).join(", ")}`);let sort=str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]);if(sort!==void 0)parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER])!==void 0?` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}`:""}`);if(typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]==="number")parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`);return{kind:esc(`${l.type}.${l.subType}`),name:esc(l.name),detailHtml:parts.join(", ")}}projectionBlock(from,n){let ix=this.ix,rows=[],bases=new Set;for(let f of ix.fields(n.id)){if(f.extends!==void 0)bases.add(ix.ownerOf(f.extends));for(let o of ix.children(f.id).filter((c)=>c.type===TYPE_ORIGIN)){let def=this.originDefinition(from,o);for(let src of this.refLinks(o,ORIGIN_PASSTHROUGH_ATTR_FROM))bases.add(ix.ownerOf(src.id));rows.push({field:esc(f.name),origin:esc(`origin.${o.subType}`),definitionHtml:def})}}return{basesHtml:[...bases].filter((b)=>b!==n.id).sort(byCodeUnit2).map((b)=>this.link(from,b)).join(", "),origins:rows,hasOrigins:rows.length>0}}originDefinition(from,o){let a=o.attrs,ref=(name)=>this.attrValues(o,name).map((v)=>v.link!==null&&!v.link.unresolved?this.link(from,v.link.id,localName(v.text)):`${esc(localName(v.text))}`).join(", "),parts=[],agg=str(a[ORIGIN_AGGREGATE_ATTR_AGG]);if(agg!==void 0)parts.push(`${esc(agg)}(${ref(ORIGIN_AGGREGATE_ATTR_OF)})`);else if(a[ORIGIN_AGGREGATE_ATTR_OF]!==void 0)parts.push(`of ${ref(ORIGIN_AGGREGATE_ATTR_OF)}`);if(a[ORIGIN_PASSTHROUGH_ATTR_FROM]!==void 0)parts.push(`from ${ref(ORIGIN_PASSTHROUGH_ATTR_FROM)}`);if(a[ORIGIN_AGGREGATE_ATTR_VIA]!==void 0)parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`);if(a[ORIGIN_COMPUTED_ATTR_EXPR]!==void 0)parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`);if(a[ORIGIN_AGGREGATE_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`);return parts.join(" · ")}reportBlock(from,n){let a=n.attrs,fromId=this.refLinks(n,OBJECT_REPORT_ATTR_FROM)[0]?.id??str(a[OBJECT_REPORT_ATTR_FROM]),resolve2=(name,kindType)=>{let hit=[fromId!==void 0?`${fromId}.${name}`:void 0,`${n.package===""?"":`${n.package}::`}${name}`].filter((x)=>x!==void 0).find((c)=>this.ix.byId.get(c)?.type===kindType||this.ix.byId.has(c)&&name.includes("."));return hit!==void 0?this.link(from,hit,name):`${esc(name)}`},spine=str(a[OBJECT_REPORT_ATTR_SPINE]);return{fromHtml:this.refHtml(from,n,OBJECT_REPORT_ATTR_FROM),spineHtml:spine!==void 0?`${esc(spine)}`:"",dimensionsHtml:strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d)=>resolve2(d,TYPE_DIMENSION)).join(", "),measuresHtml:strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m)=>resolve2(m,TYPE_MEASURE)).join(", "),segmentHtml:strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s)=>resolve2(s,TYPE_SEGMENT)).join(", "),filterHtml:a[OBJECT_REPORT_ATTR_FILTER]!==void 0?`${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}`:""}}generatedGroups(id){let groups=new Map;for(let f of this.ix.generated(id))groups.set(f.generatedBy,[...groups.get(f.generatedBy)??[],f.path]);return[...groups.keys()].sort(byCodeUnit2).map((g)=>({generator:esc(g),files:(groups.get(g)??[]).map((p)=>esc(p))}))}node(n){let ix=this.ix,from=this.objectPage(n),kindLabel=`${n.type}.${n.subType}`,whyRows=this.whyRows(from,n),attrs=this.attrRows(from,n),referrers=[...(ix.top(n.id)?.referencedBy??[]).map((e)=>e.from.id),...ix.claims(n.id).map((c)=>this.topOf(c.req).node.id)],refBy=[...new Set(referrers.filter((id)=>id!==n.id))].sort(byCodeUnit2).map((id)=>this.link(from,id));return{id:esc(n.id),name:esc(n.name),kindLabel:esc(kindLabel),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › ${esc(kindLabel)}`,isAbstract:n.abstract===!0,description:this.description(n),extendsHtml:n.extends!==void 0?this.link(from,n.extends):"",attrs,hasAttrs:attrs.length>0,members:ix.children(n.id).map((c)=>({anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),nameHtml:ix.reqById.has(c.id)?this.link(from,c.id):esc(c.name===""?`#${c.order}`:c.name),attrsHtml:this.attrRows(from,c).map((a)=>`@${a.name} ${a.valueHtml}`).join("
"),below:ix.children(c.id).length})),hasMembers:ix.children(n.id).length>0,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(from,n){return n.view.attrs.map((a)=>{let links=a.values.filter((v)=>v.link!==null&&!v.link.unresolved);return{name:esc(a.name),valueHtml:links.length>0&&links.length===a.values.length?links.map((v)=>this.link(from,v.link.id)).join(", "):`${esc(fmt(a.value))}`}})}prompt(n,text){let ix=this.ix,from=this.objectPage(n),payloadId=this.refLinks(n,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id,replyId=this.refLinks(n,TEMPLATE_ATTR_RESPONSE_REF)[0]?.id,vars=text!==void 0?templateVariables(text):void 0,payload=payloadId!==void 0?ix.byId.get(payloadId):void 0,reply=replyId!==void 0?ix.byId.get(replyId):void 0,payloadRows=payload!==void 0?ix.fields(payload.id).map((f)=>({name:esc(f.name),requiredHtml:f.attrs[FIELD_ATTR_REQUIRED]===!0?'required':"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)!==""?` → ${this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)}`:"",usedHtml:vars===void 0?'text not read':vars.has(f.name)?"yes":'no'})):[],replyRows=reply!==void 0?ix.fields(reply.id).map((f)=>({name:esc(f.name),type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),valuesHtml:f.subType===FIELD_SUBTYPE_ENUM?`
${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
`:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(` `).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
    ${tops.map((r)=>this.treeNode(page,r)).join("")}
`:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
  • ${`
    ${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}${dispositionPill(r)}${verdictBadge(r)}${bar}${links.join("")}
    ${esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??"")}
    `}${r.children.length>0?`
      ${r.children.map((c)=>this.treeNode(from,c)).join("")}
    `:""}
  • `}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`${cols.map((o)=>`
    ${this.link(from,o.id)}
    `).join("")}`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLink(from,top)}${cols.map(()=>'').join("")}`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`${levelBadge(r)}${esc(label)}${cols.map((o)=>tg.has(o.id)?`${statusGlyph(r.status)}`:'').join("")}`)}}return{tableHtml:rows.length>0?`${head}${rows.join("")}
    `:"",hasRows:rows.length>0,hasRequirements:ix.hasRequirements()}}trace(){let starts=this.ix.requirements.filter((r)=>r.level!==void 0&&r.level<=REQUIREMENT_LEVEL_SERVICE),fallback=starts.length===0?this.ix.topRequirements:[];return{options:[...starts,...fallback].map((r)=>({value:esc(r.node.id),label:esc(`${" ".repeat(Math.max(0,(r.level??1)-1))}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)}`)})),hasStarts:starts.length+fallback.length>0,hasUsage:!1}}gaps(){let ix=this.ix,from=PAGE_GAPS,cards=[],card=(title,count,source,why,bodyHtml)=>{cards.push({title:esc(title),count:esc(String(count)),source:esc(source),isGate:source==="meta verify",whyHtml:why,bodyHtml})};if(ix.view.sources.requirements){let findingsOf=(gate2)=>[...ix.requirements.flatMap((req)=>req.req.diagnostics.filter((d)=>d.source===GATE_SOURCE===gate2).map((d)=>({req,d}))),...ix.view.advisories.filter((d)=>d.path===""&&d.source===GATE_SOURCE===gate2).map((d)=>({d}))],table=(rows,chip)=>rows.length===0?'
    None.
    ':`${rows.map(({req,d})=>``).join("")}
    ${esc(d.code)}${req!==void 0?this.reqLink(from,req):""}
    ${esc(d.message)}
    `,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
    None.
    ');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
    None.
    ')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
    Not scanned.
    ');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
    No prompt text was read.
    ':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
    None.
    ':`
      ${items.map((i)=>`
    • ${i}
    • `).join("")}
    `}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found

    No such page

    ${escapeHtml2(r.path)} is not a page of this model.

    Overview

    `,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="

    No model yet

    The explorer is waiting for the running application's docs view.

    ";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="

    No model

    The source parameter is not a URL.

    ",paintLive();return}follow(source);return}if(!build())document.body.innerHTML="

    No model

    explorer-model.js did not load. Run meta gen to write it beside this page.

    ";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})(); diff --git a/fixtures/codegen-noop/rules/README.md b/fixtures/codegen-noop/rules/README.md index b5920bc3c8..374dbcd455 100644 --- a/fixtures/codegen-noop/rules/README.md +++ b/fixtures/codegen-noop/rules/README.md @@ -58,3 +58,17 @@ something half-built; these tests are what notice: Regenerate `without/` from `with/` by deleting every `transition.*` child and the `api.operational` node, nothing else. + +## The eventing and batch APIs (1.4.0) + +`with-delivery/meta.purchasing.json` is `with/` plus an `api.eventing` (`PurchasingEvents`, one +`operation.event` with a `binding.messaging`) and an `api.batch` (`PurchasingFeeds`, an +`operation.export` and an `operation.import`, each with a `binding.file`). Their operations +reference the same `DecisionInput` and `RequestSummary` the operational API does, so a generator +that read every `api` or took an operation's first binding whatever its subtype would derive a +target and emit a route for them. Nothing is generated from these two API kinds yet, so every +generator in every port, the rules-layer and service generators included, writes for +`with-delivery/` exactly what it writes for `with/`. The model explorer (`docs-site`) is the one +exception, as above, because it lists every node. Each port's test named above holds that too. + +Regenerate `with-delivery/` from `with/` by appending those two API nodes, nothing else. diff --git a/fixtures/codegen-noop/rules/with-delivery/meta.purchasing.json b/fixtures/codegen-noop/rules/with-delivery/meta.purchasing.json new file mode 100644 index 0000000000..7e342f4516 --- /dev/null +++ b/fixtures/codegen-noop/rules/with-delivery/meta.purchasing.json @@ -0,0 +1,251 @@ +{ + "metadata.root": { + "package": "acme::purchasing", + "children": [ + { + "object.entity": { + "name": "PurchaseRequest", + "children": [ + { + "source.rdb": { + "@table": "purchase_requests" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.string": { + "name": "title" + } + }, + { + "field.long": { + "name": "amountCents" + } + }, + { + "field.enum": { + "name": "status", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "@default": "draft", + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "draft" + ], + "@to": "submitted" + } + }, + { + "transition.action": { + "name": "approve", + "@from": [ + "submitted" + ], + "@to": "approved", + "@condition": { + "op": "gt", + "left": { + "field": "amountCents" + }, + "right": { + "value": 0 + } + } + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected", + "@permission": "purchasing.review" + } + } + ] + } + } + ] + } + }, + { + "object.value": { + "name": "DecisionInput", + "children": [ + { + "field.long": { + "name": "requestId", + "extends": "PurchaseRequest.id" + } + }, + { + "field.string": { + "name": "comment" + } + } + ] + } + }, + { + "object.projection": { + "name": "RequestSummary", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_request_summary" + } + }, + { + "field.long": { + "name": "id", + "extends": "PurchaseRequest.id" + } + }, + { + "field.string": { + "name": "title", + "extends": "PurchaseRequest.title" + } + }, + { + "identity.primary": { + "name": "pk", + "extends": "PurchaseRequest.pk" + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.command": { + "name": "decide", + "@inputRef": "DecisionInput", + "@transitions": [ + "approve", + "reject" + ], + "@permission": "purchasing.decide", + "@errors": [ + "over_budget", + "already_decided" + ], + "children": [ + { + "binding.rest": { + "@method": "PUT", + "@path": "/purchase-requests/{id}/decision" + } + } + ] + } + }, + { + "operation.query": { + "name": "openRequests", + "@outputRef": "RequestSummary", + "@many": true, + "@public": true + } + }, + { + "operation.query": { + "name": "requestSummary", + "@outputRef": "RequestSummary" + } + } + ] + } + }, + { + "api.eventing": { + "name": "PurchasingEvents", + "children": [ + { + "operation.event": { + "name": "requestDecided", + "@outputRef": "DecisionInput", + "@key": "requestId", + "children": [ + { + "binding.messaging": { + "@protocol": "kafka" + } + } + ] + } + } + ] + } + }, + { + "api.batch": { + "name": "PurchasingFeeds", + "children": [ + { + "operation.export": { + "name": "dailyRequests", + "@outputRef": "RequestSummary", + "@frequency": "daily", + "@availableBy": "03:00", + "children": [ + { + "binding.file": { + "@transport": "sftp", + "@path": "requests/", + "@fileName": "requests-{date}.csv", + "@format": "csv", + "@completion": "rename" + } + } + ] + } + }, + { + "operation.import": { + "name": "decisions", + "@inputRef": "DecisionInput", + "@frequency": "hourly", + "children": [ + { + "binding.file": { + "@transport": "objectStore", + "@path": "decisions/", + "@fileName": "decisions-{timestamp}.jsonl", + "@format": "jsonLines", + "@completion": "marker" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-api-binding-file-unknown-placeholder/expected-errors.json b/fixtures/conformance/error-api-binding-file-unknown-placeholder/expected-errors.json new file mode 100644 index 0000000000..756c138ee9 --- /dev/null +++ b/fixtures/conformance/error-api-binding-file-unknown-placeholder/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.parcels.json" + ], + "jsonPath": "$['metadata.root'].children[1]['api.batch'].children[0]['operation.import'].children[0]['binding.file']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-api-binding-file-unknown-placeholder/input/meta.parcels.json b/fixtures/conformance/error-api-binding-file-unknown-placeholder/input/meta.parcels.json new file mode 100644 index 0000000000..1ed0b157ab --- /dev/null +++ b/fixtures/conformance/error-api-binding-file-unknown-placeholder/input/meta.parcels.json @@ -0,0 +1,25 @@ +{ + "metadata.root": { + "package": "acme::parcels", + "children": [ + { "object.value": { "name": "ScanRecord", "children": [ { "field.string": { "name": "trackingNumber" } } ] } }, + { + "api.batch": { + "name": "ScanIntake", + "children": [ + { + "operation.import": { + "name": "scans", + "@inputRef": "ScanRecord", + "@frequency": "hourly", + "children": [ + { "binding.file": { "@transport": "sftp", "@fileName": "scans-{hour}.jsonl", "@format": "jsonLines" } } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-api-event-under-operational/expected-errors.json b/fixtures/conformance/error-api-event-under-operational/expected-errors.json new file mode 100644 index 0000000000..ecd3e5e39d --- /dev/null +++ b/fixtures/conformance/error-api-event-under-operational/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_CHILD_NOT_ALLOWED", + "source": { + "format": "json", + "files": [ + "meta.parcels.json" + ], + "jsonPath": "$['metadata.root'].children[1]['api.operational']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-api-event-under-operational/input/meta.parcels.json b/fixtures/conformance/error-api-event-under-operational/input/meta.parcels.json new file mode 100644 index 0000000000..b32fcc1324 --- /dev/null +++ b/fixtures/conformance/error-api-event-under-operational/input/meta.parcels.json @@ -0,0 +1,16 @@ +{ + "metadata.root": { + "package": "acme::parcels", + "children": [ + { "object.value": { "name": "ShipmentPlaced", "children": [ { "field.string": { "name": "trackingNumber" } } ] } }, + { + "api.operational": { + "name": "ShipmentApi", + "children": [ + { "operation.event": { "name": "shipmentPlaced", "@outputRef": "ShipmentPlaced" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-api-export-available-by-weekly-no-day/expected-errors.json b/fixtures/conformance/error-api-export-available-by-weekly-no-day/expected-errors.json new file mode 100644 index 0000000000..42917cd350 --- /dev/null +++ b/fixtures/conformance/error-api-export-available-by-weekly-no-day/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.ledger.json" + ], + "jsonPath": "$['metadata.root'].children[1]['api.batch'].children[0]['operation.export']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-api-export-available-by-weekly-no-day/input/meta.ledger.json b/fixtures/conformance/error-api-export-available-by-weekly-no-day/input/meta.ledger.json new file mode 100644 index 0000000000..575a3f84f0 --- /dev/null +++ b/fixtures/conformance/error-api-export-available-by-weekly-no-day/input/meta.ledger.json @@ -0,0 +1,16 @@ +{ + "metadata.root": { + "package": "acme::ledger", + "children": [ + { "object.value": { "name": "SettlementLine", "children": [ { "field.string": { "name": "reference" } } ] } }, + { + "api.batch": { + "name": "SettlementFeed", + "children": [ + { "operation.export": { "name": "weeklySettlement", "@outputRef": "SettlementLine", "@frequency": "weekly", "@availableBy": "06:00" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-ref-wrong-kind-carries-batch-on-stream/expected-errors.json b/fixtures/conformance/error-ref-wrong-kind-carries-batch-on-stream/expected-errors.json new file mode 100644 index 0000000000..78c913b08f --- /dev/null +++ b/fixtures/conformance/error-ref-wrong-kind-carries-batch-on-stream/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_REF_WRONG_KIND", + "source": { + "format": "json", + "files": [ + "meta.parcels.json" + ], + "jsonPath": "$['metadata.root'].children[2]['system.software'].children[0]['resource.stream']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-ref-wrong-kind-carries-batch-on-stream/input/meta.parcels.json b/fixtures/conformance/error-ref-wrong-kind-carries-batch-on-stream/input/meta.parcels.json new file mode 100644 index 0000000000..50560eb9bc --- /dev/null +++ b/fixtures/conformance/error-ref-wrong-kind-carries-batch-on-stream/input/meta.parcels.json @@ -0,0 +1,24 @@ +{ + "metadata.root": { + "package": "acme::parcels", + "children": [ + { "object.value": { "name": "ManifestLine", "children": [ { "field.string": { "name": "trackingNumber" } } ] } }, + { + "api.batch": { + "name": "ManifestFeed", + "children": [ + { "operation.export": { "name": "dailyManifest", "@outputRef": "ManifestLine", "@frequency": "daily", "@availableBy": "03:00" } } + ] + } + }, + { + "system.software": { + "name": "Parcels", + "children": [ + { "resource.stream": { "name": "events", "@carries": ["ManifestFeed"] } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/systems-api-eventing-batch/expected.json b/fixtures/conformance/systems-api-eventing-batch/expected.json new file mode 100644 index 0000000000..2e35c69448 --- /dev/null +++ b/fixtures/conformance/systems-api-eventing-batch/expected.json @@ -0,0 +1,291 @@ +{ + "metadata.root": { + "package": "acme::parcels", + "children": [ + { + "object.entity": { + "name": "Shipment", + "children": [ + { + "source.rdb": { + "@resource": "acme::parcels::Parcels.db", + "@table": "shipments" + } + }, + { + "field.string": { + "name": "trackingNumber" + } + }, + { + "field.date": { + "name": "shippedOn" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "trackingNumber" + ] + } + } + ] + } + }, + { + "object.projection": { + "name": "DailyManifestLine", + "children": [ + { + "source.rdb": { + "@kind": "materializedView", + "@materializedView": "daily_manifest_lines", + "@resource": "acme::parcels::Parcels.db" + } + }, + { + "field.string": { + "name": "trackingNumber", + "extends": "acme::parcels::Shipment.trackingNumber" + } + }, + { + "field.date": { + "name": "shippedOn", + "extends": "acme::parcels::Shipment.shippedOn" + } + }, + { + "identity.primary": { + "name": "pk", + "extends": "acme::parcels::Shipment.pk" + } + } + ] + } + }, + { + "object.value": { + "name": "ShipmentPlaced", + "children": [ + { + "field.string": { + "name": "trackingNumber", + "extends": "acme::parcels::Shipment.trackingNumber" + } + } + ] + } + }, + { + "object.value": { + "name": "ManifestLine", + "children": [ + { + "field.string": { + "name": "trackingNumber" + } + }, + { + "field.date": { + "name": "shippedOn" + } + } + ] + } + }, + { + "object.value": { + "name": "ScanRecord", + "children": [ + { + "field.string": { + "name": "trackingNumber" + } + }, + { + "field.timestamp": { + "name": "scannedAt" + } + } + ] + } + }, + { + "api.eventing": { + "name": "ShipmentEvents", + "children": [ + { + "operation.event": { + "name": "shipmentPlaced", + "@key": "trackingNumber", + "@outputRef": "acme::parcels::ShipmentPlaced", + "children": [ + { + "binding.messaging": { + "@protocol": "kafka" + } + } + ] + } + } + ] + } + }, + { + "api.eventing": { + "name": "LabelRequests", + "children": [ + { + "operation.event": { + "name": "labelRequested", + "@outputRef": "acme::parcels::ShipmentPlaced" + } + } + ] + } + }, + { + "api.batch": { + "name": "ManifestFeed", + "children": [ + { + "operation.export": { + "name": "dailyManifest", + "@availableBy": "03:00", + "@frequency": "daily", + "@outputRef": "acme::parcels::ManifestLine", + "children": [ + { + "binding.file": { + "@completion": "rename", + "@compression": "gzip", + "@fileName": "manifest-{date}.csv", + "@format": "csv", + "@path": "manifests/", + "@transport": "sftp" + } + } + ] + } + }, + { + "operation.export": { + "name": "weeklyManifest", + "@availableBy": "Mon 06:00", + "@frequency": "weekly", + "@outputRef": "acme::parcels::ManifestLine", + "children": [ + { + "binding.file": { + "@completion": "marker", + "@encryption": "pgp", + "@fileName": "manifest-week-{date}.jsonl", + "@format": "jsonLines", + "@path": "weekly/", + "@transport": "objectStore" + } + } + ] + } + }, + { + "operation.export": { + "name": "monthlyManifest", + "@availableBy": "1 06:00", + "@frequency": "monthly", + "@outputRef": "acme::parcels::ManifestLine" + } + }, + { + "operation.import": { + "name": "scans", + "@frequency": "hourly", + "@inputRef": "acme::parcels::ScanRecord", + "children": [ + { + "binding.file": { + "@completion": "rename", + "@fileName": "scans-{timestamp}.jsonl", + "@format": "jsonLines", + "@path": "scans/", + "@transport": "sftp" + } + } + ] + } + } + ] + } + }, + { + "system.software": { + "name": "Parcels", + "children": [ + { + "resource.rdb": { + "name": "db" + } + }, + { + "resource.stream": { + "name": "events", + "@carries": [ + "acme::parcels::ShipmentEvents" + ] + } + }, + { + "resource.objectStore": { + "name": "drops", + "@carries": [ + "acme::parcels::ManifestFeed" + ] + } + }, + { + "resource.queue": { + "name": "labelJobs", + "@carries": [ + "acme::parcels::LabelRequests" + ] + } + }, + { + "app.service": { + "name": "api", + "@provides": [ + "acme::parcels::ShipmentEvents" + ], + "@runsAs": "acme::parcels::Parcels.api" + } + }, + { + "app.job": { + "name": "manifestExport", + "@extracts": "acme::parcels::DailyManifestLine", + "@provides": [ + "acme::parcels::ManifestFeed" + ], + "@runsAs": "acme::parcels::Parcels.exporter", + "@schedule": "0 2 * * *" + } + }, + { + "role.service": { + "name": "api" + } + }, + { + "role.service": { + "name": "exporter" + } + } + ] + } + } + ] + } +} + diff --git a/fixtures/conformance/systems-api-eventing-batch/input/meta.parcels.json b/fixtures/conformance/systems-api-eventing-batch/input/meta.parcels.json new file mode 100644 index 0000000000..6d3f800cb1 --- /dev/null +++ b/fixtures/conformance/systems-api-eventing-batch/input/meta.parcels.json @@ -0,0 +1,142 @@ +{ + "metadata.root": { + "package": "acme::parcels", + "children": [ + { + "object.entity": { + "name": "Shipment", + "children": [ + { "source.rdb": { "@table": "shipments", "@resource": "Parcels.db" } }, + { "field.string": { "name": "trackingNumber" } }, + { "field.date": { "name": "shippedOn" } }, + { "identity.primary": { "name": "pk", "@fields": ["trackingNumber"] } } + ] + } + }, + { + "object.projection": { + "name": "DailyManifestLine", + "children": [ + { "source.rdb": { "@kind": "materializedView", "@materializedView": "daily_manifest_lines", "@resource": "Parcels.db" } }, + { "field.string": { "name": "trackingNumber", "extends": "Shipment.trackingNumber" } }, + { "field.date": { "name": "shippedOn", "extends": "Shipment.shippedOn" } }, + { "identity.primary": { "name": "pk", "extends": "Shipment.pk" } } + ] + } + }, + { + "object.value": { + "name": "ShipmentPlaced", + "children": [ + { "field.string": { "name": "trackingNumber", "extends": "Shipment.trackingNumber" } } + ] + } + }, + { + "object.value": { + "name": "ManifestLine", + "children": [ + { "field.string": { "name": "trackingNumber" } }, + { "field.date": { "name": "shippedOn" } } + ] + } + }, + { + "object.value": { + "name": "ScanRecord", + "children": [ + { "field.string": { "name": "trackingNumber" } }, + { "field.timestamp": { "name": "scannedAt" } } + ] + } + }, + { + "api.eventing": { + "name": "ShipmentEvents", + "children": [ + { + "operation.event": { + "name": "shipmentPlaced", + "@outputRef": "ShipmentPlaced", + "@key": "trackingNumber", + "children": [ + { "binding.messaging": { "@protocol": "kafka" } } + ] + } + } + ] + } + }, + { + "api.eventing": { + "name": "LabelRequests", + "children": [ + { "operation.event": { "name": "labelRequested", "@outputRef": "ShipmentPlaced" } } + ] + } + }, + { + "api.batch": { + "name": "ManifestFeed", + "children": [ + { + "operation.export": { + "name": "dailyManifest", + "@outputRef": "ManifestLine", + "@frequency": "daily", + "@availableBy": "03:00", + "children": [ + { "binding.file": { "@transport": "sftp", "@path": "manifests/", "@fileName": "manifest-{date}.csv", "@format": "csv", "@compression": "gzip", "@completion": "rename" } } + ] + } + }, + { + "operation.export": { + "name": "weeklyManifest", + "@outputRef": "ManifestLine", + "@frequency": "weekly", + "@availableBy": "Mon 06:00", + "children": [ + { "binding.file": { "@transport": "objectStore", "@path": "weekly/", "@fileName": "manifest-week-{date}.jsonl", "@format": "jsonLines", "@completion": "marker", "@encryption": "pgp" } } + ] + } + }, + { + "operation.export": { + "name": "monthlyManifest", + "@outputRef": "ManifestLine", + "@frequency": "monthly", + "@availableBy": "1 06:00" + } + }, + { + "operation.import": { + "name": "scans", + "@inputRef": "ScanRecord", + "@frequency": "hourly", + "children": [ + { "binding.file": { "@transport": "sftp", "@path": "scans/", "@fileName": "scans-{timestamp}.jsonl", "@format": "jsonLines", "@completion": "rename" } } + ] + } + } + ] + } + }, + { + "system.software": { + "name": "Parcels", + "children": [ + { "resource.rdb": { "name": "db" } }, + { "resource.stream": { "name": "events", "@carries": ["ShipmentEvents"] } }, + { "resource.objectStore": { "name": "drops", "@carries": ["ManifestFeed"] } }, + { "resource.queue": { "name": "labelJobs", "@carries": ["LabelRequests"] } }, + { "app.service": { "name": "api", "@runsAs": "api", "@provides": ["ShipmentEvents"] } }, + { "app.job": { "name": "manifestExport", "@runsAs": "exporter", "@schedule": "0 2 * * *", "@provides": ["ManifestFeed"], "@extracts": "DailyManifestLine" } }, + { "role.service": { "name": "api" } }, + { "role.service": { "name": "exporter" } } + ] + } + } + ] + } +} diff --git a/fixtures/metamodel-docs/data/INDEX.md.json b/fixtures/metamodel-docs/data/INDEX.md.json index ce382588ab..d17396ad11 100644 --- a/fixtures/metamodel-docs/data/INDEX.md.json +++ b/fixtures/metamodel-docs/data/INDEX.md.json @@ -5,6 +5,16 @@ "description": "Registry anchor for the declared API surface (ADR-0030, ADR-0054): not authorable. The `api` subtype axis is the interaction model, never the protocol; protocol lives in `binding.*` on each operation.", "page": "types/api.md#apibase" }, + { + "typeSubType": "api.batch", + "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "page": "types/api.md#apibatch" + }, + { + "typeSubType": "api.eventing", + "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "page": "types/api.md#apieventing" + }, { "typeSubType": "api.operational", "description": "A named, packaged request/response surface whose children are operations (ADR-0030). It is a wire contract: two of them (`v1`, `v2`) may declare the same operation side by side. The code behind it is one service per metadata package, whose surface is the package's operations (ADR-0067). Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", @@ -90,6 +100,16 @@ "description": "Registry anchor for protocol bindings (ADR-0030, ADR-0054): not authorable.", "page": "types/binding.md#bindingbase" }, + { + "typeSubType": "binding.file", + "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "page": "types/binding.md#bindingfile" + }, + { + "typeSubType": "binding.messaging", + "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "page": "types/binding.md#bindingmessaging" + }, { "typeSubType": "binding.rest", "description": "The HTTP method and path of an operation, declared only to override the derived ones. A query is `GET`, a command `POST`; the path is `//{id}/` for an operation with a target key and `//` without one. Most models never write it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", @@ -332,7 +352,7 @@ }, { "typeSubType": "operation.base", - "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.", + "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.", "page": "types/operation.md#operationbase" }, { @@ -340,6 +360,21 @@ "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", "page": "types/operation.md#operationcommand" }, + { + "typeSubType": "operation.event", + "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "page": "types/operation.md#operationevent" + }, + { + "typeSubType": "operation.export", + "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "page": "types/operation.md#operationexport" + }, + { + "typeSubType": "operation.import", + "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "page": "types/operation.md#operationimport" + }, { "typeSubType": "operation.query", "description": "A named operation that reads. Returns an `object.projection` (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", diff --git a/fixtures/metamodel-docs/data/providers.md.json b/fixtures/metamodel-docs/data/providers.md.json index 5331ee28e9..810c784910 100644 --- a/fixtures/metamodel-docs/data/providers.md.json +++ b/fixtures/metamodel-docs/data/providers.md.json @@ -468,25 +468,41 @@ "hasDescription": true, "description": "Business rules (ADR-0066, experimental): the declared API surface (api / operation / binding) and lifecycle moves (transition on a field.enum).", "hasOwns": true, - "owns": "`api.base`, `api.operational`, `binding.base`, `binding.rest`, `operation.base`, `operation.command`, `operation.query`, `transition.action`, `transition.base`", + "owns": "`api.base`, `api.batch`, `api.eventing`, `api.operational`, `binding.base`, `binding.file`, `binding.messaging`, `binding.rest`, `operation.base`, `operation.command`, `operation.event`, `operation.export`, `operation.import`, `operation.query`, `transition.action`, `transition.base`", "hasUniversal": false, "hasContributes": true, "contributes": [ + { + "typeSubType": "binding.file", + "attrs": "`@completion`, `@compression`, `@encryption`, `@fileName`, `@format`, `@path`, `@transport`" + }, + { + "typeSubType": "binding.messaging", + "attrs": "`@protocol`" + }, { "typeSubType": "binding.rest", "attrs": "`@method`, `@path`" }, { - "typeSubType": "operation.base", - "attrs": "`@inputRef`, `@objectRef`, `@outputRef`, `@permission`, `@public`" + "typeSubType": "operation.command", + "attrs": "`@errors`, `@inputRef`, `@objectRef`, `@outputRef`, `@permission`, `@public`, `@transitions`" }, { - "typeSubType": "operation.command", - "attrs": "`@errors`, `@transitions`" + "typeSubType": "operation.event", + "attrs": "`@key`, `@outputRef`" + }, + { + "typeSubType": "operation.export", + "attrs": "`@availableBy`, `@frequency`, `@outputRef`" + }, + { + "typeSubType": "operation.import", + "attrs": "`@frequency`, `@inputRef`" }, { "typeSubType": "operation.query", - "attrs": "`@many`" + "attrs": "`@inputRef`, `@many`, `@objectRef`, `@outputRef`, `@permission`, `@public`" }, { "typeSubType": "transition.action", @@ -517,11 +533,11 @@ }, { "typeSubType": "app.job", - "attrs": "`@schedule`" + "attrs": "`@extracts`, `@provides`, `@schedule`" }, { "typeSubType": "app.service", - "attrs": "`@public`" + "attrs": "`@provides`, `@public`" }, { "typeSubType": "build.image", @@ -569,16 +585,20 @@ }, { "typeSubType": "resource.objectStore", - "attrs": "`@publicRead`" + "attrs": "`@carries`, `@publicRead`" }, { "typeSubType": "resource.queue", - "attrs": "`@deadLetter`, `@ordered`" + "attrs": "`@carries`, `@deadLetter`, `@ordered`" }, { "typeSubType": "resource.rdb", "attrs": "`@schemas`" }, + { + "typeSubType": "resource.stream", + "attrs": "`@carries`" + }, { "typeSubType": "role.base", "attrs": "`@credential`, `@memberOf`" diff --git a/fixtures/metamodel-docs/data/types/api.md.json b/fixtures/metamodel-docs/data/types/api.md.json index 1f0de15905..4e89daec08 100644 --- a/fixtures/metamodel-docs/data/types/api.md.json +++ b/fixtures/metamodel-docs/data/types/api.md.json @@ -17,6 +17,47 @@ "children": [], "hasParents": false }, + { + "typeSubType": "api.batch", + "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "hasOwner": true, + "owner": "metaobjects-rules", + "hasImplementedIn": false, + "hasPorts": false, + "hasRules": true, + "rules": "Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.", + "hasWhenToUse": true, + "whenToUse": "A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.", + "hasExample": false, + "hasAttrs": false, + "attrs": [], + "hasChildren": true, + "children": [ + "`operation.export` — 0..*", + "`operation.import` — 0..*" + ], + "hasParents": false + }, + { + "typeSubType": "api.eventing", + "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "hasOwner": true, + "owner": "metaobjects-rules", + "hasImplementedIn": false, + "hasPorts": false, + "hasRules": true, + "rules": "Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.", + "hasWhenToUse": true, + "whenToUse": "Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.", + "hasExample": false, + "hasAttrs": false, + "attrs": [], + "hasChildren": true, + "children": [ + "`operation.event` — 0..*" + ], + "hasParents": false + }, { "typeSubType": "api.operational", "description": "A named, packaged request/response surface whose children are operations (ADR-0030). It is a wire contract: two of them (`v1`, `v2`) may declare the same operation side by side. The code behind it is one service per metadata package, whose surface is the package's operations (ADR-0067). Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", @@ -33,7 +74,8 @@ "attrs": [], "hasChildren": true, "children": [ - "`operation.*` — 0..*" + "`operation.command` — 0..*", + "`operation.query` — 0..*" ], "hasParents": false } diff --git a/fixtures/metamodel-docs/data/types/app.md.json b/fixtures/metamodel-docs/data/types/app.md.json index 66b0ed7eff..b4d6e774fb 100644 --- a/fixtures/metamodel-docs/data/types/app.md.json +++ b/fixtures/metamodel-docs/data/types/app.md.json @@ -80,6 +80,24 @@ "hasExample": false, "hasAttrs": true, "attrs": [ + { + "name": "extracts", + "type": "string", + "required": "no", + "default": "", + "allowed": "", + "provider": "metaobjects-systems-core", + "description": "The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object." + }, + { + "name": "provides", + "type": "string[]", + "required": "no", + "default": "", + "allowed": "", + "provider": "metaobjects-systems-core", + "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND." + }, { "name": "runsAs", "type": "string", @@ -118,6 +136,15 @@ "hasExample": false, "hasAttrs": true, "attrs": [ + { + "name": "provides", + "type": "string[]", + "required": "no", + "default": "", + "allowed": "", + "provider": "metaobjects-systems-core", + "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND." + }, { "name": "public", "type": "boolean", diff --git a/fixtures/metamodel-docs/data/types/binding.md.json b/fixtures/metamodel-docs/data/types/binding.md.json index 22527891db..e350b25da2 100644 --- a/fixtures/metamodel-docs/data/types/binding.md.json +++ b/fixtures/metamodel-docs/data/types/binding.md.json @@ -17,6 +17,114 @@ "children": [], "hasParents": false }, + { + "typeSubType": "binding.file", + "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "hasOwner": true, + "owner": "metaobjects-rules", + "hasImplementedIn": false, + "hasPorts": false, + "hasRules": false, + "hasWhenToUse": true, + "whenToUse": "Every export and import whose file conventions two parties must agree on.", + "hasExample": false, + "hasAttrs": true, + "attrs": [ + { + "name": "completion", + "type": "string", + "required": "no", + "default": "`none`", + "allowed": "`rename`, `marker`, `none`", + "provider": "metaobjects-rules", + "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." + }, + { + "name": "compression", + "type": "string", + "required": "no", + "default": "`none`", + "allowed": "`none`, `gzip`", + "provider": "metaobjects-rules", + "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." + }, + { + "name": "encryption", + "type": "string", + "required": "no", + "default": "`none`", + "allowed": "`none`, `pgp`", + "provider": "metaobjects-rules", + "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." + }, + { + "name": "fileName", + "type": "string", + "required": "yes", + "default": "", + "allowed": "", + "provider": "metaobjects-rules", + "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." + }, + { + "name": "format", + "type": "string", + "required": "yes", + "default": "", + "allowed": "`csv`, `jsonLines`, `parquet`", + "provider": "metaobjects-rules", + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + }, + { + "name": "path", + "type": "string", + "required": "no", + "default": "", + "allowed": "", + "provider": "metaobjects-rules", + "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." + }, + { + "name": "transport", + "type": "string", + "required": "yes", + "default": "", + "allowed": "`sftp`, `objectStore`", + "provider": "metaobjects-rules", + "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." + } + ], + "hasChildren": false, + "children": [], + "hasParents": false + }, + { + "typeSubType": "binding.messaging", + "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "hasOwner": true, + "owner": "metaobjects-rules", + "hasImplementedIn": false, + "hasPorts": false, + "hasRules": false, + "hasWhenToUse": true, + "whenToUse": "Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.", + "hasExample": false, + "hasAttrs": true, + "attrs": [ + { + "name": "protocol", + "type": "string", + "required": "no", + "default": "", + "allowed": "`kafka`, `amqp`, `mqtt`, `sqs`", + "provider": "metaobjects-rules", + "description": "The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks." + } + ], + "hasChildren": false, + "children": [], + "hasParents": false + }, { "typeSubType": "binding.rest", "description": "The HTTP method and path of an operation, declared only to override the derived ones. A query is `GET`, a command `POST`; the path is `//{id}/` for an operation with a target key and `//` without one. Most models never write it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", diff --git a/fixtures/metamodel-docs/data/types/operation.md.json b/fixtures/metamodel-docs/data/types/operation.md.json index 689bebf30d..d1275f21d4 100644 --- a/fixtures/metamodel-docs/data/types/operation.md.json +++ b/fixtures/metamodel-docs/data/types/operation.md.json @@ -3,7 +3,7 @@ "sections": [ { "typeSubType": "operation.base", - "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.", + "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.", "hasOwner": true, "owner": "metaobjects-rules", "hasImplementedIn": false, @@ -11,8 +11,34 @@ "hasRules": false, "hasWhenToUse": false, "hasExample": false, + "hasAttrs": false, + "attrs": [], + "hasChildren": false, + "children": [], + "hasParents": false + }, + { + "typeSubType": "operation.command", + "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "hasOwner": true, + "owner": "metaobjects-rules", + "hasImplementedIn": false, + "hasPorts": false, + "hasRules": false, + "hasWhenToUse": true, + "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.", + "hasExample": false, "hasAttrs": true, "attrs": [ + { + "name": "errors", + "type": "string[]", + "required": "no", + "default": "", + "allowed": "", + "provider": "metaobjects-rules", + "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE." + }, { "name": "inputRef", "type": "string", @@ -57,94 +83,143 @@ "allowed": "", "provider": "metaobjects-rules", "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." + }, + { + "name": "transitions", + "type": "string[]", + "required": "no", + "default": "", + "allowed": "", + "provider": "metaobjects-rules", + "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)." } ], "hasChildren": true, "children": [ - "`binding.*` — 0..*" + "`binding.rest` — 0..*" ], "hasParents": false }, { - "typeSubType": "operation.command", - "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "typeSubType": "operation.event", + "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", "hasOwner": true, "owner": "metaobjects-rules", "hasImplementedIn": false, "hasPorts": false, "hasRules": false, "hasWhenToUse": true, - "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.", + "whenToUse": "Each distinct fact a consumer may react to: placed, delivered, cancelled.", "hasExample": false, "hasAttrs": true, "attrs": [ { - "name": "errors", - "type": "string[]", + "name": "key", + "type": "string", "required": "no", "default": "", "allowed": "", "provider": "metaobjects-rules", - "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE." + "description": "The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised." }, { - "name": "inputRef", + "name": "outputRef", "type": "string", - "required": "no", + "required": "yes", "default": "", "allowed": "", "provider": "metaobjects-rules", - "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." - }, + "description": "The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." + } + ], + "hasChildren": true, + "children": [ + "`binding.messaging` — 0..*" + ], + "hasParents": false + }, + { + "typeSubType": "operation.export", + "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "hasOwner": true, + "owner": "metaobjects-rules", + "hasImplementedIn": false, + "hasPorts": false, + "hasRules": false, + "hasWhenToUse": true, + "whenToUse": "A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.", + "hasExample": false, + "hasAttrs": true, + "attrs": [ { - "name": "objectRef", + "name": "availableBy", "type": "string", "required": "no", "default": "", "allowed": "", "provider": "metaobjects-rules", - "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." + "description": "The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised." }, { - "name": "outputRef", + "name": "frequency", "type": "string", - "required": "no", + "required": "yes", "default": "", - "allowed": "", + "allowed": "`hourly`, `daily`, `weekly`, `monthly`", "provider": "metaobjects-rules", - "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." + "description": "How often a new file appears: hourly, daily, weekly or monthly." }, { - "name": "permission", + "name": "outputRef", "type": "string", - "required": "no", + "required": "yes", "default": "", "allowed": "", "provider": "metaobjects-rules", - "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." - }, + "description": "The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." + } + ], + "hasChildren": true, + "children": [ + "`binding.file` — 0..*" + ], + "hasParents": false + }, + { + "typeSubType": "operation.import", + "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "hasOwner": true, + "owner": "metaobjects-rules", + "hasImplementedIn": false, + "hasPorts": false, + "hasRules": false, + "hasWhenToUse": true, + "whenToUse": "A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.", + "hasExample": false, + "hasAttrs": true, + "attrs": [ { - "name": "public", - "type": "boolean", - "required": "no", + "name": "frequency", + "type": "string", + "required": "yes", "default": "", - "allowed": "", + "allowed": "`hourly`, `daily`, `weekly`, `monthly`", "provider": "metaobjects-rules", - "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." + "description": "How often a new file is expected: hourly, daily, weekly or monthly." }, { - "name": "transitions", - "type": "string[]", - "required": "no", + "name": "inputRef", + "type": "string", + "required": "yes", "default": "", "allowed": "", "provider": "metaobjects-rules", - "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)." + "description": "The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE." } ], "hasChildren": true, "children": [ - "`binding.*` — 0..*" + "`binding.file` — 0..*" ], "hasParents": false }, @@ -218,7 +293,7 @@ ], "hasChildren": true, "children": [ - "`binding.*` — 0..*" + "`binding.rest` — 0..*" ], "hasParents": false } diff --git a/fixtures/metamodel-docs/data/types/resource.md.json b/fixtures/metamodel-docs/data/types/resource.md.json index 9bea5586f7..2583c18967 100644 --- a/fixtures/metamodel-docs/data/types/resource.md.json +++ b/fixtures/metamodel-docs/data/types/resource.md.json @@ -103,6 +103,15 @@ "hasExample": false, "hasAttrs": true, "attrs": [ + { + "name": "carries", + "type": "string[]", + "required": "no", + "default": "", + "allowed": "", + "provider": "metaobjects-systems-core", + "description": "The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`." + }, { "name": "publicRead", "type": "boolean", @@ -139,6 +148,15 @@ "hasExample": false, "hasAttrs": true, "attrs": [ + { + "name": "carries", + "type": "string[]", + "required": "no", + "default": "", + "allowed": "", + "provider": "metaobjects-systems-core", + "description": "The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`." + }, { "name": "deadLetter", "type": "boolean", @@ -247,6 +265,15 @@ "hasExample": false, "hasAttrs": true, "attrs": [ + { + "name": "carries", + "type": "string[]", + "required": "no", + "default": "", + "allowed": "", + "provider": "metaobjects-systems-core", + "description": "The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`." + }, { "name": "residency", "type": "string", diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md index 800c390301..49591af340 100644 --- a/fixtures/metamodel-docs/expected/INDEX.md +++ b/fixtures/metamodel-docs/expected/INDEX.md @@ -16,6 +16,8 @@ children and the cardinality of that subtype. Documentation attributes | Type.subType | Description | Page | | --- | --- | --- | | `api.base` | Registry anchor for the declared API surface (ADR-0030, ADR-0054): not authorable. The `api` subtype axis is the interaction model, never the protocol; protocol lives in `binding.*` on each operation. | [types/api.md#apibase](types/api.md#apibase) | +| `api.batch` | A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/api.md#apibatch](types/api.md#apibatch) | +| `api.eventing` | A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/api.md#apieventing](types/api.md#apieventing) | | `api.operational` | A named, packaged request/response surface whose children are operations (ADR-0030). It is a wire contract: two of them (`v1`, `v2`) may declare the same operation side by side. The code behind it is one service per metadata package, whose surface is the package's operations (ADR-0067). Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/api.md#apioperational](types/api.md#apioperational) | | `app.base` | Abstract app base: the attributes every app.* shares. Not authored directly: an `app.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED). | [types/app.md#appbase](types/app.md#appbase) | | `app.client` | Code that runs on the user's device: a single-page web app, a static site, a mobile app. It calls services; it serves nothing itself. | [types/app.md#appclient](types/app.md#appclient) | @@ -33,6 +35,8 @@ children and the cardinality of that subtype. Documentation attributes | `attr.properties` | A key/value map attribute (a bag of arbitrary author-supplied properties). Object-shaped value; the registered escape hatch for author-supplied properties (exempt from the strict-attr check, ADR-0023). | [types/attr.md#attrproperties](types/attr.md#attrproperties) | | `attr.string` | A string-valued metadata attribute. Coerces to and validates as text; the default value-type for inline @-syntax attrs (array-of-string is the same subtype with isArray). | [types/attr.md#attrstring](types/attr.md#attrstring) | | `binding.base` | Registry anchor for protocol bindings (ADR-0030, ADR-0054): not authorable. | [types/binding.md#bindingbase](types/binding.md#bindingbase) | +| `binding.file` | How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/binding.md#bindingfile](types/binding.md#bindingfile) | +| `binding.messaging` | How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/binding.md#bindingmessaging](types/binding.md#bindingmessaging) | | `binding.rest` | The HTTP method and path of an operation, declared only to override the derived ones. A query is `GET`, a command `POST`; the path is `//{id}/` for an operation with a target key and `//` without one. Most models never write it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/binding.md#bindingrest](types/binding.md#bindingrest) | | `build.base` | Abstract build base: how an app's deployable is made, the same in every environment. A build is a child of an app. Not authored directly: a `build.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED). | [types/build.md#buildbase](types/build.md#buildbase) | | `build.image` | The app is shipped as a prebuilt container image that its publisher keeps in a registry. The tag deployed is a setting, never an attribute here. | [types/build.md#buildimage](types/build.md#buildimage) | @@ -81,8 +85,11 @@ children and the cardinality of that subtype. Documentation attributes | `object.projection` | A derived read-only representation of entities. Its fields are extends-bound / origin-derived / self-declared-under-external-assembly, all read-only at the subtype level. Identity is optional and MUST extend an entity identity; sources are restricted to read-only @kinds. The declared field set IS the exposure (inclusive, fail-closed). | [types/object.md#objectprojection](types/object.md#objectprojection) | | `object.report` | A declared report (FR-044): a fixed combination of dimensions and measures of ONE entity (@from), compiled to a read-only view. One row per distinct dimension tuple; no dimensions means exactly one row. Fields are DERIVED, not declared: one per dimension (a time dimension's field is , e.g. purchasedAtDay) and one per measure. Every measure must belong to @from (two fact tables are two reports). @filter and @segment scope rows before grouping and combine by AND. Read-only: no writes, no get-by-id. | [types/object.md#objectreport](types/object.md#objectreport) | | `object.value` | A value object — pure shape with NO identity and NO source, ever. Constructed (by caller / embedding), never populated from a store. May `extends` an entity's fields to reuse shape. Equality is by content. | [types/object.md#objectvalue](types/object.md#objectvalue) | -| `operation.base` | Registry anchor for the attributes every operation shares (ADR-0054): not authorable. | [types/operation.md#operationbase](types/operation.md#operationbase) | +| `operation.base` | Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes. | [types/operation.md#operationbase](types/operation.md#operationbase) | | `operation.command` | A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/operation.md#operationcommand](types/operation.md#operationcommand) | +| `operation.event` | Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/operation.md#operationevent](types/operation.md#operationevent) | +| `operation.export` | A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/operation.md#operationexport](types/operation.md#operationexport) | +| `operation.import` | A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/operation.md#operationimport](types/operation.md#operationimport) | | `operation.query` | A named operation that reads. Returns an `object.projection` (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/operation.md#operationquery](types/operation.md#operationquery) | | `organization.base` | Abstract organization base: the shared root of organization.company and organization.unit (ADR-0070, call 2). Not authored directly: an `organization.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED). | [types/organization.md#organizationbase](types/organization.md#organizationbase) | | `organization.company` | A legal entity: it can own systems, operate environments and be handed credentials. Declared once, by the company itself, under its own package, and imported by everyone else. There is no vendor or customer kind: whether a company is one is a fact about the reader, not the company. | [types/organization.md#organizationcompany](types/organization.md#organizationcompany) | diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md index 24e2d772b7..ae60534939 100644 --- a/fixtures/metamodel-docs/expected/providers.md +++ b/fixtures/metamodel-docs/expected/providers.md @@ -160,14 +160,18 @@ Requirements: requirement.functional and requirement.architectural, declared at Business rules (ADR-0066, experimental): the declared API surface (api / operation / binding) and lifecycle moves (transition on a field.enum). -**Owns (registers):** `api.base`, `api.operational`, `binding.base`, `binding.rest`, `operation.base`, `operation.command`, `operation.query`, `transition.action`, `transition.base` +**Owns (registers):** `api.base`, `api.batch`, `api.eventing`, `api.operational`, `binding.base`, `binding.file`, `binding.messaging`, `binding.rest`, `operation.base`, `operation.command`, `operation.event`, `operation.export`, `operation.import`, `operation.query`, `transition.action`, `transition.base` **Contributes attributes:** +- `binding.file`: `@completion`, `@compression`, `@encryption`, `@fileName`, `@format`, `@path`, `@transport` +- `binding.messaging`: `@protocol` - `binding.rest`: `@method`, `@path` -- `operation.base`: `@inputRef`, `@objectRef`, `@outputRef`, `@permission`, `@public` -- `operation.command`: `@errors`, `@transitions` -- `operation.query`: `@many` +- `operation.command`: `@errors`, `@inputRef`, `@objectRef`, `@outputRef`, `@permission`, `@public`, `@transitions` +- `operation.event`: `@key`, `@outputRef` +- `operation.export`: `@availableBy`, `@frequency`, `@outputRef` +- `operation.import`: `@frequency`, `@inputRef` +- `operation.query`: `@inputRef`, `@many`, `@objectRef`, `@outputRef`, `@permission`, `@public` - `transition.action`: `@condition`, `@from`, `@to` - `transition.base`: `@permission`, `@public` @@ -181,8 +185,8 @@ Systems (ADR-0070): organization, system.software, app (service, client, job), b - `app.base`: `@runsAs` - `app.client`: `@shell` -- `app.job`: `@schedule` -- `app.service`: `@public` +- `app.job`: `@extracts`, `@provides`, `@schedule` +- `app.service`: `@provides`, `@public` - `build.image`: `@repository` - `grant.api`: `@api`, `@credential`, `@operations` - `grant.document`: `@access`, `@collection`, `@resource` @@ -194,9 +198,10 @@ Systems (ADR-0070): organization, system.software, app (service, client, job), b - `grant.stream`: `@access`, `@resource` - `resource.base`: `@residency` - `resource.keyValue`: `@volatile` -- `resource.objectStore`: `@publicRead` -- `resource.queue`: `@deadLetter`, `@ordered` +- `resource.objectStore`: `@carries`, `@publicRead` +- `resource.queue`: `@carries`, `@deadLetter`, `@ordered` - `resource.rdb`: `@schemas` +- `resource.stream`: `@carries` - `role.base`: `@credential`, `@memberOf` - `role.token`: `@heldBy` - `source.document`: `@collection`, `@resource` diff --git a/fixtures/metamodel-docs/expected/types/api.md b/fixtures/metamodel-docs/expected/types/api.md index 63febeb56f..7e05f6781c 100644 --- a/fixtures/metamodel-docs/expected/types/api.md +++ b/fixtures/metamodel-docs/expected/types/api.md @@ -24,6 +24,43 @@ _No subtype-specific attributes._ _No structural children._ +### api.batch + +A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). + +**Owning provider:** metaobjects-rules + +**Rules:** Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name. + +**When to use:** A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off. + +**Attributes** + +_No subtype-specific attributes._ + +**Allowed children** + +- `operation.export` — 0..* +- `operation.import` — 0..* + +### api.eventing + +A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). + +**Owning provider:** metaobjects-rules + +**Rules:** Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name. + +**When to use:** Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it. + +**Attributes** + +_No subtype-specific attributes._ + +**Allowed children** + +- `operation.event` — 0..* + ### api.operational A named, packaged request/response surface whose children are operations (ADR-0030). It is a wire contract: two of them (`v1`, `v2`) may declare the same operation side by side. The code behind it is one service per metadata package, whose surface is the package's operations (ADR-0067). Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). @@ -40,5 +77,6 @@ _No subtype-specific attributes._ **Allowed children** -- `operation.*` — 0..* +- `operation.command` — 0..* +- `operation.query` — 0..* diff --git a/fixtures/metamodel-docs/expected/types/app.md b/fixtures/metamodel-docs/expected/types/app.md index 926cdfd6e2..9cd3ff6c01 100644 --- a/fixtures/metamodel-docs/expected/types/app.md +++ b/fixtures/metamodel-docs/expected/types/app.md @@ -57,6 +57,8 @@ Work that runs to completion and exits: a scheduled task, a migration, a one-off | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | +| `@extracts` | string | no | | | metaobjects-systems-core | The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object. | +| `@provides` | string[] | no | | | metaobjects-systems-core | The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. | | `@runsAs` | string | no | | | metaobjects-systems-core | The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system). | | `@schedule` | string | no | | | metaobjects-systems-core | When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered. | @@ -76,6 +78,7 @@ A long-running process that answers requests: a web server, an API, a socket ser | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | +| `@provides` | string[] | no | | | metaobjects-systems-core | The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. | | `@public` | boolean | no | | | metaobjects-systems-core | The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names. | | `@runsAs` | string | no | | | metaobjects-systems-core | The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system). | diff --git a/fixtures/metamodel-docs/expected/types/binding.md b/fixtures/metamodel-docs/expected/types/binding.md index c7b5fa826e..f182c8dc32 100644 --- a/fixtures/metamodel-docs/expected/types/binding.md +++ b/fixtures/metamodel-docs/expected/types/binding.md @@ -24,6 +24,48 @@ _No subtype-specific attributes._ _No structural children._ +### binding.file + +How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). + +**Owning provider:** metaobjects-rules + +**When to use:** Every export and import whose file conventions two parties must agree on. + +**Attributes** + +| Attribute | Type | Required | Default | Allowed values | Provider | Description | +| --- | --- | --- | --- | --- | --- | --- | +| `@completion` | string | no | `none` | `rename`, `marker`, `none` | metaobjects-rules | How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing. | +| `@compression` | string | no | `none` | `none`, `gzip` | metaobjects-rules | none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk. | +| `@encryption` | string | no | `none` | `none`, `pgp` | metaobjects-rules | none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key. | +| `@fileName` | string | yes | | | metaobjects-rules | The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE. | +| `@format` | string | yes | | `csv`, `jsonLines`, `parquet` | metaobjects-rules | How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. | +| `@path` | string | no | | | metaobjects-rules | The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store. | +| `@transport` | string | yes | | `sftp`, `objectStore` | metaobjects-rules | How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product. | + +**Allowed children** + +_No structural children._ + +### binding.messaging + +How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). + +**Owning provider:** metaobjects-rules + +**When to use:** Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out. + +**Attributes** + +| Attribute | Type | Required | Default | Allowed values | Provider | Description | +| --- | --- | --- | --- | --- | --- | --- | +| `@protocol` | string | no | | `kafka`, `amqp`, `mqtt`, `sqs` | metaobjects-rules | The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks. | + +**Allowed children** + +_No structural children._ + ### binding.rest The HTTP method and path of an operation, declared only to override the derived ones. A query is `GET`, a command `POST`; the path is `//{id}/` for an operation with a target key and `//` without one. Most models never write it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). diff --git a/fixtures/metamodel-docs/expected/types/operation.md b/fixtures/metamodel-docs/expected/types/operation.md index 65b92ceb9e..7ff5ec3446 100644 --- a/fixtures/metamodel-docs/expected/types/operation.md +++ b/fixtures/metamodel-docs/expected/types/operation.md @@ -12,23 +12,17 @@ documentation attributes are omitted here (see [providers.md](../providers.md)). ### operation.base -Registry anchor for the attributes every operation shares (ADR-0054): not authorable. +Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes. **Owning provider:** metaobjects-rules **Attributes** -| Attribute | Type | Required | Default | Allowed values | Provider | Description | -| --- | --- | --- | --- | --- | --- | --- | -| `@inputRef` | string | no | | | metaobjects-rules | The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE. | -| `@objectRef` | string | no | | | metaobjects-rules | The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED). | -| `@outputRef` | string | no | | | metaobjects-rules | The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE. | -| `@permission` | string | no | | | metaobjects-rules | The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one. | -| `@public` | boolean | no | | | metaobjects-rules | The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT. | +_No subtype-specific attributes._ **Allowed children** -- `binding.*` — 0..* +_No structural children._ ### operation.command @@ -52,7 +46,65 @@ A named operation that changes state. Takes an `object.value` (ADR-0030). Its bo **Allowed children** -- `binding.*` — 0..* +- `binding.rest` — 0..* + +### operation.event + +Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). + +**Owning provider:** metaobjects-rules + +**When to use:** Each distinct fact a consumer may react to: placed, delivered, cancelled. + +**Attributes** + +| Attribute | Type | Required | Default | Allowed values | Provider | Description | +| --- | --- | --- | --- | --- | --- | --- | +| `@key` | string | no | | | metaobjects-rules | The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised. | +| `@outputRef` | string | yes | | | metaobjects-rules | The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE. | + +**Allowed children** + +- `binding.messaging` — 0..* + +### operation.export + +A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). + +**Owning provider:** metaobjects-rules + +**When to use:** A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement. + +**Attributes** + +| Attribute | Type | Required | Default | Allowed values | Provider | Description | +| --- | --- | --- | --- | --- | --- | --- | +| `@availableBy` | string | no | | | metaobjects-rules | The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised. | +| `@frequency` | string | yes | | `hourly`, `daily`, `weekly`, `monthly` | metaobjects-rules | How often a new file appears: hourly, daily, weekly or monthly. | +| `@outputRef` | string | yes | | | metaobjects-rules | The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE. | + +**Allowed children** + +- `binding.file` — 0..* + +### operation.import + +A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). + +**Owning provider:** metaobjects-rules + +**When to use:** A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders. + +**Attributes** + +| Attribute | Type | Required | Default | Allowed values | Provider | Description | +| --- | --- | --- | --- | --- | --- | --- | +| `@frequency` | string | yes | | `hourly`, `daily`, `weekly`, `monthly` | metaobjects-rules | How often a new file is expected: hourly, daily, weekly or monthly. | +| `@inputRef` | string | yes | | | metaobjects-rules | The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE. | + +**Allowed children** + +- `binding.file` — 0..* ### operation.query @@ -75,5 +127,5 @@ A named operation that reads. Returns an `object.projection` (or an entity or va **Allowed children** -- `binding.*` — 0..* +- `binding.rest` — 0..* diff --git a/fixtures/metamodel-docs/expected/types/resource.md b/fixtures/metamodel-docs/expected/types/resource.md index 1063ea9314..24c769589d 100644 --- a/fixtures/metamodel-docs/expected/types/resource.md +++ b/fixtures/metamodel-docs/expected/types/resource.md @@ -75,6 +75,7 @@ Files and blobs addressed by key. | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | +| `@carries` | string[] | no | | | metaobjects-systems-core | The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`. | | `@publicRead` | boolean | no | | | metaobjects-systems-core | Anyone may read the objects without a credential. Absent means every read needs a grant. | | `@residency` | string | no | `free` | `free`, `confined` | metaobjects-systems-core | Where the data may be kept. confined: every copy of this data, in any one provision, stays inside one jurisdiction, and only apps running inside it may reach it directly. free (the default): no such limit. | @@ -94,6 +95,7 @@ A message queue: each message is handed to one consumer and gone once it is hand | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | +| `@carries` | string[] | no | | | metaobjects-systems-core | The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`. | | `@deadLetter` | boolean | no | | | metaobjects-systems-core | A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting. | | `@ordered` | boolean | no | | | metaobjects-systems-core | Messages with the same key are delivered in the order they were sent. Absent means no order is promised. | | `@residency` | string | no | `free` | `free`, `confined` | metaobjects-systems-core | Where the data may be kept. confined: every copy of this data, in any one provision, stays inside one jurisdiction, and only apps running inside it may reach it directly. free (the default): no such limit. | @@ -151,6 +153,7 @@ A retained, ordered log that many consumers read, each at its own position. A me | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | +| `@carries` | string[] | no | | | metaobjects-systems-core | The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`. | | `@residency` | string | no | `free` | `free`, `confined` | metaobjects-systems-core | Where the data may be kept. confined: every copy of this data, in any one provision, stays inside one jurisdiction, and only apps running inside it may reach it directly. free (the default): no such limit. | **Allowed children** diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 5706cbd3a3..95610a7bd0 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -8,6 +8,47 @@ "attrs": [], "children": [] }, + { + "type": "api", + "subType": "batch", + "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "rules": "Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.", + "whenToUse": "A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.", + "attrs": [], + "children": [ + { + "childType": "operation", + "childSubType": "export", + "childName": "*", + "min": 0, + "max": null + }, + { + "childType": "operation", + "childSubType": "import", + "childName": "*", + "min": 0, + "max": null + } + ] + }, + { + "type": "api", + "subType": "eventing", + "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "rules": "Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.", + "whenToUse": "Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.", + "attrs": [], + "children": [ + { + "childType": "operation", + "childSubType": "event", + "childName": "*", + "min": 0, + "max": null + } + ] + }, { "type": "api", "subType": "operational", @@ -18,7 +59,14 @@ "children": [ { "childType": "operation", - "childSubType": "*", + "childSubType": "command", + "childName": "*", + "min": 0, + "max": null + }, + { + "childType": "operation", + "childSubType": "query", "childName": "*", "min": 0, "max": null @@ -101,6 +149,30 @@ "description": "Work that runs to completion and exits: a scheduled task, a migration, a one-off batch. It may run on a schedule (@schedule) or when something triggers it.", "whenToUse": "A cron job, a nightly import, a queue drain that is not a long-running service.", "attrs": [ + { + "name": "extracts", + "valueType": "string", + "isArray": false, + "required": false, + "ref": { + "targetType": "object", + "targetSubTypes": [ + "entity", + "projection" + ] + }, + "description": "The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object." + }, + { + "name": "provides", + "valueType": "string", + "isArray": true, + "required": false, + "ref": { + "targetType": "api" + }, + "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND." + }, { "name": "runsAs", "valueType": "string", @@ -140,6 +212,16 @@ "description": "A long-running process that answers requests: a web server, an API, a socket server.", "whenToUse": "Anything that listens on a port and stays up.", "attrs": [ + { + "name": "provides", + "valueType": "string", + "isArray": true, + "required": false, + "ref": { + "targetType": "api" + }, + "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND." + }, { "name": "public", "valueType": "boolean", @@ -257,6 +339,108 @@ "attrs": [], "children": [] }, + { + "type": "binding", + "subType": "file", + "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Every export and import whose file conventions two parties must agree on.", + "attrs": [ + { + "name": "completion", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "rename", + "marker", + "none" + ], + "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." + }, + { + "name": "compression", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "none", + "gzip" + ], + "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." + }, + { + "name": "encryption", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "none", + "pgp" + ], + "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." + }, + { + "name": "fileName", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." + }, + { + "name": "format", + "valueType": "string", + "isArray": false, + "required": true, + "allowedValues": [ + "csv", + "jsonLines", + "parquet" + ], + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + }, + { + "name": "path", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." + }, + { + "name": "transport", + "valueType": "string", + "isArray": false, + "required": true, + "allowedValues": [ + "sftp", + "objectStore" + ], + "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." + } + ], + "children": [] + }, + { + "type": "binding", + "subType": "messaging", + "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.", + "attrs": [ + { + "name": "protocol", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "kafka", + "amqp", + "mqtt", + "sqs" + ], + "description": "The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks." + } + ], + "children": [] + }, { "type": "binding", "subType": "rest", @@ -4553,8 +4737,23 @@ { "type": "operation", "subType": "base", - "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.", + "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.", + "attrs": [], + "children": [] + }, + { + "type": "operation", + "subType": "command", + "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.", "attrs": [ + { + "name": "errors", + "valueType": "string", + "isArray": true, + "required": false, + "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE." + }, { "name": "inputRef", "valueType": "string", @@ -4589,12 +4788,19 @@ "isArray": false, "required": false, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." + }, + { + "name": "transitions", + "valueType": "string", + "isArray": true, + "required": false, + "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)." } ], "children": [ { "childType": "binding", - "childSubType": "*", + "childSubType": "rest", "childName": "*", "min": 0, "max": null @@ -4603,64 +4809,110 @@ }, { "type": "operation", - "subType": "command", - "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", - "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.", + "subType": "event", + "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Each distinct fact a consumer may react to: placed, delivered, cancelled.", "attrs": [ { - "name": "errors", + "name": "key", "valueType": "string", - "isArray": true, + "isArray": false, "required": false, - "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE." + "description": "The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised." }, { - "name": "inputRef", + "name": "outputRef", "valueType": "string", "isArray": false, - "required": false, - "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." - }, + "required": true, + "description": "The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." + } + ], + "children": [ { - "name": "objectRef", + "childType": "binding", + "childSubType": "messaging", + "childName": "*", + "min": 0, + "max": null + } + ] + }, + { + "type": "operation", + "subType": "export", + "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.", + "attrs": [ + { + "name": "availableBy", "valueType": "string", "isArray": false, "required": false, - "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." + "description": "The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised." }, { - "name": "outputRef", + "name": "frequency", "valueType": "string", "isArray": false, - "required": false, - "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." + "required": true, + "allowedValues": [ + "hourly", + "daily", + "weekly", + "monthly" + ], + "description": "How often a new file appears: hourly, daily, weekly or monthly." }, { - "name": "permission", + "name": "outputRef", "valueType": "string", "isArray": false, - "required": false, - "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." - }, + "required": true, + "description": "The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." + } + ], + "children": [ { - "name": "public", - "valueType": "boolean", + "childType": "binding", + "childSubType": "file", + "childName": "*", + "min": 0, + "max": null + } + ] + }, + { + "type": "operation", + "subType": "import", + "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.", + "attrs": [ + { + "name": "frequency", + "valueType": "string", "isArray": false, - "required": false, - "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." + "required": true, + "allowedValues": [ + "hourly", + "daily", + "weekly", + "monthly" + ], + "description": "How often a new file is expected: hourly, daily, weekly or monthly." }, { - "name": "transitions", + "name": "inputRef", "valueType": "string", - "isArray": true, - "required": false, - "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)." + "isArray": false, + "required": true, + "description": "The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE." } ], "children": [ { "childType": "binding", - "childSubType": "*", + "childSubType": "file", "childName": "*", "min": 0, "max": null @@ -4719,7 +4971,7 @@ "children": [ { "childType": "binding", - "childSubType": "*", + "childSubType": "rest", "childName": "*", "min": 0, "max": null @@ -5519,6 +5771,19 @@ "description": "Files and blobs addressed by key.", "whenToUse": "Uploaded images, exports, static assets kept outside the app.", "attrs": [ + { + "name": "carries", + "valueType": "string", + "isArray": true, + "required": false, + "ref": { + "targetType": "api", + "targetSubTypes": [ + "batch" + ] + }, + "description": "The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`." + }, { "name": "publicRead", "valueType": "boolean", @@ -5546,6 +5811,19 @@ "description": "A message queue: each message is handed to one consumer and gone once it is handled.", "whenToUse": "Work handed from one app to another to run later.", "attrs": [ + { + "name": "carries", + "valueType": "string", + "isArray": true, + "required": false, + "ref": { + "targetType": "api", + "targetSubTypes": [ + "eventing" + ] + }, + "description": "The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`." + }, { "name": "deadLetter", "valueType": "boolean", @@ -5627,6 +5905,19 @@ "description": "A retained, ordered log that many consumers read, each at its own position. A message can be read again.", "whenToUse": "Events several consumers read independently, or read again.", "attrs": [ + { + "name": "carries", + "valueType": "string", + "isArray": true, + "required": false, + "ref": { + "targetType": "api", + "targetSubTypes": [ + "eventing" + ] + }, + "description": "The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`." + }, { "name": "residency", "valueType": "string", diff --git a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs index 96381f0178..e256bc5d49 100644 --- a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs +++ b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs @@ -1,6 +1,6 @@ // @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. // -// One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (160 of them). // Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a // claim that nothing is verified — the conformance corpora already check many of // these. To FILL one, move it into C#'s own suite and write the assertion the @@ -52,10 +52,26 @@ public void declare_attributeValueTypes_attrProperties() { /* metaobjects.declar [Fact(Skip = "unfilled slot — write an assertion that fails when: A number written where a name belongs, coerced to text, and emitted into generated code as a name.")] public void declare_attributeValueTypes_attrString() { /* metaobjects.declare.attributeValueTypes.attrString */ } + // Batch API — A batch API is a named surface at the top of a document whose children are the files a provider publishes or accepts on a schedule; the operation rules of an operational API do not apply to it, and no generator writes from it yet. + [Fact(Skip = "unfilled slot — write an assertion that fails when: A nightly file described only in a runbook, so the consumer learns its columns from the first file that arrives.")] + public void declare_businessRules_apiBatch() { /* metaobjects.declare.businessRules.apiBatch */ } + + // Eventing API — An eventing API is a named surface at the top of a document whose children are the events a provider publishes; the operation rules of an operational API do not apply to it, and no generator writes from it yet. + [Fact(Skip = "unfilled slot — write an assertion that fails when: An event declared as a command, so a generated route accepts a POST for something the provider only ever emits.")] + public void declare_businessRules_apiEventing() { /* metaobjects.declare.businessRules.apiEventing */ } + // Operational API — An operational API is a named surface at the top of a document whose children are the package's declared operations. [Fact(Skip = "unfilled slot — write an assertion that fails when: A command declared inside an entity, where a versioned second surface has nowhere to put it.")] public void declare_businessRules_apiOperational() { /* metaobjects.declare.businessRules.apiOperational */ } + // File binding — A file binding names where the file is put, how its name is formed from the run's UTC date or time and nothing else, its format, compression, encryption and how a reader knows the file is whole. + [Fact(Skip = "unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.")] + public void declare_businessRules_bindingFile() { /* metaobjects.declare.businessRules.bindingFile */ } + + // Messaging binding — A messaging binding names the protocol an event is published over. + [Fact(Skip = "unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another.")] + public void declare_businessRules_bindingMessaging() { /* metaobjects.declare.businessRules.bindingMessaging */ } + // REST binding — A REST binding overrides an operation's derived method or path, and a path addressing one row names exactly its target's key fields. [Fact(Skip = "unfilled slot — write an assertion that fails when: A path whose placeholder names a field the target does not key on, so the route resolves the wrong row.")] public void declare_businessRules_bindingRest() { /* metaobjects.declare.businessRules.bindingRest */ } @@ -64,6 +80,18 @@ public void declare_businessRules_bindingRest() { /* metaobjects.declare.busines [Fact(Skip = "unfilled slot — write an assertion that fails when: A command whose declared target disagrees with the key its input carries, so the permission check guards one entity and the write touches another.")] public void declare_businessRules_operationCommand() { /* metaobjects.declare.businessRules.operationCommand */ } + // Event — An event names the declared shape of its payload and may name the field whose events must stay in order. + [Fact(Skip = "unfilled slot — write an assertion that fails when: Two consumers that assume different ordering keys for one stream, and each processes some events out of order.")] + public void declare_businessRules_operationEvent() { /* metaobjects.declare.businessRules.operationEvent */ } + + // Export — An export names the shape of one row of the file, how often the file is written, and by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. + [Fact(Skip = "unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week.")] + public void declare_businessRules_operationExport() { /* metaobjects.declare.businessRules.operationExport */ } + + // Import — An import names the declared value one row of the file must match and how often the file arrives. + [Fact(Skip = "unfilled slot — write an assertion that fails when: A file of rows the provider cannot read, discovered when the first scheduled run fails.")] + public void declare_businessRules_operationImport() { /* metaobjects.declare.businessRules.operationImport */ } + // Query — A query declares what it returns, an entity, a projection or a value, and whether it returns a list. [Fact(Skip = "unfilled slot — write an assertion that fails when: A query that returns a list on one port and a single row on another because nothing said which.")] public void declare_businessRules_operationQuery() { /* metaobjects.declare.businessRules.operationQuery */ } diff --git a/fixtures/requirement-harness/java/RequirementHarnessTest.java b/fixtures/requirement-harness/java/RequirementHarnessTest.java index d00ac8bd42..b6c5150be6 100644 --- a/fixtures/requirement-harness/java/RequirementHarnessTest.java +++ b/fixtures/requirement-harness/java/RequirementHarnessTest.java @@ -1,6 +1,6 @@ // @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. // -// One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (160 of them). // Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a // claim that nothing is verified — the conformance corpora already check many of // these. To FILL one, move it into Java's own suite and write the assertion the @@ -62,11 +62,31 @@ void declare_attributeValueTypes_attrProperties() { /* metaobjects.declare.attri @Disabled("unfilled slot — write an assertion that fails when: A number written where a name belongs, coerced to text, and emitted into generated code as a name.") void declare_attributeValueTypes_attrString() { /* metaobjects.declare.attributeValueTypes.attrString */ } + // Batch API — A batch API is a named surface at the top of a document whose children are the files a provider publishes or accepts on a schedule; the operation rules of an operational API do not apply to it, and no generator writes from it yet. + @Test + @Disabled("unfilled slot — write an assertion that fails when: A nightly file described only in a runbook, so the consumer learns its columns from the first file that arrives.") + void declare_businessRules_apiBatch() { /* metaobjects.declare.businessRules.apiBatch */ } + + // Eventing API — An eventing API is a named surface at the top of a document whose children are the events a provider publishes; the operation rules of an operational API do not apply to it, and no generator writes from it yet. + @Test + @Disabled("unfilled slot — write an assertion that fails when: An event declared as a command, so a generated route accepts a POST for something the provider only ever emits.") + void declare_businessRules_apiEventing() { /* metaobjects.declare.businessRules.apiEventing */ } + // Operational API — An operational API is a named surface at the top of a document whose children are the package's declared operations. @Test @Disabled("unfilled slot — write an assertion that fails when: A command declared inside an entity, where a versioned second surface has nowhere to put it.") void declare_businessRules_apiOperational() { /* metaobjects.declare.businessRules.apiOperational */ } + // File binding — A file binding names where the file is put, how its name is formed from the run's UTC date or time and nothing else, its format, compression, encryption and how a reader knows the file is whole. + @Test + @Disabled("unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.") + void declare_businessRules_bindingFile() { /* metaobjects.declare.businessRules.bindingFile */ } + + // Messaging binding — A messaging binding names the protocol an event is published over. + @Test + @Disabled("unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another.") + void declare_businessRules_bindingMessaging() { /* metaobjects.declare.businessRules.bindingMessaging */ } + // REST binding — A REST binding overrides an operation's derived method or path, and a path addressing one row names exactly its target's key fields. @Test @Disabled("unfilled slot — write an assertion that fails when: A path whose placeholder names a field the target does not key on, so the route resolves the wrong row.") @@ -77,6 +97,21 @@ void declare_businessRules_bindingRest() { /* metaobjects.declare.businessRules. @Disabled("unfilled slot — write an assertion that fails when: A command whose declared target disagrees with the key its input carries, so the permission check guards one entity and the write touches another.") void declare_businessRules_operationCommand() { /* metaobjects.declare.businessRules.operationCommand */ } + // Event — An event names the declared shape of its payload and may name the field whose events must stay in order. + @Test + @Disabled("unfilled slot — write an assertion that fails when: Two consumers that assume different ordering keys for one stream, and each processes some events out of order.") + void declare_businessRules_operationEvent() { /* metaobjects.declare.businessRules.operationEvent */ } + + // Export — An export names the shape of one row of the file, how often the file is written, and by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. + @Test + @Disabled("unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week.") + void declare_businessRules_operationExport() { /* metaobjects.declare.businessRules.operationExport */ } + + // Import — An import names the declared value one row of the file must match and how often the file arrives. + @Test + @Disabled("unfilled slot — write an assertion that fails when: A file of rows the provider cannot read, discovered when the first scheduled run fails.") + void declare_businessRules_operationImport() { /* metaobjects.declare.businessRules.operationImport */ } + // Query — A query declares what it returns, an entity, a projection or a value, and whether it returns a list. @Test @Disabled("unfilled slot — write an assertion that fails when: A query that returns a list on one port and a single row on another because nothing said which.") diff --git a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt index b298440758..1bf4caa0f0 100644 --- a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt +++ b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt @@ -1,6 +1,6 @@ // @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. // -// One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (160 of them). // Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a // claim that nothing is verified — the conformance corpora already check many of // these. To FILL one, move it into Kotlin's own suite and write the assertion the @@ -62,11 +62,31 @@ class RequirementHarnessTest { @Disabled("unfilled slot — write an assertion that fails when: A number written where a name belongs, coerced to text, and emitted into generated code as a name.") fun declare_attributeValueTypes_attrString() { /* metaobjects.declare.attributeValueTypes.attrString */ } + // Batch API — A batch API is a named surface at the top of a document whose children are the files a provider publishes or accepts on a schedule; the operation rules of an operational API do not apply to it, and no generator writes from it yet. + @Test + @Disabled("unfilled slot — write an assertion that fails when: A nightly file described only in a runbook, so the consumer learns its columns from the first file that arrives.") + fun declare_businessRules_apiBatch() { /* metaobjects.declare.businessRules.apiBatch */ } + + // Eventing API — An eventing API is a named surface at the top of a document whose children are the events a provider publishes; the operation rules of an operational API do not apply to it, and no generator writes from it yet. + @Test + @Disabled("unfilled slot — write an assertion that fails when: An event declared as a command, so a generated route accepts a POST for something the provider only ever emits.") + fun declare_businessRules_apiEventing() { /* metaobjects.declare.businessRules.apiEventing */ } + // Operational API — An operational API is a named surface at the top of a document whose children are the package's declared operations. @Test @Disabled("unfilled slot — write an assertion that fails when: A command declared inside an entity, where a versioned second surface has nowhere to put it.") fun declare_businessRules_apiOperational() { /* metaobjects.declare.businessRules.apiOperational */ } + // File binding — A file binding names where the file is put, how its name is formed from the run's UTC date or time and nothing else, its format, compression, encryption and how a reader knows the file is whole. + @Test + @Disabled("unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.") + fun declare_businessRules_bindingFile() { /* metaobjects.declare.businessRules.bindingFile */ } + + // Messaging binding — A messaging binding names the protocol an event is published over. + @Test + @Disabled("unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another.") + fun declare_businessRules_bindingMessaging() { /* metaobjects.declare.businessRules.bindingMessaging */ } + // REST binding — A REST binding overrides an operation's derived method or path, and a path addressing one row names exactly its target's key fields. @Test @Disabled("unfilled slot — write an assertion that fails when: A path whose placeholder names a field the target does not key on, so the route resolves the wrong row.") @@ -77,6 +97,21 @@ class RequirementHarnessTest { @Disabled("unfilled slot — write an assertion that fails when: A command whose declared target disagrees with the key its input carries, so the permission check guards one entity and the write touches another.") fun declare_businessRules_operationCommand() { /* metaobjects.declare.businessRules.operationCommand */ } + // Event — An event names the declared shape of its payload and may name the field whose events must stay in order. + @Test + @Disabled("unfilled slot — write an assertion that fails when: Two consumers that assume different ordering keys for one stream, and each processes some events out of order.") + fun declare_businessRules_operationEvent() { /* metaobjects.declare.businessRules.operationEvent */ } + + // Export — An export names the shape of one row of the file, how often the file is written, and by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. + @Test + @Disabled("unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week.") + fun declare_businessRules_operationExport() { /* metaobjects.declare.businessRules.operationExport */ } + + // Import — An import names the declared value one row of the file must match and how often the file arrives. + @Test + @Disabled("unfilled slot — write an assertion that fails when: A file of rows the provider cannot read, discovered when the first scheduled run fails.") + fun declare_businessRules_operationImport() { /* metaobjects.declare.businessRules.operationImport */ } + // Query — A query declares what it returns, an entity, a projection or a value, and whether it returns a list. @Test @Disabled("unfilled slot — write an assertion that fails when: A query that returns a list on one port and a single row on another because nothing said which.") diff --git a/fixtures/requirement-harness/python/test_requirement_harness.py b/fixtures/requirement-harness/python/test_requirement_harness.py index b72aed7396..74ded53162 100644 --- a/fixtures/requirement-harness/python/test_requirement_harness.py +++ b/fixtures/requirement-harness/python/test_requirement_harness.py @@ -1,6 +1,6 @@ # @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. # -# One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them). +# One slot per authored promise in metaobjects/meta.requirements.yaml (160 of them). # Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a # claim that nothing is verified — the conformance corpora already check many of # these. To FILL one, move it into Python's own suite and write the assertion the @@ -57,11 +57,31 @@ def test_declare_attributeValueTypes_attrProperties(): def test_declare_attributeValueTypes_attrString(): """metaobjects.declare.attributeValueTypes.attrString""" +# Batch API — A batch API is a named surface at the top of a document whose children are the files a provider publishes or accepts on a schedule; the operation rules of an operational API do not apply to it, and no generator writes from it yet. +@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A nightly file described only in a runbook, so the consumer learns its columns from the first file that arrives.") +def test_declare_businessRules_apiBatch(): + """metaobjects.declare.businessRules.apiBatch""" + +# Eventing API — An eventing API is a named surface at the top of a document whose children are the events a provider publishes; the operation rules of an operational API do not apply to it, and no generator writes from it yet. +@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: An event declared as a command, so a generated route accepts a POST for something the provider only ever emits.") +def test_declare_businessRules_apiEventing(): + """metaobjects.declare.businessRules.apiEventing""" + # Operational API — An operational API is a named surface at the top of a document whose children are the package's declared operations. @pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A command declared inside an entity, where a versioned second surface has nowhere to put it.") def test_declare_businessRules_apiOperational(): """metaobjects.declare.businessRules.apiOperational""" +# File binding — A file binding names where the file is put, how its name is formed from the run's UTC date or time and nothing else, its format, compression, encryption and how a reader knows the file is whole. +@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.") +def test_declare_businessRules_bindingFile(): + """metaobjects.declare.businessRules.bindingFile""" + +# Messaging binding — A messaging binding names the protocol an event is published over. +@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another.") +def test_declare_businessRules_bindingMessaging(): + """metaobjects.declare.businessRules.bindingMessaging""" + # REST binding — A REST binding overrides an operation's derived method or path, and a path addressing one row names exactly its target's key fields. @pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A path whose placeholder names a field the target does not key on, so the route resolves the wrong row.") def test_declare_businessRules_bindingRest(): @@ -72,6 +92,21 @@ def test_declare_businessRules_bindingRest(): def test_declare_businessRules_operationCommand(): """metaobjects.declare.businessRules.operationCommand""" +# Event — An event names the declared shape of its payload and may name the field whose events must stay in order. +@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: Two consumers that assume different ordering keys for one stream, and each processes some events out of order.") +def test_declare_businessRules_operationEvent(): + """metaobjects.declare.businessRules.operationEvent""" + +# Export — An export names the shape of one row of the file, how often the file is written, and by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. +@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week.") +def test_declare_businessRules_operationExport(): + """metaobjects.declare.businessRules.operationExport""" + +# Import — An import names the declared value one row of the file must match and how often the file arrives. +@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A file of rows the provider cannot read, discovered when the first scheduled run fails.") +def test_declare_businessRules_operationImport(): + """metaobjects.declare.businessRules.operationImport""" + # Query — A query declares what it returns, an entity, a projection or a value, and whether it returns a list. @pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A query that returns a list on one port and a single row on another because nothing said which.") def test_declare_businessRules_operationQuery(): diff --git a/fixtures/requirement-harness/typescript/requirement-harness.test.ts b/fixtures/requirement-harness/typescript/requirement-harness.test.ts index f5c2733810..9c9c18fadb 100644 --- a/fixtures/requirement-harness/typescript/requirement-harness.test.ts +++ b/fixtures/requirement-harness/typescript/requirement-harness.test.ts @@ -1,6 +1,6 @@ // @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. // -// One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (160 of them). // Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a // claim that nothing is verified — the conformance corpora already check many of // these. To FILL one, move it into TypeScript's own suite and write the assertion the @@ -57,11 +57,31 @@ test.skip("metaobjects.declare.attributeValueTypes.attrString", () => { // unfilled slot — write an assertion that fails when: A number written where a name belongs, coerced to text, and emitted into generated code as a name. }); +// Batch API — A batch API is a named surface at the top of a document whose children are the files a provider publishes or accepts on a schedule; the operation rules of an operational API do not apply to it, and no generator writes from it yet. +test.skip("metaobjects.declare.businessRules.apiBatch", () => { + // unfilled slot — write an assertion that fails when: A nightly file described only in a runbook, so the consumer learns its columns from the first file that arrives. +}); + +// Eventing API — An eventing API is a named surface at the top of a document whose children are the events a provider publishes; the operation rules of an operational API do not apply to it, and no generator writes from it yet. +test.skip("metaobjects.declare.businessRules.apiEventing", () => { + // unfilled slot — write an assertion that fails when: An event declared as a command, so a generated route accepts a POST for something the provider only ever emits. +}); + // Operational API — An operational API is a named surface at the top of a document whose children are the package's declared operations. test.skip("metaobjects.declare.businessRules.apiOperational", () => { // unfilled slot — write an assertion that fails when: A command declared inside an entity, where a versioned second surface has nowhere to put it. }); +// File binding — A file binding names where the file is put, how its name is formed from the run's UTC date or time and nothing else, its format, compression, encryption and how a reader knows the file is whole. +test.skip("metaobjects.declare.businessRules.bindingFile", () => { + // unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done. +}); + +// Messaging binding — A messaging binding names the protocol an event is published over. +test.skip("metaobjects.declare.businessRules.bindingMessaging", () => { + // unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another. +}); + // REST binding — A REST binding overrides an operation's derived method or path, and a path addressing one row names exactly its target's key fields. test.skip("metaobjects.declare.businessRules.bindingRest", () => { // unfilled slot — write an assertion that fails when: A path whose placeholder names a field the target does not key on, so the route resolves the wrong row. @@ -72,6 +92,21 @@ test.skip("metaobjects.declare.businessRules.operationCommand", () => { // unfilled slot — write an assertion that fails when: A command whose declared target disagrees with the key its input carries, so the permission check guards one entity and the write touches another. }); +// Event — An event names the declared shape of its payload and may name the field whose events must stay in order. +test.skip("metaobjects.declare.businessRules.operationEvent", () => { + // unfilled slot — write an assertion that fails when: Two consumers that assume different ordering keys for one stream, and each processes some events out of order. +}); + +// Export — An export names the shape of one row of the file, how often the file is written, and by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. +test.skip("metaobjects.declare.businessRules.operationExport", () => { + // unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week. +}); + +// Import — An import names the declared value one row of the file must match and how often the file arrives. +test.skip("metaobjects.declare.businessRules.operationImport", () => { + // unfilled slot — write an assertion that fails when: A file of rows the provider cannot read, discovered when the first scheduled run fails. +}); + // Query — A query declares what it returns, an entity, a projection or a value, and whether it returns a list. test.skip("metaobjects.declare.businessRules.operationQuery", () => { // unfilled slot — write an assertion that fails when: A query that returns a list on one port and a single row on another because nothing said which. diff --git a/metaobjects/meta.requirements.yaml b/metaobjects/meta.requirements.yaml index 49a9767153..ce098b8d58 100644 --- a/metaobjects/meta.requirements.yaml +++ b/metaobjects/meta.requirements.yaml @@ -1616,6 +1616,91 @@ metadata.root: counterexample: >- A path whose placeholder names a field the target does not key on, so the route resolves the wrong row. + - requirement.functional: + name: apiEventing + title: Eventing API + level: 4 + status: live + statement: >- + An eventing API is a named surface at the top of a document + whose children are the events a provider publishes; the + operation rules of an operational API do not apply to it, and + no generator writes from it yet. + counterexample: >- + An event declared as a command, so a generated route accepts a + POST for something the provider only ever emits. + - requirement.functional: + name: apiBatch + title: Batch API + level: 4 + status: live + statement: >- + A batch API is a named surface at the top of a document whose + children are the files a provider publishes or accepts on a + schedule; the operation rules of an operational API do not + apply to it, and no generator writes from it yet. + counterexample: >- + A nightly file described only in a runbook, so the consumer + learns its columns from the first file that arrives. + - requirement.functional: + name: operationEvent + title: Event + level: 4 + status: live + statement: >- + An event names the declared shape of its payload and may name + the field whose events must stay in order. + counterexample: >- + Two consumers that assume different ordering keys for one + stream, and each processes some events out of order. + - requirement.functional: + name: operationExport + title: Export + level: 4 + status: live + statement: >- + An export names the shape of one row of the file, how often + the file is written, and by when in UTC it is ready, in the + one form its frequency allows; a weekly or monthly file names + its day. + counterexample: >- + A weekly file promised at 06:00 with no day, so the consumer + polls every morning and alarms six days a week. + - requirement.functional: + name: operationImport + title: Import + level: 4 + status: live + statement: >- + An import names the declared value one row of the file must + match and how often the file arrives. + counterexample: >- + A file of rows the provider cannot read, discovered when the + first scheduled run fails. + - requirement.functional: + name: bindingMessaging + title: Messaging binding + level: 4 + status: live + statement: >- + A messaging binding names the protocol an event is published + over. + counterexample: >- + An event published over one broker protocol while its consumer + is built for another. + - requirement.functional: + name: bindingFile + title: File binding + level: 4 + status: live + statement: >- + A file binding names where the file is put, how its name is + formed from the run's UTC date or time and nothing else, its + format, compression, encryption and how a reader knows the + file is whole. + counterexample: >- + A reader that opens a file still being written because nothing + said the writer renames it when done. - requirement.functional: name: transitionAction title: Transition diff --git a/scripts/check-metamodel-version.mjs b/scripts/check-metamodel-version.mjs index 211602f688..a440ea2520 100755 --- a/scripts/check-metamodel-version.mjs +++ b/scripts/check-metamodel-version.mjs @@ -174,8 +174,13 @@ export function classify(base, cur) { const b = bT.get(k); if (!b) continue; diffProse(b, c, k, prose); + // An abstract anchor cannot be authored (ERR_ABSTRACT_SUBTYPE_AUTHORED), so no document + // ever set its attrs or gave it children. Its concrete subtypes list what they inherit + // from it as their own, and are diffed below, so a member moved from the anchor down to + // every subtype that uses it is no change to any document. + if (isAbstractAnchor(base, b) && isAbstractAnchor(cur, c)) continue; diffAttrs(b.attrs, c.attrs, k, breaking, additive, prose); - diffChildren(b.children, c.children, k, breaking, additive); + diffChildren(b.children, c.children, k, breaking, additive, base); } // ---- commonAttrs (registered on every node) ---- @@ -245,12 +250,44 @@ function diffAttrs(baseAttrs, curAttrs, where, breaking, additive, prose) { } } -function diffChildren(baseKids, curKids, where, breaking, additive) { +/** + * `.base` is an abstract anchor when its type has another subtype: the loader refuses + * to let it be authored (parser-core `isAbstractAnchorFor`), so the same test applies here. + */ +function isAbstractAnchor(manifest, t) { + return t.subType === "base" && manifest.types.some((o) => o.type === t.type && o.subType !== "base"); +} + +/** + * A wildcard child rule (`operation.*`) narrowed to the subtypes that existed when it was + * written (`operation.command`, `operation.query`) admits every child it admitted before: + * the only change is that a subtype added later is not admitted, and no document holds one. + * Not breaking, provided every concrete subtype of the baseline keeps a rule of its own. + */ +function narrowedToBaseline(removed, curKids, baseManifest) { + if (removed.childSubType !== "*" || !baseManifest) return false; + const subs = baseManifest.types.filter((t) => t.type === removed.childType && !isAbstractAnchor(baseManifest, t)); + if (subs.length === 0) return false; + return subs.every((t) => + curKids.some( + (c) => + c.childType === removed.childType && + c.childSubType === t.subType && + c.childName === removed.childName && + (c.min ?? 0) <= (removed.min ?? 0) && + (removed.max == null ? c.max == null : c.max == null || c.max >= removed.max), + ), + ); +} + +function diffChildren(baseKids, curKids, where, breaking, additive, baseManifest) { const b = byKey(baseKids, childKey); const c = byKey(curKids, childKey); - for (const k of b.keys()) { - if (!c.has(k)) breaking.push(`child rule removed: ${where} ← ${k}`); + for (const [k, bk] of b) { + if (!c.has(k) && !narrowedToBaseline(bk, curKids ?? [], baseManifest)) { + breaking.push(`child rule removed: ${where} ← ${k}`); + } } for (const [k, ck] of c) { if (!b.has(k)) { diff --git a/scripts/check-requirements-ledger.ts b/scripts/check-requirements-ledger.ts index 463535a3d3..9ef8d1ce25 100644 --- a/scripts/check-requirements-ledger.ts +++ b/scripts/check-requirements-ledger.ts @@ -48,7 +48,7 @@ const EXPECTED_WARNING = "WARN_REQUIREMENT_NOTHING_IMPLEMENTS"; * the neighbour — became `Number("metaobjects")`, i.e. NaN. Every comparison against * NaN is unequal, so the gate failed reporting "expected NaN" and a remedy paragraph * about updating the pin. */ -const DEFAULT_EXPECTED_WARNING_COUNT = 187; +const DEFAULT_EXPECTED_WARNING_COUNT = 194; function expectedWarnings(argv: readonly string[]): number { const flag = argv.find((a) => a.startsWith("--expect-warnings=")); diff --git a/scripts/test-metamodel-version.mjs b/scripts/test-metamodel-version.mjs index 19190074cd..037aaffbf4 100755 --- a/scripts/test-metamodel-version.mjs +++ b/scripts/test-metamodel-version.mjs @@ -266,6 +266,60 @@ check( { prose: 1 }, ); +// --------------------------------------------------------------------------- +// Abstract anchors and narrowed wildcards (1.4.0: operation.base's members moved down to +// command and query, and api.operational's `operation.*` narrowed to the two that existed) +// --------------------------------------------------------------------------- + +const shared = [attr("inputRef")]; +const op = (attrs, kids = []) => [ + type("operation", "base", { attrs, children: kids }), + type("operation", "command", { attrs: shared, children: [child("binding")] }), +]; +check( + "an attr or child rule moved off an abstract anchor its subtypes still list is NOT breaking", + manifest({ types: op(shared, [child("binding")]) }), + manifest({ types: op([]) }), + {}, +); +check( + "a lone `base` is no anchor: removing its attr is still BREAKING", + manifest({ types: [type("thing", "base", { attrs: [attr("a")] })] }), + manifest({ types: [type("thing", "base")] }), + { breaking: 1 }, +); +check( + "an attr a concrete subtype loses is still BREAKING, whatever the anchor did", + manifest({ types: op(shared) }), + manifest({ types: [type("operation", "base"), type("operation", "command")] }), + { breaking: 2 }, // its attr and its child rule +); + +const ops = [type("operation", "base"), type("operation", "command"), type("operation", "query")]; +const holder = (kids, extra = []) => + manifest({ types: [type("api", "operational", { children: kids }), ...ops, ...extra] }); +check( + "a wildcard narrowed to every concrete subtype of the baseline is NOT breaking", + holder([child("operation")]), + holder( + [child("operation", { childSubType: "command" }), child("operation", { childSubType: "query" })], + [type("operation", "event")], + ), + { additive: 3 }, +); +check( + "a wildcard narrowed to SOME of the baseline's subtypes is BREAKING", + holder([child("operation")]), + holder([child("operation", { childSubType: "command" })]), + { breaking: 1, additive: 1 }, +); +check( + "a wildcard narrowed to a rule that now requires the child is BREAKING", + holder([child("operation")]), + holder([child("operation", { childSubType: "command", min: 1 }), child("operation", { childSubType: "query" })]), + { breaking: 2, additive: 1 }, +); + // --------------------------------------------------------------------------- // Required bump + satisfaction // --------------------------------------------------------------------------- diff --git a/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs b/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs index 66f183696b..aa222c581b 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs @@ -154,4 +154,48 @@ public void The_documentation_generators_are_among_those_compared() var files = Emit(Load("with"), [Build(GeneratorRegistry.Entries["api-docs"])]); Assert.Contains(files.Keys, k => k.StartsWith("api/", StringComparison.Ordinal)); } + + // 1.4.0 — api.eventing and api.batch (operation.event / .export / .import, binding.messaging / .file) are + // registered and nothing is generated from them yet. with-delivery/ is with/ plus one API of each kind. Every + // generator but the model explorer (it lists every node) writes for it exactly what it writes for with/, + // the rules-layer and service generators included: they read only api.operational and pick the binding.rest + // by subtype. + private static IEnumerable> AllButExplorer() => + GeneratorRegistry.Entries.Where(e => e.Key != "docs-site"); + + public static TheoryData DeliveryGeneratorNames() + { + var data = new TheoryData(); + foreach (var name in AllButExplorer().Select(e => e.Key).Where(n => n != SharedModelTestSupport.Name)) data.Add(name); + return data; + } + + [Fact] + public void The_with_delivery_model_really_carries_an_eventing_and_a_batch_api() + { + var kinds = Load("with-delivery").Root().Children() + .Where(c => c.Type == TYPE_API).Select(c => c.SubType).OrderBy(k => k, StringComparer.Ordinal).ToList(); + Assert.Equal(new List { "batch", "eventing", "operational" }, kinds); + } + + [Theory] + [MemberData(nameof(DeliveryGeneratorNames))] + public void Generator_emits_the_same_files_with_and_without_the_delivery_apis(string name) + { + var entry = GeneratorRegistry.Entries[name]; + AssertSame(Emit(Load("with"), [Build(entry)]), Emit(Load("with-delivery"), [Build(entry)]), name); + } + + [Fact] + public void Every_runnable_generator_in_one_run_emits_the_same_files_with_the_delivery_apis() + { + var runnable = AllButExplorer() + .Where(e => !Emit(Load("without"), [Build(e.Value)]).ContainsKey("")) + .ToList(); + var expected = Emit(Load("with"), runnable.Select(e => Build(e.Value)).ToList()); + var actual = Emit(Load("with-delivery"), runnable.Select(e => Build(e.Value)).ToList()); + Assert.False(actual.ContainsKey(""), actual.GetValueOrDefault("")); + Assert.True(expected.Count > 10, $"only {expected.Count} files — the suite barely ran"); + AssertSame(expected, actual, "one run"); + } } diff --git a/server/csharp/MetaObjects.Codegen/ExplorerApp/assets/explorer-app.js b/server/csharp/MetaObjects.Codegen/ExplorerApp/assets/explorer-app.js index a2681492a9..ec81740b86 100644 --- a/server/csharp/MetaObjects.Codegen/ExplorerApp/assets/explorer-app.js +++ b/server/csharp/MetaObjects.Codegen/ExplorerApp/assets/explorer-app.js @@ -265,5 +265,5 @@ `);for(var i=0;i0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(` `)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",` `,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(``)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(` -`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'
    ';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return``}function pct(x){return`${(Math.round(x*1e4)/100).toString()}%`}function legendHtml(withUnclaimed){return`
    ${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
    `}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
    ${values.map(esc).join(" | ")}
    `:"",column:esc(str(f.attrs[FIELD_ATTR_COLUMN])??""),flagsHtml:flags.map((x)=>`${esc(x)}`).join(""),claimsHtml:claims.map((c)=>`${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
    ")}}keyRow(from,c){let fields=strs(c.attrs[IDENTITY_ATTR_FIELDS]),target=this.refHtml(from,c,IDENTITY_REFERENCE_ATTR_REFERENCES)||this.refHtml(from,c,RELATIONSHIP_ATTR_OBJECT_REF),through=str(c.attrs[RELATIONSHIP_ATTR_THROUGH]),card=str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]),shape=c.type===TYPE_RELATIONSHIP?[card,through!==void 0?`through ${localName(through)}`:void 0].filter((x)=>x!==void 0).join(", "):`(${fields.join(", ")})`;return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),inheritedHtml:c.inheritedFrom!==void 0?'inherited':"",shape:esc(shape),targetHtml:target!==""?`→ ${target}`:""}}reportingRow(from,c){let a=c.attrs,parts=[],agg=str(a[REPORTING_ATTR_AGG]),of=this.refHtml(from,c,REPORTING_ATTR_OF,localName);if(agg!==void 0)parts.push(`${esc(agg)}(${of})`);else if(of!=="")parts.push(`of ${of}`);let num=str(a[REPORTING_ATTR_NUMERATOR]),den=str(a[REPORTING_ATTR_DENOMINATOR]);if(num!==void 0&&den!==void 0)parts.push(`${esc(num)} ÷ ${esc(den)}`);let via=str(a[REPORTING_ATTR_VIA]);if(via!==void 0)parts.push(`via ${esc(localName(via))}`);let grains=strs(a[REPORTING_ATTR_GRAINS]);if(grains.length>0)parts.push(`grains ${grains.map((g)=>`${esc(g)}`).join(" ")}`);let seg=str(a[REPORTING_ATTR_SEGMENT]);if(seg!==void 0)parts.push(`segment ${esc(seg)}`);if(a[REPORTING_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`);if(a[REPORTING_ATTR_DEFAULT]!==void 0)parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`);return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),definitionHtml:parts.join(" · ")}}layoutRow(l){let parts=[],cols=strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]);if(cols.length>0)parts.push(`columns ${cols.map((c)=>`${esc(c)}`).join(", ")}`);let sort=str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]);if(sort!==void 0)parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER])!==void 0?` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}`:""}`);if(typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]==="number")parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`);return{kind:esc(`${l.type}.${l.subType}`),name:esc(l.name),detailHtml:parts.join(", ")}}projectionBlock(from,n){let ix=this.ix,rows=[],bases=new Set;for(let f of ix.fields(n.id)){if(f.extends!==void 0)bases.add(ix.ownerOf(f.extends));for(let o of ix.children(f.id).filter((c)=>c.type===TYPE_ORIGIN)){let def=this.originDefinition(from,o);for(let src of this.refLinks(o,ORIGIN_PASSTHROUGH_ATTR_FROM))bases.add(ix.ownerOf(src.id));rows.push({field:esc(f.name),origin:esc(`origin.${o.subType}`),definitionHtml:def})}}return{basesHtml:[...bases].filter((b)=>b!==n.id).sort(byCodeUnit2).map((b)=>this.link(from,b)).join(", "),origins:rows,hasOrigins:rows.length>0}}originDefinition(from,o){let a=o.attrs,ref=(name)=>this.attrValues(o,name).map((v)=>v.link!==null&&!v.link.unresolved?this.link(from,v.link.id,localName(v.text)):`${esc(localName(v.text))}`).join(", "),parts=[],agg=str(a[ORIGIN_AGGREGATE_ATTR_AGG]);if(agg!==void 0)parts.push(`${esc(agg)}(${ref(ORIGIN_AGGREGATE_ATTR_OF)})`);else if(a[ORIGIN_AGGREGATE_ATTR_OF]!==void 0)parts.push(`of ${ref(ORIGIN_AGGREGATE_ATTR_OF)}`);if(a[ORIGIN_PASSTHROUGH_ATTR_FROM]!==void 0)parts.push(`from ${ref(ORIGIN_PASSTHROUGH_ATTR_FROM)}`);if(a[ORIGIN_AGGREGATE_ATTR_VIA]!==void 0)parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`);if(a[ORIGIN_COMPUTED_ATTR_EXPR]!==void 0)parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`);if(a[ORIGIN_AGGREGATE_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`);return parts.join(" · ")}reportBlock(from,n){let a=n.attrs,fromId=this.refLinks(n,OBJECT_REPORT_ATTR_FROM)[0]?.id??str(a[OBJECT_REPORT_ATTR_FROM]),resolve2=(name,kindType)=>{let hit=[fromId!==void 0?`${fromId}.${name}`:void 0,`${n.package===""?"":`${n.package}::`}${name}`].filter((x)=>x!==void 0).find((c)=>this.ix.byId.get(c)?.type===kindType||this.ix.byId.has(c)&&name.includes("."));return hit!==void 0?this.link(from,hit,name):`${esc(name)}`},spine=str(a[OBJECT_REPORT_ATTR_SPINE]);return{fromHtml:this.refHtml(from,n,OBJECT_REPORT_ATTR_FROM),spineHtml:spine!==void 0?`${esc(spine)}`:"",dimensionsHtml:strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d)=>resolve2(d,TYPE_DIMENSION)).join(", "),measuresHtml:strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m)=>resolve2(m,TYPE_MEASURE)).join(", "),segmentHtml:strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s)=>resolve2(s,TYPE_SEGMENT)).join(", "),filterHtml:a[OBJECT_REPORT_ATTR_FILTER]!==void 0?`${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}`:""}}generatedGroups(id){let groups=new Map;for(let f of this.ix.generated(id))groups.set(f.generatedBy,[...groups.get(f.generatedBy)??[],f.path]);return[...groups.keys()].sort(byCodeUnit2).map((g)=>({generator:esc(g),files:(groups.get(g)??[]).map((p)=>esc(p))}))}node(n){let ix=this.ix,from=this.objectPage(n),kindLabel=`${n.type}.${n.subType}`,whyRows=this.whyRows(from,n),attrs=this.attrRows(from,n),referrers=[...(ix.top(n.id)?.referencedBy??[]).map((e)=>e.from.id),...ix.claims(n.id).map((c)=>this.topOf(c.req).node.id)],refBy=[...new Set(referrers.filter((id)=>id!==n.id))].sort(byCodeUnit2).map((id)=>this.link(from,id));return{id:esc(n.id),name:esc(n.name),kindLabel:esc(kindLabel),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › ${esc(kindLabel)}`,isAbstract:n.abstract===!0,description:this.description(n),extendsHtml:n.extends!==void 0?this.link(from,n.extends):"",attrs,hasAttrs:attrs.length>0,members:ix.children(n.id).map((c)=>({anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),nameHtml:ix.reqById.has(c.id)?this.link(from,c.id):esc(c.name===""?`#${c.order}`:c.name),attrsHtml:this.attrRows(from,c).map((a)=>`@${a.name} ${a.valueHtml}`).join("
    "),below:ix.children(c.id).length})),hasMembers:ix.children(n.id).length>0,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(from,n){return n.view.attrs.map((a)=>{let links=a.values.filter((v)=>v.link!==null&&!v.link.unresolved);return{name:esc(a.name),valueHtml:links.length>0&&links.length===a.values.length?links.map((v)=>this.link(from,v.link.id)).join(", "):`${esc(fmt(a.value))}`}})}prompt(n,text){let ix=this.ix,from=this.objectPage(n),payloadId=this.refLinks(n,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id,replyId=this.refLinks(n,TEMPLATE_ATTR_RESPONSE_REF)[0]?.id,vars=text!==void 0?templateVariables(text):void 0,payload=payloadId!==void 0?ix.byId.get(payloadId):void 0,reply=replyId!==void 0?ix.byId.get(replyId):void 0,payloadRows=payload!==void 0?ix.fields(payload.id).map((f)=>({name:esc(f.name),requiredHtml:f.attrs[FIELD_ATTR_REQUIRED]===!0?'required':"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)!==""?` → ${this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)}`:"",usedHtml:vars===void 0?'text not read':vars.has(f.name)?"yes":'no'})):[],replyRows=reply!==void 0?ix.fields(reply.id).map((f)=>({name:esc(f.name),type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),valuesHtml:f.subType===FIELD_SUBTYPE_ENUM?`
    ${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
    `:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(` +`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var FREQUENCY_HOURLY="hourly",FREQUENCY_DAILY="daily",FREQUENCY_WEEKLY="weekly",FREQUENCY_MONTHLY="monthly";var AVAILABLE_BY_PATTERNS={[FREQUENCY_HOURLY]:/^:[0-5][0-9]$/,[FREQUENCY_DAILY]:/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/,[FREQUENCY_WEEKLY]:/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/,[FREQUENCY_MONTHLY]:/^(?:[1-9]|1[0-9]|2[0-8]) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/},AVAILABLE_BY_EXAMPLES={[FREQUENCY_HOURLY]:":15",[FREQUENCY_DAILY]:"03:00",[FREQUENCY_WEEKLY]:"Mon 06:00",[FREQUENCY_MONTHLY]:"1 06:00"};var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'
    ';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return``}function pct(x){return`${(Math.round(x*1e4)/100).toString()}%`}function legendHtml(withUnclaimed){return`
    ${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
    `}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
    ${values.map(esc).join(" | ")}
    `:"",column:esc(str(f.attrs[FIELD_ATTR_COLUMN])??""),flagsHtml:flags.map((x)=>`${esc(x)}`).join(""),claimsHtml:claims.map((c)=>`${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
    ")}}keyRow(from,c){let fields=strs(c.attrs[IDENTITY_ATTR_FIELDS]),target=this.refHtml(from,c,IDENTITY_REFERENCE_ATTR_REFERENCES)||this.refHtml(from,c,RELATIONSHIP_ATTR_OBJECT_REF),through=str(c.attrs[RELATIONSHIP_ATTR_THROUGH]),card=str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]),shape=c.type===TYPE_RELATIONSHIP?[card,through!==void 0?`through ${localName(through)}`:void 0].filter((x)=>x!==void 0).join(", "):`(${fields.join(", ")})`;return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),inheritedHtml:c.inheritedFrom!==void 0?'inherited':"",shape:esc(shape),targetHtml:target!==""?`→ ${target}`:""}}reportingRow(from,c){let a=c.attrs,parts=[],agg=str(a[REPORTING_ATTR_AGG]),of=this.refHtml(from,c,REPORTING_ATTR_OF,localName);if(agg!==void 0)parts.push(`${esc(agg)}(${of})`);else if(of!=="")parts.push(`of ${of}`);let num=str(a[REPORTING_ATTR_NUMERATOR]),den=str(a[REPORTING_ATTR_DENOMINATOR]);if(num!==void 0&&den!==void 0)parts.push(`${esc(num)} ÷ ${esc(den)}`);let via=str(a[REPORTING_ATTR_VIA]);if(via!==void 0)parts.push(`via ${esc(localName(via))}`);let grains=strs(a[REPORTING_ATTR_GRAINS]);if(grains.length>0)parts.push(`grains ${grains.map((g)=>`${esc(g)}`).join(" ")}`);let seg=str(a[REPORTING_ATTR_SEGMENT]);if(seg!==void 0)parts.push(`segment ${esc(seg)}`);if(a[REPORTING_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`);if(a[REPORTING_ATTR_DEFAULT]!==void 0)parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`);return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),definitionHtml:parts.join(" · ")}}layoutRow(l){let parts=[],cols=strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]);if(cols.length>0)parts.push(`columns ${cols.map((c)=>`${esc(c)}`).join(", ")}`);let sort=str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]);if(sort!==void 0)parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER])!==void 0?` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}`:""}`);if(typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]==="number")parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`);return{kind:esc(`${l.type}.${l.subType}`),name:esc(l.name),detailHtml:parts.join(", ")}}projectionBlock(from,n){let ix=this.ix,rows=[],bases=new Set;for(let f of ix.fields(n.id)){if(f.extends!==void 0)bases.add(ix.ownerOf(f.extends));for(let o of ix.children(f.id).filter((c)=>c.type===TYPE_ORIGIN)){let def=this.originDefinition(from,o);for(let src of this.refLinks(o,ORIGIN_PASSTHROUGH_ATTR_FROM))bases.add(ix.ownerOf(src.id));rows.push({field:esc(f.name),origin:esc(`origin.${o.subType}`),definitionHtml:def})}}return{basesHtml:[...bases].filter((b)=>b!==n.id).sort(byCodeUnit2).map((b)=>this.link(from,b)).join(", "),origins:rows,hasOrigins:rows.length>0}}originDefinition(from,o){let a=o.attrs,ref=(name)=>this.attrValues(o,name).map((v)=>v.link!==null&&!v.link.unresolved?this.link(from,v.link.id,localName(v.text)):`${esc(localName(v.text))}`).join(", "),parts=[],agg=str(a[ORIGIN_AGGREGATE_ATTR_AGG]);if(agg!==void 0)parts.push(`${esc(agg)}(${ref(ORIGIN_AGGREGATE_ATTR_OF)})`);else if(a[ORIGIN_AGGREGATE_ATTR_OF]!==void 0)parts.push(`of ${ref(ORIGIN_AGGREGATE_ATTR_OF)}`);if(a[ORIGIN_PASSTHROUGH_ATTR_FROM]!==void 0)parts.push(`from ${ref(ORIGIN_PASSTHROUGH_ATTR_FROM)}`);if(a[ORIGIN_AGGREGATE_ATTR_VIA]!==void 0)parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`);if(a[ORIGIN_COMPUTED_ATTR_EXPR]!==void 0)parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`);if(a[ORIGIN_AGGREGATE_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`);return parts.join(" · ")}reportBlock(from,n){let a=n.attrs,fromId=this.refLinks(n,OBJECT_REPORT_ATTR_FROM)[0]?.id??str(a[OBJECT_REPORT_ATTR_FROM]),resolve2=(name,kindType)=>{let hit=[fromId!==void 0?`${fromId}.${name}`:void 0,`${n.package===""?"":`${n.package}::`}${name}`].filter((x)=>x!==void 0).find((c)=>this.ix.byId.get(c)?.type===kindType||this.ix.byId.has(c)&&name.includes("."));return hit!==void 0?this.link(from,hit,name):`${esc(name)}`},spine=str(a[OBJECT_REPORT_ATTR_SPINE]);return{fromHtml:this.refHtml(from,n,OBJECT_REPORT_ATTR_FROM),spineHtml:spine!==void 0?`${esc(spine)}`:"",dimensionsHtml:strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d)=>resolve2(d,TYPE_DIMENSION)).join(", "),measuresHtml:strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m)=>resolve2(m,TYPE_MEASURE)).join(", "),segmentHtml:strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s)=>resolve2(s,TYPE_SEGMENT)).join(", "),filterHtml:a[OBJECT_REPORT_ATTR_FILTER]!==void 0?`${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}`:""}}generatedGroups(id){let groups=new Map;for(let f of this.ix.generated(id))groups.set(f.generatedBy,[...groups.get(f.generatedBy)??[],f.path]);return[...groups.keys()].sort(byCodeUnit2).map((g)=>({generator:esc(g),files:(groups.get(g)??[]).map((p)=>esc(p))}))}node(n){let ix=this.ix,from=this.objectPage(n),kindLabel=`${n.type}.${n.subType}`,whyRows=this.whyRows(from,n),attrs=this.attrRows(from,n),referrers=[...(ix.top(n.id)?.referencedBy??[]).map((e)=>e.from.id),...ix.claims(n.id).map((c)=>this.topOf(c.req).node.id)],refBy=[...new Set(referrers.filter((id)=>id!==n.id))].sort(byCodeUnit2).map((id)=>this.link(from,id));return{id:esc(n.id),name:esc(n.name),kindLabel:esc(kindLabel),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › ${esc(kindLabel)}`,isAbstract:n.abstract===!0,description:this.description(n),extendsHtml:n.extends!==void 0?this.link(from,n.extends):"",attrs,hasAttrs:attrs.length>0,members:ix.children(n.id).map((c)=>({anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),nameHtml:ix.reqById.has(c.id)?this.link(from,c.id):esc(c.name===""?`#${c.order}`:c.name),attrsHtml:this.attrRows(from,c).map((a)=>`@${a.name} ${a.valueHtml}`).join("
    "),below:ix.children(c.id).length})),hasMembers:ix.children(n.id).length>0,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(from,n){return n.view.attrs.map((a)=>{let links=a.values.filter((v)=>v.link!==null&&!v.link.unresolved);return{name:esc(a.name),valueHtml:links.length>0&&links.length===a.values.length?links.map((v)=>this.link(from,v.link.id)).join(", "):`${esc(fmt(a.value))}`}})}prompt(n,text){let ix=this.ix,from=this.objectPage(n),payloadId=this.refLinks(n,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id,replyId=this.refLinks(n,TEMPLATE_ATTR_RESPONSE_REF)[0]?.id,vars=text!==void 0?templateVariables(text):void 0,payload=payloadId!==void 0?ix.byId.get(payloadId):void 0,reply=replyId!==void 0?ix.byId.get(replyId):void 0,payloadRows=payload!==void 0?ix.fields(payload.id).map((f)=>({name:esc(f.name),requiredHtml:f.attrs[FIELD_ATTR_REQUIRED]===!0?'required':"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)!==""?` → ${this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)}`:"",usedHtml:vars===void 0?'text not read':vars.has(f.name)?"yes":'no'})):[],replyRows=reply!==void 0?ix.fields(reply.id).map((f)=>({name:esc(f.name),type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),valuesHtml:f.subType===FIELD_SUBTYPE_ENUM?`
    ${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
    `:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(` `).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
      ${tops.map((r)=>this.treeNode(page,r)).join("")}
    `:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
  • ${`
    ${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}${dispositionPill(r)}${verdictBadge(r)}${bar}${links.join("")}
    ${esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??"")}
    `}${r.children.length>0?`
      ${r.children.map((c)=>this.treeNode(from,c)).join("")}
    `:""}
  • `}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`${cols.map((o)=>`
    ${this.link(from,o.id)}
    `).join("")}`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLink(from,top)}${cols.map(()=>'').join("")}`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`${levelBadge(r)}${esc(label)}${cols.map((o)=>tg.has(o.id)?`${statusGlyph(r.status)}`:'').join("")}`)}}return{tableHtml:rows.length>0?`${head}${rows.join("")}
    `:"",hasRows:rows.length>0,hasRequirements:ix.hasRequirements()}}trace(){let starts=this.ix.requirements.filter((r)=>r.level!==void 0&&r.level<=REQUIREMENT_LEVEL_SERVICE),fallback=starts.length===0?this.ix.topRequirements:[];return{options:[...starts,...fallback].map((r)=>({value:esc(r.node.id),label:esc(`${" ".repeat(Math.max(0,(r.level??1)-1))}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)}`)})),hasStarts:starts.length+fallback.length>0,hasUsage:!1}}gaps(){let ix=this.ix,from=PAGE_GAPS,cards=[],card=(title,count,source,why,bodyHtml)=>{cards.push({title:esc(title),count:esc(String(count)),source:esc(source),isGate:source==="meta verify",whyHtml:why,bodyHtml})};if(ix.view.sources.requirements){let findingsOf=(gate2)=>[...ix.requirements.flatMap((req)=>req.req.diagnostics.filter((d)=>d.source===GATE_SOURCE===gate2).map((d)=>({req,d}))),...ix.view.advisories.filter((d)=>d.path===""&&d.source===GATE_SOURCE===gate2).map((d)=>({d}))],table=(rows,chip)=>rows.length===0?'
    None.
    ':`${rows.map(({req,d})=>``).join("")}
    ${esc(d.code)}${req!==void 0?this.reqLink(from,req):""}
    ${esc(d.message)}
    `,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
    None.
    ');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
    None.
    ')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
    Not scanned.
    ');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
    No prompt text was read.
    ':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
    None.
    ':`
      ${items.map((i)=>`
    • ${i}
    • `).join("")}
    `}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found

    No such page

    ${escapeHtml2(r.path)} is not a page of this model.

    Overview

    `,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="

    No model yet

    The explorer is waiting for the running application's docs view.

    ";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="

    No model

    The source parameter is not a URL.

    ",paintLive();return}follow(source);return}if(!build())document.body.innerHTML="

    No model

    explorer-model.js did not load. Run meta gen to write it beside this page.

    ";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})(); diff --git a/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs index 892cb79ce8..5e6e3afc84 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs @@ -284,6 +284,9 @@ public void The_reader_carries_a_facet_on_a_types_entry_attr() "app.base @runsAs role/service False sameSystem ERR_RUNSAS_OTHER_SYSTEM", "app.client @runsAs role/service False sameSystem ERR_RUNSAS_OTHER_SYSTEM", "app.job @runsAs role/service False sameSystem ERR_RUNSAS_OTHER_SYSTEM", + "app.job @extracts object/entity|projection False ", + "app.job @provides api False ", + "app.service @provides api False ", "app.service @runsAs role/service False sameSystem ERR_RUNSAS_OTHER_SYSTEM", "grant.api @api api False ", "grant.rdb @resource resource/rdb False sameSystem ERR_GRANT_CROSSES_SYSTEM", @@ -299,6 +302,9 @@ public void The_reader_carries_a_facet_on_a_types_entry_attr() "role.token @heldBy organization|system False ", "role.token @memberOf role/group False ", "role.user @memberOf role/group False ", + "resource.objectStore @carries api/batch False ", + "resource.queue @carries api/eventing False ", + "resource.stream @carries api/eventing False ", "source.document @resource resource/document False ", "source.rdb @resource resource/rdb False ", "source.search @resource resource/search False ", @@ -327,7 +333,7 @@ public void The_core_definitions_declare_exactly_the_four_core_references() foreach (var a in registry.AttrsOf(id.Type, id.SubType)) { if (a.Ref is not { } f) continue; - if (id.Type is "app" or "role" or "system" or "grant" or "source") + if (id.Type is "app" or "role" or "system" or "grant" or "source" or "resource") { // The systems vocabulary: the grants and @runsAs stay inside their system, // each with its own wrong-system code; the other references do not. diff --git a/server/csharp/MetaObjects/Core/Api/ApiConstants.cs b/server/csharp/MetaObjects/Core/Api/ApiConstants.cs index 5ac913fcba..ca9cbbb5a1 100644 --- a/server/csharp/MetaObjects/Core/Api/ApiConstants.cs +++ b/server/csharp/MetaObjects/Core/Api/ApiConstants.cs @@ -15,17 +15,35 @@ public static partial class ApiConstants /// A request/response surface whose children are operations. The axis is the /// interaction model, never the protocol (ADR-0030). public const string API_SUBTYPE_OPERATIONAL = "operational"; - public static readonly string[] API_SUBTYPES = [API_SUBTYPE_OPERATIONAL]; + /// Events the provider publishes; children are operation.event. + public const string API_SUBTYPE_EVENTING = "eventing"; + /// Datasets delivered as files on a schedule; children are operation.export / .import. + public const string API_SUBTYPE_BATCH = "batch"; + public static readonly string[] API_SUBTYPES = [API_SUBTYPE_OPERATIONAL, API_SUBTYPE_EVENTING, API_SUBTYPE_BATCH]; /// Changes state; takes an object.value. public const string OPERATION_SUBTYPE_COMMAND = "command"; /// Reads; returns a projection, entity or value. public const string OPERATION_SUBTYPE_QUERY = "query"; - public static readonly string[] OPERATION_SUBTYPES = [OPERATION_SUBTYPE_COMMAND, OPERATION_SUBTYPE_QUERY]; + /// Something that happened; the payload is its @outputRef. + public const string OPERATION_SUBTYPE_EVENT = "event"; + /// A file the provider publishes on a schedule; rows are its @outputRef. + public const string OPERATION_SUBTYPE_EXPORT = "export"; + /// A file the provider accepts on a schedule; rows are its @inputRef. + public const string OPERATION_SUBTYPE_IMPORT = "import"; + public static readonly string[] OPERATION_SUBTYPES = + [ + OPERATION_SUBTYPE_COMMAND, OPERATION_SUBTYPE_QUERY, + OPERATION_SUBTYPE_EVENT, OPERATION_SUBTYPE_EXPORT, OPERATION_SUBTYPE_IMPORT, + ]; /// The HTTP binding of an operation (overrides the derived method and path). public const string BINDING_SUBTYPE_REST = "rest"; - public static readonly string[] BINDING_SUBTYPES = [BINDING_SUBTYPE_REST]; + /// How an event travels (optionally pinning the wire protocol). + public const string BINDING_SUBTYPE_MESSAGING = "messaging"; + /// How an export's or import's file is delivered. + public const string BINDING_SUBTYPE_FILE = "file"; + public static readonly string[] BINDING_SUBTYPES = [BINDING_SUBTYPE_REST, BINDING_SUBTYPE_MESSAGING, BINDING_SUBTYPE_FILE]; // Attrs on operation.* (and @permission / @public on transition.* too) public const string OPERATION_ATTR_INPUT_REF = "inputRef"; @@ -42,6 +60,48 @@ public static partial class ApiConstants public const string BINDING_ATTR_PATH = "path"; public static readonly string[] HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"]; + // Attrs on operation.event / .export / .import + public const string OPERATION_ATTR_KEY = "key"; + public const string OPERATION_ATTR_FREQUENCY = "frequency"; + public const string OPERATION_ATTR_AVAILABLE_BY = "availableBy"; + public const string FREQUENCY_HOURLY = "hourly"; + public const string FREQUENCY_DAILY = "daily"; + public const string FREQUENCY_WEEKLY = "weekly"; + public const string FREQUENCY_MONTHLY = "monthly"; + public static readonly string[] FREQUENCIES = [FREQUENCY_HOURLY, FREQUENCY_DAILY, FREQUENCY_WEEKLY, FREQUENCY_MONTHLY]; + + /// The form of @availableBy for each @frequency: hourly :MM, daily HH:MM, + /// weekly Ddd HH:MM, monthly D HH:MM with the day 1 to 28. Anchored with \z. + public static readonly IReadOnlyDictionary AVAILABLE_BY_PATTERNS = new Dictionary + { + [FREQUENCY_HOURLY] = new(@"^:[0-5][0-9]\z", RegexOptions.CultureInvariant), + [FREQUENCY_DAILY] = new(@"^(?:[01][0-9]|2[0-3]):[0-5][0-9]\z", RegexOptions.CultureInvariant), + [FREQUENCY_WEEKLY] = new(@"^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:[01][0-9]|2[0-3]):[0-5][0-9]\z", RegexOptions.CultureInvariant), + [FREQUENCY_MONTHLY] = new(@"^(?:[1-9]|1[0-9]|2[0-8]) (?:[01][0-9]|2[0-3]):[0-5][0-9]\z", RegexOptions.CultureInvariant), + }; + + /// An example of each @availableBy form, for messages. + public static readonly IReadOnlyDictionary AVAILABLE_BY_EXAMPLES = new Dictionary + { + [FREQUENCY_HOURLY] = ":15", + [FREQUENCY_DAILY] = "03:00", + [FREQUENCY_WEEKLY] = "Mon 06:00", + [FREQUENCY_MONTHLY] = "1 06:00", + }; + + // Attrs on binding.messaging / binding.file + public const string BINDING_ATTR_PROTOCOL = "protocol"; + public const string BINDING_ATTR_TRANSPORT = "transport"; + public const string BINDING_ATTR_FILE_NAME = "fileName"; + public const string BINDING_ATTR_FORMAT = "format"; + public const string BINDING_ATTR_COMPRESSION = "compression"; + public const string BINDING_ATTR_COMPLETION = "completion"; + public const string BINDING_ATTR_ENCRYPTION = "encryption"; + /// The placeholders a binding.file @fileName may hold. + public static readonly string[] FILE_NAME_PLACEHOLDERS = ["date", "timestamp"]; + /// The suffix of the marker object completion: marker puts beside a finished file. + public const string COMPLETION_MARKER_SUFFIX = ".done"; + /// Names a declared operation or a transition may not take: they are the derived /// CRUD verbs of the same service (ERR_TRANSITION_NAME_COLLISION). public static readonly string[] RESERVED_OPERATION_NAMES = ["create", "get", "list", "update", "delete"]; diff --git a/server/csharp/MetaObjects/Core/Api/ApiSchema.cs b/server/csharp/MetaObjects/Core/Api/ApiSchema.cs index a761c2c47d..3b576c3ffe 100644 --- a/server/csharp/MetaObjects/Core/Api/ApiSchema.cs +++ b/server/csharp/MetaObjects/Core/Api/ApiSchema.cs @@ -17,7 +17,13 @@ private static AttrSchema Str(string name, bool isArray = false, IReadOnlyList new(Name: name, ValueType: AttrConstants.ATTR_SUBTYPE_BOOLEAN, Required: false); - /// The attrs every operation shares (operation.base). + private static AttrSchema Req(string name, IReadOnlyList? allowed = null) => + new(Name: name, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: true, AllowedValues: allowed); + + private static AttrSchema Choice(string name, string dflt, params object[] allowed) => + new(Name: name, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, Default: dflt, AllowedValues: allowed); + + /// The attrs operation.command and operation.query share. operation.base itself declares none. public static readonly IReadOnlyList OperationBaseAttrs = [ Str(ApiConstants.OPERATION_ATTR_INPUT_REF), @@ -40,9 +46,46 @@ private static AttrSchema Bool(string name) => Bool(ApiConstants.OPERATION_ATTR_MANY), ]; + private static readonly IReadOnlyList FrequencyValues = [.. ApiConstants.FREQUENCIES]; + + public static readonly IReadOnlyList EventAttrs = + [ + Req(ApiConstants.OPERATION_ATTR_OUTPUT_REF), + Str(ApiConstants.OPERATION_ATTR_KEY), + ]; + + public static readonly IReadOnlyList ExportAttrs = + [ + Req(ApiConstants.OPERATION_ATTR_OUTPUT_REF), + Req(ApiConstants.OPERATION_ATTR_FREQUENCY, FrequencyValues), + Str(ApiConstants.OPERATION_ATTR_AVAILABLE_BY), + ]; + + public static readonly IReadOnlyList ImportAttrs = + [ + Req(ApiConstants.OPERATION_ATTR_INPUT_REF), + Req(ApiConstants.OPERATION_ATTR_FREQUENCY, FrequencyValues), + ]; + public static readonly IReadOnlyList RestBindingAttrs = [ Str(ApiConstants.BINDING_ATTR_METHOD, allowed: [.. ApiConstants.HTTP_METHODS]), Str(ApiConstants.BINDING_ATTR_PATH), ]; + + public static readonly IReadOnlyList MessagingBindingAttrs = + [ + Str(ApiConstants.BINDING_ATTR_PROTOCOL, allowed: ["kafka", "amqp", "mqtt", "sqs"]), + ]; + + public static readonly IReadOnlyList FileBindingAttrs = + [ + Req(ApiConstants.BINDING_ATTR_TRANSPORT, ["sftp", "objectStore"]), + Str(ApiConstants.BINDING_ATTR_PATH), + Req(ApiConstants.BINDING_ATTR_FILE_NAME), + Req(ApiConstants.BINDING_ATTR_FORMAT, ["csv", "jsonLines", "parquet"]), + Choice(ApiConstants.BINDING_ATTR_COMPRESSION, "none", "none", "gzip"), + Choice(ApiConstants.BINDING_ATTR_COMPLETION, "none", "rename", "marker", "none"), + Choice(ApiConstants.BINDING_ATTR_ENCRYPTION, "none", "none", "pgp"), + ]; } diff --git a/server/csharp/MetaObjects/Core/Rules/RulesMetaDataProvider.cs b/server/csharp/MetaObjects/Core/Rules/RulesMetaDataProvider.cs index ff952fb9f2..1d75488e16 100644 --- a/server/csharp/MetaObjects/Core/Rules/RulesMetaDataProvider.cs +++ b/server/csharp/MetaObjects/Core/Rules/RulesMetaDataProvider.cs @@ -50,11 +50,18 @@ void Reg(string type, string subType, List attrs, Func new MetaApi(tid, n)); Reg(TYPE_API, ApiConstants.API_SUBTYPE_OPERATIONAL, [], (tid, n) => new MetaApi(tid, n)); - Reg(TYPE_OPERATION, SUBTYPE_BASE, [.. ApiSchema.OperationBaseAttrs], (tid, n) => new MetaOperation(tid, n)); + Reg(TYPE_API, ApiConstants.API_SUBTYPE_EVENTING, [], (tid, n) => new MetaApi(tid, n)); + Reg(TYPE_API, ApiConstants.API_SUBTYPE_BATCH, [], (tid, n) => new MetaApi(tid, n)); + Reg(TYPE_OPERATION, SUBTYPE_BASE, [], (tid, n) => new MetaOperation(tid, n)); Reg(TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_COMMAND, [.. ApiSchema.CommandAttrs], (tid, n) => new MetaOperation(tid, n)); Reg(TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_QUERY, [.. ApiSchema.QueryAttrs], (tid, n) => new MetaOperation(tid, n)); + Reg(TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_EVENT, [.. ApiSchema.EventAttrs], (tid, n) => new MetaOperation(tid, n)); + Reg(TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_EXPORT, [.. ApiSchema.ExportAttrs], (tid, n) => new MetaOperation(tid, n)); + Reg(TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_IMPORT, [.. ApiSchema.ImportAttrs], (tid, n) => new MetaOperation(tid, n)); Reg(TYPE_BINDING, SUBTYPE_BASE, [], (tid, n) => new MetaBinding(tid, n)); Reg(TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_REST, [.. ApiSchema.RestBindingAttrs], (tid, n) => new MetaBinding(tid, n)); + Reg(TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_MESSAGING, [.. ApiSchema.MessagingBindingAttrs], (tid, n) => new MetaBinding(tid, n)); + Reg(TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_FILE, [.. ApiSchema.FileBindingAttrs], (tid, n) => new MetaBinding(tid, n)); Reg(TYPE_TRANSITION, SUBTYPE_BASE, [.. TransitionSchema.TransitionBaseAttrs], (tid, n) => new MetaTransition(tid, n)); Reg(TYPE_TRANSITION, TransitionConstants.TRANSITION_SUBTYPE_ACTION, [.. TransitionSchema.ActionAttrs], (tid, n) => new MetaTransition(tid, n)); diff --git a/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs b/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs index 2dfbba3d91..acd3ffbf1f 100644 --- a/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs +++ b/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs @@ -89,7 +89,7 @@ private static List Entities(MetaData root) => root.Children().Where(c => c.Type == TYPE_OBJECT && c.SubType == OBJECT_SUBTYPE_ENTITY).ToList(); private static List Operations(MetaData root) => - root.Children().Where(c => c.Type == TYPE_API) + root.Children().Where(c => c.Type == TYPE_API && c.SubType == API_SUBTYPE_OPERATIONAL) .SelectMany(api => api.Children().Where(c => c.Type == TYPE_OPERATION)).ToList(); /// Every lifecycle of the model, once per declaring field, in model order. diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs index 2c0b2c601d..a6d7d1e65c 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs @@ -15,7 +15,8 @@ // Rules: // L1 ERR_TRANSITION_NOT_ON_ENTITY a transition under an enum field not declared on an object.entity // L2 ERR_TRANSITION_NOT_ON_ENTITY a concrete entity with a lifecycle and a source, none of them writable -// (on the entity). An entity with no source at all is inert (LifecycleIsLive). +// (on the entity). An entity with no relational source (none, or only +// source.document / source.search) is inert (LifecycleIsLive). // L3 ERR_LIFECYCLE_NO_INITIAL an enum field declaring transitions has no @default // L4 ERR_TRANSITION_UNKNOWN_STATE a @from or @to value is not one of the enum's @values // L5 ERR_TRANSITION_NAME_COLLISION a transition named create/get/list/update/delete, in any case @@ -46,6 +47,13 @@ // (a keyed operation) or are not empty (an unkeyed one) // B2 ERR_BINDING_PATH_MISMATCH two binding.rest of one API declaring a @path have the same // effective method and the same path once placeholder names are ignored +// +// Operations of an api.eventing or api.batch (event, export, import) are not commands or queries: +// only O1 applies to them, with two rules of their own: +// D1 ERR_BAD_ATTR_VALUE an operation.export @availableBy does not have the form its +// @frequency gives (AVAILABLE_BY_PATTERNS) +// D2 ERR_BAD_ATTR_VALUE a binding.file @fileName holds a placeholder other than {date} or +// {timestamp}, or an unclosed brace using System.Text.RegularExpressions; using MetaObjects.Core.Transition; @@ -228,10 +236,75 @@ private static void CheckEntityLifecycles(MetaData entity, RulesErrorSink sink) !entity.Children().Any(c => c is MetaSource ms && ms.IsWritable())) { sink.Add(entity, ErrorCode.ERR_TRANSITION_NOT_ON_ENTITY, - $"object.entity \"{entity.Name}\" has a lifecycle (transitions on {RulesQuoteList(transitions.Select(t => t.Parent?.Name ?? "").Distinct(StringComparer.Ordinal))}) and a source, but no writable one; a transition is a guarded update of a stored row. (An entity with no source at all may carry a lifecycle: it is inert until a source is added.)"); + $"object.entity \"{entity.Name}\" has a lifecycle (transitions on {RulesQuoteList(transitions.Select(t => t.Parent?.Name ?? "").Distinct(StringComparer.Ordinal))}) and a source, but no writable one; a transition is a guarded update of a stored row. (An entity with no relational source may carry a lifecycle: it is inert until a source.rdb is added.)"); + } + } + + /// O1 — an operation's @inputRef and @outputRef shapes. False when one is wrong. + private static bool CheckShapes(MetaData op, RulesErrorSink sink) + { + if (op.Attr(OPERATION_ATTR_INPUT_REF) is string inputRef) + { + var input = Lifecycles.ResolveObjectOn(op, inputRef); + if (input is null || input.SubType != OBJECT_SUBTYPE_VALUE) + { + sink.Add(op, ErrorCode.ERR_OPERATION_SHAPE, + $"operation.{op.SubType} \"{RulesLabel(op)}\" @inputRef \"{inputRef}\" {(input is null ? "names no object" : $"is an object.{input.SubType}")}; an operation's input is an object.value."); + return false; + } + } + if (op.Attr(OPERATION_ATTR_OUTPUT_REF) is string outputRef) + { + var output = Lifecycles.ResolveObjectOn(op, outputRef); + var legal = output is not null && + (output.SubType == OBJECT_SUBTYPE_ENTITY || output.SubType == OBJECT_SUBTYPE_PROJECTION || output.SubType == OBJECT_SUBTYPE_VALUE); + if (!legal) + { + sink.Add(op, ErrorCode.ERR_OPERATION_SHAPE, + $"operation.{op.SubType} \"{RulesLabel(op)}\" @outputRef \"{outputRef}\" {(output is null ? "names no object" : $"is an object.{output.SubType}")}; an operation returns an object.entity, object.projection or object.value."); + return false; + } + } + return true; + } + + /// The checks for one operation of an api.eventing or api.batch: its shapes (O1), the form of an + /// export's @availableBy (D1) and the placeholders of each binding.file @fileName (D2). + private static void CheckDeliveryOperation(MetaData op, RulesErrorSink sink) + { + if (!CheckShapes(op, sink)) return; + if (op.Attr(OPERATION_ATTR_AVAILABLE_BY) is string availableBy && op.Attr(OPERATION_ATTR_FREQUENCY) is string frequency + && AVAILABLE_BY_PATTERNS.TryGetValue(frequency, out var pattern) && !pattern.IsMatch(availableBy)) + { + sink.Add(op, ErrorCode.ERR_BAD_ATTR_VALUE, + $"operation.{op.SubType} \"{RulesLabel(op)}\" @availableBy \"{availableBy}\" is not a {frequency} time; a {frequency} file's @availableBy is written like \"{AVAILABLE_BY_EXAMPLES[frequency]}\" (UTC)."); + } + // ADR-0039: own — a binding is checked on the operation that declares it. + foreach (var b in op.OwnChildren()) + { + if (b.Type != TYPE_BINDING || b.SubType != BINDING_SUBTYPE_FILE) continue; + if (b.Attr(BINDING_ATTR_FILE_NAME) is not string fileName) continue; + if (FileNamePlaceholderProblem(fileName) is { } bad) + { + sink.Add(b, ErrorCode.ERR_BAD_ATTR_VALUE, + $"binding.file on \"{RulesLabel(b)}\" @fileName \"{fileName}\" {bad}; the placeholders are {{{string.Join("} and {", FILE_NAME_PLACEHOLDERS)}}}."); + } } } + private static readonly Regex FileNameBraces = new(@"\{([^{}]*)\}", RegexOptions.CultureInvariant); + + /// What is wrong with a @fileName's placeholders, or null when nothing is. + private static string? FileNamePlaceholderProblem(string fileName) + { + foreach (Match m in FileNameBraces.Matches(fileName)) + { + if (!FILE_NAME_PLACEHOLDERS.Contains(m.Groups[1].Value, StringComparer.Ordinal)) + return $"holds the placeholder {{{m.Groups[1].Value}}}"; + } + return FileNameBraces.Replace(fileName, "").IndexOfAny(['{', '}']) >= 0 ? "has an unmatched brace" : null; + } + /// O0-O5, P1 and B1 for one operation. private static void CheckOperation(MetaData op, RulesErrorSink sink) { @@ -258,28 +331,7 @@ private static void CheckOperation(MetaData op, RulesErrorSink sink) } // O1 — shapes. - if (op.Attr(OPERATION_ATTR_INPUT_REF) is string inputRef) - { - var input = Lifecycles.ResolveObjectOn(op, inputRef); - if (input is null || input.SubType != OBJECT_SUBTYPE_VALUE) - { - sink.Add(op, ErrorCode.ERR_OPERATION_SHAPE, - $"operation.{op.SubType} \"{RulesLabel(op)}\" @inputRef \"{inputRef}\" {(input is null ? "names no object" : $"is an object.{input.SubType}")}; an operation's input is an object.value."); - return; - } - } - if (op.Attr(OPERATION_ATTR_OUTPUT_REF) is string outputRef) - { - var output = Lifecycles.ResolveObjectOn(op, outputRef); - var legal = output is not null && - (output.SubType == OBJECT_SUBTYPE_ENTITY || output.SubType == OBJECT_SUBTYPE_PROJECTION || output.SubType == OBJECT_SUBTYPE_VALUE); - if (!legal) - { - sink.Add(op, ErrorCode.ERR_OPERATION_SHAPE, - $"operation.{op.SubType} \"{RulesLabel(op)}\" @outputRef \"{outputRef}\" {(output is null ? "names no object" : $"is an object.{output.SubType}")}; an operation returns an object.entity, object.projection or object.value."); - return; - } - } + if (!CheckShapes(op, sink)) return; // O2, O3 — the target. var derived = Lifecycles.DeriveOperationTarget(op)?.Entity; @@ -358,6 +410,11 @@ public static IReadOnlyList ValidateRules(MetaData root) { if (api.Type != TYPE_API) continue; var ops = api.Children().Where(c => c.Type == TYPE_OPERATION).ToList(); + if (api.SubType != API_SUBTYPE_OPERATIONAL) + { + foreach (var op in ops) CheckDeliveryOperation(op, sink); + continue; + } foreach (var op in ops) CheckOperation(op, sink); foreach (var op in ops) { @@ -419,7 +476,7 @@ void Register(MetaData node, MetaData owner, string path) } foreach (var api in root.Children()) { - if (api.Type != TYPE_API) continue; + if (api.Type != TYPE_API || api.SubType != API_SUBTYPE_OPERATIONAL) continue; foreach (var op in api.Children().Where(c => c.Type == TYPE_OPERATION)) Register(op, api, op.Name); } } diff --git a/server/csharp/MetaObjects/SpecMetamodel/api.json b/server/csharp/MetaObjects/SpecMetamodel/api.json index 6c803bfba0..ab76347e5c 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/api.json +++ b/server/csharp/MetaObjects/SpecMetamodel/api.json @@ -15,22 +15,39 @@ "whenToUse": "The application does something beyond derived CRUD: a named command (approve, cancel, import) or a named query (my open requests). Declare it here so its input, output, permission and business errors are part of the model. A plain lifecycle needs no api.operational at all: a transition nobody claims is held to derive its own command once a shell is generated, and no shell is generated yet.", "rules": "Children are `operation.command` and `operation.query`. Lives at the document root. Declares no fields, sources or identities: shapes are referenced, never defined, by the surface. Operation names are compared without case, are unique across every API of one package, except one operation declared identically in two APIs, such as a versioned API beside its successor (one operation declared twice in one API merges), and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). Two declared bindings of one API may not share a method and path (ERR_BINDING_PATH_MISMATCH).", "children": [ - { "type": "operation", "subType": "*", "name": "*", "min": 0, "max": null, "description": "The operations this surface exposes." } + { "type": "operation", "subType": "command", "name": "*", "min": 0, "max": null, "description": "The commands this surface exposes." }, + { "type": "operation", "subType": "query", "name": "*", "min": 0, "max": null, "description": "The queries this surface exposes." } ] }, { - "type": "operation", - "subType": "base", - "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.", + "type": "api", + "subType": "eventing", + "extendsBase": true, + "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.", + "rules": "Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.", "children": [ - { "type": "binding", "subType": "*", "name": "*", "min": 0, "max": null, "description": "Optional protocol bindings. Only needed to override the derived method and path." }, - { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." }, - { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." }, - { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." }, - { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." } + { "type": "operation", "subType": "event", "name": "*", "min": 0, "max": null, "description": "The events this surface publishes." } + ] + }, + { + "type": "api", + "subType": "batch", + "extendsBase": true, + "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.", + "rules": "Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.", + "children": [ + { "type": "operation", "subType": "export", "name": "*", "min": 0, "max": null, "description": "The datasets the provider publishes." }, + { "type": "operation", "subType": "import", "name": "*", "min": 0, "max": null, "description": "The datasets the provider accepts." } ] }, + { + "type": "operation", + "subType": "base", + "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.", + "children": [] + }, { "type": "operation", "subType": "command", @@ -38,6 +55,12 @@ "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.", "children": [ + { "type": "binding", "subType": "rest", "name": "*", "min": 0, "max": null, "description": "Optional HTTP bindings. Only needed to override the derived method and path." }, + { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." }, + { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." }, + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." }, { "type": "attr", "subType": "string", "name": "transitions", "isArray": true, "min": 0, "max": 1, "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)." }, { "type": "attr", "subType": "string", "name": "errors", "isArray": true, "min": 0, "max": 1, "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE." } ] @@ -49,9 +72,52 @@ "description": "A named operation that reads. Returns an `object.projection` (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", "whenToUse": "A read with its own name and shape beyond derived get and list: my open requests, the dashboard summary.", "children": [ + { "type": "binding", "subType": "rest", "name": "*", "min": 0, "max": null, "description": "Optional HTTP bindings. Only needed to override the derived method and path." }, + { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." }, + { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." }, + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." }, { "type": "attr", "subType": "boolean", "name": "many", "min": 0, "max": 1, "description": "The query returns a list and takes the filter, sort and paging contract. Not implied by the projection, so declared. Absent means one row. Legal on a query only." } ] }, + { + "type": "operation", + "subType": "event", + "extendsBase": true, + "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Each distinct fact a consumer may react to: placed, delivered, cancelled.", + "children": [ + { "type": "binding", "subType": "messaging", "name": "*", "min": 0, "max": null, "description": "Optional messaging bindings: how the event travels." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 1, "max": 1, "description": "The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "key", "min": 0, "max": 1, "description": "The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised." } + ] + }, + { + "type": "operation", + "subType": "export", + "extendsBase": true, + "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.", + "children": [ + { "type": "binding", "subType": "file", "name": "*", "min": 0, "max": null, "description": "Optional file bindings: where the file is and how it is written." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 1, "max": 1, "description": "The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "frequency", "min": 1, "max": 1, "allowedValues": ["hourly", "daily", "weekly", "monthly"], "description": "How often a new file appears: hourly, daily, weekly or monthly." }, + { "type": "attr", "subType": "string", "name": "availableBy", "min": 0, "max": 1, "description": "The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised." } + ] + }, + { + "type": "operation", + "subType": "import", + "extendsBase": true, + "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.", + "children": [ + { "type": "binding", "subType": "file", "name": "*", "min": 0, "max": null, "description": "Optional file bindings: where the file is delivered and how it is written." }, + { "type": "attr", "subType": "string", "name": "inputRef", "min": 1, "max": 1, "description": "The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "frequency", "min": 1, "max": 1, "allowedValues": ["hourly", "daily", "weekly", "monthly"], "description": "How often a new file is expected: hourly, daily, weekly or monthly." } + ] + }, { "type": "binding", "subType": "base", @@ -68,6 +134,32 @@ { "type": "attr", "subType": "string", "name": "method", "min": 0, "max": 1, "allowedValues": ["GET", "POST", "PUT", "PATCH", "DELETE"], "description": "The HTTP method. Absent: GET for a query, POST for a command." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "A path template. Its `{name}` placeholders must be exactly the target's primary key fields when the operation is keyed, and there must be none when it is not; two declared bindings of one API may not share the method and path (ERR_BINDING_PATH_MISMATCH)." } ] + }, + { + "type": "binding", + "subType": "messaging", + "extendsBase": true, + "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.", + "children": [ + { "type": "attr", "subType": "string", "name": "protocol", "min": 0, "max": 1, "allowedValues": ["kafka", "amqp", "mqtt", "sqs"], "description": "The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks." } + ] + }, + { + "type": "binding", + "subType": "file", + "extendsBase": true, + "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Every export and import whose file conventions two parties must agree on.", + "children": [ + { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, + { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, + { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, + { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, + { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } + ] } ], "extends": [ diff --git a/server/csharp/MetaObjects/SpecMetamodel/systems.json b/server/csharp/MetaObjects/SpecMetamodel/systems.json index cb6b7da4ed..189eaf4c5e 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/systems.json +++ b/server/csharp/MetaObjects/SpecMetamodel/systems.json @@ -64,7 +64,8 @@ "description": "A long-running process that answers requests: a web server, an API, a socket server.", "whenToUse": "Anything that listens on a port and stays up.", "children": [ - { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." } + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." }, + { "type": "attr", "subType": "string", "name": "provides", "isArray": true, "min": 0, "max": 1, "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } } ] }, { @@ -84,7 +85,9 @@ "description": "Work that runs to completion and exits: a scheduled task, a migration, a one-off batch. It may run on a schedule (@schedule) or when something triggers it.", "whenToUse": "A cron job, a nightly import, a queue drain that is not a long-running service.", "children": [ - { "type": "attr", "subType": "string", "name": "schedule", "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." } + { "type": "attr", "subType": "string", "name": "schedule", "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." }, + { "type": "attr", "subType": "string", "name": "extracts", "min": 0, "max": 1, "description": "The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object.", "ref": { "targetType": "object", "targetSubTypes": ["entity", "projection"] } }, + { "type": "attr", "subType": "string", "name": "provides", "isArray": true, "min": 0, "max": 1, "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } } ] }, { @@ -137,7 +140,8 @@ "description": "Files and blobs addressed by key.", "whenToUse": "Uploaded images, exports, static assets kept outside the app.", "children": [ - { "type": "attr", "subType": "boolean", "name": "publicRead", "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." } + { "type": "attr", "subType": "boolean", "name": "publicRead", "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." }, + { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`.", "ref": { "targetType": "api", "targetSubTypes": ["batch"] } } ] }, { @@ -162,7 +166,8 @@ "whenToUse": "Work handed from one app to another to run later.", "children": [ { "type": "attr", "subType": "boolean", "name": "ordered", "min": 0, "max": 1, "description": "Messages with the same key are delivered in the order they were sent. Absent means no order is promised." }, - { "type": "attr", "subType": "boolean", "name": "deadLetter", "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." } + { "type": "attr", "subType": "boolean", "name": "deadLetter", "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." }, + { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", "ref": { "targetType": "api", "targetSubTypes": ["eventing"] } } ] }, { @@ -170,7 +175,10 @@ "subType": "stream", "extendsBase": true, "description": "A retained, ordered log that many consumers read, each at its own position. A message can be read again.", - "whenToUse": "Events several consumers read independently, or read again." + "whenToUse": "Events several consumers read independently, or read again.", + "children": [ + { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", "ref": { "targetType": "api", "targetSubTypes": ["eventing"] } } + ] }, { "type": "resource", diff --git a/server/java/codegen-base/src/main/resources/metaobjects/explorer-app/assets/explorer-app.js b/server/java/codegen-base/src/main/resources/metaobjects/explorer-app/assets/explorer-app.js index a2681492a9..ec81740b86 100644 --- a/server/java/codegen-base/src/main/resources/metaobjects/explorer-app/assets/explorer-app.js +++ b/server/java/codegen-base/src/main/resources/metaobjects/explorer-app/assets/explorer-app.js @@ -265,5 +265,5 @@ `);for(var i=0;i0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(` `)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",` `,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(``)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(` -`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'
    ';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return``}function pct(x){return`${(Math.round(x*1e4)/100).toString()}%`}function legendHtml(withUnclaimed){return`
    ${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
    `}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
    ${values.map(esc).join(" | ")}
    `:"",column:esc(str(f.attrs[FIELD_ATTR_COLUMN])??""),flagsHtml:flags.map((x)=>`${esc(x)}`).join(""),claimsHtml:claims.map((c)=>`${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
    ")}}keyRow(from,c){let fields=strs(c.attrs[IDENTITY_ATTR_FIELDS]),target=this.refHtml(from,c,IDENTITY_REFERENCE_ATTR_REFERENCES)||this.refHtml(from,c,RELATIONSHIP_ATTR_OBJECT_REF),through=str(c.attrs[RELATIONSHIP_ATTR_THROUGH]),card=str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]),shape=c.type===TYPE_RELATIONSHIP?[card,through!==void 0?`through ${localName(through)}`:void 0].filter((x)=>x!==void 0).join(", "):`(${fields.join(", ")})`;return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),inheritedHtml:c.inheritedFrom!==void 0?'inherited':"",shape:esc(shape),targetHtml:target!==""?`→ ${target}`:""}}reportingRow(from,c){let a=c.attrs,parts=[],agg=str(a[REPORTING_ATTR_AGG]),of=this.refHtml(from,c,REPORTING_ATTR_OF,localName);if(agg!==void 0)parts.push(`${esc(agg)}(${of})`);else if(of!=="")parts.push(`of ${of}`);let num=str(a[REPORTING_ATTR_NUMERATOR]),den=str(a[REPORTING_ATTR_DENOMINATOR]);if(num!==void 0&&den!==void 0)parts.push(`${esc(num)} ÷ ${esc(den)}`);let via=str(a[REPORTING_ATTR_VIA]);if(via!==void 0)parts.push(`via ${esc(localName(via))}`);let grains=strs(a[REPORTING_ATTR_GRAINS]);if(grains.length>0)parts.push(`grains ${grains.map((g)=>`${esc(g)}`).join(" ")}`);let seg=str(a[REPORTING_ATTR_SEGMENT]);if(seg!==void 0)parts.push(`segment ${esc(seg)}`);if(a[REPORTING_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`);if(a[REPORTING_ATTR_DEFAULT]!==void 0)parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`);return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),definitionHtml:parts.join(" · ")}}layoutRow(l){let parts=[],cols=strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]);if(cols.length>0)parts.push(`columns ${cols.map((c)=>`${esc(c)}`).join(", ")}`);let sort=str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]);if(sort!==void 0)parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER])!==void 0?` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}`:""}`);if(typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]==="number")parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`);return{kind:esc(`${l.type}.${l.subType}`),name:esc(l.name),detailHtml:parts.join(", ")}}projectionBlock(from,n){let ix=this.ix,rows=[],bases=new Set;for(let f of ix.fields(n.id)){if(f.extends!==void 0)bases.add(ix.ownerOf(f.extends));for(let o of ix.children(f.id).filter((c)=>c.type===TYPE_ORIGIN)){let def=this.originDefinition(from,o);for(let src of this.refLinks(o,ORIGIN_PASSTHROUGH_ATTR_FROM))bases.add(ix.ownerOf(src.id));rows.push({field:esc(f.name),origin:esc(`origin.${o.subType}`),definitionHtml:def})}}return{basesHtml:[...bases].filter((b)=>b!==n.id).sort(byCodeUnit2).map((b)=>this.link(from,b)).join(", "),origins:rows,hasOrigins:rows.length>0}}originDefinition(from,o){let a=o.attrs,ref=(name)=>this.attrValues(o,name).map((v)=>v.link!==null&&!v.link.unresolved?this.link(from,v.link.id,localName(v.text)):`${esc(localName(v.text))}`).join(", "),parts=[],agg=str(a[ORIGIN_AGGREGATE_ATTR_AGG]);if(agg!==void 0)parts.push(`${esc(agg)}(${ref(ORIGIN_AGGREGATE_ATTR_OF)})`);else if(a[ORIGIN_AGGREGATE_ATTR_OF]!==void 0)parts.push(`of ${ref(ORIGIN_AGGREGATE_ATTR_OF)}`);if(a[ORIGIN_PASSTHROUGH_ATTR_FROM]!==void 0)parts.push(`from ${ref(ORIGIN_PASSTHROUGH_ATTR_FROM)}`);if(a[ORIGIN_AGGREGATE_ATTR_VIA]!==void 0)parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`);if(a[ORIGIN_COMPUTED_ATTR_EXPR]!==void 0)parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`);if(a[ORIGIN_AGGREGATE_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`);return parts.join(" · ")}reportBlock(from,n){let a=n.attrs,fromId=this.refLinks(n,OBJECT_REPORT_ATTR_FROM)[0]?.id??str(a[OBJECT_REPORT_ATTR_FROM]),resolve2=(name,kindType)=>{let hit=[fromId!==void 0?`${fromId}.${name}`:void 0,`${n.package===""?"":`${n.package}::`}${name}`].filter((x)=>x!==void 0).find((c)=>this.ix.byId.get(c)?.type===kindType||this.ix.byId.has(c)&&name.includes("."));return hit!==void 0?this.link(from,hit,name):`${esc(name)}`},spine=str(a[OBJECT_REPORT_ATTR_SPINE]);return{fromHtml:this.refHtml(from,n,OBJECT_REPORT_ATTR_FROM),spineHtml:spine!==void 0?`${esc(spine)}`:"",dimensionsHtml:strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d)=>resolve2(d,TYPE_DIMENSION)).join(", "),measuresHtml:strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m)=>resolve2(m,TYPE_MEASURE)).join(", "),segmentHtml:strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s)=>resolve2(s,TYPE_SEGMENT)).join(", "),filterHtml:a[OBJECT_REPORT_ATTR_FILTER]!==void 0?`${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}`:""}}generatedGroups(id){let groups=new Map;for(let f of this.ix.generated(id))groups.set(f.generatedBy,[...groups.get(f.generatedBy)??[],f.path]);return[...groups.keys()].sort(byCodeUnit2).map((g)=>({generator:esc(g),files:(groups.get(g)??[]).map((p)=>esc(p))}))}node(n){let ix=this.ix,from=this.objectPage(n),kindLabel=`${n.type}.${n.subType}`,whyRows=this.whyRows(from,n),attrs=this.attrRows(from,n),referrers=[...(ix.top(n.id)?.referencedBy??[]).map((e)=>e.from.id),...ix.claims(n.id).map((c)=>this.topOf(c.req).node.id)],refBy=[...new Set(referrers.filter((id)=>id!==n.id))].sort(byCodeUnit2).map((id)=>this.link(from,id));return{id:esc(n.id),name:esc(n.name),kindLabel:esc(kindLabel),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › ${esc(kindLabel)}`,isAbstract:n.abstract===!0,description:this.description(n),extendsHtml:n.extends!==void 0?this.link(from,n.extends):"",attrs,hasAttrs:attrs.length>0,members:ix.children(n.id).map((c)=>({anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),nameHtml:ix.reqById.has(c.id)?this.link(from,c.id):esc(c.name===""?`#${c.order}`:c.name),attrsHtml:this.attrRows(from,c).map((a)=>`@${a.name} ${a.valueHtml}`).join("
    "),below:ix.children(c.id).length})),hasMembers:ix.children(n.id).length>0,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(from,n){return n.view.attrs.map((a)=>{let links=a.values.filter((v)=>v.link!==null&&!v.link.unresolved);return{name:esc(a.name),valueHtml:links.length>0&&links.length===a.values.length?links.map((v)=>this.link(from,v.link.id)).join(", "):`${esc(fmt(a.value))}`}})}prompt(n,text){let ix=this.ix,from=this.objectPage(n),payloadId=this.refLinks(n,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id,replyId=this.refLinks(n,TEMPLATE_ATTR_RESPONSE_REF)[0]?.id,vars=text!==void 0?templateVariables(text):void 0,payload=payloadId!==void 0?ix.byId.get(payloadId):void 0,reply=replyId!==void 0?ix.byId.get(replyId):void 0,payloadRows=payload!==void 0?ix.fields(payload.id).map((f)=>({name:esc(f.name),requiredHtml:f.attrs[FIELD_ATTR_REQUIRED]===!0?'required':"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)!==""?` → ${this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)}`:"",usedHtml:vars===void 0?'text not read':vars.has(f.name)?"yes":'no'})):[],replyRows=reply!==void 0?ix.fields(reply.id).map((f)=>({name:esc(f.name),type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),valuesHtml:f.subType===FIELD_SUBTYPE_ENUM?`
    ${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
    `:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(` +`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var FREQUENCY_HOURLY="hourly",FREQUENCY_DAILY="daily",FREQUENCY_WEEKLY="weekly",FREQUENCY_MONTHLY="monthly";var AVAILABLE_BY_PATTERNS={[FREQUENCY_HOURLY]:/^:[0-5][0-9]$/,[FREQUENCY_DAILY]:/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/,[FREQUENCY_WEEKLY]:/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/,[FREQUENCY_MONTHLY]:/^(?:[1-9]|1[0-9]|2[0-8]) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/},AVAILABLE_BY_EXAMPLES={[FREQUENCY_HOURLY]:":15",[FREQUENCY_DAILY]:"03:00",[FREQUENCY_WEEKLY]:"Mon 06:00",[FREQUENCY_MONTHLY]:"1 06:00"};var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'
    ';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return``}function pct(x){return`${(Math.round(x*1e4)/100).toString()}%`}function legendHtml(withUnclaimed){return`
    ${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
    `}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
    ${values.map(esc).join(" | ")}
    `:"",column:esc(str(f.attrs[FIELD_ATTR_COLUMN])??""),flagsHtml:flags.map((x)=>`${esc(x)}`).join(""),claimsHtml:claims.map((c)=>`${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
    ")}}keyRow(from,c){let fields=strs(c.attrs[IDENTITY_ATTR_FIELDS]),target=this.refHtml(from,c,IDENTITY_REFERENCE_ATTR_REFERENCES)||this.refHtml(from,c,RELATIONSHIP_ATTR_OBJECT_REF),through=str(c.attrs[RELATIONSHIP_ATTR_THROUGH]),card=str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]),shape=c.type===TYPE_RELATIONSHIP?[card,through!==void 0?`through ${localName(through)}`:void 0].filter((x)=>x!==void 0).join(", "):`(${fields.join(", ")})`;return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),inheritedHtml:c.inheritedFrom!==void 0?'inherited':"",shape:esc(shape),targetHtml:target!==""?`→ ${target}`:""}}reportingRow(from,c){let a=c.attrs,parts=[],agg=str(a[REPORTING_ATTR_AGG]),of=this.refHtml(from,c,REPORTING_ATTR_OF,localName);if(agg!==void 0)parts.push(`${esc(agg)}(${of})`);else if(of!=="")parts.push(`of ${of}`);let num=str(a[REPORTING_ATTR_NUMERATOR]),den=str(a[REPORTING_ATTR_DENOMINATOR]);if(num!==void 0&&den!==void 0)parts.push(`${esc(num)} ÷ ${esc(den)}`);let via=str(a[REPORTING_ATTR_VIA]);if(via!==void 0)parts.push(`via ${esc(localName(via))}`);let grains=strs(a[REPORTING_ATTR_GRAINS]);if(grains.length>0)parts.push(`grains ${grains.map((g)=>`${esc(g)}`).join(" ")}`);let seg=str(a[REPORTING_ATTR_SEGMENT]);if(seg!==void 0)parts.push(`segment ${esc(seg)}`);if(a[REPORTING_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`);if(a[REPORTING_ATTR_DEFAULT]!==void 0)parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`);return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),definitionHtml:parts.join(" · ")}}layoutRow(l){let parts=[],cols=strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]);if(cols.length>0)parts.push(`columns ${cols.map((c)=>`${esc(c)}`).join(", ")}`);let sort=str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]);if(sort!==void 0)parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER])!==void 0?` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}`:""}`);if(typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]==="number")parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`);return{kind:esc(`${l.type}.${l.subType}`),name:esc(l.name),detailHtml:parts.join(", ")}}projectionBlock(from,n){let ix=this.ix,rows=[],bases=new Set;for(let f of ix.fields(n.id)){if(f.extends!==void 0)bases.add(ix.ownerOf(f.extends));for(let o of ix.children(f.id).filter((c)=>c.type===TYPE_ORIGIN)){let def=this.originDefinition(from,o);for(let src of this.refLinks(o,ORIGIN_PASSTHROUGH_ATTR_FROM))bases.add(ix.ownerOf(src.id));rows.push({field:esc(f.name),origin:esc(`origin.${o.subType}`),definitionHtml:def})}}return{basesHtml:[...bases].filter((b)=>b!==n.id).sort(byCodeUnit2).map((b)=>this.link(from,b)).join(", "),origins:rows,hasOrigins:rows.length>0}}originDefinition(from,o){let a=o.attrs,ref=(name)=>this.attrValues(o,name).map((v)=>v.link!==null&&!v.link.unresolved?this.link(from,v.link.id,localName(v.text)):`${esc(localName(v.text))}`).join(", "),parts=[],agg=str(a[ORIGIN_AGGREGATE_ATTR_AGG]);if(agg!==void 0)parts.push(`${esc(agg)}(${ref(ORIGIN_AGGREGATE_ATTR_OF)})`);else if(a[ORIGIN_AGGREGATE_ATTR_OF]!==void 0)parts.push(`of ${ref(ORIGIN_AGGREGATE_ATTR_OF)}`);if(a[ORIGIN_PASSTHROUGH_ATTR_FROM]!==void 0)parts.push(`from ${ref(ORIGIN_PASSTHROUGH_ATTR_FROM)}`);if(a[ORIGIN_AGGREGATE_ATTR_VIA]!==void 0)parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`);if(a[ORIGIN_COMPUTED_ATTR_EXPR]!==void 0)parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`);if(a[ORIGIN_AGGREGATE_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`);return parts.join(" · ")}reportBlock(from,n){let a=n.attrs,fromId=this.refLinks(n,OBJECT_REPORT_ATTR_FROM)[0]?.id??str(a[OBJECT_REPORT_ATTR_FROM]),resolve2=(name,kindType)=>{let hit=[fromId!==void 0?`${fromId}.${name}`:void 0,`${n.package===""?"":`${n.package}::`}${name}`].filter((x)=>x!==void 0).find((c)=>this.ix.byId.get(c)?.type===kindType||this.ix.byId.has(c)&&name.includes("."));return hit!==void 0?this.link(from,hit,name):`${esc(name)}`},spine=str(a[OBJECT_REPORT_ATTR_SPINE]);return{fromHtml:this.refHtml(from,n,OBJECT_REPORT_ATTR_FROM),spineHtml:spine!==void 0?`${esc(spine)}`:"",dimensionsHtml:strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d)=>resolve2(d,TYPE_DIMENSION)).join(", "),measuresHtml:strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m)=>resolve2(m,TYPE_MEASURE)).join(", "),segmentHtml:strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s)=>resolve2(s,TYPE_SEGMENT)).join(", "),filterHtml:a[OBJECT_REPORT_ATTR_FILTER]!==void 0?`${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}`:""}}generatedGroups(id){let groups=new Map;for(let f of this.ix.generated(id))groups.set(f.generatedBy,[...groups.get(f.generatedBy)??[],f.path]);return[...groups.keys()].sort(byCodeUnit2).map((g)=>({generator:esc(g),files:(groups.get(g)??[]).map((p)=>esc(p))}))}node(n){let ix=this.ix,from=this.objectPage(n),kindLabel=`${n.type}.${n.subType}`,whyRows=this.whyRows(from,n),attrs=this.attrRows(from,n),referrers=[...(ix.top(n.id)?.referencedBy??[]).map((e)=>e.from.id),...ix.claims(n.id).map((c)=>this.topOf(c.req).node.id)],refBy=[...new Set(referrers.filter((id)=>id!==n.id))].sort(byCodeUnit2).map((id)=>this.link(from,id));return{id:esc(n.id),name:esc(n.name),kindLabel:esc(kindLabel),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › ${esc(kindLabel)}`,isAbstract:n.abstract===!0,description:this.description(n),extendsHtml:n.extends!==void 0?this.link(from,n.extends):"",attrs,hasAttrs:attrs.length>0,members:ix.children(n.id).map((c)=>({anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),nameHtml:ix.reqById.has(c.id)?this.link(from,c.id):esc(c.name===""?`#${c.order}`:c.name),attrsHtml:this.attrRows(from,c).map((a)=>`@${a.name} ${a.valueHtml}`).join("
    "),below:ix.children(c.id).length})),hasMembers:ix.children(n.id).length>0,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(from,n){return n.view.attrs.map((a)=>{let links=a.values.filter((v)=>v.link!==null&&!v.link.unresolved);return{name:esc(a.name),valueHtml:links.length>0&&links.length===a.values.length?links.map((v)=>this.link(from,v.link.id)).join(", "):`${esc(fmt(a.value))}`}})}prompt(n,text){let ix=this.ix,from=this.objectPage(n),payloadId=this.refLinks(n,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id,replyId=this.refLinks(n,TEMPLATE_ATTR_RESPONSE_REF)[0]?.id,vars=text!==void 0?templateVariables(text):void 0,payload=payloadId!==void 0?ix.byId.get(payloadId):void 0,reply=replyId!==void 0?ix.byId.get(replyId):void 0,payloadRows=payload!==void 0?ix.fields(payload.id).map((f)=>({name:esc(f.name),requiredHtml:f.attrs[FIELD_ATTR_REQUIRED]===!0?'required':"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)!==""?` → ${this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)}`:"",usedHtml:vars===void 0?'text not read':vars.has(f.name)?"yes":'no'})):[],replyRows=reply!==void 0?ix.fields(reply.id).map((f)=>({name:esc(f.name),type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),valuesHtml:f.subType===FIELD_SUBTYPE_ENUM?`
    ${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
    `:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(` `).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
      ${tops.map((r)=>this.treeNode(page,r)).join("")}
    `:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
  • ${`
    ${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}${dispositionPill(r)}${verdictBadge(r)}${bar}${links.join("")}
    ${esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??"")}
    `}${r.children.length>0?`
      ${r.children.map((c)=>this.treeNode(from,c)).join("")}
    `:""}
  • `}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`${cols.map((o)=>`
    ${this.link(from,o.id)}
    `).join("")}`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLink(from,top)}${cols.map(()=>'').join("")}`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`${levelBadge(r)}${esc(label)}${cols.map((o)=>tg.has(o.id)?`${statusGlyph(r.status)}`:'').join("")}`)}}return{tableHtml:rows.length>0?`${head}${rows.join("")}
    `:"",hasRows:rows.length>0,hasRequirements:ix.hasRequirements()}}trace(){let starts=this.ix.requirements.filter((r)=>r.level!==void 0&&r.level<=REQUIREMENT_LEVEL_SERVICE),fallback=starts.length===0?this.ix.topRequirements:[];return{options:[...starts,...fallback].map((r)=>({value:esc(r.node.id),label:esc(`${" ".repeat(Math.max(0,(r.level??1)-1))}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)}`)})),hasStarts:starts.length+fallback.length>0,hasUsage:!1}}gaps(){let ix=this.ix,from=PAGE_GAPS,cards=[],card=(title,count,source,why,bodyHtml)=>{cards.push({title:esc(title),count:esc(String(count)),source:esc(source),isGate:source==="meta verify",whyHtml:why,bodyHtml})};if(ix.view.sources.requirements){let findingsOf=(gate2)=>[...ix.requirements.flatMap((req)=>req.req.diagnostics.filter((d)=>d.source===GATE_SOURCE===gate2).map((d)=>({req,d}))),...ix.view.advisories.filter((d)=>d.path===""&&d.source===GATE_SOURCE===gate2).map((d)=>({d}))],table=(rows,chip)=>rows.length===0?'
    None.
    ':`${rows.map(({req,d})=>``).join("")}
    ${esc(d.code)}${req!==void 0?this.reqLink(from,req):""}
    ${esc(d.message)}
    `,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
    None.
    ');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
    None.
    ')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
    Not scanned.
    ');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
    No prompt text was read.
    ':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
    None.
    ':`
      ${items.map((i)=>`
    • ${i}
    • `).join("")}
    `}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found

    No such page

    ${escapeHtml2(r.path)} is not a page of this model.

    Overview

    `,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="

    No model yet

    The explorer is waiting for the running application's docs view.

    ";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="

    No model

    The source parameter is not a URL.

    ",paintLive();return}follow(source);return}if(!build())document.body.innerHTML="

    No model

    explorer-model.js did not load. Run meta gen to write it beside this page.

    ";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})(); diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/RulesInertTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/RulesInertTest.kt index 5165f58c18..e81b0bcda4 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/RulesInertTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/RulesInertTest.kt @@ -164,6 +164,45 @@ class RulesInertTest { assertTrue(leak == null, leak) } + // 1.4.0: an api.eventing and an api.batch are not commands or queries, and nothing is generated from them. + + @Test + fun `the with-delivery model really carries the two api kinds`() { + val subTypes = load("with-delivery").root.getChildren(MetaData::class.java, true) + .filter { it.type == "api" }.map { it.subType } + assertEquals(listOf("operational", "eventing", "batch"), subTypes) + } + + @Test + fun `every generator emits the same files with the delivery apis`() { + val leaks = codeGenerators.mapNotNull { info -> + sameOrLeak(info.name, emit("with", listOf(info)), emit("with-delivery", listOf(info))) + } + assertTrue(leaks.isEmpty(), leaks.joinToString("\n")) + } + + @Test + fun `every runnable generator in one run emits the same files with the delivery apis`() { + val runnable = codeGenerators.filter { THREW !in emit("with", listOf(it)) } + val expected = emit("with", runnable) + assertFalse(THREW in expected, "the combined suite threw: ${expected[THREW]}") + val leak = sameOrLeak("combined", expected, emit("with-delivery", runnable)) + assertTrue(leak == null, leak) + } + + @Test + fun `docs-site differs by exactly the delivery apis`() { + val info = GENERATOR_REGISTRY.getValue(DocsSiteInert.GENERATOR) + val problems = DocsSiteInert.check(emit("with", listOf(info)), emit("with-delivery", listOf(info)), setOf("api")) + assertTrue(problems.isEmpty(), problems.joinToString("\n")) + } + + @Test + fun `the api reference is identical with the delivery apis`() { + val leak = sameOrLeak("api docs", apiDocs("with"), apiDocs("with-delivery")) + assertTrue(leak == null, leak) + } + private companion object { const val THREW = "" } diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/RulesInertTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/RulesInertTest.java index 08232b7972..2b0c6b96fc 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/RulesInertTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/RulesInertTest.java @@ -192,4 +192,54 @@ public void theApiReferenceIsIdentical() throws Exception { assertTrue("only " + expected.size() + " pages - the docs barely ran", expected.size() >= 3); assertSame("api docs", expected, apiDocs("with")); } + + // 1.4.0: an api.eventing and an api.batch are not commands or queries, and nothing is generated from them. + + @Test + public void theWithDeliveryModelReallyCarriesTheTwoApiKinds() throws Exception { + List subTypes = new ArrayList<>(); + for (MetaData child : load("with-delivery").getRoot().getChildren(MetaData.class, true)) { + if ("api".equals(child.getType())) subTypes.add(child.getSubType()); + } + assertEquals(List.of("operational", "eventing", "batch"), subTypes); + } + + @Test + public void everyGeneratorEmitsForTheDeliveryApisWhatItEmitsWithoutThem() throws Exception { + List leaks = new ArrayList<>(); + for (GeneratorInfo info : GeneratorRegistry.list().values()) { + if (DocsSiteInert.GENERATOR.equals(info.stableName())) continue; + try { + assertSame(info.stableName(), emit("with", List.of(info)), emit("with-delivery", List.of(info))); + } catch (AssertionError e) { + leaks.add(e.getMessage()); + } + } + assertTrue(String.join("\n", leaks), leaks.isEmpty()); + } + + @Test + public void docsSiteDiffersByExactlyTheDeliveryApis() throws Exception { + GeneratorInfo info = GeneratorRegistry.list().get(DocsSiteInert.GENERATOR); + List problems = DocsSiteInert.check(emit("with", List.of(info)), emit("with-delivery", List.of(info)), Set.of("api")); + assertTrue(String.join("\n", problems), problems.isEmpty()); + } + + @Test + public void theModelAndWebTiersEmitTheSameFilesWithTheDeliveryApis() throws Exception { + Map all = GeneratorRegistry.list(); + for (List tier : List.of( + List.of("entity", "names"), + List.of("value-object", "dto", "repository", "filter-allowlist", "routes", "names"))) { + List suite = tier.stream().map(all::get).collect(Collectors.toList()); + Map expected = emit("with", suite); + assertFalse(tier + " threw: " + expected.get(THREW), expected.containsKey(THREW)); + assertSame(tier.toString(), expected, emit("with-delivery", suite)); + } + } + + @Test + public void theApiReferenceIsIdenticalWithTheDeliveryApis() throws Exception { + assertSame("api docs", apiDocs("with"), apiDocs("with-delivery")); + } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/ApiConstants.java b/server/java/metadata/src/main/java/com/metaobjects/api/ApiConstants.java index 371564aa65..210ae6c4ed 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/api/ApiConstants.java +++ b/server/java/metadata/src/main/java/com/metaobjects/api/ApiConstants.java @@ -33,6 +33,42 @@ private ApiConstants() { public static final String OPERATION_SUBTYPE_QUERY = "query"; public static final String BINDING_SUBTYPE_REST = "rest"; + public static final String API_SUBTYPE_EVENTING = "eventing"; + public static final String API_SUBTYPE_BATCH = "batch"; + public static final String OPERATION_SUBTYPE_EVENT = "event"; + public static final String OPERATION_SUBTYPE_EXPORT = "export"; + public static final String OPERATION_SUBTYPE_IMPORT = "import"; + public static final String BINDING_SUBTYPE_MESSAGING = "messaging"; + public static final String BINDING_SUBTYPE_FILE = "file"; + + public static final String ATTR_KEY = "key"; + public static final String ATTR_FREQUENCY = "frequency"; + public static final String ATTR_AVAILABLE_BY = "availableBy"; + public static final String ATTR_PROTOCOL = "protocol"; + public static final String ATTR_TRANSPORT = "transport"; + public static final String ATTR_FILE_NAME = "fileName"; + public static final String ATTR_FORMAT = "format"; + public static final String ATTR_COMPRESSION = "compression"; + public static final String ATTR_COMPLETION = "completion"; + public static final String ATTR_ENCRYPTION = "encryption"; + + /** How often an export or import file appears; the order is the order a message names them. */ + public static final List FREQUENCIES = List.of("hourly", "daily", "weekly", "monthly"); + + /** What an export's {@code @availableBy} looks like for each frequency (UTC). */ + public static final java.util.Map AVAILABLE_BY_PATTERNS = java.util.Map.of( + "hourly", Pattern.compile("^:[0-5][0-9]$"), + "daily", Pattern.compile("^(?:[01][0-9]|2[0-3]):[0-5][0-9]$"), + "weekly", Pattern.compile("^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:[01][0-9]|2[0-3]):[0-5][0-9]$"), + "monthly", Pattern.compile("^(?:[1-9]|1[0-9]|2[0-8]) (?:[01][0-9]|2[0-3]):[0-5][0-9]$")); + + /** One well-formed {@code @availableBy} per frequency, for a message. */ + public static final java.util.Map AVAILABLE_BY_EXAMPLES = java.util.Map.of( + "hourly", ":15", "daily", "03:00", "weekly", "Mon 06:00", "monthly", "1 06:00"); + + /** The placeholders a {@code binding.file @fileName} may hold. */ + public static final List FILE_NAME_PLACEHOLDERS = List.of("date", "timestamp"); + public static final String ATTR_INPUT_REF = "inputRef"; public static final String ATTR_OUTPUT_REF = "outputRef"; public static final String ATTR_OBJECT_REF = "objectRef"; diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/CommandOperation.java b/server/java/metadata/src/main/java/com/metaobjects/api/CommandOperation.java index d60a1cc130..8ec2aa251d 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/api/CommandOperation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/api/CommandOperation.java @@ -34,21 +34,15 @@ public static void registerTypes(MetaDataRegistry registry) { def.type(ApiConstants.TYPE_OPERATION).subType(MetaData.SUBTYPE_BASE) .description("Registry anchor for the attributes every operation shares") .inheritsFrom(MetaData.TYPE_METADATA, MetaData.SUBTYPE_BASE) - .optionalChild(ApiConstants.TYPE_BINDING, "*", "*") // Like template.base: the any-attr wildcard lets an undeclared attr reach the // strict-load ERR_UNKNOWN_ATTR diagnostic instead of failing placement. .optionalChild(com.metaobjects.attr.MetaAttribute.TYPE_ATTR, "*", "*"); - for (String ref : new String[] {ApiConstants.ATTR_INPUT_REF, ApiConstants.ATTR_OUTPUT_REF, - ApiConstants.ATTR_OBJECT_REF, ApiConstants.ATTR_PERMISSION}) { - def.optionalAttributeWithConstraints(ref).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); - } - def.optionalAttributeWithConstraints(ApiConstants.ATTR_PUBLIC) - .ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); }); registry.registerType(CommandOperation.class, def -> { def.type(ApiConstants.TYPE_OPERATION).subType(ApiConstants.OPERATION_SUBTYPE_COMMAND) .description("A named operation that changes state.") .inheritsFrom(ApiConstants.TYPE_OPERATION, MetaData.SUBTYPE_BASE); + sharedAttrs(def); def.optionalAttributeWithConstraints(ApiConstants.ATTR_TRANSITIONS) .ofType(StringAttribute.SUBTYPE_STRING).asArray(); def.optionalAttributeWithConstraints(ApiConstants.ATTR_ERRORS) @@ -58,8 +52,20 @@ public static void registerTypes(MetaDataRegistry registry) { def.type(ApiConstants.TYPE_OPERATION).subType(ApiConstants.OPERATION_SUBTYPE_QUERY) .description("A named operation that reads.") .inheritsFrom(ApiConstants.TYPE_OPERATION, MetaData.SUBTYPE_BASE); + sharedAttrs(def); def.optionalAttributeWithConstraints(ApiConstants.ATTR_MANY) .ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); }); } + + /** What a command and a query share (ADR-0030): the rest bindings, the shapes, the target and the permission. operation.base declares none. */ + private static void sharedAttrs(com.metaobjects.registry.TypeDefinitionBuilder def) { + def.optionalChild(ApiConstants.TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_REST, "*"); + for (String ref : new String[] {ApiConstants.ATTR_INPUT_REF, ApiConstants.ATTR_OUTPUT_REF, + ApiConstants.ATTR_OBJECT_REF, ApiConstants.ATTR_PERMISSION}) { + def.optionalAttributeWithConstraints(ref).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + } + def.optionalAttributeWithConstraints(ApiConstants.ATTR_PUBLIC) + .ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); + } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryNode.java b/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryNode.java new file mode 100644 index 0000000000..82bc9d15e8 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryNode.java @@ -0,0 +1,32 @@ +/* + * Copyright 2026 Doug Mealing LLC dba Meta Objects + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.metaobjects.api; + +import com.metaobjects.MetaData; + +/** + * One node class for the delivery vocabulary of 1.4.0 (ADR-0030): {@code api.eventing}, + * {@code api.batch}, {@code operation.event|export|import} and {@code binding.messaging|file}. + * They are vocabulary only on the Java port, so one class serves each type and the loader + * constructs it through the 3-argument form. Nothing is generated from them. + */ +@SuppressWarnings("serial") +public class DeliveryNode extends MetaData { + + public DeliveryNode(String type, String subType, String name) { + super(type, subType, name); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryTypes.java b/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryTypes.java new file mode 100644 index 0000000000..3e5fb7f0d5 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryTypes.java @@ -0,0 +1,92 @@ +/* + * Copyright 2026 Doug Mealing LLC dba Meta Objects + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.metaobjects.api; + +import com.metaobjects.MetaData; +import com.metaobjects.attr.StringAttribute; +import com.metaobjects.registry.MetaDataRegistry; +import com.metaobjects.registry.TypeDefinitionBuilder; + +import java.util.function.Consumer; + +/** Registers {@code api.eventing}, {@code api.batch}, their operations and bindings; text and children come from {@code spec/metamodel/api.json}. */ +public final class DeliveryTypes { + + private DeliveryTypes() { + } + + public static void registerTypes(MetaDataRegistry registry) { + type(registry, ApiConstants.TYPE_API, ApiConstants.API_SUBTYPE_EVENTING, d -> + d.optionalChild(ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_EVENT, "*")); + type(registry, ApiConstants.TYPE_API, ApiConstants.API_SUBTYPE_BATCH, d -> { + d.optionalChild(ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_EXPORT, "*"); + d.optionalChild(ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_IMPORT, "*"); + }); + + type(registry, ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_EVENT, d -> { + d.optionalChild(ApiConstants.TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_MESSAGING, "*"); + required(d, ApiConstants.ATTR_OUTPUT_REF); + optional(d, ApiConstants.ATTR_KEY); + }); + type(registry, ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_EXPORT, d -> { + d.optionalChild(ApiConstants.TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_FILE, "*"); + required(d, ApiConstants.ATTR_OUTPUT_REF); + d.requiredAttributeWithConstraints(ApiConstants.ATTR_FREQUENCY).ofType(StringAttribute.SUBTYPE_STRING) + .withEnum(ApiConstants.FREQUENCIES.toArray(new String[0])); + optional(d, ApiConstants.ATTR_AVAILABLE_BY); + }); + type(registry, ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_IMPORT, d -> { + d.optionalChild(ApiConstants.TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_FILE, "*"); + required(d, ApiConstants.ATTR_INPUT_REF); + d.requiredAttributeWithConstraints(ApiConstants.ATTR_FREQUENCY).ofType(StringAttribute.SUBTYPE_STRING) + .withEnum(ApiConstants.FREQUENCIES.toArray(new String[0])); + }); + + type(registry, ApiConstants.TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_MESSAGING, d -> + enumAttr(d, false, ApiConstants.ATTR_PROTOCOL, "kafka", "amqp", "mqtt", "sqs")); + type(registry, ApiConstants.TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_FILE, d -> { + enumAttr(d, true, ApiConstants.ATTR_TRANSPORT, "sftp", "objectStore"); + optional(d, ApiConstants.ATTR_PATH); + required(d, ApiConstants.ATTR_FILE_NAME); + enumAttr(d, true, ApiConstants.ATTR_FORMAT, "csv", "jsonLines", "parquet"); + enumAttr(d, false, ApiConstants.ATTR_COMPRESSION, "none", "gzip"); + enumAttr(d, false, ApiConstants.ATTR_COMPLETION, "rename", "marker", "none"); + enumAttr(d, false, ApiConstants.ATTR_ENCRYPTION, "none", "pgp"); + }); + } + + private static void type(MetaDataRegistry registry, String type, String subType, Consumer body) { + registry.registerType(DeliveryNode.class, d -> { + d.type(type).subType(subType) + .description(type + "." + subType + " (ADR-0030)") + .inheritsFrom(type, MetaData.SUBTYPE_BASE); + body.accept(d); + }); + } + + private static void optional(TypeDefinitionBuilder d, String name) { + d.optionalAttributeWithConstraints(name).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + } + + private static void required(TypeDefinitionBuilder d, String name) { + d.requiredAttributeWithConstraints(name).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + } + + private static void enumAttr(TypeDefinitionBuilder d, boolean required, String name, String... values) { + (required ? d.requiredAttributeWithConstraints(name) : d.optionalAttributeWithConstraints(name)) + .ofType(StringAttribute.SUBTYPE_STRING).withEnum(values); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/OperationalApi.java b/server/java/metadata/src/main/java/com/metaobjects/api/OperationalApi.java index 104ba49140..d252a3c2f9 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/api/OperationalApi.java +++ b/server/java/metadata/src/main/java/com/metaobjects/api/OperationalApi.java @@ -39,6 +39,7 @@ public static void registerTypes(MetaDataRegistry registry) { .type(ApiConstants.TYPE_API).subType(ApiConstants.API_SUBTYPE_OPERATIONAL) .description("A named, packaged request/response surface whose children are operations.") .inheritsFrom(ApiConstants.TYPE_API, MetaData.SUBTYPE_BASE) - .optionalChild(ApiConstants.TYPE_OPERATION, "*", "*")); + .optionalChild(ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_COMMAND, "*") + .optionalChild(ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_QUERY, "*")); } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/RulesCheck.java b/server/java/metadata/src/main/java/com/metaobjects/api/RulesCheck.java index 223a31a742..34019f7be8 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/api/RulesCheck.java +++ b/server/java/metadata/src/main/java/com/metaobjects/api/RulesCheck.java @@ -98,7 +98,8 @@ private static List entities(MetaRoot root) { private static List operations(MetaRoot root) { List out = new ArrayList<>(); for (MetaData api : root.getChildren(MetaData.class, true)) { - if (!ApiConstants.TYPE_API.equals(api.getType())) continue; + // Only an api.operational's operations are commands and queries; an event, export or import is not. + if (!ApiConstants.TYPE_API.equals(api.getType()) || !ApiConstants.API_SUBTYPE_OPERATIONAL.equals(api.getSubType())) continue; for (MetaData op : api.getChildren(MetaData.class, true)) { if (ApiConstants.TYPE_OPERATION.equals(op.getType())) out.add(op); } diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/RulesTypesMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/api/RulesTypesMetaDataProvider.java index 85d207a649..fe762416cf 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/api/RulesTypesMetaDataProvider.java +++ b/server/java/metadata/src/main/java/com/metaobjects/api/RulesTypesMetaDataProvider.java @@ -35,6 +35,7 @@ public void registerTypes(MetaDataRegistry registry) { OperationalApi.registerTypes(registry); CommandOperation.registerTypes(registry); RestBinding.registerTypes(registry); + DeliveryTypes.registerTypes(registry); ActionTransition.registerTypes(registry); // The child rules that admit these types on types core owns (an api under // metadata.root, a transition under field.enum) ride in api.json / transition.json diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java index b4f8dac5c7..a3160394f7 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java @@ -256,7 +256,7 @@ private static void checkEntityLifecycles(MetaData entity, Sink sink) { sink.add(entity, ErrorCode.ERR_TRANSITION_NOT_ON_ENTITY, "object.entity \"" + entity.getShortName() + "\" has a lifecycle (transitions on " + quoteList(fields) + ") and a source, but no writable one; a transition is a guarded update of a stored row. " - + "(An entity with no source at all may carry a lifecycle: it is inert until a source is added.)"); + + "(An entity with no relational source may carry a lifecycle: it is inert until a source.rdb is added.)"); } } @@ -311,28 +311,7 @@ private static void checkOperation(MetaData op, Sink sink) { } } - // O1 — shapes. - String inputRef = Lifecycles.stringValue(op, ApiConstants.ATTR_INPUT_REF); - if (inputRef != null) { - MetaData input = Lifecycles.resolveObjectOn(op, inputRef); - if (input == null || !MetaObject.SUBTYPE_VALUE.equals(input.getSubType())) { - sink.add(op, ErrorCode.ERR_OPERATION_SHAPE, - head + " @inputRef \"" + inputRef + "\" " + objectKind(input) + "; an operation's input is an object.value."); - return; - } - } - String outputRef = Lifecycles.stringValue(op, ApiConstants.ATTR_OUTPUT_REF); - if (outputRef != null) { - MetaData output = Lifecycles.resolveObjectOn(op, outputRef); - boolean legal = output != null && Arrays.asList(MetaObject.SUBTYPE_ENTITY, MetaObject.SUBTYPE_PROJECTION, - MetaObject.SUBTYPE_VALUE).contains(output.getSubType()); - if (!legal) { - sink.add(op, ErrorCode.ERR_OPERATION_SHAPE, - head + " @outputRef \"" + outputRef + "\" " + objectKind(output) - + "; an operation returns an object.entity, object.projection or object.value."); - return; - } - } + if (!checkShapes(op, sink)) return; // O2, O3 — the target. Lifecycles.DerivedTarget derivedTarget = Lifecycles.deriveOperationTarget(op); @@ -401,6 +380,74 @@ private static void checkOperation(MetaData op, Sink sink) { } } + /** O1 — an operation's {@code @inputRef} and {@code @outputRef} shapes. False when one is wrong. */ + private static boolean checkShapes(MetaData op, Sink sink) { + String head = "operation." + op.getSubType() + " \"" + label(op) + "\""; + String inputRef = Lifecycles.stringValue(op, ApiConstants.ATTR_INPUT_REF); + if (inputRef != null) { + MetaData input = Lifecycles.resolveObjectOn(op, inputRef); + if (input == null || !MetaObject.SUBTYPE_VALUE.equals(input.getSubType())) { + sink.add(op, ErrorCode.ERR_OPERATION_SHAPE, + head + " @inputRef \"" + inputRef + "\" " + objectKind(input) + "; an operation's input is an object.value."); + return false; + } + } + String outputRef = Lifecycles.stringValue(op, ApiConstants.ATTR_OUTPUT_REF); + if (outputRef != null) { + MetaData output = Lifecycles.resolveObjectOn(op, outputRef); + boolean legal = output != null && Arrays.asList(MetaObject.SUBTYPE_ENTITY, MetaObject.SUBTYPE_PROJECTION, + MetaObject.SUBTYPE_VALUE).contains(output.getSubType()); + if (!legal) { + sink.add(op, ErrorCode.ERR_OPERATION_SHAPE, + head + " @outputRef \"" + outputRef + "\" " + objectKind(output) + + "; an operation returns an object.entity, object.projection or object.value."); + return false; + } + } + return true; + } + + /** + * The checks for one operation of an api.eventing or api.batch: its shapes (O1), the form of an + * export's {@code @availableBy} (D1) and the placeholders of each binding.file {@code @fileName} (D2). + */ + private static void checkDeliveryOperation(MetaData op, Sink sink) { + if (!checkShapes(op, sink)) return; + String frequency = Lifecycles.stringValue(op, ApiConstants.ATTR_FREQUENCY); + String availableBy = Lifecycles.stringValue(op, ApiConstants.ATTR_AVAILABLE_BY); + if (availableBy != null && frequency != null && ApiConstants.FREQUENCIES.contains(frequency) + && !ApiConstants.AVAILABLE_BY_PATTERNS.get(frequency).matcher(availableBy).matches()) { + sink.add(op, ErrorCode.ERR_BAD_ATTR_VALUE, + "operation." + op.getSubType() + " \"" + label(op) + "\" @availableBy \"" + availableBy + "\" is not a " + + frequency + " time; a " + frequency + " file's @availableBy is written like \"" + + ApiConstants.AVAILABLE_BY_EXAMPLES.get(frequency) + "\" (UTC)."); + } + // ADR-0039: own — a binding is checked on the operation that declares it. + for (MetaData b : op.getChildren(MetaData.class, false)) { + if (!ApiConstants.TYPE_BINDING.equals(b.getType()) || !ApiConstants.BINDING_SUBTYPE_FILE.equals(b.getSubType())) continue; + String fileName = Lifecycles.stringValue(b, ApiConstants.ATTR_FILE_NAME); + if (fileName == null) continue; + String bad = fileNamePlaceholderProblem(fileName); + if (bad != null) { + sink.add(b, ErrorCode.ERR_BAD_ATTR_VALUE, + "binding.file on \"" + label(b) + "\" @fileName \"" + fileName + "\" " + bad + + "; the placeholders are {" + String.join("} and {", ApiConstants.FILE_NAME_PLACEHOLDERS) + "}."); + } + } + } + + private static final Pattern FILE_NAME_PLACEHOLDER = Pattern.compile("\\{([^{}]*)\\}"); + + /** What is wrong with a {@code @fileName}'s placeholders, or null when nothing is. */ + private static String fileNamePlaceholderProblem(String fileName) { + java.util.regex.Matcher m = FILE_NAME_PLACEHOLDER.matcher(fileName); + while (m.find()) { + if (!ApiConstants.FILE_NAME_PLACEHOLDERS.contains(m.group(1))) return "holds the placeholder {" + m.group(1) + "}"; + } + String rest = FILE_NAME_PLACEHOLDER.matcher(fileName).replaceAll(""); + return rest.indexOf('{') >= 0 || rest.indexOf('}') >= 0 ? "has an unmatched brace" : null; + } + /** ADR-0066 — the rules pass. Runs after reference-bearing validation. */ static List validate(MetaRoot root) { Sink sink = new Sink(); @@ -416,6 +463,10 @@ static List validate(MetaRoot root) { for (MetaData op : api.getChildren(MetaData.class, true)) { if (ApiConstants.TYPE_OPERATION.equals(op.getType())) ops.add(op); } + if (!ApiConstants.API_SUBTYPE_OPERATIONAL.equals(api.getSubType())) { + for (MetaData op : ops) checkDeliveryOperation(op, sink); + continue; + } for (MetaData op : ops) checkOperation(op, sink); for (MetaData op : ops) { String pkg = References.effectivePackageOf(api); @@ -455,7 +506,7 @@ private static void checkPermissionNames(MetaRoot root, Sink sink) { } } for (MetaData api : root.getChildren(MetaData.class, true)) { - if (!ApiConstants.TYPE_API.equals(api.getType())) continue; + if (!ApiConstants.TYPE_API.equals(api.getType()) || !ApiConstants.API_SUBTYPE_OPERATIONAL.equals(api.getSubType())) continue; for (MetaData op : api.getChildren(MetaData.class, true)) { if (ApiConstants.TYPE_OPERATION.equals(op.getType())) { registerPermissionPoint(op, api, op.getShortName(), byName, sink); diff --git a/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsTypesMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsTypesMetaDataProvider.java index 7ff113668c..12351e01ab 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsTypesMetaDataProvider.java +++ b/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsTypesMetaDataProvider.java @@ -61,9 +61,16 @@ public void registerTypes(MetaDataRegistry registry) { str(d, "runsAs"); d.optionalChild("build", "*", "*"); }); - sub(registry, "app", "service", d -> bool(d, "public")); + sub(registry, "app", "service", d -> { + bool(d, "public"); + strArray(d, "provides"); + }); sub(registry, "app", "client", d -> str(d, "shell")); - sub(registry, "app", "job", d -> str(d, "schedule")); + sub(registry, "app", "job", d -> { + str(d, "schedule"); + strArray(d, "provides"); + str(d, "extracts"); + }); // build base(registry, "build", d -> { }); @@ -77,14 +84,18 @@ public void registerTypes(MetaDataRegistry registry) { sub(registry, "resource", "rdb", d -> d.optionalAttributeWithConstraints("schemas").ofType(StringAttribute.SUBTYPE_STRING).asArray()); sub(registry, "resource", "keyValue", d -> bool(d, "volatile")); - sub(registry, "resource", "objectStore", d -> bool(d, "publicRead")); + sub(registry, "resource", "objectStore", d -> { + bool(d, "publicRead"); + strArray(d, "carries"); + }); sub(registry, "resource", "document", d -> { }); sub(registry, "resource", "search", d -> { }); sub(registry, "resource", "queue", d -> { bool(d, "ordered"); bool(d, "deadLetter"); + strArray(d, "carries"); }); - sub(registry, "resource", "stream", d -> { }); + sub(registry, "resource", "stream", d -> strArray(d, "carries")); sub(registry, "resource", "volume", d -> { }); // role @@ -165,6 +176,10 @@ private static void str(TypeDefinitionBuilder d, String name) { d.optionalAttributeWithConstraints(name).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); } + private static void strArray(TypeDefinitionBuilder d, String name) { + d.optionalAttributeWithConstraints(name).ofType(StringAttribute.SUBTYPE_STRING).asArray(); + } + private static void required(TypeDefinitionBuilder d, String name) { d.requiredAttributeWithConstraints(name).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); } diff --git a/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java b/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java index f2bdf4a0b2..f27ac4497f 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java @@ -323,13 +323,15 @@ public void theReaderCarriesATargetTypeListAsWritten() { "relationship.base @objectRef object false ERR_INVALID_RELATIONSHIP", "relationship.composition @objectRef object false ERR_INVALID_RELATIONSHIP"); - /** The systems vocabulary's four references (ADR-0070), each written on every subtype that + /** The systems vocabulary's references (ADR-0070), each written on every subtype that * inherits it. They name a target subtype or a system boundary, which core's four do not. */ private static final List SYSTEMS_FACETS = List.of( - "app.base @runsAs", "app.client @runsAs", "app.job @runsAs", "app.service @runsAs", + "app.base @runsAs", "app.client @runsAs", "app.job @extracts", "app.job @provides", "app.job @runsAs", + "app.service @provides", "app.service @runsAs", "grant.api @api", "grant.document @resource", "grant.keyValue @resource", "grant.objectStore @resource", "grant.queue @resource", "grant.rdb @resource", "grant.search @resource", "grant.stream @resource", + "resource.objectStore @carries", "resource.queue @carries", "resource.stream @carries", "role.base @memberOf", "role.group @memberOf", "role.service @memberOf", "role.token @heldBy", "role.token @memberOf", "role.user @memberOf", "source.document @resource", "source.rdb @resource", "source.search @resource", diff --git a/server/python/src/metaobjects/documentation/explorer_app/assets/explorer-app.js b/server/python/src/metaobjects/documentation/explorer_app/assets/explorer-app.js index a2681492a9..ec81740b86 100644 --- a/server/python/src/metaobjects/documentation/explorer_app/assets/explorer-app.js +++ b/server/python/src/metaobjects/documentation/explorer_app/assets/explorer-app.js @@ -265,5 +265,5 @@ `);for(var i=0;i0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(` `)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",` `,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(``)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(` -`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'
    ';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return``}function pct(x){return`${(Math.round(x*1e4)/100).toString()}%`}function legendHtml(withUnclaimed){return`
    ${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
    `}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
    ${values.map(esc).join(" | ")}
    `:"",column:esc(str(f.attrs[FIELD_ATTR_COLUMN])??""),flagsHtml:flags.map((x)=>`${esc(x)}`).join(""),claimsHtml:claims.map((c)=>`${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
    ")}}keyRow(from,c){let fields=strs(c.attrs[IDENTITY_ATTR_FIELDS]),target=this.refHtml(from,c,IDENTITY_REFERENCE_ATTR_REFERENCES)||this.refHtml(from,c,RELATIONSHIP_ATTR_OBJECT_REF),through=str(c.attrs[RELATIONSHIP_ATTR_THROUGH]),card=str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]),shape=c.type===TYPE_RELATIONSHIP?[card,through!==void 0?`through ${localName(through)}`:void 0].filter((x)=>x!==void 0).join(", "):`(${fields.join(", ")})`;return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),inheritedHtml:c.inheritedFrom!==void 0?'inherited':"",shape:esc(shape),targetHtml:target!==""?`→ ${target}`:""}}reportingRow(from,c){let a=c.attrs,parts=[],agg=str(a[REPORTING_ATTR_AGG]),of=this.refHtml(from,c,REPORTING_ATTR_OF,localName);if(agg!==void 0)parts.push(`${esc(agg)}(${of})`);else if(of!=="")parts.push(`of ${of}`);let num=str(a[REPORTING_ATTR_NUMERATOR]),den=str(a[REPORTING_ATTR_DENOMINATOR]);if(num!==void 0&&den!==void 0)parts.push(`${esc(num)} ÷ ${esc(den)}`);let via=str(a[REPORTING_ATTR_VIA]);if(via!==void 0)parts.push(`via ${esc(localName(via))}`);let grains=strs(a[REPORTING_ATTR_GRAINS]);if(grains.length>0)parts.push(`grains ${grains.map((g)=>`${esc(g)}`).join(" ")}`);let seg=str(a[REPORTING_ATTR_SEGMENT]);if(seg!==void 0)parts.push(`segment ${esc(seg)}`);if(a[REPORTING_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`);if(a[REPORTING_ATTR_DEFAULT]!==void 0)parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`);return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),definitionHtml:parts.join(" · ")}}layoutRow(l){let parts=[],cols=strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]);if(cols.length>0)parts.push(`columns ${cols.map((c)=>`${esc(c)}`).join(", ")}`);let sort=str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]);if(sort!==void 0)parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER])!==void 0?` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}`:""}`);if(typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]==="number")parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`);return{kind:esc(`${l.type}.${l.subType}`),name:esc(l.name),detailHtml:parts.join(", ")}}projectionBlock(from,n){let ix=this.ix,rows=[],bases=new Set;for(let f of ix.fields(n.id)){if(f.extends!==void 0)bases.add(ix.ownerOf(f.extends));for(let o of ix.children(f.id).filter((c)=>c.type===TYPE_ORIGIN)){let def=this.originDefinition(from,o);for(let src of this.refLinks(o,ORIGIN_PASSTHROUGH_ATTR_FROM))bases.add(ix.ownerOf(src.id));rows.push({field:esc(f.name),origin:esc(`origin.${o.subType}`),definitionHtml:def})}}return{basesHtml:[...bases].filter((b)=>b!==n.id).sort(byCodeUnit2).map((b)=>this.link(from,b)).join(", "),origins:rows,hasOrigins:rows.length>0}}originDefinition(from,o){let a=o.attrs,ref=(name)=>this.attrValues(o,name).map((v)=>v.link!==null&&!v.link.unresolved?this.link(from,v.link.id,localName(v.text)):`${esc(localName(v.text))}`).join(", "),parts=[],agg=str(a[ORIGIN_AGGREGATE_ATTR_AGG]);if(agg!==void 0)parts.push(`${esc(agg)}(${ref(ORIGIN_AGGREGATE_ATTR_OF)})`);else if(a[ORIGIN_AGGREGATE_ATTR_OF]!==void 0)parts.push(`of ${ref(ORIGIN_AGGREGATE_ATTR_OF)}`);if(a[ORIGIN_PASSTHROUGH_ATTR_FROM]!==void 0)parts.push(`from ${ref(ORIGIN_PASSTHROUGH_ATTR_FROM)}`);if(a[ORIGIN_AGGREGATE_ATTR_VIA]!==void 0)parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`);if(a[ORIGIN_COMPUTED_ATTR_EXPR]!==void 0)parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`);if(a[ORIGIN_AGGREGATE_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`);return parts.join(" · ")}reportBlock(from,n){let a=n.attrs,fromId=this.refLinks(n,OBJECT_REPORT_ATTR_FROM)[0]?.id??str(a[OBJECT_REPORT_ATTR_FROM]),resolve2=(name,kindType)=>{let hit=[fromId!==void 0?`${fromId}.${name}`:void 0,`${n.package===""?"":`${n.package}::`}${name}`].filter((x)=>x!==void 0).find((c)=>this.ix.byId.get(c)?.type===kindType||this.ix.byId.has(c)&&name.includes("."));return hit!==void 0?this.link(from,hit,name):`${esc(name)}`},spine=str(a[OBJECT_REPORT_ATTR_SPINE]);return{fromHtml:this.refHtml(from,n,OBJECT_REPORT_ATTR_FROM),spineHtml:spine!==void 0?`${esc(spine)}`:"",dimensionsHtml:strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d)=>resolve2(d,TYPE_DIMENSION)).join(", "),measuresHtml:strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m)=>resolve2(m,TYPE_MEASURE)).join(", "),segmentHtml:strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s)=>resolve2(s,TYPE_SEGMENT)).join(", "),filterHtml:a[OBJECT_REPORT_ATTR_FILTER]!==void 0?`${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}`:""}}generatedGroups(id){let groups=new Map;for(let f of this.ix.generated(id))groups.set(f.generatedBy,[...groups.get(f.generatedBy)??[],f.path]);return[...groups.keys()].sort(byCodeUnit2).map((g)=>({generator:esc(g),files:(groups.get(g)??[]).map((p)=>esc(p))}))}node(n){let ix=this.ix,from=this.objectPage(n),kindLabel=`${n.type}.${n.subType}`,whyRows=this.whyRows(from,n),attrs=this.attrRows(from,n),referrers=[...(ix.top(n.id)?.referencedBy??[]).map((e)=>e.from.id),...ix.claims(n.id).map((c)=>this.topOf(c.req).node.id)],refBy=[...new Set(referrers.filter((id)=>id!==n.id))].sort(byCodeUnit2).map((id)=>this.link(from,id));return{id:esc(n.id),name:esc(n.name),kindLabel:esc(kindLabel),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › ${esc(kindLabel)}`,isAbstract:n.abstract===!0,description:this.description(n),extendsHtml:n.extends!==void 0?this.link(from,n.extends):"",attrs,hasAttrs:attrs.length>0,members:ix.children(n.id).map((c)=>({anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),nameHtml:ix.reqById.has(c.id)?this.link(from,c.id):esc(c.name===""?`#${c.order}`:c.name),attrsHtml:this.attrRows(from,c).map((a)=>`@${a.name} ${a.valueHtml}`).join("
    "),below:ix.children(c.id).length})),hasMembers:ix.children(n.id).length>0,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(from,n){return n.view.attrs.map((a)=>{let links=a.values.filter((v)=>v.link!==null&&!v.link.unresolved);return{name:esc(a.name),valueHtml:links.length>0&&links.length===a.values.length?links.map((v)=>this.link(from,v.link.id)).join(", "):`${esc(fmt(a.value))}`}})}prompt(n,text){let ix=this.ix,from=this.objectPage(n),payloadId=this.refLinks(n,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id,replyId=this.refLinks(n,TEMPLATE_ATTR_RESPONSE_REF)[0]?.id,vars=text!==void 0?templateVariables(text):void 0,payload=payloadId!==void 0?ix.byId.get(payloadId):void 0,reply=replyId!==void 0?ix.byId.get(replyId):void 0,payloadRows=payload!==void 0?ix.fields(payload.id).map((f)=>({name:esc(f.name),requiredHtml:f.attrs[FIELD_ATTR_REQUIRED]===!0?'required':"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)!==""?` → ${this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)}`:"",usedHtml:vars===void 0?'text not read':vars.has(f.name)?"yes":'no'})):[],replyRows=reply!==void 0?ix.fields(reply.id).map((f)=>({name:esc(f.name),type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),valuesHtml:f.subType===FIELD_SUBTYPE_ENUM?`
    ${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
    `:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(` +`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var FREQUENCY_HOURLY="hourly",FREQUENCY_DAILY="daily",FREQUENCY_WEEKLY="weekly",FREQUENCY_MONTHLY="monthly";var AVAILABLE_BY_PATTERNS={[FREQUENCY_HOURLY]:/^:[0-5][0-9]$/,[FREQUENCY_DAILY]:/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/,[FREQUENCY_WEEKLY]:/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/,[FREQUENCY_MONTHLY]:/^(?:[1-9]|1[0-9]|2[0-8]) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/},AVAILABLE_BY_EXAMPLES={[FREQUENCY_HOURLY]:":15",[FREQUENCY_DAILY]:"03:00",[FREQUENCY_WEEKLY]:"Mon 06:00",[FREQUENCY_MONTHLY]:"1 06:00"};var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'
    ';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return``}function pct(x){return`${(Math.round(x*1e4)/100).toString()}%`}function legendHtml(withUnclaimed){return`
    ${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
    `}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
    ${values.map(esc).join(" | ")}
    `:"",column:esc(str(f.attrs[FIELD_ATTR_COLUMN])??""),flagsHtml:flags.map((x)=>`${esc(x)}`).join(""),claimsHtml:claims.map((c)=>`${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
    ")}}keyRow(from,c){let fields=strs(c.attrs[IDENTITY_ATTR_FIELDS]),target=this.refHtml(from,c,IDENTITY_REFERENCE_ATTR_REFERENCES)||this.refHtml(from,c,RELATIONSHIP_ATTR_OBJECT_REF),through=str(c.attrs[RELATIONSHIP_ATTR_THROUGH]),card=str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]),shape=c.type===TYPE_RELATIONSHIP?[card,through!==void 0?`through ${localName(through)}`:void 0].filter((x)=>x!==void 0).join(", "):`(${fields.join(", ")})`;return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),inheritedHtml:c.inheritedFrom!==void 0?'inherited':"",shape:esc(shape),targetHtml:target!==""?`→ ${target}`:""}}reportingRow(from,c){let a=c.attrs,parts=[],agg=str(a[REPORTING_ATTR_AGG]),of=this.refHtml(from,c,REPORTING_ATTR_OF,localName);if(agg!==void 0)parts.push(`${esc(agg)}(${of})`);else if(of!=="")parts.push(`of ${of}`);let num=str(a[REPORTING_ATTR_NUMERATOR]),den=str(a[REPORTING_ATTR_DENOMINATOR]);if(num!==void 0&&den!==void 0)parts.push(`${esc(num)} ÷ ${esc(den)}`);let via=str(a[REPORTING_ATTR_VIA]);if(via!==void 0)parts.push(`via ${esc(localName(via))}`);let grains=strs(a[REPORTING_ATTR_GRAINS]);if(grains.length>0)parts.push(`grains ${grains.map((g)=>`${esc(g)}`).join(" ")}`);let seg=str(a[REPORTING_ATTR_SEGMENT]);if(seg!==void 0)parts.push(`segment ${esc(seg)}`);if(a[REPORTING_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`);if(a[REPORTING_ATTR_DEFAULT]!==void 0)parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`);return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),definitionHtml:parts.join(" · ")}}layoutRow(l){let parts=[],cols=strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]);if(cols.length>0)parts.push(`columns ${cols.map((c)=>`${esc(c)}`).join(", ")}`);let sort=str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]);if(sort!==void 0)parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER])!==void 0?` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}`:""}`);if(typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]==="number")parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`);return{kind:esc(`${l.type}.${l.subType}`),name:esc(l.name),detailHtml:parts.join(", ")}}projectionBlock(from,n){let ix=this.ix,rows=[],bases=new Set;for(let f of ix.fields(n.id)){if(f.extends!==void 0)bases.add(ix.ownerOf(f.extends));for(let o of ix.children(f.id).filter((c)=>c.type===TYPE_ORIGIN)){let def=this.originDefinition(from,o);for(let src of this.refLinks(o,ORIGIN_PASSTHROUGH_ATTR_FROM))bases.add(ix.ownerOf(src.id));rows.push({field:esc(f.name),origin:esc(`origin.${o.subType}`),definitionHtml:def})}}return{basesHtml:[...bases].filter((b)=>b!==n.id).sort(byCodeUnit2).map((b)=>this.link(from,b)).join(", "),origins:rows,hasOrigins:rows.length>0}}originDefinition(from,o){let a=o.attrs,ref=(name)=>this.attrValues(o,name).map((v)=>v.link!==null&&!v.link.unresolved?this.link(from,v.link.id,localName(v.text)):`${esc(localName(v.text))}`).join(", "),parts=[],agg=str(a[ORIGIN_AGGREGATE_ATTR_AGG]);if(agg!==void 0)parts.push(`${esc(agg)}(${ref(ORIGIN_AGGREGATE_ATTR_OF)})`);else if(a[ORIGIN_AGGREGATE_ATTR_OF]!==void 0)parts.push(`of ${ref(ORIGIN_AGGREGATE_ATTR_OF)}`);if(a[ORIGIN_PASSTHROUGH_ATTR_FROM]!==void 0)parts.push(`from ${ref(ORIGIN_PASSTHROUGH_ATTR_FROM)}`);if(a[ORIGIN_AGGREGATE_ATTR_VIA]!==void 0)parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`);if(a[ORIGIN_COMPUTED_ATTR_EXPR]!==void 0)parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`);if(a[ORIGIN_AGGREGATE_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`);return parts.join(" · ")}reportBlock(from,n){let a=n.attrs,fromId=this.refLinks(n,OBJECT_REPORT_ATTR_FROM)[0]?.id??str(a[OBJECT_REPORT_ATTR_FROM]),resolve2=(name,kindType)=>{let hit=[fromId!==void 0?`${fromId}.${name}`:void 0,`${n.package===""?"":`${n.package}::`}${name}`].filter((x)=>x!==void 0).find((c)=>this.ix.byId.get(c)?.type===kindType||this.ix.byId.has(c)&&name.includes("."));return hit!==void 0?this.link(from,hit,name):`${esc(name)}`},spine=str(a[OBJECT_REPORT_ATTR_SPINE]);return{fromHtml:this.refHtml(from,n,OBJECT_REPORT_ATTR_FROM),spineHtml:spine!==void 0?`${esc(spine)}`:"",dimensionsHtml:strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d)=>resolve2(d,TYPE_DIMENSION)).join(", "),measuresHtml:strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m)=>resolve2(m,TYPE_MEASURE)).join(", "),segmentHtml:strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s)=>resolve2(s,TYPE_SEGMENT)).join(", "),filterHtml:a[OBJECT_REPORT_ATTR_FILTER]!==void 0?`${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}`:""}}generatedGroups(id){let groups=new Map;for(let f of this.ix.generated(id))groups.set(f.generatedBy,[...groups.get(f.generatedBy)??[],f.path]);return[...groups.keys()].sort(byCodeUnit2).map((g)=>({generator:esc(g),files:(groups.get(g)??[]).map((p)=>esc(p))}))}node(n){let ix=this.ix,from=this.objectPage(n),kindLabel=`${n.type}.${n.subType}`,whyRows=this.whyRows(from,n),attrs=this.attrRows(from,n),referrers=[...(ix.top(n.id)?.referencedBy??[]).map((e)=>e.from.id),...ix.claims(n.id).map((c)=>this.topOf(c.req).node.id)],refBy=[...new Set(referrers.filter((id)=>id!==n.id))].sort(byCodeUnit2).map((id)=>this.link(from,id));return{id:esc(n.id),name:esc(n.name),kindLabel:esc(kindLabel),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › ${esc(kindLabel)}`,isAbstract:n.abstract===!0,description:this.description(n),extendsHtml:n.extends!==void 0?this.link(from,n.extends):"",attrs,hasAttrs:attrs.length>0,members:ix.children(n.id).map((c)=>({anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),nameHtml:ix.reqById.has(c.id)?this.link(from,c.id):esc(c.name===""?`#${c.order}`:c.name),attrsHtml:this.attrRows(from,c).map((a)=>`@${a.name} ${a.valueHtml}`).join("
    "),below:ix.children(c.id).length})),hasMembers:ix.children(n.id).length>0,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(from,n){return n.view.attrs.map((a)=>{let links=a.values.filter((v)=>v.link!==null&&!v.link.unresolved);return{name:esc(a.name),valueHtml:links.length>0&&links.length===a.values.length?links.map((v)=>this.link(from,v.link.id)).join(", "):`${esc(fmt(a.value))}`}})}prompt(n,text){let ix=this.ix,from=this.objectPage(n),payloadId=this.refLinks(n,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id,replyId=this.refLinks(n,TEMPLATE_ATTR_RESPONSE_REF)[0]?.id,vars=text!==void 0?templateVariables(text):void 0,payload=payloadId!==void 0?ix.byId.get(payloadId):void 0,reply=replyId!==void 0?ix.byId.get(replyId):void 0,payloadRows=payload!==void 0?ix.fields(payload.id).map((f)=>({name:esc(f.name),requiredHtml:f.attrs[FIELD_ATTR_REQUIRED]===!0?'required':"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)!==""?` → ${this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)}`:"",usedHtml:vars===void 0?'text not read':vars.has(f.name)?"yes":'no'})):[],replyRows=reply!==void 0?ix.fields(reply.id).map((f)=>({name:esc(f.name),type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),valuesHtml:f.subType===FIELD_SUBTYPE_ENUM?`
    ${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
    `:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(` `).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
      ${tops.map((r)=>this.treeNode(page,r)).join("")}
    `:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
  • ${`
    ${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}${dispositionPill(r)}${verdictBadge(r)}${bar}${links.join("")}
    ${esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??"")}
    `}${r.children.length>0?`
      ${r.children.map((c)=>this.treeNode(from,c)).join("")}
    `:""}
  • `}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`${cols.map((o)=>`
    ${this.link(from,o.id)}
    `).join("")}`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLink(from,top)}${cols.map(()=>'').join("")}`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`${levelBadge(r)}${esc(label)}${cols.map((o)=>tg.has(o.id)?`${statusGlyph(r.status)}`:'').join("")}`)}}return{tableHtml:rows.length>0?`${head}${rows.join("")}
    `:"",hasRows:rows.length>0,hasRequirements:ix.hasRequirements()}}trace(){let starts=this.ix.requirements.filter((r)=>r.level!==void 0&&r.level<=REQUIREMENT_LEVEL_SERVICE),fallback=starts.length===0?this.ix.topRequirements:[];return{options:[...starts,...fallback].map((r)=>({value:esc(r.node.id),label:esc(`${" ".repeat(Math.max(0,(r.level??1)-1))}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)}`)})),hasStarts:starts.length+fallback.length>0,hasUsage:!1}}gaps(){let ix=this.ix,from=PAGE_GAPS,cards=[],card=(title,count,source,why,bodyHtml)=>{cards.push({title:esc(title),count:esc(String(count)),source:esc(source),isGate:source==="meta verify",whyHtml:why,bodyHtml})};if(ix.view.sources.requirements){let findingsOf=(gate2)=>[...ix.requirements.flatMap((req)=>req.req.diagnostics.filter((d)=>d.source===GATE_SOURCE===gate2).map((d)=>({req,d}))),...ix.view.advisories.filter((d)=>d.path===""&&d.source===GATE_SOURCE===gate2).map((d)=>({d}))],table=(rows,chip)=>rows.length===0?'
    None.
    ':`${rows.map(({req,d})=>``).join("")}
    ${esc(d.code)}${req!==void 0?this.reqLink(from,req):""}
    ${esc(d.message)}
    `,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
    None.
    ');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
    None.
    ')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
    Not scanned.
    ');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
    No prompt text was read.
    ':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
    None.
    ':`
      ${items.map((i)=>`
    • ${i}
    • `).join("")}
    `}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found

    No such page

    ${escapeHtml2(r.path)} is not a page of this model.

    Overview

    `,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="

    No model yet

    The explorer is waiting for the running application's docs view.

    ";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="

    No model

    The source parameter is not a URL.

    ",paintLive();return}follow(source);return}if(!build())document.body.innerHTML="

    No model

    explorer-model.js did not load. Run meta gen to write it beside this page.

    ";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})(); diff --git a/server/python/src/metaobjects/loader/validate_rules.py b/server/python/src/metaobjects/loader/validate_rules.py index ead5659bd2..42010ecf98 100644 --- a/server/python/src/metaobjects/loader/validate_rules.py +++ b/server/python/src/metaobjects/loader/validate_rules.py @@ -17,8 +17,8 @@ Rules: L1 ERR_TRANSITION_NOT_ON_ENTITY a transition under an enum field not declared on an object.entity L2 ERR_TRANSITION_NOT_ON_ENTITY a concrete entity with a lifecycle and a source, none of them writable - (on the entity). An entity with no source at all is inert: its - lifecycle loads and derives nothing (lifecycle_is_live). + (on the entity). An entity with no relational source (none, or + only source.document / source.search) is inert: its lifecycle loads and derives nothing (lifecycle_is_live). L3 ERR_LIFECYCLE_NO_INITIAL an enum field declaring transitions has no @default L4 ERR_TRANSITION_UNKNOWN_STATE a @from or @to value is not one of the enum's @values L5 ERR_TRANSITION_NAME_COLLISION a transition named create/get/list/update/delete, in any case @@ -55,9 +55,18 @@ from ..errors import ErrorCode, MetaError from ..meta.core.api.api_constants import ( + API_SUBTYPE_OPERATIONAL, + AVAILABLE_BY_EXAMPLES, + AVAILABLE_BY_PATTERNS, + BINDING_ATTR_FILE_NAME, BINDING_ATTR_METHOD, BINDING_ATTR_PATH, + BINDING_SUBTYPE_FILE, BINDING_SUBTYPE_REST, + FILE_NAME_PLACEHOLDERS, + FREQUENCIES, + OPERATION_ATTR_AVAILABLE_BY, + OPERATION_ATTR_FREQUENCY, BUSINESS_ERROR_CODE_PATTERN, OPERATION_ATTR_ERRORS, OPERATION_ATTR_INPUT_REF, @@ -324,7 +333,7 @@ def _check_entity_lifecycles(entity: MetaData, sink: _Sink) -> None: ErrorCode.ERR_TRANSITION_NOT_ON_ENTITY, f'object.entity "{entity.name}" has a lifecycle (transitions on {_quote_list(owners)}) and a ' "source, but no writable one; a transition is a guarded update of a stored row. (An entity " - "with no source at all may carry a lifecycle: it is inert until a source is added.)", + "with no relational source may carry a lifecycle: it is inert until a source.rdb is added.)", ) @@ -359,34 +368,8 @@ def _check_operation(op: MetaData, sink: _Sink) -> None: ) sink.add(op, ErrorCode.ERR_BAD_ATTR_VALUE, f'operation.{op.sub_type} "{_label(op)}" @errors: {why}.') - # O1 — shapes. - input_ref = op.get_meta_attr(OPERATION_ATTR_INPUT_REF) - if isinstance(input_ref, str): - inp = resolve_object_on(op, input_ref) - if inp is None or inp.sub_type != OBJECT_SUBTYPE_VALUE: - what = "names no object" if inp is None else f"is an object.{inp.sub_type}" - sink.add( - op, - ErrorCode.ERR_OPERATION_SHAPE, - f'operation.{op.sub_type} "{_label(op)}" @inputRef "{input_ref}" {what}; ' - "an operation's input is an object.value.", - ) - return - output_ref = op.get_meta_attr(OPERATION_ATTR_OUTPUT_REF) - if isinstance(output_ref, str): - out = resolve_object_on(op, output_ref) - legal = out is not None and out.sub_type in ( - OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_VALUE, - ) - if not legal: - what = "names no object" if out is None else f"is an object.{out.sub_type}" - sink.add( - op, - ErrorCode.ERR_OPERATION_SHAPE, - f'operation.{op.sub_type} "{_label(op)}" @outputRef "{output_ref}" {what}; ' - "an operation returns an object.entity, object.projection or object.value.", - ) - return + if not _check_shapes(op, sink): + return # O2, O3 — the target. derived_target = derive_operation_target(op) @@ -462,6 +445,84 @@ def _check_operation(op: MetaData, sink: _Sink) -> None: ) +def _check_shapes(op: MetaData, sink: _Sink) -> bool: + """O1 — an operation's @inputRef and @outputRef shapes. False when one is wrong.""" + input_ref = op.get_meta_attr(OPERATION_ATTR_INPUT_REF) + if isinstance(input_ref, str): + inp = resolve_object_on(op, input_ref) + if inp is None or inp.sub_type != OBJECT_SUBTYPE_VALUE: + what = "names no object" if inp is None else f"is an object.{inp.sub_type}" + sink.add( + op, + ErrorCode.ERR_OPERATION_SHAPE, + f'operation.{op.sub_type} "{_label(op)}" @inputRef "{input_ref}" {what}; ' + "an operation's input is an object.value.", + ) + return False + output_ref = op.get_meta_attr(OPERATION_ATTR_OUTPUT_REF) + if isinstance(output_ref, str): + out = resolve_object_on(op, output_ref) + legal = out is not None and out.sub_type in ( + OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_VALUE, + ) + if not legal: + what = "names no object" if out is None else f"is an object.{out.sub_type}" + sink.add( + op, + ErrorCode.ERR_OPERATION_SHAPE, + f'operation.{op.sub_type} "{_label(op)}" @outputRef "{output_ref}" {what}; ' + "an operation returns an object.entity, object.projection or object.value.", + ) + return False + return True + + +def _file_name_placeholder_problem(file_name: str) -> str | None: + """What is wrong with a @fileName's placeholders, or None when nothing is.""" + for m in re.finditer(r"\{([^{}]*)\}", file_name): + if m.group(1) not in FILE_NAME_PLACEHOLDERS: + return f"holds the placeholder {{{m.group(1)}}}" + if re.search(r"[{}]", re.sub(r"\{[^{}]*\}", "", file_name)): + return "has an unmatched brace" + return None + + +def _check_delivery_operation(op: MetaData, sink: _Sink) -> None: + """O1, D1 and D2 for one operation of an api.eventing or api.batch: its shapes, the form of an + export's @availableBy and the placeholders of each binding.file @fileName.""" + if not _check_shapes(op, sink): + return + frequency = op.get_meta_attr(OPERATION_ATTR_FREQUENCY) + available_by = op.get_meta_attr(OPERATION_ATTR_AVAILABLE_BY) + if ( + isinstance(available_by, str) + and isinstance(frequency, str) + and frequency in FREQUENCIES + and AVAILABLE_BY_PATTERNS[frequency].fullmatch(available_by) is None + ): + sink.add( + op, + ErrorCode.ERR_BAD_ATTR_VALUE, + f'operation.{op.sub_type} "{_label(op)}" @availableBy "{available_by}" is not a {frequency} time; ' + f'a {frequency} file\'s @availableBy is written like "{AVAILABLE_BY_EXAMPLES[frequency]}" (UTC).', + ) + # ADR-0039 sanctioned own: a binding is checked on the operation that declares it. + for b in op.own_children(): + if b.type != TYPE_BINDING or b.sub_type != BINDING_SUBTYPE_FILE: + continue + file_name = b.get_meta_attr(BINDING_ATTR_FILE_NAME) + if not isinstance(file_name, str): + continue + bad = _file_name_placeholder_problem(file_name) + if bad is not None: + sink.add( + b, + ErrorCode.ERR_BAD_ATTR_VALUE, + f'binding.file on "{_label(b)}" @fileName "{file_name}" {bad}; ' + f"the placeholders are {{{'} and {'.join(FILE_NAME_PLACEHOLDERS)}}}.", + ) + + def validate_rules(root: MetaData, errors: list[MetaError]) -> None: """ADR-0066 — the rules pass. Runs after reference-bearing validation, before freeze.""" sink = _Sink(errors) @@ -476,6 +537,10 @@ def validate_rules(root: MetaData, errors: list[MetaError]) -> None: if api.type != TYPE_API: continue ops = [c for c in api.children() if c.type == TYPE_OPERATION] + if api.sub_type != API_SUBTYPE_OPERATIONAL: + for op in ops: + _check_delivery_operation(op, sink) + continue for op in ops: _check_operation(op, sink) for op in ops: @@ -556,7 +621,7 @@ def register(node: MetaData, owner: MetaData, path: str) -> None: for t in entity_transitions(entity): register(t, entity, f"{entity.name}.{t.name}") for api in root.children(): - if api.type != TYPE_API: + if api.type != TYPE_API or api.sub_type != API_SUBTYPE_OPERATIONAL: continue for op in api.children(): if op.type == TYPE_OPERATION: diff --git a/server/python/src/metaobjects/meta/core/api/api_constants.py b/server/python/src/metaobjects/meta/core/api/api_constants.py index 8e24c45146..a07ea3fef0 100644 --- a/server/python/src/metaobjects/meta/core/api/api_constants.py +++ b/server/python/src/metaobjects/meta/core/api/api_constants.py @@ -6,15 +6,35 @@ # A request/response surface whose children are operations. The axis is the interaction # model, never the protocol (ADR-0030). API_SUBTYPE_OPERATIONAL = "operational" -API_SUBTYPES = (API_SUBTYPE_OPERATIONAL,) +# Events the provider publishes; children are operation.event. +API_SUBTYPE_EVENTING = "eventing" +# Datasets delivered as files on a schedule; children are operation.export / .import. +API_SUBTYPE_BATCH = "batch" +API_SUBTYPES = (API_SUBTYPE_OPERATIONAL, API_SUBTYPE_EVENTING, API_SUBTYPE_BATCH) OPERATION_SUBTYPE_COMMAND = "command" OPERATION_SUBTYPE_QUERY = "query" -OPERATION_SUBTYPES = (OPERATION_SUBTYPE_COMMAND, OPERATION_SUBTYPE_QUERY) +# Something that happened; the payload is its @outputRef. +OPERATION_SUBTYPE_EVENT = "event" +# A file the provider publishes on a schedule; rows are its @outputRef. +OPERATION_SUBTYPE_EXPORT = "export" +# A file the provider accepts on a schedule; rows are its @inputRef. +OPERATION_SUBTYPE_IMPORT = "import" +OPERATION_SUBTYPES = ( + OPERATION_SUBTYPE_COMMAND, + OPERATION_SUBTYPE_QUERY, + OPERATION_SUBTYPE_EVENT, + OPERATION_SUBTYPE_EXPORT, + OPERATION_SUBTYPE_IMPORT, +) # The HTTP binding of an operation (overrides the derived method and path). BINDING_SUBTYPE_REST = "rest" -BINDING_SUBTYPES = (BINDING_SUBTYPE_REST,) +# How an event travels (optionally pinning the wire protocol). +BINDING_SUBTYPE_MESSAGING = "messaging" +# How an export's or import's file is delivered. +BINDING_SUBTYPE_FILE = "file" +BINDING_SUBTYPES = (BINDING_SUBTYPE_REST, BINDING_SUBTYPE_MESSAGING, BINDING_SUBTYPE_FILE) # Attrs on operation.* (@permission / @public are on transition.* too). OPERATION_ATTR_INPUT_REF = "inputRef" @@ -31,6 +51,51 @@ BINDING_ATTR_PATH = "path" HTTP_METHODS = ("GET", "POST", "PUT", "PATCH", "DELETE") +# Attrs on operation.event / .export / .import. +OPERATION_ATTR_KEY = "key" +OPERATION_ATTR_FREQUENCY = "frequency" +OPERATION_ATTR_AVAILABLE_BY = "availableBy" +FREQUENCY_HOURLY = "hourly" +FREQUENCY_DAILY = "daily" +FREQUENCY_WEEKLY = "weekly" +FREQUENCY_MONTHLY = "monthly" +FREQUENCIES = (FREQUENCY_HOURLY, FREQUENCY_DAILY, FREQUENCY_WEEKLY, FREQUENCY_MONTHLY) +# The form of @availableBy for each @frequency: hourly :MM, daily HH:MM, weekly Ddd HH:MM, +# monthly D HH:MM with the day 1 to 28 (every month has it). Matched with ``fullmatch``. +AVAILABLE_BY_PATTERNS = { + FREQUENCY_HOURLY: re.compile(r":[0-5][0-9]"), + FREQUENCY_DAILY: re.compile(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]"), + FREQUENCY_WEEKLY: re.compile(r"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:[01][0-9]|2[0-3]):[0-5][0-9]"), + FREQUENCY_MONTHLY: re.compile(r"(?:[1-9]|1[0-9]|2[0-8]) (?:[01][0-9]|2[0-3]):[0-5][0-9]"), +} +# An example of each form, for messages. +AVAILABLE_BY_EXAMPLES = { + FREQUENCY_HOURLY: ":15", + FREQUENCY_DAILY: "03:00", + FREQUENCY_WEEKLY: "Mon 06:00", + FREQUENCY_MONTHLY: "1 06:00", +} + +# Attrs on binding.messaging / binding.file. +BINDING_ATTR_PROTOCOL = "protocol" +BINDING_ATTR_TRANSPORT = "transport" +BINDING_ATTR_FILE_NAME = "fileName" +BINDING_ATTR_FORMAT = "format" +BINDING_ATTR_COMPRESSION = "compression" +BINDING_ATTR_COMPLETION = "completion" +BINDING_ATTR_ENCRYPTION = "encryption" +MESSAGING_PROTOCOLS = ("kafka", "amqp", "mqtt", "sqs") +FILE_TRANSPORTS = ("sftp", "objectStore") +FILE_FORMATS = ("csv", "jsonLines", "parquet") +FILE_COMPRESSIONS = ("none", "gzip") +FILE_COMPLETIONS = ("rename", "marker", "none") +FILE_ENCRYPTIONS = ("none", "pgp") +# The placeholders a binding.file @fileName may hold: the UTC start of the run, as +# YYYY-MM-DD and YYYYMMDDTHHMMSSZ. +FILE_NAME_PLACEHOLDERS = ("date", "timestamp") +# The suffix of the marker object ``completion: marker`` puts beside a finished file. +COMPLETION_MARKER_SUFFIX = ".done" + # Names a declared operation or a transition may not take: they are the derived CRUD verbs # of the same service (ERR_TRANSITION_NAME_COLLISION). RESERVED_OPERATION_NAMES = ("create", "get", "list", "update", "delete") diff --git a/server/python/src/metaobjects/meta/core/rules/rules_provider.py b/server/python/src/metaobjects/meta/core/rules/rules_provider.py index a7f2a11857..957f91784a 100644 --- a/server/python/src/metaobjects/meta/core/rules/rules_provider.py +++ b/server/python/src/metaobjects/meta/core/rules/rules_provider.py @@ -30,11 +30,35 @@ ) from ...provider_extends import register_extends from ..api.api_constants import ( + API_SUBTYPE_BATCH, + API_SUBTYPE_EVENTING, API_SUBTYPE_OPERATIONAL, + BINDING_ATTR_COMPLETION, + BINDING_ATTR_COMPRESSION, + BINDING_ATTR_ENCRYPTION, + BINDING_ATTR_FILE_NAME, + BINDING_ATTR_FORMAT, BINDING_ATTR_METHOD, BINDING_ATTR_PATH, + BINDING_ATTR_PROTOCOL, + BINDING_ATTR_TRANSPORT, + BINDING_SUBTYPE_FILE, + BINDING_SUBTYPE_MESSAGING, BINDING_SUBTYPE_REST, + FILE_COMPLETIONS, + FILE_COMPRESSIONS, + FILE_ENCRYPTIONS, + FILE_FORMATS, + FILE_TRANSPORTS, + FREQUENCIES, HTTP_METHODS, + MESSAGING_PROTOCOLS, + OPERATION_ATTR_AVAILABLE_BY, + OPERATION_ATTR_FREQUENCY, + OPERATION_ATTR_KEY, + OPERATION_SUBTYPE_EVENT, + OPERATION_SUBTYPE_EXPORT, + OPERATION_SUBTYPE_IMPORT, OPERATION_ATTR_ERRORS, OPERATION_ATTR_INPUT_REF, OPERATION_ATTR_MANY, @@ -73,8 +97,6 @@ type=TYPE_OPERATION, sub_type=SUBTYPE_BASE, factory=MetaOperation, - attrs=list(_OPERATION_COMMON_ATTRS), - child_rules=[ChildRule(TYPE_BINDING, "*")], ) ) rules_provider.add(TypeDefinition(type=TYPE_BINDING, sub_type=SUBTYPE_BASE, factory=MetaBinding)) @@ -94,7 +116,29 @@ type=TYPE_API, sub_type=API_SUBTYPE_OPERATIONAL, factory=MetaApi, - child_rules=[ChildRule(TYPE_OPERATION, "*")], + child_rules=[ + ChildRule(TYPE_OPERATION, OPERATION_SUBTYPE_COMMAND), + ChildRule(TYPE_OPERATION, OPERATION_SUBTYPE_QUERY), + ], + ) +) +rules_provider.add( + TypeDefinition( + type=TYPE_API, + sub_type=API_SUBTYPE_EVENTING, + factory=MetaApi, + child_rules=[ChildRule(TYPE_OPERATION, OPERATION_SUBTYPE_EVENT)], + ) +) +rules_provider.add( + TypeDefinition( + type=TYPE_API, + sub_type=API_SUBTYPE_BATCH, + factory=MetaApi, + child_rules=[ + ChildRule(TYPE_OPERATION, OPERATION_SUBTYPE_EXPORT), + ChildRule(TYPE_OPERATION, OPERATION_SUBTYPE_IMPORT), + ], ) ) rules_provider.add( @@ -107,7 +151,7 @@ AttrSchema(name=OPERATION_ATTR_TRANSITIONS, value_type=ATTR_SUBTYPE_STRING, required=False, is_array=True), AttrSchema(name=OPERATION_ATTR_ERRORS, value_type=ATTR_SUBTYPE_STRING, required=False, is_array=True), ], - child_rules=[ChildRule(TYPE_BINDING, "*")], + child_rules=[ChildRule(TYPE_BINDING, BINDING_SUBTYPE_REST)], ) ) rules_provider.add( @@ -119,7 +163,98 @@ *_OPERATION_COMMON_ATTRS, AttrSchema(name=OPERATION_ATTR_MANY, value_type=ATTR_SUBTYPE_BOOLEAN, required=False), ], - child_rules=[ChildRule(TYPE_BINDING, "*")], + child_rules=[ChildRule(TYPE_BINDING, BINDING_SUBTYPE_REST)], + ) +) +rules_provider.add( + TypeDefinition( + type=TYPE_OPERATION, + sub_type=OPERATION_SUBTYPE_EVENT, + factory=MetaOperation, + attrs=[ + AttrSchema(name=OPERATION_ATTR_OUTPUT_REF, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema(name=OPERATION_ATTR_KEY, value_type=ATTR_SUBTYPE_STRING, required=False), + ], + child_rules=[ChildRule(TYPE_BINDING, BINDING_SUBTYPE_MESSAGING)], + ) +) +rules_provider.add( + TypeDefinition( + type=TYPE_OPERATION, + sub_type=OPERATION_SUBTYPE_EXPORT, + factory=MetaOperation, + attrs=[ + AttrSchema(name=OPERATION_ATTR_OUTPUT_REF, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema( + name=OPERATION_ATTR_FREQUENCY, value_type=ATTR_SUBTYPE_STRING, required=True, allowed_values=FREQUENCIES + ), + AttrSchema(name=OPERATION_ATTR_AVAILABLE_BY, value_type=ATTR_SUBTYPE_STRING, required=False), + ], + child_rules=[ChildRule(TYPE_BINDING, BINDING_SUBTYPE_FILE)], + ) +) +rules_provider.add( + TypeDefinition( + type=TYPE_OPERATION, + sub_type=OPERATION_SUBTYPE_IMPORT, + factory=MetaOperation, + attrs=[ + AttrSchema(name=OPERATION_ATTR_INPUT_REF, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema( + name=OPERATION_ATTR_FREQUENCY, value_type=ATTR_SUBTYPE_STRING, required=True, allowed_values=FREQUENCIES + ), + ], + child_rules=[ChildRule(TYPE_BINDING, BINDING_SUBTYPE_FILE)], + ) +) +rules_provider.add( + TypeDefinition( + type=TYPE_BINDING, + sub_type=BINDING_SUBTYPE_MESSAGING, + factory=MetaBinding, + attrs=[ + AttrSchema( + name=BINDING_ATTR_PROTOCOL, + value_type=ATTR_SUBTYPE_STRING, + required=False, + allowed_values=MESSAGING_PROTOCOLS, + ), + ], + ) +) +rules_provider.add( + TypeDefinition( + type=TYPE_BINDING, + sub_type=BINDING_SUBTYPE_FILE, + factory=MetaBinding, + attrs=[ + AttrSchema( + name=BINDING_ATTR_TRANSPORT, value_type=ATTR_SUBTYPE_STRING, required=True, allowed_values=FILE_TRANSPORTS + ), + AttrSchema(name=BINDING_ATTR_PATH, value_type=ATTR_SUBTYPE_STRING, required=False), + AttrSchema(name=BINDING_ATTR_FILE_NAME, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema( + name=BINDING_ATTR_FORMAT, value_type=ATTR_SUBTYPE_STRING, required=True, allowed_values=FILE_FORMATS + ), + AttrSchema( + name=BINDING_ATTR_COMPRESSION, + value_type=ATTR_SUBTYPE_STRING, + required=False, + allowed_values=FILE_COMPRESSIONS, + ), + AttrSchema( + name=BINDING_ATTR_COMPLETION, + value_type=ATTR_SUBTYPE_STRING, + required=False, + allowed_values=FILE_COMPLETIONS, + ), + AttrSchema( + name=BINDING_ATTR_ENCRYPTION, + value_type=ATTR_SUBTYPE_STRING, + required=False, + allowed_values=FILE_ENCRYPTIONS, + ), + ], ) ) rules_provider.add( diff --git a/server/python/src/metaobjects/rules_check.py b/server/python/src/metaobjects/rules_check.py index 0488e7cfde..079b188eea 100644 --- a/server/python/src/metaobjects/rules_check.py +++ b/server/python/src/metaobjects/rules_check.py @@ -57,6 +57,7 @@ from metaobjects.naming_refs import effective_package_of, top_level_node_of from metaobjects.requirement_check import SEVERITY_ERROR, SEVERITY_WARN, Diagnostic from metaobjects.rules_settings import RulesSettings +from metaobjects.meta.core.api.api_constants import API_SUBTYPE_OPERATIONAL from metaobjects.shared.base_types import TYPE_API, TYPE_OBJECT, TYPE_OPERATION from metaobjects.shared.separators import PACKAGE_SEP @@ -126,7 +127,7 @@ def _operations(root: MetaData) -> list[MetaData]: return [ op for api in root.children() - if api.type == TYPE_API + if api.type == TYPE_API and api.sub_type == API_SUBTYPE_OPERATIONAL for op in api.children() if op.type == TYPE_OPERATION ] diff --git a/server/python/src/metaobjects/spec_metamodel/api.json b/server/python/src/metaobjects/spec_metamodel/api.json index 6c803bfba0..ab76347e5c 100644 --- a/server/python/src/metaobjects/spec_metamodel/api.json +++ b/server/python/src/metaobjects/spec_metamodel/api.json @@ -15,22 +15,39 @@ "whenToUse": "The application does something beyond derived CRUD: a named command (approve, cancel, import) or a named query (my open requests). Declare it here so its input, output, permission and business errors are part of the model. A plain lifecycle needs no api.operational at all: a transition nobody claims is held to derive its own command once a shell is generated, and no shell is generated yet.", "rules": "Children are `operation.command` and `operation.query`. Lives at the document root. Declares no fields, sources or identities: shapes are referenced, never defined, by the surface. Operation names are compared without case, are unique across every API of one package, except one operation declared identically in two APIs, such as a versioned API beside its successor (one operation declared twice in one API merges), and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). Two declared bindings of one API may not share a method and path (ERR_BINDING_PATH_MISMATCH).", "children": [ - { "type": "operation", "subType": "*", "name": "*", "min": 0, "max": null, "description": "The operations this surface exposes." } + { "type": "operation", "subType": "command", "name": "*", "min": 0, "max": null, "description": "The commands this surface exposes." }, + { "type": "operation", "subType": "query", "name": "*", "min": 0, "max": null, "description": "The queries this surface exposes." } ] }, { - "type": "operation", - "subType": "base", - "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.", + "type": "api", + "subType": "eventing", + "extendsBase": true, + "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.", + "rules": "Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.", "children": [ - { "type": "binding", "subType": "*", "name": "*", "min": 0, "max": null, "description": "Optional protocol bindings. Only needed to override the derived method and path." }, - { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." }, - { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." }, - { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." }, - { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." } + { "type": "operation", "subType": "event", "name": "*", "min": 0, "max": null, "description": "The events this surface publishes." } + ] + }, + { + "type": "api", + "subType": "batch", + "extendsBase": true, + "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.", + "rules": "Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.", + "children": [ + { "type": "operation", "subType": "export", "name": "*", "min": 0, "max": null, "description": "The datasets the provider publishes." }, + { "type": "operation", "subType": "import", "name": "*", "min": 0, "max": null, "description": "The datasets the provider accepts." } ] }, + { + "type": "operation", + "subType": "base", + "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.", + "children": [] + }, { "type": "operation", "subType": "command", @@ -38,6 +55,12 @@ "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.", "children": [ + { "type": "binding", "subType": "rest", "name": "*", "min": 0, "max": null, "description": "Optional HTTP bindings. Only needed to override the derived method and path." }, + { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." }, + { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." }, + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." }, { "type": "attr", "subType": "string", "name": "transitions", "isArray": true, "min": 0, "max": 1, "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)." }, { "type": "attr", "subType": "string", "name": "errors", "isArray": true, "min": 0, "max": 1, "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE." } ] @@ -49,9 +72,52 @@ "description": "A named operation that reads. Returns an `object.projection` (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", "whenToUse": "A read with its own name and shape beyond derived get and list: my open requests, the dashboard summary.", "children": [ + { "type": "binding", "subType": "rest", "name": "*", "min": 0, "max": null, "description": "Optional HTTP bindings. Only needed to override the derived method and path." }, + { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." }, + { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." }, + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." }, { "type": "attr", "subType": "boolean", "name": "many", "min": 0, "max": 1, "description": "The query returns a list and takes the filter, sort and paging contract. Not implied by the projection, so declared. Absent means one row. Legal on a query only." } ] }, + { + "type": "operation", + "subType": "event", + "extendsBase": true, + "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Each distinct fact a consumer may react to: placed, delivered, cancelled.", + "children": [ + { "type": "binding", "subType": "messaging", "name": "*", "min": 0, "max": null, "description": "Optional messaging bindings: how the event travels." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 1, "max": 1, "description": "The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "key", "min": 0, "max": 1, "description": "The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised." } + ] + }, + { + "type": "operation", + "subType": "export", + "extendsBase": true, + "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.", + "children": [ + { "type": "binding", "subType": "file", "name": "*", "min": 0, "max": null, "description": "Optional file bindings: where the file is and how it is written." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 1, "max": 1, "description": "The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "frequency", "min": 1, "max": 1, "allowedValues": ["hourly", "daily", "weekly", "monthly"], "description": "How often a new file appears: hourly, daily, weekly or monthly." }, + { "type": "attr", "subType": "string", "name": "availableBy", "min": 0, "max": 1, "description": "The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised." } + ] + }, + { + "type": "operation", + "subType": "import", + "extendsBase": true, + "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.", + "children": [ + { "type": "binding", "subType": "file", "name": "*", "min": 0, "max": null, "description": "Optional file bindings: where the file is delivered and how it is written." }, + { "type": "attr", "subType": "string", "name": "inputRef", "min": 1, "max": 1, "description": "The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "frequency", "min": 1, "max": 1, "allowedValues": ["hourly", "daily", "weekly", "monthly"], "description": "How often a new file is expected: hourly, daily, weekly or monthly." } + ] + }, { "type": "binding", "subType": "base", @@ -68,6 +134,32 @@ { "type": "attr", "subType": "string", "name": "method", "min": 0, "max": 1, "allowedValues": ["GET", "POST", "PUT", "PATCH", "DELETE"], "description": "The HTTP method. Absent: GET for a query, POST for a command." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "A path template. Its `{name}` placeholders must be exactly the target's primary key fields when the operation is keyed, and there must be none when it is not; two declared bindings of one API may not share the method and path (ERR_BINDING_PATH_MISMATCH)." } ] + }, + { + "type": "binding", + "subType": "messaging", + "extendsBase": true, + "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.", + "children": [ + { "type": "attr", "subType": "string", "name": "protocol", "min": 0, "max": 1, "allowedValues": ["kafka", "amqp", "mqtt", "sqs"], "description": "The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks." } + ] + }, + { + "type": "binding", + "subType": "file", + "extendsBase": true, + "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Every export and import whose file conventions two parties must agree on.", + "children": [ + { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, + { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, + { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, + { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, + { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } + ] } ], "extends": [ diff --git a/server/python/src/metaobjects/spec_metamodel/systems.json b/server/python/src/metaobjects/spec_metamodel/systems.json index cb6b7da4ed..189eaf4c5e 100644 --- a/server/python/src/metaobjects/spec_metamodel/systems.json +++ b/server/python/src/metaobjects/spec_metamodel/systems.json @@ -64,7 +64,8 @@ "description": "A long-running process that answers requests: a web server, an API, a socket server.", "whenToUse": "Anything that listens on a port and stays up.", "children": [ - { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." } + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." }, + { "type": "attr", "subType": "string", "name": "provides", "isArray": true, "min": 0, "max": 1, "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } } ] }, { @@ -84,7 +85,9 @@ "description": "Work that runs to completion and exits: a scheduled task, a migration, a one-off batch. It may run on a schedule (@schedule) or when something triggers it.", "whenToUse": "A cron job, a nightly import, a queue drain that is not a long-running service.", "children": [ - { "type": "attr", "subType": "string", "name": "schedule", "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." } + { "type": "attr", "subType": "string", "name": "schedule", "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." }, + { "type": "attr", "subType": "string", "name": "extracts", "min": 0, "max": 1, "description": "The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object.", "ref": { "targetType": "object", "targetSubTypes": ["entity", "projection"] } }, + { "type": "attr", "subType": "string", "name": "provides", "isArray": true, "min": 0, "max": 1, "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } } ] }, { @@ -137,7 +140,8 @@ "description": "Files and blobs addressed by key.", "whenToUse": "Uploaded images, exports, static assets kept outside the app.", "children": [ - { "type": "attr", "subType": "boolean", "name": "publicRead", "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." } + { "type": "attr", "subType": "boolean", "name": "publicRead", "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." }, + { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`.", "ref": { "targetType": "api", "targetSubTypes": ["batch"] } } ] }, { @@ -162,7 +166,8 @@ "whenToUse": "Work handed from one app to another to run later.", "children": [ { "type": "attr", "subType": "boolean", "name": "ordered", "min": 0, "max": 1, "description": "Messages with the same key are delivered in the order they were sent. Absent means no order is promised." }, - { "type": "attr", "subType": "boolean", "name": "deadLetter", "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." } + { "type": "attr", "subType": "boolean", "name": "deadLetter", "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." }, + { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", "ref": { "targetType": "api", "targetSubTypes": ["eventing"] } } ] }, { @@ -170,7 +175,10 @@ "subType": "stream", "extendsBase": true, "description": "A retained, ordered log that many consumers read, each at its own position. A message can be read again.", - "whenToUse": "Events several consumers read independently, or read again." + "whenToUse": "Events several consumers read independently, or read again.", + "children": [ + { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", "ref": { "targetType": "api", "targetSubTypes": ["eventing"] } } + ] }, { "type": "resource", diff --git a/server/python/tests/test_rules_inert.py b/server/python/tests/test_rules_inert.py index 52fb39e780..da753775c0 100644 --- a/server/python/tests/test_rules_inert.py +++ b/server/python/tests/test_rules_inert.py @@ -6,7 +6,7 @@ must generate exactly what the same model without it generates, byte for byte, through every registered generator and every documentation generator. -The model pair is ``fixtures/codegen-noop/rules/{with,without}`` (see its README), shared with +The model set is ``fixtures/codegen-noop/rules/{with,without,with-delivery}`` (see its README), shared with the other ports' copies of this test. A generator that started reading an operation or a transition by accident would emit something half-built; this test is what notices. @@ -159,3 +159,50 @@ def test_exactly_these_generators_cannot_run_from_a_bare_model(tmp_path: Path) - if THREW in _emit("without", [e], tmp_path / f"probe-{i}") ) assert threw == [] + + +# 1.4.0 — ``api.eventing`` and ``api.batch`` (``operation.event`` / ``.export`` / ``.import``, +# ``binding.messaging`` / ``.file``) are registered and nothing is generated from them yet. The +# ``with-delivery`` model is ``with`` plus one API of each kind; every generator but the model +# explorer must write for it exactly what it writes for ``with``. +def test_the_with_delivery_model_really_carries_an_eventing_and_a_batch_api() -> None: + kinds = sorted(c.sub_type for c in _load("with-delivery").children() if c.type == TYPE_API) + assert kinds == ["batch", "eventing", "operational"] + + +@pytest.mark.parametrize("entry", _inert_generators(), ids=lambda e: e.name) +def test_generator_emits_the_same_files_for_with_delivery_as_for_with( + entry: GeneratorEntry, tmp_path: Path +) -> None: + expected = _emit("with", [entry], tmp_path / "a") + actual = _emit("with-delivery", [entry], tmp_path / "b") + assert actual == expected + + +def test_every_runnable_generator_in_one_run_emits_the_same_files_for_with_delivery(tmp_path: Path) -> None: + runnable = [ + e for i, e in enumerate(_inert_generators()) + if THREW not in _emit("with", [e], tmp_path / f"probe-{i}") + ] + expected = _emit("with", runnable, tmp_path / "a") + actual = _emit("with-delivery", runnable, tmp_path / "b") + assert THREW not in expected, expected.get(THREW) + assert actual == expected + + +def test_api_docs_are_byte_identical_for_with_delivery() -> None: + assert _api_docs("with-delivery") == _api_docs("with") + + +def test_the_rules_check_sees_the_same_operations_for_with_delivery_as_for_with() -> None: + # `verify`'s rules check walks every operation; only an api.operational's are commands or + # queries, so an event, export or import must add no summary count and no diagnostic. + from metaobjects.rules_check import check_rules + from metaobjects.rules_settings import RulesSettings + + settings = RulesSettings(permission_names="require") + expected = check_rules(_load("with"), settings) + actual = check_rules(_load("with-delivery"), settings) + assert expected.summary is not None and expected.summary.operations > 0 + assert actual.summary == expected.summary + assert [d.message for d in actual.diagnostics] == [d.message for d in expected.diagnostics] diff --git a/server/python/tests/unit/test_reference_facet.py b/server/python/tests/unit/test_reference_facet.py index 971407925e..68f9772d4e 100644 --- a/server/python/tests/unit/test_reference_facet.py +++ b/server/python/tests/unit/test_reference_facet.py @@ -720,7 +720,7 @@ def test_an_attribute_with_no_facet_writes_no_ref_key() -> None: assert manifest.count('"ref"') == len(_CORE_FACETS) -def test_the_shipped_systems_definition_declares_the_four_systems_references() -> None: +def test_the_shipped_systems_definition_declares_the_systems_references() -> None: registry = compose_registry(list(core_providers)) found = sorted( { @@ -732,7 +732,10 @@ def test_the_shipped_systems_definition_declares_the_four_systems_references() - } ) assert found == [ + ("app", "extracts", "object"), + ("app", "provides", "api"), ("app", "runsAs", "role"), + ("resource", "carries", "api"), ("role", "heldBy", ("organization", "system")), ("role", "memberOf", "role"), ("system", "owner", "organization"), diff --git a/server/rust/metaobjects-codegen/explorer-app/assets/explorer-app.js b/server/rust/metaobjects-codegen/explorer-app/assets/explorer-app.js index a2681492a9..ec81740b86 100644 --- a/server/rust/metaobjects-codegen/explorer-app/assets/explorer-app.js +++ b/server/rust/metaobjects-codegen/explorer-app/assets/explorer-app.js @@ -265,5 +265,5 @@ `);for(var i=0;i0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(` `)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",` `,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(``)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(` -`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'
    ';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return``}function pct(x){return`${(Math.round(x*1e4)/100).toString()}%`}function legendHtml(withUnclaimed){return`
    ${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
    `}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
    ${values.map(esc).join(" | ")}
    `:"",column:esc(str(f.attrs[FIELD_ATTR_COLUMN])??""),flagsHtml:flags.map((x)=>`${esc(x)}`).join(""),claimsHtml:claims.map((c)=>`${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
    ")}}keyRow(from,c){let fields=strs(c.attrs[IDENTITY_ATTR_FIELDS]),target=this.refHtml(from,c,IDENTITY_REFERENCE_ATTR_REFERENCES)||this.refHtml(from,c,RELATIONSHIP_ATTR_OBJECT_REF),through=str(c.attrs[RELATIONSHIP_ATTR_THROUGH]),card=str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]),shape=c.type===TYPE_RELATIONSHIP?[card,through!==void 0?`through ${localName(through)}`:void 0].filter((x)=>x!==void 0).join(", "):`(${fields.join(", ")})`;return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),inheritedHtml:c.inheritedFrom!==void 0?'inherited':"",shape:esc(shape),targetHtml:target!==""?`→ ${target}`:""}}reportingRow(from,c){let a=c.attrs,parts=[],agg=str(a[REPORTING_ATTR_AGG]),of=this.refHtml(from,c,REPORTING_ATTR_OF,localName);if(agg!==void 0)parts.push(`${esc(agg)}(${of})`);else if(of!=="")parts.push(`of ${of}`);let num=str(a[REPORTING_ATTR_NUMERATOR]),den=str(a[REPORTING_ATTR_DENOMINATOR]);if(num!==void 0&&den!==void 0)parts.push(`${esc(num)} ÷ ${esc(den)}`);let via=str(a[REPORTING_ATTR_VIA]);if(via!==void 0)parts.push(`via ${esc(localName(via))}`);let grains=strs(a[REPORTING_ATTR_GRAINS]);if(grains.length>0)parts.push(`grains ${grains.map((g)=>`${esc(g)}`).join(" ")}`);let seg=str(a[REPORTING_ATTR_SEGMENT]);if(seg!==void 0)parts.push(`segment ${esc(seg)}`);if(a[REPORTING_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`);if(a[REPORTING_ATTR_DEFAULT]!==void 0)parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`);return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),definitionHtml:parts.join(" · ")}}layoutRow(l){let parts=[],cols=strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]);if(cols.length>0)parts.push(`columns ${cols.map((c)=>`${esc(c)}`).join(", ")}`);let sort=str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]);if(sort!==void 0)parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER])!==void 0?` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}`:""}`);if(typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]==="number")parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`);return{kind:esc(`${l.type}.${l.subType}`),name:esc(l.name),detailHtml:parts.join(", ")}}projectionBlock(from,n){let ix=this.ix,rows=[],bases=new Set;for(let f of ix.fields(n.id)){if(f.extends!==void 0)bases.add(ix.ownerOf(f.extends));for(let o of ix.children(f.id).filter((c)=>c.type===TYPE_ORIGIN)){let def=this.originDefinition(from,o);for(let src of this.refLinks(o,ORIGIN_PASSTHROUGH_ATTR_FROM))bases.add(ix.ownerOf(src.id));rows.push({field:esc(f.name),origin:esc(`origin.${o.subType}`),definitionHtml:def})}}return{basesHtml:[...bases].filter((b)=>b!==n.id).sort(byCodeUnit2).map((b)=>this.link(from,b)).join(", "),origins:rows,hasOrigins:rows.length>0}}originDefinition(from,o){let a=o.attrs,ref=(name)=>this.attrValues(o,name).map((v)=>v.link!==null&&!v.link.unresolved?this.link(from,v.link.id,localName(v.text)):`${esc(localName(v.text))}`).join(", "),parts=[],agg=str(a[ORIGIN_AGGREGATE_ATTR_AGG]);if(agg!==void 0)parts.push(`${esc(agg)}(${ref(ORIGIN_AGGREGATE_ATTR_OF)})`);else if(a[ORIGIN_AGGREGATE_ATTR_OF]!==void 0)parts.push(`of ${ref(ORIGIN_AGGREGATE_ATTR_OF)}`);if(a[ORIGIN_PASSTHROUGH_ATTR_FROM]!==void 0)parts.push(`from ${ref(ORIGIN_PASSTHROUGH_ATTR_FROM)}`);if(a[ORIGIN_AGGREGATE_ATTR_VIA]!==void 0)parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`);if(a[ORIGIN_COMPUTED_ATTR_EXPR]!==void 0)parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`);if(a[ORIGIN_AGGREGATE_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`);return parts.join(" · ")}reportBlock(from,n){let a=n.attrs,fromId=this.refLinks(n,OBJECT_REPORT_ATTR_FROM)[0]?.id??str(a[OBJECT_REPORT_ATTR_FROM]),resolve2=(name,kindType)=>{let hit=[fromId!==void 0?`${fromId}.${name}`:void 0,`${n.package===""?"":`${n.package}::`}${name}`].filter((x)=>x!==void 0).find((c)=>this.ix.byId.get(c)?.type===kindType||this.ix.byId.has(c)&&name.includes("."));return hit!==void 0?this.link(from,hit,name):`${esc(name)}`},spine=str(a[OBJECT_REPORT_ATTR_SPINE]);return{fromHtml:this.refHtml(from,n,OBJECT_REPORT_ATTR_FROM),spineHtml:spine!==void 0?`${esc(spine)}`:"",dimensionsHtml:strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d)=>resolve2(d,TYPE_DIMENSION)).join(", "),measuresHtml:strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m)=>resolve2(m,TYPE_MEASURE)).join(", "),segmentHtml:strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s)=>resolve2(s,TYPE_SEGMENT)).join(", "),filterHtml:a[OBJECT_REPORT_ATTR_FILTER]!==void 0?`${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}`:""}}generatedGroups(id){let groups=new Map;for(let f of this.ix.generated(id))groups.set(f.generatedBy,[...groups.get(f.generatedBy)??[],f.path]);return[...groups.keys()].sort(byCodeUnit2).map((g)=>({generator:esc(g),files:(groups.get(g)??[]).map((p)=>esc(p))}))}node(n){let ix=this.ix,from=this.objectPage(n),kindLabel=`${n.type}.${n.subType}`,whyRows=this.whyRows(from,n),attrs=this.attrRows(from,n),referrers=[...(ix.top(n.id)?.referencedBy??[]).map((e)=>e.from.id),...ix.claims(n.id).map((c)=>this.topOf(c.req).node.id)],refBy=[...new Set(referrers.filter((id)=>id!==n.id))].sort(byCodeUnit2).map((id)=>this.link(from,id));return{id:esc(n.id),name:esc(n.name),kindLabel:esc(kindLabel),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › ${esc(kindLabel)}`,isAbstract:n.abstract===!0,description:this.description(n),extendsHtml:n.extends!==void 0?this.link(from,n.extends):"",attrs,hasAttrs:attrs.length>0,members:ix.children(n.id).map((c)=>({anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),nameHtml:ix.reqById.has(c.id)?this.link(from,c.id):esc(c.name===""?`#${c.order}`:c.name),attrsHtml:this.attrRows(from,c).map((a)=>`@${a.name} ${a.valueHtml}`).join("
    "),below:ix.children(c.id).length})),hasMembers:ix.children(n.id).length>0,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(from,n){return n.view.attrs.map((a)=>{let links=a.values.filter((v)=>v.link!==null&&!v.link.unresolved);return{name:esc(a.name),valueHtml:links.length>0&&links.length===a.values.length?links.map((v)=>this.link(from,v.link.id)).join(", "):`${esc(fmt(a.value))}`}})}prompt(n,text){let ix=this.ix,from=this.objectPage(n),payloadId=this.refLinks(n,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id,replyId=this.refLinks(n,TEMPLATE_ATTR_RESPONSE_REF)[0]?.id,vars=text!==void 0?templateVariables(text):void 0,payload=payloadId!==void 0?ix.byId.get(payloadId):void 0,reply=replyId!==void 0?ix.byId.get(replyId):void 0,payloadRows=payload!==void 0?ix.fields(payload.id).map((f)=>({name:esc(f.name),requiredHtml:f.attrs[FIELD_ATTR_REQUIRED]===!0?'required':"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)!==""?` → ${this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)}`:"",usedHtml:vars===void 0?'text not read':vars.has(f.name)?"yes":'no'})):[],replyRows=reply!==void 0?ix.fields(reply.id).map((f)=>({name:esc(f.name),type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),valuesHtml:f.subType===FIELD_SUBTYPE_ENUM?`
    ${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
    `:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(` +`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var FREQUENCY_HOURLY="hourly",FREQUENCY_DAILY="daily",FREQUENCY_WEEKLY="weekly",FREQUENCY_MONTHLY="monthly";var AVAILABLE_BY_PATTERNS={[FREQUENCY_HOURLY]:/^:[0-5][0-9]$/,[FREQUENCY_DAILY]:/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/,[FREQUENCY_WEEKLY]:/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/,[FREQUENCY_MONTHLY]:/^(?:[1-9]|1[0-9]|2[0-8]) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/},AVAILABLE_BY_EXAMPLES={[FREQUENCY_HOURLY]:":15",[FREQUENCY_DAILY]:"03:00",[FREQUENCY_WEEKLY]:"Mon 06:00",[FREQUENCY_MONTHLY]:"1 06:00"};var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'
    ';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return``}function pct(x){return`${(Math.round(x*1e4)/100).toString()}%`}function legendHtml(withUnclaimed){return`
    ${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
    `}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
    ${values.map(esc).join(" | ")}
    `:"",column:esc(str(f.attrs[FIELD_ATTR_COLUMN])??""),flagsHtml:flags.map((x)=>`${esc(x)}`).join(""),claimsHtml:claims.map((c)=>`${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
    ")}}keyRow(from,c){let fields=strs(c.attrs[IDENTITY_ATTR_FIELDS]),target=this.refHtml(from,c,IDENTITY_REFERENCE_ATTR_REFERENCES)||this.refHtml(from,c,RELATIONSHIP_ATTR_OBJECT_REF),through=str(c.attrs[RELATIONSHIP_ATTR_THROUGH]),card=str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]),shape=c.type===TYPE_RELATIONSHIP?[card,through!==void 0?`through ${localName(through)}`:void 0].filter((x)=>x!==void 0).join(", "):`(${fields.join(", ")})`;return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),inheritedHtml:c.inheritedFrom!==void 0?'inherited':"",shape:esc(shape),targetHtml:target!==""?`→ ${target}`:""}}reportingRow(from,c){let a=c.attrs,parts=[],agg=str(a[REPORTING_ATTR_AGG]),of=this.refHtml(from,c,REPORTING_ATTR_OF,localName);if(agg!==void 0)parts.push(`${esc(agg)}(${of})`);else if(of!=="")parts.push(`of ${of}`);let num=str(a[REPORTING_ATTR_NUMERATOR]),den=str(a[REPORTING_ATTR_DENOMINATOR]);if(num!==void 0&&den!==void 0)parts.push(`${esc(num)} ÷ ${esc(den)}`);let via=str(a[REPORTING_ATTR_VIA]);if(via!==void 0)parts.push(`via ${esc(localName(via))}`);let grains=strs(a[REPORTING_ATTR_GRAINS]);if(grains.length>0)parts.push(`grains ${grains.map((g)=>`${esc(g)}`).join(" ")}`);let seg=str(a[REPORTING_ATTR_SEGMENT]);if(seg!==void 0)parts.push(`segment ${esc(seg)}`);if(a[REPORTING_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`);if(a[REPORTING_ATTR_DEFAULT]!==void 0)parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`);return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),definitionHtml:parts.join(" · ")}}layoutRow(l){let parts=[],cols=strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]);if(cols.length>0)parts.push(`columns ${cols.map((c)=>`${esc(c)}`).join(", ")}`);let sort=str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]);if(sort!==void 0)parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER])!==void 0?` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}`:""}`);if(typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]==="number")parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`);return{kind:esc(`${l.type}.${l.subType}`),name:esc(l.name),detailHtml:parts.join(", ")}}projectionBlock(from,n){let ix=this.ix,rows=[],bases=new Set;for(let f of ix.fields(n.id)){if(f.extends!==void 0)bases.add(ix.ownerOf(f.extends));for(let o of ix.children(f.id).filter((c)=>c.type===TYPE_ORIGIN)){let def=this.originDefinition(from,o);for(let src of this.refLinks(o,ORIGIN_PASSTHROUGH_ATTR_FROM))bases.add(ix.ownerOf(src.id));rows.push({field:esc(f.name),origin:esc(`origin.${o.subType}`),definitionHtml:def})}}return{basesHtml:[...bases].filter((b)=>b!==n.id).sort(byCodeUnit2).map((b)=>this.link(from,b)).join(", "),origins:rows,hasOrigins:rows.length>0}}originDefinition(from,o){let a=o.attrs,ref=(name)=>this.attrValues(o,name).map((v)=>v.link!==null&&!v.link.unresolved?this.link(from,v.link.id,localName(v.text)):`${esc(localName(v.text))}`).join(", "),parts=[],agg=str(a[ORIGIN_AGGREGATE_ATTR_AGG]);if(agg!==void 0)parts.push(`${esc(agg)}(${ref(ORIGIN_AGGREGATE_ATTR_OF)})`);else if(a[ORIGIN_AGGREGATE_ATTR_OF]!==void 0)parts.push(`of ${ref(ORIGIN_AGGREGATE_ATTR_OF)}`);if(a[ORIGIN_PASSTHROUGH_ATTR_FROM]!==void 0)parts.push(`from ${ref(ORIGIN_PASSTHROUGH_ATTR_FROM)}`);if(a[ORIGIN_AGGREGATE_ATTR_VIA]!==void 0)parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`);if(a[ORIGIN_COMPUTED_ATTR_EXPR]!==void 0)parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`);if(a[ORIGIN_AGGREGATE_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`);return parts.join(" · ")}reportBlock(from,n){let a=n.attrs,fromId=this.refLinks(n,OBJECT_REPORT_ATTR_FROM)[0]?.id??str(a[OBJECT_REPORT_ATTR_FROM]),resolve2=(name,kindType)=>{let hit=[fromId!==void 0?`${fromId}.${name}`:void 0,`${n.package===""?"":`${n.package}::`}${name}`].filter((x)=>x!==void 0).find((c)=>this.ix.byId.get(c)?.type===kindType||this.ix.byId.has(c)&&name.includes("."));return hit!==void 0?this.link(from,hit,name):`${esc(name)}`},spine=str(a[OBJECT_REPORT_ATTR_SPINE]);return{fromHtml:this.refHtml(from,n,OBJECT_REPORT_ATTR_FROM),spineHtml:spine!==void 0?`${esc(spine)}`:"",dimensionsHtml:strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d)=>resolve2(d,TYPE_DIMENSION)).join(", "),measuresHtml:strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m)=>resolve2(m,TYPE_MEASURE)).join(", "),segmentHtml:strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s)=>resolve2(s,TYPE_SEGMENT)).join(", "),filterHtml:a[OBJECT_REPORT_ATTR_FILTER]!==void 0?`${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}`:""}}generatedGroups(id){let groups=new Map;for(let f of this.ix.generated(id))groups.set(f.generatedBy,[...groups.get(f.generatedBy)??[],f.path]);return[...groups.keys()].sort(byCodeUnit2).map((g)=>({generator:esc(g),files:(groups.get(g)??[]).map((p)=>esc(p))}))}node(n){let ix=this.ix,from=this.objectPage(n),kindLabel=`${n.type}.${n.subType}`,whyRows=this.whyRows(from,n),attrs=this.attrRows(from,n),referrers=[...(ix.top(n.id)?.referencedBy??[]).map((e)=>e.from.id),...ix.claims(n.id).map((c)=>this.topOf(c.req).node.id)],refBy=[...new Set(referrers.filter((id)=>id!==n.id))].sort(byCodeUnit2).map((id)=>this.link(from,id));return{id:esc(n.id),name:esc(n.name),kindLabel:esc(kindLabel),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › ${esc(kindLabel)}`,isAbstract:n.abstract===!0,description:this.description(n),extendsHtml:n.extends!==void 0?this.link(from,n.extends):"",attrs,hasAttrs:attrs.length>0,members:ix.children(n.id).map((c)=>({anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),nameHtml:ix.reqById.has(c.id)?this.link(from,c.id):esc(c.name===""?`#${c.order}`:c.name),attrsHtml:this.attrRows(from,c).map((a)=>`@${a.name} ${a.valueHtml}`).join("
    "),below:ix.children(c.id).length})),hasMembers:ix.children(n.id).length>0,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(from,n){return n.view.attrs.map((a)=>{let links=a.values.filter((v)=>v.link!==null&&!v.link.unresolved);return{name:esc(a.name),valueHtml:links.length>0&&links.length===a.values.length?links.map((v)=>this.link(from,v.link.id)).join(", "):`${esc(fmt(a.value))}`}})}prompt(n,text){let ix=this.ix,from=this.objectPage(n),payloadId=this.refLinks(n,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id,replyId=this.refLinks(n,TEMPLATE_ATTR_RESPONSE_REF)[0]?.id,vars=text!==void 0?templateVariables(text):void 0,payload=payloadId!==void 0?ix.byId.get(payloadId):void 0,reply=replyId!==void 0?ix.byId.get(replyId):void 0,payloadRows=payload!==void 0?ix.fields(payload.id).map((f)=>({name:esc(f.name),requiredHtml:f.attrs[FIELD_ATTR_REQUIRED]===!0?'required':"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)!==""?` → ${this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)}`:"",usedHtml:vars===void 0?'text not read':vars.has(f.name)?"yes":'no'})):[],replyRows=reply!==void 0?ix.fields(reply.id).map((f)=>({name:esc(f.name),type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),valuesHtml:f.subType===FIELD_SUBTYPE_ENUM?`
    ${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
    `:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(` `).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
      ${tops.map((r)=>this.treeNode(page,r)).join("")}
    `:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
  • ${`
    ${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}${dispositionPill(r)}${verdictBadge(r)}${bar}${links.join("")}
    ${esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??"")}
    `}${r.children.length>0?`
      ${r.children.map((c)=>this.treeNode(from,c)).join("")}
    `:""}
  • `}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`${cols.map((o)=>`
    ${this.link(from,o.id)}
    `).join("")}`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLink(from,top)}${cols.map(()=>'').join("")}`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`${levelBadge(r)}${esc(label)}${cols.map((o)=>tg.has(o.id)?`${statusGlyph(r.status)}`:'').join("")}`)}}return{tableHtml:rows.length>0?`${head}${rows.join("")}
    `:"",hasRows:rows.length>0,hasRequirements:ix.hasRequirements()}}trace(){let starts=this.ix.requirements.filter((r)=>r.level!==void 0&&r.level<=REQUIREMENT_LEVEL_SERVICE),fallback=starts.length===0?this.ix.topRequirements:[];return{options:[...starts,...fallback].map((r)=>({value:esc(r.node.id),label:esc(`${" ".repeat(Math.max(0,(r.level??1)-1))}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)}`)})),hasStarts:starts.length+fallback.length>0,hasUsage:!1}}gaps(){let ix=this.ix,from=PAGE_GAPS,cards=[],card=(title,count,source,why,bodyHtml)=>{cards.push({title:esc(title),count:esc(String(count)),source:esc(source),isGate:source==="meta verify",whyHtml:why,bodyHtml})};if(ix.view.sources.requirements){let findingsOf=(gate2)=>[...ix.requirements.flatMap((req)=>req.req.diagnostics.filter((d)=>d.source===GATE_SOURCE===gate2).map((d)=>({req,d}))),...ix.view.advisories.filter((d)=>d.path===""&&d.source===GATE_SOURCE===gate2).map((d)=>({d}))],table=(rows,chip)=>rows.length===0?'
    None.
    ':`${rows.map(({req,d})=>``).join("")}
    ${esc(d.code)}${req!==void 0?this.reqLink(from,req):""}
    ${esc(d.message)}
    `,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
    None.
    ');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
    None.
    ')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
    Not scanned.
    ');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
    No prompt text was read.
    ':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
    None.
    ':`
      ${items.map((i)=>`
    • ${i}
    • `).join("")}
    `}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found

    No such page

    ${escapeHtml2(r.path)} is not a page of this model.

    Overview

    `,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="

    No model yet

    The explorer is waiting for the running application's docs view.

    ";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="

    No model

    The source parameter is not a URL.

    ",paintLive();return}follow(source);return}if(!build())document.body.innerHTML="

    No model

    explorer-model.js did not load. Run meta gen to write it beside this page.

    ";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})(); diff --git a/server/rust/metaobjects-codegen/src/service_routes.rs b/server/rust/metaobjects-codegen/src/service_routes.rs index 766729139d..9ec3990160 100644 --- a/server/rust/metaobjects-codegen/src/service_routes.rs +++ b/server/rust/metaobjects-codegen/src/service_routes.rs @@ -64,6 +64,7 @@ const ATTR_FORM_EXCLUDE: &str = "formExclude"; const ATTR_METHOD: &str = "method"; const ATTR_PATH: &str = "path"; const TYPE_BINDING: &str = "binding"; +const SUBTYPE_REST: &str = "rest"; const ORDER_DESC: &str = "desc"; /// The `axum` the transport crates are written for. @@ -345,7 +346,9 @@ pub fn routes_packages(ctx: &GenContext<'_>) -> Result, GenEr .children(o.names.node) .iter() .copied() - .find(|&c| tree.node(c).type_name == TYPE_BINDING); + .find(|&c| { + tree.node(c).type_name == TYPE_BINDING && tree.node(c).sub_type == SUBTYPE_REST + }); let declared = |attr| binding.and_then(|b| tree.attr(b, attr)?.as_str().map(str::to_string)); let method = declared(ATTR_METHOD).map_or_else( diff --git a/server/rust/metaobjects-codegen/tests/rules_inert.rs b/server/rust/metaobjects-codegen/tests/rules_inert.rs index 506fb9d05c..af3df9b6e1 100644 --- a/server/rust/metaobjects-codegen/tests/rules_inert.rs +++ b/server/rust/metaobjects-codegen/tests/rules_inert.rs @@ -73,6 +73,11 @@ fn pick_of(name: &str) -> Pick { /// Every file the picked shipped generators write for one variant: path to contents. fn emit(variant: &str, pick: Pick) -> BTreeMap { + emit_where(variant, |name| pick_of(name) == pick) +} + +/// Every file the shipped generators `keep` selects write for one variant: path to contents. +fn emit_where(variant: &str, keep: impl Fn(&str) -> bool) -> BTreeMap { let fixture = Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../../fixtures/codegen-noop/rules") .join(variant) @@ -98,7 +103,7 @@ fn emit(variant: &str, pick: Pick) -> BTreeMap { .into_iter() .filter(|g| g.name() != "shared-model") { - if pick_of(g.name()) != pick { + if !keep(g.name()) { continue; } let emitted = g @@ -253,3 +258,23 @@ fn the_transport_writes_the_same_files_and_changes_only_its_manifest_and_router( } } } + +/// 1.4.0: `api.eventing` and `api.batch` (with `operation.event`, `.export` and `.import`, and +/// `binding.messaging` and `binding.file`) are registered and nothing is generated from them. +/// `with-delivery` is `with` plus one API of each kind; every generator but the model explorer +/// writes exactly what it writes for `with`, the service generators included: they read only +/// `api.operational` and select its `binding.rest` by subtype. +#[test] +fn eventing_and_batch_apis_generate_what_the_model_without_them_does() { + let every = |name: &str| name != "docs-site"; + let with = emit_where("with", every); + let delivery = emit_where("with-delivery", every); + assert!(with.len() > 10, "the model generates something"); + assert_eq!( + delivery.keys().collect::>(), + with.keys().collect::>() + ); + for (path, text) in &with { + assert_eq!(&delivery[path], text, "{path}"); + } +} diff --git a/server/rust/metaobjects/data/metamodel/api.json b/server/rust/metaobjects/data/metamodel/api.json index 6c803bfba0..ab76347e5c 100644 --- a/server/rust/metaobjects/data/metamodel/api.json +++ b/server/rust/metaobjects/data/metamodel/api.json @@ -15,22 +15,39 @@ "whenToUse": "The application does something beyond derived CRUD: a named command (approve, cancel, import) or a named query (my open requests). Declare it here so its input, output, permission and business errors are part of the model. A plain lifecycle needs no api.operational at all: a transition nobody claims is held to derive its own command once a shell is generated, and no shell is generated yet.", "rules": "Children are `operation.command` and `operation.query`. Lives at the document root. Declares no fields, sources or identities: shapes are referenced, never defined, by the surface. Operation names are compared without case, are unique across every API of one package, except one operation declared identically in two APIs, such as a versioned API beside its successor (one operation declared twice in one API merges), and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). Two declared bindings of one API may not share a method and path (ERR_BINDING_PATH_MISMATCH).", "children": [ - { "type": "operation", "subType": "*", "name": "*", "min": 0, "max": null, "description": "The operations this surface exposes." } + { "type": "operation", "subType": "command", "name": "*", "min": 0, "max": null, "description": "The commands this surface exposes." }, + { "type": "operation", "subType": "query", "name": "*", "min": 0, "max": null, "description": "The queries this surface exposes." } ] }, { - "type": "operation", - "subType": "base", - "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.", + "type": "api", + "subType": "eventing", + "extendsBase": true, + "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.", + "rules": "Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.", "children": [ - { "type": "binding", "subType": "*", "name": "*", "min": 0, "max": null, "description": "Optional protocol bindings. Only needed to override the derived method and path." }, - { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." }, - { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." }, - { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." }, - { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." } + { "type": "operation", "subType": "event", "name": "*", "min": 0, "max": null, "description": "The events this surface publishes." } + ] + }, + { + "type": "api", + "subType": "batch", + "extendsBase": true, + "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.", + "rules": "Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.", + "children": [ + { "type": "operation", "subType": "export", "name": "*", "min": 0, "max": null, "description": "The datasets the provider publishes." }, + { "type": "operation", "subType": "import", "name": "*", "min": 0, "max": null, "description": "The datasets the provider accepts." } ] }, + { + "type": "operation", + "subType": "base", + "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.", + "children": [] + }, { "type": "operation", "subType": "command", @@ -38,6 +55,12 @@ "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.", "children": [ + { "type": "binding", "subType": "rest", "name": "*", "min": 0, "max": null, "description": "Optional HTTP bindings. Only needed to override the derived method and path." }, + { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." }, + { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." }, + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." }, { "type": "attr", "subType": "string", "name": "transitions", "isArray": true, "min": 0, "max": 1, "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)." }, { "type": "attr", "subType": "string", "name": "errors", "isArray": true, "min": 0, "max": 1, "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE." } ] @@ -49,9 +72,52 @@ "description": "A named operation that reads. Returns an `object.projection` (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", "whenToUse": "A read with its own name and shape beyond derived get and list: my open requests, the dashboard summary.", "children": [ + { "type": "binding", "subType": "rest", "name": "*", "min": 0, "max": null, "description": "Optional HTTP bindings. Only needed to override the derived method and path." }, + { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." }, + { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." }, + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." }, { "type": "attr", "subType": "boolean", "name": "many", "min": 0, "max": 1, "description": "The query returns a list and takes the filter, sort and paging contract. Not implied by the projection, so declared. Absent means one row. Legal on a query only." } ] }, + { + "type": "operation", + "subType": "event", + "extendsBase": true, + "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Each distinct fact a consumer may react to: placed, delivered, cancelled.", + "children": [ + { "type": "binding", "subType": "messaging", "name": "*", "min": 0, "max": null, "description": "Optional messaging bindings: how the event travels." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 1, "max": 1, "description": "The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "key", "min": 0, "max": 1, "description": "The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised." } + ] + }, + { + "type": "operation", + "subType": "export", + "extendsBase": true, + "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.", + "children": [ + { "type": "binding", "subType": "file", "name": "*", "min": 0, "max": null, "description": "Optional file bindings: where the file is and how it is written." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 1, "max": 1, "description": "The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "frequency", "min": 1, "max": 1, "allowedValues": ["hourly", "daily", "weekly", "monthly"], "description": "How often a new file appears: hourly, daily, weekly or monthly." }, + { "type": "attr", "subType": "string", "name": "availableBy", "min": 0, "max": 1, "description": "The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised." } + ] + }, + { + "type": "operation", + "subType": "import", + "extendsBase": true, + "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.", + "children": [ + { "type": "binding", "subType": "file", "name": "*", "min": 0, "max": null, "description": "Optional file bindings: where the file is delivered and how it is written." }, + { "type": "attr", "subType": "string", "name": "inputRef", "min": 1, "max": 1, "description": "The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "frequency", "min": 1, "max": 1, "allowedValues": ["hourly", "daily", "weekly", "monthly"], "description": "How often a new file is expected: hourly, daily, weekly or monthly." } + ] + }, { "type": "binding", "subType": "base", @@ -68,6 +134,32 @@ { "type": "attr", "subType": "string", "name": "method", "min": 0, "max": 1, "allowedValues": ["GET", "POST", "PUT", "PATCH", "DELETE"], "description": "The HTTP method. Absent: GET for a query, POST for a command." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "A path template. Its `{name}` placeholders must be exactly the target's primary key fields when the operation is keyed, and there must be none when it is not; two declared bindings of one API may not share the method and path (ERR_BINDING_PATH_MISMATCH)." } ] + }, + { + "type": "binding", + "subType": "messaging", + "extendsBase": true, + "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.", + "children": [ + { "type": "attr", "subType": "string", "name": "protocol", "min": 0, "max": 1, "allowedValues": ["kafka", "amqp", "mqtt", "sqs"], "description": "The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks." } + ] + }, + { + "type": "binding", + "subType": "file", + "extendsBase": true, + "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Every export and import whose file conventions two parties must agree on.", + "children": [ + { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, + { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, + { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, + { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, + { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } + ] } ], "extends": [ diff --git a/server/rust/metaobjects/data/metamodel/systems.json b/server/rust/metaobjects/data/metamodel/systems.json index cb6b7da4ed..189eaf4c5e 100644 --- a/server/rust/metaobjects/data/metamodel/systems.json +++ b/server/rust/metaobjects/data/metamodel/systems.json @@ -64,7 +64,8 @@ "description": "A long-running process that answers requests: a web server, an API, a socket server.", "whenToUse": "Anything that listens on a port and stays up.", "children": [ - { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." } + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." }, + { "type": "attr", "subType": "string", "name": "provides", "isArray": true, "min": 0, "max": 1, "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } } ] }, { @@ -84,7 +85,9 @@ "description": "Work that runs to completion and exits: a scheduled task, a migration, a one-off batch. It may run on a schedule (@schedule) or when something triggers it.", "whenToUse": "A cron job, a nightly import, a queue drain that is not a long-running service.", "children": [ - { "type": "attr", "subType": "string", "name": "schedule", "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." } + { "type": "attr", "subType": "string", "name": "schedule", "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." }, + { "type": "attr", "subType": "string", "name": "extracts", "min": 0, "max": 1, "description": "The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object.", "ref": { "targetType": "object", "targetSubTypes": ["entity", "projection"] } }, + { "type": "attr", "subType": "string", "name": "provides", "isArray": true, "min": 0, "max": 1, "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } } ] }, { @@ -137,7 +140,8 @@ "description": "Files and blobs addressed by key.", "whenToUse": "Uploaded images, exports, static assets kept outside the app.", "children": [ - { "type": "attr", "subType": "boolean", "name": "publicRead", "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." } + { "type": "attr", "subType": "boolean", "name": "publicRead", "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." }, + { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`.", "ref": { "targetType": "api", "targetSubTypes": ["batch"] } } ] }, { @@ -162,7 +166,8 @@ "whenToUse": "Work handed from one app to another to run later.", "children": [ { "type": "attr", "subType": "boolean", "name": "ordered", "min": 0, "max": 1, "description": "Messages with the same key are delivered in the order they were sent. Absent means no order is promised." }, - { "type": "attr", "subType": "boolean", "name": "deadLetter", "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." } + { "type": "attr", "subType": "boolean", "name": "deadLetter", "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." }, + { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", "ref": { "targetType": "api", "targetSubTypes": ["eventing"] } } ] }, { @@ -170,7 +175,10 @@ "subType": "stream", "extendsBase": true, "description": "A retained, ordered log that many consumers read, each at its own position. A message can be read again.", - "whenToUse": "Events several consumers read independently, or read again." + "whenToUse": "Events several consumers read independently, or read again.", + "children": [ + { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", "ref": { "targetType": "api", "targetSubTypes": ["eventing"] } } + ] }, { "type": "resource", diff --git a/server/rust/metaobjects/src/rules_check.rs b/server/rust/metaobjects/src/rules_check.rs index c0c0c30436..a11d7e01a0 100644 --- a/server/rust/metaobjects/src/rules_check.rs +++ b/server/rust/metaobjects/src/rules_check.rs @@ -56,6 +56,7 @@ pub const WARN_DERIVED_COMMAND_BYPASSES_DECLARED: &str = "WARN_DERIVED_COMMAND_B const T_API: &str = "api"; const T_OPERATION: &str = "operation"; +const SUB_OPERATIONAL: &str = "operational"; const SUB_ENTITY: &str = "entity"; const SUB_ENUM: &str = "enum"; const SUB_COMMAND: &str = "command"; @@ -186,7 +187,7 @@ pub(crate) fn operations(tree: &Tree, root: NodeId) -> Vec { tree.children(root) .iter() .copied() - .filter(|&a| tree.node(a).type_name == T_API) + .filter(|&a| is_a(tree, a, T_API, SUB_OPERATIONAL)) .flat_map(|api| { tree.children(api) .iter() diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs index bfa8773398..8943df00a4 100644 --- a/server/rust/metaobjects/src/validate/rules.rs +++ b/server/rust/metaobjects/src/validate/rules.rs @@ -44,6 +44,13 @@ //! B1 ERR_BINDING_PATH_MISMATCH a binding.rest @path's placeholders are not the target's key //! fields (keyed) or are not empty (unkeyed) //! B2 ERR_BINDING_PATH_MISMATCH two bindings of one API share a method and a path +//! +//! Operations of an api.eventing or api.batch (event, export, import) are not commands or +//! queries: only O1 applies to them, with two rules of their own: +//! D1 ERR_BAD_ATTR_VALUE an operation.export @availableBy lacks the form its +//! @frequency gives +//! D2 ERR_BAD_ATTR_VALUE a binding.file @fileName holds a placeholder other than +//! {date} or {timestamp}, or an unclosed brace //! ``` //! //! Everything a lifecycle has beyond its transitions is derived, with no vocabulary of @@ -89,6 +96,8 @@ const SUB_ACTION: &str = "action"; const SUB_COMMAND: &str = "command"; const SUB_QUERY: &str = "query"; const SUB_REST: &str = "rest"; +const SUB_OPERATIONAL: &str = "operational"; +const SUB_FILE: &str = "file"; const SUB_PRIMARY: &str = "primary"; const A_DEFAULT: &str = "default"; @@ -107,6 +116,22 @@ const A_MANY: &str = "many"; const A_METHOD: &str = "method"; const A_PATH: &str = "path"; const A_FIELDS: &str = "fields"; +const A_FREQUENCY: &str = "frequency"; +const A_AVAILABLE_BY: &str = "availableBy"; +const A_FILE_NAME: &str = "fileName"; + +/// The placeholders a binding.file `@fileName` may hold. +const FILE_NAME_PLACEHOLDERS: [&str; 2] = ["date", "timestamp"]; + +/// How an export's `@availableBy` is written for each `@frequency`: `(frequency, example)`. +const AVAILABLE_BY_EXAMPLES: [(&str, &str); 4] = [ + ("hourly", ":15"), + ("daily", "03:00"), + ("weekly", "Mon 06:00"), + ("monthly", "1 06:00"), +]; + +const WEEKDAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; const METHOD_POST: &str = "POST"; const METHOD_GET: &str = "GET"; @@ -772,7 +797,7 @@ fn check_entity_lifecycles(tree: &Tree, entity: NodeId, sink: &mut Sink<'_>) { entity, ERR_TRANSITION_NOT_ON_ENTITY, format!( - "object.entity \"{}\" has a lifecycle (transitions on {}) and a source, but no writable one; a transition is a guarded update of a stored row. (An entity with no source at all may carry a lifecycle: it is inert until a source is added.)", + "object.entity \"{}\" has a lifecycle (transitions on {}) and a source, but no writable one; a transition is a guarded update of a stored row. (An entity with no relational source may carry a lifecycle: it is inert until a source.rdb is added.)", enode.name, quote_list(&fields) ), @@ -791,6 +816,166 @@ fn declared_paths(tree: &Tree, op: NodeId) -> Vec<(NodeId, &str)> { .collect() } +/// What a reference found: nothing, or the subtype of the object it names. +fn found_shape(tree: &Tree, target: Option) -> String { + match target { + None => "names no object".to_string(), + Some(t) => format!("is an object.{}", tree.node(t).sub_type), + } +} + +/// O1: an operation's `@inputRef` and `@outputRef` shapes. False when one is wrong. +fn check_shapes(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) -> bool { + let tree = ctx.tree; + let sub = tree.node(op).sub_type.as_str(); + let op_label = label(tree, op); + if let Some(input_ref) = str_attr(tree, op, A_INPUT_REF) { + let input = resolve_object_on(&ctx.env(), op, input_ref); + if input.is_none_or(|i| tree.node(i).sub_type != SUB_VALUE) { + sink.add( + op, + ERR_OPERATION_SHAPE, + format!( + "operation.{sub} \"{op_label}\" @inputRef \"{input_ref}\" {}; an operation's input is an object.value.", + found_shape(tree, input) + ), + ); + return false; + } + } + if let Some(output_ref) = str_attr(tree, op, A_OUTPUT_REF) { + let output = resolve_object_on(&ctx.env(), op, output_ref); + let legal = output.is_some_and(|o| { + [SUB_ENTITY, SUB_PROJECTION, SUB_VALUE].contains(&tree.node(o).sub_type.as_str()) + }); + if !legal { + sink.add( + op, + ERR_OPERATION_SHAPE, + format!( + "operation.{sub} \"{op_label}\" @outputRef \"{output_ref}\" {}; an operation returns an object.entity, object.projection or object.value.", + found_shape(tree, output) + ), + ); + return false; + } + } + true +} + +/// `[0-5][0-9]`. +fn is_minute(s: &str) -> bool { + let b = s.as_bytes(); + b.len() == 2 && (b'0'..=b'5').contains(&b[0]) && b[1].is_ascii_digit() +} + +/// `(?:[01][0-9]|2[0-3])`. +fn is_hour(s: &str) -> bool { + let b = s.as_bytes(); + b.len() == 2 + && b[1].is_ascii_digit() + && (b[0] == b'0' || b[0] == b'1' || (b[0] == b'2' && b[1] <= b'3')) +} + +/// `HH:MM`. +fn is_clock(s: &str) -> bool { + s.split_once(':') + .is_some_and(|(h, m)| is_hour(h) && is_minute(m)) +} + +/// `(?:[1-9]|1[0-9]|2[0-8])`. +fn is_month_day(s: &str) -> bool { + s.parse::().is_ok_and(|d| (1..=28).contains(&d)) + && s.bytes().all(|c| c.is_ascii_digit()) + && !s.starts_with('0') +} + +/// Whether `value` has the form `frequency` gives (the reference's AVAILABLE_BY_PATTERNS). +fn available_by_matches(frequency: &str, value: &str) -> bool { + match frequency { + "hourly" => value.strip_prefix(':').is_some_and(is_minute), + "daily" => is_clock(value), + "weekly" => value + .split_once(' ') + .is_some_and(|(d, t)| WEEKDAYS.contains(&d) && is_clock(t)), + "monthly" => value + .split_once(' ') + .is_some_and(|(d, t)| is_month_day(d) && is_clock(t)), + _ => true, + } +} + +/// What is wrong with a `@fileName`'s placeholders, or `None` when nothing is. +fn file_name_placeholder_problem(file_name: &str) -> Option { + let mut rest = String::new(); + let mut i = 0; + let bytes = file_name.as_bytes(); + // Scan for `{[^{}]*}` the way the reference's /\{([^{}]*)\}/g does. + while i < bytes.len() { + if bytes[i] == b'{' { + if let Some(len) = file_name[i + 1..].find(['{', '}']) { + if bytes[i + 1 + len] == b'}' { + let name = &file_name[i + 1..i + 1 + len]; + if !FILE_NAME_PLACEHOLDERS.contains(&name) { + return Some(format!("holds the placeholder {{{name}}}")); + } + i += len + 2; + continue; + } + } + } + let ch = file_name[i..].chars().next().unwrap_or(' '); + rest.push(ch); + i += ch.len_utf8(); + } + rest.contains(['{', '}']).then(|| "has an unmatched brace".to_string()) +} + +/// The checks for one operation of an api.eventing or api.batch: its shapes (O1), the form of +/// an export's `@availableBy` (D1) and the placeholders of each binding.file `@fileName` (D2). +fn check_delivery_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) { + if !check_shapes(ctx, op, sink) { + return; + } + let tree = ctx.tree; + let sub = tree.node(op).sub_type.as_str(); + let op_label = label(tree, op); + if let (Some(by), Some(freq)) = ( + str_attr(tree, op, A_AVAILABLE_BY), + str_attr(tree, op, A_FREQUENCY), + ) && let Some((_, example)) = AVAILABLE_BY_EXAMPLES.iter().find(|(f, _)| *f == freq) + && !available_by_matches(freq, by) + { + sink.add( + op, + ERR_BAD_ATTR_VALUE, + format!( + "operation.{sub} \"{op_label}\" @availableBy \"{by}\" is not a {freq} time; a {freq} file's @availableBy is written like \"{example}\" (UTC)." + ), + ); + } + // ADR-0039: own — a binding is checked on the operation that declares it. + for &b in tree.own_children(op) { + if !is_a(tree, b, T_BINDING, SUB_FILE) { + continue; + } + let Some(file_name) = str_attr(tree, b, A_FILE_NAME) else { + continue; + }; + if let Some(problem) = file_name_placeholder_problem(file_name) { + sink.add( + b, + ERR_BAD_ATTR_VALUE, + format!( + "binding.file on \"{}\" @fileName \"{file_name}\" {problem}; the placeholders are {{{}}}.", + label(tree, b), + FILE_NAME_PLACEHOLDERS.join("} and {") + ), + ); + } + } +} + /// O0 to O5, P1, P2 and B1 for one operation. fn check_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) { let tree = ctx.tree; @@ -867,40 +1052,8 @@ fn check_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) { } // O1 — shapes. - let found = |target: Option| match target { - None => "names no object".to_string(), - Some(t) => format!("is an object.{}", tree.node(t).sub_type), - }; - if let Some(input_ref) = str_attr(tree, op, A_INPUT_REF) { - let input = resolve_object_on(&ctx.env(), op, input_ref); - if input.is_none_or(|i| tree.node(i).sub_type != SUB_VALUE) { - sink.add( - op, - ERR_OPERATION_SHAPE, - format!( - "operation.{sub} \"{op_label}\" @inputRef \"{input_ref}\" {}; an operation's input is an object.value.", - found(input) - ), - ); - return; - } - } - if let Some(output_ref) = str_attr(tree, op, A_OUTPUT_REF) { - let output = resolve_object_on(&ctx.env(), op, output_ref); - let legal = output.is_some_and(|o| { - [SUB_ENTITY, SUB_PROJECTION, SUB_VALUE].contains(&tree.node(o).sub_type.as_str()) - }); - if !legal { - sink.add( - op, - ERR_OPERATION_SHAPE, - format!( - "operation.{sub} \"{op_label}\" @outputRef \"{output_ref}\" {}; an operation returns an object.entity, object.projection or object.value.", - found(output) - ), - ); - return; - } + if !check_shapes(ctx, op, sink) { + return; } // O2, O3 — the target. @@ -914,7 +1067,7 @@ fn check_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) { ERR_OPERATION_TARGET_UNRESOLVED, format!( "operation.{sub} \"{op_label}\" @objectRef \"{object_ref}\" {}; an operation acts on an object.entity.", - found(declared) + found_shape(tree, declared) ), ); return; @@ -1179,7 +1332,7 @@ fn check_permission_names(ctx: &Ctx<'_>, top_level: &[NodeId], sink: &mut Sink<' } } for &api in top_level { - if tree.node(api).type_name != T_API { + if !is_a(tree, api, T_API, SUB_OPERATIONAL) { continue; } for &op in tree.children(api).iter() { @@ -1237,6 +1390,14 @@ pub fn validate_rules(ctx: &Ctx<'_>, f: &mut Findings) { if tree.node(api).type_name != T_API { continue; } + if tree.node(api).sub_type != SUB_OPERATIONAL { + for &op in tree.children(api).iter() { + if tree.node(op).type_name == T_OPERATION { + check_delivery_operation(ctx, op, &mut sink); + } + } + continue; + } let ops: Vec = tree .children(api) .iter() diff --git a/server/rust/metaobjects/tests/conformance-expected-failures.json b/server/rust/metaobjects/tests/conformance-expected-failures.json index 363ec1e16b..8b9e3bf8ea 100644 --- a/server/rust/metaobjects/tests/conformance-expected-failures.json +++ b/server/rust/metaobjects/tests/conformance-expected-failures.json @@ -1,6 +1,6 @@ { "language": "rust", "notes": "The Rust port passes every fixture of the shared metamodel corpus, so the ledger is empty. The ledger may only shrink and is kept for the day a new fixture lands that Rust does not pass yet: list it here with the reason, and it leaves when the work that covers it lands. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.", - "minPassing": 614, + "minPassing": 619, "fixtures": [] } diff --git a/server/typescript/packages/cli/test/unit/rules-inert.test.ts b/server/typescript/packages/cli/test/unit/rules-inert.test.ts index d727fc9a7a..de2ec82e48 100644 --- a/server/typescript/packages/cli/test/unit/rules-inert.test.ts +++ b/server/typescript/packages/cli/test/unit/rules-inert.test.ts @@ -42,7 +42,7 @@ const SCRATCH = mkdtempSync(join(tmpdir(), "rules-inert-")); const MODEL_FILE = join(SCRATCH, "model", "meta.purchasing.json"); const PROJECT = join(SCRATCH, "project"); -async function load(variant: "with" | "without"): Promise { +async function load(variant: "with" | "without" | "with-delivery"): Promise { mkdirSync(join(SCRATCH, "model"), { recursive: true }); copyFileSync(join(MODELS, variant, "meta.purchasing.json"), MODEL_FILE); const file = MODEL_FILE; @@ -129,10 +129,12 @@ const SERVICE_LAYER: Record = { let withRules: MetaRoot; let withoutRules: MetaRoot; +let withDelivery: MetaRoot; beforeAll(async () => { withRules = await load("with"); withoutRules = await load("without"); + withDelivery = await load("with-delivery"); }); afterAll(() => rmSync(SCRATCH, { recursive: true, force: true })); @@ -278,3 +280,32 @@ describe("ADR-0066 the business-rules vocabulary is inert in every generator and .toEqual(buildExpectedSchema(withoutRules, { dialect: "postgres", views: views(withoutRules) })); }); }); + +// 1.4.0 — `api.eventing` and `api.batch`, with `operation.event` / `.export` / `.import` and +// `binding.messaging` / `binding.file`, are registered and nothing is generated from them yet. +// The `with-delivery` model is `with` plus one API of each kind, whose operations reference the +// same value and projection the operational API does. Every generator but the model explorer +// (which lists every node) must write exactly what it writes for `with`: the service generators +// included, which read only `api.operational` and select the `binding.rest` by subtype. +describe("api.eventing and api.batch are inert in every generator and in migrate", () => { + test("the with-delivery model really carries an eventing and a batch API", () => { + const kinds = withDelivery.children().filter((c) => c.type === TYPE_API).map((c) => c.subType).sort(); + expect(kinds).toEqual(["batch", "eventing", "operational"]); + }); + + const catalog = composeCatalog(); + for (const [name, entry] of Object.entries(catalog)) { + if (name === DOCS_SITE) continue; + test(`generator "${name}" emits the same files, byte for byte`, async () => { + const expected = await emit(withRules, [entry.factory()]); + const actual = await emit(withDelivery, [entry.factory()]); + expect(actual).toEqual(expected); + }); + } + + test("migrate's expected schema is the same", () => { + const views = (m: MetaRoot) => buildProjectionViews(m, { dialect: "postgres" }); + expect(buildExpectedSchema(withDelivery, { dialect: "postgres", views: views(withDelivery) })) + .toEqual(buildExpectedSchema(withRules, { dialect: "postgres", views: views(withRules) })); + }); +}); diff --git a/server/typescript/packages/codegen-ts/src/service-walk.ts b/server/typescript/packages/codegen-ts/src/service-walk.ts index 4d9e09b455..10b47d60f9 100644 --- a/server/typescript/packages/codegen-ts/src/service-walk.ts +++ b/server/typescript/packages/codegen-ts/src/service-walk.ts @@ -28,6 +28,7 @@ import { OPERATION_ATTR_TRANSITIONS, OPERATION_SUBTYPE_COMMAND, TRANSITION_ATTR_CONDITION, + BINDING_SUBTYPE_REST, TYPE_BINDING, TYPE_FIELD, claimedTransitions, @@ -348,7 +349,9 @@ function operationOf(op: MetaData, target: ServiceEntity | undefined, settings: const lifecycles = target === undefined ? [] : lifecyclesOf(target.obj); const names = new Set(kind === "command" ? stringsOf(op, OPERATION_ATTR_TRANSITIONS) : []); const transitions = lifecycles.flatMap((l) => l.transitions.filter((t) => names.has(t.name)).map((t) => transitionOf(t, l.field.name))); - const binding = op.children().find((c) => c.type === TYPE_BINDING); + // The service is the HTTP surface, so the binding it reads is the rest one, chosen by subtype: + // another binding kind carries no method or path. + const binding = op.children().find((c) => c.type === TYPE_BINDING && c.subType === BINDING_SUBTYPE_REST); const declaredMethod = binding?.attr(BINDING_ATTR_METHOD); const declaredPath = binding?.attr(BINDING_ATTR_PATH); const method = (typeof declaredMethod === "string" ? declaredMethod : kind === "query" ? "GET" : "POST") as ServiceOperation["method"]; diff --git a/server/typescript/packages/docs-site/app/assets/explorer-app.js b/server/typescript/packages/docs-site/app/assets/explorer-app.js index a2681492a9..ec81740b86 100644 --- a/server/typescript/packages/docs-site/app/assets/explorer-app.js +++ b/server/typescript/packages/docs-site/app/assets/explorer-app.js @@ -265,5 +265,5 @@ `);for(var i=0;i0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(` `)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",` `,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(``)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(` -`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'
    ';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return``}function pct(x){return`${(Math.round(x*1e4)/100).toString()}%`}function legendHtml(withUnclaimed){return`
    ${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
    `}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
    ${values.map(esc).join(" | ")}
    `:"",column:esc(str(f.attrs[FIELD_ATTR_COLUMN])??""),flagsHtml:flags.map((x)=>`${esc(x)}`).join(""),claimsHtml:claims.map((c)=>`${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
    ")}}keyRow(from,c){let fields=strs(c.attrs[IDENTITY_ATTR_FIELDS]),target=this.refHtml(from,c,IDENTITY_REFERENCE_ATTR_REFERENCES)||this.refHtml(from,c,RELATIONSHIP_ATTR_OBJECT_REF),through=str(c.attrs[RELATIONSHIP_ATTR_THROUGH]),card=str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]),shape=c.type===TYPE_RELATIONSHIP?[card,through!==void 0?`through ${localName(through)}`:void 0].filter((x)=>x!==void 0).join(", "):`(${fields.join(", ")})`;return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),inheritedHtml:c.inheritedFrom!==void 0?'inherited':"",shape:esc(shape),targetHtml:target!==""?`→ ${target}`:""}}reportingRow(from,c){let a=c.attrs,parts=[],agg=str(a[REPORTING_ATTR_AGG]),of=this.refHtml(from,c,REPORTING_ATTR_OF,localName);if(agg!==void 0)parts.push(`${esc(agg)}(${of})`);else if(of!=="")parts.push(`of ${of}`);let num=str(a[REPORTING_ATTR_NUMERATOR]),den=str(a[REPORTING_ATTR_DENOMINATOR]);if(num!==void 0&&den!==void 0)parts.push(`${esc(num)} ÷ ${esc(den)}`);let via=str(a[REPORTING_ATTR_VIA]);if(via!==void 0)parts.push(`via ${esc(localName(via))}`);let grains=strs(a[REPORTING_ATTR_GRAINS]);if(grains.length>0)parts.push(`grains ${grains.map((g)=>`${esc(g)}`).join(" ")}`);let seg=str(a[REPORTING_ATTR_SEGMENT]);if(seg!==void 0)parts.push(`segment ${esc(seg)}`);if(a[REPORTING_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`);if(a[REPORTING_ATTR_DEFAULT]!==void 0)parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`);return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),definitionHtml:parts.join(" · ")}}layoutRow(l){let parts=[],cols=strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]);if(cols.length>0)parts.push(`columns ${cols.map((c)=>`${esc(c)}`).join(", ")}`);let sort=str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]);if(sort!==void 0)parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER])!==void 0?` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}`:""}`);if(typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]==="number")parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`);return{kind:esc(`${l.type}.${l.subType}`),name:esc(l.name),detailHtml:parts.join(", ")}}projectionBlock(from,n){let ix=this.ix,rows=[],bases=new Set;for(let f of ix.fields(n.id)){if(f.extends!==void 0)bases.add(ix.ownerOf(f.extends));for(let o of ix.children(f.id).filter((c)=>c.type===TYPE_ORIGIN)){let def=this.originDefinition(from,o);for(let src of this.refLinks(o,ORIGIN_PASSTHROUGH_ATTR_FROM))bases.add(ix.ownerOf(src.id));rows.push({field:esc(f.name),origin:esc(`origin.${o.subType}`),definitionHtml:def})}}return{basesHtml:[...bases].filter((b)=>b!==n.id).sort(byCodeUnit2).map((b)=>this.link(from,b)).join(", "),origins:rows,hasOrigins:rows.length>0}}originDefinition(from,o){let a=o.attrs,ref=(name)=>this.attrValues(o,name).map((v)=>v.link!==null&&!v.link.unresolved?this.link(from,v.link.id,localName(v.text)):`${esc(localName(v.text))}`).join(", "),parts=[],agg=str(a[ORIGIN_AGGREGATE_ATTR_AGG]);if(agg!==void 0)parts.push(`${esc(agg)}(${ref(ORIGIN_AGGREGATE_ATTR_OF)})`);else if(a[ORIGIN_AGGREGATE_ATTR_OF]!==void 0)parts.push(`of ${ref(ORIGIN_AGGREGATE_ATTR_OF)}`);if(a[ORIGIN_PASSTHROUGH_ATTR_FROM]!==void 0)parts.push(`from ${ref(ORIGIN_PASSTHROUGH_ATTR_FROM)}`);if(a[ORIGIN_AGGREGATE_ATTR_VIA]!==void 0)parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`);if(a[ORIGIN_COMPUTED_ATTR_EXPR]!==void 0)parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`);if(a[ORIGIN_AGGREGATE_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`);return parts.join(" · ")}reportBlock(from,n){let a=n.attrs,fromId=this.refLinks(n,OBJECT_REPORT_ATTR_FROM)[0]?.id??str(a[OBJECT_REPORT_ATTR_FROM]),resolve2=(name,kindType)=>{let hit=[fromId!==void 0?`${fromId}.${name}`:void 0,`${n.package===""?"":`${n.package}::`}${name}`].filter((x)=>x!==void 0).find((c)=>this.ix.byId.get(c)?.type===kindType||this.ix.byId.has(c)&&name.includes("."));return hit!==void 0?this.link(from,hit,name):`${esc(name)}`},spine=str(a[OBJECT_REPORT_ATTR_SPINE]);return{fromHtml:this.refHtml(from,n,OBJECT_REPORT_ATTR_FROM),spineHtml:spine!==void 0?`${esc(spine)}`:"",dimensionsHtml:strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d)=>resolve2(d,TYPE_DIMENSION)).join(", "),measuresHtml:strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m)=>resolve2(m,TYPE_MEASURE)).join(", "),segmentHtml:strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s)=>resolve2(s,TYPE_SEGMENT)).join(", "),filterHtml:a[OBJECT_REPORT_ATTR_FILTER]!==void 0?`${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}`:""}}generatedGroups(id){let groups=new Map;for(let f of this.ix.generated(id))groups.set(f.generatedBy,[...groups.get(f.generatedBy)??[],f.path]);return[...groups.keys()].sort(byCodeUnit2).map((g)=>({generator:esc(g),files:(groups.get(g)??[]).map((p)=>esc(p))}))}node(n){let ix=this.ix,from=this.objectPage(n),kindLabel=`${n.type}.${n.subType}`,whyRows=this.whyRows(from,n),attrs=this.attrRows(from,n),referrers=[...(ix.top(n.id)?.referencedBy??[]).map((e)=>e.from.id),...ix.claims(n.id).map((c)=>this.topOf(c.req).node.id)],refBy=[...new Set(referrers.filter((id)=>id!==n.id))].sort(byCodeUnit2).map((id)=>this.link(from,id));return{id:esc(n.id),name:esc(n.name),kindLabel:esc(kindLabel),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › ${esc(kindLabel)}`,isAbstract:n.abstract===!0,description:this.description(n),extendsHtml:n.extends!==void 0?this.link(from,n.extends):"",attrs,hasAttrs:attrs.length>0,members:ix.children(n.id).map((c)=>({anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),nameHtml:ix.reqById.has(c.id)?this.link(from,c.id):esc(c.name===""?`#${c.order}`:c.name),attrsHtml:this.attrRows(from,c).map((a)=>`@${a.name} ${a.valueHtml}`).join("
    "),below:ix.children(c.id).length})),hasMembers:ix.children(n.id).length>0,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(from,n){return n.view.attrs.map((a)=>{let links=a.values.filter((v)=>v.link!==null&&!v.link.unresolved);return{name:esc(a.name),valueHtml:links.length>0&&links.length===a.values.length?links.map((v)=>this.link(from,v.link.id)).join(", "):`${esc(fmt(a.value))}`}})}prompt(n,text){let ix=this.ix,from=this.objectPage(n),payloadId=this.refLinks(n,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id,replyId=this.refLinks(n,TEMPLATE_ATTR_RESPONSE_REF)[0]?.id,vars=text!==void 0?templateVariables(text):void 0,payload=payloadId!==void 0?ix.byId.get(payloadId):void 0,reply=replyId!==void 0?ix.byId.get(replyId):void 0,payloadRows=payload!==void 0?ix.fields(payload.id).map((f)=>({name:esc(f.name),requiredHtml:f.attrs[FIELD_ATTR_REQUIRED]===!0?'required':"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)!==""?` → ${this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)}`:"",usedHtml:vars===void 0?'text not read':vars.has(f.name)?"yes":'no'})):[],replyRows=reply!==void 0?ix.fields(reply.id).map((f)=>({name:esc(f.name),type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),valuesHtml:f.subType===FIELD_SUBTYPE_ENUM?`
    ${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
    `:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(` +`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var FREQUENCY_HOURLY="hourly",FREQUENCY_DAILY="daily",FREQUENCY_WEEKLY="weekly",FREQUENCY_MONTHLY="monthly";var AVAILABLE_BY_PATTERNS={[FREQUENCY_HOURLY]:/^:[0-5][0-9]$/,[FREQUENCY_DAILY]:/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/,[FREQUENCY_WEEKLY]:/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/,[FREQUENCY_MONTHLY]:/^(?:[1-9]|1[0-9]|2[0-8]) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/},AVAILABLE_BY_EXAMPLES={[FREQUENCY_HOURLY]:":15",[FREQUENCY_DAILY]:"03:00",[FREQUENCY_WEEKLY]:"Mon 06:00",[FREQUENCY_MONTHLY]:"1 06:00"};var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'
    ';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return``}function pct(x){return`${(Math.round(x*1e4)/100).toString()}%`}function legendHtml(withUnclaimed){return`
    ${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
    `}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
    ${values.map(esc).join(" | ")}
    `:"",column:esc(str(f.attrs[FIELD_ATTR_COLUMN])??""),flagsHtml:flags.map((x)=>`${esc(x)}`).join(""),claimsHtml:claims.map((c)=>`${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
    ")}}keyRow(from,c){let fields=strs(c.attrs[IDENTITY_ATTR_FIELDS]),target=this.refHtml(from,c,IDENTITY_REFERENCE_ATTR_REFERENCES)||this.refHtml(from,c,RELATIONSHIP_ATTR_OBJECT_REF),through=str(c.attrs[RELATIONSHIP_ATTR_THROUGH]),card=str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]),shape=c.type===TYPE_RELATIONSHIP?[card,through!==void 0?`through ${localName(through)}`:void 0].filter((x)=>x!==void 0).join(", "):`(${fields.join(", ")})`;return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),inheritedHtml:c.inheritedFrom!==void 0?'inherited':"",shape:esc(shape),targetHtml:target!==""?`→ ${target}`:""}}reportingRow(from,c){let a=c.attrs,parts=[],agg=str(a[REPORTING_ATTR_AGG]),of=this.refHtml(from,c,REPORTING_ATTR_OF,localName);if(agg!==void 0)parts.push(`${esc(agg)}(${of})`);else if(of!=="")parts.push(`of ${of}`);let num=str(a[REPORTING_ATTR_NUMERATOR]),den=str(a[REPORTING_ATTR_DENOMINATOR]);if(num!==void 0&&den!==void 0)parts.push(`${esc(num)} ÷ ${esc(den)}`);let via=str(a[REPORTING_ATTR_VIA]);if(via!==void 0)parts.push(`via ${esc(localName(via))}`);let grains=strs(a[REPORTING_ATTR_GRAINS]);if(grains.length>0)parts.push(`grains ${grains.map((g)=>`${esc(g)}`).join(" ")}`);let seg=str(a[REPORTING_ATTR_SEGMENT]);if(seg!==void 0)parts.push(`segment ${esc(seg)}`);if(a[REPORTING_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`);if(a[REPORTING_ATTR_DEFAULT]!==void 0)parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`);return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),definitionHtml:parts.join(" · ")}}layoutRow(l){let parts=[],cols=strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]);if(cols.length>0)parts.push(`columns ${cols.map((c)=>`${esc(c)}`).join(", ")}`);let sort=str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]);if(sort!==void 0)parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER])!==void 0?` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}`:""}`);if(typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]==="number")parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`);return{kind:esc(`${l.type}.${l.subType}`),name:esc(l.name),detailHtml:parts.join(", ")}}projectionBlock(from,n){let ix=this.ix,rows=[],bases=new Set;for(let f of ix.fields(n.id)){if(f.extends!==void 0)bases.add(ix.ownerOf(f.extends));for(let o of ix.children(f.id).filter((c)=>c.type===TYPE_ORIGIN)){let def=this.originDefinition(from,o);for(let src of this.refLinks(o,ORIGIN_PASSTHROUGH_ATTR_FROM))bases.add(ix.ownerOf(src.id));rows.push({field:esc(f.name),origin:esc(`origin.${o.subType}`),definitionHtml:def})}}return{basesHtml:[...bases].filter((b)=>b!==n.id).sort(byCodeUnit2).map((b)=>this.link(from,b)).join(", "),origins:rows,hasOrigins:rows.length>0}}originDefinition(from,o){let a=o.attrs,ref=(name)=>this.attrValues(o,name).map((v)=>v.link!==null&&!v.link.unresolved?this.link(from,v.link.id,localName(v.text)):`${esc(localName(v.text))}`).join(", "),parts=[],agg=str(a[ORIGIN_AGGREGATE_ATTR_AGG]);if(agg!==void 0)parts.push(`${esc(agg)}(${ref(ORIGIN_AGGREGATE_ATTR_OF)})`);else if(a[ORIGIN_AGGREGATE_ATTR_OF]!==void 0)parts.push(`of ${ref(ORIGIN_AGGREGATE_ATTR_OF)}`);if(a[ORIGIN_PASSTHROUGH_ATTR_FROM]!==void 0)parts.push(`from ${ref(ORIGIN_PASSTHROUGH_ATTR_FROM)}`);if(a[ORIGIN_AGGREGATE_ATTR_VIA]!==void 0)parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`);if(a[ORIGIN_COMPUTED_ATTR_EXPR]!==void 0)parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`);if(a[ORIGIN_AGGREGATE_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`);return parts.join(" · ")}reportBlock(from,n){let a=n.attrs,fromId=this.refLinks(n,OBJECT_REPORT_ATTR_FROM)[0]?.id??str(a[OBJECT_REPORT_ATTR_FROM]),resolve2=(name,kindType)=>{let hit=[fromId!==void 0?`${fromId}.${name}`:void 0,`${n.package===""?"":`${n.package}::`}${name}`].filter((x)=>x!==void 0).find((c)=>this.ix.byId.get(c)?.type===kindType||this.ix.byId.has(c)&&name.includes("."));return hit!==void 0?this.link(from,hit,name):`${esc(name)}`},spine=str(a[OBJECT_REPORT_ATTR_SPINE]);return{fromHtml:this.refHtml(from,n,OBJECT_REPORT_ATTR_FROM),spineHtml:spine!==void 0?`${esc(spine)}`:"",dimensionsHtml:strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d)=>resolve2(d,TYPE_DIMENSION)).join(", "),measuresHtml:strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m)=>resolve2(m,TYPE_MEASURE)).join(", "),segmentHtml:strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s)=>resolve2(s,TYPE_SEGMENT)).join(", "),filterHtml:a[OBJECT_REPORT_ATTR_FILTER]!==void 0?`${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}`:""}}generatedGroups(id){let groups=new Map;for(let f of this.ix.generated(id))groups.set(f.generatedBy,[...groups.get(f.generatedBy)??[],f.path]);return[...groups.keys()].sort(byCodeUnit2).map((g)=>({generator:esc(g),files:(groups.get(g)??[]).map((p)=>esc(p))}))}node(n){let ix=this.ix,from=this.objectPage(n),kindLabel=`${n.type}.${n.subType}`,whyRows=this.whyRows(from,n),attrs=this.attrRows(from,n),referrers=[...(ix.top(n.id)?.referencedBy??[]).map((e)=>e.from.id),...ix.claims(n.id).map((c)=>this.topOf(c.req).node.id)],refBy=[...new Set(referrers.filter((id)=>id!==n.id))].sort(byCodeUnit2).map((id)=>this.link(from,id));return{id:esc(n.id),name:esc(n.name),kindLabel:esc(kindLabel),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › ${esc(kindLabel)}`,isAbstract:n.abstract===!0,description:this.description(n),extendsHtml:n.extends!==void 0?this.link(from,n.extends):"",attrs,hasAttrs:attrs.length>0,members:ix.children(n.id).map((c)=>({anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),nameHtml:ix.reqById.has(c.id)?this.link(from,c.id):esc(c.name===""?`#${c.order}`:c.name),attrsHtml:this.attrRows(from,c).map((a)=>`@${a.name} ${a.valueHtml}`).join("
    "),below:ix.children(c.id).length})),hasMembers:ix.children(n.id).length>0,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(from,n){return n.view.attrs.map((a)=>{let links=a.values.filter((v)=>v.link!==null&&!v.link.unresolved);return{name:esc(a.name),valueHtml:links.length>0&&links.length===a.values.length?links.map((v)=>this.link(from,v.link.id)).join(", "):`${esc(fmt(a.value))}`}})}prompt(n,text){let ix=this.ix,from=this.objectPage(n),payloadId=this.refLinks(n,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id,replyId=this.refLinks(n,TEMPLATE_ATTR_RESPONSE_REF)[0]?.id,vars=text!==void 0?templateVariables(text):void 0,payload=payloadId!==void 0?ix.byId.get(payloadId):void 0,reply=replyId!==void 0?ix.byId.get(replyId):void 0,payloadRows=payload!==void 0?ix.fields(payload.id).map((f)=>({name:esc(f.name),requiredHtml:f.attrs[FIELD_ATTR_REQUIRED]===!0?'required':"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)!==""?` → ${this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)}`:"",usedHtml:vars===void 0?'text not read':vars.has(f.name)?"yes":'no'})):[],replyRows=reply!==void 0?ix.fields(reply.id).map((f)=>({name:esc(f.name),type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),valuesHtml:f.subType===FIELD_SUBTYPE_ENUM?`
    ${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
    `:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(` `).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
      ${tops.map((r)=>this.treeNode(page,r)).join("")}
    `:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
  • ${`
    ${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}${dispositionPill(r)}${verdictBadge(r)}${bar}${links.join("")}
    ${esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??"")}
    `}${r.children.length>0?`
      ${r.children.map((c)=>this.treeNode(from,c)).join("")}
    `:""}
  • `}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`${cols.map((o)=>`
    ${this.link(from,o.id)}
    `).join("")}`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLink(from,top)}${cols.map(()=>'').join("")}`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`${levelBadge(r)}${esc(label)}${cols.map((o)=>tg.has(o.id)?`${statusGlyph(r.status)}`:'').join("")}`)}}return{tableHtml:rows.length>0?`${head}${rows.join("")}
    `:"",hasRows:rows.length>0,hasRequirements:ix.hasRequirements()}}trace(){let starts=this.ix.requirements.filter((r)=>r.level!==void 0&&r.level<=REQUIREMENT_LEVEL_SERVICE),fallback=starts.length===0?this.ix.topRequirements:[];return{options:[...starts,...fallback].map((r)=>({value:esc(r.node.id),label:esc(`${" ".repeat(Math.max(0,(r.level??1)-1))}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)}`)})),hasStarts:starts.length+fallback.length>0,hasUsage:!1}}gaps(){let ix=this.ix,from=PAGE_GAPS,cards=[],card=(title,count,source,why,bodyHtml)=>{cards.push({title:esc(title),count:esc(String(count)),source:esc(source),isGate:source==="meta verify",whyHtml:why,bodyHtml})};if(ix.view.sources.requirements){let findingsOf=(gate2)=>[...ix.requirements.flatMap((req)=>req.req.diagnostics.filter((d)=>d.source===GATE_SOURCE===gate2).map((d)=>({req,d}))),...ix.view.advisories.filter((d)=>d.path===""&&d.source===GATE_SOURCE===gate2).map((d)=>({d}))],table=(rows,chip)=>rows.length===0?'
    None.
    ':`${rows.map(({req,d})=>``).join("")}
    ${esc(d.code)}${req!==void 0?this.reqLink(from,req):""}
    ${esc(d.message)}
    `,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
    None.
    ');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
    None.
    ')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
    Not scanned.
    ');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
    No prompt text was read.
    ':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
    None.
    ':`
      ${items.map((i)=>`
    • ${i}
    • `).join("")}
    `}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found

    No such page

    ${escapeHtml2(r.path)} is not a page of this model.

    Overview

    `,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="

    No model yet

    The explorer is waiting for the running application's docs view.

    ";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="

    No model

    The source parameter is not a URL.

    ",paintLive();return}follow(source);return}if(!build())document.body.innerHTML="

    No model

    explorer-model.js did not load. Run meta gen to write it beside this page.

    ";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})(); diff --git a/server/typescript/packages/metadata/src/core/api/api-constants.ts b/server/typescript/packages/metadata/src/core/api/api-constants.ts index bc9eef468e..a90b56be6c 100644 --- a/server/typescript/packages/metadata/src/core/api/api-constants.ts +++ b/server/typescript/packages/metadata/src/core/api/api-constants.ts @@ -15,19 +15,39 @@ export { TYPE_API, TYPE_BINDING, TYPE_OPERATION }; /** A request/response surface whose children are operations. The axis is the * interaction model, never the protocol (ADR-0030). */ export const API_SUBTYPE_OPERATIONAL = "operational"; -export const API_SUBTYPES = [API_SUBTYPE_OPERATIONAL] as const; +/** Events the provider publishes; children are `operation.event`. */ +export const API_SUBTYPE_EVENTING = "eventing"; +/** Datasets delivered as files on a schedule; children are `operation.export` / `.import`. */ +export const API_SUBTYPE_BATCH = "batch"; +export const API_SUBTYPES = [API_SUBTYPE_OPERATIONAL, API_SUBTYPE_EVENTING, API_SUBTYPE_BATCH] as const; export type ApiSubType = (typeof API_SUBTYPES)[number]; /** Changes state; takes an `object.value`. */ export const OPERATION_SUBTYPE_COMMAND = "command"; /** Reads; returns a projection, entity or value. */ export const OPERATION_SUBTYPE_QUERY = "query"; -export const OPERATION_SUBTYPES = [OPERATION_SUBTYPE_COMMAND, OPERATION_SUBTYPE_QUERY] as const; +/** Something that happened; the payload is its `@outputRef`. */ +export const OPERATION_SUBTYPE_EVENT = "event"; +/** A file the provider publishes on a schedule; rows are its `@outputRef`. */ +export const OPERATION_SUBTYPE_EXPORT = "export"; +/** A file the provider accepts on a schedule; rows are its `@inputRef`. */ +export const OPERATION_SUBTYPE_IMPORT = "import"; +export const OPERATION_SUBTYPES = [ + OPERATION_SUBTYPE_COMMAND, + OPERATION_SUBTYPE_QUERY, + OPERATION_SUBTYPE_EVENT, + OPERATION_SUBTYPE_EXPORT, + OPERATION_SUBTYPE_IMPORT, +] as const; export type OperationSubType = (typeof OPERATION_SUBTYPES)[number]; /** The HTTP binding of an operation (overrides the derived method and path). */ export const BINDING_SUBTYPE_REST = "rest"; -export const BINDING_SUBTYPES = [BINDING_SUBTYPE_REST] as const; +/** How an event travels (optionally pinning the wire protocol). */ +export const BINDING_SUBTYPE_MESSAGING = "messaging"; +/** How an export's or import's file is delivered. */ +export const BINDING_SUBTYPE_FILE = "file"; +export const BINDING_SUBTYPES = [BINDING_SUBTYPE_REST, BINDING_SUBTYPE_MESSAGING, BINDING_SUBTYPE_FILE] as const; export type BindingSubType = (typeof BINDING_SUBTYPES)[number]; // --------------------------------------------------------------------------- @@ -60,6 +80,55 @@ export const BINDING_ATTR_PATH = "path"; export const HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const; export type HttpMethod = (typeof HTTP_METHODS)[number]; +// --------------------------------------------------------------------------- +// Attrs on operation.event / .export / .import +// --------------------------------------------------------------------------- + +/** `operation.event @key` — the payload field whose events stay in order. */ +export const OPERATION_ATTR_KEY = "key"; +/** `operation.export|import @frequency`. */ +export const OPERATION_ATTR_FREQUENCY = "frequency"; +/** `operation.export @availableBy` — the UTC time each file is in place by. */ +export const OPERATION_ATTR_AVAILABLE_BY = "availableBy"; +export const FREQUENCY_HOURLY = "hourly"; +export const FREQUENCY_DAILY = "daily"; +export const FREQUENCY_WEEKLY = "weekly"; +export const FREQUENCY_MONTHLY = "monthly"; +export const FREQUENCIES = [FREQUENCY_HOURLY, FREQUENCY_DAILY, FREQUENCY_WEEKLY, FREQUENCY_MONTHLY] as const; +export type Frequency = (typeof FREQUENCIES)[number]; +/** The form of `@availableBy` for each `@frequency`: hourly `:MM`, daily `HH:MM`, weekly + * `Ddd HH:MM`, monthly `D HH:MM` with the day 1 to 28 (every month has it). */ +export const AVAILABLE_BY_PATTERNS: Readonly> = { + [FREQUENCY_HOURLY]: /^:[0-5][0-9]$/, + [FREQUENCY_DAILY]: /^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/, + [FREQUENCY_WEEKLY]: /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/, + [FREQUENCY_MONTHLY]: /^(?:[1-9]|1[0-9]|2[0-8]) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/, +}; +/** An example of each form, for messages. */ +export const AVAILABLE_BY_EXAMPLES: Readonly> = { + [FREQUENCY_HOURLY]: ":15", + [FREQUENCY_DAILY]: "03:00", + [FREQUENCY_WEEKLY]: "Mon 06:00", + [FREQUENCY_MONTHLY]: "1 06:00", +}; + +// --------------------------------------------------------------------------- +// Attrs on binding.messaging / binding.file +// --------------------------------------------------------------------------- + +export const BINDING_ATTR_PROTOCOL = "protocol"; +export const BINDING_ATTR_TRANSPORT = "transport"; +export const BINDING_ATTR_FILE_NAME = "fileName"; +export const BINDING_ATTR_FORMAT = "format"; +export const BINDING_ATTR_COMPRESSION = "compression"; +export const BINDING_ATTR_COMPLETION = "completion"; +export const BINDING_ATTR_ENCRYPTION = "encryption"; +/** The placeholders a `binding.file @fileName` may hold: the UTC start of the run, as + * `YYYY-MM-DD` and `YYYYMMDDTHHMMSSZ`. */ +export const FILE_NAME_PLACEHOLDERS = ["date", "timestamp"] as const; +/** The suffix of the marker object `completion: marker` puts beside a finished file. */ +export const COMPLETION_MARKER_SUFFIX = ".done"; + /** Names a declared operation or a transition may not take: they are the derived CRUD * verbs of the same service (ERR_TRANSITION_NAME_COLLISION). */ export const RESERVED_OPERATION_NAMES = ["create", "get", "list", "update", "delete"] as const; diff --git a/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts b/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts index b1166a7f33..d230e5437d 100644 --- a/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts @@ -25,26 +25,86 @@ export const API_DEFINITION: ProviderDefinition = { "children": [ { "type": "operation", - "subType": "*", + "subType": "command", + "name": "*", + "min": 0, + "max": null, + "description": "The commands this surface exposes." + }, + { + "type": "operation", + "subType": "query", + "name": "*", + "min": 0, + "max": null, + "description": "The queries this surface exposes." + } + ] + }, + { + "type": "api", + "subType": "eventing", + "extendsBase": true, + "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.", + "rules": "Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.", + "children": [ + { + "type": "operation", + "subType": "event", + "name": "*", + "min": 0, + "max": null, + "description": "The events this surface publishes." + } + ] + }, + { + "type": "api", + "subType": "batch", + "extendsBase": true, + "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.", + "rules": "Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.", + "children": [ + { + "type": "operation", + "subType": "export", + "name": "*", + "min": 0, + "max": null, + "description": "The datasets the provider publishes." + }, + { + "type": "operation", + "subType": "import", "name": "*", "min": 0, "max": null, - "description": "The operations this surface exposes." + "description": "The datasets the provider accepts." } ] }, { "type": "operation", "subType": "base", - "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.", + "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.", + "children": [] + }, + { + "type": "operation", + "subType": "command", + "extendsBase": true, + "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.", "children": [ { "type": "binding", - "subType": "*", + "subType": "rest", "name": "*", "min": 0, "max": null, - "description": "Optional protocol bindings. Only needed to override the derived method and path." + "description": "Optional HTTP bindings. Only needed to override the derived method and path." }, { "type": "attr", @@ -85,16 +145,7 @@ export const API_DEFINITION: ProviderDefinition = { "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." - } - ] - }, - { - "type": "operation", - "subType": "command", - "extendsBase": true, - "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", - "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.", - "children": [ + }, { "type": "attr", "subType": "string", @@ -122,6 +173,54 @@ export const API_DEFINITION: ProviderDefinition = { "description": "A named operation that reads. Returns an `object.projection` (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", "whenToUse": "A read with its own name and shape beyond derived get and list: my open requests, the dashboard summary.", "children": [ + { + "type": "binding", + "subType": "rest", + "name": "*", + "min": 0, + "max": null, + "description": "Optional HTTP bindings. Only needed to override the derived method and path." + }, + { + "type": "attr", + "subType": "string", + "name": "inputRef", + "min": 0, + "max": 1, + "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." + }, + { + "type": "attr", + "subType": "string", + "name": "outputRef", + "min": 0, + "max": 1, + "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." + }, + { + "type": "attr", + "subType": "string", + "name": "objectRef", + "min": 0, + "max": 1, + "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." + }, + { + "type": "attr", + "subType": "string", + "name": "permission", + "min": 0, + "max": 1, + "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." + }, + { + "type": "attr", + "subType": "boolean", + "name": "public", + "min": 0, + "max": 1, + "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." + }, { "type": "attr", "subType": "boolean", @@ -132,6 +231,125 @@ export const API_DEFINITION: ProviderDefinition = { } ] }, + { + "type": "operation", + "subType": "event", + "extendsBase": true, + "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Each distinct fact a consumer may react to: placed, delivered, cancelled.", + "children": [ + { + "type": "binding", + "subType": "messaging", + "name": "*", + "min": 0, + "max": null, + "description": "Optional messaging bindings: how the event travels." + }, + { + "type": "attr", + "subType": "string", + "name": "outputRef", + "min": 1, + "max": 1, + "description": "The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." + }, + { + "type": "attr", + "subType": "string", + "name": "key", + "min": 0, + "max": 1, + "description": "The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised." + } + ] + }, + { + "type": "operation", + "subType": "export", + "extendsBase": true, + "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.", + "children": [ + { + "type": "binding", + "subType": "file", + "name": "*", + "min": 0, + "max": null, + "description": "Optional file bindings: where the file is and how it is written." + }, + { + "type": "attr", + "subType": "string", + "name": "outputRef", + "min": 1, + "max": 1, + "description": "The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." + }, + { + "type": "attr", + "subType": "string", + "name": "frequency", + "min": 1, + "max": 1, + "allowedValues": [ + "hourly", + "daily", + "weekly", + "monthly" + ], + "description": "How often a new file appears: hourly, daily, weekly or monthly." + }, + { + "type": "attr", + "subType": "string", + "name": "availableBy", + "min": 0, + "max": 1, + "description": "The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised." + } + ] + }, + { + "type": "operation", + "subType": "import", + "extendsBase": true, + "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.", + "children": [ + { + "type": "binding", + "subType": "file", + "name": "*", + "min": 0, + "max": null, + "description": "Optional file bindings: where the file is delivered and how it is written." + }, + { + "type": "attr", + "subType": "string", + "name": "inputRef", + "min": 1, + "max": 1, + "description": "The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE." + }, + { + "type": "attr", + "subType": "string", + "name": "frequency", + "min": 1, + "max": 1, + "allowedValues": [ + "hourly", + "daily", + "weekly", + "monthly" + ], + "description": "How often a new file is expected: hourly, daily, weekly or monthly." + } + ] + }, { "type": "binding", "subType": "base", @@ -169,6 +387,119 @@ export const API_DEFINITION: ProviderDefinition = { "description": "A path template. Its `{name}` placeholders must be exactly the target's primary key fields when the operation is keyed, and there must be none when it is not; two declared bindings of one API may not share the method and path (ERR_BINDING_PATH_MISMATCH)." } ] + }, + { + "type": "binding", + "subType": "messaging", + "extendsBase": true, + "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "protocol", + "min": 0, + "max": 1, + "allowedValues": [ + "kafka", + "amqp", + "mqtt", + "sqs" + ], + "description": "The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks." + } + ] + }, + { + "type": "binding", + "subType": "file", + "extendsBase": true, + "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Every export and import whose file conventions two parties must agree on.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "transport", + "min": 1, + "max": 1, + "allowedValues": [ + "sftp", + "objectStore" + ], + "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." + }, + { + "type": "attr", + "subType": "string", + "name": "path", + "min": 0, + "max": 1, + "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." + }, + { + "type": "attr", + "subType": "string", + "name": "fileName", + "min": 1, + "max": 1, + "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." + }, + { + "type": "attr", + "subType": "string", + "name": "format", + "min": 1, + "max": 1, + "allowedValues": [ + "csv", + "jsonLines", + "parquet" + ], + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + }, + { + "type": "attr", + "subType": "string", + "name": "compression", + "min": 0, + "max": 1, + "allowedValues": [ + "none", + "gzip" + ], + "default": "none", + "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." + }, + { + "type": "attr", + "subType": "string", + "name": "completion", + "min": 0, + "max": 1, + "allowedValues": [ + "rename", + "marker", + "none" + ], + "default": "none", + "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." + }, + { + "type": "attr", + "subType": "string", + "name": "encryption", + "min": 0, + "max": 1, + "allowedValues": [ + "none", + "pgp" + ], + "default": "none", + "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." + } + ] } ], "extends": [ diff --git a/server/typescript/packages/metadata/src/core/systems/systems-constants.ts b/server/typescript/packages/metadata/src/core/systems/systems-constants.ts index 97243bd83d..578512c2b9 100644 --- a/server/typescript/packages/metadata/src/core/systems/systems-constants.ts +++ b/server/typescript/packages/metadata/src/core/systems/systems-constants.ts @@ -97,12 +97,16 @@ export type GrantSubType = (typeof GRANT_SUBTYPES)[number]; export const SYSTEM_ATTR_OWNER = "owner"; /** `app @runsAs` — a `role.service`, by name. */ export const APP_ATTR_RUNS_AS = "runsAs"; +/** `app @provides` — the APIs the app provides (hosts), by name. */ +export const APP_ATTR_PROVIDES = "provides"; /** `app.service @public`. */ export const APP_ATTR_PUBLIC = "public"; /** `app.client @shell`. */ export const APP_ATTR_SHELL = "shell"; /** `app.job @schedule` — a five-field cron expression in UTC. */ export const APP_ATTR_SCHEDULE = "schedule"; +/** `app.job @extracts` — the entity or projection the job reads its rows from, by name. */ +export const APP_ATTR_EXTRACTS = "extracts"; /** `build.image @repository`. */ export const BUILD_ATTR_REPOSITORY = "repository"; /** `resource @residency` — `free` (default) or `confined`. */ @@ -121,6 +125,9 @@ export const RESOURCE_ATTR_PUBLIC_READ = "publicRead"; export const RESOURCE_ATTR_ORDERED = "ordered"; /** `resource.queue @deadLetter`. */ export const RESOURCE_ATTR_DEAD_LETTER = "deadLetter"; +/** `resource.stream|queue|objectStore @carries` — the APIs that travel on the resource, by name + * (an eventing API on a stream or queue, a batch API on an object store). */ +export const RESOURCE_ATTR_CARRIES = "carries"; /** `role @memberOf` — `role.group` nodes, by name. */ export const ROLE_ATTR_MEMBER_OF = "memberOf"; /** `role @credential` — the name of an adopted key, never a value. */ diff --git a/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts b/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts index bab4c24f86..eecbd0ecc0 100644 --- a/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts @@ -146,6 +146,18 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = { "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." + }, + { + "type": "attr", + "subType": "string", + "name": "provides", + "isArray": true, + "min": 0, + "max": 1, + "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", + "ref": { + "targetType": "api" + } } ] }, @@ -180,6 +192,33 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = { "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." + }, + { + "type": "attr", + "subType": "string", + "name": "extracts", + "min": 0, + "max": 1, + "description": "The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object.", + "ref": { + "targetType": "object", + "targetSubTypes": [ + "entity", + "projection" + ] + } + }, + { + "type": "attr", + "subType": "string", + "name": "provides", + "isArray": true, + "min": 0, + "max": 1, + "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", + "ref": { + "targetType": "api" + } } ] }, @@ -274,6 +313,21 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = { "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." + }, + { + "type": "attr", + "subType": "string", + "name": "carries", + "isArray": true, + "min": 0, + "max": 1, + "description": "The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`.", + "ref": { + "targetType": "api", + "targetSubTypes": [ + "batch" + ] + } } ] }, @@ -313,6 +367,21 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = { "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." + }, + { + "type": "attr", + "subType": "string", + "name": "carries", + "isArray": true, + "min": 0, + "max": 1, + "description": "The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", + "ref": { + "targetType": "api", + "targetSubTypes": [ + "eventing" + ] + } } ] }, @@ -321,7 +390,24 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = { "subType": "stream", "extendsBase": true, "description": "A retained, ordered log that many consumers read, each at its own position. A message can be read again.", - "whenToUse": "Events several consumers read independently, or read again." + "whenToUse": "Events several consumers read independently, or read again.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "carries", + "isArray": true, + "min": 0, + "max": 1, + "description": "The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", + "ref": { + "targetType": "api", + "targetSubTypes": [ + "eventing" + ] + } + } + ] }, { "type": "resource", diff --git a/server/typescript/packages/metadata/src/core/transition/commands.ts b/server/typescript/packages/metadata/src/core/transition/commands.ts index f1583cfa8a..5612dacf3b 100644 --- a/server/typescript/packages/metadata/src/core/transition/commands.ts +++ b/server/typescript/packages/metadata/src/core/transition/commands.ts @@ -13,6 +13,7 @@ import { TYPE_API, TYPE_OBJECT, TYPE_OPERATION } from "../../shared/base-types.j import { OBJECT_SUBTYPE_ENTITY } from "../object/object-constants.js"; import { effectivePackageOf, topLevelNodeOf } from "../../naming-refs.js"; import { + API_SUBTYPE_OPERATIONAL, OPERATION_ATTR_PERMISSION, OPERATION_ATTR_PUBLIC, OPERATION_ATTR_TRANSITIONS, @@ -26,10 +27,13 @@ export function modelEntities(root: MetaData): MetaData[] { return root.children().filter((c) => c.type === TYPE_OBJECT && c.subType === OBJECT_SUBTYPE_ENTITY); } -/** Every declared operation, across every `api.*` of the root, in model order. */ +/** Every declared command and query, across every `api.operational` of the root, in model order. + * An `api.eventing` or `api.batch` is not a request/response surface: its operations have no + * target, claim no transition, ask no policy and are served by no route, so nothing that reads + * this list sees them. */ export function modelOperations(root: MetaData): MetaData[] { return root.children() - .filter((c) => c.type === TYPE_API) + .filter((c) => c.type === TYPE_API && c.subType === API_SUBTYPE_OPERATIONAL) .flatMap((api) => api.children().filter((c) => c.type === TYPE_OPERATION)); } diff --git a/server/typescript/packages/metadata/src/loader/rules-validation.ts b/server/typescript/packages/metadata/src/loader/rules-validation.ts index c14342ccd5..ac1fe10b0e 100644 --- a/server/typescript/packages/metadata/src/loader/rules-validation.ts +++ b/server/typescript/packages/metadata/src/loader/rules-validation.ts @@ -15,8 +15,8 @@ // Rules: // L1 ERR_TRANSITION_NOT_ON_ENTITY a transition under an enum field not declared on an object.entity // L2 ERR_TRANSITION_NOT_ON_ENTITY a concrete entity with a lifecycle and a source, none of them writable -// (on the entity). An entity with no source at all is inert: its -// lifecycle loads and derives nothing (lifecycleIsLive). +// (on the entity). An entity with no relational source (none, or +// only source.document / source.search) is inert: its lifecycle loads and derives nothing (lifecycleIsLive). // L3 ERR_LIFECYCLE_NO_INITIAL an enum field declaring transitions has no @default // L4 ERR_TRANSITION_UNKNOWN_STATE a @from or @to value is not one of the enum's @values // L5 ERR_TRANSITION_NAME_COLLISION a transition named create/get/list/update/delete, in any case @@ -53,6 +53,13 @@ // (a keyed operation) or are not empty (an unkeyed one) // B2 ERR_BINDING_PATH_MISMATCH two binding.rest of one API declaring a @path have the same // effective method and the same path once placeholder names are ignored +// +// Operations of an api.eventing or api.batch (event, export, import) are not commands or queries: +// only O1 applies to them, with two rules of their own: +// D1 ERR_BAD_ATTR_VALUE an operation.export @availableBy does not have the form its +// @frequency gives (AVAILABLE_BY_PATTERNS) +// D2 ERR_BAD_ATTR_VALUE a binding.file @fileName holds a placeholder other than {date} or +// {timestamp}, or an unclosed brace import type { MetaData } from "../shared/meta-data.js"; import type { MetaObject } from "../core/object/meta-object.js"; @@ -69,9 +76,19 @@ import { import { FIELD_ATTR_DEFAULT, FIELD_ATTR_VALUES, FIELD_SUBTYPE_ENUM } from "../core/field/field-constants.js"; import { OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_VALUE } from "../core/object/object-constants.js"; import { + API_SUBTYPE_OPERATIONAL, + AVAILABLE_BY_EXAMPLES, + AVAILABLE_BY_PATTERNS, + BINDING_ATTR_FILE_NAME, BINDING_ATTR_METHOD, BINDING_ATTR_PATH, + BINDING_SUBTYPE_FILE, BINDING_SUBTYPE_REST, + FILE_NAME_PLACEHOLDERS, + FREQUENCIES, + type Frequency, + OPERATION_ATTR_AVAILABLE_BY, + OPERATION_ATTR_FREQUENCY, BUSINESS_ERROR_CODE_PATTERN, PERMISSION_NAME_PATTERN, OPERATION_ATTR_ERRORS, @@ -280,27 +297,7 @@ function checkOperation(op: MetaData, sink: Sink): void { sink.add(op, "ERR_BAD_ATTR_VALUE", `operation.${op.subType} "${label(op)}" @errors: ${why}.`); } - // O1 — shapes. - const inputRef = op.attr(OPERATION_ATTR_INPUT_REF); - if (typeof inputRef === "string") { - const input = resolveObjectOn(op, inputRef); - if (input === undefined || input.subType !== OBJECT_SUBTYPE_VALUE) { - sink.add(op, "ERR_OPERATION_SHAPE", - `operation.${op.subType} "${label(op)}" @inputRef "${inputRef}" ${input === undefined ? "names no object" : `is an object.${input.subType}`}; an operation's input is an object.value.`); - return; - } - } - const outputRef = op.attr(OPERATION_ATTR_OUTPUT_REF); - if (typeof outputRef === "string") { - const output = resolveObjectOn(op, outputRef); - const legal = output !== undefined && - [OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_VALUE].includes(output.subType); - if (!legal) { - sink.add(op, "ERR_OPERATION_SHAPE", - `operation.${op.subType} "${label(op)}" @outputRef "${outputRef}" ${output === undefined ? "names no object" : `is an object.${output.subType}`}; an operation returns an object.entity, object.projection or object.value.`); - return; - } - } + if (!checkShapes(op, sink)) return; // O2, O3 — the target. const derived = deriveOperationTarget(op)?.entity; @@ -357,6 +354,65 @@ function checkOperation(op: MetaData, sink: Sink): void { } } +/** The checks for one operation of an api.eventing or api.batch: its shapes (O1), the + * form of an export's @availableBy (D1) and the placeholders of each binding.file @fileName (D2). */ +function checkDeliveryOperation(op: MetaData, sink: Sink): void { + if (!checkShapes(op, sink)) return; + const frequency = op.attr(OPERATION_ATTR_FREQUENCY); + const availableBy = op.attr(OPERATION_ATTR_AVAILABLE_BY); + if (typeof availableBy === "string" && typeof frequency === "string" && + (FREQUENCIES as readonly string[]).includes(frequency) && + !AVAILABLE_BY_PATTERNS[frequency as Frequency].test(availableBy)) { + sink.add(op, "ERR_BAD_ATTR_VALUE", + `operation.${op.subType} "${label(op)}" @availableBy "${availableBy}" is not a ${frequency} time; a ${frequency} file's @availableBy is written like "${AVAILABLE_BY_EXAMPLES[frequency as Frequency]}" (UTC).`); + } + // ADR-0039: own — a binding is checked on the operation that declares it. + for (const b of op.ownChildren()) { + if (b.type !== TYPE_BINDING || b.subType !== BINDING_SUBTYPE_FILE) continue; + const fileName = b.attr(BINDING_ATTR_FILE_NAME); + if (typeof fileName !== "string") continue; + const bad = fileNamePlaceholderProblem(fileName); + if (bad !== undefined) { + sink.add(b, "ERR_BAD_ATTR_VALUE", + `binding.file on "${label(b)}" @fileName "${fileName}" ${bad}; the placeholders are {${FILE_NAME_PLACEHOLDERS.join("} and {")}}.`); + } + } +} + +/** What is wrong with a @fileName's placeholders, or undefined when nothing is. */ +function fileNamePlaceholderProblem(fileName: string): string | undefined { + for (const m of fileName.matchAll(/\{([^{}]*)\}/g)) { + const name = m[1] ?? ""; + if (!(FILE_NAME_PLACEHOLDERS as readonly string[]).includes(name)) return `holds the placeholder {${name}}`; + } + return /[{}]/.test(fileName.replace(/\{[^{}]*\}/g, "")) ? "has an unmatched brace" : undefined; +} + +/** O1 — an operation's @inputRef and @outputRef shapes. False when one is wrong. */ +function checkShapes(op: MetaData, sink: Sink): boolean { + const inputRef = op.attr(OPERATION_ATTR_INPUT_REF); + if (typeof inputRef === "string") { + const input = resolveObjectOn(op, inputRef); + if (input === undefined || input.subType !== OBJECT_SUBTYPE_VALUE) { + sink.add(op, "ERR_OPERATION_SHAPE", + `operation.${op.subType} "${label(op)}" @inputRef "${inputRef}" ${input === undefined ? "names no object" : `is an object.${input.subType}`}; an operation's input is an object.value.`); + return false; + } + } + const outputRef = op.attr(OPERATION_ATTR_OUTPUT_REF); + if (typeof outputRef === "string") { + const output = resolveObjectOn(op, outputRef); + const legal = output !== undefined && + [OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_VALUE].includes(output.subType); + if (!legal) { + sink.add(op, "ERR_OPERATION_SHAPE", + `operation.${op.subType} "${label(op)}" @outputRef "${outputRef}" ${output === undefined ? "names no object" : `is an object.${output.subType}`}; an operation returns an object.entity, object.projection or object.value.`); + return false; + } + } + return true; +} + /** ADR-0066 — the rules pass. Runs after reference-bearing validation, before freeze. */ export function validateRules(root: MetaData): ParseError[] { const sink = new Sink(); @@ -369,6 +425,10 @@ export function validateRules(root: MetaData): ParseError[] { for (const api of root.children()) { if (api.type !== TYPE_API) continue; const ops = api.children().filter((c) => c.type === TYPE_OPERATION); + if (api.subType !== API_SUBTYPE_OPERATIONAL) { + for (const op of ops) checkDeliveryOperation(op, sink); + continue; + } for (const op of ops) checkOperation(op, sink); for (const op of ops) { const pkg = effectivePackageOf(api); @@ -430,7 +490,7 @@ function checkPermissionNames(root: MetaData, sink: Sink): void { for (const t of entityTransitions(entity)) register(t, entity, `${entity.name}.${t.name}`); } for (const api of root.children()) { - if (api.type !== TYPE_API) continue; + if (api.type !== TYPE_API || api.subType !== API_SUBTYPE_OPERATIONAL) continue; for (const op of api.children()) if (op.type === TYPE_OPERATION) register(op, api, op.name); } } diff --git a/server/typescript/packages/metadata/test/definition-schema.test.ts b/server/typescript/packages/metadata/test/definition-schema.test.ts index 093ba1376d..3e4176c317 100644 --- a/server/typescript/packages/metadata/test/definition-schema.test.ts +++ b/server/typescript/packages/metadata/test/definition-schema.test.ts @@ -96,6 +96,12 @@ describe("definition schema — the existing definition files", () => { `grant.${kind} @resource ${JSON.stringify({ targetType: "resource", targetSubTypes: [kind], sameSystem: true, wrongSystemCode: "ERR_GRANT_CROSSES_SYSTEM" })}`, ), `grant.api @api ${JSON.stringify({ targetType: "api" })}`, + `app.service @provides ${JSON.stringify({ targetType: "api" })}`, + `app.job @provides ${JSON.stringify({ targetType: "api" })}`, + `app.job @extracts ${JSON.stringify({ targetType: "object", targetSubTypes: ["entity", "projection"] })}`, + `resource.objectStore @carries ${JSON.stringify({ targetType: "api", targetSubTypes: ["batch"] })}`, + `resource.queue @carries ${JSON.stringify({ targetType: "api", targetSubTypes: ["eventing"] })}`, + `resource.stream @carries ${JSON.stringify({ targetType: "api", targetSubTypes: ["eventing"] })}`, `source.rdb @resource ${JSON.stringify({ targetType: "resource", targetSubTypes: ["rdb"] })}`, `source.document @resource ${JSON.stringify({ targetType: "resource", targetSubTypes: ["document"] })}`, `source.search @resource ${JSON.stringify({ targetType: "resource", targetSubTypes: ["search"] })}`, diff --git a/server/typescript/packages/metadata/test/reference-facet.test.ts b/server/typescript/packages/metadata/test/reference-facet.test.ts index f3bb03fcd0..8d4f235d25 100644 --- a/server/typescript/packages/metadata/test/reference-facet.test.ts +++ b/server/typescript/packages/metadata/test/reference-facet.test.ts @@ -659,7 +659,10 @@ describe("reference facet — the registry manifest", () => { expect(withRef.sort()).toEqual([ "app.base @runsAs", "app.client @runsAs", + "app.job @extracts", + "app.job @provides", "app.job @runsAs", + "app.service @provides", "app.service @runsAs", "field.map @objectRef", "field.object @objectRef", @@ -676,6 +679,9 @@ describe("reference facet — the registry manifest", () => { "relationship.association @objectRef", "relationship.base @objectRef", "relationship.composition @objectRef", + "resource.objectStore @carries", + "resource.queue @carries", + "resource.stream @carries", "role.base @memberOf", "role.group @memberOf", "role.service @memberOf", diff --git a/site-reference/index.html b/site-reference/index.html index 8ddf6d89df..6e9aba0960 100644 --- a/site-reference/index.html +++ b/site-reference/index.html @@ -66,6 +66,16 @@ types/api.md#apibase +api.batch +A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that provides it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the resource.objectStore that carries it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). +types/api.md#apibatch + + +api.eventing +A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that provides it publishes; a role holding grant.api on it consumes. It travels on the resource.stream or resource.queue that carries it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). +types/api.md#apieventing + + api.operational A named, packaged request/response surface whose children are operations (ADR-0030). It is a wire contract: two of them (v1, v2) may declare the same operation side by side. The code behind it is one service per metadata package, whose surface is the package's operations (ADR-0067). Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). types/api.md#apioperational @@ -151,6 +161,16 @@ types/binding.md#bindingbase +binding.file +How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the resource.objectStore that carries the API; @transport says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an operation.export or operation.import. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). +types/binding.md#bindingfile + + +binding.messaging +How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an operation.event. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). +types/binding.md#bindingmessaging + + binding.rest The HTTP method and path of an operation, declared only to override the derived ones. A query is GET, a command POST; the path is /<collection>/{id}/<operation-kebab> for an operation with a target key and /<collection>/<operation-kebab> without one. Most models never write it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). types/binding.md#bindingrest @@ -392,7 +412,7 @@ operation.base -Registry anchor for the attributes every operation shares (ADR-0054): not authorable. +Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes. types/operation.md#operationbase @@ -401,6 +421,21 @@ types/operation.md#operationcommand +operation.event +Something that happened, published by the provider: the payload is its @outputRef. A child of an api.eventing. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). +types/operation.md#operationevent + + +operation.export +A file the provider publishes on a schedule for consumers to collect: each row has the shape of its @outputRef, and the file appears this often (@frequency), by this time (@availableBy). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (app.job @schedule). A child of an api.batch. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). +types/operation.md#operationexport + + +operation.import +A file the provider accepts on a schedule from consumers: each row has the shape of its @inputRef, and a new file is expected this often (@frequency). The consumer delivers; the provider collects and reads. A child of an api.batch. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). +types/operation.md#operationimport + + operation.query A named operation that reads. Returns an object.projection (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). types/operation.md#operationquery diff --git a/site-reference/providers.html b/site-reference/providers.html index e5a33d0e1e..5b89f0e7e9 100644 --- a/site-reference/providers.html +++ b/site-reference/providers.html @@ -182,13 +182,17 @@

    metaobjects-requirements

    metaobjects-rules

    Business rules (ADR-0066, experimental): the declared API surface (api / operation / binding) and lifecycle moves (transition on a field.enum).

    -

    Owns (registers): api.base, api.operational, binding.base, binding.rest, operation.base, operation.command, operation.query, transition.action, transition.base

    +

    Owns (registers): api.base, api.batch, api.eventing, api.operational, binding.base, binding.file, binding.messaging, binding.rest, operation.base, operation.command, operation.event, operation.export, operation.import, operation.query, transition.action, transition.base

    Contributes attributes:

      +
    • binding.file: @completion, @compression, @encryption, @fileName, @format, @path, @transport
    • +
    • binding.messaging: @protocol
    • binding.rest: @method, @path
    • -
    • operation.base: @inputRef, @objectRef, @outputRef, @permission, @public
    • -
    • operation.command: @errors, @transitions
    • -
    • operation.query: @many
    • +
    • operation.command: @errors, @inputRef, @objectRef, @outputRef, @permission, @public, @transitions
    • +
    • operation.event: @key, @outputRef
    • +
    • operation.export: @availableBy, @frequency, @outputRef
    • +
    • operation.import: @frequency, @inputRef
    • +
    • operation.query: @inputRef, @many, @objectRef, @outputRef, @permission, @public
    • transition.action: @condition, @from, @to
    • transition.base: @permission, @public
    @@ -199,8 +203,8 @@

    metaobjects-systems-core

    • app.base: @runsAs
    • app.client: @shell
    • -
    • app.job: @schedule
    • -
    • app.service: @public
    • +
    • app.job: @extracts, @provides, @schedule
    • +
    • app.service: @provides, @public
    • build.image: @repository
    • grant.api: @api, @credential, @operations
    • grant.document: @access, @collection, @resource
    • @@ -212,9 +216,10 @@

      metaobjects-systems-core

    • grant.stream: @access, @resource
    • resource.base: @residency
    • resource.keyValue: @volatile
    • -
    • resource.objectStore: @publicRead
    • -
    • resource.queue: @deadLetter, @ordered
    • +
    • resource.objectStore: @carries, @publicRead
    • +
    • resource.queue: @carries, @deadLetter, @ordered
    • resource.rdb: @schemas
    • +
    • resource.stream: @carries
    • role.base: @credential, @memberOf
    • role.token: @heldBy
    • source.document: @collection, @resource
    • diff --git a/site-reference/types/api.html b/site-reference/types/api.html index 1952c17048..a7da28e4cd 100644 --- a/site-reference/types/api.html +++ b/site-reference/types/api.html @@ -57,6 +57,29 @@

      api.base

      No subtype-specific attributes.

      Allowed children

      No structural children.

      +

      api.batch

      +

      A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that provides it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the resource.objectStore that carries it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).

      +

      Owning provider: metaobjects-rules

      +

      Rules: Children are operation.export and operation.import. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.

      +

      When to use: A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.

      +

      Attributes

      +

      No subtype-specific attributes.

      +

      Allowed children

      +
        +
      • operation.export — 0..*
      • +
      • operation.import — 0..*
      • +
      +

      api.eventing

      +

      A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that provides it publishes; a role holding grant.api on it consumes. It travels on the resource.stream or resource.queue that carries it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).

      +

      Owning provider: metaobjects-rules

      +

      Rules: Children are operation.event. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.

      +

      When to use: Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.

      +

      Attributes

      +

      No subtype-specific attributes.

      +

      Allowed children

      +
        +
      • operation.event — 0..*
      • +

      api.operational

      A named, packaged request/response surface whose children are operations (ADR-0030). It is a wire contract: two of them (v1, v2) may declare the same operation side by side. The code behind it is one service per metadata package, whose surface is the package's operations (ADR-0067). Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).

      Owning provider: metaobjects-rules

      @@ -66,7 +89,8 @@

      api.operational

      No subtype-specific attributes.

      Allowed children

        -
      • operation.* — 0..*
      • +
      • operation.command — 0..*
      • +
      • operation.query — 0..*
      diff --git a/site-reference/types/app.html b/site-reference/types/app.html index 943c90ee51..f3db05b35f 100644 --- a/site-reference/types/app.html +++ b/site-reference/types/app.html @@ -138,6 +138,24 @@

      app.job

      +@extracts +string +no + + +metaobjects-systems-core +The entity or projection this job reads the rows of the files it writes from (DailyManifestLine), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object. + + +@provides +string[] +no + + +metaobjects-systems-core +The APIs this app provides, by name (ShipmentEvents, pkg::ManifestFeed): any api node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. + + @runsAs string no @@ -178,6 +196,15 @@

      app.service

      +@provides +string[] +no + + +metaobjects-systems-core +The APIs this app provides, by name (ShipmentEvents, pkg::ManifestFeed): any api node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. + + @public boolean no diff --git a/site-reference/types/binding.html b/site-reference/types/binding.html index 9901c1cd77..0149becc91 100644 --- a/site-reference/types/binding.html +++ b/site-reference/types/binding.html @@ -57,6 +57,118 @@

      binding.base

      No subtype-specific attributes.

      Allowed children

      No structural children.

      +

      binding.file

      +

      How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the resource.objectStore that carries the API; @transport says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an operation.export or operation.import. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).

      +

      Owning provider: metaobjects-rules

      +

      When to use: Every export and import whose file conventions two parties must agree on.

      +

      Attributes

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      AttributeTypeRequiredDefaultAllowed valuesProviderDescription
      @completionstringnononerename, marker, nonemetaobjects-rulesHow a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus .done (manifest-2026-12-03.csv.done) is put beside it. none (the default): the reader is told nothing.
      @compressionstringnononenone, gzipmetaobjects-rulesnone (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk.
      @encryptionstringnononenone, pgpmetaobjects-rulesnone (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key.
      @fileNamestringyesmetaobjects-rulesThe name of each file, with optional placeholders (manifest-{date}.csv). {date} is the UTC date on which the run that writes the file started, as YYYY-MM-DD (2026-12-03). {timestamp} is the UTC time at which that run started, to the second, as YYYYMMDDTHHMMSSZ (20261203T020000Z). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE.
      @formatstringyescsv, jsonLines, parquetmetaobjects-rulesHow the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is YYYY-MM-DD, a timestamp is in UTC and ends in Z, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is true or false, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet.
      @pathstringnometaobjects-rulesThe folder, within the object store, that holds the files (manifests/). Absent: the top of the store.
      @transportstringyessftp, objectStoremetaobjects-rulesHow the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product.
      +

      Allowed children

      +

      No structural children.

      +

      binding.messaging

      +

      How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an operation.event. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).

      +

      Owning provider: metaobjects-rules

      +

      When to use: Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.

      +

      Attributes

      + + + + + + + + + + + + + + + + + + + + + +
      AttributeTypeRequiredDefaultAllowed valuesProviderDescription
      @protocolstringnokafka, amqp, mqtt, sqsmetaobjects-rulesThe wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks.
      +

      Allowed children

      +

      No structural children.

      binding.rest

      The HTTP method and path of an operation, declared only to override the derived ones. A query is GET, a command POST; the path is /<collection>/{id}/<operation-kebab> for an operation with a target key and /<collection>/<operation-kebab> without one. Most models never write it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).

      Owning provider: metaobjects-rules

      diff --git a/site-reference/types/operation.html b/site-reference/types/operation.html index b13b6c311e..1454eae9e2 100644 --- a/site-reference/types/operation.html +++ b/site-reference/types/operation.html @@ -51,9 +51,17 @@ Allowed children lists the structural child rules with their cardinality (min..max, * = unbounded).

      operation.base

      -

      Registry anchor for the attributes every operation shares (ADR-0054): not authorable.

      +

      Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.

      Owning provider: metaobjects-rules

      Attributes

      +

      No subtype-specific attributes.

      +

      Allowed children

      +

      No structural children.

      +

      operation.command

      +

      A named operation that changes state. Takes an object.value (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).

      +

      Owning provider: metaobjects-rules

      +

      When to use: A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.

      +

      Attributes

      @@ -67,6 +75,15 @@

      operation.base

      + + + + + + + + + @@ -111,15 +128,24 @@

      operation.base

      + + + + + + + + +
      @errorsstring[]nometaobjects-rulesThe business failures the hand-written body may return, each a lower snake case code (insufficient_funds). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE.
      @inputRef string no metaobjects-rules The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT.
      @transitionsstring[]nometaobjects-rulesThe lifecycle moves this command may make: names of transition.action nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED).

      Allowed children

        -
      • binding.* — 0..*
      • +
      • binding.rest — 0..*
      -

      operation.command

      -

      A named operation that changes state. Takes an object.value (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).

      +

      operation.event

      +

      Something that happened, published by the provider: the payload is its @outputRef. A child of an api.eventing. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).

      Owning provider: metaobjects-rules

      -

      When to use: A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.

      +

      When to use: Each distinct fact a consumer may react to: placed, delivered, cancelled.

      Attributes

      @@ -134,72 +160,116 @@

      operation.command

      - - + + - + - + - + - + +
      @errorsstring[]@keystring no metaobjects-rulesThe business failures the hand-written body may return, each a lower snake case code (insufficient_funds). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE.The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised.
      @inputRef@outputRef stringnoyes metaobjects-rulesThe object.value this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an object.value is ERR_OPERATION_SHAPE.The payload the provider emits: an object.value, object.projection or object.entity. Anything else is ERR_OPERATION_SHAPE.
      +

      Allowed children

      +
        +
      • binding.messaging — 0..*
      • +
      +

      operation.export

      +

      A file the provider publishes on a schedule for consumers to collect: each row has the shape of its @outputRef, and the file appears this often (@frequency), by this time (@availableBy). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (app.job @schedule). A child of an api.batch. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).

      +

      Owning provider: metaobjects-rules

      +

      When to use: A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.

      +

      Attributes

      + + - + + + + + + + + + + + - + - + - - + + - + - + - + - + +
      @objectRefAttributeTypeRequiredDefaultAllowed valuesProviderDescription
      @availableBy string no metaobjects-rulesThe entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields extend every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an object.entity (ERR_OPERATION_TARGET_UNRESOLVED).The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly :MM (minutes past each hour, :15); daily HH:MM (03:00); weekly a day and a time, Ddd HH:MM with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (Mon 06:00); monthly a day of the month from 1 to 28 and a time, D HH:MM (1 06:00), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised.
      @outputRef@frequency stringnoyes hourly, daily, weekly, monthly metaobjects-rulesThe object this operation returns: an object.projection, object.entity or object.value. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE.How often a new file appears: hourly, daily, weekly or monthly.
      @permission@outputRef stringnoyes metaobjects-rulesThe permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as purchasing.approve; a package prefix may use :: (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name <package>.<operation>, with the package of the operation's API, and verify advises or requires an explicit one (setting rules.permissions.names). Several operations may share one.The shape of one row of the file the provider publishes: an object.value, object.projection or object.entity. Anything else is ERR_OPERATION_SHAPE.
      +

      Allowed children

      +
        +
      • binding.file — 0..*
      • +
      +

      operation.import

      +

      A file the provider accepts on a schedule from consumers: each row has the shape of its @inputRef, and a new file is expected this often (@frequency). The consumer delivers; the provider collects and reads. A child of an api.batch. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).

      +

      Owning provider: metaobjects-rules

      +

      When to use: A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.

      +

      Attributes

      + + - - - - + + + + + + + + + + + + + + - + - - - + + + - +
      @publicbooleannoAttributeTypeRequiredDefaultAllowed valuesProviderDescription
      @frequencystringyes hourly, daily, weekly, monthly metaobjects-rulesThe shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT.How often a new file is expected: hourly, daily, weekly or monthly.
      @transitionsstring[]no@inputRefstringyes metaobjects-rulesThe lifecycle moves this command may make: names of transition.action nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED).The shape of one row of the file the provider accepts: an object.value. Anything else is ERR_OPERATION_SHAPE.

      Allowed children

        -
      • binding.* — 0..*
      • +
      • binding.file — 0..*

      operation.query

      A named operation that reads. Returns an object.projection (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).

      @@ -275,7 +345,7 @@

      operation.query

      Allowed children

        -
      • binding.* — 0..*
      • +
      • binding.rest — 0..*
      diff --git a/site-reference/types/resource.html b/site-reference/types/resource.html index 374d559118..7d00cddd31 100644 --- a/site-reference/types/resource.html +++ b/site-reference/types/resource.html @@ -163,6 +163,15 @@

      resource.objectStore

      +@carries +string[] +no + + +metaobjects-systems-core +The batch APIs whose files sit in this store, by name (ManifestFeed). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an api.batch, is ERR_REF_WRONG_KIND: an eventing API travels on a resource.stream or resource.queue. + + @publicRead boolean no @@ -201,6 +210,15 @@

      resource.queue

      +@carries +string[] +no + + +metaobjects-systems-core +The eventing APIs whose events travel on this queue, by name (ShipmentEvents). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an api.eventing, is ERR_REF_WRONG_KIND: a batch API travels on a resource.objectStore. + + @deadLetter boolean no @@ -315,6 +333,15 @@

      resource.stream

      +@carries +string[] +no + + +metaobjects-systems-core +The eventing APIs whose events travel on this stream, by name (ShipmentEvents). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an api.eventing, is ERR_REF_WRONG_KIND: a batch API travels on a resource.objectStore. + + @residency string no diff --git a/spec/metamodel/api.json b/spec/metamodel/api.json index 6c803bfba0..ab76347e5c 100644 --- a/spec/metamodel/api.json +++ b/spec/metamodel/api.json @@ -15,22 +15,39 @@ "whenToUse": "The application does something beyond derived CRUD: a named command (approve, cancel, import) or a named query (my open requests). Declare it here so its input, output, permission and business errors are part of the model. A plain lifecycle needs no api.operational at all: a transition nobody claims is held to derive its own command once a shell is generated, and no shell is generated yet.", "rules": "Children are `operation.command` and `operation.query`. Lives at the document root. Declares no fields, sources or identities: shapes are referenced, never defined, by the surface. Operation names are compared without case, are unique across every API of one package, except one operation declared identically in two APIs, such as a versioned API beside its successor (one operation declared twice in one API merges), and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). Two declared bindings of one API may not share a method and path (ERR_BINDING_PATH_MISMATCH).", "children": [ - { "type": "operation", "subType": "*", "name": "*", "min": 0, "max": null, "description": "The operations this surface exposes." } + { "type": "operation", "subType": "command", "name": "*", "min": 0, "max": null, "description": "The commands this surface exposes." }, + { "type": "operation", "subType": "query", "name": "*", "min": 0, "max": null, "description": "The queries this surface exposes." } ] }, { - "type": "operation", - "subType": "base", - "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.", + "type": "api", + "subType": "eventing", + "extendsBase": true, + "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.", + "rules": "Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.", "children": [ - { "type": "binding", "subType": "*", "name": "*", "min": 0, "max": null, "description": "Optional protocol bindings. Only needed to override the derived method and path." }, - { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." }, - { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." }, - { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." }, - { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." } + { "type": "operation", "subType": "event", "name": "*", "min": 0, "max": null, "description": "The events this surface publishes." } + ] + }, + { + "type": "api", + "subType": "batch", + "extendsBase": true, + "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.", + "rules": "Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.", + "children": [ + { "type": "operation", "subType": "export", "name": "*", "min": 0, "max": null, "description": "The datasets the provider publishes." }, + { "type": "operation", "subType": "import", "name": "*", "min": 0, "max": null, "description": "The datasets the provider accepts." } ] }, + { + "type": "operation", + "subType": "base", + "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.", + "children": [] + }, { "type": "operation", "subType": "command", @@ -38,6 +55,12 @@ "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.", "children": [ + { "type": "binding", "subType": "rest", "name": "*", "min": 0, "max": null, "description": "Optional HTTP bindings. Only needed to override the derived method and path." }, + { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." }, + { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." }, + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." }, { "type": "attr", "subType": "string", "name": "transitions", "isArray": true, "min": 0, "max": 1, "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)." }, { "type": "attr", "subType": "string", "name": "errors", "isArray": true, "min": 0, "max": 1, "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE." } ] @@ -49,9 +72,52 @@ "description": "A named operation that reads. Returns an `object.projection` (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", "whenToUse": "A read with its own name and shape beyond derived get and list: my open requests, the dashboard summary.", "children": [ + { "type": "binding", "subType": "rest", "name": "*", "min": 0, "max": null, "description": "Optional HTTP bindings. Only needed to override the derived method and path." }, + { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." }, + { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." }, + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." }, { "type": "attr", "subType": "boolean", "name": "many", "min": 0, "max": 1, "description": "The query returns a list and takes the filter, sort and paging contract. Not implied by the projection, so declared. Absent means one row. Legal on a query only." } ] }, + { + "type": "operation", + "subType": "event", + "extendsBase": true, + "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Each distinct fact a consumer may react to: placed, delivered, cancelled.", + "children": [ + { "type": "binding", "subType": "messaging", "name": "*", "min": 0, "max": null, "description": "Optional messaging bindings: how the event travels." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 1, "max": 1, "description": "The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "key", "min": 0, "max": 1, "description": "The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised." } + ] + }, + { + "type": "operation", + "subType": "export", + "extendsBase": true, + "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.", + "children": [ + { "type": "binding", "subType": "file", "name": "*", "min": 0, "max": null, "description": "Optional file bindings: where the file is and how it is written." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 1, "max": 1, "description": "The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "frequency", "min": 1, "max": 1, "allowedValues": ["hourly", "daily", "weekly", "monthly"], "description": "How often a new file appears: hourly, daily, weekly or monthly." }, + { "type": "attr", "subType": "string", "name": "availableBy", "min": 0, "max": 1, "description": "The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised." } + ] + }, + { + "type": "operation", + "subType": "import", + "extendsBase": true, + "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.", + "children": [ + { "type": "binding", "subType": "file", "name": "*", "min": 0, "max": null, "description": "Optional file bindings: where the file is delivered and how it is written." }, + { "type": "attr", "subType": "string", "name": "inputRef", "min": 1, "max": 1, "description": "The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "frequency", "min": 1, "max": 1, "allowedValues": ["hourly", "daily", "weekly", "monthly"], "description": "How often a new file is expected: hourly, daily, weekly or monthly." } + ] + }, { "type": "binding", "subType": "base", @@ -68,6 +134,32 @@ { "type": "attr", "subType": "string", "name": "method", "min": 0, "max": 1, "allowedValues": ["GET", "POST", "PUT", "PATCH", "DELETE"], "description": "The HTTP method. Absent: GET for a query, POST for a command." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "A path template. Its `{name}` placeholders must be exactly the target's primary key fields when the operation is keyed, and there must be none when it is not; two declared bindings of one API may not share the method and path (ERR_BINDING_PATH_MISMATCH)." } ] + }, + { + "type": "binding", + "subType": "messaging", + "extendsBase": true, + "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.", + "children": [ + { "type": "attr", "subType": "string", "name": "protocol", "min": 0, "max": 1, "allowedValues": ["kafka", "amqp", "mqtt", "sqs"], "description": "The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks." } + ] + }, + { + "type": "binding", + "subType": "file", + "extendsBase": true, + "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "Every export and import whose file conventions two parties must agree on.", + "children": [ + { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, + { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, + { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, + { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, + { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } + ] } ], "extends": [ diff --git a/spec/metamodel/systems.json b/spec/metamodel/systems.json index cb6b7da4ed..189eaf4c5e 100644 --- a/spec/metamodel/systems.json +++ b/spec/metamodel/systems.json @@ -64,7 +64,8 @@ "description": "A long-running process that answers requests: a web server, an API, a socket server.", "whenToUse": "Anything that listens on a port and stays up.", "children": [ - { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." } + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." }, + { "type": "attr", "subType": "string", "name": "provides", "isArray": true, "min": 0, "max": 1, "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } } ] }, { @@ -84,7 +85,9 @@ "description": "Work that runs to completion and exits: a scheduled task, a migration, a one-off batch. It may run on a schedule (@schedule) or when something triggers it.", "whenToUse": "A cron job, a nightly import, a queue drain that is not a long-running service.", "children": [ - { "type": "attr", "subType": "string", "name": "schedule", "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." } + { "type": "attr", "subType": "string", "name": "schedule", "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." }, + { "type": "attr", "subType": "string", "name": "extracts", "min": 0, "max": 1, "description": "The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object.", "ref": { "targetType": "object", "targetSubTypes": ["entity", "projection"] } }, + { "type": "attr", "subType": "string", "name": "provides", "isArray": true, "min": 0, "max": 1, "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } } ] }, { @@ -137,7 +140,8 @@ "description": "Files and blobs addressed by key.", "whenToUse": "Uploaded images, exports, static assets kept outside the app.", "children": [ - { "type": "attr", "subType": "boolean", "name": "publicRead", "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." } + { "type": "attr", "subType": "boolean", "name": "publicRead", "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." }, + { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`.", "ref": { "targetType": "api", "targetSubTypes": ["batch"] } } ] }, { @@ -162,7 +166,8 @@ "whenToUse": "Work handed from one app to another to run later.", "children": [ { "type": "attr", "subType": "boolean", "name": "ordered", "min": 0, "max": 1, "description": "Messages with the same key are delivered in the order they were sent. Absent means no order is promised." }, - { "type": "attr", "subType": "boolean", "name": "deadLetter", "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." } + { "type": "attr", "subType": "boolean", "name": "deadLetter", "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." }, + { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", "ref": { "targetType": "api", "targetSubTypes": ["eventing"] } } ] }, { @@ -170,7 +175,10 @@ "subType": "stream", "extendsBase": true, "description": "A retained, ordered log that many consumers read, each at its own position. A message can be read again.", - "whenToUse": "Events several consumers read independently, or read again." + "whenToUse": "Events several consumers read independently, or read again.", + "children": [ + { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", "ref": { "targetType": "api", "targetSubTypes": ["eventing"] } } + ] }, { "type": "resource", From b85f962f2bc050d4078695d9a8e42e42d1dfa652 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 5 Dec 2026 00:21:01 -0500 Subject: [PATCH 02/10] no-mistakes(review): Pin CSV empty-string, time and JSON column forms --- docs/features/business-rules.md | 9 ++++++--- fixtures/metamodel-docs/data/types/binding.md.json | 2 +- fixtures/metamodel-docs/expected/types/binding.md | 2 +- fixtures/registry-conformance/expected-registry.json | 2 +- server/csharp/MetaObjects/SpecMetamodel/api.json | 2 +- server/python/src/metaobjects/spec_metamodel/api.json | 2 +- server/rust/metaobjects/data/metamodel/api.json | 2 +- .../metadata/src/core/api/api-definition.embedded.ts | 2 +- site-reference/types/binding.html | 2 +- spec/metamodel/api.json | 2 +- 10 files changed, 15 insertions(+), 12 deletions(-) diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index e920b70b64..7fffd947c6 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -171,9 +171,12 @@ file is in place by, and its form follows the frequency: - `format`: `csv`, `jsonLines` or `parquet`. A CSV file is RFC 4180: a comma between fields, CRLF after every line, UTF-8 with no byte order mark, and a first line of field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is - an empty field, a date is `YYYY-MM-DD`, a timestamp is UTC ending in `Z`, a decimal is plain - digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, - and a double is the shortest text that reads back to the same value, with no exponent. + an empty field, and an empty string is always written quoted (`""`) so that it differs from + null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is UTC ending in `Z`, + a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is + `true` or `false`, and a double is the shortest text that reads back to the same value, with no + exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner + quotes are doubled. `jsonLines` is one JSON object per line, UTF-8, LF after each. - `compression`: `none` (the default) or `gzip`. - `completion`: how a reader knows a file is whole. `rename`: it appears under its final name diff --git a/fixtures/metamodel-docs/data/types/binding.md.json b/fixtures/metamodel-docs/data/types/binding.md.json index e350b25da2..df5de4b18c 100644 --- a/fixtures/metamodel-docs/data/types/binding.md.json +++ b/fixtures/metamodel-docs/data/types/binding.md.json @@ -73,7 +73,7 @@ "default": "", "allowed": "`csv`, `jsonLines`, `parquet`", "provider": "metaobjects-rules", - "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`\"\"`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "name": "path", diff --git a/fixtures/metamodel-docs/expected/types/binding.md b/fixtures/metamodel-docs/expected/types/binding.md index f182c8dc32..380ca5fb59 100644 --- a/fixtures/metamodel-docs/expected/types/binding.md +++ b/fixtures/metamodel-docs/expected/types/binding.md @@ -40,7 +40,7 @@ How a file of an export or import is delivered: where it sits, what it is called | `@compression` | string | no | `none` | `none`, `gzip` | metaobjects-rules | none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk. | | `@encryption` | string | no | `none` | `none`, `pgp` | metaobjects-rules | none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key. | | `@fileName` | string | yes | | | metaobjects-rules | The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE. | -| `@format` | string | yes | | `csv`, `jsonLines`, `parquet` | metaobjects-rules | How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. | +| `@format` | string | yes | | `csv`, `jsonLines`, `parquet` | metaobjects-rules | How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`""`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. | | `@path` | string | no | | | metaobjects-rules | The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store. | | `@transport` | string | yes | | `sftp`, `objectStore` | metaobjects-rules | How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product. | diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 95610a7bd0..3d8148db6f 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -396,7 +396,7 @@ "jsonLines", "parquet" ], - "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`\"\"`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "name": "path", diff --git a/server/csharp/MetaObjects/SpecMetamodel/api.json b/server/csharp/MetaObjects/SpecMetamodel/api.json index ab76347e5c..ad58f864d1 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/api.json +++ b/server/csharp/MetaObjects/SpecMetamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`\"\"`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } diff --git a/server/python/src/metaobjects/spec_metamodel/api.json b/server/python/src/metaobjects/spec_metamodel/api.json index ab76347e5c..ad58f864d1 100644 --- a/server/python/src/metaobjects/spec_metamodel/api.json +++ b/server/python/src/metaobjects/spec_metamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`\"\"`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } diff --git a/server/rust/metaobjects/data/metamodel/api.json b/server/rust/metaobjects/data/metamodel/api.json index ab76347e5c..ad58f864d1 100644 --- a/server/rust/metaobjects/data/metamodel/api.json +++ b/server/rust/metaobjects/data/metamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`\"\"`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } diff --git a/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts b/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts index d230e5437d..abb3b2d20b 100644 --- a/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts @@ -457,7 +457,7 @@ export const API_DEFINITION: ProviderDefinition = { "jsonLines", "parquet" ], - "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`\"\"`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", diff --git a/site-reference/types/binding.html b/site-reference/types/binding.html index 0149becc91..a863bdec9f 100644 --- a/site-reference/types/binding.html +++ b/site-reference/types/binding.html @@ -117,7 +117,7 @@

      binding.file

      csv, jsonLines, parquet metaobjects-rules -How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is YYYY-MM-DD, a timestamp is in UTC and ends in Z, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is true or false, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. +How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted ("") so that it differs from null. A date is YYYY-MM-DD, a time is HH:MM:SS wall time, a timestamp is in UTC and ends in Z, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is true or false, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. @path diff --git a/spec/metamodel/api.json b/spec/metamodel/api.json index ab76347e5c..ad58f864d1 100644 --- a/spec/metamodel/api.json +++ b/spec/metamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field. A date is `YYYY-MM-DD`, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`\"\"`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } From 2c5fedaf9fc307871b289a599008d579366a84fa Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 5 Dec 2026 00:30:46 -0500 Subject: [PATCH 03/10] no-mistakes(review): Add event @key rule, fix Java API nodes and CSV form --- .claude/rules/cross-language-porting.md | 2 +- AGENTS.md | 2 +- changelog.d/api-eventing-and-batch.md | 7 +++-- docs/CONFORMANCE.md | 10 +++---- docs/features/business-rules.md | 28 ++++++++++++++----- examples/showcase/site-payload.json | 2 +- .../expected-errors.json | 15 ++++++++++ .../input/meta.parcels.json | 18 ++++++++++++ .../metamodel-docs/data/types/binding.md.json | 2 +- .../metamodel-docs/expected/types/binding.md | 2 +- .../expected-registry.json | 2 +- .../Loader/ValidationPasses.Rules.cs | 14 ++++++++-- .../csharp/MetaObjects/SpecMetamodel/api.json | 2 +- .../{DeliveryNode.java => DeliveryApi.java} | 15 +++------- .../com/metaobjects/api/DeliveryBinding.java | 25 +++++++++++++++++ .../metaobjects/api/DeliveryOperation.java | 25 +++++++++++++++++ .../com/metaobjects/api/DeliveryTypes.java | 19 +++++++------ .../metaobjects/loader/RulesValidation.java | 13 ++++++++- .../src/metaobjects/loader/validate_rules.py | 17 +++++++++-- .../src/metaobjects/spec_metamodel/api.json | 2 +- .../rust/metaobjects/data/metamodel/api.json | 2 +- server/rust/metaobjects/src/validate/rules.rs | 27 ++++++++++++++++-- .../tests/conformance-expected-failures.json | 2 +- .../src/core/api/api-definition.embedded.ts | 2 +- .../metadata/src/loader/rules-validation.ts | 18 ++++++++++-- site-reference/types/binding.html | 2 +- spec/metamodel/api.json | 2 +- 27 files changed, 221 insertions(+), 56 deletions(-) create mode 100644 fixtures/conformance/error-api-event-key-not-a-field/expected-errors.json create mode 100644 fixtures/conformance/error-api-event-key-not-a-field/input/meta.parcels.json rename server/java/metadata/src/main/java/com/metaobjects/api/{DeliveryNode.java => DeliveryApi.java} (55%) create mode 100644 server/java/metadata/src/main/java/com/metaobjects/api/DeliveryBinding.java create mode 100644 server/java/metadata/src/main/java/com/metaobjects/api/DeliveryOperation.java diff --git a/.claude/rules/cross-language-porting.md b/.claude/rules/cross-language-porting.md index ab7ea5168f..130ea4c8da 100644 --- a/.claude/rules/cross-language-porting.md +++ b/.claude/rules/cross-language-porting.md @@ -26,7 +26,7 @@ Preserve the following contracts exactly across all language ports: - Relationship subtypes: `association`, `aggregation`, `composition`. Cardinality via `@cardinality: one|many`; target via `@objectRef`. **M:N (FR-018) slim vocabulary:** `@cardinality: "many"` + `@objectRef` (target) + `@through` (the junction/through entity — a third entity that MUST declare two `identity.reference` children, one per FK side). The relationship's FK fields are **derived** from those references (the `identity.reference` SSOT for FK direction), never restated. `@sourceRefField` (optional) disambiguates a *directed* self-join by naming the source-side FK field on the junction (the other reference is the target side); on a `@cardinality: one` relationship it instead names which of several `identity.reference` nodes onto the same target this relationship navigates, short-circuiting the unique-candidate/`@sourceRefField`/name-pairing ladder (#368, [ADR-0029](spec/decisions/ADR-0029-entity-child-extends-and-via-inference.md) Amendment 1) — an unresolvable 1:N reference set is `ERR_INVALID_RELATIONSHIP` at load. `@symmetric` (optional boolean) marks an *undirected* self-join (union-on-read) — valid only when `@objectRef` == the declaring entity, and mutually exclusive with `@sourceRefField`. The pre-FR-018 `@joinEntity`/`@joinFields` attrs are REMOVED. Validation errors: symmetric-on-hetero / symmetric+sourceRefField → `ERR_BAD_ATTR_VALUE`; junction-missing-two-references / sourceRefField-not-matching / M:N-attr-on-1:N / **junction-unpairable** → `ERR_INVALID_RELATIONSHIP`. **Unpairable means the junction declares its two references but neither resolves to the navigating entity, or neither to the `@objectRef` target** — declaring two references is NOT enough, and the loader now checks WHAT they point at (owner ruling 2026-09-20). It does so by running the real FK derivation and converting its failure, never a parallel re-implementation, so the loader and the derivation cannot drift; scope mirrors codegen's own iteration exactly — every CONCRETE, non-projection object crossed with its EFFECTIVE relationships, NOT deduped by declaration, because pairing is a property of the navigating entity and an inherited M:N can pair from one subtype and not another. Before the ruling this loaded clean and then diverged: TS and C# warned and emitted no traversal route (a silent 404), while Java, Kotlin and Python failed the build. Gated by `fixtures/conformance/error-relationship-m2m-junction-unpairable/`. - Index subtypes: `index.lookup` (non-unique retrieval index; uniqueness is encoded in the **type**: `identity.secondary` = unique alternate key, `index.lookup` = non-unique; `@unique` is REMOVED from `identity.secondary` — `ERR_UNKNOWN_ATTR` on any legacy `@unique`). RDB-physical escapes `@using`/`@expr`/`@where`/`@orders` are registered by the db provider on **both** `identity.secondary` and `index.lookup`. `index.fulltext` / `index.vector` / `index.spatial` are reserved on the subtype axis — documented, NOT registered (YAGNI + 1.0 vocab freeze). See [ADR-0040](spec/decisions/ADR-0040-index-type-and-secondary-key-purity.md). - Layout subtypes: `dataGrid` -- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`), `binding.messaging` and `binding.file`; `grpc` reserved). `api.eventing` (`operation.event` + `binding.messaging`) and `api.batch` (`operation.export`/`.import` + `binding.file`) are registered since 1.4.0, experimental: only O1 and the delivery rules D1/D2 read them, and every port's API generators select `binding.rest` by subtype and skip them. Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (`rules-names` and `contract-types` in TypeScript and C#; the TypeScript `service`, `service-routes` and `service-routes-hono` for derived CRUD, transitions, declared operations and the rules' checks). +- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`), `binding.messaging` and `binding.file`; `grpc` reserved). `api.eventing` (`operation.event` + `binding.messaging`) and `api.batch` (`operation.export`/`.import` + `binding.file`) are registered since 1.4.0, experimental: only O1 and the delivery rules D1 to D3 read them, and every port's API generators select `binding.rest` by subtype and skip them. Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (`rules-names` and `contract-types` in TypeScript and C#; the TypeScript `service`, `service-routes` and `service-routes-hono` for derived CRUD, transitions, declared operations and the rules' checks). - Transition subtypes: `transition.action` (a child of `field.enum` on an `object.entity`: `@from`, `@to`, `@condition` in the validators' grammar, `@permission`, `@public`); `transition.base` is the abstract root and `transition.timed` is reserved, not registered. An enum with a transition IS a lifecycle — states, initial state (`@default`), terminal states and each unclaimed transition's command are derived, never declared (ADR-0066). A transition's `@from` lists enum members, not object references: every port's ref-bearing-attr check excludes `transition.*` nodes. A lifecycle belongs to the declaring entity and its `extends` descendants, NEVER to an entity whose field merely `extends` the lifecycle field (filter by the declaring field's owner); a command claims a transition NODE for its target and every entity extending it. Transition and operation names compare case-insensitively; operation names are unique per PACKAGE across its APIs, except one operation declared identically in two APIs (a versioned API). A lifecycle on an entity with no source loads and is inert (no derived command, no permission checks); the writable-source check applies once a source exists. A `@permission` is a dotted identifier path (a package prefix may use `::`); an absent one derives `.` for an operation and `..` for a transition's command. - Currency attrs: `@currency` (ISO 4217), `@locale` (BCP 47) - Schema attrs: `@schema` on `source.rdb` (DB schema name; Postgres default `public`, SQLite rejects non-default values) diff --git a/AGENTS.md b/AGENTS.md index cce1264123..b5cfb45c5d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,7 +74,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (laid out by `KotlinWriter`, ADR-0063, on the JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (619 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (620 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / Java / Kotlin / Python / C# / Rust byte-identical; the C# and Rust drift ledgers are empty (`docs/CONFORMANCE.md`). - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python; `op: guardedUpdate` is TS-only until each port's 1.3.0 guarded update lands), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (the Node reference helper writes them; a native tool is equally first-class, ADR-0015 Amendment 2). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/changelog.d/api-eventing-and-batch.md b/changelog.d/api-eventing-and-batch.md index 5a5bfde833..bdb33ac8b7 100644 --- a/changelog.d/api-eventing-and-batch.md +++ b/changelog.d/api-eventing-and-batch.md @@ -10,10 +10,13 @@ `@completion` and `@encryption`. The file conventions are pinned: `{date}` is the run's start date as `YYYY-MM-DD` and `{timestamp}` is `YYYYMMDDTHHMMSSZ`, both UTC, and are the only placeholders; a `marker` completion is an empty file named the data file's name plus `.done`; - `csv` is RFC 4180 with a header row. `@availableBy` is written `:MM` for an hourly file, + `csv` is RFC 4180 with a header row, an empty string always quoted so it differs from null, and + one written form per field subtype (a UTC timestamp ends in `Z`, a `@localTime` one has no zone, + an object, map or array is its JSON text). `@availableBy` is written `:MM` for an hourly file, `HH:MM` for daily, `Ddd HH:MM` for weekly and `D HH:MM` (day 1 to 28) for monthly; another form is `ERR_BAD_ATTR_VALUE` (`error-api-export-available-by-weekly-no-day`), and so is any other - `@fileName` placeholder (`error-api-binding-file-unknown-placeholder`). An event, export or + `@fileName` placeholder (`error-api-binding-file-unknown-placeholder`), and an event `@key` that + is not a field of its `@outputRef` (`error-api-event-key-not-a-field`, rule D3). An event, export or import under an `api.operational`, or a command or query under the new kinds, is `ERR_CHILD_NOT_ALLOWED` (`error-api-event-under-operational`), and so is a `binding.rest` on them. In a system, `resource.stream` and `resource.queue` take `@carries` naming eventing APIs diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 1e4da01500..0b6976c920 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | Rust | |---|---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 619 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (619 / 619, empty ledger) | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 620 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (620 / 620, empty ledger) | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | 19 / 19 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | — | @@ -82,7 +82,7 @@ and render ledgers; the api-contract runner's list of sub-corpora not built yet) shrink, and the corpora without one assert each case outright. A new fixture that fails in Rust and is not on the ledger prints a warning and does not fail the lane; it becomes a hard failure when ADR-0065 turns the warning off. A regression still fails: the ledger's -`minPassing` (619) is the number of fixtures known to pass, and the run fails when fewer do. +`minPassing` (620) is the number of fixtures known to pass, and the run fails when fewer do. Beside the corpora it runs the codegen-compile gate (below) with every shipped generator, a scale gate over twenty copies of the fitness model, and `examples/rust-service/`'s HTTP test. [The Rust port page](ports/rust.md#conformance) has the detail. @@ -445,7 +445,7 @@ carry it, and a model that uses it fails there by name. There is no row per pack ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (619) +### `fixtures/conformance/` — metamodel loader + canonical serializer (620) | Fixture prefix | Feature doc | |---|---| @@ -470,7 +470,7 @@ carry it, and a model that uses it fails there by name. There is no row per pack | `requirement-*`, `error-unknown-attr-requirement` | [features/requirements.md](features/requirements.md) (vocabulary only — the gate has its own corpus, `requirement-check-conformance/`; see "Split coverage" above) | | `systems-vocabulary`, `error-ref-wrong-kind-runsas`, `error-ref-unresolved-runsas`, `ref-target-type-list-heldby`, `error-ref-wrong-kind-heldby`, `error-ref-ambiguous-heldby`, `error-resource-residency-bad-value`, `error-app-two-builds`, `error-app-three-builds`, `error-app-build-beside-inherited`, `systems-grants-and-sources`, `error-ref-unresolved-grant-resource`, `error-ref-wrong-kind-grant-rdb-on-queue`, `error-ref-wrong-kind-source-rdb-on-document`, `error-ref-wrong-kind-grant-stream-on-other-system-queue`, `error-grant-crosses-system`, `error-runsas-other-system`, `error-duplicate-name-in-system`, `systems-duplicate-name-overlay-in-system`, `error-ref-ambiguous-heldby-bare-name`, `systems-rdb-with-search-copy`, `systems-role-grants-across-files`, `systems-document-only-lifecycle-inert`, `systems-sql-view-with-search-copy`, `systems-payload-ref-search-only-projection`, `error-ref-wrong-kind-carries-batch-on-stream` | [spec/metamodel-definitions.md](../spec/metamodel-definitions.md) (the systems vocabulary, ADR-0070: the reference facet's worked cases, including the target type list behind `@heldBy`, the closed `@residency` set, an app's one build, counting a build it inherits, the grants and their same-system rule, `@resource` on a source, one name per type within a system, a role redeclared in a second file keeping every grant, a search copy beside a SQL view leaving its columns unchecked, a lifecycle that stays inert when its entity has no relational source, and a projection kept only in a search index still serving as a template payload) | | `reporting-*`, `error-dimension-*`, `error-measure-*`, `error-ratio-*`, `error-segment-*`, `error-report-*`, `error-relative-date-*` | [features/reporting.md](features/reporting.md) (the `dimension` / `measure` / `segment` / `object.report` vocabulary and its load-time rules; design in the [FR-044 spec](superpowers/specs/2026-10-02-fr-044-core-reporting-design.md)) | -| `systems-api-eventing-batch`, `error-api-export-available-by-weekly-no-day`, `error-api-binding-file-unknown-placeholder`, `error-api-event-under-operational` | [features/business-rules.md](features/business-rules.md) ("Eventing and batch APIs": `api.eventing` and `api.batch`, their operations and bindings, what a resource carries and an app provides, and the `@availableBy` and `@fileName` rules D1 and D2) | +| `systems-api-eventing-batch`, `error-api-export-available-by-weekly-no-day`, `error-api-binding-file-unknown-placeholder`, `error-api-event-under-operational`, `error-api-event-key-not-a-field` | [features/business-rules.md](features/business-rules.md) ("Eventing and batch APIs": `api.eventing` and `api.batch`, their operations and bindings, what a resource carries and an app provides, and the `@availableBy` and `@fileName` rules D1 and D2, and the event `@key` rule D3) | | `rules-*`, `error-rules-*` | [features/business-rules.md](features/business-rules.md) (operations, permission names and lifecycles: the vocabulary and its load-time rules, ADR-0066; the `verify` gate has its own corpus, `rules-check-conformance/`) | | `provider-extension-*`, `provider-custom-vocabulary-*` | [features/extending-with-providers.md](features/extending-with-providers.md) (a project's own provider: a new subtype plus attributes on an existing type load with it and are refused without it, every port writing the provider in its own language) | | `error-packs-left-out-*` | [features/extending-with-providers.md](features/extending-with-providers.md) ([Where vocabulary lives](features/extending-with-providers.md#where-vocabulary-lives): a model that uses a left-out pack's type fails to load, naming the unknown type or subtype) | @@ -962,7 +962,7 @@ shared input. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 619 + yaml 19 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 620 + yaml 19 + verify 45 + render 26 + persistence 68 + api-contract 191 + source-resolution 30 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `rules-check-conformance`, `shared-model-conformance`, the `cube-model` corpus, `explorer-conformance` and `list-query-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 7fffd947c6..e62d91a23b 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -170,13 +170,26 @@ file is in place by, and its form follows the frequency: that day's date. - `format`: `csv`, `jsonLines` or `parquet`. A CSV file is RFC 4180: a comma between fields, CRLF after every line, UTF-8 with no byte order mark, and a first line of field names. A field is - quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is - an empty field, and an empty string is always written quoted (`""`) so that it differs from - null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is UTC ending in `Z`, - a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is - `true` or `false`, and a double is the shortest text that reads back to the same value, with no - exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner - quotes are doubled. + quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. + An empty string is the one exception: it is always quoted (`""`), so that it differs from null, + which is an empty field. Each value is written by its field's subtype: + + | Subtype | Written as | + |---|---| + | `string`, `uri`, `inet` | its text | + | `enum` | the member's name | + | `uuid` | lowercase `8-4-4-4-12` | + | `int`, `long` | plain digits with an optional leading minus | + | `decimal` | the same, with a decimal point where it has one, never an exponent | + | `double`, `float` | the shortest text that reads back to the same value, with no exponent | + | `currency` | an integer in minor units | + | `boolean` | `true` or `false` | + | `date` | `YYYY-MM-DD` | + | `time` | `HH:MM:SS`, wall time | + | `timestamp` | UTC, `YYYY-MM-DDTHH:MM:SSZ`; with `@localTime`, wall time `YYYY-MM-DDTHH:MM:SS` with no zone | + | `duration` | ISO 8601 (`PT1H30M`) | + | `object`, `map`, any array | its JSON text, quoted by the same rule | + `jsonLines` is one JSON object per line, UTF-8, LF after each. - `compression`: `none` (the default) or `gzip`. - `completion`: how a reader knows a file is whole. `rename`: it appears under its final name @@ -262,6 +275,7 @@ setting `rules.permissions.names` makes `verify` warn about derived names, or fa | B2 | `ERR_BINDING_PATH_MISMATCH` | Two declared bindings of one API have the same method (declared or derived) and the same path, ignoring placeholder names. | | D1 | `ERR_BAD_ATTR_VALUE` | An `operation.export` `availableBy` does not have the form its `frequency` gives. | | D2 | `ERR_BAD_ATTR_VALUE` | A `binding.file` `fileName` holds a placeholder other than `{date}` or `{timestamp}`, or an unmatched brace. | +| D3 | `ERR_BAD_ATTR_VALUE` | An `operation.event` `key` is not a field of the object its `outputRef` names (inherited fields count). | Names are compared without case (L5 and O0, L6, O6) because each one becomes a command, a permission constant and a file, and those collide on a case-folding target. P3 compares permission names diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 3694438925..5759eb0b10 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.4" }, "counts": { - "fixtures": 619, + "fixtures": 620, "corpora": 49, "baseTypes": 28 }, diff --git a/fixtures/conformance/error-api-event-key-not-a-field/expected-errors.json b/fixtures/conformance/error-api-event-key-not-a-field/expected-errors.json new file mode 100644 index 0000000000..cec7564865 --- /dev/null +++ b/fixtures/conformance/error-api-event-key-not-a-field/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.parcels.json" + ], + "jsonPath": "$['metadata.root'].children[2]['api.eventing'].children[1]['operation.event']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-api-event-key-not-a-field/input/meta.parcels.json b/fixtures/conformance/error-api-event-key-not-a-field/input/meta.parcels.json new file mode 100644 index 0000000000..c12069fb3f --- /dev/null +++ b/fixtures/conformance/error-api-event-key-not-a-field/input/meta.parcels.json @@ -0,0 +1,18 @@ +{ + "metadata.root": { + "package": "acme::parcels", + "children": [ + { "object.value": { "name": "ParcelEvent", "abstract": true, "children": [ { "field.string": { "name": "trackingNumber" } } ] } }, + { "object.value": { "name": "ParcelScanned", "extends": "ParcelEvent", "children": [ { "field.string": { "name": "depot" } } ] } }, + { + "api.eventing": { + "name": "ParcelEvents", + "children": [ + { "operation.event": { "name": "parcelScanned", "@outputRef": "ParcelScanned", "@key": "trackingNumber" } }, + { "operation.event": { "name": "parcelRescanned", "@outputRef": "ParcelScanned", "@key": "trackingNumbr" } } + ] + } + } + ] + } +} diff --git a/fixtures/metamodel-docs/data/types/binding.md.json b/fixtures/metamodel-docs/data/types/binding.md.json index df5de4b18c..df07dd8ad0 100644 --- a/fixtures/metamodel-docs/data/types/binding.md.json +++ b/fixtures/metamodel-docs/data/types/binding.md.json @@ -73,7 +73,7 @@ "default": "", "allowed": "`csv`, `jsonLines`, `parquet`", "provider": "metaobjects-rules", - "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`\"\"`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "name": "path", diff --git a/fixtures/metamodel-docs/expected/types/binding.md b/fixtures/metamodel-docs/expected/types/binding.md index 380ca5fb59..86f28db223 100644 --- a/fixtures/metamodel-docs/expected/types/binding.md +++ b/fixtures/metamodel-docs/expected/types/binding.md @@ -40,7 +40,7 @@ How a file of an export or import is delivered: where it sits, what it is called | `@compression` | string | no | `none` | `none`, `gzip` | metaobjects-rules | none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk. | | `@encryption` | string | no | `none` | `none`, `pgp` | metaobjects-rules | none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key. | | `@fileName` | string | yes | | | metaobjects-rules | The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE. | -| `@format` | string | yes | | `csv`, `jsonLines`, `parquet` | metaobjects-rules | How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`""`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. | +| `@format` | string | yes | | `csv`, `jsonLines`, `parquet` | metaobjects-rules | How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`""`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. | | `@path` | string | no | | | metaobjects-rules | The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store. | | `@transport` | string | yes | | `sftp`, `objectStore` | metaobjects-rules | How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product. | diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 3d8148db6f..324a07dd19 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -396,7 +396,7 @@ "jsonLines", "parquet" ], - "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`\"\"`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "name": "path", diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs index a6d7d1e65c..a6df2d7304 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs @@ -49,11 +49,13 @@ // effective method and the same path once placeholder names are ignored // // Operations of an api.eventing or api.batch (event, export, import) are not commands or queries: -// only O1 applies to them, with two rules of their own: +// only O1 applies to them, with three rules of their own: // D1 ERR_BAD_ATTR_VALUE an operation.export @availableBy does not have the form its // @frequency gives (AVAILABLE_BY_PATTERNS) // D2 ERR_BAD_ATTR_VALUE a binding.file @fileName holds a placeholder other than {date} or // {timestamp}, or an unclosed brace +// D3 ERR_BAD_ATTR_VALUE an operation.event @key is not an effective field of the +// object its @outputRef names using System.Text.RegularExpressions; using MetaObjects.Core.Transition; @@ -269,10 +271,18 @@ private static bool CheckShapes(MetaData op, RulesErrorSink sink) } /// The checks for one operation of an api.eventing or api.batch: its shapes (O1), the form of an - /// export's @availableBy (D1) and the placeholders of each binding.file @fileName (D2). + /// export's @availableBy (D1), the placeholders of each binding.file @fileName (D2) and an event's @key (D3). private static void CheckDeliveryOperation(MetaData op, RulesErrorSink sink) { if (!CheckShapes(op, sink)) return; + if (op.SubType == OPERATION_SUBTYPE_EVENT && op.Attr(OPERATION_ATTR_KEY) is string key + && op.Attr(OPERATION_ATTR_OUTPUT_REF) is string outputRef + && Lifecycles.ResolveObjectOn(op, outputRef) is { } output + && !output.Children().Any(c => c.Type == TYPE_FIELD && c.Name == key)) + { + sink.Add(op, ErrorCode.ERR_BAD_ATTR_VALUE, + $"operation.event \"{RulesLabel(op)}\" @key \"{key}\" is not a field of \"{output.Name}\"; @key names the payload field whose events stay in order."); + } if (op.Attr(OPERATION_ATTR_AVAILABLE_BY) is string availableBy && op.Attr(OPERATION_ATTR_FREQUENCY) is string frequency && AVAILABLE_BY_PATTERNS.TryGetValue(frequency, out var pattern) && !pattern.IsMatch(availableBy)) { diff --git a/server/csharp/MetaObjects/SpecMetamodel/api.json b/server/csharp/MetaObjects/SpecMetamodel/api.json index ad58f864d1..31d734056d 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/api.json +++ b/server/csharp/MetaObjects/SpecMetamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`\"\"`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryNode.java b/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryApi.java similarity index 55% rename from server/java/metadata/src/main/java/com/metaobjects/api/DeliveryNode.java rename to server/java/metadata/src/main/java/com/metaobjects/api/DeliveryApi.java index 82bc9d15e8..0a94bb11ed 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryNode.java +++ b/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryApi.java @@ -15,18 +15,11 @@ */ package com.metaobjects.api; -import com.metaobjects.MetaData; - -/** - * One node class for the delivery vocabulary of 1.4.0 (ADR-0030): {@code api.eventing}, - * {@code api.batch}, {@code operation.event|export|import} and {@code binding.messaging|file}. - * They are vocabulary only on the Java port, so one class serves each type and the loader - * constructs it through the 3-argument form. Nothing is generated from them. - */ +/** {@code api.eventing} and {@code api.batch} (ADR-0030). Vocabulary only on the Java port: nothing is generated from it. */ @SuppressWarnings("serial") -public class DeliveryNode extends MetaData { +public class DeliveryApi extends MetaApi { - public DeliveryNode(String type, String subType, String name) { - super(type, subType, name); + public DeliveryApi(String type, String subType, String name) { + super(subType, name); } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryBinding.java b/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryBinding.java new file mode 100644 index 0000000000..356018fc45 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryBinding.java @@ -0,0 +1,25 @@ +/* + * Copyright 2026 Doug Mealing LLC dba Meta Objects + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.metaobjects.api; + +/** {@code binding.messaging} and {@code binding.file} (ADR-0030). Vocabulary only on the Java port: nothing is generated from it. */ +@SuppressWarnings("serial") +public class DeliveryBinding extends MetaBinding { + + public DeliveryBinding(String type, String subType, String name) { + super(subType, name); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryOperation.java b/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryOperation.java new file mode 100644 index 0000000000..42c620c49b --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryOperation.java @@ -0,0 +1,25 @@ +/* + * Copyright 2026 Doug Mealing LLC dba Meta Objects + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.metaobjects.api; + +/** {@code operation.event}, {@code operation.export} and {@code operation.import} (ADR-0030). Vocabulary only on the Java port: nothing is generated from it. */ +@SuppressWarnings("serial") +public class DeliveryOperation extends MetaOperation { + + public DeliveryOperation(String type, String subType, String name) { + super(subType, name); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryTypes.java b/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryTypes.java index 3e5fb7f0d5..b1d51f4b7c 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryTypes.java +++ b/server/java/metadata/src/main/java/com/metaobjects/api/DeliveryTypes.java @@ -29,35 +29,35 @@ private DeliveryTypes() { } public static void registerTypes(MetaDataRegistry registry) { - type(registry, ApiConstants.TYPE_API, ApiConstants.API_SUBTYPE_EVENTING, d -> + type(registry, DeliveryApi.class, ApiConstants.TYPE_API, ApiConstants.API_SUBTYPE_EVENTING, d -> d.optionalChild(ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_EVENT, "*")); - type(registry, ApiConstants.TYPE_API, ApiConstants.API_SUBTYPE_BATCH, d -> { + type(registry, DeliveryApi.class, ApiConstants.TYPE_API, ApiConstants.API_SUBTYPE_BATCH, d -> { d.optionalChild(ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_EXPORT, "*"); d.optionalChild(ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_IMPORT, "*"); }); - type(registry, ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_EVENT, d -> { + type(registry, DeliveryOperation.class, ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_EVENT, d -> { d.optionalChild(ApiConstants.TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_MESSAGING, "*"); required(d, ApiConstants.ATTR_OUTPUT_REF); optional(d, ApiConstants.ATTR_KEY); }); - type(registry, ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_EXPORT, d -> { + type(registry, DeliveryOperation.class, ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_EXPORT, d -> { d.optionalChild(ApiConstants.TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_FILE, "*"); required(d, ApiConstants.ATTR_OUTPUT_REF); d.requiredAttributeWithConstraints(ApiConstants.ATTR_FREQUENCY).ofType(StringAttribute.SUBTYPE_STRING) .withEnum(ApiConstants.FREQUENCIES.toArray(new String[0])); optional(d, ApiConstants.ATTR_AVAILABLE_BY); }); - type(registry, ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_IMPORT, d -> { + type(registry, DeliveryOperation.class, ApiConstants.TYPE_OPERATION, ApiConstants.OPERATION_SUBTYPE_IMPORT, d -> { d.optionalChild(ApiConstants.TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_FILE, "*"); required(d, ApiConstants.ATTR_INPUT_REF); d.requiredAttributeWithConstraints(ApiConstants.ATTR_FREQUENCY).ofType(StringAttribute.SUBTYPE_STRING) .withEnum(ApiConstants.FREQUENCIES.toArray(new String[0])); }); - type(registry, ApiConstants.TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_MESSAGING, d -> + type(registry, DeliveryBinding.class, ApiConstants.TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_MESSAGING, d -> enumAttr(d, false, ApiConstants.ATTR_PROTOCOL, "kafka", "amqp", "mqtt", "sqs")); - type(registry, ApiConstants.TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_FILE, d -> { + type(registry, DeliveryBinding.class, ApiConstants.TYPE_BINDING, ApiConstants.BINDING_SUBTYPE_FILE, d -> { enumAttr(d, true, ApiConstants.ATTR_TRANSPORT, "sftp", "objectStore"); optional(d, ApiConstants.ATTR_PATH); required(d, ApiConstants.ATTR_FILE_NAME); @@ -68,8 +68,9 @@ public static void registerTypes(MetaDataRegistry registry) { }); } - private static void type(MetaDataRegistry registry, String type, String subType, Consumer body) { - registry.registerType(DeliveryNode.class, d -> { + private static void type(MetaDataRegistry registry, Class nodeClass, String type, String subType, + Consumer body) { + registry.registerType(nodeClass, d -> { d.type(type).subType(subType) .description(type + "." + subType + " (ADR-0030)") .inheritsFrom(type, MetaData.SUBTYPE_BASE); diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java index a3160394f7..e3177cd774 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java @@ -409,10 +409,21 @@ private static boolean checkShapes(MetaData op, Sink sink) { /** * The checks for one operation of an api.eventing or api.batch: its shapes (O1), the form of an - * export's {@code @availableBy} (D1) and the placeholders of each binding.file {@code @fileName} (D2). + * export's {@code @availableBy} (D1), the placeholders of each binding.file {@code @fileName} (D2) and an + * event's {@code @key} (D3). */ private static void checkDeliveryOperation(MetaData op, Sink sink) { if (!checkShapes(op, sink)) return; + String key = Lifecycles.stringValue(op, ApiConstants.ATTR_KEY); + String outputRef = Lifecycles.stringValue(op, ApiConstants.ATTR_OUTPUT_REF); + MetaData output = ApiConstants.OPERATION_SUBTYPE_EVENT.equals(op.getSubType()) && key != null && outputRef != null + ? Lifecycles.resolveObjectOn(op, outputRef) : null; + if (output != null && output.getChildren(MetaData.class, true).stream() + .noneMatch(c -> MetaField.TYPE_FIELD.equals(c.getType()) && c.getShortName().equals(key))) { + sink.add(op, ErrorCode.ERR_BAD_ATTR_VALUE, + "operation.event \"" + label(op) + "\" @key \"" + key + "\" is not a field of \"" + output.getShortName() + + "\"; @key names the payload field whose events stay in order."); + } String frequency = Lifecycles.stringValue(op, ApiConstants.ATTR_FREQUENCY); String availableBy = Lifecycles.stringValue(op, ApiConstants.ATTR_AVAILABLE_BY); if (availableBy != null && frequency != null && ApiConstants.FREQUENCIES.contains(frequency) diff --git a/server/python/src/metaobjects/loader/validate_rules.py b/server/python/src/metaobjects/loader/validate_rules.py index 42010ecf98..16830de5f9 100644 --- a/server/python/src/metaobjects/loader/validate_rules.py +++ b/server/python/src/metaobjects/loader/validate_rules.py @@ -70,6 +70,7 @@ BUSINESS_ERROR_CODE_PATTERN, OPERATION_ATTR_ERRORS, OPERATION_ATTR_INPUT_REF, + OPERATION_ATTR_KEY, OPERATION_ATTR_MANY, OPERATION_ATTR_OBJECT_REF, OPERATION_ATTR_OUTPUT_REF, @@ -78,6 +79,7 @@ OPERATION_ATTR_TRANSITIONS, PERMISSION_NAME_PATTERN, OPERATION_SUBTYPE_COMMAND, + OPERATION_SUBTYPE_EVENT, RESERVED_ERROR_CODES, RESERVED_OPERATION_NAMES, ) @@ -488,10 +490,21 @@ def _file_name_placeholder_problem(file_name: str) -> str | None: def _check_delivery_operation(op: MetaData, sink: _Sink) -> None: - """O1, D1 and D2 for one operation of an api.eventing or api.batch: its shapes, the form of an - export's @availableBy and the placeholders of each binding.file @fileName.""" + """O1, D1, D2 and D3 for one operation of an api.eventing or api.batch: its shapes, the form of an + export's @availableBy, the placeholders of each binding.file @fileName and an event's @key.""" if not _check_shapes(op, sink): return + key = op.get_meta_attr(OPERATION_ATTR_KEY) + output_ref = op.get_meta_attr(OPERATION_ATTR_OUTPUT_REF) + if op.sub_type == OPERATION_SUBTYPE_EVENT and isinstance(key, str) and isinstance(output_ref, str): + output = resolve_object_on(op, output_ref) + if output is not None and not any(c.type == TYPE_FIELD and c.name == key for c in output.children()): + sink.add( + op, + ErrorCode.ERR_BAD_ATTR_VALUE, + f'operation.event "{_label(op)}" @key "{key}" is not a field of "{output.name}"; ' + "@key names the payload field whose events stay in order.", + ) frequency = op.get_meta_attr(OPERATION_ATTR_FREQUENCY) available_by = op.get_meta_attr(OPERATION_ATTR_AVAILABLE_BY) if ( diff --git a/server/python/src/metaobjects/spec_metamodel/api.json b/server/python/src/metaobjects/spec_metamodel/api.json index ad58f864d1..31d734056d 100644 --- a/server/python/src/metaobjects/spec_metamodel/api.json +++ b/server/python/src/metaobjects/spec_metamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`\"\"`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } diff --git a/server/rust/metaobjects/data/metamodel/api.json b/server/rust/metaobjects/data/metamodel/api.json index ad58f864d1..31d734056d 100644 --- a/server/rust/metaobjects/data/metamodel/api.json +++ b/server/rust/metaobjects/data/metamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`\"\"`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs index 8943df00a4..cd913137dc 100644 --- a/server/rust/metaobjects/src/validate/rules.rs +++ b/server/rust/metaobjects/src/validate/rules.rs @@ -46,11 +46,13 @@ //! B2 ERR_BINDING_PATH_MISMATCH two bindings of one API share a method and a path //! //! Operations of an api.eventing or api.batch (event, export, import) are not commands or -//! queries: only O1 applies to them, with two rules of their own: +//! queries: only O1 applies to them, with three rules of their own: //! D1 ERR_BAD_ATTR_VALUE an operation.export @availableBy lacks the form its //! @frequency gives //! D2 ERR_BAD_ATTR_VALUE a binding.file @fileName holds a placeholder other than //! {date} or {timestamp}, or an unclosed brace +//! D3 ERR_BAD_ATTR_VALUE an operation.event @key is not an effective field of +//! the object its @outputRef names //! ``` //! //! Everything a lifecycle has beyond its transitions is derived, with no vocabulary of @@ -98,6 +100,7 @@ const SUB_QUERY: &str = "query"; const SUB_REST: &str = "rest"; const SUB_OPERATIONAL: &str = "operational"; const SUB_FILE: &str = "file"; +const SUB_EVENT: &str = "event"; const SUB_PRIMARY: &str = "primary"; const A_DEFAULT: &str = "default"; @@ -119,6 +122,7 @@ const A_FIELDS: &str = "fields"; const A_FREQUENCY: &str = "frequency"; const A_AVAILABLE_BY: &str = "availableBy"; const A_FILE_NAME: &str = "fileName"; +const A_KEY: &str = "key"; /// The placeholders a binding.file `@fileName` may hold. const FILE_NAME_PLACEHOLDERS: [&str; 2] = ["date", "timestamp"]; @@ -932,7 +936,8 @@ fn file_name_placeholder_problem(file_name: &str) -> Option { } /// The checks for one operation of an api.eventing or api.batch: its shapes (O1), the form of -/// an export's `@availableBy` (D1) and the placeholders of each binding.file `@fileName` (D2). +/// an export's `@availableBy` (D1), the placeholders of each binding.file `@fileName` (D2) and +/// an event's `@key` (D3). fn check_delivery_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) { if !check_shapes(ctx, op, sink) { return; @@ -940,6 +945,24 @@ fn check_delivery_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) { let tree = ctx.tree; let sub = tree.node(op).sub_type.as_str(); let op_label = label(tree, op); + if sub == SUB_EVENT + && let Some(key) = str_attr(tree, op, A_KEY) + && let Some(output) = + str_attr(tree, op, A_OUTPUT_REF).and_then(|r| resolve_object_on(&ctx.env(), op, r)) + && !tree.children(output).iter().any(|&c| { + let n = tree.node(c); + n.type_name == TYPE_FIELD && n.name == key + }) + { + sink.add( + op, + ERR_BAD_ATTR_VALUE, + format!( + "operation.event \"{op_label}\" @key \"{key}\" is not a field of \"{}\"; @key names the payload field whose events stay in order.", + tree.node(output).name + ), + ); + } if let (Some(by), Some(freq)) = ( str_attr(tree, op, A_AVAILABLE_BY), str_attr(tree, op, A_FREQUENCY), diff --git a/server/rust/metaobjects/tests/conformance-expected-failures.json b/server/rust/metaobjects/tests/conformance-expected-failures.json index 8b9e3bf8ea..3d01d4e52f 100644 --- a/server/rust/metaobjects/tests/conformance-expected-failures.json +++ b/server/rust/metaobjects/tests/conformance-expected-failures.json @@ -1,6 +1,6 @@ { "language": "rust", "notes": "The Rust port passes every fixture of the shared metamodel corpus, so the ledger is empty. The ledger may only shrink and is kept for the day a new fixture lands that Rust does not pass yet: list it here with the reason, and it leaves when the work that covers it lands. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.", - "minPassing": 619, + "minPassing": 620, "fixtures": [] } diff --git a/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts b/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts index abb3b2d20b..b13fbbd9bd 100644 --- a/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts @@ -457,7 +457,7 @@ export const API_DEFINITION: ProviderDefinition = { "jsonLines", "parquet" ], - "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`\"\"`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", diff --git a/server/typescript/packages/metadata/src/loader/rules-validation.ts b/server/typescript/packages/metadata/src/loader/rules-validation.ts index ac1fe10b0e..98cfb93343 100644 --- a/server/typescript/packages/metadata/src/loader/rules-validation.ts +++ b/server/typescript/packages/metadata/src/loader/rules-validation.ts @@ -55,11 +55,13 @@ // effective method and the same path once placeholder names are ignored // // Operations of an api.eventing or api.batch (event, export, import) are not commands or queries: -// only O1 applies to them, with two rules of their own: +// only O1 applies to them, with three rules of their own: // D1 ERR_BAD_ATTR_VALUE an operation.export @availableBy does not have the form its // @frequency gives (AVAILABLE_BY_PATTERNS) // D2 ERR_BAD_ATTR_VALUE a binding.file @fileName holds a placeholder other than {date} or // {timestamp}, or an unclosed brace +// D3 ERR_BAD_ATTR_VALUE an operation.event @key is not an effective field of the +// object its @outputRef names import type { MetaData } from "../shared/meta-data.js"; import type { MetaObject } from "../core/object/meta-object.js"; @@ -93,6 +95,7 @@ import { PERMISSION_NAME_PATTERN, OPERATION_ATTR_ERRORS, OPERATION_ATTR_INPUT_REF, + OPERATION_ATTR_KEY, OPERATION_ATTR_MANY, OPERATION_ATTR_OBJECT_REF, OPERATION_ATTR_OUTPUT_REF, @@ -100,6 +103,7 @@ import { OPERATION_ATTR_PUBLIC, OPERATION_ATTR_TRANSITIONS, OPERATION_SUBTYPE_COMMAND, + OPERATION_SUBTYPE_EVENT, RESERVED_ERROR_CODES, RESERVED_OPERATION_NAMES, } from "../core/api/api-constants.js"; @@ -355,9 +359,19 @@ function checkOperation(op: MetaData, sink: Sink): void { } /** The checks for one operation of an api.eventing or api.batch: its shapes (O1), the - * form of an export's @availableBy (D1) and the placeholders of each binding.file @fileName (D2). */ + * form of an export's @availableBy (D1), the placeholders of each binding.file @fileName (D2) + * and an event's @key (D3). */ function checkDeliveryOperation(op: MetaData, sink: Sink): void { if (!checkShapes(op, sink)) return; + const key = op.attr(OPERATION_ATTR_KEY); + const outputRef = op.attr(OPERATION_ATTR_OUTPUT_REF); + if (op.subType === OPERATION_SUBTYPE_EVENT && typeof key === "string" && typeof outputRef === "string") { + const output = resolveObjectOn(op, outputRef); + if (output !== undefined && !output.children().some((c) => c.type === TYPE_FIELD && c.name === key)) { + sink.add(op, "ERR_BAD_ATTR_VALUE", + `operation.event "${label(op)}" @key "${key}" is not a field of "${output.name}"; @key names the payload field whose events stay in order.`); + } + } const frequency = op.attr(OPERATION_ATTR_FREQUENCY); const availableBy = op.attr(OPERATION_ATTR_AVAILABLE_BY); if (typeof availableBy === "string" && typeof frequency === "string" && diff --git a/site-reference/types/binding.html b/site-reference/types/binding.html index a863bdec9f..d5619aecb7 100644 --- a/site-reference/types/binding.html +++ b/site-reference/types/binding.html @@ -117,7 +117,7 @@

      binding.file

      csv, jsonLines, parquet metaobjects-rules -How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted ("") so that it differs from null. A date is YYYY-MM-DD, a time is HH:MM:SS wall time, a timestamp is in UTC and ends in Z, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is true or false, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. +How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (""), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase 8-4-4-4-12. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is true or false. A date is YYYY-MM-DD and a time is HH:MM:SS wall time. A timestamp is in UTC, YYYY-MM-DDTHH:MM:SSZ; one with @localTime is wall time, YYYY-MM-DDTHH:MM:SS with no zone. A duration is ISO 8601 (PT1H30M). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. @path diff --git a/spec/metamodel/api.json b/spec/metamodel/api.json index ad58f864d1..31d734056d 100644 --- a/spec/metamodel/api.json +++ b/spec/metamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside it is doubled. Null is an empty field, and an empty string is always written quoted (`\"\"`) so that it differs from null. A date is `YYYY-MM-DD`, a time is `HH:MM:SS` wall time, a timestamp is in UTC and ends in `Z`, a decimal is plain digits with no exponent, a currency amount is in minor units, a boolean is `true` or `false`, and a double is the shortest text that reads back to the same value, with no exponent. An object, map or array value is its JSON text, quoted by the same rule, so its inner quotes are doubled. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } From b1436d9f72de914876b7dd080b4980c2c4e92ab7 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 5 Dec 2026 00:35:54 -0500 Subject: [PATCH 04/10] no-mistakes(review): Defer CSV value forms to the REST wire contract --- changelog.d/api-eventing-and-batch.md | 6 ++-- docs/features/business-rules.md | 29 +++++++------------ .../metamodel-docs/data/types/binding.md.json | 2 +- .../metamodel-docs/expected/types/binding.md | 2 +- .../expected-registry.json | 2 +- .../csharp/RequirementHarnessTests.cs | 4 +-- .../java/RequirementHarnessTest.java | 4 +-- .../kotlin/RequirementHarnessTest.kt | 4 +-- .../python/test_requirement_harness.py | 4 +-- .../typescript/requirement-harness.test.ts | 4 +-- metaobjects/meta.requirements.yaml | 10 +++---- .../csharp/MetaObjects/SpecMetamodel/api.json | 2 +- .../src/metaobjects/spec_metamodel/api.json | 2 +- .../rust/metaobjects/data/metamodel/api.json | 2 +- .../src/core/api/api-definition.embedded.ts | 2 +- site-reference/types/binding.html | 2 +- spec/metamodel/api.json | 2 +- 17 files changed, 38 insertions(+), 45 deletions(-) diff --git a/changelog.d/api-eventing-and-batch.md b/changelog.d/api-eventing-and-batch.md index bdb33ac8b7..092b255375 100644 --- a/changelog.d/api-eventing-and-batch.md +++ b/changelog.d/api-eventing-and-batch.md @@ -10,9 +10,9 @@ `@completion` and `@encryption`. The file conventions are pinned: `{date}` is the run's start date as `YYYY-MM-DD` and `{timestamp}` is `YYYYMMDDTHHMMSSZ`, both UTC, and are the only placeholders; a `marker` completion is an empty file named the data file's name plus `.done`; - `csv` is RFC 4180 with a header row, an empty string always quoted so it differs from null, and - one written form per field subtype (a UTC timestamp ends in `Z`, a `@localTime` one has no zone, - an object, map or array is its JSON text). `@availableBy` is written `:MM` for an hourly file, + `csv` is RFC 4180 with a header row, an empty string always quoted so it differs from null, an + object, map or array as its JSON text, and every other value in the REST wire contract's + canonical form, whatever the project's `wire` setting. `@availableBy` is written `:MM` for an hourly file, `HH:MM` for daily, `Ddd HH:MM` for weekly and `D HH:MM` (day 1 to 28) for monthly; another form is `ERR_BAD_ATTR_VALUE` (`error-api-export-available-by-weekly-no-day`), and so is any other `@fileName` placeholder (`error-api-binding-file-unknown-placeholder`), and an event `@key` that diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index e62d91a23b..13a215ef86 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -172,24 +172,17 @@ file is in place by, and its form follows the frequency: after every line, UTF-8 with no byte order mark, and a first line of field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`""`), so that it differs from null, - which is an empty field. Each value is written by its field's subtype: - - | Subtype | Written as | - |---|---| - | `string`, `uri`, `inet` | its text | - | `enum` | the member's name | - | `uuid` | lowercase `8-4-4-4-12` | - | `int`, `long` | plain digits with an optional leading minus | - | `decimal` | the same, with a decimal point where it has one, never an exponent | - | `double`, `float` | the shortest text that reads back to the same value, with no exponent | - | `currency` | an integer in minor units | - | `boolean` | `true` or `false` | - | `date` | `YYYY-MM-DD` | - | `time` | `HH:MM:SS`, wall time | - | `timestamp` | UTC, `YYYY-MM-DDTHH:MM:SSZ`; with `@localTime`, wall time `YYYY-MM-DDTHH:MM:SS` with no zone | - | `duration` | ISO 8601 (`PT1H30M`) | - | `object`, `map`, any array | its JSON text, quoted by the same rule | - + which is an empty field. An object, a map and any array is its JSON text, quoted by the same + rule. Every other value is written in the canonical form of the REST wire contract + ([api-contract.md](api-contract.md) and + [`normalization.md`](../../fixtures/persistence-conformance/normalization.md)), whatever the + project's `wire` setting. Among that contract's forms: a timestamp ends in `Z` and one with + `@localTime` has no zone suffix; a time or timestamp carries a fraction of a second only when it + is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the + canonical string of + [ADR-0019 Amendment 1](../../spec/decisions/ADR-0019-runtime-return-type-contract.md) (plain + notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer + in minor units. `jsonLines` is one JSON object per line, UTF-8, LF after each. - `compression`: `none` (the default) or `gzip`. - `completion`: how a reader knows a file is whole. `rename`: it appears under its final name diff --git a/fixtures/metamodel-docs/data/types/binding.md.json b/fixtures/metamodel-docs/data/types/binding.md.json index df07dd8ad0..6750043709 100644 --- a/fixtures/metamodel-docs/data/types/binding.md.json +++ b/fixtures/metamodel-docs/data/types/binding.md.json @@ -73,7 +73,7 @@ "default": "", "allowed": "`csv`, `jsonLines`, `parquet`", "provider": "metaobjects-rules", - "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "name": "path", diff --git a/fixtures/metamodel-docs/expected/types/binding.md b/fixtures/metamodel-docs/expected/types/binding.md index 86f28db223..ed80b466c8 100644 --- a/fixtures/metamodel-docs/expected/types/binding.md +++ b/fixtures/metamodel-docs/expected/types/binding.md @@ -40,7 +40,7 @@ How a file of an export or import is delivered: where it sits, what it is called | `@compression` | string | no | `none` | `none`, `gzip` | metaobjects-rules | none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk. | | `@encryption` | string | no | `none` | `none`, `pgp` | metaobjects-rules | none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key. | | `@fileName` | string | yes | | | metaobjects-rules | The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE. | -| `@format` | string | yes | | `csv`, `jsonLines`, `parquet` | metaobjects-rules | How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`""`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. | +| `@format` | string | yes | | `csv`, `jsonLines`, `parquet` | metaobjects-rules | How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`""`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. | | `@path` | string | no | | | metaobjects-rules | The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store. | | `@transport` | string | yes | | `sftp`, `objectStore` | metaobjects-rules | How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product. | diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 324a07dd19..98f46d543d 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -396,7 +396,7 @@ "jsonLines", "parquet" ], - "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "name": "path", diff --git a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs index e256bc5d49..4404ba86b1 100644 --- a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs +++ b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs @@ -68,7 +68,7 @@ public void declare_businessRules_apiOperational() { /* metaobjects.declare.busi [Fact(Skip = "unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.")] public void declare_businessRules_bindingFile() { /* metaobjects.declare.businessRules.bindingFile */ } - // Messaging binding — A messaging binding names the protocol an event is published over. + // Messaging binding — A messaging binding may name the protocol an event is published over. [Fact(Skip = "unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another.")] public void declare_businessRules_bindingMessaging() { /* metaobjects.declare.businessRules.bindingMessaging */ } @@ -84,7 +84,7 @@ public void declare_businessRules_operationCommand() { /* metaobjects.declare.bu [Fact(Skip = "unfilled slot — write an assertion that fails when: Two consumers that assume different ordering keys for one stream, and each processes some events out of order.")] public void declare_businessRules_operationEvent() { /* metaobjects.declare.businessRules.operationEvent */ } - // Export — An export names the shape of one row of the file, how often the file is written, and by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. + // Export — An export names the shape of one row of the file and how often the file is written, and may name by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. [Fact(Skip = "unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week.")] public void declare_businessRules_operationExport() { /* metaobjects.declare.businessRules.operationExport */ } diff --git a/fixtures/requirement-harness/java/RequirementHarnessTest.java b/fixtures/requirement-harness/java/RequirementHarnessTest.java index b6c5150be6..8f1e5a61f1 100644 --- a/fixtures/requirement-harness/java/RequirementHarnessTest.java +++ b/fixtures/requirement-harness/java/RequirementHarnessTest.java @@ -82,7 +82,7 @@ void declare_businessRules_apiOperational() { /* metaobjects.declare.businessRul @Disabled("unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.") void declare_businessRules_bindingFile() { /* metaobjects.declare.businessRules.bindingFile */ } - // Messaging binding — A messaging binding names the protocol an event is published over. + // Messaging binding — A messaging binding may name the protocol an event is published over. @Test @Disabled("unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another.") void declare_businessRules_bindingMessaging() { /* metaobjects.declare.businessRules.bindingMessaging */ } @@ -102,7 +102,7 @@ void declare_businessRules_operationCommand() { /* metaobjects.declare.businessR @Disabled("unfilled slot — write an assertion that fails when: Two consumers that assume different ordering keys for one stream, and each processes some events out of order.") void declare_businessRules_operationEvent() { /* metaobjects.declare.businessRules.operationEvent */ } - // Export — An export names the shape of one row of the file, how often the file is written, and by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. + // Export — An export names the shape of one row of the file and how often the file is written, and may name by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. @Test @Disabled("unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week.") void declare_businessRules_operationExport() { /* metaobjects.declare.businessRules.operationExport */ } diff --git a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt index 1bf4caa0f0..1daf976aae 100644 --- a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt +++ b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt @@ -82,7 +82,7 @@ class RequirementHarnessTest { @Disabled("unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.") fun declare_businessRules_bindingFile() { /* metaobjects.declare.businessRules.bindingFile */ } - // Messaging binding — A messaging binding names the protocol an event is published over. + // Messaging binding — A messaging binding may name the protocol an event is published over. @Test @Disabled("unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another.") fun declare_businessRules_bindingMessaging() { /* metaobjects.declare.businessRules.bindingMessaging */ } @@ -102,7 +102,7 @@ class RequirementHarnessTest { @Disabled("unfilled slot — write an assertion that fails when: Two consumers that assume different ordering keys for one stream, and each processes some events out of order.") fun declare_businessRules_operationEvent() { /* metaobjects.declare.businessRules.operationEvent */ } - // Export — An export names the shape of one row of the file, how often the file is written, and by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. + // Export — An export names the shape of one row of the file and how often the file is written, and may name by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. @Test @Disabled("unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week.") fun declare_businessRules_operationExport() { /* metaobjects.declare.businessRules.operationExport */ } diff --git a/fixtures/requirement-harness/python/test_requirement_harness.py b/fixtures/requirement-harness/python/test_requirement_harness.py index 74ded53162..2a3abd371f 100644 --- a/fixtures/requirement-harness/python/test_requirement_harness.py +++ b/fixtures/requirement-harness/python/test_requirement_harness.py @@ -77,7 +77,7 @@ def test_declare_businessRules_apiOperational(): def test_declare_businessRules_bindingFile(): """metaobjects.declare.businessRules.bindingFile""" -# Messaging binding — A messaging binding names the protocol an event is published over. +# Messaging binding — A messaging binding may name the protocol an event is published over. @pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another.") def test_declare_businessRules_bindingMessaging(): """metaobjects.declare.businessRules.bindingMessaging""" @@ -97,7 +97,7 @@ def test_declare_businessRules_operationCommand(): def test_declare_businessRules_operationEvent(): """metaobjects.declare.businessRules.operationEvent""" -# Export — An export names the shape of one row of the file, how often the file is written, and by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. +# Export — An export names the shape of one row of the file and how often the file is written, and may name by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. @pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week.") def test_declare_businessRules_operationExport(): """metaobjects.declare.businessRules.operationExport""" diff --git a/fixtures/requirement-harness/typescript/requirement-harness.test.ts b/fixtures/requirement-harness/typescript/requirement-harness.test.ts index 9c9c18fadb..98d8772b23 100644 --- a/fixtures/requirement-harness/typescript/requirement-harness.test.ts +++ b/fixtures/requirement-harness/typescript/requirement-harness.test.ts @@ -77,7 +77,7 @@ test.skip("metaobjects.declare.businessRules.bindingFile", () => { // unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done. }); -// Messaging binding — A messaging binding names the protocol an event is published over. +// Messaging binding — A messaging binding may name the protocol an event is published over. test.skip("metaobjects.declare.businessRules.bindingMessaging", () => { // unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another. }); @@ -97,7 +97,7 @@ test.skip("metaobjects.declare.businessRules.operationEvent", () => { // unfilled slot — write an assertion that fails when: Two consumers that assume different ordering keys for one stream, and each processes some events out of order. }); -// Export — An export names the shape of one row of the file, how often the file is written, and by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. +// Export — An export names the shape of one row of the file and how often the file is written, and may name by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day. test.skip("metaobjects.declare.businessRules.operationExport", () => { // unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week. }); diff --git a/metaobjects/meta.requirements.yaml b/metaobjects/meta.requirements.yaml index ce098b8d58..2f5d990158 100644 --- a/metaobjects/meta.requirements.yaml +++ b/metaobjects/meta.requirements.yaml @@ -1659,10 +1659,10 @@ metadata.root: level: 4 status: live statement: >- - An export names the shape of one row of the file, how often - the file is written, and by when in UTC it is ready, in the - one form its frequency allows; a weekly or monthly file names - its day. + An export names the shape of one row of the file and how often + the file is written, and may name by when in UTC it is ready, + in the one form its frequency allows; a weekly or monthly file + names its day. counterexample: >- A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week. @@ -1683,7 +1683,7 @@ metadata.root: level: 4 status: live statement: >- - A messaging binding names the protocol an event is published + A messaging binding may name the protocol an event is published over. counterexample: >- An event published over one broker protocol while its consumer diff --git a/server/csharp/MetaObjects/SpecMetamodel/api.json b/server/csharp/MetaObjects/SpecMetamodel/api.json index 31d734056d..a0eda80596 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/api.json +++ b/server/csharp/MetaObjects/SpecMetamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } diff --git a/server/python/src/metaobjects/spec_metamodel/api.json b/server/python/src/metaobjects/spec_metamodel/api.json index 31d734056d..a0eda80596 100644 --- a/server/python/src/metaobjects/spec_metamodel/api.json +++ b/server/python/src/metaobjects/spec_metamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } diff --git a/server/rust/metaobjects/data/metamodel/api.json b/server/rust/metaobjects/data/metamodel/api.json index 31d734056d..a0eda80596 100644 --- a/server/rust/metaobjects/data/metamodel/api.json +++ b/server/rust/metaobjects/data/metamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } diff --git a/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts b/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts index b13fbbd9bd..5a786e6fbd 100644 --- a/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts @@ -457,7 +457,7 @@ export const API_DEFINITION: ProviderDefinition = { "jsonLines", "parquet" ], - "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", diff --git a/site-reference/types/binding.html b/site-reference/types/binding.html index d5619aecb7..ffd4b487cc 100644 --- a/site-reference/types/binding.html +++ b/site-reference/types/binding.html @@ -117,7 +117,7 @@

      binding.file

      csv, jsonLines, parquet metaobjects-rules -How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (""), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase 8-4-4-4-12. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is true or false. A date is YYYY-MM-DD and a time is HH:MM:SS wall time. A timestamp is in UTC, YYYY-MM-DDTHH:MM:SSZ; one with @localTime is wall time, YYYY-MM-DDTHH:MM:SS with no zone. A duration is ISO 8601 (PT1H30M). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. +How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (""), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in Z and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as 0); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. @path diff --git a/spec/metamodel/api.json b/spec/metamodel/api.json index 31d734056d..a0eda80596 100644 --- a/spec/metamodel/api.json +++ b/spec/metamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. A string, uri or inet is its text, an enum is its member's name and a uuid is lowercase `8-4-4-4-12`. An int or long is plain digits with an optional leading minus, and a decimal is the same with a decimal point where it has one, never an exponent. A double or float is the shortest text that reads back to the same value, with no exponent. A currency amount is an integer in minor units. A boolean is `true` or `false`. A date is `YYYY-MM-DD` and a time is `HH:MM:SS` wall time. A timestamp is in UTC, `YYYY-MM-DDTHH:MM:SSZ`; one with @localTime is wall time, `YYYY-MM-DDTHH:MM:SS` with no zone. A duration is ISO 8601 (`PT1H30M`). An object, a map and any array is its JSON text, quoted by the same rule. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } From 30b57b78b60bd161c2fd0ad4d36ebe87ce2eb42f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 5 Dec 2026 00:50:03 -0500 Subject: [PATCH 05/10] no-mistakes(review): Enforce closed attr sets in Java; ledger version gate --- AGENTS.md | 2 +- changelog.d/api-eventing-and-batch.md | 10 ++- docs/CONFORMANCE.md | 10 +-- .../expected-errors.json | 15 ++++ .../input/meta.ledger.json | 25 ++++++ .../expected-errors.json | 15 ++++ .../input/meta.ledger.json | 16 ++++ scripts/check-metamodel-version.mjs | 90 ++++++++++--------- scripts/metamodel-version-exceptions.json | 50 +++++++++++ scripts/test-metamodel-version.mjs | 90 ++++++++----------- .../loader/ReportingValidation.java | 46 +--------- .../metaobjects/loader/RulesValidation.java | 13 --- .../metaobjects/loader/ValidationPhase.java | 67 ++++++++------ .../registry/MetaDataRegistry.java | 20 +++-- .../loader/ReportingValidationTest.java | 16 ++-- .../RulesValidationMethodOrderTest.java | 10 +-- .../tests/conformance-expected-failures.json | 2 +- 17 files changed, 297 insertions(+), 200 deletions(-) create mode 100644 fixtures/conformance/error-api-binding-file-format-fixed-width/expected-errors.json create mode 100644 fixtures/conformance/error-api-binding-file-format-fixed-width/input/meta.ledger.json create mode 100644 fixtures/conformance/error-api-export-frequency-unknown/expected-errors.json create mode 100644 fixtures/conformance/error-api-export-frequency-unknown/input/meta.ledger.json create mode 100644 scripts/metamodel-version-exceptions.json diff --git a/AGENTS.md b/AGENTS.md index b5cfb45c5d..b355f8ed81 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,7 +74,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (laid out by `KotlinWriter`, ADR-0063, on the JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (620 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (622 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / Java / Kotlin / Python / C# / Rust byte-identical; the C# and Rust drift ledgers are empty (`docs/CONFORMANCE.md`). - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python; `op: guardedUpdate` is TS-only until each port's 1.3.0 guarded update lands), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (the Node reference helper writes them; a native tool is equally first-class, ADR-0015 Amendment 2). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/changelog.d/api-eventing-and-batch.md b/changelog.d/api-eventing-and-batch.md index 092b255375..91ab15ce8f 100644 --- a/changelog.d/api-eventing-and-batch.md +++ b/changelog.d/api-eventing-and-batch.md @@ -32,5 +32,13 @@ `metamodelVersion` stays at `1.4`. Upgrading: `operation.base` no longer declares attributes; a command and a query declare the - same ones themselves, so a model loads as before. The `ERR_TRANSITION_NOT_ON_ENTITY` message in + same ones themselves, so a model loads as before. A project provider's own operation subtype no + longer inherits `@inputRef`, `@outputRef`, `@objectRef`, `@permission`, `@public` or binding + children from `operation.base`, and is not admitted under `api.operational`, which now takes + `operation.command` and `operation.query` only; such a provider declares those attributes itself + and places its subtype under its own API type. Java and Kotlin now refuse an attribute value + outside its registered closed set (`ERR_BAD_ATTR_VALUE`, with the TypeScript message), as the + other ports already did, so `binding.file @format: fixedWidth` + (`error-api-binding-file-format-fixed-width`) and `operation.export @frequency: yearly` + (`error-api-export-frequency-unknown`) fail there too; no shipped model or fixture needed a change. The `ERR_TRANSITION_NOT_ON_ENTITY` message in C#, Java and Kotlin, Python and Rust now reads as the TypeScript one does. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 0b6976c920..e29f4df7b9 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | Rust | |---|---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 620 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (620 / 620, empty ledger) | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 622 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (622 / 622, empty ledger) | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | 19 / 19 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | — | @@ -82,7 +82,7 @@ and render ledgers; the api-contract runner's list of sub-corpora not built yet) shrink, and the corpora without one assert each case outright. A new fixture that fails in Rust and is not on the ledger prints a warning and does not fail the lane; it becomes a hard failure when ADR-0065 turns the warning off. A regression still fails: the ledger's -`minPassing` (620) is the number of fixtures known to pass, and the run fails when fewer do. +`minPassing` (622) is the number of fixtures known to pass, and the run fails when fewer do. Beside the corpora it runs the codegen-compile gate (below) with every shipped generator, a scale gate over twenty copies of the fitness model, and `examples/rust-service/`'s HTTP test. [The Rust port page](ports/rust.md#conformance) has the detail. @@ -445,7 +445,7 @@ carry it, and a model that uses it fails there by name. There is no row per pack ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (620) +### `fixtures/conformance/` — metamodel loader + canonical serializer (622) | Fixture prefix | Feature doc | |---|---| @@ -470,7 +470,7 @@ carry it, and a model that uses it fails there by name. There is no row per pack | `requirement-*`, `error-unknown-attr-requirement` | [features/requirements.md](features/requirements.md) (vocabulary only — the gate has its own corpus, `requirement-check-conformance/`; see "Split coverage" above) | | `systems-vocabulary`, `error-ref-wrong-kind-runsas`, `error-ref-unresolved-runsas`, `ref-target-type-list-heldby`, `error-ref-wrong-kind-heldby`, `error-ref-ambiguous-heldby`, `error-resource-residency-bad-value`, `error-app-two-builds`, `error-app-three-builds`, `error-app-build-beside-inherited`, `systems-grants-and-sources`, `error-ref-unresolved-grant-resource`, `error-ref-wrong-kind-grant-rdb-on-queue`, `error-ref-wrong-kind-source-rdb-on-document`, `error-ref-wrong-kind-grant-stream-on-other-system-queue`, `error-grant-crosses-system`, `error-runsas-other-system`, `error-duplicate-name-in-system`, `systems-duplicate-name-overlay-in-system`, `error-ref-ambiguous-heldby-bare-name`, `systems-rdb-with-search-copy`, `systems-role-grants-across-files`, `systems-document-only-lifecycle-inert`, `systems-sql-view-with-search-copy`, `systems-payload-ref-search-only-projection`, `error-ref-wrong-kind-carries-batch-on-stream` | [spec/metamodel-definitions.md](../spec/metamodel-definitions.md) (the systems vocabulary, ADR-0070: the reference facet's worked cases, including the target type list behind `@heldBy`, the closed `@residency` set, an app's one build, counting a build it inherits, the grants and their same-system rule, `@resource` on a source, one name per type within a system, a role redeclared in a second file keeping every grant, a search copy beside a SQL view leaving its columns unchecked, a lifecycle that stays inert when its entity has no relational source, and a projection kept only in a search index still serving as a template payload) | | `reporting-*`, `error-dimension-*`, `error-measure-*`, `error-ratio-*`, `error-segment-*`, `error-report-*`, `error-relative-date-*` | [features/reporting.md](features/reporting.md) (the `dimension` / `measure` / `segment` / `object.report` vocabulary and its load-time rules; design in the [FR-044 spec](superpowers/specs/2026-10-02-fr-044-core-reporting-design.md)) | -| `systems-api-eventing-batch`, `error-api-export-available-by-weekly-no-day`, `error-api-binding-file-unknown-placeholder`, `error-api-event-under-operational`, `error-api-event-key-not-a-field` | [features/business-rules.md](features/business-rules.md) ("Eventing and batch APIs": `api.eventing` and `api.batch`, their operations and bindings, what a resource carries and an app provides, and the `@availableBy` and `@fileName` rules D1 and D2, and the event `@key` rule D3) | +| `systems-api-eventing-batch`, `error-api-export-available-by-weekly-no-day`, `error-api-binding-file-unknown-placeholder`, `error-api-event-under-operational`, `error-api-event-key-not-a-field`, `error-api-binding-file-format-fixed-width`, `error-api-export-frequency-unknown` | [features/business-rules.md](features/business-rules.md) ("Eventing and batch APIs": `api.eventing` and `api.batch`, their operations and bindings, what a resource carries and an app provides, and the `@availableBy` and `@fileName` rules D1 and D2, and the event `@key` rule D3) | | `rules-*`, `error-rules-*` | [features/business-rules.md](features/business-rules.md) (operations, permission names and lifecycles: the vocabulary and its load-time rules, ADR-0066; the `verify` gate has its own corpus, `rules-check-conformance/`) | | `provider-extension-*`, `provider-custom-vocabulary-*` | [features/extending-with-providers.md](features/extending-with-providers.md) (a project's own provider: a new subtype plus attributes on an existing type load with it and are refused without it, every port writing the provider in its own language) | | `error-packs-left-out-*` | [features/extending-with-providers.md](features/extending-with-providers.md) ([Where vocabulary lives](features/extending-with-providers.md#where-vocabulary-lives): a model that uses a left-out pack's type fails to load, naming the unknown type or subtype) | @@ -962,7 +962,7 @@ shared input. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 620 + yaml 19 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 622 + yaml 19 + verify 45 + render 26 + persistence 68 + api-contract 191 + source-resolution 30 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `rules-check-conformance`, `shared-model-conformance`, the `cube-model` corpus, `explorer-conformance` and `list-query-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/fixtures/conformance/error-api-binding-file-format-fixed-width/expected-errors.json b/fixtures/conformance/error-api-binding-file-format-fixed-width/expected-errors.json new file mode 100644 index 0000000000..4376672f1f --- /dev/null +++ b/fixtures/conformance/error-api-binding-file-format-fixed-width/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.ledger.json" + ], + "jsonPath": "$['metadata.root'].children[1]['api.batch'].children[0]['operation.export'].children[0]['binding.file']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-api-binding-file-format-fixed-width/input/meta.ledger.json b/fixtures/conformance/error-api-binding-file-format-fixed-width/input/meta.ledger.json new file mode 100644 index 0000000000..df0d59e0bc --- /dev/null +++ b/fixtures/conformance/error-api-binding-file-format-fixed-width/input/meta.ledger.json @@ -0,0 +1,25 @@ +{ + "metadata.root": { + "package": "acme::ledger", + "children": [ + { "object.value": { "name": "SettlementLine", "children": [ { "field.string": { "name": "reference" } } ] } }, + { + "api.batch": { + "name": "SettlementFeed", + "children": [ + { + "operation.export": { + "name": "dailySettlement", + "@outputRef": "SettlementLine", + "@frequency": "daily", + "children": [ + { "binding.file": { "@transport": "sftp", "@fileName": "settlement-{date}.txt", "@format": "fixedWidth" } } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-api-export-frequency-unknown/expected-errors.json b/fixtures/conformance/error-api-export-frequency-unknown/expected-errors.json new file mode 100644 index 0000000000..42917cd350 --- /dev/null +++ b/fixtures/conformance/error-api-export-frequency-unknown/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.ledger.json" + ], + "jsonPath": "$['metadata.root'].children[1]['api.batch'].children[0]['operation.export']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-api-export-frequency-unknown/input/meta.ledger.json b/fixtures/conformance/error-api-export-frequency-unknown/input/meta.ledger.json new file mode 100644 index 0000000000..6d97446597 --- /dev/null +++ b/fixtures/conformance/error-api-export-frequency-unknown/input/meta.ledger.json @@ -0,0 +1,16 @@ +{ + "metadata.root": { + "package": "acme::ledger", + "children": [ + { "object.value": { "name": "SettlementLine", "children": [ { "field.string": { "name": "reference" } } ] } }, + { + "api.batch": { + "name": "SettlementFeed", + "children": [ + { "operation.export": { "name": "yearlySettlement", "@outputRef": "SettlementLine", "@frequency": "yearly" } } + ] + } + } + ] + } +} diff --git a/scripts/check-metamodel-version.mjs b/scripts/check-metamodel-version.mjs index a440ea2520..28f2982b2b 100755 --- a/scripts/check-metamodel-version.mjs +++ b/scripts/check-metamodel-version.mjs @@ -53,6 +53,7 @@ import { fileURLToPath } from "node:url"; const REPO = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const MANIFEST = "fixtures/registry-conformance/expected-registry.json"; +const EXCEPTIONS = "scripts/metamodel-version-exceptions.json"; /** * Every site that declares the metamodel version. The manifest is the one the @@ -174,13 +175,8 @@ export function classify(base, cur) { const b = bT.get(k); if (!b) continue; diffProse(b, c, k, prose); - // An abstract anchor cannot be authored (ERR_ABSTRACT_SUBTYPE_AUTHORED), so no document - // ever set its attrs or gave it children. Its concrete subtypes list what they inherit - // from it as their own, and are diffed below, so a member moved from the anchor down to - // every subtype that uses it is no change to any document. - if (isAbstractAnchor(base, b) && isAbstractAnchor(cur, c)) continue; diffAttrs(b.attrs, c.attrs, k, breaking, additive, prose); - diffChildren(b.children, c.children, k, breaking, additive, base); + diffChildren(b.children, c.children, k, breaking, additive); } // ---- commonAttrs (registered on every node) ---- @@ -250,44 +246,12 @@ function diffAttrs(baseAttrs, curAttrs, where, breaking, additive, prose) { } } -/** - * `.base` is an abstract anchor when its type has another subtype: the loader refuses - * to let it be authored (parser-core `isAbstractAnchorFor`), so the same test applies here. - */ -function isAbstractAnchor(manifest, t) { - return t.subType === "base" && manifest.types.some((o) => o.type === t.type && o.subType !== "base"); -} - -/** - * A wildcard child rule (`operation.*`) narrowed to the subtypes that existed when it was - * written (`operation.command`, `operation.query`) admits every child it admitted before: - * the only change is that a subtype added later is not admitted, and no document holds one. - * Not breaking, provided every concrete subtype of the baseline keeps a rule of its own. - */ -function narrowedToBaseline(removed, curKids, baseManifest) { - if (removed.childSubType !== "*" || !baseManifest) return false; - const subs = baseManifest.types.filter((t) => t.type === removed.childType && !isAbstractAnchor(baseManifest, t)); - if (subs.length === 0) return false; - return subs.every((t) => - curKids.some( - (c) => - c.childType === removed.childType && - c.childSubType === t.subType && - c.childName === removed.childName && - (c.min ?? 0) <= (removed.min ?? 0) && - (removed.max == null ? c.max == null : c.max == null || c.max >= removed.max), - ), - ); -} - -function diffChildren(baseKids, curKids, where, breaking, additive, baseManifest) { +function diffChildren(baseKids, curKids, where, breaking, additive) { const b = byKey(baseKids, childKey); const c = byKey(curKids, childKey); - for (const [k, bk] of b) { - if (!c.has(k) && !narrowedToBaseline(bk, curKids ?? [], baseManifest)) { - breaking.push(`child rule removed: ${where} ← ${k}`); - } + for (const k of b.keys()) { + if (!c.has(k)) breaking.push(`child rule removed: ${where} ← ${k}`); } for (const [k, ck] of c) { if (!b.has(k)) { @@ -319,6 +283,34 @@ function diffChildren(baseKids, curKids, where, breaking, additive, baseManifest const git = (...args) => execFileSync("git", args, { cwd: REPO, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); +/** + * The exceptions ledger: a breaking finding excused against one baseline tag, with its reason. + * Throws when an entry lacks a baseline, a finding or a reason, so no exception is unexplained. + */ +export function readExceptions(ledger) { + const entries = ledger?.exceptions ?? []; + for (const [i, e] of entries.entries()) { + for (const key of ["baseline", "finding", "reason"]) { + if (typeof e?.[key] !== "string" || !e[key].trim()) { + throw new Error(`exception ${i} has no ${key}; every exception names its baseline, finding and reason`); + } + } + } + return entries; +} + +/** Split breaking findings into those still breaking and the exceptions that excused the rest. + * An exception applies only when `against` is exactly its baseline tag. */ +export function applyExceptions(breaking, exceptions, against) { + const applied = []; + const kept = breaking.filter((f) => { + const e = exceptions.find((x) => x.baseline === against && x.finding === f); + if (e) applied.push(e); + return !e; + }); + return { kept, applied }; +} + /** The highest published STABLE release tag on the npm/PyPI/NuGet line (`v0.*` / `v1.*` …). * The four registries cut together, so any one line dates the metamodel baseline. * @@ -479,7 +471,21 @@ function main() { const baseVer = parseVersion(baseline.metamodelVersion, against); const curVer = parseVersion(current.metamodelVersion, "working tree"); - const { breaking, additive, prose } = classify(baseline, current); + const classified = classify(baseline, current); + const { additive, prose } = classified; + let exceptions; + try { + exceptions = readExceptions(JSON.parse(readFileSync(resolve(REPO, EXCEPTIONS), "utf8"))); + } catch (e) { + fail(`${EXCEPTIONS}: ${e.message}`); + } + const { kept: breaking, applied } = applyExceptions(classified.breaking, exceptions, against); + if (applied.length) { + process.stdout.write( + ` metamodel-version: ${applied.length} breaking finding(s) excused against ${against} by ${EXCEPTIONS}:\n` + + `${bullets(applied.map((e) => e.finding))}\n`, + ); + } let severity = "none"; if (breaking.length) severity = "breaking"; else if (additive.length) severity = "additive"; diff --git a/scripts/metamodel-version-exceptions.json b/scripts/metamodel-version-exceptions.json new file mode 100644 index 0000000000..42d5e9f0ae --- /dev/null +++ b/scripts/metamodel-version-exceptions.json @@ -0,0 +1,50 @@ +{ + "$comment": "Breaking findings excused against ONE baseline tag, each with its reason. An entry applies only when that tag is the baseline being compared, so it expires at the next release. Read by scripts/check-metamodel-version.mjs.", + "exceptions": [ + { + "baseline": "v1.3.1", + "finding": "child rule removed: api.operational ← operation.*/*", + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + }, + { + "baseline": "v1.3.1", + "finding": "attr removed: operation.base @inputRef", + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + }, + { + "baseline": "v1.3.1", + "finding": "attr removed: operation.base @objectRef", + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + }, + { + "baseline": "v1.3.1", + "finding": "attr removed: operation.base @outputRef", + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + }, + { + "baseline": "v1.3.1", + "finding": "attr removed: operation.base @permission", + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + }, + { + "baseline": "v1.3.1", + "finding": "attr removed: operation.base @public", + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + }, + { + "baseline": "v1.3.1", + "finding": "child rule removed: operation.base ← binding.*/*", + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + }, + { + "baseline": "v1.3.1", + "finding": "child rule removed: operation.command ← binding.*/*", + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + }, + { + "baseline": "v1.3.1", + "finding": "child rule removed: operation.query ← binding.*/*", + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + } + ] +} diff --git a/scripts/test-metamodel-version.mjs b/scripts/test-metamodel-version.mjs index 037aaffbf4..d41281c5f1 100755 --- a/scripts/test-metamodel-version.mjs +++ b/scripts/test-metamodel-version.mjs @@ -10,7 +10,15 @@ // // node scripts/test-metamodel-version.mjs -import { classify, requiredBump, satisfies, parseVersion, pickBaselineTag } from "./check-metamodel-version.mjs"; +import { + applyExceptions, + classify, + parseVersion, + pickBaselineTag, + readExceptions, + requiredBump, + satisfies, +} from "./check-metamodel-version.mjs"; let fails = 0; const ok = (m) => console.log(`ok: ${m}`); @@ -267,58 +275,38 @@ check( ); // --------------------------------------------------------------------------- -// Abstract anchors and narrowed wildcards (1.4.0: operation.base's members moved down to -// command and query, and api.operational's `operation.*` narrowed to the two that existed) +// The exceptions ledger: a breaking finding excused against one baseline tag only // --------------------------------------------------------------------------- -const shared = [attr("inputRef")]; -const op = (attrs, kids = []) => [ - type("operation", "base", { attrs, children: kids }), - type("operation", "command", { attrs: shared, children: [child("binding")] }), -]; -check( - "an attr or child rule moved off an abstract anchor its subtypes still list is NOT breaking", - manifest({ types: op(shared, [child("binding")]) }), - manifest({ types: op([]) }), - {}, -); -check( - "a lone `base` is no anchor: removing its attr is still BREAKING", - manifest({ types: [type("thing", "base", { attrs: [attr("a")] })] }), - manifest({ types: [type("thing", "base")] }), - { breaking: 1 }, -); -check( - "an attr a concrete subtype loses is still BREAKING, whatever the anchor did", - manifest({ types: op(shared) }), - manifest({ types: [type("operation", "base"), type("operation", "command")] }), - { breaking: 2 }, // its attr and its child rule -); - -const ops = [type("operation", "base"), type("operation", "command"), type("operation", "query")]; -const holder = (kids, extra = []) => - manifest({ types: [type("api", "operational", { children: kids }), ...ops, ...extra] }); -check( - "a wildcard narrowed to every concrete subtype of the baseline is NOT breaking", - holder([child("operation")]), - holder( - [child("operation", { childSubType: "command" }), child("operation", { childSubType: "query" })], - [type("operation", "event")], - ), - { additive: 3 }, -); -check( - "a wildcard narrowed to SOME of the baseline's subtypes is BREAKING", - holder([child("operation")]), - holder([child("operation", { childSubType: "command" })]), - { breaking: 1, additive: 1 }, -); -check( - "a wildcard narrowed to a rule that now requires the child is BREAKING", - holder([child("operation")]), - holder([child("operation", { childSubType: "command", min: 1 }), child("operation", { childSubType: "query" })]), - { breaking: 2, additive: 1 }, -); +{ + const removed = classify( + manifest({ types: [type("thing", "a", { attrs: [attr("x"), attr("y")] })] }), + manifest({ types: [type("thing", "a")] }), + ).breaking; + const ledger = readExceptions({ + exceptions: [{ baseline: "v1.3.1", finding: "attr removed: thing.a @x", reason: "nobody could set it" }], + }); + const same = applyExceptions(removed, ledger, "v1.3.1"); + if (same.kept.length === 1 && same.kept[0] === "attr removed: thing.a @y" && same.applied.length === 1) { + ok("a listed finding against its baseline is excused, and an unlisted one still breaks"); + } else { + bad(`exceptions against their baseline: ${JSON.stringify(same)}`); + } + const other = applyExceptions(removed, ledger, "v1.4.0"); + if (other.kept.length === 2 && other.applied.length === 0) { + ok("a listed finding compared against a different baseline still breaks"); + } else { + bad(`exceptions against another baseline: ${JSON.stringify(other)}`); + } + let refused = false; + try { + readExceptions({ exceptions: [{ baseline: "v1.3.1", finding: "attr removed: thing.a @x", reason: " " }] }); + } catch { + refused = true; + } + if (refused) ok("a ledger entry with no reason is refused"); + else bad("a ledger entry with no reason was accepted"); +} // --------------------------------------------------------------------------- // Required bump + satisfaction diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java index eedad7b05f..9513525b90 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java @@ -166,8 +166,6 @@ static List validate(MetaRoot root) { // F1 on every host that is not a reporting host. checkNoRelativeDates(root, root, sink); - // Java-only: closed-set membership the TS registry enforces generically. - checkClosedSets(root, sink); return sink.errors; } @@ -375,7 +373,7 @@ private static String displayName(MetaData node) { } /** {@code . ''}, or just {@code .} for an unnamed node. */ - private static String childLabel(MetaData node) { + static String childLabel(MetaData node) { String head = node.getType() + "." + node.getSubType(); String name = displayName(node); return name.isEmpty() ? head : head + " '" + name + "'"; @@ -1418,46 +1416,4 @@ && filterContainsRelativeValue(((MetaAttribute) c).getValue())) { if (!(c instanceof MetaAttribute)) checkNoRelativeDates(root, c, sink); } } - - // --------------------------------------------------------------------------- - // Closed sets (Java: the registry's allowedValues are not enforced generically) - // --------------------------------------------------------------------------- - - /** - * {@code measure.aggregate @agg} and {@code dimension.time @grains} hold members of their - * closed sets ({@code ERR_BAD_ATTR_VALUE}, one error per offending value, as the TS - * attr-schema check reports them). - */ - private static void checkClosedSets(MetaData node, ErrorSink sink) { - if (node instanceof MetaMeasure && ReportingConstants.MEASURE_SUBTYPE_AGGREGATE.equals(node.getSubType())) { - // ADR-0039: own — an attr rule validates the attr on the node that DECLARES it. - String agg = node.hasMetaAttr(ReportingConstants.ATTR_AGG, false) - ? stringAttr(node, ReportingConstants.ATTR_AGG) : null; - if (agg != null && !ReportingConstants.MEASURE_AGGS.contains(agg)) { - pushBadValue(node, ReportingConstants.ATTR_AGG, agg, ReportingConstants.MEASURE_AGGS, sink); - } - } - if (node instanceof MetaDimension && ((MetaDimension) node).isTime() - // ADR-0039: own — an attr rule validates the attr on the node that DECLARES it. - && node.hasMetaAttr(ReportingConstants.ATTR_GRAINS, false)) { - Object v = node.getMetaAttr(ReportingConstants.ATTR_GRAINS, false).getValue(); - List items = v instanceof List ? (List) v : v == null ? List.of() : List.of(v); - for (Object g : items) { - if (!ReportingConstants.TIME_GRAINS.contains(String.valueOf(g))) { - pushBadValue(node, ReportingConstants.ATTR_GRAINS, String.valueOf(g), ReportingConstants.TIME_GRAINS, sink); - } - } - } - // ADR-0039: own — a tree walk; each declared node is visited once, at its declaration. - for (MetaData c : node.getChildren(MetaData.class, false)) { - if (!(c instanceof MetaAttribute)) checkClosedSets(c, sink); - } - } - - private static void pushBadValue(MetaData node, String attr, String value, List allowed, ErrorSink sink) { - // The TS attr-schema check's short label (`type.subType 'name'`, no parent chain). - sink.push(node, ErrorCode.ERR_BAD_ATTR_VALUE, childLabel(node), - " attribute '@" + attr + "' has value '" + value + "' which is not one of the allowed values: " - + String.join(", ", allowed)); - } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java index e3177cd774..30c35593b1 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java @@ -298,19 +298,6 @@ private static void checkOperation(MetaData op, Sink sink) { sink.add(op, ErrorCode.ERR_BAD_ATTR_VALUE, head + " @errors: " + why + "."); } - // Java addition: .withEnum is decorative on attr children in this port, so the closed - // @method set the TS registry enforces generically is checked here. - // ADR-0039: own — a binding is checked on the operation that declares it. - for (MetaData b : op.getChildren(MetaData.class, false)) { - if (!ApiConstants.TYPE_BINDING.equals(b.getType()) || !b.hasMetaAttr(ApiConstants.ATTR_METHOD, false)) continue; - String method = Lifecycles.stringValue(b, ApiConstants.ATTR_METHOD); - if (method != null && !ApiConstants.BINDING_METHODS.contains(method)) { - sink.add(b, ErrorCode.ERR_BAD_ATTR_VALUE, - b.getType() + "." + b.getSubType() + " attribute '@" + ApiConstants.ATTR_METHOD + "' has value '" + method - + "' which is not one of the allowed values: " + String.join(", ", ApiConstants.BINDING_METHODS)); - } - } - if (!checkShapes(op, sink)) return; // O2, O3 — the target. diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index 6ccb0a9a2f..250d8468e3 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -187,9 +187,8 @@ public static void run(MetaRoot root, MetaDataLoader loader) { // ERR_TOO_MANY_OCCURRENCES (e.g. two identity.primary on one object). pass(collected, () -> validateMaxOccurs(root, loader)); validateChildRuleMax(root, loader, collected); - // The closed set of resource.* @residency (ADR-0070): the attr builder's enum is not - // enforced on an attribute, so the loader checks it here. - pass(collected, () -> validateResidency(root)); + // Every attribute's registered closed set (the registry manifest's allowedValues). + pass(collected, () -> validateAllowedValues(root, loader != null ? loader.getTypeRegistry() : null, collected)); pass(collected, () -> validateEnumValues(root)); pass(collected, () -> validateFieldDefaults(root)); pass(collected, () -> validateDbColumnType(root)); @@ -624,33 +623,51 @@ private static void validateChildRuleMaxNode(MetaData parent, MetaDataRegistry r } // ========================================================================= - // resource.* @residency validation (ADR-0070) + // Closed attribute value sets (ADR-0036 Wave 1, decision 5) // - // @residency is a closed set (free | confined) on every concrete resource kind. - // Own attribute only: an inherited value was checked on its declaring node. + // For each OWN attribute whose registered definition declares a non-empty closed set + // (the registry manifest's allowedValues), the value must be a member; an array attr + // checks each element. An inherited value was checked on its declaring node. + // @dbColumnType is exempt: its (subtype x value) pairing check reports instead. + // Mirrors TS attr-schema-validate Check 3, one ERR_BAD_ATTR_VALUE per offending value. // ========================================================================= - static void validateResidency(MetaRoot root) { - walkResidency(root); - } - - private static void walkResidency(MetaData node) { - if (SystemsNode.TYPE_RESOURCE.equals(node.getType()) - && SystemsNode.RESOURCE_KINDS.contains(node.getSubType()) - && node.hasMetaAttr(SystemsNode.ATTR_RESIDENCY, false)) { - String residency = node.getMetaAttr(SystemsNode.ATTR_RESIDENCY, false).getValueAsString(); - if (!SystemsNode.RESIDENCIES.contains(residency)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": " + node.getType() + "." + node.getSubType() + " '" + node.getName() - + "' @" + SystemsNode.ATTR_RESIDENCY + " '" + residency - + "' is not a valid value; allowed: " - + String.join(", ", SystemsNode.RESIDENCIES), - ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + static void validateAllowedValues(MetaRoot root, MetaDataRegistry registry, List out) { + if (registry != null) walkAllowedValues(root, registry, out); + } + + private static void walkAllowedValues(MetaData node, MetaDataRegistry registry, List out) { + TypeDefinition def = node.getType() == null || node.getSubType() == null + ? null : registry.getTypeDefinition(node.getType(), node.getSubType()); + // ADR-0039: own — an attr is checked on the node that declares it; the walk visits each node once. + List own = node.getChildren(MetaData.class, false); + if (def != null) { + Map> allowedByName = new java.util.HashMap<>(); + for (ChildRequirement req : def.getChildRequirements()) { + if (!MetaAttribute.TYPE_ATTR.equals(req.getExpectedType()) || req.isWildcard()) continue; + List allowed = req.getAllowedValues(); + if (allowed != null && !allowed.isEmpty()) allowedByName.putIfAbsent(req.getName(), allowed); + } + for (MetaData c : own) { + if (!(c instanceof MetaAttribute attr)) continue; + String name = attr.getShortName(); + List allowed = allowedByName.get(name); + if (allowed == null || MetaField.ATTR_DB_COLUMN_TYPE.equals(name)) continue; + Object value = attr.getValue(); + List items = value instanceof java.util.Collection coll ? new ArrayList<>(coll) : java.util.Arrays.asList(value); + for (Object item : items) { + String text = String.valueOf(item); + if (allowed.contains(text)) continue; + out.add(new MetaDataException( + ErrorMessageConstants.ERR_BAD_ATTR_VALUE + ": " + ReportingValidation.childLabel(node) + + " attribute '@" + name + "' has value '" + text + + "' which is not one of the allowed values: " + String.join(", ", allowed), + ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource())); + } } } - for (MetaData child : node.getChildren(MetaData.class, false)) { - walkResidency(child); + for (MetaData child : own) { + if (!(child instanceof MetaAttribute)) walkAllowedValues(child, registry, out); } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java b/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java index f72f68be3a..274ee57a2d 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java +++ b/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java @@ -1632,10 +1632,11 @@ private static String directKey(ChildRequirement req) { } /** - * Put the reference facet the spec definitions declare onto each attr requirement, direct - * and inherited, of every registered type — and nothing else. The core bootstrap runs this - * so a registry that never goes through {@link #applySpecDescriptions} (the SPI singleton, - * {@link #createWithCoreProviders()}) still enforces the core references, and + * Put the reference facet and the closed value set the spec definitions declare onto each + * attr requirement, direct and inherited, of every registered type — and nothing else. The + * core bootstrap runs this so a registry that never goes through {@link #applySpecDescriptions} + * (the SPI singleton, {@link #createWithCoreProviders()}) still enforces the core references + * and closed sets, and * {@link #applySpecDescriptions} runs it last so every path ends the same. * *

      An extension subtype the spec does not declare inherits its parent's definition data, @@ -1702,10 +1703,17 @@ private static ChildRequirement withSpecRef(ChildRequirement req, MetaDataTypeId } com.metaobjects.registry.spec.SpecMetamodelReader.AttrEntry doc = reader.attrDoc(id.type(), id.subType(), req.getName()); - if (doc == null || doc.ref() == null || doc.ref().equals(req.getRef())) { + if (doc == null) { return req; } - return req.withRef(doc.ref()); + ChildRequirement out = req; + if (doc.ref() != null && !doc.ref().equals(req.getRef())) { + out = out.withRef(doc.ref()); + } + if (doc.allowedValues() != null && !doc.allowedValues().equals(req.getAllowedValues())) { + out = out.withAllowedValues(doc.allowedValues()); + } + return out; } /** diff --git a/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java b/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java index 333081e3ba..7eb20b14d3 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java @@ -439,17 +439,20 @@ public void aFieldNamedNowIsAFieldNotARelativeDate() throws IOException { } // --------------------------------------------------------------------------- - // Closed sets (Java: .withEnum is decorative, so the pass enforces them) + // Closed sets (the loader's generic allowed-values pass; none is reported by the reporting pass) // --------------------------------------------------------------------------- @Test public void aggOutsideTheClosedSetIsABadAttrValue() throws IOException { JsonObject doc = cleanModel(); member(doc, "Purchase", "measure.aggregate", "revenue").addProperty("@agg", "median"); - List got = ValidationPhase.validateReporting(loadJson(doc)); + MetaRoot root = loadJson(doc); + assertEquals(List.of(), ValidationPhase.validateReporting(root)); + List got = new java.util.ArrayList<>(); + ValidationPhase.validateAllowedValues(root, sharedRegistry, got); assertEquals(List.of("ERR_BAD_ATTR_VALUE"), codes(got)); // Byte-identical to the TS attr-schema check (attr-schema-validate.ts, Check 3). - assertEquals("measure.aggregate 'revenue' attribute '@agg' has value 'median' which is not one of " + assertEquals("ERR_BAD_ATTR_VALUE: measure.aggregate 'revenue' attribute '@agg' has value 'median' which is not one of " + "the allowed values: count, sum, avg, min, max, any, all", got.get(0).getMessage()); } @@ -458,10 +461,13 @@ public void grainOutsideTheClosedSetIsABadAttrValue() throws IOException { JsonObject doc = cleanModel(); member(doc, "Purchase", "dimension.time", "purchasedAt").add("@grains", JsonParser.parseString("[\"day\", \"fortnight\"]")); - List got = ValidationPhase.validateReporting(loadJson(doc)); + MetaRoot root = loadJson(doc); + assertEquals(List.of(), ValidationPhase.validateReporting(root)); + List got = new java.util.ArrayList<>(); + ValidationPhase.validateAllowedValues(root, sharedRegistry, got); assertEquals(List.of("ERR_BAD_ATTR_VALUE"), codes(got)); // An isArray attr reports each offending ELEMENT, as TS does. - assertEquals("dimension.time 'purchasedAt' attribute '@grains' has value 'fortnight' which is not one " + assertEquals("ERR_BAD_ATTR_VALUE: dimension.time 'purchasedAt' attribute '@grains' has value 'fortnight' which is not one " + "of the allowed values: hour, day, week, month, quarter, year", got.get(0).getMessage()); } diff --git a/server/java/metadata/src/test/java/com/metaobjects/loader/RulesValidationMethodOrderTest.java b/server/java/metadata/src/test/java/com/metaobjects/loader/RulesValidationMethodOrderTest.java index 23058c7bf5..40bdf892ee 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/loader/RulesValidationMethodOrderTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/loader/RulesValidationMethodOrderTest.java @@ -17,7 +17,6 @@ import com.metaobjects.ErrorCode; import com.metaobjects.MetaDataException; -import com.metaobjects.MetaRoot; import com.metaobjects.registry.SharedRegistryTestBase; import org.junit.Test; @@ -53,14 +52,15 @@ public void badMethodIsReportedAlongsideAnO1Failure() throws Exception { LoaderOptions.create(false, false, true), MetaDataLoader.SUBTYPE_MANUAL, "rules-method-order"); loader.setSourceURIs(java.util.Collections.emptyList()); loader.init(); + MetaDataException thrown = null; try { loader.load(List.of(new InMemoryStringSource(broken, "meta.purchasing.json"))); } catch (MetaDataException expected) { - // the load fails on the rules; the tree is still built + thrown = expected; } - MetaRoot root = loader.getRoot(); - List codes = RulesValidation.validate(root).stream() - .map(e -> e.getCode().orElseThrow()).collect(Collectors.toList()); + List codes = new java.util.ArrayList<>(loader.getErrors().stream() + .map(e -> e.getCode().orElseThrow()).collect(Collectors.toList())); + if (thrown != null) codes.add(thrown.getCode().orElseThrow()); assertTrue(codes.toString(), codes.contains(ErrorCode.ERR_OPERATION_SHAPE)); assertTrue(codes.toString(), codes.contains(ErrorCode.ERR_BAD_ATTR_VALUE)); } diff --git a/server/rust/metaobjects/tests/conformance-expected-failures.json b/server/rust/metaobjects/tests/conformance-expected-failures.json index 3d01d4e52f..b8fbb2cd0a 100644 --- a/server/rust/metaobjects/tests/conformance-expected-failures.json +++ b/server/rust/metaobjects/tests/conformance-expected-failures.json @@ -1,6 +1,6 @@ { "language": "rust", "notes": "The Rust port passes every fixture of the shared metamodel corpus, so the ledger is empty. The ledger may only shrink and is kept for the day a new fixture lands that Rust does not pass yet: list it here with the reason, and it leaves when the work that covers it lands. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.", - "minPassing": 620, + "minPassing": 622, "fixtures": [] } From bbf4f7b4bb211de82350f82f95c8baeecb7e8db7 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 5 Dec 2026 01:45:46 -0500 Subject: [PATCH 06/10] no-mistakes(review): Key Java closed-set findings by message; fix stale docs --- docs/features/business-rules.md | 2 +- examples/showcase/site-payload.json | 2 +- .../metamodel-docs/data/types/binding.md.json | 2 +- .../metamodel-docs/expected/types/binding.md | 2 +- .../expected-registry.json | 2 +- .../csharp/RequirementHarnessTests.cs | 2 +- .../java/RequirementHarnessTest.java | 2 +- .../kotlin/RequirementHarnessTest.kt | 2 +- .../python/test_requirement_harness.py | 2 +- .../typescript/requirement-harness.test.ts | 2 +- metaobjects/meta.requirements.yaml | 9 +- scripts/metamodel-version-exceptions.json | 18 +- .../csharp/MetaObjects/SpecMetamodel/api.json | 2 +- .../metaobjects/identity/PrimaryIdentity.java | 2 +- .../identity/ReferenceIdentity.java | 5 +- .../loader/ReportingValidation.java | 5 +- .../metaobjects/loader/ValidationPhase.java | 434 ++---------------- .../loader/ClosedSetValuesLoadTest.java | 91 ++++ .../loader/ReportingValidationTest.java | 4 +- .../template/PromptStyleAttrTest.java | 8 +- .../src/metaobjects/spec_metamodel/api.json | 2 +- .../rust/metaobjects/data/metamodel/api.json | 2 +- .../src/core/api/api-definition.embedded.ts | 2 +- site-reference/types/binding.html | 2 +- spec/metamodel/api.json | 2 +- 25 files changed, 163 insertions(+), 445 deletions(-) create mode 100644 server/java/metadata/src/test/java/com/metaobjects/loader/ClosedSetValuesLoadTest.java diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 13a215ef86..a7f1d82d71 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -170,7 +170,7 @@ file is in place by, and its form follows the frequency: that day's date. - `format`: `csv`, `jsonLines` or `parquet`. A CSV file is RFC 4180: a comma between fields, CRLF after every line, UTF-8 with no byte order mark, and a first line of field names. A field is - quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. + quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`""`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 5759eb0b10..cf83537150 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.4" }, "counts": { - "fixtures": 620, + "fixtures": 622, "corpora": 49, "baseTypes": 28 }, diff --git a/fixtures/metamodel-docs/data/types/binding.md.json b/fixtures/metamodel-docs/data/types/binding.md.json index 6750043709..d5ef5f1263 100644 --- a/fixtures/metamodel-docs/data/types/binding.md.json +++ b/fixtures/metamodel-docs/data/types/binding.md.json @@ -73,7 +73,7 @@ "default": "", "allowed": "`csv`, `jsonLines`, `parquet`", "provider": "metaobjects-rules", - "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "name": "path", diff --git a/fixtures/metamodel-docs/expected/types/binding.md b/fixtures/metamodel-docs/expected/types/binding.md index ed80b466c8..71555f3893 100644 --- a/fixtures/metamodel-docs/expected/types/binding.md +++ b/fixtures/metamodel-docs/expected/types/binding.md @@ -40,7 +40,7 @@ How a file of an export or import is delivered: where it sits, what it is called | `@compression` | string | no | `none` | `none`, `gzip` | metaobjects-rules | none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk. | | `@encryption` | string | no | `none` | `none`, `pgp` | metaobjects-rules | none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key. | | `@fileName` | string | yes | | | metaobjects-rules | The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE. | -| `@format` | string | yes | | `csv`, `jsonLines`, `parquet` | metaobjects-rules | How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`""`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. | +| `@format` | string | yes | | `csv`, `jsonLines`, `parquet` | metaobjects-rules | How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`""`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. | | `@path` | string | no | | | metaobjects-rules | The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store. | | `@transport` | string | yes | | `sftp`, `objectStore` | metaobjects-rules | How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product. | diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 98f46d543d..88ce79c87c 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -396,7 +396,7 @@ "jsonLines", "parquet" ], - "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "name": "path", diff --git a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs index 4404ba86b1..81476bd085 100644 --- a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs +++ b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs @@ -64,7 +64,7 @@ public void declare_businessRules_apiEventing() { /* metaobjects.declare.busines [Fact(Skip = "unfilled slot — write an assertion that fails when: A command declared inside an entity, where a versioned second surface has nowhere to put it.")] public void declare_businessRules_apiOperational() { /* metaobjects.declare.businessRules.apiOperational */ } - // File binding — A file binding names where the file is put, how its name is formed from the run's UTC date or time and nothing else, its format, compression, encryption and how a reader knows the file is whole. + // File binding — A file binding names how the file is moved, how its name is formed from the run's UTC date or time and nothing else, and its format. It may name the folder the file is put in, its compression, its encryption and how a reader knows the file is whole; each of the last three is none when not named. [Fact(Skip = "unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.")] public void declare_businessRules_bindingFile() { /* metaobjects.declare.businessRules.bindingFile */ } diff --git a/fixtures/requirement-harness/java/RequirementHarnessTest.java b/fixtures/requirement-harness/java/RequirementHarnessTest.java index 8f1e5a61f1..bdc7be6561 100644 --- a/fixtures/requirement-harness/java/RequirementHarnessTest.java +++ b/fixtures/requirement-harness/java/RequirementHarnessTest.java @@ -77,7 +77,7 @@ void declare_businessRules_apiEventing() { /* metaobjects.declare.businessRules. @Disabled("unfilled slot — write an assertion that fails when: A command declared inside an entity, where a versioned second surface has nowhere to put it.") void declare_businessRules_apiOperational() { /* metaobjects.declare.businessRules.apiOperational */ } - // File binding — A file binding names where the file is put, how its name is formed from the run's UTC date or time and nothing else, its format, compression, encryption and how a reader knows the file is whole. + // File binding — A file binding names how the file is moved, how its name is formed from the run's UTC date or time and nothing else, and its format. It may name the folder the file is put in, its compression, its encryption and how a reader knows the file is whole; each of the last three is none when not named. @Test @Disabled("unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.") void declare_businessRules_bindingFile() { /* metaobjects.declare.businessRules.bindingFile */ } diff --git a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt index 1daf976aae..a4915a8c9b 100644 --- a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt +++ b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt @@ -77,7 +77,7 @@ class RequirementHarnessTest { @Disabled("unfilled slot — write an assertion that fails when: A command declared inside an entity, where a versioned second surface has nowhere to put it.") fun declare_businessRules_apiOperational() { /* metaobjects.declare.businessRules.apiOperational */ } - // File binding — A file binding names where the file is put, how its name is formed from the run's UTC date or time and nothing else, its format, compression, encryption and how a reader knows the file is whole. + // File binding — A file binding names how the file is moved, how its name is formed from the run's UTC date or time and nothing else, and its format. It may name the folder the file is put in, its compression, its encryption and how a reader knows the file is whole; each of the last three is none when not named. @Test @Disabled("unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.") fun declare_businessRules_bindingFile() { /* metaobjects.declare.businessRules.bindingFile */ } diff --git a/fixtures/requirement-harness/python/test_requirement_harness.py b/fixtures/requirement-harness/python/test_requirement_harness.py index 2a3abd371f..24afe5e6da 100644 --- a/fixtures/requirement-harness/python/test_requirement_harness.py +++ b/fixtures/requirement-harness/python/test_requirement_harness.py @@ -72,7 +72,7 @@ def test_declare_businessRules_apiEventing(): def test_declare_businessRules_apiOperational(): """metaobjects.declare.businessRules.apiOperational""" -# File binding — A file binding names where the file is put, how its name is formed from the run's UTC date or time and nothing else, its format, compression, encryption and how a reader knows the file is whole. +# File binding — A file binding names how the file is moved, how its name is formed from the run's UTC date or time and nothing else, and its format. It may name the folder the file is put in, its compression, its encryption and how a reader knows the file is whole; each of the last three is none when not named. @pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.") def test_declare_businessRules_bindingFile(): """metaobjects.declare.businessRules.bindingFile""" diff --git a/fixtures/requirement-harness/typescript/requirement-harness.test.ts b/fixtures/requirement-harness/typescript/requirement-harness.test.ts index 98d8772b23..bcfaa5a649 100644 --- a/fixtures/requirement-harness/typescript/requirement-harness.test.ts +++ b/fixtures/requirement-harness/typescript/requirement-harness.test.ts @@ -72,7 +72,7 @@ test.skip("metaobjects.declare.businessRules.apiOperational", () => { // unfilled slot — write an assertion that fails when: A command declared inside an entity, where a versioned second surface has nowhere to put it. }); -// File binding — A file binding names where the file is put, how its name is formed from the run's UTC date or time and nothing else, its format, compression, encryption and how a reader knows the file is whole. +// File binding — A file binding names how the file is moved, how its name is formed from the run's UTC date or time and nothing else, and its format. It may name the folder the file is put in, its compression, its encryption and how a reader knows the file is whole; each of the last three is none when not named. test.skip("metaobjects.declare.businessRules.bindingFile", () => { // unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done. }); diff --git a/metaobjects/meta.requirements.yaml b/metaobjects/meta.requirements.yaml index 2f5d990158..68edf25a9f 100644 --- a/metaobjects/meta.requirements.yaml +++ b/metaobjects/meta.requirements.yaml @@ -1694,10 +1694,11 @@ metadata.root: level: 4 status: live statement: >- - A file binding names where the file is put, how its name is - formed from the run's UTC date or time and nothing else, its - format, compression, encryption and how a reader knows the - file is whole. + A file binding names how the file is moved, how its name is + formed from the run's UTC date or time and nothing else, and + its format. It may name the folder the file is put in, its + compression, its encryption and how a reader knows the file + is whole; each of the last three is none when not named. counterexample: >- A reader that opens a file still being written because nothing said the writer renames it when done. diff --git a/scripts/metamodel-version-exceptions.json b/scripts/metamodel-version-exceptions.json index 42d5e9f0ae..89d7f92f81 100644 --- a/scripts/metamodel-version-exceptions.json +++ b/scripts/metamodel-version-exceptions.json @@ -4,47 +4,47 @@ { "baseline": "v1.3.1", "finding": "child rule removed: api.operational ← operation.*/*", - "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change." }, { "baseline": "v1.3.1", "finding": "attr removed: operation.base @inputRef", - "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change." }, { "baseline": "v1.3.1", "finding": "attr removed: operation.base @objectRef", - "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change." }, { "baseline": "v1.3.1", "finding": "attr removed: operation.base @outputRef", - "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change." }, { "baseline": "v1.3.1", "finding": "attr removed: operation.base @permission", - "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change." }, { "baseline": "v1.3.1", "finding": "attr removed: operation.base @public", - "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change." }, { "baseline": "v1.3.1", "finding": "child rule removed: operation.base ← binding.*/*", - "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change." }, { "baseline": "v1.3.1", "finding": "child rule removed: operation.command ← binding.*/*", - "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change." }, { "baseline": "v1.3.1", "finding": "child rule removed: operation.query ← binding.*/*", - "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document loses anything." + "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change." } ] } diff --git a/server/csharp/MetaObjects/SpecMetamodel/api.json b/server/csharp/MetaObjects/SpecMetamodel/api.json index a0eda80596..79f2e2cb08 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/api.json +++ b/server/csharp/MetaObjects/SpecMetamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } diff --git a/server/java/metadata/src/main/java/com/metaobjects/identity/PrimaryIdentity.java b/server/java/metadata/src/main/java/com/metaobjects/identity/PrimaryIdentity.java index f30c678a7c..13cd412490 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/identity/PrimaryIdentity.java +++ b/server/java/metadata/src/main/java/com/metaobjects/identity/PrimaryIdentity.java @@ -50,7 +50,7 @@ public static void registerTypes(MetaDataRegistry registry) { // Configure each attribute separately to avoid method chaining conflicts. // @fields is REQUIRED on identity.primary (matches the cross-port canonical; - // the dedicated validateIdentityFieldsAndGeneration pass already enforces it). + // the dedicated validateIdentityFields pass already enforces it). def.requiredAttributeWithConstraints(ATTR_FIELDS).ofType(StringAttribute.SUBTYPE_STRING).asArray(); def.optionalAttributeWithConstraints(ATTR_GENERATION).ofType(StringAttribute.SUBTYPE_STRING).withEnum(GENERATION_INCREMENT, GENERATION_UUID, GENERATION_ASSIGNED); // The sequence an @generation "increment" key draws from: its first value and its diff --git a/server/java/metadata/src/main/java/com/metaobjects/identity/ReferenceIdentity.java b/server/java/metadata/src/main/java/com/metaobjects/identity/ReferenceIdentity.java index c1474f2a62..c70c0126c1 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/identity/ReferenceIdentity.java +++ b/server/java/metadata/src/main/java/com/metaobjects/identity/ReferenceIdentity.java @@ -71,9 +71,8 @@ public static void registerTypes(MetaDataRegistry registry) { // correlated relationship's action / subtype default). RDB-physical, contributed // by the db provider (db.json extends identity.reference); descriptions + // allowedValues sourced from spec/metamodel/db.json by applySpecDescriptions. - // Value-set enforcement (ERR_BAD_ATTR_VALUE) lives in - // ValidationPhase.validateRelationshipReferentialActions, which also walks - // identity.reference nodes. (These were removed in SP-G Unit 6a to match the + // Value-set enforcement (ERR_BAD_ATTR_VALUE) is ValidationPhase's generic + // closed-set pass over those allowedValues. (These were removed in SP-G Unit 6a to match the // then-canonical; ADR-0047 registers them cross-port.) def.optionalAttributeWithConstraints(ATTR_ON_DELETE).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); def.optionalAttributeWithConstraints(ATTR_ON_UPDATE).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java index 9513525b90..f5094a61fd 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java @@ -90,9 +90,8 @@ * the same message is not repeated, so a broken base member is reported ONCE, and a failure * that only an inheritor exposes carries {@code " (inherited by '')"}.

      * - *

      Java addition: {@code .withEnum} is decorative on attr children in this port (see - * {@code validateRequirementStatus}), so the closed {@code @agg} / {@code @grains} sets the - * TS registry enforces generically are checked here as {@code ERR_BAD_ATTR_VALUE}.

      + *

      The closed {@code @agg} / {@code @grains} sets are checked by ValidationPhase's generic + * closed-set pass ({@code validateAllowedValues}), as the TS registry does, not here.

      * *

      A fractional measure {@code @default}: the TypeScript reference refuses it here, in * {@code checkMeasure}, because its generic attr.int check lets a fraction through. This diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index 250d8468e3..44a82f1055 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -117,7 +117,7 @@ * ({@code @through}/{@code @sourceRefField}/{@code @objectRef}/{@code @cardinality}/ * {@code @symmetric}) and the junction's {@code identity.reference} view, the * {@code layout.dataGrid} lookup + its {@code @defaultSortField}/{@code @filter}, and - * the {@code template.*} attrs ({@code @format}/{@code @promptStyle}/{@code @kind}/ + * the {@code template.*} attrs ({@code @kind}/ * part-refs — templates CAN extend) — are flipped to the resolving accessor inline and * marked "ADR-0039: resolving" (mirrors the TS reference and the C# ValidationPasses * fix). Declaration-layer markers ({@code @isAbstract}, TPH {@code @discriminator}/ @@ -137,14 +137,8 @@ private ValidationPhase() { *

      Currently runs:

      *
        *
      1. {@link #validateEnumValues(MetaRoot)} — enum {@code @values} content rules.
      2. - *
      3. {@link #validateSourceAttrs(MetaRoot)} — {@code source.*} {@code @kind}/{@code @role} - * enum-membership rules.
      4. *
      5. {@link #validateOnePrimarySource(MetaRoot)} — exactly one {@code role=primary} source * per object that declares any sources.
      6. - *
      7. {@link #validateRelationshipReferentialActions(MetaRoot)} — {@code relationship.*} - * {@code @onDelete}/{@code @onUpdate} enum-membership rules.
      8. - *
      9. {@link #validateRequirementStatus(MetaRoot)} — {@code requirement.*} - * {@code @status} enum-membership rules.
      10. *
      11. {@link #validateOrigins(MetaRoot)} — {@code origin.*} required-attr + * {@code @from}/{@code @of} reference resolution + {@code @via} path traversal * through declared relationships.
      12. @@ -187,12 +181,21 @@ public static void run(MetaRoot root, MetaDataLoader loader) { // ERR_TOO_MANY_OCCURRENCES (e.g. two identity.primary on one object). pass(collected, () -> validateMaxOccurs(root, loader)); validateChildRuleMax(root, loader, collected); - // Every attribute's registered closed set (the registry manifest's allowedValues). - pass(collected, () -> validateAllowedValues(root, loader != null ? loader.getTypeRegistry() : null, collected)); + // Findings a pass reports several of per node (code + envelope alike), deduped on their + // MESSAGE too, so only a true repeat collapses. + java.util.Set keyedByMessage = + java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>()); + // Every attribute's registered closed set (the registry manifest's allowedValues): + // one finding per offending value. + pass(collected, () -> { + List badValues = new ArrayList<>(); + validateAllowedValues(root, loader != null ? loader.getTypeRegistry() : null, badValues); + keyedByMessage.addAll(badValues); + collected.addAll(badValues); + }); pass(collected, () -> validateEnumValues(root)); pass(collected, () -> validateFieldDefaults(root)); pass(collected, () -> validateDbColumnType(root)); - pass(collected, () -> validateSourceAttrs(root)); pass(collected, () -> validateSourcePhysicalNames(root, loader)); // FR-013 — field-level @readOnly cross-attribute rules. pass(collected, () -> validateFieldMutability(root, loader)); @@ -213,7 +216,6 @@ public static void run(MetaRoot root, MetaDataLoader loader) { // #208 — DDL-ownership escape valves (@sql/@unmanaged on source.rdb). // Sibling of the source-role pass above; must run after it. pass(collected, () -> validateSourceEscapes(root, loader)); - pass(collected, () -> validateRelationshipReferentialActions(root)); // Pass 14 (FR-017): M:N relationship slim-vocabulary validation — collects // EVERY violation across the effective relationship set (own + inherited via // extends), deduped by the relationship node's own identity (#368 / ADR-0039). @@ -281,7 +283,7 @@ public static void run(MetaRoot root, MetaDataLoader loader) { loader != null && loader.getLoaderOptions() != null && loader.getLoaderOptions().isStrict()); validateDbCheck(root, collected); pass(collected, () -> validateFieldMap(root)); - pass(collected, () -> validateIdentityFieldsAndGeneration(root)); + pass(collected, () -> validateIdentityFields(root)); // FR-024 B3/B4a — subtype rules (identity-name, value purity, projection licensing). pass(collected, () -> validateSubtypeRules(root)); // FR-024 B3 — projection identity pass-through + key correspondence. @@ -300,11 +302,9 @@ public static void run(MetaRoot root, MetaDataLoader loader) { // so its findings are deduped on their MESSAGE too: two distinct reporting failures // on one node (two unresolved @dimensions items, two inheritors breaking one // inherited dimension) share code + envelope but are two errors in every port. - java.util.Set reportingFindings = - java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>()); pass(collected, () -> { List reporting = validateReporting(root); - reportingFindings.addAll(reporting); + keyedByMessage.addAll(reporting); collected.addAll(reporting); }); pass(collected, () -> validateTemplates(root)); @@ -317,22 +317,19 @@ public static void run(MetaRoot root, MetaDataLoader loader) { // once); keyed by message like the reporting pass, since they share code + envelope. pass(collected, () -> { List collisions = validateColumnNameCollisions(root); - reportingFindings.addAll(collisions); + keyedByMessage.addAll(collisions); collected.addAll(collisions); }); // FR-039 — a retired requirement carries no @implementedBy (refused, not exempted, // so the dangling-ref class is unreachable) and @supersededBy is legal only there. pass(collected, () -> validateRetiredRequirementLinks(root)); - // The capability ledger's closed status enum (requirements-as-metadata - // ruling, Amendment 3) — the loader owns what is UNCONDITIONAL. - pass(collected, () -> validateRequirementStatus(root)); warnFilterableWithoutIndex(root, loader); // warnings only — never throws // The SAME defect can be flagged by more than one pass (e.g. a missing required attr // caught by both the generic required-attr pass and a subtype-specific pass) — that is // one finding, not two, and the envelope (code + source) is identical. Dedupe on it so // a defect is reported once, while genuinely-distinct findings stay separate. - java.util.List findings = dedupe(collected, reportingFindings); + java.util.List findings = dedupe(collected, keyedByMessage); // Surface ALL findings: record every error but the last on the loader (source order), // then throw the last so the load still fails. Single error → records nothing, throws @@ -424,14 +421,14 @@ public static void run(MetaRoot root) { // // Only requirements whose expectedType is "attr" are enforced here. Other // required-child kinds (fields / identities) have their own bespoke checks - // already (validateEnumValues, validateIdentityFieldsAndGeneration) that + // already (validateEnumValues, validateIdentityFields) that // carry semantic context this pass does not. // // Loader nullness: when the loader handle is unavailable (legacy two-arg // entry point that passes null), this pass is a no-op — the registry // is reached via the loader, and absent that handle there is nowhere // safe to look up TypeDefinitions. The downstream subtype passes - // (validateEnumValues, validateIdentityFieldsAndGeneration) continue to + // (validateEnumValues, validateIdentityFields) continue to // run regardless and catch the previously-enforced cases. // ========================================================================= @@ -659,8 +656,7 @@ private static void walkAllowedValues(MetaData node, MetaDataRegistry registry, String text = String.valueOf(item); if (allowed.contains(text)) continue; out.add(new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE + ": " + ReportingValidation.childLabel(node) - + " attribute '@" + name + "' has value '" + text + ReportingValidation.childLabel(node) + " attribute '@" + name + "' has value '" + text + "' which is not one of the allowed values: " + String.join(", ", allowed), ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource())); } @@ -1171,8 +1167,6 @@ private static void validateEnumStringValueMap(MetaData node) { *
          *
        • {@code @coerceDefault} (own) must be a member of the EFFECTIVE {@code @values} * (own or inherited via {@code extends:}) → {@code ERR_BAD_ATTR_VALUE}.
        • - *
        • {@code @normalize} (own) must be one of {@code none|collapse|strip} - * → {@code ERR_BAD_ATTR_VALUE} (belt-and-braces with the registered withEnum).
        • *
        * *

        Own-only policy: only checks attrs declared on THIS node, matching the {@code @values} @@ -1208,19 +1202,6 @@ private static void validateEnumFr011Attrs(MetaData node) { ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); } } - - // @normalize closed-enum membership. - if (node.hasMetaAttr(EnumField.ATTR_NORMALIZE, false)) { - String mode = node.getMetaAttr(EnumField.ATTR_NORMALIZE, false).getValueAsString(); - if (mode != null && !EnumField.NORMALIZE_MODES.contains(mode)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": field.enum '" + node.getName() - + "' @" + EnumField.ATTR_NORMALIZE + " '" + mode - + "' is not a valid value; allowed: none, collapse, strip", - ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); - } - } } /** @@ -1410,86 +1391,6 @@ private static void validateDbColumnTypeNode(MetaData node) { } } - // ========================================================================= - // Source @kind / @role enum validation - // - // Applied to every source.* node after the full tree is built (attrs are set - // post-placement, so we cannot validate at addChild time via the constraint - // framework — same reason field.enum uses a post-load pass). - // - // @kind must be one of: table / view / materializedView / storedProc / tableFunction - // @role must be one of MetaSource.VALID_ROLES: primary / replica - // - // Missing attrs are fine (defaults apply); only explicitly-set bad values fail. - // ========================================================================= - - /** - * Walk the full tree and validate {@code @kind} and {@code @role} on every - * {@code source.*} node. - * - * @param root the root node to walk - * @throws MetaDataException on the first error found - */ - static void validateSourceAttrs(MetaRoot root) { - walkSourceAttrs(root); - } - - private static void walkSourceAttrs(MetaData node) { - validateSourceNode(node); - for (MetaData child : node.getChildren(MetaData.class, false)) { - walkSourceAttrs(child); - } - } - - /** - * Validate {@code @kind} and {@code @role} on a single node if it is a {@code source.*}. - * - * @param node the node to inspect - * @throws MetaDataException if {@code @kind} or {@code @role} is set to an invalid value - */ - private static void validateSourceNode(MetaData node) { - if (!MetaSource.TYPE_SOURCE.equals(node.getType())) { - return; - } - // Only validate on instances of MetaSource (skip the abstract base type itself at - // registration time — it will never appear in a loaded document tree). - if (!(node instanceof MetaSource)) { - return; - } - MetaSource src = (MetaSource) node; - - // Validate @kind (own attribute only — defaults are fine) - if (node.hasMetaAttr(MetaSource.ATTR_KIND, false)) { - String kind = src.getEffectiveKind(); - if (!MetaSource.VALID_KINDS.contains(kind)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": source '" + node.getName() - + "' @kind '" + kind - + "' is not a valid value; allowed: table, view, materializedView," - + " storedProc, tableFunction", - ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); - } - } - - // Validate @role (own attribute only — defaults are fine) - if (node.hasMetaAttr(MetaSource.ATTR_ROLE, false)) { - String role = src.getRole(); - if (!MetaSource.VALID_ROLES.contains(role)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": source '" + node.getName() - + "' @role '" + role - // Derived from the registered set (sorted for a deterministic - // message — Set.of iteration order is unspecified) so the - // diagnostic can never drift from MetaSource.VALID_ROLES again. - + "' is not a valid value; allowed: " - + String.join(", ", new TreeSet<>(MetaSource.VALID_ROLES)), - ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); - } - } - } - // ========================================================================= // FR-016 / ADR-0018 — per-kind physical-name alias validation // @@ -1848,126 +1749,6 @@ private static void validateObjectSourceEscapes(MetaObject obj, MetaDataLoader l } } - // ========================================================================= - // Relationship @onDelete / @onUpdate enum validation - // - // Applied to every relationship.* node after the full tree is built. - // The .withEnum() constraint registered on relationship.base does not fire - // eagerly at addChild time (the CustomConstraint applicability test checks - // the container node's own type/subtype, which is attr.string for the attr - // child, not relationship.base) — so we use this post-load pass instead, - // mirroring the pattern for source @kind/@role. - // - // @onDelete must be one of: cascade / set-null / restrict / no-action - // @onUpdate must be one of: cascade / set-null / restrict / no-action - // - // Missing attrs are fine (defaults apply per subtype in consumer code); - // only explicitly-set bad values fail. - // ========================================================================= - - /** - * Walk the full tree and validate {@code @onDelete} and {@code @onUpdate} on every - * {@code relationship.*} node. - * - * @param root the root node to walk - * @throws MetaDataException on the first error found - */ - static void validateRelationshipReferentialActions(MetaRoot root) { - walkRelationshipReferentialActions(root); - } - - private static void walkRelationshipReferentialActions(MetaData node) { - validateRelationshipNode(node); - validateReferenceIdentityActions(node); - for (MetaData child : node.getChildren(MetaData.class, false)) { - walkRelationshipReferentialActions(child); - } - } - - /** - * ADR-0047 — validate {@code @onDelete} / {@code @onUpdate} declared directly on an - * {@code identity.reference} (the explicit per-FK override). Same closed value set - * as the relationship-level attrs ({@link MetaRelationship#REFERENTIAL_ACTIONS}); - * an out-of-set value throws {@code ERR_BAD_ATTR_VALUE}, matching the other ports' - * generic allowedValues enforcement. - */ - private static void validateReferenceIdentityActions(MetaData node) { - if (!(node instanceof ReferenceIdentity)) { - return; - } - ReferenceIdentity ref = (ReferenceIdentity) node; - - if (node.hasMetaAttr(MetaIdentity.ATTR_ON_DELETE, false)) { - String onDelete = ref.getOnDeleteRaw(); - if (!MetaRelationship.REFERENTIAL_ACTIONS.contains(onDelete)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": identity.reference '" + node.getName() - + "' @onDelete '" + onDelete - + "' is not a valid value; allowed: cascade, set-null, restrict, no-action", - ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); - } - } - - if (node.hasMetaAttr(MetaIdentity.ATTR_ON_UPDATE, false)) { - String onUpdate = ref.getOnUpdateRaw(); - if (!MetaRelationship.REFERENTIAL_ACTIONS.contains(onUpdate)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": identity.reference '" + node.getName() - + "' @onUpdate '" + onUpdate - + "' is not a valid value; allowed: cascade, set-null, restrict, no-action", - ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); - } - } - } - - /** - * Validate {@code @onDelete} and {@code @onUpdate} on a single node if it is a - * {@code relationship.*} instance. - * - * @param node the node to inspect - * @throws MetaDataException if {@code @onDelete} or {@code @onUpdate} is set to an - * invalid value (not in {@link MetaRelationship#REFERENTIAL_ACTIONS}) - */ - private static void validateRelationshipNode(MetaData node) { - if (!MetaRelationship.TYPE_RELATIONSHIP.equals(node.getType())) { - return; - } - // Only validate concrete MetaRelationship instances — skip the abstract base type - // itself at registration time; it will never appear in a loaded document tree. - if (!(node instanceof MetaRelationship)) { - return; - } - MetaRelationship rel = (MetaRelationship) node; - - // Validate @onDelete (own attribute only — absent is fine) - if (node.hasMetaAttr(MetaRelationship.ATTR_ON_DELETE, false)) { - String onDelete = rel.getOnDeleteRaw(); - if (!MetaRelationship.REFERENTIAL_ACTIONS.contains(onDelete)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": relationship '" + node.getName() - + "' @onDelete '" + onDelete - + "' is not a valid value; allowed: cascade, set-null, restrict, no-action", - ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); - } - } - - // Validate @onUpdate (own attribute only — absent is fine) - if (node.hasMetaAttr(MetaRelationship.ATTR_ON_UPDATE, false)) { - String onUpdate = rel.getOnUpdateRaw(); - if (!MetaRelationship.REFERENTIAL_ACTIONS.contains(onUpdate)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": relationship '" + node.getName() - + "' @onUpdate '" + onUpdate - + "' is not a valid value; allowed: cascade, set-null, restrict, no-action", - ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); - } - } - } - // ========================================================================= // FR-017 — M:N relationship validation (slim vocabulary) // @@ -3544,17 +3325,11 @@ private static void validateOriginNode(MetaRoot root, MetaObject obj, if (AggregateOrigin.SUBTYPE_AGGREGATE.equals(subType)) { com.metaobjects.source.ErrorSource src = origin.getSource(); - // Re-check @agg vocabulary — the .withEnum constraint on the base - // can be subverted by inline attribute parsing paths; mirror the - // belt-and-braces approach used for relationship referential actions. + // An @agg outside the closed set is reported by the closed-set pass; the + // rules below depend on the function, so they are not checked for it. String agg = origin.getAgg(); if (agg != null && !agg.isEmpty() && !MetaOrigin.AGGREGATE_FUNCTIONS.contains(agg)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": origin.aggregate on " + obj.getName() + "." + field.getName() - + " @agg '" + agg + "' is not a valid value; allowed: " - + "count, sum, avg, min, max, any, all, collect", - ErrorCode.ERR_BAD_ATTR_VALUE, src); + return; } String of = origin.getOf(); @@ -4243,34 +4018,24 @@ private static void checkObjectIdentity(MetaObject obj, MetaDataLoader loader) { } // ========================================================================= - // Identity @fields (required) + @generation (enum) validation - // - // The unified registry exposes withEnum() but the runtime doesn't currently - // walk those constraints post-load (only validators with side-effect passes - // do). For cross-port parity (TS / C# both throw on these shapes) we run a - // dedicated pass here. + // Identity @fields (required) validation // // @fields is required on every identity.* node → ERR_MISSING_REQUIRED_ATTR - // @generation, if present, must be one of increment / uuid / assigned → - // ERR_BAD_ATTR_VALUE // ========================================================================= - static void validateIdentityFieldsAndGeneration(MetaRoot root) { - walkIdentityFieldsAndGeneration(root); + static void validateIdentityFields(MetaRoot root) { + walkIdentityFields(root); } - private static void walkIdentityFieldsAndGeneration(MetaData node) { + private static void walkIdentityFields(MetaData node) { if (node instanceof MetaIdentity) { validateIdentityNode((MetaIdentity) node); } for (MetaData child : node.getChildren(MetaData.class, false)) { - walkIdentityFieldsAndGeneration(child); + walkIdentityFields(child); } } - private static final java.util.Set VALID_IDENTITY_GENERATIONS = - java.util.Set.of("increment", "uuid", "assigned"); - private static void validateIdentityNode(MetaIdentity identity) { // FR-024 (ADR-0029): an identity with a resolved extends (identity // pass-through, e.g. a projection identity extending an entity identity) @@ -4299,18 +4064,6 @@ && hasNonBlankAttr(identity, SecondaryIdentity.ATTR_EXPR)) { + "' is missing required @fields attribute", ErrorCode.ERR_MISSING_REQUIRED_ATTR, identity.getSource()); } - if (identity.hasMetaAttr(MetaIdentity.ATTR_GENERATION, false)) { - Object v = identity.getMetaAttr(MetaIdentity.ATTR_GENERATION, false).getValue(); - String gen = v == null ? null : v.toString(); - if (gen != null && !VALID_IDENTITY_GENERATIONS.contains(gen)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": identity '" + identity.getName() - + "' @generation '" + gen + "' is not a valid value;" - + " allowed: increment, uuid, assigned", - ErrorCode.ERR_BAD_ATTR_VALUE, identity.getSource()); - } - } } // ========================================================================= @@ -4990,8 +4743,6 @@ static boolean isAbstract(MetaData node) { // object.value at root → ERR_INVALID_TEMPLATE // R3: template.prompt @requiredSlots members must each be a field on the // resolved payload VO → ERR_INVALID_TEMPLATE - // R4: @format (if present) must be a member of TemplateConstants.ALLOWED_FORMATS - // → ERR_BAD_ATTR_VALUE // // Templates always live at the document root. We walk root children only. // ========================================================================= @@ -5013,64 +4764,8 @@ private static void validateTemplateNode(MetaRoot root, MetaTemplate template) { String subType = template.getSubType(); String payloadRef = template.getPayloadRef(); - // R4 — @format (if present) must be in the closed allowed set - // (text|html|xml|csv|json|markdown|spreadsheet). - // ADR-0039: resolving — a template may inherit @format via extends - // (templates CAN extend; consistent with the merged codegen template - // decision). TS handles @format via the resolving generic schema pass. - if (template.hasMetaAttr(TemplateConstants.ATTR_FORMAT)) { - String fmt = template.getMetaAttr(TemplateConstants.ATTR_FORMAT).getValueAsString(); - if (fmt != null && !TemplateConstants.ALLOWED_FORMATS.contains(fmt)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": template '" + template.getName() - + "' @format '" + fmt - + "' is not a valid value; allowed: " - + TemplateConstants.ALLOWED_FORMATS, - ErrorCode.ERR_BAD_ATTR_VALUE, template.getSource()); - } - } - - // R5 — @promptStyle (template.prompt only since ADR-0052, FR-010) must be in - // the closed set (guide|inline|exampleOnly). Absent is fine; default is "guide". - // ADR-0039: resolving — a template may inherit @promptStyle via extends. - if (template.hasMetaAttr(TemplateConstants.ATTR_PROMPT_STYLE)) { - String style = template.getMetaAttr(TemplateConstants.ATTR_PROMPT_STYLE) - .getValueAsString(); - if (style != null && !TemplateConstants.ALLOWED_PROMPT_STYLES.contains(style)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": template '" + template.getName() - + "' @promptStyle '" + style - + "' is not a valid value; allowed: " - + TemplateConstants.ALLOWED_PROMPT_STYLES, - ErrorCode.ERR_BAD_ATTR_VALUE, template.getSource()); - } - } - - // R5b — @responseFormat (template.prompt only, ADR-0053) must be in the closed - // set (json|xml). Absent is fine; default is "json". Deliberately NOT - // ALLOWED_FORMATS: a reply is only ever parsed as JSON or XML, and registering - // members nothing dispatches on is what ADR-0007 Amendment 2 forbids. - // ADR-0039: resolving — a template may inherit @responseFormat via extends. - if (template.hasMetaAttr(TemplateConstants.ATTR_RESPONSE_FORMAT)) { - String respFmt = template.getMetaAttr(TemplateConstants.ATTR_RESPONSE_FORMAT) - .getValueAsString(); - if (respFmt != null - && !TemplateConstants.ALLOWED_RESPONSE_FORMATS.contains(respFmt)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": template '" + template.getName() - + "' @responseFormat '" + respFmt - + "' is not a valid value; allowed: " - + TemplateConstants.ALLOWED_RESPONSE_FORMATS, - ErrorCode.ERR_BAD_ATTR_VALUE, template.getSource()); - } - } - - // R6 — @kind (template.output only, Task 1) closed-enum + conditional - // ref requirements. @kind is a closed set (document|email); an email - // requires @subjectRef + @htmlBodyRef; a document (or absent @kind) + // R6 — @kind (template.output only, Task 1) conditional ref requirements. + // An email requires @subjectRef + @htmlBodyRef; a document (or absent @kind) // requires @textRef. template.prompt always requires @textRef (its // renderable body). Mirrors TS validateTemplatePayloadRefs. if (TemplateConstants.SUBTYPE_OUTPUT.equals(subType)) { @@ -5080,16 +4775,6 @@ private static void validateTemplateNode(MetaRoot root, MetaTemplate template) { String kind = template.hasMetaAttr(TemplateConstants.ATTR_KIND) ? template.getMetaAttr(TemplateConstants.ATTR_KIND).getValueAsString() : null; - // Closed-enum membership (absent → default "document"). - if (kind != null && !TemplateConstants.ALLOWED_KINDS.contains(kind)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": template '" + template.getName() - + "' @kind '" + kind - + "' is not a valid value; allowed: " - + TemplateConstants.ALLOWED_KINDS, - ErrorCode.ERR_BAD_ATTR_VALUE, template.getSource()); - } if (TemplateConstants.KIND_EMAIL.equals(kind)) { if (!template.hasMetaAttr(TemplateConstants.ATTR_SUBJECT_REF)) { throw new MetaDataException( @@ -5107,7 +4792,8 @@ private static void validateTemplateNode(MetaRoot root, MetaTemplate template) { } } else { // @kind absent or "document" → require @textRef so a document is - // never bodyless. (An out-of-enum @kind already threw above.) + // never bodyless. (An out-of-enum @kind is reported by the closed-set + // pass; @textRef is still required, as in TS.) if (!template.hasMetaAttr(TemplateConstants.ATTR_TEXT_REF)) { throw new MetaDataException( ErrorMessageConstants.ERR_INVALID_TEMPLATE @@ -7101,60 +6787,4 @@ private static boolean hasNonBlankAttr(MetaData node, String name) { return v != null && !v.trim().isEmpty(); } - // ========================================================================= - // requirement.* @status enum validation - // - // Applied to every requirement.* node after the full tree is built (attrs are - // set post-placement, so the registered .withEnum() CustomConstraint cannot - // fire at addChild time — its applicability test sees the ATTR node's own - // type/subtype, not the container's; same reason source @kind/@role and - // relationship @onDelete/@onUpdate use post-load passes). - // - // @status must be one of: planned / live / partial - // - // This is the mechanism the capability ledger was made registered vocabulary - // FOR (requirements-as-metadata ruling, Amendment 3): a typo'd status is - // refused by the LOADER, not by a hand-written string comparison in one CLI. - // ERR_BAD_ATTR_VALUE is the existing cross-port code for an out-of-set - // allowedValues member — no new error code. - // ========================================================================= - - /** - * Walk the full tree and validate {@code @status} on every {@code requirement.*} node. - * - * @param root the root node to walk - * @throws MetaDataException when {@code @status} carries a value outside the closed set - */ - static void validateRequirementStatus(MetaRoot root) { - walkRequirementStatus(root); - } - - private static void walkRequirementStatus(MetaData node) { - validateRequirementStatusNode(node); - for (MetaData child : node.getChildren(MetaData.class, false)) { - walkRequirementStatus(child); - } - } - - private static void validateRequirementStatusNode(MetaData node) { - if (!(node instanceof MetaRequirement)) { - return; - } - // Own attribute only — an inherited @status was already validated on its declaring - // node, matching the source @kind/@role and relationship @onDelete/@onUpdate passes. - if (!node.hasMetaAttr(MetaRequirement.ATTR_STATUS, false)) { - return; - } - String status = ((MetaRequirement) node).getStatus(); - if (!MetaRequirement.STATUSES.contains(status)) { - throw new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE - + ": requirement '" + node.getName() - + "' @" + MetaRequirement.ATTR_STATUS + " '" + status - + "' is not a valid value; allowed: " - + String.join(", ", MetaRequirement.STATUSES), - ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); - } - } - } diff --git a/server/java/metadata/src/test/java/com/metaobjects/loader/ClosedSetValuesLoadTest.java b/server/java/metadata/src/test/java/com/metaobjects/loader/ClosedSetValuesLoadTest.java new file mode 100644 index 0000000000..0c7de6ab0d --- /dev/null +++ b/server/java/metadata/src/test/java/com/metaobjects/loader/ClosedSetValuesLoadTest.java @@ -0,0 +1,91 @@ +/* + * Copyright 2026 Doug Mealing LLC dba Meta Objects + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.metaobjects.loader; + +import com.metaobjects.ErrorCode; +import com.metaobjects.MetaDataException; +import com.metaobjects.registry.SharedRegistryTestBase; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * Two out-of-set values on ONE node are two findings through the full loader, as in the + * TypeScript reference (attr-schema-validate Check 3): the closed-set findings share code and + * source envelope, so the load-level dedupe must keep them apart by message. + */ +public class ClosedSetValuesLoadTest extends SharedRegistryTestBase { + + private static List loadFindings(String json) { + MetaDataLoader loader = new MetaDataLoader( + LoaderOptions.create(false, false, true), MetaDataLoader.SUBTYPE_MANUAL, "closed-set-values"); + loader.setSourceURIs(java.util.Collections.emptyList()); + loader.init(); + List found = new ArrayList<>(); + try { + loader.load(List.of(new InMemoryStringSource(json, "meta.ledger.json"))); + } catch (MetaDataException thrown) { + found.addAll(loader.getErrors()); + found.add(thrown); + } + return found; + } + + private static List messages(List found) { + List out = new ArrayList<>(); + for (MetaDataException e : found) { + assertEquals(e.getMessage(), ErrorCode.ERR_BAD_ATTR_VALUE, e.getCode().orElseThrow()); + out.add(e.getMessage()); + } + return out; + } + + @Test + public void twoBadAttrsOnOneBindingAreTwoErrors() { + String json = "{ \"metadata.root\": { \"package\": \"acme::ledger\", \"children\": [" + + "{ \"object.value\": { \"name\": \"SettlementLine\", \"children\": [ { \"field.string\": { \"name\": \"reference\" } } ] } }," + + "{ \"api.batch\": { \"name\": \"SettlementFeed\", \"children\": [ { \"operation.export\": {" + + " \"name\": \"dailySettlement\", \"@outputRef\": \"SettlementLine\", \"@frequency\": \"daily\", \"children\": [" + + " { \"binding.file\": { \"@transport\": \"sftp\", \"@fileName\": \"settlement-{date}.csv\"," + + " \"@format\": \"fixedWidth\", \"@encryption\": \"rot13\" } } ] } } ] } } ] } }"; + assertEquals(List.of( + "binding.file attribute '@format' has value 'fixedWidth' which is not one of the allowed values: " + + "csv, jsonLines, parquet", + "binding.file attribute '@encryption' has value 'rot13' which is not one of the allowed values: " + + "none, pgp"), + messages(loadFindings(json))); + } + + @Test + public void twoBadElementsOfOneArrayAttrAreTwoErrors() { + String json = "{ \"metadata.root\": { \"package\": \"acme::ledger\", \"children\": [" + + "{ \"object.entity\": { \"name\": \"Purchase\", \"children\": [" + + " { \"field.long\": { \"name\": \"id\" } }," + + " { \"field.timestamp\": { \"name\": \"purchasedAt\" } }," + + " { \"identity.primary\": { \"@fields\": [\"id\"] } }," + + " { \"dimension.time\": { \"name\": \"purchasedAt\", \"@of\": \"Purchase.purchasedAt\", \"@grains\": [\"day\", \"fortnight\", \"decade\"] } }" + + "] } } ] } }"; + assertEquals(List.of( + "dimension.time 'purchasedAt' attribute '@grains' has value 'fortnight' which is not one of the " + + "allowed values: hour, day, week, month, quarter, year", + "dimension.time 'purchasedAt' attribute '@grains' has value 'decade' which is not one of the " + + "allowed values: hour, day, week, month, quarter, year"), + messages(loadFindings(json))); + } +} diff --git a/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java b/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java index 7eb20b14d3..8521f89ba7 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java @@ -452,7 +452,7 @@ public void aggOutsideTheClosedSetIsABadAttrValue() throws IOException { ValidationPhase.validateAllowedValues(root, sharedRegistry, got); assertEquals(List.of("ERR_BAD_ATTR_VALUE"), codes(got)); // Byte-identical to the TS attr-schema check (attr-schema-validate.ts, Check 3). - assertEquals("ERR_BAD_ATTR_VALUE: measure.aggregate 'revenue' attribute '@agg' has value 'median' which is not one of " + assertEquals("measure.aggregate 'revenue' attribute '@agg' has value 'median' which is not one of " + "the allowed values: count, sum, avg, min, max, any, all", got.get(0).getMessage()); } @@ -467,7 +467,7 @@ public void grainOutsideTheClosedSetIsABadAttrValue() throws IOException { ValidationPhase.validateAllowedValues(root, sharedRegistry, got); assertEquals(List.of("ERR_BAD_ATTR_VALUE"), codes(got)); // An isArray attr reports each offending ELEMENT, as TS does. - assertEquals("ERR_BAD_ATTR_VALUE: dimension.time 'purchasedAt' attribute '@grains' has value 'fortnight' which is not one " + assertEquals("dimension.time 'purchasedAt' attribute '@grains' has value 'fortnight' which is not one " + "of the allowed values: hour, day, week, month, quarter, year", got.get(0).getMessage()); } diff --git a/server/java/metadata/src/test/java/com/metaobjects/template/PromptStyleAttrTest.java b/server/java/metadata/src/test/java/com/metaobjects/template/PromptStyleAttrTest.java index 05ae1a532b..99dfc78c77 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/template/PromptStyleAttrTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/template/PromptStyleAttrTest.java @@ -187,12 +187,10 @@ public void rejectsUnknownResponseFormatValue() { try { load(json, "bad-response-format.json"); fail("an out-of-set @responseFormat must be rejected"); - } catch (RuntimeException e) { - boolean messageMatches = e.getMessage() != null - && e.getMessage().contains("ERR_BAD_ATTR_VALUE"); - assertTrue( + } catch (MetaDataException e) { + assertEquals( "Exception must signal ERR_BAD_ATTR_VALUE: " + e.getMessage(), - messageMatches); + java.util.Optional.of(ErrorCode.ERR_BAD_ATTR_VALUE), e.getCode()); } } } diff --git a/server/python/src/metaobjects/spec_metamodel/api.json b/server/python/src/metaobjects/spec_metamodel/api.json index a0eda80596..79f2e2cb08 100644 --- a/server/python/src/metaobjects/spec_metamodel/api.json +++ b/server/python/src/metaobjects/spec_metamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } diff --git a/server/rust/metaobjects/data/metamodel/api.json b/server/rust/metaobjects/data/metamodel/api.json index a0eda80596..79f2e2cb08 100644 --- a/server/rust/metaobjects/data/metamodel/api.json +++ b/server/rust/metaobjects/data/metamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } diff --git a/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts b/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts index 5a786e6fbd..612a14514c 100644 --- a/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts @@ -457,7 +457,7 @@ export const API_DEFINITION: ProviderDefinition = { "jsonLines", "parquet" ], - "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." + "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", diff --git a/site-reference/types/binding.html b/site-reference/types/binding.html index ffd4b487cc..e61fd9de5a 100644 --- a/site-reference/types/binding.html +++ b/site-reference/types/binding.html @@ -117,7 +117,7 @@

        binding.file

        csv, jsonLines, parquet metaobjects-rules -How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (""), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in Z and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as 0); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. +How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (""), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in Z and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as 0); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. @path diff --git a/spec/metamodel/api.json b/spec/metamodel/api.json index a0eda80596..79f2e2cb08 100644 --- a/spec/metamodel/api.json +++ b/spec/metamodel/api.json @@ -155,7 +155,7 @@ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." }, { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." }, { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." }, - { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, + { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." }, { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." }, { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." }, { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." } From 119cb43660a06a47eee2aaa7a38d92264ee8f145 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 5 Dec 2026 01:49:43 -0500 Subject: [PATCH 07/10] no-mistakes(review): apply reviewer inline fixes --- changelog.d/api-eventing-and-batch.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/changelog.d/api-eventing-and-batch.md b/changelog.d/api-eventing-and-batch.md index 91ab15ce8f..01675e6ae8 100644 --- a/changelog.d/api-eventing-and-batch.md +++ b/changelog.d/api-eventing-and-batch.md @@ -36,7 +36,10 @@ longer inherits `@inputRef`, `@outputRef`, `@objectRef`, `@permission`, `@public` or binding children from `operation.base`, and is not admitted under `api.operational`, which now takes `operation.command` and `operation.query` only; such a provider declares those attributes itself - and places its subtype under its own API type. Java and Kotlin now refuse an attribute value + and places its subtype under its own API type. Permission names, transition claims, `verify`'s + rules check and every generator that reads operations read those under `api.operational` only, + so they do not read an operation under a provider's own API type; of the operation rules, the + shape check O1 still applies to it. Java and Kotlin now refuse an attribute value outside its registered closed set (`ERR_BAD_ATTR_VALUE`, with the TypeScript message), as the other ports already did, so `binding.file @format: fixedWidth` (`error-api-binding-file-format-fixed-width`) and `operation.export @frequency: yearly` From 8e97ece4f05463943294493f05c8413244e1d47b Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 5 Dec 2026 02:12:49 -0500 Subject: [PATCH 08/10] no-mistakes(test): Reflow Rust rules.rs and service_routes.rs for rustfmt --- .../metaobjects-codegen/src/service_routes.rs | 10 +- server/rust/metaobjects/src/validate/rules.rs | 3 +- .../AllTypes.names.ts | 39 ++ .../AllTypes.queries.ts | 50 ++ .../AllTypes.ts | 552 ++++++++++++++++++ .../AllTypesBreakdown.names.ts | 26 + .../AllTypesBreakdown.queries.ts | 19 + .../AllTypesBreakdown.ts | 88 +++ .../ArchivedLedgerEntry.names.ts | 19 + .../ArchivedLedgerEntry.queries.ts | 56 ++ .../ArchivedLedgerEntry.ts | 86 +++ .../Asset.names.ts | 25 + .../Asset.queries.ts | 50 ++ .../Asset.ts | 164 ++++++ .../AssetActivity.names.ts | 18 + .../AssetActivity.queries.ts | 19 + .../AssetActivity.ts | 42 ++ .../AssetDays.names.ts | 22 + .../AssetDays.queries.ts | 19 + .../AssetDays.ts | 58 ++ .../Auth.names.ts | 20 + .../Auth.queries.ts | 175 ++++++ .../Auth.ts | 143 +++++ .../AuthsByKind.names.ts | 18 + .../AuthsByKind.queries.ts | 19 + .../AuthsByKind.ts | 42 ++ .../BridgeAuth.names.ts | 23 + .../BridgeAuth.ts | 113 ++++ .../CouponAuth.names.ts | 23 + .../CouponAuth.ts | 151 +++++ .../Entry.names.ts | 21 + .../Entry.queries.ts | 50 ++ .../Entry.ts | 145 +++++ .../EntryTotals.names.ts | 23 + .../EntryTotals.queries.ts | 19 + .../EntryTotals.ts | 62 ++ .../FitnessTotals.names.ts | 18 + .../FitnessTotals.queries.ts | 19 + .../FitnessTotals.ts | 42 ++ .../FitnessTotalsFilled.names.ts | 18 + .../FitnessTotalsFilled.queries.ts | 19 + .../FitnessTotalsFilled.ts | 42 ++ .../Follow.names.ts | 21 + .../Follow.queries.ts | 72 +++ .../Follow.ts | 92 +++ .../Friendship.names.ts | 21 + .../Friendship.queries.ts | 78 +++ .../Friendship.ts | 92 +++ .../Gadget.names.ts | 23 + .../Gadget.queries.ts | 50 ++ .../Gadget.ts | 86 +++ .../GadgetEvent.names.ts | 20 + .../GadgetEvent.queries.ts | 67 +++ .../GadgetEvent.ts | 87 +++ .../GadgetEventsByLabel.names.ts | 17 + .../GadgetEventsByLabel.queries.ts | 19 + .../GadgetEventsByLabel.ts | 38 ++ .../IntEnumArray.names.ts | 20 + .../IntEnumArray.queries.ts | 56 ++ .../IntEnumArray.ts | 134 +++++ .../Label.ts | 35 ++ .../Labeled.names.ts | 17 + .../Labeled.ts | 14 + .../LedgerEntry.names.ts | 19 + .../LedgerEntry.queries.ts | 56 ++ .../LedgerEntry.ts | 86 +++ .../LiveIntroPrograms.names.ts | 19 + .../LiveIntroPrograms.queries.ts | 19 + .../LiveIntroPrograms.ts | 46 ++ .../Measurement.names.ts | 21 + .../Measurement.queries.ts | 56 ++ .../Measurement.ts | 147 +++++ .../MeasurementStats.names.ts | 24 + .../MeasurementStats.queries.ts | 19 + .../MeasurementStats.ts | 66 +++ .../MeasurementStatsFilled.names.ts | 18 + .../MeasurementStatsFilled.queries.ts | 19 + .../MeasurementStatsFilled.ts | 42 ++ .../Node.names.ts | 21 + .../Node.queries.ts | 61 ++ .../Node.ts | 95 +++ .../NodesByParent.names.ts | 17 + .../NodesByParent.queries.ts | 19 + .../NodesByParent.ts | 38 ++ .../PermitAuth.names.ts | 23 + .../PermitAuth.ts | 113 ++++ .../Person.names.ts | 19 + .../Person.queries.ts | 50 ++ .../Person.ts | 93 +++ .../Post.names.ts | 19 + .../Post.queries.ts | 50 ++ .../Post.ts | 93 +++ .../PostReferral.names.ts | 21 + .../PostReferral.queries.ts | 78 +++ .../PostReferral.ts | 93 +++ .../PostTag.names.ts | 21 + .../PostTag.queries.ts | 72 +++ .../PostTag.ts | 93 +++ .../Program.names.ts | 25 + .../Program.queries.ts | 50 ++ .../Program.ts | 124 ++++ .../ProgramBrief.ts | 45 ++ .../ProgramFlagRoster.names.ts | 20 + .../ProgramFlagRoster.queries.ts | 19 + .../ProgramFlagRoster.ts | 50 ++ .../ProgramFlags.names.ts | 20 + .../ProgramFlags.queries.ts | 19 + .../ProgramFlags.ts | 50 ++ .../ProgramLongWeeks.names.ts | 18 + .../ProgramLongWeeks.queries.ts | 19 + .../ProgramLongWeeks.ts | 42 ++ .../ProgramMinutes.names.ts | 26 + .../ProgramMinutes.queries.ts | 19 + .../ProgramMinutes.ts | 74 +++ .../ProgramRoster.names.ts | 22 + .../ProgramRoster.queries.ts | 19 + .../ProgramRoster.ts | 58 ++ .../ProgramSessions.names.ts | 20 + .../ProgramSessions.queries.ts | 19 + .../ProgramSessions.ts | 50 ++ .../ProgramStat.names.ts | 23 + .../ProgramStat.queries.ts | 25 + .../ProgramStat.ts | 48 ++ .../ProgramVerdict.ts | 40 ++ .../ProgramView.names.ts | 20 + .../ProgramView.queries.ts | 25 + .../ProgramView.ts | 39 ++ .../ProgramsByMonth.names.ts | 19 + .../ProgramsByMonth.queries.ts | 19 + .../ProgramsByMonth.ts | 46 ++ .../ProgramsByWeek.names.ts | 17 + .../ProgramsByWeek.queries.ts | 19 + .../ProgramsByWeek.ts | 38 ++ .../ProgramsEmptyScope.names.ts | 17 + .../ProgramsEmptyScope.queries.ts | 19 + .../ProgramsEmptyScope.ts | 38 ++ .../ProgramsOverTime.names.ts | 22 + .../ProgramsOverTime.queries.ts | 19 + .../ProgramsOverTime.ts | 58 ++ .../RecentPrograms.names.ts | 16 + .../RecentPrograms.queries.ts | 19 + .../RecentPrograms.ts | 34 ++ .../ReferralAuth.names.ts | 23 + .../ReferralAuth.ts | 113 ++++ .../Session.names.ts | 21 + .../Session.queries.ts | 61 ++ .../Session.ts | 97 +++ .../SessionsByProgram.names.ts | 19 + .../SessionsByProgram.queries.ts | 19 + .../SessionsByProgram.ts | 46 ++ .../Settings.ts | 43 ++ .../Tag.names.ts | 19 + .../Tag.queries.ts | 50 ++ .../Tag.ts | 86 +++ .../Week.names.ts | 23 + .../Week.queries.ts | 61 ++ .../Week.ts | 116 ++++ .../WeekLabel.ts | 28 + .../WeekShapes.names.ts | 22 + .../WeekShapes.queries.ts | 19 + .../WeekShapes.ts | 58 ++ .../coachNote.extractor.ts | 45 ++ .../coachNote.response.ts | 103 ++++ .../coachNote.responseFormat.ts | 20 + .../enums.ts | 7 + .../index.ts | 59 ++ .../package.json | 1 + .../prompts.ts | 8 + .../WorkItem.queries.ts | 56 ++ .../tmp-db-schema-generic-sAIph4/WorkItem.ts | 86 +++ .../tmp-db-schema-generic-sAIph4/consumer.ts | 12 + .../tmp-tph-ref-sqlite-YoKZOH/Broker.names.ts | 23 + .../test/tmp-tph-ref-sqlite-YoKZOH/Broker.ts | 103 ++++ .../Carrier.names.ts | 24 + .../test/tmp-tph-ref-sqlite-YoKZOH/Carrier.ts | 112 ++++ .../tmp-tph-ref-sqlite-YoKZOH/Depot.names.ts | 18 + .../Depot.queries.ts | 50 ++ .../test/tmp-tph-ref-sqlite-YoKZOH/Depot.ts | 80 +++ .../tmp-tph-ref-sqlite-YoKZOH/Leg.names.ts | 22 + .../tmp-tph-ref-sqlite-YoKZOH/Leg.queries.ts | 72 +++ .../test/tmp-tph-ref-sqlite-YoKZOH/Leg.ts | 110 ++++ .../Organization.names.ts | 24 + .../tmp-tph-ref-sqlite-YoKZOH/Organization.ts | 19 + .../tmp-tph-ref-sqlite-YoKZOH/Party.names.ts | 19 + .../Party.queries.ts | 101 ++++ .../test/tmp-tph-ref-sqlite-YoKZOH/Party.ts | 130 +++++ .../Shipment.names.ts | 18 + .../Shipment.queries.ts | 56 ++ .../tmp-tph-ref-sqlite-YoKZOH/Shipment.ts | 85 +++ .../test/tmp-tph-ref-sqlite-YoKZOH/index.ts | 8 + 190 files changed, 9190 insertions(+), 8 deletions(-) create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Label.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramBrief.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramVerdict.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Settings.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekLabel.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.extractor.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.response.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.responseFormat.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/enums.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/index.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/package.json create mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/prompts.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/consumer.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.names.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.queries.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.ts create mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/index.ts diff --git a/server/rust/metaobjects-codegen/src/service_routes.rs b/server/rust/metaobjects-codegen/src/service_routes.rs index 9ec3990160..b89b33e53a 100644 --- a/server/rust/metaobjects-codegen/src/service_routes.rs +++ b/server/rust/metaobjects-codegen/src/service_routes.rs @@ -342,13 +342,9 @@ pub fn routes_packages(ctx: &GenContext<'_>) -> Result, GenEr }, None => String::new(), }; - let binding = tree - .children(o.names.node) - .iter() - .copied() - .find(|&c| { - tree.node(c).type_name == TYPE_BINDING && tree.node(c).sub_type == SUBTYPE_REST - }); + let binding = tree.children(o.names.node).iter().copied().find(|&c| { + tree.node(c).type_name == TYPE_BINDING && tree.node(c).sub_type == SUBTYPE_REST + }); let declared = |attr| binding.and_then(|b| tree.attr(b, attr)?.as_str().map(str::to_string)); let method = declared(ATTR_METHOD).map_or_else( diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs index cd913137dc..48b3aae251 100644 --- a/server/rust/metaobjects/src/validate/rules.rs +++ b/server/rust/metaobjects/src/validate/rules.rs @@ -932,7 +932,8 @@ fn file_name_placeholder_problem(file_name: &str) -> Option { rest.push(ch); i += ch.len_utf8(); } - rest.contains(['{', '}']).then(|| "has an unmatched brace".to_string()) + rest.contains(['{', '}']) + .then(|| "has an unmatched brace".to_string()) } /// The checks for one operation of an api.eventing or api.batch: its shapes (O1), the form of diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.names.ts new file mode 100644 index 0000000000..dd73c208d5 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.names.ts @@ -0,0 +1,39 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AllTypes + +export const AllTypesNames = { + type: "object", + subType: "entity", + name: "AllTypes", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "all_types" }, + }, + fields: { + bVal: { name: "bVal", column: "b_val" }, + dVal: { name: "dVal", column: "d_val" }, + dateVal: { name: "dateVal", column: "date_val" }, + decVal: { name: "decVal", column: "dec_val" }, + durationVal: { name: "durationVal", column: "duration_val" }, + enumVal: { name: "enumVal", column: "enum_val" }, + fVal: { name: "fVal", column: "f_val" }, + iVal: { name: "iVal", column: "i_val" }, + id: { name: "id", column: "id" }, + inet6Val: { name: "inet6Val", column: "inet6_val" }, + inetVal: { name: "inetVal", column: "inet_val" }, + intEnumVal: { name: "intEnumVal", column: "int_enum_val" }, + lVal: { name: "lVal", column: "l_val" }, + labels: { name: "labels", column: "labels" }, + moneyVal: { name: "moneyVal", column: "money_val" }, + sVal: { name: "sVal", column: "s_val" }, + settings: { name: "settings", column: "settings" }, + timeVal: { name: "timeVal", column: "time_val" }, + tsTzVal: { name: "tsTzVal", column: "ts_tz_val" }, + tsVal: { name: "tsVal", column: "ts_val" }, + uriVal: { name: "uriVal", column: "uri_val" }, + uuidVal: { name: "uuidVal", column: "uuid_val" }, + }, + identities: { + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.queries.ts new file mode 100644 index 0000000000..b6fb3cab28 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.queries.ts @@ -0,0 +1,50 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AllTypes (AllTypes) +// Extend in your own module (e.g. AllTypes.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { type AllTypes, AllTypesInsertSchema, type AllTypesPatch, AllTypesUpdateSchema, allTypes } from "./AllTypes.js"; + +type Db = PgDatabase>; + +export async function findAllTypesById(db: Db, id: string): Promise { + const [allTypesRow] = await db.select().from(allTypes).where(eq(allTypes.id, id)).limit(1); + return allTypesRow ?? null; +} + +export async function listAllTypes(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(allTypes).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createAllTypes(db: Db, data: z.input): Promise { + const validated = AllTypesInsertSchema.parse(data); + const [allTypesRow] = await db.insert(allTypes).values(validated).returning(); + return allTypesRow!; +} + +export async function updateAllTypes(db: Db, id: string, patch: AllTypesPatch): Promise { + const validated = AllTypesUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findAllTypesById(db, id); + } + const [allTypesRow] = await db.update(allTypes).set(validated).where(eq(allTypes.id, id)).returning(); + return allTypesRow ?? null; +} + +export async function deleteAllTypesById(db: Db, id: string): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(allTypes).where(eq(allTypes.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.ts new file mode 100644 index 0000000000..425354ba28 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.ts @@ -0,0 +1,552 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AllTypes (AllTypes) +// Extend in your own module (e.g. AllTypes.extra.ts) — nothing imports it for you. + +import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; +import { + bigint, + boolean, + check, + customType, + date, + doublePrecision, + inet, + integer, + jsonb, + numeric, + pgTable, + real, + text, + time, + timestamp, + uuid, + varchar, +} from "drizzle-orm/pg-core"; +import { z } from "zod"; +import { type Label, LabelInsertSchema } from "./Label.js"; +import { type Settings, SettingsInsertSchema } from "./Settings.js"; + +/** A field.duration column. Binds the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration); + * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month + * part. Counted in bigint microseconds, so the column is the only limit. Generated. */ +const durationColumn = (() => { + const ZERO = BigInt(0); + const SECOND = BigInt(1000000); + const MINUTE = BigInt(60000000); + const HOUR = BigInt(3600000000); + const DAY = BigInt(86400000000); + const WEEK = BigInt(604800000000); + const INT64_MAX = BigInt("9223372036854775807"); + const parseIso = (text: string): bigint | undefined => { + const p = /^([-+])?P(?!$)(?:(\d+)W)?(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d+))?S)?)?$/.exec(text); + if (p === null) { + return undefined; + } + const mag = BigInt(p[2] ?? 0) * WEEK + BigInt(p[3] ?? 0) * DAY + BigInt(p[4] ?? 0) * HOUR + + BigInt(p[5] ?? 0) * MINUTE + BigInt(p[6] ?? 0) * SECOND + BigInt((p[7] ?? "").padEnd(6, "0").slice(0, 6)); + return p[1] === "-" ? -mag : mag; + }; + const isoText = (micros: bigint): string => { + const neg = micros < ZERO; + let rest = neg ? -micros : micros; + const h = rest / HOUR; + rest %= HOUR; + const m = rest / MINUTE; + rest %= MINUTE; + const s = rest / SECOND; + const f = rest % SECOND; + let out = "PT"; + if (h > ZERO) { + out += String(h) + "H"; + } + if (m > ZERO) { + out += String(m) + "M"; + } + if (s > ZERO || f > ZERO) { + out += String(s) + (f > ZERO ? "." + String(f).padStart(6, "0").replace(/0+$/, "") : "") + "S"; + } + if (out === "PT") { + return "PT0S"; + } + return neg ? "-" + out : out; + }; + const pgText = (micros: bigint): string => { + const neg = micros < ZERO; + let rest = neg ? -micros : micros; + const two = (n: bigint): string => String(n).padStart(2, "0"); + const h = rest / HOUR; + rest %= HOUR; + const m = rest / MINUTE; + rest %= MINUTE; + let out = two(h) + ":" + two(m) + ":" + two(rest / SECOND); + const f = rest % SECOND; + if (f > ZERO) { + out += "." + String(f).padStart(6, "0").replace(/0+$/, ""); + } + return neg ? "-" + out : out; + }; + const stored = (micros: bigint): number | bigint => { + if (micros > INT64_MAX || micros < -INT64_MAX - BigInt(1)) { + throw new Error("the span " + isoText(micros) + " does not fit the 64-bit microsecond column a field.duration is stored in"); + } + const n = Number(micros); + return Number.isSafeInteger(n) ? n : micros; + }; + const notFixed = (v: unknown): Error => + new Error("the interval " + JSON.stringify(v) + " has a year or month part, so it is not a fixed-length field.duration"); + const read = (v: unknown): bigint => { + if (typeof v === "bigint") { + return v; + } + if (typeof v === "number" && Number.isInteger(v)) { + return BigInt(v); + } + if (typeof v === "string") { + if (/^-?\d+$/.test(v)) { + return BigInt(v); + } + const iso = parseIso(v); + if (iso !== undefined) { + return iso; + } + const p = v.length === 0 ? null : /^(?:([-+]?\d+) years? ?)?(?:([-+]?\d+) mons? ?)?(?:([-+]?\d+) days? ?)?(?:([-+])?(\d+):(\d{2}):(\d{2})(?:\.(\d{1,6}))?)?$/.exec(v); + if (p === null) { + throw new Error("not a field.duration value: " + JSON.stringify(v)); + } + if (Number(p[1] ?? 0) !== 0 || Number(p[2] ?? 0) !== 0) { + throw notFixed(v); + } + let time = ZERO; + if (p[5] !== undefined) { + time = BigInt(p[5]) * HOUR + BigInt(p[6] ?? 0) * MINUTE + BigInt(p[7] ?? 0) * SECOND + BigInt((p[8] ?? "").padEnd(6, "0")); + if (p[4] === "-") { + time = -time; + } + } + return BigInt(p[3] ?? 0) * DAY + time; + } + if (v !== null && typeof v === "object") { + const o = v as Record; + if ((o.years ?? 0) !== 0 || (o.months ?? 0) !== 0) { + throw notFixed(v); + } + const whole = (n: number | undefined): bigint => BigInt(Math.trunc(n ?? 0)); + // postgres-interval carries microseconds as a fractional millisecond count. + return whole(o.days) * DAY + whole(o.hours) * HOUR + whole(o.minutes) * MINUTE + whole(o.seconds) * SECOND + + BigInt(Math.round((o.milliseconds ?? 0) * 1000)); + } + throw new Error("not a field.duration value: " + JSON.stringify(v)); + }; + return customType<{ data: string; driverData: string }>({ + dataType: () => "interval", + toDriver: (value) => pgText(read(value)), + fromDriver: (value) => isoText(read(value)), + }); +})(); + +const INT_ENUM_VAL_TO_INT = { "DRAFT": 0, "PUBLISHED": 5, "ARCHIVED": 9 } as const satisfies Record<"DRAFT" | "PUBLISHED" | "ARCHIVED", number>; +const INT_ENUM_VAL_FROM_INT: Record = { 0: "DRAFT", 5: "PUBLISHED", 9: "ARCHIVED" }; +const intEnumValIntEnum = customType<{ data: "DRAFT" | "PUBLISHED" | "ARCHIVED"; driverData: number }>({ + dataType: () => "integer", + toDriver: (value) => INT_ENUM_VAL_TO_INT[value], + fromDriver: (value) => { + const member = INT_ENUM_VAL_FROM_INT[value]; + if (member === undefined) { + throw new Error(`unmapped intEnumValIntEnum value: ${value}`); + } + return member; + }, +}); + +export const allTypes = pgTable("all_types", { + id: uuid("id").primaryKey().defaultRandom(), + sVal: varchar("s_val", { length: 200 }).notNull(), + iVal: integer("i_val").notNull(), + lVal: bigint("l_val", { mode: "number" }).notNull(), + dVal: doublePrecision("d_val").notNull(), + fVal: real("f_val").notNull(), + decVal: numeric("dec_val", { precision: 18, scale: 6 }).notNull(), + bVal: boolean("b_val").notNull(), + dateVal: date("date_val").notNull(), + timeVal: time("time_val").notNull(), + tsVal: timestamp("ts_val", { mode: "string", withTimezone: false }).notNull(), + tsTzVal: timestamp("ts_tz_val", { mode: "string", withTimezone: true }).notNull(), + moneyVal: bigint("money_val", { mode: "number" }).notNull(), + enumVal: text("enum_val", { enum: ["LOW", "MEDIUM", "HIGH"] as const }).notNull(), + intEnumVal: intEnumValIntEnum("int_enum_val"), + uuidVal: uuid("uuid_val").notNull(), + uriVal: text("uri_val").notNull(), + inetVal: inet("inet_val").notNull(), + inet6Val: inet("inet6_val").notNull(), + durationVal: durationColumn("duration_val"), + settings: jsonb("settings").$type(), + labels: jsonb("labels").$type(), +}, (table) => [ + check("all_types_enum_val_chk", sql`enum_val IN ('LOW', 'MEDIUM', 'HIGH')`), + check("all_types_int_enum_val_chk", sql`int_enum_val IN (0, 5, 9)`), +]); + +export type AllTypes = InferSelectModel; +export type AllTypesInsert = InferInsertModel; +export type AllTypesUpdate = Partial; + +export type AllTypesEnumVal = "LOW" | "MEDIUM" | "HIGH"; +export const AllTypesEnumValEnum = z.enum(["LOW", "MEDIUM", "HIGH"]); +export type AllTypesIntEnumVal = "DRAFT" | "PUBLISHED" | "ARCHIVED"; +export const AllTypesIntEnumValEnum = z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]); + +/** A field.timestamp instant in UTC (`YYYY-MM-DDTHH:MM:SS[.fff]Z`): a value already spelled so is kept + * as sent, an offset is applied, a zoneless value is UTC and a date alone is midnight UTC. + * SQLite/D1 compare timestamps as text, so instants are stored in UTC. Generated. */ +function utcIsoTimestamp(v: string): string { + if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { + return v; + } + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); + if (m === null) { + return v; + } + const t = Date.parse( + `${m[1]}T${m[2] ?? "00:00"}:${m[3] ?? "00"}.${(m[4] ?? "").slice(0, 3).padEnd(3, "0")}${ + m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` + }`, + ); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); +} + +/** A field.decimal on the wire: a string in the JSON-number grammar (an exponent is allowed) or a JSON + * number, rewritten to its canonical string (plain notation, no trailing fraction zeros, zero as "0"). + * Garbage, or a value the column cannot hold without rounding, is a validation issue. Generated. */ +function decimalWrite(v: string | number, ctx: z.RefinementCtx, precision?: number, scale = 0): string { + if (typeof v === "number" && Number.isFinite(v) && !Number.isSafeInteger(v) && Number(v.toPrecision(15)) !== v) { + ctx.addIssue({ code: "custom", message: "Decimal number cannot be read exactly as a JSON number; send it as a string" }); + return z.NEVER; + } + const text = typeof v === "number" ? (Number.isFinite(v) ? String(v) : "") : v; + const m = /^(-?)(0|[1-9][0-9]*)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/.exec(text); + const e = m === null || m[4] === undefined ? 0 : Number(m[4]); + if (m === null || !Number.isSafeInteger(e) || Math.abs(e) > 1000) { + ctx.addIssue({ code: "custom", message: "Not a decimal number" }); + return z.NEVER; + } + const whole = m[2] ?? ""; + let digits = whole + (m[3] ?? ""); + let point = whole.length + e; + const lead = digits.length - digits.replace(/^0+/, "").length; + digits = digits.slice(lead).replace(/0+$/, ""); + point -= lead; + if (digits.length === 0) { + return "0"; + } + const plain = point <= 0 + ? `0.${"0".repeat(-point)}${digits}` + : point >= digits.length + ? digits + "0".repeat(point - digits.length) + : `${digits.slice(0, point)}.${digits.slice(point)}`; + const fraction = point >= digits.length ? 0 : digits.length - Math.max(point, 0) + Math.max(-point, 0); + const integer = Math.max(point, 0); + if (plain.length > 1000 || (precision !== undefined && (fraction > scale || integer > precision - scale))) { + ctx.addIssue({ code: "custom", message: "Decimal out of range for the column" }); + return z.NEVER; + } + return m[1] === "-" ? `-${plain}` : plain; +} + +/** A field.duration on the wire: an ISO-8601 duration (weeks, days, hours, minutes, seconds) rewritten + * to its canonical form — hours never folded into days, zero components left out, zero as PT0S, one + * leading "-" for a negative span. Counted in bigint microseconds, so any length is exact and a + * fraction past six digits is truncated toward zero. Generated. */ +function durationWrite(text: string): string { + const ZERO = BigInt(0); + const SECOND = BigInt(1000000); + const MINUTE = BigInt(60000000); + const HOUR = BigInt(3600000000); + const DAY = BigInt(86400000000); + const WEEK = BigInt(604800000000); + const parseIso = (text: string): bigint | undefined => { + const p = /^([-+])?P(?!$)(?:(\d+)W)?(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d+))?S)?)?$/.exec(text); + if (p === null) { + return undefined; + } + const mag = BigInt(p[2] ?? 0) * WEEK + BigInt(p[3] ?? 0) * DAY + BigInt(p[4] ?? 0) * HOUR + + BigInt(p[5] ?? 0) * MINUTE + BigInt(p[6] ?? 0) * SECOND + BigInt((p[7] ?? "").padEnd(6, "0").slice(0, 6)); + return p[1] === "-" ? -mag : mag; + }; + const isoText = (micros: bigint): string => { + const neg = micros < ZERO; + let rest = neg ? -micros : micros; + const h = rest / HOUR; + rest %= HOUR; + const m = rest / MINUTE; + rest %= MINUTE; + const s = rest / SECOND; + const f = rest % SECOND; + let out = "PT"; + if (h > ZERO) { + out += String(h) + "H"; + } + if (m > ZERO) { + out += String(m) + "M"; + } + if (s > ZERO || f > ZERO) { + out += String(s) + (f > ZERO ? "." + String(f).padStart(6, "0").replace(/0+$/, "") : "") + "S"; + } + if (out === "PT") { + return "PT0S"; + } + return neg ? "-" + out : out; + }; + const micros = parseIso(text); + return micros === undefined ? text : isoText(micros); +} + +export const AllTypesInsertSchema = z.object({ + sVal: z.string().min(1).max(200), + iVal: z.number().int(), + lVal: z.number().int(), + dVal: z.number(), + fVal: z.number(), + decVal: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 18, 6)), + bVal: z.boolean(), + dateVal: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)$/, "must be an ISO date (YYYY-MM-DD)"), + timeVal: z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?$/, "must be a time of day (HH:MM[:SS[.fff]], optional offset)"), + tsVal: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])"), + tsTzVal: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])").transform(utcIsoTimestamp), + moneyVal: z.number().int(), + enumVal: z.enum(["LOW", "MEDIUM", "HIGH"]), + intEnumVal: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]).optional(), + uuidVal: z.string().regex(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, "Invalid uuid"), + uriVal: z.string().url(), + inetVal: z.string().regex(/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/).or(z.string().regex(/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9]))$/)), + inet6Val: z.string().regex(/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/).or(z.string().regex(/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9]))$/)), + durationVal: z.string().regex(/^[-+]?P(?!$)(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+(\.\d+)?S)?)?$/).transform(durationWrite).optional(), + settings: SettingsInsertSchema.optional(), + labels: z.array(LabelInsertSchema).optional(), +}); + +export const AllTypesUpdateSchema = z.object({ + sVal: z.string().min(1).max(200).optional(), + iVal: z.number().int().optional(), + lVal: z.number().int().optional(), + dVal: z.number().optional(), + fVal: z.number().optional(), + decVal: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 18, 6)).optional(), + bVal: z.boolean().optional(), + dateVal: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)$/, "must be an ISO date (YYYY-MM-DD)").optional(), + timeVal: z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?$/, "must be a time of day (HH:MM[:SS[.fff]], optional offset)").optional(), + tsVal: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])").optional(), + tsTzVal: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])").transform(utcIsoTimestamp).optional(), + moneyVal: z.number().int().optional(), + enumVal: z.enum(["LOW", "MEDIUM", "HIGH"]).optional(), + intEnumVal: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]).optional().nullable(), + uuidVal: z.string().regex(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, "Invalid uuid").optional(), + uriVal: z.string().url().optional(), + inetVal: z.string().regex(/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/).or(z.string().regex(/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9]))$/)).optional(), + inet6Val: z.string().regex(/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/).or(z.string().regex(/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9]))$/)).optional(), + durationVal: z.string().regex(/^[-+]?P(?!$)(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+(\.\d+)?S)?)?$/).transform(durationWrite).optional().nullable(), + settings: SettingsInsertSchema.optional().nullable(), + labels: z.array(LabelInsertSchema).optional().nullable(), +}); + +/** + * Typed create shape for AllTypes: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createAllTypes` call site; + * the schema still validates at runtime. + */ +export type AllTypesCreate = z.input; + +/** + * Typed patch shape for AllTypes: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateAllTypes` call site. + */ +export type AllTypesPatch = z.input; + +/** + * Metadata constants for AllTypes. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(AllTypes, AllTypesInsertSchema); + * + */ +export const AllTypes = { + $entity: "AllTypes", + $table: "all_types", + $path: "/all_types", + id: { + name: "id", + label: "Id", + view: "text", + htmlType: "text", + }, + sVal: { + name: "sVal", + label: "S Val", + view: "text", + htmlType: "text", + rules: { required: "S Val is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, + }, + iVal: { + name: "iVal", + label: "I Val", + view: "number", + htmlType: "number", + rules: { required: "I Val is required" }, + }, + lVal: { + name: "lVal", + label: "L Val", + view: "number", + htmlType: "number", + rules: { required: "L Val is required" }, + }, + dVal: { + name: "dVal", + label: "D Val", + view: "number", + htmlType: "number", + step: "any", + rules: { required: "D Val is required" }, + }, + fVal: { + name: "fVal", + label: "F Val", + view: "number", + htmlType: "number", + step: "any", + rules: { required: "F Val is required" }, + }, + decVal: { + name: "decVal", + label: "Dec Val", + view: "number", + htmlType: "text", + inputMode: "decimal", + rules: { required: "Dec Val is required" }, + }, + bVal: { + name: "bVal", + label: "B Val", + view: "checkbox", + htmlType: "checkbox", + rules: { required: "B Val is required" }, + }, + dateVal: { + name: "dateVal", + label: "Date Val", + view: "date", + htmlType: "date", + rules: { required: "Date Val is required" }, + }, + timeVal: { + name: "timeVal", + label: "Time Val", + view: "date", + htmlType: "time", + rules: { required: "Time Val is required" }, + }, + tsVal: { + name: "tsVal", + label: "Ts Val", + view: "date", + htmlType: "datetime-local", + rules: { required: "Ts Val is required" }, + }, + tsTzVal: { + name: "tsTzVal", + label: "Ts Tz Val", + view: "date", + htmlType: "datetime-local", + rules: { required: "Ts Tz Val is required" }, + }, + moneyVal: { + name: "moneyVal", + label: "Money Val", + view: "currency", + rules: { required: "Money Val is required" }, + currency: "USD", + locale: "en-US", + }, + enumVal: { + name: "enumVal", + label: "Enum Val", + view: "dropdown", + rules: { required: "Enum Val is required" }, + options: ["LOW", "MEDIUM", "HIGH"] as const, + }, + intEnumVal: { + name: "intEnumVal", + label: "Int Enum Val", + view: "dropdown", + options: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const, + }, + uuidVal: { + name: "uuidVal", + label: "Uuid Val", + view: "text", + htmlType: "text", + rules: { required: "Uuid Val is required" }, + }, + uriVal: { + name: "uriVal", + label: "Uri Val", + view: "text", + htmlType: "text", + rules: { required: "Uri Val is required" }, + }, + inetVal: { + name: "inetVal", + label: "Inet Val", + view: "text", + htmlType: "text", + rules: { required: "Inet Val is required" }, + }, + inet6Val: { + name: "inet6Val", + label: "Inet6Val", + view: "text", + htmlType: "text", + rules: { required: "Inet6Val is required" }, + }, + durationVal: { + name: "durationVal", + label: "Duration Val", + view: "text", + htmlType: "text", + }, + settings: { + name: "settings", + label: "Settings", + view: "text", + htmlType: "text", + }, + labels: { + name: "labels", + label: "Labels", + view: "text", + htmlType: "text", + }, +} as const; + +export type AllTypesFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: AllTypesFilter[]; + and?: AllTypesFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.names.ts new file mode 100644 index 0000000000..0bdf425a02 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.names.ts @@ -0,0 +1,26 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AllTypesBreakdown + +export const AllTypesBreakdownNames = { + type: "object", + subType: "report", + name: "AllTypesBreakdown", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_all_types_breakdown" }, + }, + fields: { + allRows: { name: "allRows", column: "all_rows" }, + avgDec: { name: "avgDec", column: "avg_dec" }, + dateKey: { name: "dateKey", column: "date_key" }, + flag: { name: "flag", column: "flag" }, + highRows: { name: "highRows", column: "high_rows" }, + legacyStatus: { name: "legacyStatus", column: "legacy_status" }, + level: { name: "level", column: "level" }, + maxMoney: { name: "maxMoney", column: "max_money" }, + minLong: { name: "minLong", column: "min_long" }, + totalInts: { name: "totalInts", column: "total_ints" }, + uuidKey: { name: "uuidKey", column: "uuid_key" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.queries.ts new file mode 100644 index 0000000000..d6c781b655 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AllTypesBreakdown (AllTypesBreakdown) — report (read-only) +// Extend in your own module (e.g. AllTypesBreakdown.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type AllTypesBreakdown, allTypesBreakdownView } from "./AllTypesBreakdown.js"; + +type Db = PgDatabase>; + +export async function listAllTypesBreakdowns(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(allTypesBreakdownView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.ts new file mode 100644 index 0000000000..a02efa6888 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.ts @@ -0,0 +1,88 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AllTypesBreakdown (AllTypesBreakdown) + +import { bigint, boolean, customType, date, numeric, pgView, text, uuid } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +const LEGACY_STATUS_TO_INT = { "DRAFT": 0, "PUBLISHED": 5, "ARCHIVED": 9 } as const satisfies Record<"DRAFT" | "PUBLISHED" | "ARCHIVED", number>; +const LEGACY_STATUS_FROM_INT: Record = { 0: "DRAFT", 5: "PUBLISHED", 9: "ARCHIVED" }; +const legacyStatusIntEnum = customType<{ data: "DRAFT" | "PUBLISHED" | "ARCHIVED"; driverData: number }>({ + dataType: () => "integer", + toDriver: (value) => LEGACY_STATUS_TO_INT[value], + fromDriver: (value) => { + const member = LEGACY_STATUS_FROM_INT[value]; + if (member === undefined) { + throw new Error(`unmapped legacyStatusIntEnum value: ${value}`); + } + return member; + }, +}); + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const allTypesBreakdownView = pgView("v_all_types_breakdown", { + flag: boolean("flag").notNull(), + level: text("level", { enum: ["LOW", "MEDIUM", "HIGH"] as const }).notNull(), + legacyStatus: legacyStatusIntEnum("legacy_status"), + dateKey: date("date_key").notNull(), + uuidKey: uuid("uuid_key").notNull(), + allRows: bigint("all_rows", { mode: "number" }).notNull(), + totalInts: bigint("total_ints", { mode: "number" }), + avgDec: numeric("avg_dec", { precision: 19, scale: 4 }), + maxMoney: bigint("max_money", { mode: "number" }), + minLong: bigint("min_long", { mode: "number" }), + highRows: bigint("high_rows", { mode: "number" }).notNull(), +}).existing(); + +export const AllTypesBreakdownSchema = z.object({ + flag: z.boolean(), + level: z.enum(["LOW", "MEDIUM", "HIGH"]), + legacyStatus: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]).nullable(), + dateKey: z.string(), + uuidKey: z.string(), + allRows: z.number().int(), + totalInts: z.number().int().nullable(), + avgDec: z.string().nullable(), + maxMoney: z.number().int().nullable(), + minLong: z.number().int().nullable(), + highRows: z.number().int(), +}); + +export type AllTypesBreakdown = z.infer; + +export const AllTypesBreakdown = { + $entity: "AllTypesBreakdown", + $view: "v_all_types_breakdown", + $path: "/all_types_breakdowns", + flag: { name: "flag", label: "Flag", view: "checkbox", dbCol: "flag" }, + level: { name: "level", label: "Level", view: "dropdown", dbCol: "level" }, + legacyStatus: { name: "legacyStatus", label: "Legacy Status", view: "dropdown", dbCol: "legacy_status" }, + dateKey: { name: "dateKey", label: "Date Key", view: "date", dbCol: "date_key" }, + uuidKey: { name: "uuidKey", label: "Uuid Key", view: "text", dbCol: "uuid_key" }, + allRows: { name: "allRows", label: "All Rows", view: "number", dbCol: "all_rows" }, + totalInts: { name: "totalInts", label: "Total Ints", view: "number", dbCol: "total_ints" }, + avgDec: { name: "avgDec", label: "Avg Dec", view: "number", dbCol: "avg_dec" }, + maxMoney: { name: "maxMoney", label: "Max Money", view: "currency", dbCol: "max_money", currency: "USD", locale: "en-US" }, + minLong: { name: "minLong", label: "Min Long", view: "number", dbCol: "min_long" }, + highRows: { name: "highRows", label: "High Rows", view: "number", dbCol: "high_rows" }, +} as const; + +export type AllTypesBreakdownFilter = { + limit?: number; + offset?: number; + sort?: `${"flag" | "level" | "legacyStatus" | "dateKey" | "uuidKey" | "allRows" | "totalInts" | "avgDec" | "maxMoney" | "minLong" | "highRows"}:${"asc" | "desc"}` | "flag" | "level" | "legacyStatus" | "dateKey" | "uuidKey" | "allRows" | "totalInts" | "avgDec" | "maxMoney" | "minLong" | "highRows"; + flag?: boolean | { eq?: boolean; isNull?: boolean }; + level?: "LOW" | "MEDIUM" | "HIGH" | { eq?: "LOW" | "MEDIUM" | "HIGH"; ne?: "LOW" | "MEDIUM" | "HIGH"; in?: ("LOW" | "MEDIUM" | "HIGH")[]; like?: string; isNull?: boolean }; + legacyStatus?: "DRAFT" | "PUBLISHED" | "ARCHIVED" | { eq?: "DRAFT" | "PUBLISHED" | "ARCHIVED"; ne?: "DRAFT" | "PUBLISHED" | "ARCHIVED"; in?: ("DRAFT" | "PUBLISHED" | "ARCHIVED")[]; isNull?: boolean }; + dateKey?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + uuidKey?: string | { eq?: string; ne?: string; in?: string[]; isNull?: boolean }; + allRows?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + totalInts?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + avgDec?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + maxMoney?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + minLong?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + highRows?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: AllTypesBreakdownFilter[]; + and?: AllTypesBreakdownFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.names.ts new file mode 100644 index 0000000000..c6a45c0069 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.names.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ArchivedLedgerEntry + +export const ArchivedLedgerEntryNames = { + type: "object", + subType: "entity", + name: "ArchivedLedgerEntry", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", schema: "archive", table: "ledger_entries" }, + }, + fields: { + id: { name: "id", column: "id" }, + memo: { name: "memo", column: "memo" }, + }, + identities: { + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.queries.ts new file mode 100644 index 0000000000..546d797a24 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.queries.ts @@ -0,0 +1,56 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ArchivedLedgerEntry (ArchivedLedgerEntry) +// Extend in your own module (e.g. ArchivedLedgerEntry.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { + type ArchivedLedgerEntry, + ArchivedLedgerEntryInsertSchema, + type ArchivedLedgerEntryPatch, + ArchivedLedgerEntryUpdateSchema, + archivedLedgerEntries, +} from "./ArchivedLedgerEntry.js"; + +type Db = PgDatabase>; + +export async function findArchivedLedgerEntryById(db: Db, id: number): Promise { + const [archivedLedgerEntry] = await db.select().from(archivedLedgerEntries).where(eq(archivedLedgerEntries.id, id)).limit(1); + return archivedLedgerEntry ?? null; +} + +export async function listArchivedLedgerEntries(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(archivedLedgerEntries).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createArchivedLedgerEntry(db: Db, data: z.input): Promise { + const validated = ArchivedLedgerEntryInsertSchema.parse(data); + const [archivedLedgerEntry] = await db.insert(archivedLedgerEntries).values(validated).returning(); + return archivedLedgerEntry!; +} + +export async function updateArchivedLedgerEntry(db: Db, id: number, patch: ArchivedLedgerEntryPatch): Promise { + const validated = ArchivedLedgerEntryUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findArchivedLedgerEntryById(db, id); + } + const [archivedLedgerEntry] = await db.update(archivedLedgerEntries).set(validated).where(eq(archivedLedgerEntries.id, id)).returning(); + return archivedLedgerEntry ?? null; +} + +export async function deleteArchivedLedgerEntryById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(archivedLedgerEntries).where(eq(archivedLedgerEntries.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.ts new file mode 100644 index 0000000000..3110cc4c61 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.ts @@ -0,0 +1,86 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ArchivedLedgerEntry (ArchivedLedgerEntry) +// Extend in your own module (e.g. ArchivedLedgerEntry.extra.ts) — nothing imports it for you. + +import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; +import { bigint, pgSchema, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +export const archivedLedgerEntries = pgSchema("archive").table("ledger_entries", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + memo: varchar("memo", { length: 40 }), +}); + +export type ArchivedLedgerEntry = InferSelectModel; +export type ArchivedLedgerEntryInsert = InferInsertModel; +export type ArchivedLedgerEntryUpdate = Partial; + +export const ArchivedLedgerEntryInsertSchema = z.object({ + memo: z.string().max(40).optional(), +}); + +export const ArchivedLedgerEntryUpdateSchema = z.object({ + memo: z.string().max(40).optional().nullable(), +}); + +/** + * Typed create shape for ArchivedLedgerEntry: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createArchivedLedgerEntry` call site; + * the schema still validates at runtime. + */ +export type ArchivedLedgerEntryCreate = z.input; + +/** + * Typed patch shape for ArchivedLedgerEntry: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateArchivedLedgerEntry` call site. + */ +export type ArchivedLedgerEntryPatch = z.input; + +/** + * Metadata constants for ArchivedLedgerEntry. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(ArchivedLedgerEntry, ArchivedLedgerEntryInsertSchema); + * + */ +export const ArchivedLedgerEntry = { + $entity: "ArchivedLedgerEntry", + $table: "ledger_entries", + $path: "/archived_ledger_entries", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + memo: { + name: "memo", + label: "Memo", + view: "text", + htmlType: "text", + rules: { maxLength: { value: 40, message: "Must be 40 characters or fewer" } }, + }, +} as const; + +export type ArchivedLedgerEntryFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: ArchivedLedgerEntryFilter[]; + and?: ArchivedLedgerEntryFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.names.ts new file mode 100644 index 0000000000..88ef6e4b4b --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.names.ts @@ -0,0 +1,25 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Asset + +export const AssetNames = { + type: "object", + subType: "entity", + name: "Asset", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "assets" }, + }, + fields: { + asOfDate: { name: "asOfDate", column: "as_of_date" }, + atTime: { name: "atTime", column: "at_time" }, + externalId: { name: "externalId", column: "external_id" }, + id: { name: "id", column: "id" }, + observedAt: { name: "observedAt", column: "observed_at" }, + ownerId: { name: "ownerId", column: "owner_id" }, + payload: { name: "payload", column: "payload" }, + recordedAt: { name: "recordedAt", column: "recorded_at" }, + }, + identities: { + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.queries.ts new file mode 100644 index 0000000000..799989ac65 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.queries.ts @@ -0,0 +1,50 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Asset (Asset) +// Extend in your own module (e.g. Asset.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { type Asset, AssetInsertSchema, type AssetPatch, AssetUpdateSchema, assets } from "./Asset.js"; + +type Db = PgDatabase>; + +export async function findAssetById(db: Db, id: string): Promise { + const [asset] = await db.select().from(assets).where(eq(assets.id, id)).limit(1); + return asset ?? null; +} + +export async function listAssets(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(assets).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createAsset(db: Db, data: z.input): Promise { + const validated = AssetInsertSchema.parse(data); + const [asset] = await db.insert(assets).values(validated).returning(); + return asset!; +} + +export async function updateAsset(db: Db, id: string, patch: AssetPatch): Promise { + const validated = AssetUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findAssetById(db, id); + } + const [asset] = await db.update(assets).set(validated).where(eq(assets.id, id)).returning(); + return asset ?? null; +} + +export async function deleteAssetById(db: Db, id: string): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(assets).where(eq(assets.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.ts new file mode 100644 index 0000000000..374eba6365 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.ts @@ -0,0 +1,164 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Asset (Asset) +// Extend in your own module (e.g. Asset.extra.ts) — nothing imports it for you. + +import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; +import { date, jsonb, pgTable, time, timestamp, uuid } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +export const assets = pgTable("assets", { + id: uuid("id").primaryKey().defaultRandom(), + ownerId: uuid("owner_id").notNull(), + externalId: uuid("external_id"), + payload: jsonb("payload"), + recordedAt: timestamp("recorded_at", { mode: "string", withTimezone: true }).notNull(), + observedAt: timestamp("observed_at", { mode: "string", withTimezone: false }).notNull(), + asOfDate: date("as_of_date").notNull(), + atTime: time("at_time").notNull(), +}); + +export type Asset = InferSelectModel; +export type AssetInsert = InferInsertModel; +export type AssetUpdate = Partial; + +/** A field.timestamp instant in UTC (`YYYY-MM-DDTHH:MM:SS[.fff]Z`): a value already spelled so is kept + * as sent, an offset is applied, a zoneless value is UTC and a date alone is midnight UTC. + * SQLite/D1 compare timestamps as text, so instants are stored in UTC. Generated. */ +function utcIsoTimestamp(v: string): string { + if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { + return v; + } + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); + if (m === null) { + return v; + } + const t = Date.parse( + `${m[1]}T${m[2] ?? "00:00"}:${m[3] ?? "00"}.${(m[4] ?? "").slice(0, 3).padEnd(3, "0")}${ + m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` + }`, + ); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); +} + +export const AssetInsertSchema = z.object({ + ownerId: z.string().regex(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, "Invalid uuid"), + externalId: z.string().optional(), + payload: z.unknown().optional(), + recordedAt: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])").transform(utcIsoTimestamp), + observedAt: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])"), + asOfDate: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)$/, "must be an ISO date (YYYY-MM-DD)"), + atTime: z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?$/, "must be a time of day (HH:MM[:SS[.fff]], optional offset)"), +}); + +export const AssetUpdateSchema = z.object({ + ownerId: z.string().regex(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, "Invalid uuid").optional(), + externalId: z.string().optional().nullable(), + payload: z.unknown().optional().nullable(), + recordedAt: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])").transform(utcIsoTimestamp).optional(), + observedAt: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])").optional(), + asOfDate: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)$/, "must be an ISO date (YYYY-MM-DD)").optional(), + atTime: z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?$/, "must be a time of day (HH:MM[:SS[.fff]], optional offset)").optional(), +}); + +/** + * Typed create shape for Asset: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createAsset` call site; + * the schema still validates at runtime. + */ +export type AssetCreate = z.input; + +/** + * Typed patch shape for Asset: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateAsset` call site. + */ +export type AssetPatch = z.input; + +/** + * Metadata constants for Asset. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Asset, AssetInsertSchema); + * + */ +export const Asset = { + $entity: "Asset", + $table: "assets", + $path: "/assets", + id: { + name: "id", + label: "Id", + view: "text", + htmlType: "text", + }, + ownerId: { + name: "ownerId", + label: "Owner Id", + view: "text", + htmlType: "text", + rules: { required: "Owner Id is required" }, + }, + externalId: { + name: "externalId", + label: "External Id", + view: "text", + htmlType: "text", + }, + payload: { + name: "payload", + label: "Payload", + view: "text", + htmlType: "text", + }, + recordedAt: { + name: "recordedAt", + label: "Recorded At", + view: "date", + htmlType: "datetime-local", + rules: { required: "Recorded At is required" }, + }, + observedAt: { + name: "observedAt", + label: "Observed At", + view: "date", + htmlType: "datetime-local", + rules: { required: "Observed At is required" }, + }, + asOfDate: { + name: "asOfDate", + label: "As Of Date", + view: "date", + htmlType: "date", + rules: { required: "As Of Date is required" }, + }, + atTime: { + name: "atTime", + label: "At Time", + view: "date", + htmlType: "time", + rules: { required: "At Time is required" }, + }, +} as const; + +export type AssetFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: AssetFilter[]; + and?: AssetFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.names.ts new file mode 100644 index 0000000000..6b593ceabc --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.names.ts @@ -0,0 +1,18 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AssetActivity + +export const AssetActivityNames = { + type: "object", + subType: "report", + name: "AssetActivity", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_asset_activity" }, + }, + fields: { + asOfDateWeek: { name: "asOfDateWeek", column: "as_of_date_week" }, + assets: { name: "assets", column: "assets" }, + recordedAtHour: { name: "recordedAtHour", column: "recorded_at_hour" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.queries.ts new file mode 100644 index 0000000000..e8a825d5a2 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AssetActivity (AssetActivity) — report (read-only) +// Extend in your own module (e.g. AssetActivity.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type AssetActivity, assetActivityView } from "./AssetActivity.js"; + +type Db = PgDatabase>; + +export async function listAssetActivities(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(assetActivityView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.ts new file mode 100644 index 0000000000..c4e9cb5bec --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.ts @@ -0,0 +1,42 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AssetActivity (AssetActivity) + +import { bigint, date, pgView, timestamp } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const assetActivityView = pgView("v_asset_activity", { + recordedAtHour: timestamp("recorded_at_hour", { mode: "string", withTimezone: true }).notNull(), + asOfDateWeek: date("as_of_date_week").notNull(), + assets: bigint("assets", { mode: "number" }).notNull(), +}).existing(); + +export const AssetActivitySchema = z.object({ + recordedAtHour: z.string(), + asOfDateWeek: z.string(), + assets: z.number().int(), +}); + +export type AssetActivity = z.infer; + +export const AssetActivity = { + $entity: "AssetActivity", + $view: "v_asset_activity", + $path: "/asset_activities", + recordedAtHour: { name: "recordedAtHour", label: "Recorded At Hour", view: "date", dbCol: "recorded_at_hour" }, + asOfDateWeek: { name: "asOfDateWeek", label: "As Of Date Week", view: "date", dbCol: "as_of_date_week" }, + assets: { name: "assets", label: "Assets", view: "number", dbCol: "assets" }, +} as const; + +export type AssetActivityFilter = { + limit?: number; + offset?: number; + sort?: `${"recordedAtHour" | "asOfDateWeek" | "assets"}:${"asc" | "desc"}` | "recordedAtHour" | "asOfDateWeek" | "assets"; + recordedAtHour?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + asOfDateWeek?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + assets?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: AssetActivityFilter[]; + and?: AssetActivityFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.names.ts new file mode 100644 index 0000000000..c052c495a9 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.names.ts @@ -0,0 +1,22 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AssetDays + +export const AssetDaysNames = { + type: "object", + subType: "report", + name: "AssetDays", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_asset_days" }, + }, + fields: { + asOfDateMonth: { name: "asOfDateMonth", column: "as_of_date_month" }, + assets: { name: "assets", column: "assets" }, + firstRecorded: { name: "firstRecorded", column: "first_recorded" }, + lastAsOf: { name: "lastAsOf", column: "last_as_of" }, + lastObserved: { name: "lastObserved", column: "last_observed" }, + owners: { name: "owners", column: "owners" }, + recordedAtDay: { name: "recordedAtDay", column: "recorded_at_day" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.queries.ts new file mode 100644 index 0000000000..2ba90b5003 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AssetDays (AssetDays) — report (read-only) +// Extend in your own module (e.g. AssetDays.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type AssetDays, assetDaysView } from "./AssetDays.js"; + +type Db = PgDatabase>; + +export async function listAssetDays(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(assetDaysView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.ts new file mode 100644 index 0000000000..3a5f42f544 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.ts @@ -0,0 +1,58 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AssetDays (AssetDays) + +import { bigint, date, pgView, timestamp } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const assetDaysView = pgView("v_asset_days", { + recordedAtDay: date("recorded_at_day").notNull(), + asOfDateMonth: date("as_of_date_month").notNull(), + assets: bigint("assets", { mode: "number" }).notNull(), + owners: bigint("owners", { mode: "number" }).notNull(), + firstRecorded: timestamp("first_recorded", { mode: "string", withTimezone: true }), + lastObserved: timestamp("last_observed", { mode: "string", withTimezone: false }), + lastAsOf: date("last_as_of"), +}).existing(); + +export const AssetDaysSchema = z.object({ + recordedAtDay: z.string(), + asOfDateMonth: z.string(), + assets: z.number().int(), + owners: z.number().int(), + firstRecorded: z.string().nullable(), + lastObserved: z.string().nullable(), + lastAsOf: z.string().nullable(), +}); + +export type AssetDays = z.infer; + +export const AssetDays = { + $entity: "AssetDays", + $view: "v_asset_days", + $path: "/asset_days", + recordedAtDay: { name: "recordedAtDay", label: "Recorded At Day", view: "date", dbCol: "recorded_at_day" }, + asOfDateMonth: { name: "asOfDateMonth", label: "As Of Date Month", view: "date", dbCol: "as_of_date_month" }, + assets: { name: "assets", label: "Assets", view: "number", dbCol: "assets" }, + owners: { name: "owners", label: "Owners", view: "number", dbCol: "owners" }, + firstRecorded: { name: "firstRecorded", label: "First Recorded", view: "date", dbCol: "first_recorded" }, + lastObserved: { name: "lastObserved", label: "Last Observed", view: "date", dbCol: "last_observed" }, + lastAsOf: { name: "lastAsOf", label: "Last As Of", view: "date", dbCol: "last_as_of" }, +} as const; + +export type AssetDaysFilter = { + limit?: number; + offset?: number; + sort?: `${"recordedAtDay" | "asOfDateMonth" | "assets" | "owners" | "firstRecorded" | "lastObserved" | "lastAsOf"}:${"asc" | "desc"}` | "recordedAtDay" | "asOfDateMonth" | "assets" | "owners" | "firstRecorded" | "lastObserved" | "lastAsOf"; + recordedAtDay?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + asOfDateMonth?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + assets?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + owners?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + firstRecorded?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + lastObserved?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + lastAsOf?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + or?: AssetDaysFilter[]; + and?: AssetDaysFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.names.ts new file mode 100644 index 0000000000..f697de41f3 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.names.ts @@ -0,0 +1,20 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Auth + +export const AuthNames = { + type: "object", + subType: "entity", + name: "Auth", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "auths" }, + }, + fields: { + id: { name: "id", column: "id" }, + reference: { name: "reference", column: "reference" }, + type: { name: "type", column: "type" }, + }, + identities: { + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.queries.ts new file mode 100644 index 0000000000..fd8a18a0b6 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.queries.ts @@ -0,0 +1,175 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Auth (Auth) — TPH discriminator base +// Extend in your own module (e.g. Auth.extra.ts) — nothing imports it for you. + +import { and, eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { type Auth, auths, parseAuth } from "./Auth.js"; +import { type BridgeAuth, BridgeAuthInsertSchema, BridgeAuthSchema } from "./BridgeAuth.js"; +import { type CouponAuth, CouponAuthInsertSchema, CouponAuthSchema } from "./CouponAuth.js"; +import { type PermitAuth, PermitAuthInsertSchema, PermitAuthSchema } from "./PermitAuth.js"; +import { type ReferralAuth, ReferralAuthInsertSchema, ReferralAuthSchema } from "./ReferralAuth.js"; + +type Db = PgDatabase>; + +export async function findAuthById(db: Db, id: number): Promise { + const [row] = await db.select().from(auths).where(eq(auths.id, id)).limit(1); + return row ? parseAuth(row) : null; +} + +export async function listAuths(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(auths).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + const rows = await q; + return rows.map((r) => parseAuth(r)); +} + +export async function listBridgeAuths(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(auths).where(eq(auths.type, "Bridge")).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + const rows = await q; + return rows.map((r) => BridgeAuthSchema.parse(r)); +} + +export async function findBridgeAuthById(db: Db, id: number): Promise { + const [row] = await db.select().from(auths).where(and(eq(auths.id, id), eq(auths.type, "Bridge"))).limit(1); + return row ? BridgeAuthSchema.parse(row) : null; +} + +export async function createBridgeAuth(db: Db, data: z.input): Promise { + const validated = BridgeAuthInsertSchema.parse(data); + const [row] = await db.insert(auths).values({ ...validated, type: "Bridge" }).returning(); + return BridgeAuthSchema.parse(row!); +} + +export async function updateBridgeAuthById(db: Db, id: number, data: Partial>): Promise { + const validated = BridgeAuthInsertSchema.partial().parse(data) as Record; + // The discriminator is immutable — a BridgeAuth can never become another subtype. + const { ["type"]: _disc, ...safe } = validated; + const [row] = await db.update(auths).set(safe).where(and(eq(auths.id, id), eq(auths.type, "Bridge"))).returning(); + return row ? BridgeAuthSchema.parse(row) : null; +} + +export async function deleteBridgeAuthById(db: Db, id: number): Promise { + const deleted = await db.delete(auths).where(and(eq(auths.id, id), eq(auths.type, "Bridge"))).returning(); + return deleted.length > 0; +} + +export async function listCouponAuths(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(auths).where(eq(auths.type, "Coupon")).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + const rows = await q; + return rows.map((r) => CouponAuthSchema.parse(r)); +} + +export async function findCouponAuthById(db: Db, id: number): Promise { + const [row] = await db.select().from(auths).where(and(eq(auths.id, id), eq(auths.type, "Coupon"))).limit(1); + return row ? CouponAuthSchema.parse(row) : null; +} + +export async function createCouponAuth(db: Db, data: z.input): Promise { + const validated = CouponAuthInsertSchema.parse(data); + const [row] = await db.insert(auths).values({ ...validated, type: "Coupon" }).returning(); + return CouponAuthSchema.parse(row!); +} + +export async function updateCouponAuthById(db: Db, id: number, data: Partial>): Promise { + const validated = CouponAuthInsertSchema.partial().parse(data) as Record; + // The discriminator is immutable — a CouponAuth can never become another subtype. + const { ["type"]: _disc, ...safe } = validated; + const [row] = await db.update(auths).set(safe).where(and(eq(auths.id, id), eq(auths.type, "Coupon"))).returning(); + return row ? CouponAuthSchema.parse(row) : null; +} + +export async function deleteCouponAuthById(db: Db, id: number): Promise { + const deleted = await db.delete(auths).where(and(eq(auths.id, id), eq(auths.type, "Coupon"))).returning(); + return deleted.length > 0; +} + +export async function listPermitAuths(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(auths).where(eq(auths.type, "Permit")).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + const rows = await q; + return rows.map((r) => PermitAuthSchema.parse(r)); +} + +export async function findPermitAuthById(db: Db, id: number): Promise { + const [row] = await db.select().from(auths).where(and(eq(auths.id, id), eq(auths.type, "Permit"))).limit(1); + return row ? PermitAuthSchema.parse(row) : null; +} + +export async function createPermitAuth(db: Db, data: z.input): Promise { + const validated = PermitAuthInsertSchema.parse(data); + const [row] = await db.insert(auths).values({ ...validated, type: "Permit" }).returning(); + return PermitAuthSchema.parse(row!); +} + +export async function updatePermitAuthById(db: Db, id: number, data: Partial>): Promise { + const validated = PermitAuthInsertSchema.partial().parse(data) as Record; + // The discriminator is immutable — a PermitAuth can never become another subtype. + const { ["type"]: _disc, ...safe } = validated; + const [row] = await db.update(auths).set(safe).where(and(eq(auths.id, id), eq(auths.type, "Permit"))).returning(); + return row ? PermitAuthSchema.parse(row) : null; +} + +export async function deletePermitAuthById(db: Db, id: number): Promise { + const deleted = await db.delete(auths).where(and(eq(auths.id, id), eq(auths.type, "Permit"))).returning(); + return deleted.length > 0; +} + +export async function listReferralAuths(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(auths).where(eq(auths.type, "Referral")).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + const rows = await q; + return rows.map((r) => ReferralAuthSchema.parse(r)); +} + +export async function findReferralAuthById(db: Db, id: number): Promise { + const [row] = await db.select().from(auths).where(and(eq(auths.id, id), eq(auths.type, "Referral"))).limit(1); + return row ? ReferralAuthSchema.parse(row) : null; +} + +export async function createReferralAuth(db: Db, data: z.input): Promise { + const validated = ReferralAuthInsertSchema.parse(data); + const [row] = await db.insert(auths).values({ ...validated, type: "Referral" }).returning(); + return ReferralAuthSchema.parse(row!); +} + +export async function updateReferralAuthById(db: Db, id: number, data: Partial>): Promise { + const validated = ReferralAuthInsertSchema.partial().parse(data) as Record; + // The discriminator is immutable — a ReferralAuth can never become another subtype. + const { ["type"]: _disc, ...safe } = validated; + const [row] = await db.update(auths).set(safe).where(and(eq(auths.id, id), eq(auths.type, "Referral"))).returning(); + return row ? ReferralAuthSchema.parse(row) : null; +} + +export async function deleteReferralAuthById(db: Db, id: number): Promise { + const deleted = await db.delete(auths).where(and(eq(auths.id, id), eq(auths.type, "Referral"))).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.ts new file mode 100644 index 0000000000..825e2d9a1e --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.ts @@ -0,0 +1,143 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Auth (Auth) +// Extend in your own module (e.g. Auth.extra.ts) — nothing imports it for you. + +import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; +import { bigint, check, integer, numeric, pgTable, text, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; +import { type BridgeAuth, BridgeAuthSchema } from "./BridgeAuth.js"; +import { type CouponAuth, CouponAuthSchema } from "./CouponAuth.js"; +import { type PermitAuth, PermitAuthSchema } from "./PermitAuth.js"; +import { type ReferralAuth, ReferralAuthSchema } from "./ReferralAuth.js"; + +export const auths = pgTable("auths", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + type: text("type", { enum: ["Bridge", "Coupon", "Permit", "Referral"] as const }), + reference: varchar("reference", { length: 80 }).notNull(), + quantity: integer("quantity"), + couponAmount: numeric("coupon_amount", { precision: 10, scale: 2 }), + approver: varchar("approver", { length: 80 }), + urgency: varchar("urgency", { length: 16 }), +}, (table) => [check("auths_type_chk", sql`type IN ('Bridge', 'Coupon', 'Permit', 'Referral')`)]); + +export type AuthRow = InferSelectModel; +export type AuthInsert = InferInsertModel; +export type AuthUpdate = Partial; + +export type AuthType = "Bridge" | "Coupon" | "Permit" | "Referral"; +export const AuthTypeEnum = z.enum(["Bridge", "Coupon", "Permit", "Referral"]); + +export const AuthInsertSchema = z.object({ + type: z.enum(["Bridge", "Coupon", "Permit", "Referral"]).optional(), + reference: z.string().min(1).max(80), +}); + +export const AuthUpdateSchema = z.object({ + type: z.enum(["Bridge", "Coupon", "Permit", "Referral"]).optional().nullable(), + reference: z.string().min(1).max(80).optional(), +}); + +/** + * Typed create shape for Auth: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createAuth` call site; + * the schema still validates at runtime. + */ +export type AuthCreate = z.input; + +/** + * Typed patch shape for Auth: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateAuth` call site. + */ +export type AuthPatch = z.input; + +/** + * Metadata constants for Auth. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Auth, AuthInsertSchema); + * + */ +export const Auth = { + $entity: "Auth", + $table: "auths", + $path: "/auths", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + type: { + name: "type", + label: "Type", + view: "dropdown", + options: ["Bridge", "Coupon", "Permit", "Referral"] as const, + }, + reference: { + name: "reference", + label: "Reference", + view: "text", + htmlType: "text", + rules: { required: "Reference is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, + }, +} as const; + +export type AuthFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: AuthFilter[]; + and?: AuthFilter[]; +}; + +export type Auth = BridgeAuth | CouponAuth | PermitAuth | ReferralAuth; + +/** True when value is a BridgeAuth (discriminated by type === "Bridge"). */ +export function isBridgeAuth(value: Auth): value is BridgeAuth { + return value.type === "Bridge"; +} + +/** True when value is a CouponAuth (discriminated by type === "Coupon"). */ +export function isCouponAuth(value: Auth): value is CouponAuth { + return value.type === "Coupon"; +} + +/** True when value is a PermitAuth (discriminated by type === "Permit"). */ +export function isPermitAuth(value: Auth): value is PermitAuth { + return value.type === "Permit"; +} + +/** True when value is a ReferralAuth (discriminated by type === "Referral"). */ +export function isReferralAuth(value: Auth): value is ReferralAuth { + return value.type === "Referral"; +} + +/** + * Parse a row from the Auth table, dispatching by the + * `type` discriminator value to the matching subtype's + * Zod schema. Throws on unknown discriminator values. + */ +export function parseAuth(row: unknown): Auth { + const head = z.object({ type: z.enum(["Bridge", "Coupon", "Permit", "Referral"]) }).parse(row); + switch (head.type) { + case "Bridge": return BridgeAuthSchema.parse(row); + case "Coupon": return CouponAuthSchema.parse(row); + case "Permit": return PermitAuthSchema.parse(row); + case "Referral": return ReferralAuthSchema.parse(row); + } +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.names.ts new file mode 100644 index 0000000000..e9f026d125 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.names.ts @@ -0,0 +1,18 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AuthsByKind + +export const AuthsByKindNames = { + type: "object", + subType: "report", + name: "AuthsByKind", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_auths_by_kind" }, + }, + fields: { + auths: { name: "auths", column: "auths" }, + distinctRefs: { name: "distinctRefs", column: "distinct_refs" }, + kind: { name: "kind", column: "kind" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.queries.ts new file mode 100644 index 0000000000..cc02874029 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AuthsByKind (AuthsByKind) — report (read-only) +// Extend in your own module (e.g. AuthsByKind.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type AuthsByKind, authsByKindView } from "./AuthsByKind.js"; + +type Db = PgDatabase>; + +export async function listAuthsByKinds(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(authsByKindView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.ts new file mode 100644 index 0000000000..6e9c1bcd5d --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.ts @@ -0,0 +1,42 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: AuthsByKind (AuthsByKind) + +import { bigint, pgView, text } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const authsByKindView = pgView("v_auths_by_kind", { + kind: text("kind", { enum: ["Bridge", "Coupon", "Permit", "Referral"] as const }), + auths: bigint("auths", { mode: "number" }).notNull(), + distinctRefs: bigint("distinct_refs", { mode: "number" }).notNull(), +}).existing(); + +export const AuthsByKindSchema = z.object({ + kind: z.enum(["Bridge", "Coupon", "Permit", "Referral"]).nullable(), + auths: z.number().int(), + distinctRefs: z.number().int(), +}); + +export type AuthsByKind = z.infer; + +export const AuthsByKind = { + $entity: "AuthsByKind", + $view: "v_auths_by_kind", + $path: "/auths_by_kinds", + kind: { name: "kind", label: "Kind", view: "dropdown", dbCol: "kind" }, + auths: { name: "auths", label: "Auths", view: "number", dbCol: "auths" }, + distinctRefs: { name: "distinctRefs", label: "Distinct Refs", view: "number", dbCol: "distinct_refs" }, +} as const; + +export type AuthsByKindFilter = { + limit?: number; + offset?: number; + sort?: `${"kind" | "auths" | "distinctRefs"}:${"asc" | "desc"}` | "kind" | "auths" | "distinctRefs"; + kind?: "Bridge" | "Coupon" | "Permit" | "Referral" | { eq?: "Bridge" | "Coupon" | "Permit" | "Referral"; ne?: "Bridge" | "Coupon" | "Permit" | "Referral"; in?: ("Bridge" | "Coupon" | "Permit" | "Referral")[]; like?: string; isNull?: boolean }; + auths?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + distinctRefs?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: AuthsByKindFilter[]; + and?: AuthsByKindFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.names.ts new file mode 100644 index 0000000000..50cce25f69 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.names.ts @@ -0,0 +1,23 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: BridgeAuth + +import { AuthNames } from "./Auth.names.js"; + +export const BridgeAuthNames = { + type: "object", + subType: "entity", + name: "BridgeAuth", + sources: { + ...AuthNames.sources, + }, + fields: { + ...AuthNames.fields, + quantity: { name: "quantity", column: "quantity" }, + }, + identities: { + ...AuthNames.identities, + }, + indexes: { + ...AuthNames.indexes, + }, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.ts new file mode 100644 index 0000000000..c99e85cae0 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.ts @@ -0,0 +1,113 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: BridgeAuth (BridgeAuth) +// Extend in your own module (e.g. BridgeAuth.extra.ts) — nothing imports it for you. + +import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; +import { z } from "zod"; + +export interface BridgeAuth { + id?: number | undefined; + type?: BridgeAuthType | null | undefined; + reference: string; + quantity: number | null; +} + +export type BridgeAuthType = "Bridge" | "Coupon" | "Permit" | "Referral"; +export const BridgeAuthTypeEnum = z.enum(["Bridge", "Coupon", "Permit", "Referral"]); + +export const BridgeAuthSchema = z.object({ + id: z.number().int(), + type: z.literal("Bridge"), + reference: z.string().min(1).max(80), + quantity: z.number().int().nullable(), +}); + +export const BridgeAuthInsertSchema = z.object({ + type: z.literal("Bridge"), + reference: z.string().min(1).max(80), + quantity: z.number().int(), +}); + +export const BridgeAuthUpdateSchema = z.object({ + reference: z.string().min(1).max(80).optional(), + quantity: z.number().int().optional(), +}); + +/** + * Typed create shape for BridgeAuth: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createBridgeAuth` call site; + * the schema still validates at runtime. + */ +export type BridgeAuthCreate = z.input; + +/** + * Typed patch shape for BridgeAuth: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateBridgeAuth` call site. + */ +export type BridgeAuthPatch = z.input; + +/** + * Metadata constants for BridgeAuth. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(BridgeAuth, BridgeAuthInsertSchema); + * + */ +export const BridgeAuth = { + $entity: "BridgeAuth", + $table: "auths", + $path: "/auths/bridge", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + type: { + name: "type", + label: "Type", + view: "dropdown", + options: ["Bridge", "Coupon", "Permit", "Referral"] as const, + }, + reference: { + name: "reference", + label: "Reference", + view: "text", + htmlType: "text", + rules: { required: "Reference is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, + }, + quantity: { + name: "quantity", + label: "Quantity", + view: "number", + htmlType: "number", + rules: { required: "Quantity is required" }, + }, +} as const; + +export const BridgeAuthFilterAllowlist = {} as const satisfies FilterAllowlist; + +export const BridgeAuthSortAllowlist = {} as const satisfies SortAllowlist; + +export type BridgeAuthFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: BridgeAuthFilter[]; + and?: BridgeAuthFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.names.ts new file mode 100644 index 0000000000..e5bcb0fbb7 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.names.ts @@ -0,0 +1,23 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: CouponAuth + +import { AuthNames } from "./Auth.names.js"; + +export const CouponAuthNames = { + type: "object", + subType: "entity", + name: "CouponAuth", + sources: { + ...AuthNames.sources, + }, + fields: { + ...AuthNames.fields, + couponAmount: { name: "couponAmount", column: "coupon_amount" }, + }, + identities: { + ...AuthNames.identities, + }, + indexes: { + ...AuthNames.indexes, + }, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.ts new file mode 100644 index 0000000000..a426a9cb77 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.ts @@ -0,0 +1,151 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: CouponAuth (CouponAuth) +// Extend in your own module (e.g. CouponAuth.extra.ts) — nothing imports it for you. + +import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; +import { z } from "zod"; + +export interface CouponAuth { + id?: number | undefined; + type?: CouponAuthType | null | undefined; + reference: string; + couponAmount?: string | null | undefined; +} + +export type CouponAuthType = "Bridge" | "Coupon" | "Permit" | "Referral"; +export const CouponAuthTypeEnum = z.enum(["Bridge", "Coupon", "Permit", "Referral"]); + +export const CouponAuthSchema = z.object({ + id: z.number().int(), + type: z.literal("Coupon"), + reference: z.string().min(1).max(80), + couponAmount: z.string().nullable(), +}); + +/** A field.decimal on the wire: a string in the JSON-number grammar (an exponent is allowed) or a JSON + * number, rewritten to its canonical string (plain notation, no trailing fraction zeros, zero as "0"). + * Garbage, or a value the column cannot hold without rounding, is a validation issue. Generated. */ +function decimalWrite(v: string | number, ctx: z.RefinementCtx, precision?: number, scale = 0): string { + if (typeof v === "number" && Number.isFinite(v) && !Number.isSafeInteger(v) && Number(v.toPrecision(15)) !== v) { + ctx.addIssue({ code: "custom", message: "Decimal number cannot be read exactly as a JSON number; send it as a string" }); + return z.NEVER; + } + const text = typeof v === "number" ? (Number.isFinite(v) ? String(v) : "") : v; + const m = /^(-?)(0|[1-9][0-9]*)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/.exec(text); + const e = m === null || m[4] === undefined ? 0 : Number(m[4]); + if (m === null || !Number.isSafeInteger(e) || Math.abs(e) > 1000) { + ctx.addIssue({ code: "custom", message: "Not a decimal number" }); + return z.NEVER; + } + const whole = m[2] ?? ""; + let digits = whole + (m[3] ?? ""); + let point = whole.length + e; + const lead = digits.length - digits.replace(/^0+/, "").length; + digits = digits.slice(lead).replace(/0+$/, ""); + point -= lead; + if (digits.length === 0) { + return "0"; + } + const plain = point <= 0 + ? `0.${"0".repeat(-point)}${digits}` + : point >= digits.length + ? digits + "0".repeat(point - digits.length) + : `${digits.slice(0, point)}.${digits.slice(point)}`; + const fraction = point >= digits.length ? 0 : digits.length - Math.max(point, 0) + Math.max(-point, 0); + const integer = Math.max(point, 0); + if (plain.length > 1000 || (precision !== undefined && (fraction > scale || integer > precision - scale))) { + ctx.addIssue({ code: "custom", message: "Decimal out of range for the column" }); + return z.NEVER; + } + return m[1] === "-" ? `-${plain}` : plain; +} + +export const CouponAuthInsertSchema = z.object({ + type: z.literal("Coupon"), + reference: z.string().min(1).max(80), + couponAmount: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 10, 2)).optional(), +}); + +export const CouponAuthUpdateSchema = z.object({ + reference: z.string().min(1).max(80).optional(), + couponAmount: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 10, 2)).optional().nullable(), +}); + +/** + * Typed create shape for CouponAuth: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createCouponAuth` call site; + * the schema still validates at runtime. + */ +export type CouponAuthCreate = z.input; + +/** + * Typed patch shape for CouponAuth: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateCouponAuth` call site. + */ +export type CouponAuthPatch = z.input; + +/** + * Metadata constants for CouponAuth. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(CouponAuth, CouponAuthInsertSchema); + * + */ +export const CouponAuth = { + $entity: "CouponAuth", + $table: "auths", + $path: "/auths/coupon", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + type: { + name: "type", + label: "Type", + view: "dropdown", + options: ["Bridge", "Coupon", "Permit", "Referral"] as const, + }, + reference: { + name: "reference", + label: "Reference", + view: "text", + htmlType: "text", + rules: { required: "Reference is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, + }, + couponAmount: { + name: "couponAmount", + label: "Coupon Amount", + view: "number", + htmlType: "text", + inputMode: "decimal", + }, +} as const; + +export const CouponAuthFilterAllowlist = {} as const satisfies FilterAllowlist; + +export const CouponAuthSortAllowlist = {} as const satisfies SortAllowlist; + +export type CouponAuthFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: CouponAuthFilter[]; + and?: CouponAuthFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.names.ts new file mode 100644 index 0000000000..c1bcc078cd --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.names.ts @@ -0,0 +1,21 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Entry + +export const EntryNames = { + type: "object", + subType: "entity", + name: "Entry", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "entries" }, + }, + fields: { + amount: { name: "amount", column: "amount" }, + bucket: { name: "bucket", column: "bucket" }, + flagged: { name: "flagged", column: "flagged" }, + id: { name: "id", column: "id" }, + }, + identities: { + pk: { type: "identity", subType: "primary", name: "pk" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.queries.ts new file mode 100644 index 0000000000..2476e693ea --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.queries.ts @@ -0,0 +1,50 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Entry (Entry) +// Extend in your own module (e.g. Entry.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { type Entry, EntryInsertSchema, type EntryPatch, EntryUpdateSchema, entries } from "./Entry.js"; + +type Db = PgDatabase>; + +export async function findEntryById(db: Db, id: number): Promise { + const [entry] = await db.select().from(entries).where(eq(entries.id, id)).limit(1); + return entry ?? null; +} + +export async function listEntries(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(entries).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createEntry(db: Db, data: z.input): Promise { + const validated = EntryInsertSchema.parse(data); + const [entry] = await db.insert(entries).values(validated).returning(); + return entry!; +} + +export async function updateEntry(db: Db, id: number, patch: EntryPatch): Promise { + const validated = EntryUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findEntryById(db, id); + } + const [entry] = await db.update(entries).set(validated).where(eq(entries.id, id)).returning(); + return entry ?? null; +} + +export async function deleteEntryById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(entries).where(eq(entries.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.ts new file mode 100644 index 0000000000..0a054f4ba0 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.ts @@ -0,0 +1,145 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Entry (Entry) +// Extend in your own module (e.g. Entry.extra.ts) — nothing imports it for you. + +import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; +import { bigint, boolean, numeric, pgTable, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +export const entries = pgTable("entries", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + bucket: varchar("bucket", { length: 8 }).notNull(), + amount: numeric("amount", { precision: 28, scale: 10 }), + flagged: boolean("flagged").notNull(), +}); + +export type Entry = InferSelectModel; +export type EntryInsert = InferInsertModel; +export type EntryUpdate = Partial; + +/** A field.decimal on the wire: a string in the JSON-number grammar (an exponent is allowed) or a JSON + * number, rewritten to its canonical string (plain notation, no trailing fraction zeros, zero as "0"). + * Garbage, or a value the column cannot hold without rounding, is a validation issue. Generated. */ +function decimalWrite(v: string | number, ctx: z.RefinementCtx, precision?: number, scale = 0): string { + if (typeof v === "number" && Number.isFinite(v) && !Number.isSafeInteger(v) && Number(v.toPrecision(15)) !== v) { + ctx.addIssue({ code: "custom", message: "Decimal number cannot be read exactly as a JSON number; send it as a string" }); + return z.NEVER; + } + const text = typeof v === "number" ? (Number.isFinite(v) ? String(v) : "") : v; + const m = /^(-?)(0|[1-9][0-9]*)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/.exec(text); + const e = m === null || m[4] === undefined ? 0 : Number(m[4]); + if (m === null || !Number.isSafeInteger(e) || Math.abs(e) > 1000) { + ctx.addIssue({ code: "custom", message: "Not a decimal number" }); + return z.NEVER; + } + const whole = m[2] ?? ""; + let digits = whole + (m[3] ?? ""); + let point = whole.length + e; + const lead = digits.length - digits.replace(/^0+/, "").length; + digits = digits.slice(lead).replace(/0+$/, ""); + point -= lead; + if (digits.length === 0) { + return "0"; + } + const plain = point <= 0 + ? `0.${"0".repeat(-point)}${digits}` + : point >= digits.length + ? digits + "0".repeat(point - digits.length) + : `${digits.slice(0, point)}.${digits.slice(point)}`; + const fraction = point >= digits.length ? 0 : digits.length - Math.max(point, 0) + Math.max(-point, 0); + const integer = Math.max(point, 0); + if (plain.length > 1000 || (precision !== undefined && (fraction > scale || integer > precision - scale))) { + ctx.addIssue({ code: "custom", message: "Decimal out of range for the column" }); + return z.NEVER; + } + return m[1] === "-" ? `-${plain}` : plain; +} + +export const EntryInsertSchema = z.object({ + bucket: z.string().min(1).max(8), + amount: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 28, 10)).optional(), + flagged: z.boolean(), +}); + +export const EntryUpdateSchema = z.object({ + bucket: z.string().min(1).max(8).optional(), + amount: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 28, 10)).optional().nullable(), + flagged: z.boolean().optional(), +}); + +/** + * Typed create shape for Entry: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createEntry` call site; + * the schema still validates at runtime. + */ +export type EntryCreate = z.input; + +/** + * Typed patch shape for Entry: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateEntry` call site. + */ +export type EntryPatch = z.input; + +/** + * Metadata constants for Entry. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Entry, EntryInsertSchema); + * + */ +export const Entry = { + $entity: "Entry", + $table: "entries", + $path: "/entries", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + bucket: { + name: "bucket", + label: "Bucket", + view: "text", + htmlType: "text", + rules: { required: "Bucket is required", maxLength: { value: 8, message: "Must be 8 characters or fewer" } }, + }, + amount: { + name: "amount", + label: "Amount", + view: "number", + htmlType: "text", + inputMode: "decimal", + }, + flagged: { + name: "flagged", + label: "Flagged", + view: "checkbox", + htmlType: "checkbox", + rules: { required: "Flagged is required" }, + }, +} as const; + +export type EntryFilter = { + limit?: number; + offset?: number; + sort?: `${"amount"}:${"asc" | "desc"}` | "amount"; + amount?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + or?: EntryFilter[]; + and?: EntryFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.names.ts new file mode 100644 index 0000000000..0a6596155c --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.names.ts @@ -0,0 +1,23 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: EntryTotals + +export const EntryTotalsNames = { + type: "object", + subType: "report", + name: "EntryTotals", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_entry_totals" }, + }, + fields: { + bucket: { name: "bucket", column: "bucket" }, + entries: { name: "entries", column: "entries" }, + flaggedShare: { name: "flaggedShare", column: "flagged_share" }, + mean: { name: "mean", column: "mean" }, + perFlagged: { name: "perFlagged", column: "per_flagged" }, + top: { name: "top", column: "top" }, + total: { name: "total", column: "total" }, + totalOrZero: { name: "totalOrZero", column: "total_or_zero" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.queries.ts new file mode 100644 index 0000000000..7d98ec8664 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: EntryTotals (EntryTotals) — report (read-only) +// Extend in your own module (e.g. EntryTotals.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type EntryTotals, entryTotalsView } from "./EntryTotals.js"; + +type Db = PgDatabase>; + +export async function listEntryTotals(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(entryTotalsView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.ts new file mode 100644 index 0000000000..8652f8fa1c --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.ts @@ -0,0 +1,62 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: EntryTotals (EntryTotals) + +import { bigint, numeric, pgView, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const entryTotalsView = pgView("v_entry_totals", { + bucket: varchar("bucket", { length: 8 }).notNull(), + entries: bigint("entries", { mode: "number" }).notNull(), + total: numeric("total", { precision: 19, scale: 4 }), + totalOrZero: numeric("total_or_zero", { precision: 19, scale: 4 }).notNull(), + mean: numeric("mean", { precision: 19, scale: 4 }), + top: numeric("top", { precision: 28, scale: 10 }), + flaggedShare: numeric("flagged_share", { precision: 19, scale: 4 }), + perFlagged: numeric("per_flagged", { precision: 19, scale: 4 }), +}).existing(); + +export const EntryTotalsSchema = z.object({ + bucket: z.string(), + entries: z.number().int(), + total: z.string().nullable(), + totalOrZero: z.string(), + mean: z.string().nullable(), + top: z.string().nullable(), + flaggedShare: z.string().nullable(), + perFlagged: z.string().nullable(), +}); + +export type EntryTotals = z.infer; + +export const EntryTotals = { + $entity: "EntryTotals", + $view: "v_entry_totals", + $path: "/entry_totals", + bucket: { name: "bucket", label: "Bucket", view: "text", dbCol: "bucket" }, + entries: { name: "entries", label: "Entries", view: "number", dbCol: "entries" }, + total: { name: "total", label: "Total", view: "number", dbCol: "total" }, + totalOrZero: { name: "totalOrZero", label: "Total Or Zero", view: "number", dbCol: "total_or_zero" }, + mean: { name: "mean", label: "Mean", view: "number", dbCol: "mean" }, + top: { name: "top", label: "Top", view: "number", dbCol: "top" }, + flaggedShare: { name: "flaggedShare", label: "Flagged Share", view: "number", dbCol: "flagged_share" }, + perFlagged: { name: "perFlagged", label: "Per Flagged", view: "number", dbCol: "per_flagged" }, +} as const; + +export type EntryTotalsFilter = { + limit?: number; + offset?: number; + sort?: `${"bucket" | "entries" | "total" | "totalOrZero" | "mean" | "top" | "flaggedShare" | "perFlagged"}:${"asc" | "desc"}` | "bucket" | "entries" | "total" | "totalOrZero" | "mean" | "top" | "flaggedShare" | "perFlagged"; + bucket?: string | { eq?: string; ne?: string; in?: string[]; like?: string; isNull?: boolean }; + entries?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + total?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + totalOrZero?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + mean?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + top?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + flaggedShare?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + perFlagged?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + or?: EntryTotalsFilter[]; + and?: EntryTotalsFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.names.ts new file mode 100644 index 0000000000..905a3db475 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.names.ts @@ -0,0 +1,18 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: FitnessTotals + +export const FitnessTotalsNames = { + type: "object", + subType: "report", + name: "FitnessTotals", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_fitness_totals" }, + }, + fields: { + longShare: { name: "longShare", column: "long_share" }, + totalMinutes: { name: "totalMinutes", column: "total_minutes" }, + weeks: { name: "weeks", column: "weeks" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.queries.ts new file mode 100644 index 0000000000..851b00c13c --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: FitnessTotals (FitnessTotals) — report (read-only) +// Extend in your own module (e.g. FitnessTotals.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type FitnessTotals, fitnessTotalsView } from "./FitnessTotals.js"; + +type Db = PgDatabase>; + +export async function listFitnessTotals(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(fitnessTotalsView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.ts new file mode 100644 index 0000000000..9053045feb --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.ts @@ -0,0 +1,42 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: FitnessTotals (FitnessTotals) + +import { bigint, numeric, pgView } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const fitnessTotalsView = pgView("v_fitness_totals", { + weeks: bigint("weeks", { mode: "number" }).notNull(), + totalMinutes: bigint("total_minutes", { mode: "number" }), + longShare: numeric("long_share", { precision: 19, scale: 4 }), +}).existing(); + +export const FitnessTotalsSchema = z.object({ + weeks: z.number().int(), + totalMinutes: z.number().int().nullable(), + longShare: z.string().nullable(), +}); + +export type FitnessTotals = z.infer; + +export const FitnessTotals = { + $entity: "FitnessTotals", + $view: "v_fitness_totals", + $path: "/fitness_totals", + weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, + totalMinutes: { name: "totalMinutes", label: "Total Minutes", view: "number", dbCol: "total_minutes" }, + longShare: { name: "longShare", label: "Long Share", view: "number", dbCol: "long_share" }, +} as const; + +export type FitnessTotalsFilter = { + limit?: number; + offset?: number; + sort?: `${"weeks" | "totalMinutes" | "longShare"}:${"asc" | "desc"}` | "weeks" | "totalMinutes" | "longShare"; + weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + totalMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + longShare?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + or?: FitnessTotalsFilter[]; + and?: FitnessTotalsFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.names.ts new file mode 100644 index 0000000000..1a5bb1faf1 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.names.ts @@ -0,0 +1,18 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: FitnessTotalsFilled + +export const FitnessTotalsFilledNames = { + type: "object", + subType: "report", + name: "FitnessTotalsFilled", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_fitness_totals_filled" }, + }, + fields: { + longShareOrZero: { name: "longShareOrZero", column: "long_share_or_zero" }, + totalMinutesOrZero: { name: "totalMinutesOrZero", column: "total_minutes_or_zero" }, + weeks: { name: "weeks", column: "weeks" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.queries.ts new file mode 100644 index 0000000000..f19012360d --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: FitnessTotalsFilled (FitnessTotalsFilled) — report (read-only) +// Extend in your own module (e.g. FitnessTotalsFilled.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type FitnessTotalsFilled, fitnessTotalsFilledView } from "./FitnessTotalsFilled.js"; + +type Db = PgDatabase>; + +export async function listFitnessTotalsFilleds(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(fitnessTotalsFilledView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.ts new file mode 100644 index 0000000000..cb0d6b45c2 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.ts @@ -0,0 +1,42 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: FitnessTotalsFilled (FitnessTotalsFilled) + +import { bigint, numeric, pgView } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const fitnessTotalsFilledView = pgView("v_fitness_totals_filled", { + weeks: bigint("weeks", { mode: "number" }).notNull(), + totalMinutesOrZero: bigint("total_minutes_or_zero", { mode: "number" }).notNull(), + longShareOrZero: numeric("long_share_or_zero", { precision: 19, scale: 4 }).notNull(), +}).existing(); + +export const FitnessTotalsFilledSchema = z.object({ + weeks: z.number().int(), + totalMinutesOrZero: z.number().int(), + longShareOrZero: z.string(), +}); + +export type FitnessTotalsFilled = z.infer; + +export const FitnessTotalsFilled = { + $entity: "FitnessTotalsFilled", + $view: "v_fitness_totals_filled", + $path: "/fitness_totals_filleds", + weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, + totalMinutesOrZero: { name: "totalMinutesOrZero", label: "Total Minutes Or Zero", view: "number", dbCol: "total_minutes_or_zero" }, + longShareOrZero: { name: "longShareOrZero", label: "Long Share Or Zero", view: "number", dbCol: "long_share_or_zero" }, +} as const; + +export type FitnessTotalsFilledFilter = { + limit?: number; + offset?: number; + sort?: `${"weeks" | "totalMinutesOrZero" | "longShareOrZero"}:${"asc" | "desc"}` | "weeks" | "totalMinutesOrZero" | "longShareOrZero"; + weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + totalMinutesOrZero?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + longShareOrZero?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + or?: FitnessTotalsFilledFilter[]; + and?: FitnessTotalsFilledFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.names.ts new file mode 100644 index 0000000000..ada76da34c --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.names.ts @@ -0,0 +1,21 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Follow + +export const FollowNames = { + type: "object", + subType: "entity", + name: "Follow", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "follows" }, + }, + fields: { + followeeId: { name: "followeeId", column: "followee_id" }, + followerId: { name: "followerId", column: "follower_id" }, + }, + identities: { + fkFollowee: { type: "identity", subType: "reference", name: "fkFollowee" }, + fkFollower: { type: "identity", subType: "reference", name: "fkFollower" }, + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.queries.ts new file mode 100644 index 0000000000..1a9d7990ee --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.queries.ts @@ -0,0 +1,72 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Follow (Follow) +// Extend in your own module (e.g. Follow.extra.ts) — nothing imports it for you. + +import { eq, inArray } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { type Follow, FollowInsertSchema, type FollowPatch, FollowUpdateSchema, follows } from "./Follow.js"; + +type Db = PgDatabase>; + +export async function findFollowById(db: Db, followerId: number): Promise { + const [follow] = await db.select().from(follows).where(eq(follows.followerId, followerId)).limit(1); + return follow ?? null; +} + +export async function listFollows(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(follows).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createFollow(db: Db, data: z.input): Promise { + const validated = FollowInsertSchema.parse(data); + const [follow] = await db.insert(follows).values(validated).returning(); + return follow!; +} + +export async function updateFollow(db: Db, followerId: number, patch: FollowPatch): Promise { + const validated = FollowUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findFollowById(db, followerId); + } + const [follow] = await db.update(follows).set(validated).where(eq(follows.followerId, followerId)).returning(); + return follow ?? null; +} + +export async function deleteFollowById(db: Db, followerId: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(follows).where(eq(follows.followerId, followerId)).returning(); + return deleted.length > 0; +} + +export async function findFollowsByFollower(db: Db, followerId: number): Promise { + return db.select().from(follows).where(eq(follows.followerId, followerId)); +} + +export async function findFollowsByFollowerIn(db: Db, followerIds: number[]): Promise { + if (followerIds.length === 0) { + return []; + } + return db.select().from(follows).where(inArray(follows.followerId, followerIds)); +} + +export async function findFollowsByFollowee(db: Db, followeeId: number): Promise { + return db.select().from(follows).where(eq(follows.followeeId, followeeId)); +} + +export async function findFollowsByFolloweeIn(db: Db, followeeIds: number[]): Promise { + if (followeeIds.length === 0) { + return []; + } + return db.select().from(follows).where(inArray(follows.followeeId, followeeIds)); +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.ts new file mode 100644 index 0000000000..1d28088137 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.ts @@ -0,0 +1,92 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Follow (Follow) +// Extend in your own module (e.g. Follow.extra.ts) — nothing imports it for you. + +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { bigint, pgTable, primaryKey } from "drizzle-orm/pg-core"; +import { z } from "zod"; +import { persons } from "./Person.js"; + +export const follows = pgTable("follows", { + followerId: bigint("follower_id", { mode: "number" }).notNull(), + followeeId: bigint("followee_id", { mode: "number" }).notNull(), +}, (table) => [primaryKey({ columns: [table.followerId, table.followeeId] })]); + +export const followsRelations = relations(follows, ({ one }) => ({ + fkFollower: one(persons, { fields: [follows.followerId], references: [persons.id] }), + fkFollowee: one(persons, { fields: [follows.followeeId], references: [persons.id] }), +})); + +export type Follow = InferSelectModel; +export type FollowInsert = InferInsertModel; +export type FollowUpdate = Partial; + +export const FollowInsertSchema = z.object({ + followerId: z.number().int(), + followeeId: z.number().int(), +}); + +export const FollowUpdateSchema = z.object({}); + +/** + * Typed create shape for Follow: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createFollow` call site; + * the schema still validates at runtime. + */ +export type FollowCreate = z.input; + +/** + * Typed patch shape for Follow: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateFollow` call site. + */ +export type FollowPatch = z.input; + +/** + * Metadata constants for Follow. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Follow, FollowInsertSchema); + * + */ +export const Follow = { + $entity: "Follow", + $table: "follows", + $path: "/follows", + followerId: { + name: "followerId", + label: "Follower Id", + view: "number", + htmlType: "number", + rules: { required: "Follower Id is required" }, + }, + followeeId: { + name: "followeeId", + label: "Followee Id", + view: "number", + htmlType: "number", + rules: { required: "Followee Id is required" }, + }, +} as const; + +export type FollowFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: FollowFilter[]; + and?: FollowFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.names.ts new file mode 100644 index 0000000000..ea1532290b --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.names.ts @@ -0,0 +1,21 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Friendship + +export const FriendshipNames = { + type: "object", + subType: "entity", + name: "Friendship", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "friendships" }, + }, + fields: { + personAId: { name: "personAId", column: "person_a_id" }, + personBId: { name: "personBId", column: "person_b_id" }, + }, + identities: { + fkPersonA: { type: "identity", subType: "reference", name: "fkPersonA" }, + fkPersonB: { type: "identity", subType: "reference", name: "fkPersonB" }, + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.queries.ts new file mode 100644 index 0000000000..f74e318f7b --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.queries.ts @@ -0,0 +1,78 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Friendship (Friendship) +// Extend in your own module (e.g. Friendship.extra.ts) — nothing imports it for you. + +import { eq, inArray } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { + type Friendship, + FriendshipInsertSchema, + type FriendshipPatch, + FriendshipUpdateSchema, + friendships, +} from "./Friendship.js"; + +type Db = PgDatabase>; + +export async function findFriendshipById(db: Db, personAId: number): Promise { + const [friendship] = await db.select().from(friendships).where(eq(friendships.personAId, personAId)).limit(1); + return friendship ?? null; +} + +export async function listFriendships(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(friendships).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createFriendship(db: Db, data: z.input): Promise { + const validated = FriendshipInsertSchema.parse(data); + const [friendship] = await db.insert(friendships).values(validated).returning(); + return friendship!; +} + +export async function updateFriendship(db: Db, personAId: number, patch: FriendshipPatch): Promise { + const validated = FriendshipUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findFriendshipById(db, personAId); + } + const [friendship] = await db.update(friendships).set(validated).where(eq(friendships.personAId, personAId)).returning(); + return friendship ?? null; +} + +export async function deleteFriendshipById(db: Db, personAId: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(friendships).where(eq(friendships.personAId, personAId)).returning(); + return deleted.length > 0; +} + +export async function findFriendshipsByPersonA(db: Db, personAId: number): Promise { + return db.select().from(friendships).where(eq(friendships.personAId, personAId)); +} + +export async function findFriendshipsByPersonAIn(db: Db, personAIds: number[]): Promise { + if (personAIds.length === 0) { + return []; + } + return db.select().from(friendships).where(inArray(friendships.personAId, personAIds)); +} + +export async function findFriendshipsByPersonB(db: Db, personBId: number): Promise { + return db.select().from(friendships).where(eq(friendships.personBId, personBId)); +} + +export async function findFriendshipsByPersonBIn(db: Db, personBIds: number[]): Promise { + if (personBIds.length === 0) { + return []; + } + return db.select().from(friendships).where(inArray(friendships.personBId, personBIds)); +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.ts new file mode 100644 index 0000000000..49629badd1 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.ts @@ -0,0 +1,92 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Friendship (Friendship) +// Extend in your own module (e.g. Friendship.extra.ts) — nothing imports it for you. + +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { bigint, pgTable, primaryKey } from "drizzle-orm/pg-core"; +import { z } from "zod"; +import { persons } from "./Person.js"; + +export const friendships = pgTable("friendships", { + personAId: bigint("person_a_id", { mode: "number" }).notNull(), + personBId: bigint("person_b_id", { mode: "number" }).notNull(), +}, (table) => [primaryKey({ columns: [table.personAId, table.personBId] })]); + +export const friendshipsRelations = relations(friendships, ({ one }) => ({ + fkPersonA: one(persons, { fields: [friendships.personAId], references: [persons.id] }), + fkPersonB: one(persons, { fields: [friendships.personBId], references: [persons.id] }), +})); + +export type Friendship = InferSelectModel; +export type FriendshipInsert = InferInsertModel; +export type FriendshipUpdate = Partial; + +export const FriendshipInsertSchema = z.object({ + personAId: z.number().int(), + personBId: z.number().int(), +}); + +export const FriendshipUpdateSchema = z.object({}); + +/** + * Typed create shape for Friendship: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createFriendship` call site; + * the schema still validates at runtime. + */ +export type FriendshipCreate = z.input; + +/** + * Typed patch shape for Friendship: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateFriendship` call site. + */ +export type FriendshipPatch = z.input; + +/** + * Metadata constants for Friendship. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Friendship, FriendshipInsertSchema); + * + */ +export const Friendship = { + $entity: "Friendship", + $table: "friendships", + $path: "/friendships", + personAId: { + name: "personAId", + label: "Person AId", + view: "number", + htmlType: "number", + rules: { required: "Person AId is required" }, + }, + personBId: { + name: "personBId", + label: "Person BId", + view: "number", + htmlType: "number", + rules: { required: "Person BId is required" }, + }, +} as const; + +export type FriendshipFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: FriendshipFilter[]; + and?: FriendshipFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.names.ts new file mode 100644 index 0000000000..c63d5dab15 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.names.ts @@ -0,0 +1,23 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Gadget + +import { LabeledNames } from "./Labeled.names.js"; + +export const GadgetNames = { + type: "object", + subType: "entity", + name: "Gadget", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "gadgets" }, + }, + fields: { + ...LabeledNames.fields, + label: { name: "label", column: "gadget_code" }, + }, + identities: { + ...LabeledNames.identities, + }, + indexes: { + ...LabeledNames.indexes, + }, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.queries.ts new file mode 100644 index 0000000000..b4a6ff1389 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.queries.ts @@ -0,0 +1,50 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Gadget (Gadget) +// Extend in your own module (e.g. Gadget.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { type Gadget, GadgetInsertSchema, type GadgetPatch, GadgetUpdateSchema, gadgets } from "./Gadget.js"; + +type Db = PgDatabase>; + +export async function findGadgetById(db: Db, id: number): Promise { + const [gadget] = await db.select().from(gadgets).where(eq(gadgets.id, id)).limit(1); + return gadget ?? null; +} + +export async function listGadgets(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(gadgets).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createGadget(db: Db, data: z.input): Promise { + const validated = GadgetInsertSchema.parse(data); + const [gadget] = await db.insert(gadgets).values(validated).returning(); + return gadget!; +} + +export async function updateGadget(db: Db, id: number, patch: GadgetPatch): Promise { + const validated = GadgetUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findGadgetById(db, id); + } + const [gadget] = await db.update(gadgets).set(validated).where(eq(gadgets.id, id)).returning(); + return gadget ?? null; +} + +export async function deleteGadgetById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(gadgets).where(eq(gadgets.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.ts new file mode 100644 index 0000000000..5a05b8fcbe --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.ts @@ -0,0 +1,86 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Gadget (Gadget) +// Extend in your own module (e.g. Gadget.extra.ts) — nothing imports it for you. + +import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; +import { bigint, integer, pgTable } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +export const gadgets = pgTable("gadgets", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + label: integer("gadget_code").notNull(), +}); + +export type Gadget = InferSelectModel; +export type GadgetInsert = InferInsertModel; +export type GadgetUpdate = Partial; + +export const GadgetInsertSchema = z.object({ + label: z.number().int(), +}); + +export const GadgetUpdateSchema = z.object({ + label: z.number().int().optional(), +}); + +/** + * Typed create shape for Gadget: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createGadget` call site; + * the schema still validates at runtime. + */ +export type GadgetCreate = z.input; + +/** + * Typed patch shape for Gadget: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateGadget` call site. + */ +export type GadgetPatch = z.input; + +/** + * Metadata constants for Gadget. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Gadget, GadgetInsertSchema); + * + */ +export const Gadget = { + $entity: "Gadget", + $table: "gadgets", + $path: "/gadgets", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + label: { + name: "label", + label: "Label", + view: "number", + htmlType: "number", + rules: { required: "Label is required" }, + }, +} as const; + +export type GadgetFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: GadgetFilter[]; + and?: GadgetFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.names.ts new file mode 100644 index 0000000000..292c3c9a2e --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.names.ts @@ -0,0 +1,20 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: GadgetEvent + +export const GadgetEventNames = { + type: "object", + subType: "entity", + name: "GadgetEvent", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "gadget_events" }, + }, + fields: { + gadgetId: { name: "gadgetId", column: "gadget_id" }, + id: { name: "id", column: "id" }, + }, + identities: { + fkGadget: { type: "identity", subType: "reference", name: "fkGadget" }, + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.queries.ts new file mode 100644 index 0000000000..f811fc3bf7 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.queries.ts @@ -0,0 +1,67 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: GadgetEvent (GadgetEvent) +// Extend in your own module (e.g. GadgetEvent.extra.ts) — nothing imports it for you. + +import { eq, inArray } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { + type GadgetEvent, + GadgetEventInsertSchema, + type GadgetEventPatch, + GadgetEventUpdateSchema, + gadgetEvents, +} from "./GadgetEvent.js"; + +type Db = PgDatabase>; + +export async function findGadgetEventById(db: Db, id: number): Promise { + const [gadgetEvent] = await db.select().from(gadgetEvents).where(eq(gadgetEvents.id, id)).limit(1); + return gadgetEvent ?? null; +} + +export async function listGadgetEvents(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(gadgetEvents).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createGadgetEvent(db: Db, data: z.input): Promise { + const validated = GadgetEventInsertSchema.parse(data); + const [gadgetEvent] = await db.insert(gadgetEvents).values(validated).returning(); + return gadgetEvent!; +} + +export async function updateGadgetEvent(db: Db, id: number, patch: GadgetEventPatch): Promise { + const validated = GadgetEventUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findGadgetEventById(db, id); + } + const [gadgetEvent] = await db.update(gadgetEvents).set(validated).where(eq(gadgetEvents.id, id)).returning(); + return gadgetEvent ?? null; +} + +export async function deleteGadgetEventById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(gadgetEvents).where(eq(gadgetEvents.id, id)).returning(); + return deleted.length > 0; +} + +export async function findGadgetEventsByGadget(db: Db, gadgetId: number): Promise { + return db.select().from(gadgetEvents).where(eq(gadgetEvents.gadgetId, gadgetId)); +} + +export async function findGadgetEventsByGadgetIn(db: Db, gadgetIds: number[]): Promise { + if (gadgetIds.length === 0) { + return []; + } + return db.select().from(gadgetEvents).where(inArray(gadgetEvents.gadgetId, gadgetIds)); +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.ts new file mode 100644 index 0000000000..e86a8d357c --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.ts @@ -0,0 +1,87 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: GadgetEvent (GadgetEvent) +// Extend in your own module (e.g. GadgetEvent.extra.ts) — nothing imports it for you. + +import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; +import { type AnyPgColumn, bigint, pgTable } from "drizzle-orm/pg-core"; +import { z } from "zod"; +import { gadgets } from "./Gadget.js"; + +export const gadgetEvents = pgTable("gadget_events", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + gadgetId: bigint("gadget_id", { mode: "number" }).notNull().references((): AnyPgColumn => gadgets.id), +}); + +export type GadgetEvent = InferSelectModel; +export type GadgetEventInsert = InferInsertModel; +export type GadgetEventUpdate = Partial; + +export const GadgetEventInsertSchema = z.object({ + gadgetId: z.number().int(), +}); + +export const GadgetEventUpdateSchema = z.object({ + gadgetId: z.number().int().optional(), +}); + +/** + * Typed create shape for GadgetEvent: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createGadgetEvent` call site; + * the schema still validates at runtime. + */ +export type GadgetEventCreate = z.input; + +/** + * Typed patch shape for GadgetEvent: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateGadgetEvent` call site. + */ +export type GadgetEventPatch = z.input; + +/** + * Metadata constants for GadgetEvent. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(GadgetEvent, GadgetEventInsertSchema); + * + */ +export const GadgetEvent = { + $entity: "GadgetEvent", + $table: "gadget_events", + $path: "/gadget_events", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + gadgetId: { + name: "gadgetId", + label: "Gadget Id", + view: "number", + htmlType: "number", + rules: { required: "Gadget Id is required" }, + }, +} as const; + +export type GadgetEventFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: GadgetEventFilter[]; + and?: GadgetEventFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.names.ts new file mode 100644 index 0000000000..8eb2408f81 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.names.ts @@ -0,0 +1,17 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: GadgetEventsByLabel + +export const GadgetEventsByLabelNames = { + type: "object", + subType: "report", + name: "GadgetEventsByLabel", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_gadget_events_by_label" }, + }, + fields: { + gadgetEvents: { name: "gadgetEvents", column: "gadget_events" }, + gadgetLabel: { name: "gadgetLabel", column: "gadget_label" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.queries.ts new file mode 100644 index 0000000000..2e9124f5ce --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: GadgetEventsByLabel (GadgetEventsByLabel) — report (read-only) +// Extend in your own module (e.g. GadgetEventsByLabel.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type GadgetEventsByLabel, gadgetEventsByLabelView } from "./GadgetEventsByLabel.js"; + +type Db = PgDatabase>; + +export async function listGadgetEventsByLabels(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(gadgetEventsByLabelView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.ts new file mode 100644 index 0000000000..bddd2f961a --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.ts @@ -0,0 +1,38 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: GadgetEventsByLabel (GadgetEventsByLabel) + +import { bigint, integer, pgView } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const gadgetEventsByLabelView = pgView("v_gadget_events_by_label", { + gadgetLabel: integer("gadget_label").notNull(), + gadgetEvents: bigint("gadget_events", { mode: "number" }).notNull(), +}).existing(); + +export const GadgetEventsByLabelSchema = z.object({ + gadgetLabel: z.number().int(), + gadgetEvents: z.number().int(), +}); + +export type GadgetEventsByLabel = z.infer; + +export const GadgetEventsByLabel = { + $entity: "GadgetEventsByLabel", + $view: "v_gadget_events_by_label", + $path: "/gadget_events_by_labels", + gadgetLabel: { name: "gadgetLabel", label: "Gadget Label", view: "number", dbCol: "gadget_label" }, + gadgetEvents: { name: "gadgetEvents", label: "Gadget Events", view: "number", dbCol: "gadget_events" }, +} as const; + +export type GadgetEventsByLabelFilter = { + limit?: number; + offset?: number; + sort?: `${"gadgetLabel" | "gadgetEvents"}:${"asc" | "desc"}` | "gadgetLabel" | "gadgetEvents"; + gadgetLabel?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + gadgetEvents?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: GadgetEventsByLabelFilter[]; + and?: GadgetEventsByLabelFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.names.ts new file mode 100644 index 0000000000..f6d70cb4df --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.names.ts @@ -0,0 +1,20 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: IntEnumArray + +export const IntEnumArrayNames = { + type: "object", + subType: "entity", + name: "IntEnumArray", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "int_enum_arrays" }, + }, + fields: { + history: { name: "history", column: "history" }, + id: { name: "id", column: "id" }, + state: { name: "state", column: "state" }, + }, + identities: { + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.queries.ts new file mode 100644 index 0000000000..4c91e9b867 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.queries.ts @@ -0,0 +1,56 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: IntEnumArray (IntEnumArray) +// Extend in your own module (e.g. IntEnumArray.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { + type IntEnumArray, + IntEnumArrayInsertSchema, + type IntEnumArrayPatch, + IntEnumArrayUpdateSchema, + intEnumArrays, +} from "./IntEnumArray.js"; + +type Db = PgDatabase>; + +export async function findIntEnumArrayById(db: Db, id: number): Promise { + const [intEnumArray] = await db.select().from(intEnumArrays).where(eq(intEnumArrays.id, id)).limit(1); + return intEnumArray ?? null; +} + +export async function listIntEnumArrays(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(intEnumArrays).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createIntEnumArray(db: Db, data: z.input): Promise { + const validated = IntEnumArrayInsertSchema.parse(data); + const [intEnumArray] = await db.insert(intEnumArrays).values(validated).returning(); + return intEnumArray!; +} + +export async function updateIntEnumArray(db: Db, id: number, patch: IntEnumArrayPatch): Promise { + const validated = IntEnumArrayUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findIntEnumArrayById(db, id); + } + const [intEnumArray] = await db.update(intEnumArrays).set(validated).where(eq(intEnumArrays.id, id)).returning(); + return intEnumArray ?? null; +} + +export async function deleteIntEnumArrayById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(intEnumArrays).where(eq(intEnumArrays.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.ts new file mode 100644 index 0000000000..9f17ba4cb0 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.ts @@ -0,0 +1,134 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: IntEnumArray (IntEnumArray) +// Extend in your own module (e.g. IntEnumArray.extra.ts) — nothing imports it for you. + +import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; +import { bigint, check, customType, pgTable } from "drizzle-orm/pg-core"; +import { z } from "zod"; +import { PublishStateEnum } from "./enums.js"; + +const HISTORY_TO_INT = { "DRAFT": 0, "PUBLISHED": 5, "ARCHIVED": 9 } as const satisfies Record<"DRAFT" | "PUBLISHED" | "ARCHIVED", number>; +const HISTORY_FROM_INT: Record = { 0: "DRAFT", 5: "PUBLISHED", 9: "ARCHIVED" }; +const historyIntEnum = customType<{ data: "DRAFT" | "PUBLISHED" | "ARCHIVED"; driverData: number }>({ + dataType: () => "integer", + toDriver: (value) => { + const stored = HISTORY_TO_INT[value]; + if (stored === undefined) { + throw new Error(`unmapped historyIntEnum member: ${String(value)}`); + } + return stored; + }, + fromDriver: (value) => { + if (value === null) { + return value as never; + } + const member = HISTORY_FROM_INT[value]; + if (member === undefined) { + throw new Error(`unmapped historyIntEnum value: ${value}`); + } + return member; + }, +}); + +const STATE_TO_INT = { "DRAFT": 0, "PUBLISHED": 5, "ARCHIVED": 9 } as const satisfies Record<"DRAFT" | "PUBLISHED" | "ARCHIVED", number>; +const STATE_FROM_INT: Record = { 0: "DRAFT", 5: "PUBLISHED", 9: "ARCHIVED" }; +const stateIntEnum = customType<{ data: "DRAFT" | "PUBLISHED" | "ARCHIVED"; driverData: number }>({ + dataType: () => "integer", + toDriver: (value) => STATE_TO_INT[value], + fromDriver: (value) => { + const member = STATE_FROM_INT[value]; + if (member === undefined) { + throw new Error(`unmapped stateIntEnum value: ${value}`); + } + return member; + }, +}); + +export const intEnumArrays = pgTable("int_enum_arrays", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + state: stateIntEnum("state"), + history: historyIntEnum("history").array(), +}, (table) => [check("int_enum_arrays_state_chk", sql`state IN (0, 5, 9)`)]); + +export type IntEnumArray = InferSelectModel; +export type IntEnumArrayInsert = InferInsertModel; +export type IntEnumArrayUpdate = Partial; + +export { type PublishState, PublishStateEnum } from "./enums.js"; + +export const IntEnumArrayInsertSchema = z.object({ + state: PublishStateEnum.optional(), + history: z.array(PublishStateEnum).optional(), +}); + +export const IntEnumArrayUpdateSchema = z.object({ + state: PublishStateEnum.optional().nullable(), + history: z.array(PublishStateEnum).optional().nullable(), +}); + +/** + * Typed create shape for IntEnumArray: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createIntEnumArray` call site; + * the schema still validates at runtime. + */ +export type IntEnumArrayCreate = z.input; + +/** + * Typed patch shape for IntEnumArray: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateIntEnumArray` call site. + */ +export type IntEnumArrayPatch = z.input; + +/** + * Metadata constants for IntEnumArray. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(IntEnumArray, IntEnumArrayInsertSchema); + * + */ +export const IntEnumArray = { + $entity: "IntEnumArray", + $table: "int_enum_arrays", + $path: "/int_enum_arrays", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + state: { + name: "state", + label: "State", + view: "dropdown", + options: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const, + }, + history: { + name: "history", + label: "History", + view: "dropdown", + options: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const, + }, +} as const; + +export type IntEnumArrayFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: IntEnumArrayFilter[]; + and?: IntEnumArrayFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Label.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Label.ts new file mode 100644 index 0000000000..d260f4aa66 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Label.ts @@ -0,0 +1,35 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Label (Label) +// Extend in your own module (e.g. Label.extra.ts) — nothing imports it for you. + +import { z } from "zod"; + +export interface Label { + key?: string | undefined; + weight?: number | undefined; +} + +export const LabelInsertSchema = z.object({ + key: z.string().optional(), + weight: z.number().int().optional(), +}); + +/** + * Metadata constants for the value object Label: each field's name, label, view and the + * validation rules derived from its validator children (e.g. `Label..rules.maxLength.value`). + */ +export const Label = { + $entity: "Label", + key: { + name: "key", + label: "Key", + view: "text", + htmlType: "text", + }, + weight: { + name: "weight", + label: "Weight", + view: "number", + htmlType: "number", + }, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.names.ts new file mode 100644 index 0000000000..000d862737 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.names.ts @@ -0,0 +1,17 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Labeled + +export const LabeledNames = { + type: "object", + subType: "entity", + name: "Labeled", + sources: {}, + fields: { + id: { name: "id", column: "id" }, + label: { name: "label", column: "label_text" }, + }, + identities: { + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.ts new file mode 100644 index 0000000000..4d431113e0 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.ts @@ -0,0 +1,14 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Labeled (Labeled) +// Extend in your own module (e.g. Labeled.extra.ts) — nothing imports it for you. + +import { z } from "zod"; + +export interface Labeled { + id?: number | undefined; + label?: string | undefined; +} + +export const LabeledInsertSchema = z.object({ + label: z.string().optional(), +}); diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.names.ts new file mode 100644 index 0000000000..4cd394e8f9 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.names.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: LedgerEntry + +export const LedgerEntryNames = { + type: "object", + subType: "entity", + name: "LedgerEntry", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "ledger_entries" }, + }, + fields: { + id: { name: "id", column: "id" }, + memo: { name: "memo", column: "memo" }, + }, + identities: { + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.queries.ts new file mode 100644 index 0000000000..22ca30e8a4 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.queries.ts @@ -0,0 +1,56 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: LedgerEntry (LedgerEntry) +// Extend in your own module (e.g. LedgerEntry.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { + type LedgerEntry, + LedgerEntryInsertSchema, + type LedgerEntryPatch, + LedgerEntryUpdateSchema, + ledgerEntries, +} from "./LedgerEntry.js"; + +type Db = PgDatabase>; + +export async function findLedgerEntryById(db: Db, id: number): Promise { + const [ledgerEntry] = await db.select().from(ledgerEntries).where(eq(ledgerEntries.id, id)).limit(1); + return ledgerEntry ?? null; +} + +export async function listLedgerEntries(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(ledgerEntries).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createLedgerEntry(db: Db, data: z.input): Promise { + const validated = LedgerEntryInsertSchema.parse(data); + const [ledgerEntry] = await db.insert(ledgerEntries).values(validated).returning(); + return ledgerEntry!; +} + +export async function updateLedgerEntry(db: Db, id: number, patch: LedgerEntryPatch): Promise { + const validated = LedgerEntryUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findLedgerEntryById(db, id); + } + const [ledgerEntry] = await db.update(ledgerEntries).set(validated).where(eq(ledgerEntries.id, id)).returning(); + return ledgerEntry ?? null; +} + +export async function deleteLedgerEntryById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(ledgerEntries).where(eq(ledgerEntries.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.ts new file mode 100644 index 0000000000..1aa1b4e46d --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.ts @@ -0,0 +1,86 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: LedgerEntry (LedgerEntry) +// Extend in your own module (e.g. LedgerEntry.extra.ts) — nothing imports it for you. + +import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; +import { bigint, pgTable, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +export const ledgerEntries = pgTable("ledger_entries", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + memo: varchar("memo", { length: 40 }), +}); + +export type LedgerEntry = InferSelectModel; +export type LedgerEntryInsert = InferInsertModel; +export type LedgerEntryUpdate = Partial; + +export const LedgerEntryInsertSchema = z.object({ + memo: z.string().max(40).optional(), +}); + +export const LedgerEntryUpdateSchema = z.object({ + memo: z.string().max(40).optional().nullable(), +}); + +/** + * Typed create shape for LedgerEntry: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createLedgerEntry` call site; + * the schema still validates at runtime. + */ +export type LedgerEntryCreate = z.input; + +/** + * Typed patch shape for LedgerEntry: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateLedgerEntry` call site. + */ +export type LedgerEntryPatch = z.input; + +/** + * Metadata constants for LedgerEntry. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(LedgerEntry, LedgerEntryInsertSchema); + * + */ +export const LedgerEntry = { + $entity: "LedgerEntry", + $table: "ledger_entries", + $path: "/ledger_entries", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + memo: { + name: "memo", + label: "Memo", + view: "text", + htmlType: "text", + rules: { maxLength: { value: 40, message: "Must be 40 characters or fewer" } }, + }, +} as const; + +export type LedgerEntryFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: LedgerEntryFilter[]; + and?: LedgerEntryFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.names.ts new file mode 100644 index 0000000000..9d7691a78d --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.names.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: LiveIntroPrograms + +export const LiveIntroProgramsNames = { + type: "object", + subType: "report", + name: "LiveIntroPrograms", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_live_intro_programs" }, + }, + fields: { + listValue: { name: "listValue", column: "list_value" }, + notDrafts: { name: "notDrafts", column: "not_drafts" }, + programs: { name: "programs", column: "programs" }, + status: { name: "status", column: "status" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.queries.ts new file mode 100644 index 0000000000..4c729465bc --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: LiveIntroPrograms (LiveIntroPrograms) — report (read-only) +// Extend in your own module (e.g. LiveIntroPrograms.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type LiveIntroPrograms, liveIntroProgramsView } from "./LiveIntroPrograms.js"; + +type Db = PgDatabase>; + +export async function listLiveIntroPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(liveIntroProgramsView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.ts new file mode 100644 index 0000000000..5369c4527d --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.ts @@ -0,0 +1,46 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: LiveIntroPrograms (LiveIntroPrograms) + +import { bigint, pgView, text } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const liveIntroProgramsView = pgView("v_live_intro_programs", { + status: text("status", { enum: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const }).notNull(), + programs: bigint("programs", { mode: "number" }).notNull(), + notDrafts: bigint("not_drafts", { mode: "number" }).notNull(), + listValue: bigint("list_value", { mode: "number" }), +}).existing(); + +export const LiveIntroProgramsSchema = z.object({ + status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]), + programs: z.number().int(), + notDrafts: z.number().int(), + listValue: z.number().int().nullable(), +}); + +export type LiveIntroPrograms = z.infer; + +export const LiveIntroPrograms = { + $entity: "LiveIntroPrograms", + $view: "v_live_intro_programs", + $path: "/live_intro_programs", + status: { name: "status", label: "Status", view: "dropdown", dbCol: "status" }, + programs: { name: "programs", label: "Programs", view: "number", dbCol: "programs" }, + notDrafts: { name: "notDrafts", label: "Not Drafts", view: "number", dbCol: "not_drafts" }, + listValue: { name: "listValue", label: "List Value", view: "currency", dbCol: "list_value", currency: "USD", locale: "en-US" }, +} as const; + +export type LiveIntroProgramsFilter = { + limit?: number; + offset?: number; + sort?: `${"status" | "programs" | "notDrafts" | "listValue"}:${"asc" | "desc"}` | "status" | "programs" | "notDrafts" | "listValue"; + status?: "DRAFT" | "PUBLISHED" | "ARCHIVED" | { eq?: "DRAFT" | "PUBLISHED" | "ARCHIVED"; ne?: "DRAFT" | "PUBLISHED" | "ARCHIVED"; in?: ("DRAFT" | "PUBLISHED" | "ARCHIVED")[]; like?: string; isNull?: boolean }; + programs?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + notDrafts?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + listValue?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: LiveIntroProgramsFilter[]; + and?: LiveIntroProgramsFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.names.ts new file mode 100644 index 0000000000..988cd2a37e --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.names.ts @@ -0,0 +1,21 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Measurement + +export const MeasurementNames = { + type: "object", + subType: "entity", + name: "Measurement", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "measurements" }, + }, + fields: { + id: { name: "id", column: "id" }, + massKg: { name: "massKg", column: "mass_kg" }, + preciseKg: { name: "preciseKg", column: "precise_kg" }, + tempC: { name: "tempC", column: "temp_c" }, + }, + identities: { + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.queries.ts new file mode 100644 index 0000000000..bc5bf38237 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.queries.ts @@ -0,0 +1,56 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Measurement (Measurement) +// Extend in your own module (e.g. Measurement.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { + type Measurement, + MeasurementInsertSchema, + type MeasurementPatch, + MeasurementUpdateSchema, + measurements, +} from "./Measurement.js"; + +type Db = PgDatabase>; + +export async function findMeasurementById(db: Db, id: number): Promise { + const [measurement] = await db.select().from(measurements).where(eq(measurements.id, id)).limit(1); + return measurement ?? null; +} + +export async function listMeasurements(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(measurements).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createMeasurement(db: Db, data: z.input): Promise { + const validated = MeasurementInsertSchema.parse(data); + const [measurement] = await db.insert(measurements).values(validated).returning(); + return measurement!; +} + +export async function updateMeasurement(db: Db, id: number, patch: MeasurementPatch): Promise { + const validated = MeasurementUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findMeasurementById(db, id); + } + const [measurement] = await db.update(measurements).set(validated).where(eq(measurements.id, id)).returning(); + return measurement ?? null; +} + +export async function deleteMeasurementById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(measurements).where(eq(measurements.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.ts new file mode 100644 index 0000000000..0379236267 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.ts @@ -0,0 +1,147 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Measurement (Measurement) +// Extend in your own module (e.g. Measurement.extra.ts) — nothing imports it for you. + +import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; +import { bigint, doublePrecision, numeric, pgTable, real } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +export const measurements = pgTable("measurements", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + tempC: real("temp_c").notNull(), + massKg: doublePrecision("mass_kg").notNull(), + preciseKg: numeric("precise_kg", { precision: 9, scale: 4 }).notNull(), +}); + +export type Measurement = InferSelectModel; +export type MeasurementInsert = InferInsertModel; +export type MeasurementUpdate = Partial; + +/** A field.decimal on the wire: a string in the JSON-number grammar (an exponent is allowed) or a JSON + * number, rewritten to its canonical string (plain notation, no trailing fraction zeros, zero as "0"). + * Garbage, or a value the column cannot hold without rounding, is a validation issue. Generated. */ +function decimalWrite(v: string | number, ctx: z.RefinementCtx, precision?: number, scale = 0): string { + if (typeof v === "number" && Number.isFinite(v) && !Number.isSafeInteger(v) && Number(v.toPrecision(15)) !== v) { + ctx.addIssue({ code: "custom", message: "Decimal number cannot be read exactly as a JSON number; send it as a string" }); + return z.NEVER; + } + const text = typeof v === "number" ? (Number.isFinite(v) ? String(v) : "") : v; + const m = /^(-?)(0|[1-9][0-9]*)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/.exec(text); + const e = m === null || m[4] === undefined ? 0 : Number(m[4]); + if (m === null || !Number.isSafeInteger(e) || Math.abs(e) > 1000) { + ctx.addIssue({ code: "custom", message: "Not a decimal number" }); + return z.NEVER; + } + const whole = m[2] ?? ""; + let digits = whole + (m[3] ?? ""); + let point = whole.length + e; + const lead = digits.length - digits.replace(/^0+/, "").length; + digits = digits.slice(lead).replace(/0+$/, ""); + point -= lead; + if (digits.length === 0) { + return "0"; + } + const plain = point <= 0 + ? `0.${"0".repeat(-point)}${digits}` + : point >= digits.length + ? digits + "0".repeat(point - digits.length) + : `${digits.slice(0, point)}.${digits.slice(point)}`; + const fraction = point >= digits.length ? 0 : digits.length - Math.max(point, 0) + Math.max(-point, 0); + const integer = Math.max(point, 0); + if (plain.length > 1000 || (precision !== undefined && (fraction > scale || integer > precision - scale))) { + ctx.addIssue({ code: "custom", message: "Decimal out of range for the column" }); + return z.NEVER; + } + return m[1] === "-" ? `-${plain}` : plain; +} + +export const MeasurementInsertSchema = z.object({ + tempC: z.number(), + massKg: z.number(), + preciseKg: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 9, 4)), +}); + +export const MeasurementUpdateSchema = z.object({ + tempC: z.number().optional(), + massKg: z.number().optional(), + preciseKg: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 9, 4)).optional(), +}); + +/** + * Typed create shape for Measurement: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createMeasurement` call site; + * the schema still validates at runtime. + */ +export type MeasurementCreate = z.input; + +/** + * Typed patch shape for Measurement: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateMeasurement` call site. + */ +export type MeasurementPatch = z.input; + +/** + * Metadata constants for Measurement. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Measurement, MeasurementInsertSchema); + * + */ +export const Measurement = { + $entity: "Measurement", + $table: "measurements", + $path: "/measurements", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + tempC: { + name: "tempC", + label: "Temp C", + view: "number", + htmlType: "number", + step: "any", + rules: { required: "Temp C is required" }, + }, + massKg: { + name: "massKg", + label: "Mass Kg", + view: "number", + htmlType: "number", + step: "any", + rules: { required: "Mass Kg is required" }, + }, + preciseKg: { + name: "preciseKg", + label: "Precise Kg", + view: "number", + htmlType: "text", + inputMode: "decimal", + rules: { required: "Precise Kg is required" }, + }, +} as const; + +export type MeasurementFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: MeasurementFilter[]; + and?: MeasurementFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.names.ts new file mode 100644 index 0000000000..0243315d28 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.names.ts @@ -0,0 +1,24 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: MeasurementStats + +export const MeasurementStatsNames = { + type: "object", + subType: "report", + name: "MeasurementStats", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_measurement_stats" }, + }, + fields: { + avgMassKg: { name: "avgMassKg", column: "avg_mass_kg" }, + avgPreciseKg: { name: "avgPreciseKg", column: "avg_precise_kg" }, + heavyReadings: { name: "heavyReadings", column: "heavy_readings" }, + maxPreciseKg: { name: "maxPreciseKg", column: "max_precise_kg" }, + maxTempC: { name: "maxTempC", column: "max_temp_c" }, + minTempC: { name: "minTempC", column: "min_temp_c" }, + readings: { name: "readings", column: "readings" }, + totalMassKg: { name: "totalMassKg", column: "total_mass_kg" }, + totalPreciseKg: { name: "totalPreciseKg", column: "total_precise_kg" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.queries.ts new file mode 100644 index 0000000000..40a3c32447 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: MeasurementStats (MeasurementStats) — report (read-only) +// Extend in your own module (e.g. MeasurementStats.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type MeasurementStats, measurementStatsView } from "./MeasurementStats.js"; + +type Db = PgDatabase>; + +export async function listMeasurementStats(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(measurementStatsView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.ts new file mode 100644 index 0000000000..247e2aa778 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.ts @@ -0,0 +1,66 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: MeasurementStats (MeasurementStats) + +import { bigint, doublePrecision, numeric, pgView, real } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const measurementStatsView = pgView("v_measurement_stats", { + readings: bigint("readings", { mode: "number" }).notNull(), + totalMassKg: doublePrecision("total_mass_kg"), + avgMassKg: doublePrecision("avg_mass_kg"), + maxTempC: real("max_temp_c"), + minTempC: real("min_temp_c"), + totalPreciseKg: numeric("total_precise_kg", { precision: 19, scale: 4 }), + avgPreciseKg: numeric("avg_precise_kg", { precision: 19, scale: 4 }), + maxPreciseKg: numeric("max_precise_kg", { precision: 9, scale: 4 }), + heavyReadings: bigint("heavy_readings", { mode: "number" }).notNull(), +}).existing(); + +export const MeasurementStatsSchema = z.object({ + readings: z.number().int(), + totalMassKg: z.number().nullable(), + avgMassKg: z.number().nullable(), + maxTempC: z.number().nullable(), + minTempC: z.number().nullable(), + totalPreciseKg: z.string().nullable(), + avgPreciseKg: z.string().nullable(), + maxPreciseKg: z.string().nullable(), + heavyReadings: z.number().int(), +}); + +export type MeasurementStats = z.infer; + +export const MeasurementStats = { + $entity: "MeasurementStats", + $view: "v_measurement_stats", + $path: "/measurement_stats", + readings: { name: "readings", label: "Readings", view: "number", dbCol: "readings" }, + totalMassKg: { name: "totalMassKg", label: "Total Mass Kg", view: "number", dbCol: "total_mass_kg" }, + avgMassKg: { name: "avgMassKg", label: "Avg Mass Kg", view: "number", dbCol: "avg_mass_kg" }, + maxTempC: { name: "maxTempC", label: "Max Temp C", view: "number", dbCol: "max_temp_c" }, + minTempC: { name: "minTempC", label: "Min Temp C", view: "number", dbCol: "min_temp_c" }, + totalPreciseKg: { name: "totalPreciseKg", label: "Total Precise Kg", view: "number", dbCol: "total_precise_kg" }, + avgPreciseKg: { name: "avgPreciseKg", label: "Avg Precise Kg", view: "number", dbCol: "avg_precise_kg" }, + maxPreciseKg: { name: "maxPreciseKg", label: "Max Precise Kg", view: "number", dbCol: "max_precise_kg" }, + heavyReadings: { name: "heavyReadings", label: "Heavy Readings", view: "number", dbCol: "heavy_readings" }, +} as const; + +export type MeasurementStatsFilter = { + limit?: number; + offset?: number; + sort?: `${"readings" | "totalMassKg" | "avgMassKg" | "maxTempC" | "minTempC" | "totalPreciseKg" | "avgPreciseKg" | "maxPreciseKg" | "heavyReadings"}:${"asc" | "desc"}` | "readings" | "totalMassKg" | "avgMassKg" | "maxTempC" | "minTempC" | "totalPreciseKg" | "avgPreciseKg" | "maxPreciseKg" | "heavyReadings"; + readings?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + totalMassKg?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + avgMassKg?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + maxTempC?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + minTempC?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + totalPreciseKg?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + avgPreciseKg?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + maxPreciseKg?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + heavyReadings?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: MeasurementStatsFilter[]; + and?: MeasurementStatsFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.names.ts new file mode 100644 index 0000000000..4ba14cc02c --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.names.ts @@ -0,0 +1,18 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: MeasurementStatsFilled + +export const MeasurementStatsFilledNames = { + type: "object", + subType: "report", + name: "MeasurementStatsFilled", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_measurement_stats_filled" }, + }, + fields: { + avgPreciseKgOrMinusOne: { name: "avgPreciseKgOrMinusOne", column: "avg_precise_kg_or_minus_one" }, + maxPreciseKgOrZero: { name: "maxPreciseKgOrZero", column: "max_precise_kg_or_zero" }, + readings: { name: "readings", column: "readings" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.queries.ts new file mode 100644 index 0000000000..afbc518d35 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: MeasurementStatsFilled (MeasurementStatsFilled) — report (read-only) +// Extend in your own module (e.g. MeasurementStatsFilled.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type MeasurementStatsFilled, measurementStatsFilledView } from "./MeasurementStatsFilled.js"; + +type Db = PgDatabase>; + +export async function listMeasurementStatsFilleds(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(measurementStatsFilledView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.ts new file mode 100644 index 0000000000..ba7e616ce3 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.ts @@ -0,0 +1,42 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: MeasurementStatsFilled (MeasurementStatsFilled) + +import { bigint, numeric, pgView } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const measurementStatsFilledView = pgView("v_measurement_stats_filled", { + readings: bigint("readings", { mode: "number" }).notNull(), + avgPreciseKgOrMinusOne: numeric("avg_precise_kg_or_minus_one", { precision: 19, scale: 4 }).notNull(), + maxPreciseKgOrZero: numeric("max_precise_kg_or_zero", { precision: 9, scale: 4 }).notNull(), +}).existing(); + +export const MeasurementStatsFilledSchema = z.object({ + readings: z.number().int(), + avgPreciseKgOrMinusOne: z.string(), + maxPreciseKgOrZero: z.string(), +}); + +export type MeasurementStatsFilled = z.infer; + +export const MeasurementStatsFilled = { + $entity: "MeasurementStatsFilled", + $view: "v_measurement_stats_filled", + $path: "/measurement_stats_filleds", + readings: { name: "readings", label: "Readings", view: "number", dbCol: "readings" }, + avgPreciseKgOrMinusOne: { name: "avgPreciseKgOrMinusOne", label: "Avg Precise Kg Or Minus One", view: "number", dbCol: "avg_precise_kg_or_minus_one" }, + maxPreciseKgOrZero: { name: "maxPreciseKgOrZero", label: "Max Precise Kg Or Zero", view: "number", dbCol: "max_precise_kg_or_zero" }, +} as const; + +export type MeasurementStatsFilledFilter = { + limit?: number; + offset?: number; + sort?: `${"readings" | "avgPreciseKgOrMinusOne" | "maxPreciseKgOrZero"}:${"asc" | "desc"}` | "readings" | "avgPreciseKgOrMinusOne" | "maxPreciseKgOrZero"; + readings?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + avgPreciseKgOrMinusOne?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + maxPreciseKgOrZero?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + or?: MeasurementStatsFilledFilter[]; + and?: MeasurementStatsFilledFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.names.ts new file mode 100644 index 0000000000..8d8d7779d0 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.names.ts @@ -0,0 +1,21 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Node + +export const NodeNames = { + type: "object", + subType: "entity", + name: "Node", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "nodes" }, + }, + fields: { + id: { name: "id", column: "id" }, + label: { name: "label", column: "label" }, + parentId: { name: "parentId", column: "parent_id" }, + }, + identities: { + fkParent: { type: "identity", subType: "reference", name: "fkParent" }, + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.queries.ts new file mode 100644 index 0000000000..a431a58f6e --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.queries.ts @@ -0,0 +1,61 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Node (Node) +// Extend in your own module (e.g. Node.extra.ts) — nothing imports it for you. + +import { eq, inArray } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { type Node, NodeInsertSchema, type NodePatch, NodeUpdateSchema, nodes } from "./Node.js"; + +type Db = PgDatabase>; + +export async function findNodeById(db: Db, id: number): Promise { + const [node] = await db.select().from(nodes).where(eq(nodes.id, id)).limit(1); + return node ?? null; +} + +export async function listNodes(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(nodes).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createNode(db: Db, data: z.input): Promise { + const validated = NodeInsertSchema.parse(data); + const [node] = await db.insert(nodes).values(validated).returning(); + return node!; +} + +export async function updateNode(db: Db, id: number, patch: NodePatch): Promise { + const validated = NodeUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findNodeById(db, id); + } + const [node] = await db.update(nodes).set(validated).where(eq(nodes.id, id)).returning(); + return node ?? null; +} + +export async function deleteNodeById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(nodes).where(eq(nodes.id, id)).returning(); + return deleted.length > 0; +} + +export async function findNodesByParent(db: Db, parentId: number): Promise { + return db.select().from(nodes).where(eq(nodes.parentId, parentId)); +} + +export async function findNodesByParentIn(db: Db, parentIds: number[]): Promise { + if (parentIds.length === 0) { + return []; + } + return db.select().from(nodes).where(inArray(nodes.parentId, parentIds)); +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.ts new file mode 100644 index 0000000000..1a6317c444 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.ts @@ -0,0 +1,95 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Node (Node) +// Extend in your own module (e.g. Node.extra.ts) — nothing imports it for you. + +import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; +import { type AnyPgColumn, bigint, pgTable, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +export const nodes = pgTable("nodes", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + label: varchar("label", { length: 80 }).notNull(), + parentId: bigint("parent_id", { mode: "number" }).references((): AnyPgColumn => nodes.id), +}); + +export type Node = InferSelectModel; +export type NodeInsert = InferInsertModel; +export type NodeUpdate = Partial; + +export const NodeInsertSchema = z.object({ + label: z.string().min(1).max(80), + parentId: z.number().int().optional(), +}); + +export const NodeUpdateSchema = z.object({ + label: z.string().min(1).max(80).optional(), + parentId: z.number().int().optional().nullable(), +}); + +/** + * Typed create shape for Node: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createNode` call site; + * the schema still validates at runtime. + */ +export type NodeCreate = z.input; + +/** + * Typed patch shape for Node: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateNode` call site. + */ +export type NodePatch = z.input; + +/** + * Metadata constants for Node. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Node, NodeInsertSchema); + * + */ +export const Node = { + $entity: "Node", + $table: "nodes", + $path: "/nodes", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + label: { + name: "label", + label: "Label", + view: "text", + htmlType: "text", + rules: { required: "Label is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, + }, + parentId: { + name: "parentId", + label: "Parent Id", + view: "number", + htmlType: "number", + }, +} as const; + +export type NodeFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: NodeFilter[]; + and?: NodeFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.names.ts new file mode 100644 index 0000000000..93d1ee8ba3 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.names.ts @@ -0,0 +1,17 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: NodesByParent + +export const NodesByParentNames = { + type: "object", + subType: "report", + name: "NodesByParent", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_nodes_by_parent" }, + }, + fields: { + nodes: { name: "nodes", column: "nodes" }, + parentLabel: { name: "parentLabel", column: "parent_label" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.queries.ts new file mode 100644 index 0000000000..f5596b3fad --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: NodesByParent (NodesByParent) — report (read-only) +// Extend in your own module (e.g. NodesByParent.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type NodesByParent, nodesByParentView } from "./NodesByParent.js"; + +type Db = PgDatabase>; + +export async function listNodesByParents(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(nodesByParentView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.ts new file mode 100644 index 0000000000..2fbf0e9a6e --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.ts @@ -0,0 +1,38 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: NodesByParent (NodesByParent) + +import { bigint, pgView, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const nodesByParentView = pgView("v_nodes_by_parent", { + parentLabel: varchar("parent_label", { length: 80 }), + nodes: bigint("nodes", { mode: "number" }).notNull(), +}).existing(); + +export const NodesByParentSchema = z.object({ + parentLabel: z.string().nullable(), + nodes: z.number().int(), +}); + +export type NodesByParent = z.infer; + +export const NodesByParent = { + $entity: "NodesByParent", + $view: "v_nodes_by_parent", + $path: "/nodes_by_parents", + parentLabel: { name: "parentLabel", label: "Parent Label", view: "text", dbCol: "parent_label" }, + nodes: { name: "nodes", label: "Nodes", view: "number", dbCol: "nodes" }, +} as const; + +export type NodesByParentFilter = { + limit?: number; + offset?: number; + sort?: `${"parentLabel" | "nodes"}:${"asc" | "desc"}` | "parentLabel" | "nodes"; + parentLabel?: string | { eq?: string; ne?: string; in?: string[]; like?: string; isNull?: boolean }; + nodes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: NodesByParentFilter[]; + and?: NodesByParentFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.names.ts new file mode 100644 index 0000000000..97302c7aa0 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.names.ts @@ -0,0 +1,23 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: PermitAuth + +import { AuthNames } from "./Auth.names.js"; + +export const PermitAuthNames = { + type: "object", + subType: "entity", + name: "PermitAuth", + sources: { + ...AuthNames.sources, + }, + fields: { + ...AuthNames.fields, + approver: { name: "approver", column: "approver" }, + }, + identities: { + ...AuthNames.identities, + }, + indexes: { + ...AuthNames.indexes, + }, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.ts new file mode 100644 index 0000000000..11954c4bdc --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.ts @@ -0,0 +1,113 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: PermitAuth (PermitAuth) +// Extend in your own module (e.g. PermitAuth.extra.ts) — nothing imports it for you. + +import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; +import { z } from "zod"; + +export interface PermitAuth { + id?: number | undefined; + type?: PermitAuthType | null | undefined; + reference: string; + approver?: string | null | undefined; +} + +export type PermitAuthType = "Bridge" | "Coupon" | "Permit" | "Referral"; +export const PermitAuthTypeEnum = z.enum(["Bridge", "Coupon", "Permit", "Referral"]); + +export const PermitAuthSchema = z.object({ + id: z.number().int(), + type: z.literal("Permit"), + reference: z.string().min(1).max(80), + approver: z.string().max(80).nullable(), +}); + +export const PermitAuthInsertSchema = z.object({ + type: z.literal("Permit"), + reference: z.string().min(1).max(80), + approver: z.string().max(80).optional(), +}); + +export const PermitAuthUpdateSchema = z.object({ + reference: z.string().min(1).max(80).optional(), + approver: z.string().max(80).optional().nullable(), +}); + +/** + * Typed create shape for PermitAuth: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createPermitAuth` call site; + * the schema still validates at runtime. + */ +export type PermitAuthCreate = z.input; + +/** + * Typed patch shape for PermitAuth: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updatePermitAuth` call site. + */ +export type PermitAuthPatch = z.input; + +/** + * Metadata constants for PermitAuth. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(PermitAuth, PermitAuthInsertSchema); + * + */ +export const PermitAuth = { + $entity: "PermitAuth", + $table: "auths", + $path: "/auths/permit", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + type: { + name: "type", + label: "Type", + view: "dropdown", + options: ["Bridge", "Coupon", "Permit", "Referral"] as const, + }, + reference: { + name: "reference", + label: "Reference", + view: "text", + htmlType: "text", + rules: { required: "Reference is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, + }, + approver: { + name: "approver", + label: "Approver", + view: "text", + htmlType: "text", + rules: { maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, + }, +} as const; + +export const PermitAuthFilterAllowlist = {} as const satisfies FilterAllowlist; + +export const PermitAuthSortAllowlist = {} as const satisfies SortAllowlist; + +export type PermitAuthFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: PermitAuthFilter[]; + and?: PermitAuthFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.names.ts new file mode 100644 index 0000000000..138ab13434 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.names.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Person + +export const PersonNames = { + type: "object", + subType: "entity", + name: "Person", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "people" }, + }, + fields: { + id: { name: "id", column: "id" }, + name: { name: "name", column: "name" }, + }, + identities: { + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.queries.ts new file mode 100644 index 0000000000..c7560e9dc0 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.queries.ts @@ -0,0 +1,50 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Person (Person) +// Extend in your own module (e.g. Person.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { type Person, PersonInsertSchema, type PersonPatch, PersonUpdateSchema, persons } from "./Person.js"; + +type Db = PgDatabase>; + +export async function findPersonById(db: Db, id: number): Promise { + const [person] = await db.select().from(persons).where(eq(persons.id, id)).limit(1); + return person ?? null; +} + +export async function listPersons(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(persons).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createPerson(db: Db, data: z.input): Promise { + const validated = PersonInsertSchema.parse(data); + const [person] = await db.insert(persons).values(validated).returning(); + return person!; +} + +export async function updatePerson(db: Db, id: number, patch: PersonPatch): Promise { + const validated = PersonUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findPersonById(db, id); + } + const [person] = await db.update(persons).set(validated).where(eq(persons.id, id)).returning(); + return person ?? null; +} + +export async function deletePersonById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(persons).where(eq(persons.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.ts new file mode 100644 index 0000000000..8620411a71 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.ts @@ -0,0 +1,93 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Person (Person) +// Extend in your own module (e.g. Person.extra.ts) — nothing imports it for you. + +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { bigint, pgTable, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; +import { follows } from "./Follow.js"; +import { friendships } from "./Friendship.js"; + +export const persons = pgTable("people", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + name: varchar("name", { length: 80 }).notNull(), +}); + +export const personsRelations = relations(persons, ({ many }) => ({ + following: many(follows), + friends: many(friendships), +})); + +export type Person = InferSelectModel; +export type PersonInsert = InferInsertModel; +export type PersonUpdate = Partial; + +export const PersonInsertSchema = z.object({ + name: z.string().min(1).max(80), +}); + +export const PersonUpdateSchema = z.object({ + name: z.string().min(1).max(80).optional(), +}); + +/** + * Typed create shape for Person: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createPerson` call site; + * the schema still validates at runtime. + */ +export type PersonCreate = z.input; + +/** + * Typed patch shape for Person: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updatePerson` call site. + */ +export type PersonPatch = z.input; + +/** + * Metadata constants for Person. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Person, PersonInsertSchema); + * + */ +export const Person = { + $entity: "Person", + $table: "people", + $path: "/persons", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + name: { + name: "name", + label: "Name", + view: "text", + htmlType: "text", + rules: { required: "Name is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, + }, +} as const; + +export type PersonFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: PersonFilter[]; + and?: PersonFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.names.ts new file mode 100644 index 0000000000..b84c96f3eb --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.names.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Post + +export const PostNames = { + type: "object", + subType: "entity", + name: "Post", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "posts" }, + }, + fields: { + id: { name: "id", column: "id" }, + title: { name: "title", column: "title" }, + }, + identities: { + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.queries.ts new file mode 100644 index 0000000000..768993bbca --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.queries.ts @@ -0,0 +1,50 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Post (Post) +// Extend in your own module (e.g. Post.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { type Post, PostInsertSchema, type PostPatch, PostUpdateSchema, posts } from "./Post.js"; + +type Db = PgDatabase>; + +export async function findPostById(db: Db, id: number): Promise { + const [post] = await db.select().from(posts).where(eq(posts.id, id)).limit(1); + return post ?? null; +} + +export async function listPosts(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(posts).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createPost(db: Db, data: z.input): Promise { + const validated = PostInsertSchema.parse(data); + const [post] = await db.insert(posts).values(validated).returning(); + return post!; +} + +export async function updatePost(db: Db, id: number, patch: PostPatch): Promise { + const validated = PostUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findPostById(db, id); + } + const [post] = await db.update(posts).set(validated).where(eq(posts.id, id)).returning(); + return post ?? null; +} + +export async function deletePostById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(posts).where(eq(posts.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.ts new file mode 100644 index 0000000000..3248b4557e --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.ts @@ -0,0 +1,93 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Post (Post) +// Extend in your own module (e.g. Post.extra.ts) — nothing imports it for you. + +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { bigint, pgTable, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; +import { postReferrals } from "./PostReferral.js"; +import { postTags } from "./PostTag.js"; + +export const posts = pgTable("posts", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + title: varchar("title", { length: 200 }).notNull(), +}); + +export const postsRelations = relations(posts, ({ many }) => ({ + tags: many(postTags), + referrals: many(postReferrals), +})); + +export type Post = InferSelectModel; +export type PostInsert = InferInsertModel; +export type PostUpdate = Partial; + +export const PostInsertSchema = z.object({ + title: z.string().min(1).max(200), +}); + +export const PostUpdateSchema = z.object({ + title: z.string().min(1).max(200).optional(), +}); + +/** + * Typed create shape for Post: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createPost` call site; + * the schema still validates at runtime. + */ +export type PostCreate = z.input; + +/** + * Typed patch shape for Post: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updatePost` call site. + */ +export type PostPatch = z.input; + +/** + * Metadata constants for Post. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Post, PostInsertSchema); + * + */ +export const Post = { + $entity: "Post", + $table: "posts", + $path: "/posts", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + title: { + name: "title", + label: "Title", + view: "text", + htmlType: "text", + rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, + }, +} as const; + +export type PostFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: PostFilter[]; + and?: PostFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.names.ts new file mode 100644 index 0000000000..cb4d68b72b --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.names.ts @@ -0,0 +1,21 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: PostReferral + +export const PostReferralNames = { + type: "object", + subType: "entity", + name: "PostReferral", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "post_referrals" }, + }, + fields: { + postId: { name: "postId", column: "post_id" }, + referralId: { name: "referralId", column: "referral_id" }, + }, + identities: { + fkPost: { type: "identity", subType: "reference", name: "fkPost" }, + fkReferral: { type: "identity", subType: "reference", name: "fkReferral" }, + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.queries.ts new file mode 100644 index 0000000000..e29690bf2b --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.queries.ts @@ -0,0 +1,78 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: PostReferral (PostReferral) +// Extend in your own module (e.g. PostReferral.extra.ts) — nothing imports it for you. + +import { eq, inArray } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { + type PostReferral, + PostReferralInsertSchema, + type PostReferralPatch, + PostReferralUpdateSchema, + postReferrals, +} from "./PostReferral.js"; + +type Db = PgDatabase>; + +export async function findPostReferralById(db: Db, postId: number): Promise { + const [postReferral] = await db.select().from(postReferrals).where(eq(postReferrals.postId, postId)).limit(1); + return postReferral ?? null; +} + +export async function listPostReferrals(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(postReferrals).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createPostReferral(db: Db, data: z.input): Promise { + const validated = PostReferralInsertSchema.parse(data); + const [postReferral] = await db.insert(postReferrals).values(validated).returning(); + return postReferral!; +} + +export async function updatePostReferral(db: Db, postId: number, patch: PostReferralPatch): Promise { + const validated = PostReferralUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findPostReferralById(db, postId); + } + const [postReferral] = await db.update(postReferrals).set(validated).where(eq(postReferrals.postId, postId)).returning(); + return postReferral ?? null; +} + +export async function deletePostReferralById(db: Db, postId: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(postReferrals).where(eq(postReferrals.postId, postId)).returning(); + return deleted.length > 0; +} + +export async function findPostReferralsByPost(db: Db, postId: number): Promise { + return db.select().from(postReferrals).where(eq(postReferrals.postId, postId)); +} + +export async function findPostReferralsByPostIn(db: Db, postIds: number[]): Promise { + if (postIds.length === 0) { + return []; + } + return db.select().from(postReferrals).where(inArray(postReferrals.postId, postIds)); +} + +export async function findPostReferralsByReferral(db: Db, referralId: number): Promise { + return db.select().from(postReferrals).where(eq(postReferrals.referralId, referralId)); +} + +export async function findPostReferralsByReferralIn(db: Db, referralIds: number[]): Promise { + if (referralIds.length === 0) { + return []; + } + return db.select().from(postReferrals).where(inArray(postReferrals.referralId, referralIds)); +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.ts new file mode 100644 index 0000000000..5fc57699fa --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.ts @@ -0,0 +1,93 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: PostReferral (PostReferral) +// Extend in your own module (e.g. PostReferral.extra.ts) — nothing imports it for you. + +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { bigint, pgTable, primaryKey } from "drizzle-orm/pg-core"; +import { z } from "zod"; +import { auths } from "./Auth.js"; +import { posts } from "./Post.js"; + +export const postReferrals = pgTable("post_referrals", { + postId: bigint("post_id", { mode: "number" }).notNull(), + referralId: bigint("referral_id", { mode: "number" }).notNull(), +}, (table) => [primaryKey({ columns: [table.postId, table.referralId] })]); + +export const postReferralsRelations = relations(postReferrals, ({ one }) => ({ + fkPost: one(posts, { fields: [postReferrals.postId], references: [posts.id] }), + fkReferral: one(auths, { fields: [postReferrals.referralId], references: [auths.id] }), +})); + +export type PostReferral = InferSelectModel; +export type PostReferralInsert = InferInsertModel; +export type PostReferralUpdate = Partial; + +export const PostReferralInsertSchema = z.object({ + postId: z.number().int(), + referralId: z.number().int(), +}); + +export const PostReferralUpdateSchema = z.object({}); + +/** + * Typed create shape for PostReferral: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createPostReferral` call site; + * the schema still validates at runtime. + */ +export type PostReferralCreate = z.input; + +/** + * Typed patch shape for PostReferral: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updatePostReferral` call site. + */ +export type PostReferralPatch = z.input; + +/** + * Metadata constants for PostReferral. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(PostReferral, PostReferralInsertSchema); + * + */ +export const PostReferral = { + $entity: "PostReferral", + $table: "post_referrals", + $path: "/post_referrals", + postId: { + name: "postId", + label: "Post Id", + view: "number", + htmlType: "number", + rules: { required: "Post Id is required" }, + }, + referralId: { + name: "referralId", + label: "Referral Id", + view: "number", + htmlType: "number", + rules: { required: "Referral Id is required" }, + }, +} as const; + +export type PostReferralFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: PostReferralFilter[]; + and?: PostReferralFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.names.ts new file mode 100644 index 0000000000..fc30da83a2 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.names.ts @@ -0,0 +1,21 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: PostTag + +export const PostTagNames = { + type: "object", + subType: "entity", + name: "PostTag", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "post_tags" }, + }, + fields: { + postId: { name: "postId", column: "post_id" }, + tagId: { name: "tagId", column: "tag_id" }, + }, + identities: { + fkPost: { type: "identity", subType: "reference", name: "fkPost" }, + fkTag: { type: "identity", subType: "reference", name: "fkTag" }, + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.queries.ts new file mode 100644 index 0000000000..21d7bd1ece --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.queries.ts @@ -0,0 +1,72 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: PostTag (PostTag) +// Extend in your own module (e.g. PostTag.extra.ts) — nothing imports it for you. + +import { eq, inArray } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { type PostTag, PostTagInsertSchema, type PostTagPatch, PostTagUpdateSchema, postTags } from "./PostTag.js"; + +type Db = PgDatabase>; + +export async function findPostTagById(db: Db, postId: number): Promise { + const [postTag] = await db.select().from(postTags).where(eq(postTags.postId, postId)).limit(1); + return postTag ?? null; +} + +export async function listPostTags(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(postTags).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createPostTag(db: Db, data: z.input): Promise { + const validated = PostTagInsertSchema.parse(data); + const [postTag] = await db.insert(postTags).values(validated).returning(); + return postTag!; +} + +export async function updatePostTag(db: Db, postId: number, patch: PostTagPatch): Promise { + const validated = PostTagUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findPostTagById(db, postId); + } + const [postTag] = await db.update(postTags).set(validated).where(eq(postTags.postId, postId)).returning(); + return postTag ?? null; +} + +export async function deletePostTagById(db: Db, postId: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(postTags).where(eq(postTags.postId, postId)).returning(); + return deleted.length > 0; +} + +export async function findPostTagsByPost(db: Db, postId: number): Promise { + return db.select().from(postTags).where(eq(postTags.postId, postId)); +} + +export async function findPostTagsByPostIn(db: Db, postIds: number[]): Promise { + if (postIds.length === 0) { + return []; + } + return db.select().from(postTags).where(inArray(postTags.postId, postIds)); +} + +export async function findPostTagsByTag(db: Db, tagId: number): Promise { + return db.select().from(postTags).where(eq(postTags.tagId, tagId)); +} + +export async function findPostTagsByTagIn(db: Db, tagIds: number[]): Promise { + if (tagIds.length === 0) { + return []; + } + return db.select().from(postTags).where(inArray(postTags.tagId, tagIds)); +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.ts new file mode 100644 index 0000000000..0838e0bff3 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.ts @@ -0,0 +1,93 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: PostTag (PostTag) +// Extend in your own module (e.g. PostTag.extra.ts) — nothing imports it for you. + +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { bigint, pgTable, primaryKey } from "drizzle-orm/pg-core"; +import { z } from "zod"; +import { posts } from "./Post.js"; +import { tags } from "./Tag.js"; + +export const postTags = pgTable("post_tags", { + postId: bigint("post_id", { mode: "number" }).notNull(), + tagId: bigint("tag_id", { mode: "number" }).notNull(), +}, (table) => [primaryKey({ columns: [table.postId, table.tagId] })]); + +export const postTagsRelations = relations(postTags, ({ one }) => ({ + fkPost: one(posts, { fields: [postTags.postId], references: [posts.id] }), + fkTag: one(tags, { fields: [postTags.tagId], references: [tags.id] }), +})); + +export type PostTag = InferSelectModel; +export type PostTagInsert = InferInsertModel; +export type PostTagUpdate = Partial; + +export const PostTagInsertSchema = z.object({ + postId: z.number().int(), + tagId: z.number().int(), +}); + +export const PostTagUpdateSchema = z.object({}); + +/** + * Typed create shape for PostTag: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createPostTag` call site; + * the schema still validates at runtime. + */ +export type PostTagCreate = z.input; + +/** + * Typed patch shape for PostTag: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updatePostTag` call site. + */ +export type PostTagPatch = z.input; + +/** + * Metadata constants for PostTag. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(PostTag, PostTagInsertSchema); + * + */ +export const PostTag = { + $entity: "PostTag", + $table: "post_tags", + $path: "/post_tags", + postId: { + name: "postId", + label: "Post Id", + view: "number", + htmlType: "number", + rules: { required: "Post Id is required" }, + }, + tagId: { + name: "tagId", + label: "Tag Id", + view: "number", + htmlType: "number", + rules: { required: "Tag Id is required" }, + }, +} as const; + +export type PostTagFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: PostTagFilter[]; + and?: PostTagFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.names.ts new file mode 100644 index 0000000000..61dec41559 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.names.ts @@ -0,0 +1,25 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Program + +export const ProgramNames = { + type: "object", + subType: "entity", + name: "Program", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "programs" }, + }, + fields: { + createdAt: { name: "createdAt", column: "created_ts" }, + id: { name: "id", column: "id" }, + priceCents: { name: "priceCents", column: "price_cents" }, + status: { name: "status", column: "status" }, + title: { name: "title", column: "title" }, + }, + identities: { + byTitle: { type: "identity", subType: "secondary", name: "byTitle", index: "byTitle" }, + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: { + idx_programs_title_status: { type: "index", subType: "lookup", name: "idx_programs_title_status", index: "idx_programs_title_status" }, + }, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.queries.ts new file mode 100644 index 0000000000..b32fcbda13 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.queries.ts @@ -0,0 +1,50 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Program (Program) +// Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { type Program, ProgramInsertSchema, type ProgramPatch, ProgramUpdateSchema, programs } from "./Program.js"; + +type Db = PgDatabase>; + +export async function findProgramById(db: Db, id: number): Promise { + const [program] = await db.select().from(programs).where(eq(programs.id, id)).limit(1); + return program ?? null; +} + +export async function listPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(programs).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createProgram(db: Db, data: z.input): Promise { + const validated = ProgramInsertSchema.parse(data); + const [program] = await db.insert(programs).values(validated).returning(); + return program!; +} + +export async function updateProgram(db: Db, id: number, patch: ProgramPatch): Promise { + const validated = ProgramUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findProgramById(db, id); + } + const [program] = await db.update(programs).set(validated).where(eq(programs.id, id)).returning(); + return program ?? null; +} + +export async function deleteProgramById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(programs).where(eq(programs.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.ts new file mode 100644 index 0000000000..f616babddb --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.ts @@ -0,0 +1,124 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Program (Program) +// Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you. + +import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; +import { bigint, check, index, pgTable, text, timestamp, uniqueIndex, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +export const programs = pgTable("programs", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + title: varchar("title", { length: 200 }).notNull(), + priceCents: bigint("price_cents", { mode: "number" }).notNull(), + status: text("status", { enum: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const }).notNull(), + createdAt: timestamp("created_ts", { mode: "string", withTimezone: false }).notNull(), +}, (table) => [ + uniqueIndex("byTitle").on(table.title), + index("idx_programs_title_status").on(table.title, table.status), + check("programs_status_chk", sql`status IN ('DRAFT', 'PUBLISHED', 'ARCHIVED')`), +]); + +export type Program = InferSelectModel; +export type ProgramInsert = InferInsertModel; +export type ProgramUpdate = Partial; + +export type ProgramStatus = "DRAFT" | "PUBLISHED" | "ARCHIVED"; +export const ProgramStatusEnum = z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]); + +export const ProgramInsertSchema = z.object({ + title: z.string().min(1).max(200), + priceCents: z.number().int(), + status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]), + createdAt: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])"), +}); + +export const ProgramUpdateSchema = z.object({ + title: z.string().min(1).max(200).optional(), + priceCents: z.number().int().optional(), + status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]).optional(), + createdAt: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])").optional(), +}); + +/** + * Typed create shape for Program: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createProgram` call site; + * the schema still validates at runtime. + */ +export type ProgramCreate = z.input; + +/** + * Typed patch shape for Program: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateProgram` call site. + */ +export type ProgramPatch = z.input; + +/** + * Metadata constants for Program. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Program, ProgramInsertSchema); + * + */ +export const Program = { + $entity: "Program", + $table: "programs", + $path: "/programs", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + title: { + name: "title", + label: "Title", + view: "text", + htmlType: "text", + rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, + }, + priceCents: { + name: "priceCents", + label: "Price Cents", + view: "currency", + rules: { required: "Price Cents is required" }, + currency: "USD", + locale: "en-US", + }, + status: { + name: "status", + label: "Status", + view: "dropdown", + rules: { required: "Status is required" }, + options: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const, + }, + createdAt: { + name: "createdAt", + label: "Created At", + view: "date", + htmlType: "datetime-local", + rules: { required: "Created At is required" }, + }, +} as const; + +export type ProgramFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: ProgramFilter[]; + and?: ProgramFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramBrief.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramBrief.ts new file mode 100644 index 0000000000..533fdcbfa5 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramBrief.ts @@ -0,0 +1,45 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramBrief (ProgramBrief) +// Extend in your own module (e.g. ProgramBrief.extra.ts) — nothing imports it for you. + +import { z } from "zod"; +import { type WeekLabel, WeekLabelInsertSchema } from "./WeekLabel.js"; + +export interface ProgramBrief { + title: string; + weekCount?: number | undefined; + weekLabels?: WeekLabel[] | undefined; +} + +export const ProgramBriefInsertSchema = z.object({ + title: z.string().min(1).max(200), + weekCount: z.number().int().optional(), + weekLabels: z.array(WeekLabelInsertSchema).optional(), +}); + +/** + * Metadata constants for the value object ProgramBrief: each field's name, label, view and the + * validation rules derived from its validator children (e.g. `ProgramBrief..rules.maxLength.value`). + */ +export const ProgramBrief = { + $entity: "ProgramBrief", + title: { + name: "title", + label: "Title", + view: "text", + htmlType: "text", + rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, + }, + weekCount: { + name: "weekCount", + label: "Week Count", + view: "number", + htmlType: "number", + }, + weekLabels: { + name: "weekLabels", + label: "Week Labels", + view: "text", + htmlType: "text", + }, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.names.ts new file mode 100644 index 0000000000..b2a87d8146 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.names.ts @@ -0,0 +1,20 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramFlagRoster + +export const ProgramFlagRosterNames = { + type: "object", + subType: "report", + name: "ProgramFlagRoster", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_program_flag_roster" }, + }, + fields: { + allDeloadOrTrue: { name: "allDeloadOrTrue", column: "all_deload_or_true" }, + anyDeload: { name: "anyDeload", column: "any_deload" }, + anyDeloadOrFalse: { name: "anyDeloadOrFalse", column: "any_deload_or_false" }, + programKey: { name: "programKey", column: "program_key" }, + weeks: { name: "weeks", column: "weeks" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.queries.ts new file mode 100644 index 0000000000..7048403892 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramFlagRoster (ProgramFlagRoster) — report (read-only) +// Extend in your own module (e.g. ProgramFlagRoster.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type ProgramFlagRoster, programFlagRosterView } from "./ProgramFlagRoster.js"; + +type Db = PgDatabase>; + +export async function listProgramFlagRosters(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(programFlagRosterView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.ts new file mode 100644 index 0000000000..9459af4d1b --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.ts @@ -0,0 +1,50 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramFlagRoster (ProgramFlagRoster) + +import { bigint, boolean, pgView } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const programFlagRosterView = pgView("v_program_flag_roster", { + programKey: bigint("program_key", { mode: "number" }).notNull(), + weeks: bigint("weeks", { mode: "number" }).notNull(), + anyDeload: boolean("any_deload"), + anyDeloadOrFalse: boolean("any_deload_or_false").notNull(), + allDeloadOrTrue: boolean("all_deload_or_true").notNull(), +}).existing(); + +export const ProgramFlagRosterSchema = z.object({ + programKey: z.number().int(), + weeks: z.number().int(), + anyDeload: z.boolean().nullable(), + anyDeloadOrFalse: z.boolean(), + allDeloadOrTrue: z.boolean(), +}); + +export type ProgramFlagRoster = z.infer; + +export const ProgramFlagRoster = { + $entity: "ProgramFlagRoster", + $view: "v_program_flag_roster", + $path: "/program_flag_rosters", + programKey: { name: "programKey", label: "Program Key", view: "number", dbCol: "program_key" }, + weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, + anyDeload: { name: "anyDeload", label: "Any Deload", view: "checkbox", dbCol: "any_deload" }, + anyDeloadOrFalse: { name: "anyDeloadOrFalse", label: "Any Deload Or False", view: "checkbox", dbCol: "any_deload_or_false" }, + allDeloadOrTrue: { name: "allDeloadOrTrue", label: "All Deload Or True", view: "checkbox", dbCol: "all_deload_or_true" }, +} as const; + +export type ProgramFlagRosterFilter = { + limit?: number; + offset?: number; + sort?: `${"programKey" | "weeks" | "anyDeload" | "anyDeloadOrFalse" | "allDeloadOrTrue"}:${"asc" | "desc"}` | "programKey" | "weeks" | "anyDeload" | "anyDeloadOrFalse" | "allDeloadOrTrue"; + programKey?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + anyDeload?: boolean | { eq?: boolean; isNull?: boolean }; + anyDeloadOrFalse?: boolean | { eq?: boolean; isNull?: boolean }; + allDeloadOrTrue?: boolean | { eq?: boolean; isNull?: boolean }; + or?: ProgramFlagRosterFilter[]; + and?: ProgramFlagRosterFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.names.ts new file mode 100644 index 0000000000..926963d744 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.names.ts @@ -0,0 +1,20 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramFlags + +export const ProgramFlagsNames = { + type: "object", + subType: "report", + name: "ProgramFlags", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_program_flags" }, + }, + fields: { + allDeload: { name: "allDeload", column: "all_deload" }, + anyDeload: { name: "anyDeload", column: "any_deload" }, + anyLongDeload: { name: "anyLongDeload", column: "any_long_deload" }, + program: { name: "program", column: "program" }, + weeks: { name: "weeks", column: "weeks" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.queries.ts new file mode 100644 index 0000000000..1ad321b9e9 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramFlags (ProgramFlags) — report (read-only) +// Extend in your own module (e.g. ProgramFlags.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type ProgramFlags, programFlagsView } from "./ProgramFlags.js"; + +type Db = PgDatabase>; + +export async function listProgramFlags(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(programFlagsView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.ts new file mode 100644 index 0000000000..d2689d2306 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.ts @@ -0,0 +1,50 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramFlags (ProgramFlags) + +import { bigint, boolean, pgView } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const programFlagsView = pgView("v_program_flags", { + program: bigint("program", { mode: "number" }).notNull(), + weeks: bigint("weeks", { mode: "number" }).notNull(), + anyDeload: boolean("any_deload"), + allDeload: boolean("all_deload"), + anyLongDeload: boolean("any_long_deload"), +}).existing(); + +export const ProgramFlagsSchema = z.object({ + program: z.number().int(), + weeks: z.number().int(), + anyDeload: z.boolean().nullable(), + allDeload: z.boolean().nullable(), + anyLongDeload: z.boolean().nullable(), +}); + +export type ProgramFlags = z.infer; + +export const ProgramFlags = { + $entity: "ProgramFlags", + $view: "v_program_flags", + $path: "/program_flags", + program: { name: "program", label: "Program", view: "number", dbCol: "program" }, + weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, + anyDeload: { name: "anyDeload", label: "Any Deload", view: "checkbox", dbCol: "any_deload" }, + allDeload: { name: "allDeload", label: "All Deload", view: "checkbox", dbCol: "all_deload" }, + anyLongDeload: { name: "anyLongDeload", label: "Any Long Deload", view: "checkbox", dbCol: "any_long_deload" }, +} as const; + +export type ProgramFlagsFilter = { + limit?: number; + offset?: number; + sort?: `${"program" | "weeks" | "anyDeload" | "allDeload" | "anyLongDeload"}:${"asc" | "desc"}` | "program" | "weeks" | "anyDeload" | "allDeload" | "anyLongDeload"; + program?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + anyDeload?: boolean | { eq?: boolean; isNull?: boolean }; + allDeload?: boolean | { eq?: boolean; isNull?: boolean }; + anyLongDeload?: boolean | { eq?: boolean; isNull?: boolean }; + or?: ProgramFlagsFilter[]; + and?: ProgramFlagsFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.names.ts new file mode 100644 index 0000000000..fd33a3e5c5 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.names.ts @@ -0,0 +1,18 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramLongWeeks + +export const ProgramLongWeeksNames = { + type: "object", + subType: "report", + name: "ProgramLongWeeks", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_program_long_weeks" }, + }, + fields: { + programKey: { name: "programKey", column: "program_key" }, + totalMinutesOrZero: { name: "totalMinutesOrZero", column: "total_minutes_or_zero" }, + weeks: { name: "weeks", column: "weeks" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.queries.ts new file mode 100644 index 0000000000..f5ef2a3ec2 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramLongWeeks (ProgramLongWeeks) — report (read-only) +// Extend in your own module (e.g. ProgramLongWeeks.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type ProgramLongWeeks, programLongWeeksView } from "./ProgramLongWeeks.js"; + +type Db = PgDatabase>; + +export async function listProgramLongWeeks(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(programLongWeeksView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.ts new file mode 100644 index 0000000000..03e3caf294 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.ts @@ -0,0 +1,42 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramLongWeeks (ProgramLongWeeks) + +import { bigint, pgView } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const programLongWeeksView = pgView("v_program_long_weeks", { + programKey: bigint("program_key", { mode: "number" }).notNull(), + weeks: bigint("weeks", { mode: "number" }).notNull(), + totalMinutesOrZero: bigint("total_minutes_or_zero", { mode: "number" }).notNull(), +}).existing(); + +export const ProgramLongWeeksSchema = z.object({ + programKey: z.number().int(), + weeks: z.number().int(), + totalMinutesOrZero: z.number().int(), +}); + +export type ProgramLongWeeks = z.infer; + +export const ProgramLongWeeks = { + $entity: "ProgramLongWeeks", + $view: "v_program_long_weeks", + $path: "/program_long_weeks", + programKey: { name: "programKey", label: "Program Key", view: "number", dbCol: "program_key" }, + weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, + totalMinutesOrZero: { name: "totalMinutesOrZero", label: "Total Minutes Or Zero", view: "number", dbCol: "total_minutes_or_zero" }, +} as const; + +export type ProgramLongWeeksFilter = { + limit?: number; + offset?: number; + sort?: `${"programKey" | "weeks" | "totalMinutesOrZero"}:${"asc" | "desc"}` | "programKey" | "weeks" | "totalMinutesOrZero"; + programKey?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + totalMinutesOrZero?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: ProgramLongWeeksFilter[]; + and?: ProgramLongWeeksFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.names.ts new file mode 100644 index 0000000000..53689e016d --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.names.ts @@ -0,0 +1,26 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramMinutes + +export const ProgramMinutesNames = { + type: "object", + subType: "report", + name: "ProgramMinutes", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_program_minutes" }, + }, + fields: { + avgMinutes: { name: "avgMinutes", column: "avg_minutes" }, + labels: { name: "labels", column: "labels" }, + longShare: { name: "longShare", column: "long_share" }, + longWeeks: { name: "longWeeks", column: "long_weeks" }, + maxMinutes: { name: "maxMinutes", column: "max_minutes" }, + minMinutes: { name: "minMinutes", column: "min_minutes" }, + program: { name: "program", column: "program" }, + programTitle: { name: "programTitle", column: "program_title" }, + slots: { name: "slots", column: "slots" }, + totalMinutes: { name: "totalMinutes", column: "total_minutes" }, + weeks: { name: "weeks", column: "weeks" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.queries.ts new file mode 100644 index 0000000000..e275488ade --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramMinutes (ProgramMinutes) — report (read-only) +// Extend in your own module (e.g. ProgramMinutes.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type ProgramMinutes, programMinutesView } from "./ProgramMinutes.js"; + +type Db = PgDatabase>; + +export async function listProgramMinutes(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(programMinutesView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.ts new file mode 100644 index 0000000000..0190230434 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.ts @@ -0,0 +1,74 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramMinutes (ProgramMinutes) + +import { bigint, integer, numeric, pgView, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const programMinutesView = pgView("v_program_minutes", { + program: bigint("program", { mode: "number" }).notNull(), + programTitle: varchar("program_title", { length: 200 }).notNull(), + weeks: bigint("weeks", { mode: "number" }).notNull(), + longWeeks: bigint("long_weeks", { mode: "number" }).notNull(), + labels: bigint("labels", { mode: "number" }).notNull(), + slots: bigint("slots", { mode: "number" }).notNull(), + totalMinutes: bigint("total_minutes", { mode: "number" }), + avgMinutes: numeric("avg_minutes", { precision: 19, scale: 4 }), + minMinutes: integer("min_minutes"), + maxMinutes: integer("max_minutes"), + longShare: numeric("long_share", { precision: 19, scale: 4 }), +}).existing(); + +export const ProgramMinutesSchema = z.object({ + program: z.number().int(), + programTitle: z.string(), + weeks: z.number().int(), + longWeeks: z.number().int(), + labels: z.number().int(), + slots: z.number().int(), + totalMinutes: z.number().int().nullable(), + avgMinutes: z.string().nullable(), + minMinutes: z.number().int().nullable(), + maxMinutes: z.number().int().nullable(), + longShare: z.string().nullable(), +}); + +export type ProgramMinutes = z.infer; + +export const ProgramMinutes = { + $entity: "ProgramMinutes", + $view: "v_program_minutes", + $path: "/program_minutes", + program: { name: "program", label: "Program", view: "number", dbCol: "program" }, + programTitle: { name: "programTitle", label: "Program Title", view: "text", dbCol: "program_title" }, + weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, + longWeeks: { name: "longWeeks", label: "Long Weeks", view: "number", dbCol: "long_weeks" }, + labels: { name: "labels", label: "Labels", view: "number", dbCol: "labels" }, + slots: { name: "slots", label: "Slots", view: "number", dbCol: "slots" }, + totalMinutes: { name: "totalMinutes", label: "Total Minutes", view: "number", dbCol: "total_minutes" }, + avgMinutes: { name: "avgMinutes", label: "Avg Minutes", view: "number", dbCol: "avg_minutes" }, + minMinutes: { name: "minMinutes", label: "Min Minutes", view: "number", dbCol: "min_minutes" }, + maxMinutes: { name: "maxMinutes", label: "Max Minutes", view: "number", dbCol: "max_minutes" }, + longShare: { name: "longShare", label: "Long Share", view: "number", dbCol: "long_share" }, +} as const; + +export type ProgramMinutesFilter = { + limit?: number; + offset?: number; + sort?: `${"program" | "programTitle" | "weeks" | "longWeeks" | "labels" | "slots" | "totalMinutes" | "avgMinutes" | "minMinutes" | "maxMinutes" | "longShare"}:${"asc" | "desc"}` | "program" | "programTitle" | "weeks" | "longWeeks" | "labels" | "slots" | "totalMinutes" | "avgMinutes" | "minMinutes" | "maxMinutes" | "longShare"; + program?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + programTitle?: string | { eq?: string; ne?: string; in?: string[]; like?: string; isNull?: boolean }; + weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + longWeeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + labels?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + slots?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + totalMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + avgMinutes?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + minMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + maxMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + longShare?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + or?: ProgramMinutesFilter[]; + and?: ProgramMinutesFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.names.ts new file mode 100644 index 0000000000..f615f4c15f --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.names.ts @@ -0,0 +1,22 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramRoster + +export const ProgramRosterNames = { + type: "object", + subType: "report", + name: "ProgramRoster", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_program_roster" }, + }, + fields: { + longShare: { name: "longShare", column: "long_share" }, + longShareOrZero: { name: "longShareOrZero", column: "long_share_or_zero" }, + programKey: { name: "programKey", column: "program_key" }, + programTitle: { name: "programTitle", column: "program_title" }, + totalMinutes: { name: "totalMinutes", column: "total_minutes" }, + totalMinutesOrZero: { name: "totalMinutesOrZero", column: "total_minutes_or_zero" }, + weeks: { name: "weeks", column: "weeks" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.queries.ts new file mode 100644 index 0000000000..beba376f0b --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramRoster (ProgramRoster) — report (read-only) +// Extend in your own module (e.g. ProgramRoster.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type ProgramRoster, programRosterView } from "./ProgramRoster.js"; + +type Db = PgDatabase>; + +export async function listProgramRosters(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(programRosterView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.ts new file mode 100644 index 0000000000..2fa6f4dbe6 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.ts @@ -0,0 +1,58 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramRoster (ProgramRoster) + +import { bigint, numeric, pgView, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const programRosterView = pgView("v_program_roster", { + programKey: bigint("program_key", { mode: "number" }).notNull(), + programTitle: varchar("program_title", { length: 200 }).notNull(), + weeks: bigint("weeks", { mode: "number" }).notNull(), + totalMinutes: bigint("total_minutes", { mode: "number" }), + totalMinutesOrZero: bigint("total_minutes_or_zero", { mode: "number" }).notNull(), + longShare: numeric("long_share", { precision: 19, scale: 4 }), + longShareOrZero: numeric("long_share_or_zero", { precision: 19, scale: 4 }).notNull(), +}).existing(); + +export const ProgramRosterSchema = z.object({ + programKey: z.number().int(), + programTitle: z.string(), + weeks: z.number().int(), + totalMinutes: z.number().int().nullable(), + totalMinutesOrZero: z.number().int(), + longShare: z.string().nullable(), + longShareOrZero: z.string(), +}); + +export type ProgramRoster = z.infer; + +export const ProgramRoster = { + $entity: "ProgramRoster", + $view: "v_program_roster", + $path: "/program_rosters", + programKey: { name: "programKey", label: "Program Key", view: "number", dbCol: "program_key" }, + programTitle: { name: "programTitle", label: "Program Title", view: "text", dbCol: "program_title" }, + weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, + totalMinutes: { name: "totalMinutes", label: "Total Minutes", view: "number", dbCol: "total_minutes" }, + totalMinutesOrZero: { name: "totalMinutesOrZero", label: "Total Minutes Or Zero", view: "number", dbCol: "total_minutes_or_zero" }, + longShare: { name: "longShare", label: "Long Share", view: "number", dbCol: "long_share" }, + longShareOrZero: { name: "longShareOrZero", label: "Long Share Or Zero", view: "number", dbCol: "long_share_or_zero" }, +} as const; + +export type ProgramRosterFilter = { + limit?: number; + offset?: number; + sort?: `${"programKey" | "programTitle" | "weeks" | "totalMinutes" | "totalMinutesOrZero" | "longShare" | "longShareOrZero"}:${"asc" | "desc"}` | "programKey" | "programTitle" | "weeks" | "totalMinutes" | "totalMinutesOrZero" | "longShare" | "longShareOrZero"; + programKey?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + programTitle?: string | { eq?: string; ne?: string; in?: string[]; like?: string; isNull?: boolean }; + weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + totalMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + totalMinutesOrZero?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + longShare?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + longShareOrZero?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + or?: ProgramRosterFilter[]; + and?: ProgramRosterFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.names.ts new file mode 100644 index 0000000000..22e0cb4f4f --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.names.ts @@ -0,0 +1,20 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramSessions + +export const ProgramSessionsNames = { + type: "object", + subType: "report", + name: "ProgramSessions", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_program_sessions" }, + }, + fields: { + programKey: { name: "programKey", column: "program_key" }, + programTitle: { name: "programTitle", column: "program_title" }, + sessionMinutes: { name: "sessionMinutes", column: "session_minutes" }, + sessionMinutesOrZero: { name: "sessionMinutesOrZero", column: "session_minutes_or_zero" }, + sessions: { name: "sessions", column: "sessions" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.queries.ts new file mode 100644 index 0000000000..bfd8d94b31 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramSessions (ProgramSessions) — report (read-only) +// Extend in your own module (e.g. ProgramSessions.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type ProgramSessions, programSessionsView } from "./ProgramSessions.js"; + +type Db = PgDatabase>; + +export async function listProgramSessions(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(programSessionsView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.ts new file mode 100644 index 0000000000..b9cbe855f1 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.ts @@ -0,0 +1,50 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramSessions (ProgramSessions) + +import { bigint, pgView, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const programSessionsView = pgView("v_program_sessions", { + programKey: bigint("program_key", { mode: "number" }).notNull(), + programTitle: varchar("program_title", { length: 200 }).notNull(), + sessions: bigint("sessions", { mode: "number" }).notNull(), + sessionMinutes: bigint("session_minutes", { mode: "number" }), + sessionMinutesOrZero: bigint("session_minutes_or_zero", { mode: "number" }).notNull(), +}).existing(); + +export const ProgramSessionsSchema = z.object({ + programKey: z.number().int(), + programTitle: z.string(), + sessions: z.number().int(), + sessionMinutes: z.number().int().nullable(), + sessionMinutesOrZero: z.number().int(), +}); + +export type ProgramSessions = z.infer; + +export const ProgramSessions = { + $entity: "ProgramSessions", + $view: "v_program_sessions", + $path: "/program_sessions", + programKey: { name: "programKey", label: "Program Key", view: "number", dbCol: "program_key" }, + programTitle: { name: "programTitle", label: "Program Title", view: "text", dbCol: "program_title" }, + sessions: { name: "sessions", label: "Sessions", view: "number", dbCol: "sessions" }, + sessionMinutes: { name: "sessionMinutes", label: "Session Minutes", view: "number", dbCol: "session_minutes" }, + sessionMinutesOrZero: { name: "sessionMinutesOrZero", label: "Session Minutes Or Zero", view: "number", dbCol: "session_minutes_or_zero" }, +} as const; + +export type ProgramSessionsFilter = { + limit?: number; + offset?: number; + sort?: `${"programKey" | "programTitle" | "sessions" | "sessionMinutes" | "sessionMinutesOrZero"}:${"asc" | "desc"}` | "programKey" | "programTitle" | "sessions" | "sessionMinutes" | "sessionMinutesOrZero"; + programKey?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + programTitle?: string | { eq?: string; ne?: string; in?: string[]; like?: string; isNull?: boolean }; + sessions?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + sessionMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + sessionMinutesOrZero?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: ProgramSessionsFilter[]; + and?: ProgramSessionsFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.names.ts new file mode 100644 index 0000000000..1d42dd8bd9 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.names.ts @@ -0,0 +1,23 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramStat + +export const ProgramStatNames = { + type: "object", + subType: "projection", + name: "ProgramStat", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_program_stat" }, + }, + fields: { + avgMinutes: { name: "avgMinutes", column: "avg_minutes" }, + maxMinutes: { name: "maxMinutes", column: "max_minutes" }, + minMinutes: { name: "minMinutes", column: "min_minutes" }, + programId: { name: "programId", column: "program_id" }, + totalMinutes: { name: "totalMinutes", column: "total_minutes" }, + weekCount: { name: "weekCount", column: "week_count" }, + }, + identities: { + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.queries.ts new file mode 100644 index 0000000000..8522a3b790 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.queries.ts @@ -0,0 +1,25 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramStat (ProgramStat) — projection (read-only) +// Extend in your own module (e.g. ProgramStat.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type ProgramStat, programStatView } from "./ProgramStat.js"; + +type Db = PgDatabase>; + +export async function findProgramStatById(db: Db, programId: number): Promise { + const [row] = await db.select().from(programStatView).where(eq(programStatView.programId, programId)).limit(1); + return row ?? null; +} + +export async function listProgramStats(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(programStatView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.ts new file mode 100644 index 0000000000..2196035227 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.ts @@ -0,0 +1,48 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramStat (ProgramStat) + +import { bigint, doublePrecision, pgView } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const programStatView = pgView("v_program_stat", { + programId: bigint("program_id", { mode: "number" }).notNull(), + weekCount: bigint("week_count", { mode: "number" }), + totalMinutes: bigint("total_minutes", { mode: "number" }), + avgMinutes: doublePrecision("avg_minutes"), + minMinutes: bigint("min_minutes", { mode: "number" }), + maxMinutes: bigint("max_minutes", { mode: "number" }), +}).existing(); + +export const ProgramStatSchema = z.object({ + programId: z.number().int(), + weekCount: z.number().int().nullable(), + totalMinutes: z.number().int().nullable(), + avgMinutes: z.number().nullable(), + minMinutes: z.number().int().nullable(), + maxMinutes: z.number().int().nullable(), +}); + +export type ProgramStat = z.infer; + +export const ProgramStat = { + $entity: "ProgramStat", + $view: "v_program_stat", + $path: "/program_stats", + programId: { name: "programId", label: "Program Id", view: "number", dbCol: "program_id" }, + weekCount: { name: "weekCount", label: "Week Count", view: "number", dbCol: "week_count" }, + totalMinutes: { name: "totalMinutes", label: "Total Minutes", view: "number", dbCol: "total_minutes" }, + avgMinutes: { name: "avgMinutes", label: "Avg Minutes", view: "number", dbCol: "avg_minutes" }, + minMinutes: { name: "minMinutes", label: "Min Minutes", view: "number", dbCol: "min_minutes" }, + maxMinutes: { name: "maxMinutes", label: "Max Minutes", view: "number", dbCol: "max_minutes" }, +} as const; + +export type ProgramStatFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: ProgramStatFilter[]; + and?: ProgramStatFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramVerdict.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramVerdict.ts new file mode 100644 index 0000000000..0ad48890f2 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramVerdict.ts @@ -0,0 +1,40 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramVerdict (ProgramVerdict) +// Extend in your own module (e.g. ProgramVerdict.extra.ts) — nothing imports it for you. + +import { z } from "zod"; + +export interface ProgramVerdict { + verdict: ProgramVerdictVerdict; + rationale: string; +} + +export type ProgramVerdictVerdict = "GOOD" | "OK" | "POOR"; +export const ProgramVerdictVerdictEnum = z.enum(["GOOD", "OK", "POOR"]); + +export const ProgramVerdictInsertSchema = z.object({ + verdict: z.enum(["GOOD", "OK", "POOR"]), + rationale: z.string().min(1).max(480), +}); + +/** + * Metadata constants for the value object ProgramVerdict: each field's name, label, view and the + * validation rules derived from its validator children (e.g. `ProgramVerdict..rules.maxLength.value`). + */ +export const ProgramVerdict = { + $entity: "ProgramVerdict", + verdict: { + name: "verdict", + label: "Verdict", + view: "dropdown", + rules: { required: "Verdict is required" }, + options: ["GOOD", "OK", "POOR"] as const, + }, + rationale: { + name: "rationale", + label: "Rationale", + view: "text", + htmlType: "text", + rules: { required: "Rationale is required", maxLength: { value: 480, message: "Must be 480 characters or fewer" } }, + }, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.names.ts new file mode 100644 index 0000000000..9f1809cefe --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.names.ts @@ -0,0 +1,20 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramView + +export const ProgramViewNames = { + type: "object", + subType: "projection", + name: "ProgramView", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_program" }, + }, + fields: { + id: { name: "id", column: "id" }, + status: { name: "status", column: "status" }, + title: { name: "title", column: "title" }, + }, + identities: { + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.queries.ts new file mode 100644 index 0000000000..ce44872ece --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.queries.ts @@ -0,0 +1,25 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramView (ProgramView) — projection (read-only) +// Extend in your own module (e.g. ProgramView.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type ProgramView, programViewView } from "./ProgramView.js"; + +type Db = PgDatabase>; + +export async function findProgramViewById(db: Db, id: number): Promise { + const [row] = await db.select().from(programViewView).where(eq(programViewView.id, id)).limit(1); + return row ?? null; +} + +export async function listProgramViews(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(programViewView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.ts new file mode 100644 index 0000000000..73210ded6f --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.ts @@ -0,0 +1,39 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramView (ProgramView) + +import { bigint, pgView, text } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const programViewView = pgView("v_program", { + id: bigint("id", { mode: "number" }).notNull(), + title: text("title"), + status: text("status", { enum: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const }).notNull(), +}).existing(); + +export const ProgramViewSchema = z.object({ + id: z.number().int(), + title: z.string().nullable(), + status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]), +}); + +export type ProgramView = z.infer; + +export const ProgramView = { + $entity: "ProgramView", + $view: "v_program", + $path: "/program_views", + id: { name: "id", label: "Id", view: "number", dbCol: "id" }, + title: { name: "title", label: "Title", view: "text", dbCol: "title" }, + status: { name: "status", label: "Status", view: "dropdown", dbCol: "status" }, +} as const; + +export type ProgramViewFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: ProgramViewFilter[]; + and?: ProgramViewFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.names.ts new file mode 100644 index 0000000000..add5c32e81 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.names.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramsByMonth + +export const ProgramsByMonthNames = { + type: "object", + subType: "report", + name: "ProgramsByMonth", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_programs_by_month" }, + }, + fields: { + createdAtMonth: { name: "createdAtMonth", column: "created_at_month" }, + listValue: { name: "listValue", column: "list_value" }, + programs: { name: "programs", column: "programs" }, + status: { name: "status", column: "status" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.queries.ts new file mode 100644 index 0000000000..e971f3e1b4 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramsByMonth (ProgramsByMonth) — report (read-only) +// Extend in your own module (e.g. ProgramsByMonth.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type ProgramsByMonth, programsByMonthView } from "./ProgramsByMonth.js"; + +type Db = PgDatabase>; + +export async function listProgramsByMonths(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(programsByMonthView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.ts new file mode 100644 index 0000000000..fdbecc8eb9 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.ts @@ -0,0 +1,46 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramsByMonth (ProgramsByMonth) + +import { bigint, date, pgView, text } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const programsByMonthView = pgView("v_programs_by_month", { + createdAtMonth: date("created_at_month").notNull(), + status: text("status", { enum: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const }).notNull(), + programs: bigint("programs", { mode: "number" }).notNull(), + listValue: bigint("list_value", { mode: "number" }), +}).existing(); + +export const ProgramsByMonthSchema = z.object({ + createdAtMonth: z.string(), + status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]), + programs: z.number().int(), + listValue: z.number().int().nullable(), +}); + +export type ProgramsByMonth = z.infer; + +export const ProgramsByMonth = { + $entity: "ProgramsByMonth", + $view: "v_programs_by_month", + $path: "/programs_by_months", + createdAtMonth: { name: "createdAtMonth", label: "Created At Month", view: "date", dbCol: "created_at_month" }, + status: { name: "status", label: "Status", view: "dropdown", dbCol: "status" }, + programs: { name: "programs", label: "Programs", view: "number", dbCol: "programs" }, + listValue: { name: "listValue", label: "List Value", view: "currency", dbCol: "list_value", currency: "USD", locale: "en-US" }, +} as const; + +export type ProgramsByMonthFilter = { + limit?: number; + offset?: number; + sort?: `${"createdAtMonth" | "status" | "programs" | "listValue"}:${"asc" | "desc"}` | "createdAtMonth" | "status" | "programs" | "listValue"; + createdAtMonth?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + status?: "DRAFT" | "PUBLISHED" | "ARCHIVED" | { eq?: "DRAFT" | "PUBLISHED" | "ARCHIVED"; ne?: "DRAFT" | "PUBLISHED" | "ARCHIVED"; in?: ("DRAFT" | "PUBLISHED" | "ARCHIVED")[]; like?: string; isNull?: boolean }; + programs?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + listValue?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: ProgramsByMonthFilter[]; + and?: ProgramsByMonthFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.names.ts new file mode 100644 index 0000000000..07ac1e1a05 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.names.ts @@ -0,0 +1,17 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramsByWeek + +export const ProgramsByWeekNames = { + type: "object", + subType: "report", + name: "ProgramsByWeek", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_programs_by_week" }, + }, + fields: { + createdAtWeek: { name: "createdAtWeek", column: "created_at_week" }, + programs: { name: "programs", column: "programs" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.queries.ts new file mode 100644 index 0000000000..793f304e59 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramsByWeek (ProgramsByWeek) — report (read-only) +// Extend in your own module (e.g. ProgramsByWeek.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type ProgramsByWeek, programsByWeekView } from "./ProgramsByWeek.js"; + +type Db = PgDatabase>; + +export async function listProgramsByWeeks(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(programsByWeekView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.ts new file mode 100644 index 0000000000..ea3ad67232 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.ts @@ -0,0 +1,38 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramsByWeek (ProgramsByWeek) + +import { bigint, date, pgView } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const programsByWeekView = pgView("v_programs_by_week", { + createdAtWeek: date("created_at_week").notNull(), + programs: bigint("programs", { mode: "number" }).notNull(), +}).existing(); + +export const ProgramsByWeekSchema = z.object({ + createdAtWeek: z.string(), + programs: z.number().int(), +}); + +export type ProgramsByWeek = z.infer; + +export const ProgramsByWeek = { + $entity: "ProgramsByWeek", + $view: "v_programs_by_week", + $path: "/programs_by_weeks", + createdAtWeek: { name: "createdAtWeek", label: "Created At Week", view: "date", dbCol: "created_at_week" }, + programs: { name: "programs", label: "Programs", view: "number", dbCol: "programs" }, +} as const; + +export type ProgramsByWeekFilter = { + limit?: number; + offset?: number; + sort?: `${"createdAtWeek" | "programs"}:${"asc" | "desc"}` | "createdAtWeek" | "programs"; + createdAtWeek?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + programs?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: ProgramsByWeekFilter[]; + and?: ProgramsByWeekFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.names.ts new file mode 100644 index 0000000000..74a01da315 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.names.ts @@ -0,0 +1,17 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramsEmptyScope + +export const ProgramsEmptyScopeNames = { + type: "object", + subType: "report", + name: "ProgramsEmptyScope", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_programs_empty_scope" }, + }, + fields: { + avgPriceOrMinusOne: { name: "avgPriceOrMinusOne", column: "avg_price_or_minus_one" }, + programs: { name: "programs", column: "programs" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.queries.ts new file mode 100644 index 0000000000..b60a0b1afc --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramsEmptyScope (ProgramsEmptyScope) — report (read-only) +// Extend in your own module (e.g. ProgramsEmptyScope.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type ProgramsEmptyScope, programsEmptyScopeView } from "./ProgramsEmptyScope.js"; + +type Db = PgDatabase>; + +export async function listProgramsEmptyScopes(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(programsEmptyScopeView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.ts new file mode 100644 index 0000000000..6fa5498102 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.ts @@ -0,0 +1,38 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramsEmptyScope (ProgramsEmptyScope) + +import { bigint, numeric, pgView } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const programsEmptyScopeView = pgView("v_programs_empty_scope", { + programs: bigint("programs", { mode: "number" }).notNull(), + avgPriceOrMinusOne: numeric("avg_price_or_minus_one", { precision: 19, scale: 4 }).notNull(), +}).existing(); + +export const ProgramsEmptyScopeSchema = z.object({ + programs: z.number().int(), + avgPriceOrMinusOne: z.string(), +}); + +export type ProgramsEmptyScope = z.infer; + +export const ProgramsEmptyScope = { + $entity: "ProgramsEmptyScope", + $view: "v_programs_empty_scope", + $path: "/programs_empty_scopes", + programs: { name: "programs", label: "Programs", view: "number", dbCol: "programs" }, + avgPriceOrMinusOne: { name: "avgPriceOrMinusOne", label: "Avg Price Or Minus One", view: "number", dbCol: "avg_price_or_minus_one" }, +} as const; + +export type ProgramsEmptyScopeFilter = { + limit?: number; + offset?: number; + sort?: `${"programs" | "avgPriceOrMinusOne"}:${"asc" | "desc"}` | "programs" | "avgPriceOrMinusOne"; + programs?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + avgPriceOrMinusOne?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + or?: ProgramsEmptyScopeFilter[]; + and?: ProgramsEmptyScopeFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.names.ts new file mode 100644 index 0000000000..d8bd5d7b53 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.names.ts @@ -0,0 +1,22 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramsOverTime + +export const ProgramsOverTimeNames = { + type: "object", + subType: "report", + name: "ProgramsOverTime", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_programs_over_time" }, + }, + fields: { + avgPrice: { name: "avgPrice", column: "avg_price" }, + cheapest: { name: "cheapest", column: "cheapest" }, + createdAtDay: { name: "createdAtDay", column: "created_at_day" }, + createdAtQuarter: { name: "createdAtQuarter", column: "created_at_quarter" }, + createdAtYear: { name: "createdAtYear", column: "created_at_year" }, + priciest: { name: "priciest", column: "priciest" }, + programs: { name: "programs", column: "programs" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.queries.ts new file mode 100644 index 0000000000..c28356adf3 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramsOverTime (ProgramsOverTime) — report (read-only) +// Extend in your own module (e.g. ProgramsOverTime.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type ProgramsOverTime, programsOverTimeView } from "./ProgramsOverTime.js"; + +type Db = PgDatabase>; + +export async function listProgramsOverTimes(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(programsOverTimeView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.ts new file mode 100644 index 0000000000..e041e1b49d --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.ts @@ -0,0 +1,58 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ProgramsOverTime (ProgramsOverTime) + +import { bigint, date, numeric, pgView } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const programsOverTimeView = pgView("v_programs_over_time", { + createdAtDay: date("created_at_day").notNull(), + createdAtQuarter: date("created_at_quarter").notNull(), + createdAtYear: date("created_at_year").notNull(), + programs: bigint("programs", { mode: "number" }).notNull(), + avgPrice: numeric("avg_price", { precision: 19, scale: 4 }), + cheapest: bigint("cheapest", { mode: "number" }), + priciest: bigint("priciest", { mode: "number" }), +}).existing(); + +export const ProgramsOverTimeSchema = z.object({ + createdAtDay: z.string(), + createdAtQuarter: z.string(), + createdAtYear: z.string(), + programs: z.number().int(), + avgPrice: z.string().nullable(), + cheapest: z.number().int().nullable(), + priciest: z.number().int().nullable(), +}); + +export type ProgramsOverTime = z.infer; + +export const ProgramsOverTime = { + $entity: "ProgramsOverTime", + $view: "v_programs_over_time", + $path: "/programs_over_times", + createdAtDay: { name: "createdAtDay", label: "Created At Day", view: "date", dbCol: "created_at_day" }, + createdAtQuarter: { name: "createdAtQuarter", label: "Created At Quarter", view: "date", dbCol: "created_at_quarter" }, + createdAtYear: { name: "createdAtYear", label: "Created At Year", view: "date", dbCol: "created_at_year" }, + programs: { name: "programs", label: "Programs", view: "number", dbCol: "programs" }, + avgPrice: { name: "avgPrice", label: "Avg Price", view: "number", dbCol: "avg_price" }, + cheapest: { name: "cheapest", label: "Cheapest", view: "currency", dbCol: "cheapest", currency: "USD", locale: "en-US" }, + priciest: { name: "priciest", label: "Priciest", view: "currency", dbCol: "priciest", currency: "USD", locale: "en-US" }, +} as const; + +export type ProgramsOverTimeFilter = { + limit?: number; + offset?: number; + sort?: `${"createdAtDay" | "createdAtQuarter" | "createdAtYear" | "programs" | "avgPrice" | "cheapest" | "priciest"}:${"asc" | "desc"}` | "createdAtDay" | "createdAtQuarter" | "createdAtYear" | "programs" | "avgPrice" | "cheapest" | "priciest"; + createdAtDay?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + createdAtQuarter?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + createdAtYear?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + programs?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + avgPrice?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; + cheapest?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + priciest?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: ProgramsOverTimeFilter[]; + and?: ProgramsOverTimeFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.names.ts new file mode 100644 index 0000000000..5deef7de69 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.names.ts @@ -0,0 +1,16 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: RecentPrograms + +export const RecentProgramsNames = { + type: "object", + subType: "report", + name: "RecentPrograms", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_recent_programs" }, + }, + fields: { + programs: { name: "programs", column: "programs" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.queries.ts new file mode 100644 index 0000000000..10b246de52 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: RecentPrograms (RecentPrograms) — report (read-only) +// Extend in your own module (e.g. RecentPrograms.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type RecentPrograms, recentProgramsView } from "./RecentPrograms.js"; + +type Db = PgDatabase>; + +export async function listRecentPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(recentProgramsView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.ts new file mode 100644 index 0000000000..82a19fee3b --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.ts @@ -0,0 +1,34 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: RecentPrograms (RecentPrograms) + +import { bigint, pgView } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const recentProgramsView = pgView("v_recent_programs", { + programs: bigint("programs", { mode: "number" }).notNull(), +}).existing(); + +export const RecentProgramsSchema = z.object({ + programs: z.number().int(), +}); + +export type RecentPrograms = z.infer; + +export const RecentPrograms = { + $entity: "RecentPrograms", + $view: "v_recent_programs", + $path: "/recent_programs", + programs: { name: "programs", label: "Programs", view: "number", dbCol: "programs" }, +} as const; + +export type RecentProgramsFilter = { + limit?: number; + offset?: number; + sort?: `${"programs"}:${"asc" | "desc"}` | "programs"; + programs?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: RecentProgramsFilter[]; + and?: RecentProgramsFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.names.ts new file mode 100644 index 0000000000..44ba951928 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.names.ts @@ -0,0 +1,23 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ReferralAuth + +import { AuthNames } from "./Auth.names.js"; + +export const ReferralAuthNames = { + type: "object", + subType: "entity", + name: "ReferralAuth", + sources: { + ...AuthNames.sources, + }, + fields: { + ...AuthNames.fields, + urgency: { name: "urgency", column: "urgency" }, + }, + identities: { + ...AuthNames.identities, + }, + indexes: { + ...AuthNames.indexes, + }, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.ts new file mode 100644 index 0000000000..1109fb75d1 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.ts @@ -0,0 +1,113 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: ReferralAuth (ReferralAuth) +// Extend in your own module (e.g. ReferralAuth.extra.ts) — nothing imports it for you. + +import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; +import { z } from "zod"; + +export interface ReferralAuth { + id?: number | undefined; + type?: ReferralAuthType | null | undefined; + reference: string; + urgency: string | null; +} + +export type ReferralAuthType = "Bridge" | "Coupon" | "Permit" | "Referral"; +export const ReferralAuthTypeEnum = z.enum(["Bridge", "Coupon", "Permit", "Referral"]); + +export const ReferralAuthSchema = z.object({ + id: z.number().int(), + type: z.literal("Referral"), + reference: z.string().min(1).max(80), + urgency: z.string().min(1).max(16).nullable(), +}); + +export const ReferralAuthInsertSchema = z.object({ + type: z.literal("Referral"), + reference: z.string().min(1).max(80), + urgency: z.string().min(1).max(16).optional(), +}); + +export const ReferralAuthUpdateSchema = z.object({ + reference: z.string().min(1).max(80).optional(), + urgency: z.string().min(1).max(16).optional(), +}); + +/** + * Typed create shape for ReferralAuth: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createReferralAuth` call site; + * the schema still validates at runtime. + */ +export type ReferralAuthCreate = z.input; + +/** + * Typed patch shape for ReferralAuth: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateReferralAuth` call site. + */ +export type ReferralAuthPatch = z.input; + +/** + * Metadata constants for ReferralAuth. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(ReferralAuth, ReferralAuthInsertSchema); + * + */ +export const ReferralAuth = { + $entity: "ReferralAuth", + $table: "auths", + $path: "/auths/referral", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + type: { + name: "type", + label: "Type", + view: "dropdown", + options: ["Bridge", "Coupon", "Permit", "Referral"] as const, + }, + reference: { + name: "reference", + label: "Reference", + view: "text", + htmlType: "text", + rules: { required: "Reference is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, + }, + urgency: { + name: "urgency", + label: "Urgency", + view: "text", + htmlType: "text", + rules: { required: "Urgency is required", maxLength: { value: 16, message: "Must be 16 characters or fewer" } }, + }, +} as const; + +export const ReferralAuthFilterAllowlist = {} as const satisfies FilterAllowlist; + +export const ReferralAuthSortAllowlist = {} as const satisfies SortAllowlist; + +export type ReferralAuthFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: ReferralAuthFilter[]; + and?: ReferralAuthFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.names.ts new file mode 100644 index 0000000000..9d59d90620 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.names.ts @@ -0,0 +1,21 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Session + +export const SessionNames = { + type: "object", + subType: "entity", + name: "Session", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "sessions" }, + }, + fields: { + id: { name: "id", column: "id" }, + minutes: { name: "minutes", column: "minutes" }, + weekId: { name: "weekId", column: "week_id" }, + }, + identities: { + fkWeek: { type: "identity", subType: "reference", name: "fkWeek" }, + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.queries.ts new file mode 100644 index 0000000000..cb8545afa8 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.queries.ts @@ -0,0 +1,61 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Session (Session) +// Extend in your own module (e.g. Session.extra.ts) — nothing imports it for you. + +import { eq, inArray } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { type Session, SessionInsertSchema, type SessionPatch, SessionUpdateSchema, sessions } from "./Session.js"; + +type Db = PgDatabase>; + +export async function findSessionById(db: Db, id: number): Promise { + const [session] = await db.select().from(sessions).where(eq(sessions.id, id)).limit(1); + return session ?? null; +} + +export async function listSessions(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(sessions).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createSession(db: Db, data: z.input): Promise { + const validated = SessionInsertSchema.parse(data); + const [session] = await db.insert(sessions).values(validated).returning(); + return session!; +} + +export async function updateSession(db: Db, id: number, patch: SessionPatch): Promise { + const validated = SessionUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findSessionById(db, id); + } + const [session] = await db.update(sessions).set(validated).where(eq(sessions.id, id)).returning(); + return session ?? null; +} + +export async function deleteSessionById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(sessions).where(eq(sessions.id, id)).returning(); + return deleted.length > 0; +} + +export async function findSessionsByWeek(db: Db, weekId: number): Promise { + return db.select().from(sessions).where(eq(sessions.weekId, weekId)); +} + +export async function findSessionsByWeekIn(db: Db, weekIds: number[]): Promise { + if (weekIds.length === 0) { + return []; + } + return db.select().from(sessions).where(inArray(sessions.weekId, weekIds)); +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.ts new file mode 100644 index 0000000000..35258fb418 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.ts @@ -0,0 +1,97 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Session (Session) +// Extend in your own module (e.g. Session.extra.ts) — nothing imports it for you. + +import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; +import { type AnyPgColumn, bigint, integer, pgTable } from "drizzle-orm/pg-core"; +import { z } from "zod"; +import { weeks } from "./Week.js"; + +export const sessions = pgTable("sessions", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + weekId: bigint("week_id", { mode: "number" }).notNull().references((): AnyPgColumn => weeks.id), + minutes: integer("minutes").notNull(), +}); + +export type Session = InferSelectModel; +export type SessionInsert = InferInsertModel; +export type SessionUpdate = Partial; + +export const SessionInsertSchema = z.object({ + weekId: z.number().int(), + minutes: z.number().int(), +}); + +export const SessionUpdateSchema = z.object({ + weekId: z.number().int().optional(), + minutes: z.number().int().optional(), +}); + +/** + * Typed create shape for Session: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createSession` call site; + * the schema still validates at runtime. + */ +export type SessionCreate = z.input; + +/** + * Typed patch shape for Session: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateSession` call site. + */ +export type SessionPatch = z.input; + +/** + * Metadata constants for Session. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Session, SessionInsertSchema); + * + */ +export const Session = { + $entity: "Session", + $table: "sessions", + $path: "/sessions", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + weekId: { + name: "weekId", + label: "Week Id", + view: "number", + htmlType: "number", + rules: { required: "Week Id is required" }, + }, + minutes: { + name: "minutes", + label: "Minutes", + view: "number", + htmlType: "number", + rules: { required: "Minutes is required" }, + }, +} as const; + +export type SessionFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: SessionFilter[]; + and?: SessionFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.names.ts new file mode 100644 index 0000000000..69db72de97 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.names.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: SessionsByProgram + +export const SessionsByProgramNames = { + type: "object", + subType: "report", + name: "SessionsByProgram", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_sessions_by_program" }, + }, + fields: { + programTitle: { name: "programTitle", column: "program_title" }, + sessionMinutes: { name: "sessionMinutes", column: "session_minutes" }, + sessions: { name: "sessions", column: "sessions" }, + weekKey: { name: "weekKey", column: "week_key" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.queries.ts new file mode 100644 index 0000000000..d441835946 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: SessionsByProgram (SessionsByProgram) — report (read-only) +// Extend in your own module (e.g. SessionsByProgram.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type SessionsByProgram, sessionsByProgramView } from "./SessionsByProgram.js"; + +type Db = PgDatabase>; + +export async function listSessionsByPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(sessionsByProgramView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.ts new file mode 100644 index 0000000000..a74a352d1a --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.ts @@ -0,0 +1,46 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: SessionsByProgram (SessionsByProgram) + +import { bigint, pgView, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const sessionsByProgramView = pgView("v_sessions_by_program", { + programTitle: varchar("program_title", { length: 200 }).notNull(), + weekKey: bigint("week_key", { mode: "number" }), + sessions: bigint("sessions", { mode: "number" }).notNull(), + sessionMinutes: bigint("session_minutes", { mode: "number" }), +}).existing(); + +export const SessionsByProgramSchema = z.object({ + programTitle: z.string(), + weekKey: z.number().int().nullable(), + sessions: z.number().int(), + sessionMinutes: z.number().int().nullable(), +}); + +export type SessionsByProgram = z.infer; + +export const SessionsByProgram = { + $entity: "SessionsByProgram", + $view: "v_sessions_by_program", + $path: "/sessions_by_programs", + programTitle: { name: "programTitle", label: "Program Title", view: "text", dbCol: "program_title" }, + weekKey: { name: "weekKey", label: "Week Key", view: "number", dbCol: "week_key" }, + sessions: { name: "sessions", label: "Sessions", view: "number", dbCol: "sessions" }, + sessionMinutes: { name: "sessionMinutes", label: "Session Minutes", view: "number", dbCol: "session_minutes" }, +} as const; + +export type SessionsByProgramFilter = { + limit?: number; + offset?: number; + sort?: `${"programTitle" | "weekKey" | "sessions" | "sessionMinutes"}:${"asc" | "desc"}` | "programTitle" | "weekKey" | "sessions" | "sessionMinutes"; + programTitle?: string | { eq?: string; ne?: string; in?: string[]; like?: string; isNull?: boolean }; + weekKey?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + sessions?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + sessionMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: SessionsByProgramFilter[]; + and?: SessionsByProgramFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Settings.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Settings.ts new file mode 100644 index 0000000000..3ceee3f004 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Settings.ts @@ -0,0 +1,43 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Settings (Settings) +// Extend in your own module (e.g. Settings.extra.ts) — nothing imports it for you. + +import { z } from "zod"; + +export interface Settings { + theme?: string | undefined; + notify?: boolean | undefined; + retries?: number | undefined; +} + +export const SettingsInsertSchema = z.object({ + theme: z.string().optional(), + notify: z.boolean().optional(), + retries: z.number().int().optional(), +}); + +/** + * Metadata constants for the value object Settings: each field's name, label, view and the + * validation rules derived from its validator children (e.g. `Settings..rules.maxLength.value`). + */ +export const Settings = { + $entity: "Settings", + theme: { + name: "theme", + label: "Theme", + view: "text", + htmlType: "text", + }, + notify: { + name: "notify", + label: "Notify", + view: "checkbox", + htmlType: "checkbox", + }, + retries: { + name: "retries", + label: "Retries", + view: "number", + htmlType: "number", + }, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.names.ts new file mode 100644 index 0000000000..5fbeb7660c --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.names.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Tag + +export const TagNames = { + type: "object", + subType: "entity", + name: "Tag", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "tags" }, + }, + fields: { + id: { name: "id", column: "id" }, + name: { name: "name", column: "name" }, + }, + identities: { + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.queries.ts new file mode 100644 index 0000000000..50e299aec8 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.queries.ts @@ -0,0 +1,50 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Tag (Tag) +// Extend in your own module (e.g. Tag.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { type Tag, TagInsertSchema, type TagPatch, TagUpdateSchema, tags } from "./Tag.js"; + +type Db = PgDatabase>; + +export async function findTagById(db: Db, id: number): Promise { + const [tag] = await db.select().from(tags).where(eq(tags.id, id)).limit(1); + return tag ?? null; +} + +export async function listTags(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(tags).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createTag(db: Db, data: z.input): Promise { + const validated = TagInsertSchema.parse(data); + const [tag] = await db.insert(tags).values(validated).returning(); + return tag!; +} + +export async function updateTag(db: Db, id: number, patch: TagPatch): Promise { + const validated = TagUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findTagById(db, id); + } + const [tag] = await db.update(tags).set(validated).where(eq(tags.id, id)).returning(); + return tag ?? null; +} + +export async function deleteTagById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(tags).where(eq(tags.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.ts new file mode 100644 index 0000000000..d4489e4189 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.ts @@ -0,0 +1,86 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Tag (Tag) +// Extend in your own module (e.g. Tag.extra.ts) — nothing imports it for you. + +import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; +import { bigint, pgTable, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +export const tags = pgTable("tags", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + name: varchar("name", { length: 80 }).notNull(), +}); + +export type Tag = InferSelectModel; +export type TagInsert = InferInsertModel; +export type TagUpdate = Partial; + +export const TagInsertSchema = z.object({ + name: z.string().min(1).max(80), +}); + +export const TagUpdateSchema = z.object({ + name: z.string().min(1).max(80).optional(), +}); + +/** + * Typed create shape for Tag: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createTag` call site; + * the schema still validates at runtime. + */ +export type TagCreate = z.input; + +/** + * Typed patch shape for Tag: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateTag` call site. + */ +export type TagPatch = z.input; + +/** + * Metadata constants for Tag. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Tag, TagInsertSchema); + * + */ +export const Tag = { + $entity: "Tag", + $table: "tags", + $path: "/tags", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + name: { + name: "name", + label: "Name", + view: "text", + htmlType: "text", + rules: { required: "Name is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, + }, +} as const; + +export type TagFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: TagFilter[]; + and?: TagFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.names.ts new file mode 100644 index 0000000000..277f662361 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.names.ts @@ -0,0 +1,23 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Week + +export const WeekNames = { + type: "object", + subType: "entity", + name: "Week", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "weeks" }, + }, + fields: { + deload: { name: "deload", column: "deload" }, + durationMinutes: { name: "durationMinutes", column: "duration_minutes" }, + id: { name: "id", column: "id" }, + label: { name: "label", column: "label" }, + programId: { name: "programId", column: "program_id" }, + }, + identities: { + fkProgram: { type: "identity", subType: "reference", name: "fkProgram" }, + id: { type: "identity", subType: "primary", name: "id" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.queries.ts new file mode 100644 index 0000000000..8c89fc4b9a --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.queries.ts @@ -0,0 +1,61 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Week (Week) +// Extend in your own module (e.g. Week.extra.ts) — nothing imports it for you. + +import { eq, inArray } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import type { z } from "zod"; +import { type Week, WeekInsertSchema, type WeekPatch, WeekUpdateSchema, weeks } from "./Week.js"; + +type Db = PgDatabase>; + +export async function findWeekById(db: Db, id: number): Promise { + const [week] = await db.select().from(weeks).where(eq(weeks.id, id)).limit(1); + return week ?? null; +} + +export async function listWeeks(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(weeks).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createWeek(db: Db, data: z.input): Promise { + const validated = WeekInsertSchema.parse(data); + const [week] = await db.insert(weeks).values(validated).returning(); + return week!; +} + +export async function updateWeek(db: Db, id: number, patch: WeekPatch): Promise { + const validated = WeekUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findWeekById(db, id); + } + const [week] = await db.update(weeks).set(validated).where(eq(weeks.id, id)).returning(); + return week ?? null; +} + +export async function deleteWeekById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(weeks).where(eq(weeks.id, id)).returning(); + return deleted.length > 0; +} + +export async function findWeeksByProgram(db: Db, programId: number): Promise { + return db.select().from(weeks).where(eq(weeks.programId, programId)); +} + +export async function findWeeksByProgramIn(db: Db, programIds: number[]): Promise { + if (programIds.length === 0) { + return []; + } + return db.select().from(weeks).where(inArray(weeks.programId, programIds)); +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.ts new file mode 100644 index 0000000000..11fa7bc792 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.ts @@ -0,0 +1,116 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Week (Week) +// Extend in your own module (e.g. Week.extra.ts) — nothing imports it for you. + +import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; +import { type AnyPgColumn, bigint, boolean, integer, pgTable, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; +import { programs } from "./Program.js"; + +export const weeks = pgTable("weeks", { + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + programId: bigint("program_id", { mode: "number" }).notNull().references((): AnyPgColumn => programs.id), + label: varchar("label", { length: 80 }), + durationMinutes: integer("duration_minutes").notNull(), + deload: boolean("deload"), +}); + +export type Week = InferSelectModel; +export type WeekInsert = InferInsertModel; +export type WeekUpdate = Partial; + +export const WeekInsertSchema = z.object({ + programId: z.number().int(), + label: z.string().max(80).optional(), + durationMinutes: z.number().int(), + deload: z.boolean().optional(), +}); + +export const WeekUpdateSchema = z.object({ + programId: z.number().int().optional(), + label: z.string().max(80).optional().nullable(), + durationMinutes: z.number().int().optional(), + deload: z.boolean().optional().nullable(), +}); + +/** + * Typed create shape for Week: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createWeek` call site; + * the schema still validates at runtime. + */ +export type WeekCreate = z.input; + +/** + * Typed patch shape for Week: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateWeek` call site. + */ +export type WeekPatch = z.input; + +/** + * Metadata constants for Week. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Week, WeekInsertSchema); + * + */ +export const Week = { + $entity: "Week", + $table: "weeks", + $path: "/weeks", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + programId: { + name: "programId", + label: "Program Id", + view: "number", + htmlType: "number", + rules: { required: "Program Id is required" }, + }, + label: { + name: "label", + label: "Label", + view: "text", + htmlType: "text", + rules: { maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, + }, + durationMinutes: { + name: "durationMinutes", + label: "Duration Minutes", + view: "number", + htmlType: "number", + rules: { required: "Duration Minutes is required" }, + }, + deload: { + name: "deload", + label: "Deload", + view: "checkbox", + htmlType: "checkbox", + }, +} as const; + +export type WeekFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: WeekFilter[]; + and?: WeekFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekLabel.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekLabel.ts new file mode 100644 index 0000000000..98ba4a8ea4 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekLabel.ts @@ -0,0 +1,28 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: WeekLabel (WeekLabel) +// Extend in your own module (e.g. WeekLabel.extra.ts) — nothing imports it for you. + +import { z } from "zod"; + +export interface WeekLabel { + label: string; +} + +export const WeekLabelInsertSchema = z.object({ + label: z.string().min(1).max(80), +}); + +/** + * Metadata constants for the value object WeekLabel: each field's name, label, view and the + * validation rules derived from its validator children (e.g. `WeekLabel..rules.maxLength.value`). + */ +export const WeekLabel = { + $entity: "WeekLabel", + label: { + name: "label", + label: "Label", + view: "text", + htmlType: "text", + rules: { required: "Label is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, + }, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.names.ts new file mode 100644 index 0000000000..16bbc3bef0 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.names.ts @@ -0,0 +1,22 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: WeekShapes + +export const WeekShapesNames = { + type: "object", + subType: "report", + name: "WeekShapes", + sources: { + primary: { type: "source", subType: "rdb", kind: "view", view: "v_week_shapes" }, + }, + fields: { + labelledMinutes: { name: "labelledMinutes", column: "labelled_minutes" }, + longWMinutes: { name: "longWMinutes", column: "long_w_minutes" }, + midWeeks: { name: "midWeeks", column: "mid_weeks" }, + programTitle: { name: "programTitle", column: "program_title" }, + shortWeeks: { name: "shortWeeks", column: "short_weeks" }, + unlabelled: { name: "unlabelled", column: "unlabelled" }, + weeks: { name: "weeks", column: "weeks" }, + }, + identities: {}, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.queries.ts new file mode 100644 index 0000000000..f10a0dd379 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.queries.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: WeekShapes (WeekShapes) — report (read-only) +// Extend in your own module (e.g. WeekShapes.extra.ts) — nothing imports it for you. + +import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; +import { type WeekShapes, weekShapesView } from "./WeekShapes.js"; + +type Db = PgDatabase>; + +export async function listWeekShapes(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(weekShapesView).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.ts new file mode 100644 index 0000000000..bd221cff2c --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.ts @@ -0,0 +1,58 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: WeekShapes (WeekShapes) + +import { bigint, pgView, varchar } from "drizzle-orm/pg-core"; +import { z } from "zod"; + +// View declaration — Drizzle uses this for typed SELECT queries. +// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle +// not to attempt DDL for this declaration. +export const weekShapesView = pgView("v_week_shapes", { + programTitle: varchar("program_title", { length: 200 }).notNull(), + weeks: bigint("weeks", { mode: "number" }).notNull(), + unlabelled: bigint("unlabelled", { mode: "number" }).notNull(), + labelledMinutes: bigint("labelled_minutes", { mode: "number" }), + shortWeeks: bigint("short_weeks", { mode: "number" }).notNull(), + midWeeks: bigint("mid_weeks", { mode: "number" }).notNull(), + longWMinutes: bigint("long_w_minutes", { mode: "number" }), +}).existing(); + +export const WeekShapesSchema = z.object({ + programTitle: z.string(), + weeks: z.number().int(), + unlabelled: z.number().int(), + labelledMinutes: z.number().int().nullable(), + shortWeeks: z.number().int(), + midWeeks: z.number().int(), + longWMinutes: z.number().int().nullable(), +}); + +export type WeekShapes = z.infer; + +export const WeekShapes = { + $entity: "WeekShapes", + $view: "v_week_shapes", + $path: "/week_shapes", + programTitle: { name: "programTitle", label: "Program Title", view: "text", dbCol: "program_title" }, + weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, + unlabelled: { name: "unlabelled", label: "Unlabelled", view: "number", dbCol: "unlabelled" }, + labelledMinutes: { name: "labelledMinutes", label: "Labelled Minutes", view: "number", dbCol: "labelled_minutes" }, + shortWeeks: { name: "shortWeeks", label: "Short Weeks", view: "number", dbCol: "short_weeks" }, + midWeeks: { name: "midWeeks", label: "Mid Weeks", view: "number", dbCol: "mid_weeks" }, + longWMinutes: { name: "longWMinutes", label: "Long WMinutes", view: "number", dbCol: "long_w_minutes" }, +} as const; + +export type WeekShapesFilter = { + limit?: number; + offset?: number; + sort?: `${"programTitle" | "weeks" | "unlabelled" | "labelledMinutes" | "shortWeeks" | "midWeeks" | "longWMinutes"}:${"asc" | "desc"}` | "programTitle" | "weeks" | "unlabelled" | "labelledMinutes" | "shortWeeks" | "midWeeks" | "longWMinutes"; + programTitle?: string | { eq?: string; ne?: string; in?: string[]; like?: string; isNull?: boolean }; + weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + unlabelled?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + labelledMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + shortWeeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + midWeeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + longWMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; + or?: WeekShapesFilter[]; + and?: WeekShapesFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.extractor.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.extractor.ts new file mode 100644 index 0000000000..4d899beb2b --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.extractor.ts @@ -0,0 +1,45 @@ +// GENERATED — extractor for "coachNote". +// +// Turns dirty LLM text into a fully-typed `ProgramVerdict` graph (nested objects + +// arrays-of-objects populated) in one call, by delegating to the nested-capable extract and +// mapping the all-nullable mirror onto the strict payload. No registry / binding / factory. + +import type { MetaRoot } from "@metaobjectsdev/metadata"; +import type { ExtractionResult } from "@metaobjectsdev/render"; +import type { ProgramVerdict, ProgramVerdictVerdict } from "./ProgramVerdict.js"; +import { type ProgramVerdictExtracted, extractLenientCoachNoteWithLoader } from "./coachNote.response.js"; + +/** + * Extract a fully-typed `ProgramVerdict` from dirty `text` using the loaded `root` (which must + * declare the "ProgramVerdict" payload value-object). Runs the tolerant extract, then maps the + * extracted mirror onto the strict payload. + * + * @throws Error iff a `@required` field was lost, or was present but unusable (MALFORMED — + * an undeclared enum member, text where a number belongs): the strict opt-in gate. + */ +export function extractCoachNote(root: MetaRoot, text: string): ProgramVerdict { + const r = extractLenientCoachNoteWithLoader(root, text); + if (r.report.hasLostRequired() || r.report.hasMalformedRequired()) { + const unusable: string[] = []; + if (r.report.hasLostRequired()) unusable.push("lost required field(s): " + r.report.lostRequired().join(", ")); + if (r.report.hasMalformedRequired()) unusable.push("malformed required field(s): " + r.report.malformedRequired().join(", ")); + throw new Error("extractCoachNote: " + unusable.join("; ")); + } + return toStrictProgramVerdict(r.data!); +} + +/** + * Extract a `ProgramVerdict` from dirty `text` using the loaded `root`, never throwing. + * Re-exposes the nested-capable extract; inspect `report` for lost/malformed/defaulted fields. + */ +export function extractLenientCoachNote(root: MetaRoot, text: string): ExtractionResult { + return extractLenientCoachNoteWithLoader(root, text); +} + +/** Map the all-nullable `ProgramVerdictExtracted` mirror onto the strict `ProgramVerdict` payload. Generated. */ +function toStrictProgramVerdict(m: ProgramVerdictExtracted): ProgramVerdict { + return { + verdict: m.verdict! as ProgramVerdictVerdict, + rationale: m.rationale!, + }; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.response.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.response.ts new file mode 100644 index 0000000000..86b99de2ae --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.response.ts @@ -0,0 +1,103 @@ +import type { MetaRoot } from "@metaobjectsdev/metadata"; +import { type ExtractOptions, type ExtractionResult, Format } from "@metaobjectsdev/render"; +import { extractObject } from "@metaobjectsdev/runtime-ts"; +import { z } from "zod"; +import type { ProgramVerdict } from "./ProgramVerdict.js"; + +const CoachNoteSchema = z.object({ + verdict: z.enum(["GOOD", "OK", "POOR"]), + rationale: z.string(), +}); + +export type CoachNoteValidationError = z.ZodError; + +/** + * Parse an LLM response into a typed ProgramVerdict. The reply must BE the JSON document (a + * structured-output / JSON-mode reply); prose or a code fence around it fails. For a raw + * model reply use `extractLenientCoachNoteWithLoader`. + * @throws ZodError on validation failure. + */ +export function parseCoachNote(text: string): ProgramVerdict { + return CoachNoteSchema.parse(JSON.parse(text)); +} + +/** + * Parse an LLM response with explicit error handling (Result-style). + * Does not throw on validation failure. + */ +export function safeParseCoachNote( + text: string, +): { success: true; data: ProgramVerdict } | { success: false; error: CoachNoteValidationError } { + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch (err) { + return { + success: false, + error: new z.ZodError([{ code: "custom", path: [], message: `invalid JSON: ${(err as Error).message}` }]), + }; + } + const result = CoachNoteSchema.safeParse(parsed); + return result.success + ? { success: true, data: result.data } + : { success: false, error: result.error }; +} + +/** Payload value-object name this parser extracts — resolved against a loaded MetaRoot at runtime. */ +export const COACHNOTE_PAYLOAD_NAME = "ProgramVerdict"; + +/** Best-effort extracted twin of `ProgramVerdict` — every field nullable (null where lost/malformed). */ +export interface ProgramVerdictExtracted { + verdict: string | null; + rationale: string | null; +} + +/** Map an assembled ValueObject graph into a typed `ProgramVerdictExtracted` mirror. Generated; null-tolerant. */ +function fromProgramVerdictExtracted(o: unknown): ProgramVerdictExtracted | null { + if (o == null) return null; + return { + verdict: dlgString(readProp(o, "verdict")), + rationale: dlgString(readProp(o, "rationale")), + }; +} + +// ---- runtime-delegating extract helpers (generated) ---- + +/** Read a property from an assembled backing object, mirroring the MetaField getValue SPI. */ +function readProp(o: unknown, name: string): unknown { + if (o == null) return undefined; + const vo = o as { get?: (n: string) => unknown }; + if (typeof vo.get === "function") return vo.get(name); + return (o as Record)[name]; +} + +function dlgString(v: unknown): string | null { + return v == null ? null : String(v); +} + +/** + * Runtime-delegating tolerant best-effort extraction for a RAW model reply (prose, code + * fences, a truncated or mis-typed field): a bad reply never throws — each field is classified + * in `report` and `data` carries what was recovered (`orThrow` from the render package + * makes a lost @required field an error). Throws only when `root` does not declare the payload + * value object — a setup error, not a reply error. FULLY populates + * nested-object and array-of-object components by delegating to the metadata-driven runtime + * `extractObject` (which assembles the whole graph reflection-free via the Phase A object + * model, reading the live metadata directly), then maps the assembled graph into the typed + * `ProgramVerdictExtracted` mirror. + * + * @param root a loaded MetaRoot (e.g. `(await new MetaDataLoader().load(...)).root`) that declares + * the `ProgramVerdict` value-object. + */ +export function extractLenientCoachNoteWithLoader( + root: MetaRoot, + text: string, + opts?: Partial | null, +): ExtractionResult { + const mo = root.findObject(COACHNOTE_PAYLOAD_NAME); + if (mo === undefined) { + throw new Error(`extractLenientCoachNoteWithLoader: payload "${COACHNOTE_PAYLOAD_NAME}" not found in the supplied MetaRoot`); + } + const outcome = extractObject(mo, text, Format.JSON, opts); + return { data: fromProgramVerdictExtracted(outcome.data), report: outcome.report }; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.responseFormat.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.responseFormat.ts new file mode 100644 index 0000000000..977cdfd801 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.responseFormat.ts @@ -0,0 +1,20 @@ +import { + FieldKind, + Format, + type OutputFormatSpec, + type PromptOverrides, + PromptStyle, + renderOutputFormat, +} from "@metaobjectsdev/render"; + +const CoachNoteFormatSpec: OutputFormatSpec = { format: Format.JSON, rootName: "ProgramVerdict", style: PromptStyle.GUIDE, fields: [{ name: "verdict", kind: FieldKind.ENUM, required: true, array: false, enumValues: ["GOOD", "OK", "POOR"], enumDoc: null, example: null, instruction: null, nested: null }, { name: "rationale", kind: FieldKind.STRING, required: true, array: false, enumValues: null, enumDoc: null, example: null, instruction: null, nested: null }] } satisfies OutputFormatSpec; + +/** + * The response-format instruction fragment for the coachNote template.prompt + * ("produce your answer like this"). Comment-free — guidance lives in prose / + * inline placeholders / a filled skeleton. Pass `overrides` to override the style + * or per-field example/instruction at render time. + */ +export function renderCoachNoteFormat(overrides?: PromptOverrides): string { + return renderOutputFormat(CoachNoteFormatSpec, overrides ?? {}); +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/enums.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/enums.ts new file mode 100644 index 0000000000..00be4df9d6 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/enums.ts @@ -0,0 +1,7 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Shared enum types (FR-019): one declaration per reused package-level enum. + +import { z } from "zod"; + +export type PublishState = "DRAFT" | "PUBLISHED" | "ARCHIVED"; +export const PublishStateEnum = z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]); diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/index.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/index.ts new file mode 100644 index 0000000000..24785da990 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/index.ts @@ -0,0 +1,59 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +export * from "./AllTypes.js"; +export * from "./AllTypesBreakdown.js"; +export * from "./ArchivedLedgerEntry.js"; +export * from "./Asset.js"; +export * from "./AssetActivity.js"; +export * from "./AssetDays.js"; +export * from "./Auth.js"; +export * from "./AuthsByKind.js"; +export * from "./BridgeAuth.js"; +export * from "./CouponAuth.js"; +export * from "./Entry.js"; +export * from "./EntryTotals.js"; +export * from "./FitnessTotals.js"; +export * from "./FitnessTotalsFilled.js"; +export * from "./Follow.js"; +export * from "./Friendship.js"; +export * from "./Gadget.js"; +export * from "./GadgetEvent.js"; +export * from "./GadgetEventsByLabel.js"; +export * from "./IntEnumArray.js"; +export * from "./Label.js"; +export * from "./Labeled.js"; +export * from "./LedgerEntry.js"; +export * from "./LiveIntroPrograms.js"; +export * from "./Measurement.js"; +export * from "./MeasurementStats.js"; +export * from "./MeasurementStatsFilled.js"; +export * from "./Node.js"; +export * from "./NodesByParent.js"; +export * from "./PermitAuth.js"; +export * from "./Person.js"; +export * from "./Post.js"; +export * from "./PostReferral.js"; +export * from "./PostTag.js"; +export * from "./Program.js"; +export * from "./ProgramBrief.js"; +export * from "./ProgramFlagRoster.js"; +export * from "./ProgramFlags.js"; +export * from "./ProgramLongWeeks.js"; +export * from "./ProgramMinutes.js"; +export * from "./ProgramRoster.js"; +export * from "./ProgramsByMonth.js"; +export * from "./ProgramsByWeek.js"; +export * from "./ProgramsEmptyScope.js"; +export * from "./ProgramSessions.js"; +export * from "./ProgramsOverTime.js"; +export * from "./ProgramStat.js"; +export * from "./ProgramVerdict.js"; +export * from "./ProgramView.js"; +export * from "./RecentPrograms.js"; +export * from "./ReferralAuth.js"; +export * from "./Session.js"; +export * from "./SessionsByProgram.js"; +export * from "./Settings.js"; +export * from "./Tag.js"; +export * from "./Week.js"; +export * from "./WeekLabel.js"; +export * from "./WeekShapes.js"; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/package.json b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/package.json new file mode 100644 index 0000000000..7c34deb583 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/package.json @@ -0,0 +1 @@ +{"type":"module"} \ No newline at end of file diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/prompts.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/prompts.ts new file mode 100644 index 0000000000..ec13c286dd --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/prompts.ts @@ -0,0 +1,8 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. + +import { type Provider, render } from "@metaobjectsdev/render"; +import type { ProgramBrief } from "./ProgramBrief.js"; + +export function renderCoachNote(payload: ProgramBrief, provider: Provider): string { + return render({ ref: "fitness/coach-note", payload, format: "text", provider, verify: [{"name":"title"},{"name":"weekCount"},{"name":"weekLabels","fields":[{"name":"label"}],"isArray":true}] }); +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.queries.ts new file mode 100644 index 0000000000..0bd045862b --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.queries.ts @@ -0,0 +1,56 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: WorkItem (WorkItem) +// Extend in your own module (e.g. WorkItem.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; +import type { z } from "zod"; +import { + type WorkItem, + WorkItemInsertSchema, + type WorkItemPatch, + WorkItemUpdateSchema, + workItems, +} from "./WorkItem.js"; + +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; + +export async function findWorkItemById(db: Db, id: number): Promise { + const [workItem] = await db.select().from(workItems).where(eq(workItems.id, id)).limit(1); + return workItem ?? null; +} + +export async function listWorkItems(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(workItems).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createWorkItem(db: Db, data: z.input): Promise { + const validated = WorkItemInsertSchema.parse(data); + const [workItem] = await db.insert(workItems).values(validated).returning(); + return workItem!; +} + +export async function updateWorkItem(db: Db, id: number, patch: WorkItemPatch): Promise { + const validated = WorkItemUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findWorkItemById(db, id); + } + const [workItem] = await db.update(workItems).set(validated).where(eq(workItems.id, id)).returning(); + return workItem ?? null; +} + +export async function deleteWorkItemById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(workItems).where(eq(workItems.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.ts b/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.ts new file mode 100644 index 0000000000..1e59f0a338 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.ts @@ -0,0 +1,86 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: WorkItem (WorkItem) +// Extend in your own module (e.g. WorkItem.extra.ts) — nothing imports it for you. + +import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; +import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; +import { z } from "zod"; + +export const workItems = sqliteTable("work_item", { + id: integer("id").primaryKey({ autoIncrement: true }), + title: text("title").notNull(), +}); + +export type WorkItem = InferSelectModel; +export type WorkItemInsert = InferInsertModel; +export type WorkItemUpdate = Partial; + +export const WorkItemInsertSchema = z.object({ + title: z.string().min(1), +}); + +export const WorkItemUpdateSchema = z.object({ + title: z.string().min(1).optional(), +}); + +/** + * Typed create shape for WorkItem: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createWorkItem` call site; + * the schema still validates at runtime. + */ +export type WorkItemCreate = z.input; + +/** + * Typed patch shape for WorkItem: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateWorkItem` call site. + */ +export type WorkItemPatch = z.input; + +/** + * Metadata constants for WorkItem. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(WorkItem, WorkItemInsertSchema); + * + */ +export const WorkItem = { + $entity: "WorkItem", + $table: "work_item", + $path: "/work_items", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + title: { + name: "title", + label: "Title", + view: "text", + htmlType: "text", + rules: { required: "Title is required" }, + }, +} as const; + +export type WorkItemFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: WorkItemFilter[]; + and?: WorkItemFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/consumer.ts b/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/consumer.ts new file mode 100644 index 0000000000..803e8f0b08 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/consumer.ts @@ -0,0 +1,12 @@ +import { drizzle } from "drizzle-orm/sqlite-proxy"; +import * as schema from "./WorkItem"; +import { findWorkItemById, listWorkItems } from "./WorkItem.queries"; + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +const callback = async () => ({ rows: [] as never[] }); + +export const db = drizzle(callback, { schema }); + +export const one = await findWorkItemById(db, 1); +export const many = await listWorkItems(db, { limit: 10 }); +// `schema` is referenced above; keep the namespace import load-bearing. diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.names.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.names.ts new file mode 100644 index 0000000000..99a0df1b33 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.names.ts @@ -0,0 +1,23 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Broker + +import { PartyNames } from "./Party.names"; + +export const BrokerNames = { + type: "object", + subType: "entity", + name: "Broker", + sources: { + ...PartyNames.sources, + }, + fields: { + ...PartyNames.fields, + mcNumber: { name: "mcNumber", column: "mc_number" }, + }, + identities: { + ...PartyNames.identities, + }, + indexes: { + ...PartyNames.indexes, + }, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.ts new file mode 100644 index 0000000000..ff45aaa541 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.ts @@ -0,0 +1,103 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Broker (Broker) +// Extend in your own module (e.g. Broker.extra.ts) — nothing imports it for you. + +import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; +import { z } from "zod"; +import { BrokerNames } from "./Broker.names.js"; + +export interface Broker { + id?: number | undefined; + partyType?: BrokerPartyType | null | undefined; + mcNumber?: string | null | undefined; +} + +export type BrokerPartyType = "Carrier" | "Broker"; +export const BrokerPartyTypeEnum = z.enum(["Carrier", "Broker"]); + +export const BrokerSchema = z.object({ + id: z.number().int(), + partyType: z.literal("Broker"), + mcNumber: z.string().max(20).nullable(), +}); + +export const BrokerInsertSchema = z.object({ + partyType: z.literal("Broker"), + mcNumber: z.string().max(20).optional(), +}); + +export const BrokerUpdateSchema = z.object({ + mcNumber: z.string().max(20).optional().nullable(), +}); + +/** + * Typed create shape for Broker: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createBroker` call site; + * the schema still validates at runtime. + */ +export type BrokerCreate = z.input; + +/** + * Typed patch shape for Broker: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateBroker` call site. + */ +export type BrokerPatch = z.input; + +/** + * Metadata constants for Broker. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Broker, BrokerInsertSchema); + * + */ +export const Broker = { + $entity: "Broker", + $table: BrokerNames.sources.primary.table, + $path: "/parties/broker", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + partyType: { + name: "partyType", + label: "Party Type", + view: "dropdown", + options: ["Carrier", "Broker"] as const, + }, + mcNumber: { + name: "mcNumber", + label: "Mc Number", + view: "text", + htmlType: "text", + rules: { maxLength: { value: 20, message: "Must be 20 characters or fewer" } }, + }, +} as const; + +export const BrokerFilterAllowlist = {} as const satisfies FilterAllowlist; + +export const BrokerSortAllowlist = {} as const satisfies SortAllowlist; + +export type BrokerFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: BrokerFilter[]; + and?: BrokerFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.names.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.names.ts new file mode 100644 index 0000000000..a4dd94d375 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.names.ts @@ -0,0 +1,24 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Carrier + +import { OrganizationNames } from "./Organization.names"; + +export const CarrierNames = { + type: "object", + subType: "entity", + name: "Carrier", + sources: { + ...OrganizationNames.sources, + }, + fields: { + ...OrganizationNames.fields, + homeDepotId: { name: "homeDepotId", column: "home_depot_id" }, + }, + identities: { + ...OrganizationNames.identities, + fkHomeDepot: { type: "identity", subType: "reference", name: "fkHomeDepot" }, + }, + indexes: { + ...OrganizationNames.indexes, + }, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.ts new file mode 100644 index 0000000000..a9bbbfd3f7 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.ts @@ -0,0 +1,112 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Carrier (Carrier) +// Extend in your own module (e.g. Carrier.extra.ts) — nothing imports it for you. + +import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; +import { z } from "zod"; +import { CarrierNames } from "./Carrier.names.js"; + +export interface Carrier { + id?: number | undefined; + partyType?: CarrierPartyType | null | undefined; + hqDepotId?: number | null | undefined; + homeDepotId?: number | null | undefined; +} + +export type CarrierPartyType = "Carrier" | "Broker"; +export const CarrierPartyTypeEnum = z.enum(["Carrier", "Broker"]); + +export const CarrierSchema = z.object({ + id: z.number().int(), + partyType: z.literal("Carrier"), + hqDepotId: z.number().int().nullable(), + homeDepotId: z.number().int().nullable(), +}); + +export const CarrierInsertSchema = z.object({ + partyType: z.literal("Carrier"), + hqDepotId: z.number().int().optional(), + homeDepotId: z.number().int().optional(), +}); + +export const CarrierUpdateSchema = z.object({ + hqDepotId: z.number().int().optional().nullable(), + homeDepotId: z.number().int().optional().nullable(), +}); + +/** + * Typed create shape for Carrier: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createCarrier` call site; + * the schema still validates at runtime. + */ +export type CarrierCreate = z.input; + +/** + * Typed patch shape for Carrier: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateCarrier` call site. + */ +export type CarrierPatch = z.input; + +/** + * Metadata constants for Carrier. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Carrier, CarrierInsertSchema); + * + */ +export const Carrier = { + $entity: "Carrier", + $table: CarrierNames.sources.primary.table, + $path: "/parties/carrier", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + partyType: { + name: "partyType", + label: "Party Type", + view: "dropdown", + options: ["Carrier", "Broker"] as const, + }, + hqDepotId: { + name: "hqDepotId", + label: "Hq Depot Id", + view: "number", + htmlType: "number", + }, + homeDepotId: { + name: "homeDepotId", + label: "Home Depot Id", + view: "number", + htmlType: "number", + }, +} as const; + +export const CarrierFilterAllowlist = {} as const satisfies FilterAllowlist; + +export const CarrierSortAllowlist = {} as const satisfies SortAllowlist; + +export type CarrierFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: CarrierFilter[]; + and?: CarrierFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.names.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.names.ts new file mode 100644 index 0000000000..738bb586b0 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.names.ts @@ -0,0 +1,18 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Depot + +export const DepotNames = { + type: "object", + subType: "entity", + name: "Depot", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "depots" }, + }, + fields: { + id: { name: "id", column: "id" }, + }, + identities: { + pk: { type: "identity", subType: "primary", name: "pk" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.queries.ts new file mode 100644 index 0000000000..2a32c4f2ad --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.queries.ts @@ -0,0 +1,50 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Depot (Depot) +// Extend in your own module (e.g. Depot.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; +import type { z } from "zod"; +import { type Depot, DepotInsertSchema, type DepotPatch, DepotUpdateSchema, depots } from "./Depot.js"; + +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; + +export async function findDepotById(db: Db, id: number): Promise { + const [depot] = await db.select().from(depots).where(eq(depots.id, id)).limit(1); + return depot ?? null; +} + +export async function listDepots(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(depots).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createDepot(db: Db, data: z.input): Promise { + const validated = DepotInsertSchema.parse(data); + const [depot] = await db.insert(depots).values(validated).returning(); + return depot!; +} + +export async function updateDepot(db: Db, id: number, patch: DepotPatch): Promise { + const validated = DepotUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findDepotById(db, id); + } + const [depot] = await db.update(depots).set(validated).where(eq(depots.id, id)).returning(); + return depot ?? null; +} + +export async function deleteDepotById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(depots).where(eq(depots.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.ts new file mode 100644 index 0000000000..889457300c --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.ts @@ -0,0 +1,80 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Depot (Depot) +// Extend in your own module (e.g. Depot.extra.ts) — nothing imports it for you. + +import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; +import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; +import { integer, sqliteTable } from "drizzle-orm/sqlite-core"; +import { z } from "zod"; +import { DepotNames } from "./Depot.names.js"; + +export const depots = sqliteTable(DepotNames.sources.primary.table, { + id: integer(DepotNames.fields.id.column).primaryKey({ autoIncrement: true }), +}); + +export type Depot = InferSelectModel; +export type DepotInsert = InferInsertModel; +export type DepotUpdate = Partial; + +export const DepotInsertSchema = z.object({}); + +export const DepotUpdateSchema = z.object({}); + +/** + * Typed create shape for Depot: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createDepot` call site; + * the schema still validates at runtime. + */ +export type DepotCreate = z.input; + +/** + * Typed patch shape for Depot: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateDepot` call site. + */ +export type DepotPatch = z.input; + +/** + * Metadata constants for Depot. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Depot, DepotInsertSchema); + * + */ +export const Depot = { + $entity: "Depot", + $table: DepotNames.sources.primary.table, + $path: "/depots", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, +} as const; + +export const DepotFilterAllowlist = {} as const satisfies FilterAllowlist; + +export const DepotSortAllowlist = {} as const satisfies SortAllowlist; + +export type DepotFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: DepotFilter[]; + and?: DepotFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.names.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.names.ts new file mode 100644 index 0000000000..252e7039cd --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.names.ts @@ -0,0 +1,22 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Leg + +export const LegNames = { + type: "object", + subType: "entity", + name: "Leg", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "legs" }, + }, + fields: { + carrierId: { name: "carrierId", column: "carrier_id" }, + id: { name: "id", column: "id" }, + shipmentId: { name: "shipmentId", column: "shipment_id" }, + }, + identities: { + fkCarrier: { type: "identity", subType: "reference", name: "fkCarrier" }, + fkShipment: { type: "identity", subType: "reference", name: "fkShipment" }, + pk: { type: "identity", subType: "primary", name: "pk" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.queries.ts new file mode 100644 index 0000000000..8b1534c9e1 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.queries.ts @@ -0,0 +1,72 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Leg (Leg) +// Extend in your own module (e.g. Leg.extra.ts) — nothing imports it for you. + +import { eq, inArray } from "drizzle-orm"; +import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; +import type { z } from "zod"; +import { type Leg, LegInsertSchema, type LegPatch, LegUpdateSchema, legs } from "./Leg.js"; + +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; + +export async function findLegById(db: Db, id: number): Promise { + const [leg] = await db.select().from(legs).where(eq(legs.id, id)).limit(1); + return leg ?? null; +} + +export async function listLegs(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(legs).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createLeg(db: Db, data: z.input): Promise { + const validated = LegInsertSchema.parse(data); + const [leg] = await db.insert(legs).values(validated).returning(); + return leg!; +} + +export async function updateLeg(db: Db, id: number, patch: LegPatch): Promise { + const validated = LegUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findLegById(db, id); + } + const [leg] = await db.update(legs).set(validated).where(eq(legs.id, id)).returning(); + return leg ?? null; +} + +export async function deleteLegById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(legs).where(eq(legs.id, id)).returning(); + return deleted.length > 0; +} + +export async function findLegsByShipment(db: Db, shipmentId: number): Promise { + return db.select().from(legs).where(eq(legs.shipmentId, shipmentId)); +} + +export async function findLegsByShipmentIn(db: Db, shipmentIds: number[]): Promise { + if (shipmentIds.length === 0) { + return []; + } + return db.select().from(legs).where(inArray(legs.shipmentId, shipmentIds)); +} + +export async function findLegsByCarrier(db: Db, carrierId: number): Promise { + return db.select().from(legs).where(eq(legs.carrierId, carrierId)); +} + +export async function findLegsByCarrierIn(db: Db, carrierIds: number[]): Promise { + if (carrierIds.length === 0) { + return []; + } + return db.select().from(legs).where(inArray(legs.carrierId, carrierIds)); +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.ts new file mode 100644 index 0000000000..7aaa547ee3 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.ts @@ -0,0 +1,110 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Leg (Leg) +// Extend in your own module (e.g. Leg.extra.ts) — nothing imports it for you. + +import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnySQLiteColumn, integer, sqliteTable } from "drizzle-orm/sqlite-core"; +import { z } from "zod"; +import { LegNames } from "./Leg.names.js"; +import { parties } from "./Party.js"; +import { shipments } from "./Shipment.js"; + +export const legs = sqliteTable(LegNames.sources.primary.table, { + id: integer(LegNames.fields.id.column).primaryKey({ autoIncrement: true }), + shipmentId: integer(LegNames.fields.shipmentId.column).notNull().references((): AnySQLiteColumn => shipments.id), + carrierId: integer(LegNames.fields.carrierId.column).notNull().references((): AnySQLiteColumn => parties.id), +}); + +export const legsRelations = relations(legs, ({ one }) => ({ + carrier: one(parties, { fields: [legs.carrierId], references: [parties.id] }), + fkShipment: one(shipments, { fields: [legs.shipmentId], references: [shipments.id] }), + fkCarrier: one(parties, { fields: [legs.carrierId], references: [parties.id] }), +})); + +export type Leg = InferSelectModel; +export type LegInsert = InferInsertModel; +export type LegUpdate = Partial; + +export const LegInsertSchema = z.object({ + shipmentId: z.number().int(), + carrierId: z.number().int(), +}); + +export const LegUpdateSchema = z.object({ + shipmentId: z.number().int().optional(), + carrierId: z.number().int().optional(), +}); + +/** + * Typed create shape for Leg: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createLeg` call site; + * the schema still validates at runtime. + */ +export type LegCreate = z.input; + +/** + * Typed patch shape for Leg: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateLeg` call site. + */ +export type LegPatch = z.input; + +/** + * Metadata constants for Leg. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Leg, LegInsertSchema); + * + */ +export const Leg = { + $entity: "Leg", + $table: LegNames.sources.primary.table, + $path: "/legs", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + shipmentId: { + name: "shipmentId", + label: "Shipment Id", + view: "number", + htmlType: "number", + rules: { required: "Shipment Id is required" }, + }, + carrierId: { + name: "carrierId", + label: "Carrier Id", + view: "number", + htmlType: "number", + rules: { required: "Carrier Id is required" }, + }, +} as const; + +export const LegFilterAllowlist = {} as const satisfies FilterAllowlist; + +export const LegSortAllowlist = {} as const satisfies SortAllowlist; + +export type LegFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: LegFilter[]; + and?: LegFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.names.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.names.ts new file mode 100644 index 0000000000..18b9f52811 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.names.ts @@ -0,0 +1,24 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Organization + +import { PartyNames } from "./Party.names"; + +export const OrganizationNames = { + type: "object", + subType: "entity", + name: "Organization", + sources: { + ...PartyNames.sources, + }, + fields: { + ...PartyNames.fields, + hqDepotId: { name: "hqDepotId", column: "hq_depot_id" }, + }, + identities: { + ...PartyNames.identities, + fkHqDepot: { type: "identity", subType: "reference", name: "fkHqDepot" }, + }, + indexes: { + ...PartyNames.indexes, + }, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.ts new file mode 100644 index 0000000000..bd588c7c22 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Organization (Organization) +// Extend in your own module (e.g. Organization.extra.ts) — nothing imports it for you. + +import { z } from "zod"; + +export interface Organization { + id?: number | undefined; + partyType?: OrganizationPartyType | undefined; + hqDepotId?: number | undefined; +} + +export type OrganizationPartyType = "Carrier" | "Broker"; +export const OrganizationPartyTypeEnum = z.enum(["Carrier", "Broker"]); + +export const OrganizationInsertSchema = z.object({ + partyType: z.enum(["Carrier", "Broker"]).optional(), + hqDepotId: z.number().int().optional(), +}); diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.names.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.names.ts new file mode 100644 index 0000000000..2b664d73fb --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.names.ts @@ -0,0 +1,19 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Party + +export const PartyNames = { + type: "object", + subType: "entity", + name: "Party", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "parties" }, + }, + fields: { + id: { name: "id", column: "id" }, + partyType: { name: "partyType", column: "party_type" }, + }, + identities: { + pk: { type: "identity", subType: "primary", name: "pk" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.queries.ts new file mode 100644 index 0000000000..ff7615bd07 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.queries.ts @@ -0,0 +1,101 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Party (Party) — TPH discriminator base +// Extend in your own module (e.g. Party.extra.ts) — nothing imports it for you. + +import { and, eq } from "drizzle-orm"; +import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; +import type { z } from "zod"; +import { type Broker, BrokerInsertSchema, BrokerSchema } from "./Broker.js"; +import { type Carrier, CarrierInsertSchema, CarrierSchema } from "./Carrier.js"; +import { type Party, parseParty, parties } from "./Party.js"; + +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; + +export async function findPartyById(db: Db, id: number): Promise { + const [row] = await db.select().from(parties).where(eq(parties.id, id)).limit(1); + return row ? parseParty(row) : null; +} + +export async function listParties(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(parties).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + const rows = await q; + return rows.map((r) => parseParty(r)); +} + +export async function listBrokers(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(parties).where(eq(parties.partyType, "Broker")).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + const rows = await q; + return rows.map((r) => BrokerSchema.parse(r)); +} + +export async function findBrokerById(db: Db, id: number): Promise { + const [row] = await db.select().from(parties).where(and(eq(parties.id, id), eq(parties.partyType, "Broker"))).limit(1); + return row ? BrokerSchema.parse(row) : null; +} + +export async function createBroker(db: Db, data: z.input): Promise { + const validated = BrokerInsertSchema.parse(data); + const [row] = await db.insert(parties).values({ ...validated, partyType: "Broker" }).returning(); + return BrokerSchema.parse(row!); +} + +export async function updateBrokerById(db: Db, id: number, data: Partial>): Promise { + const validated = BrokerInsertSchema.partial().parse(data) as Record; + // The discriminator is immutable — a Broker can never become another subtype. + const { ["partyType"]: _disc, ...safe } = validated; + const [row] = await db.update(parties).set(safe).where(and(eq(parties.id, id), eq(parties.partyType, "Broker"))).returning(); + return row ? BrokerSchema.parse(row) : null; +} + +export async function deleteBrokerById(db: Db, id: number): Promise { + const deleted = await db.delete(parties).where(and(eq(parties.id, id), eq(parties.partyType, "Broker"))).returning(); + return deleted.length > 0; +} + +export async function listCarriers(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(parties).where(eq(parties.partyType, "Carrier")).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + const rows = await q; + return rows.map((r) => CarrierSchema.parse(r)); +} + +export async function findCarrierById(db: Db, id: number): Promise { + const [row] = await db.select().from(parties).where(and(eq(parties.id, id), eq(parties.partyType, "Carrier"))).limit(1); + return row ? CarrierSchema.parse(row) : null; +} + +export async function createCarrier(db: Db, data: z.input): Promise { + const validated = CarrierInsertSchema.parse(data); + const [row] = await db.insert(parties).values({ ...validated, partyType: "Carrier" }).returning(); + return CarrierSchema.parse(row!); +} + +export async function updateCarrierById(db: Db, id: number, data: Partial>): Promise { + const validated = CarrierInsertSchema.partial().parse(data) as Record; + // The discriminator is immutable — a Carrier can never become another subtype. + const { ["partyType"]: _disc, ...safe } = validated; + const [row] = await db.update(parties).set(safe).where(and(eq(parties.id, id), eq(parties.partyType, "Carrier"))).returning(); + return row ? CarrierSchema.parse(row) : null; +} + +export async function deleteCarrierById(db: Db, id: number): Promise { + const deleted = await db.delete(parties).where(and(eq(parties.id, id), eq(parties.partyType, "Carrier"))).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.ts new file mode 100644 index 0000000000..4f2d8abe6c --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.ts @@ -0,0 +1,130 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Party (Party) +// Extend in your own module (e.g. Party.extra.ts) — nothing imports it for you. + +import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; +import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; +import { type AnySQLiteColumn, check, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; +import { z } from "zod"; +import { type Broker, BrokerSchema } from "./Broker.js"; +import { BrokerNames } from "./Broker.names.js"; +import { type Carrier, CarrierSchema } from "./Carrier.js"; +import { CarrierNames } from "./Carrier.names.js"; +import { depots } from "./Depot.js"; +import { OrganizationNames } from "./Organization.names.js"; +import { PartyNames } from "./Party.names.js"; + +export const parties = sqliteTable(PartyNames.sources.primary.table, { + id: integer(PartyNames.fields.id.column).primaryKey({ autoIncrement: true }), + partyType: text(PartyNames.fields.partyType.column, { enum: ["Carrier", "Broker"] as const }), + mcNumber: text(BrokerNames.fields.mcNumber.column), + hqDepotId: integer(OrganizationNames.fields.hqDepotId.column).references((): AnySQLiteColumn => depots.id), + homeDepotId: integer(CarrierNames.fields.homeDepotId.column).references((): AnySQLiteColumn => depots.id), +}, (table) => [ + check(`${PartyNames.sources.primary.table}_${PartyNames.fields.partyType.column}_chk`, sql`${sql.raw(PartyNames.fields.partyType.column)} IN ('Carrier', 'Broker')`), +]); + +export type PartyRow = InferSelectModel; +export type PartyInsert = InferInsertModel; +export type PartyUpdate = Partial; + +export type PartyPartyType = "Carrier" | "Broker"; +export const PartyPartyTypeEnum = z.enum(["Carrier", "Broker"]); + +export const PartyInsertSchema = z.object({ + partyType: z.enum(["Carrier", "Broker"]).optional(), +}); + +export const PartyUpdateSchema = z.object({ + partyType: z.enum(["Carrier", "Broker"]).optional().nullable(), +}); + +/** + * Typed create shape for Party: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createParty` call site; + * the schema still validates at runtime. + */ +export type PartyCreate = z.input; + +/** + * Typed patch shape for Party: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateParty` call site. + */ +export type PartyPatch = z.input; + +/** + * Metadata constants for Party. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Party, PartyInsertSchema); + * + */ +export const Party = { + $entity: "Party", + $table: PartyNames.sources.primary.table, + $path: "/parties", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, + partyType: { + name: "partyType", + label: "Party Type", + view: "dropdown", + options: ["Carrier", "Broker"] as const, + }, +} as const; + +export const PartyFilterAllowlist = {} as const satisfies FilterAllowlist; + +export const PartySortAllowlist = {} as const satisfies SortAllowlist; + +export type PartyFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: PartyFilter[]; + and?: PartyFilter[]; +}; + +export type Party = Broker | Carrier; + +/** True when value is a Broker (discriminated by partyType === "Broker"). */ +export function isBroker(value: Party): value is Broker { + return value.partyType === "Broker"; +} + +/** True when value is a Carrier (discriminated by partyType === "Carrier"). */ +export function isCarrier(value: Party): value is Carrier { + return value.partyType === "Carrier"; +} + +/** + * Parse a row from the Party table, dispatching by the + * `partyType` discriminator value to the matching subtype's + * Zod schema. Throws on unknown discriminator values. + */ +export function parseParty(row: unknown): Party { + const head = z.object({ partyType: z.enum(["Broker", "Carrier"]) }).parse(row); + switch (head.partyType) { + case "Broker": return BrokerSchema.parse(row); + case "Carrier": return CarrierSchema.parse(row); + } +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.names.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.names.ts new file mode 100644 index 0000000000..0a9f4af871 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.names.ts @@ -0,0 +1,18 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Shipment + +export const ShipmentNames = { + type: "object", + subType: "entity", + name: "Shipment", + sources: { + primary: { type: "source", subType: "rdb", kind: "table", table: "shipments" }, + }, + fields: { + id: { name: "id", column: "id" }, + }, + identities: { + pk: { type: "identity", subType: "primary", name: "pk" }, + }, + indexes: {}, +} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.queries.ts new file mode 100644 index 0000000000..058c2a82fb --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.queries.ts @@ -0,0 +1,56 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Shipment (Shipment) +// Extend in your own module (e.g. Shipment.extra.ts) — nothing imports it for you. + +import { eq } from "drizzle-orm"; +import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; +import type { z } from "zod"; +import { + type Shipment, + ShipmentInsertSchema, + type ShipmentPatch, + ShipmentUpdateSchema, + shipments, +} from "./Shipment.js"; + +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; + +export async function findShipmentById(db: Db, id: number): Promise { + const [shipment] = await db.select().from(shipments).where(eq(shipments.id, id)).limit(1); + return shipment ?? null; +} + +export async function listShipments(db: Db, opts?: { limit?: number; offset?: number }): Promise { + let q = db.select().from(shipments).$dynamic(); + if (opts?.limit !== undefined) { + q = q.limit(opts.limit); + } + if (opts?.offset !== undefined) { + q = q.offset(opts.offset); + } + return q; +} + +export async function createShipment(db: Db, data: z.input): Promise { + const validated = ShipmentInsertSchema.parse(data); + const [shipment] = await db.insert(shipments).values(validated).returning(); + return shipment!; +} + +export async function updateShipment(db: Db, id: number, patch: ShipmentPatch): Promise { + const validated = ShipmentUpdateSchema.parse(patch); + // PATCH-5: an empty patch is a no-op — return the current row rather than let + // Drizzle throw on an empty SET clause. + if (Object.keys(validated).length === 0) { + return findShipmentById(db, id); + } + const [shipment] = await db.update(shipments).set(validated).where(eq(shipments.id, id)).returning(); + return shipment ?? null; +} + +export async function deleteShipmentById(db: Db, id: number): Promise { + // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) + // and Postgres. Result is an array of deleted rows; presence implies success. + const deleted = await db.delete(shipments).where(eq(shipments.id, id)).returning(); + return deleted.length > 0; +} diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.ts new file mode 100644 index 0000000000..fb10eb0dc1 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.ts @@ -0,0 +1,85 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Source metadata: Shipment (Shipment) +// Extend in your own module (e.g. Shipment.extra.ts) — nothing imports it for you. + +import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { integer, sqliteTable } from "drizzle-orm/sqlite-core"; +import { z } from "zod"; +import { legs } from "./Leg.js"; +import { ShipmentNames } from "./Shipment.names.js"; + +export const shipments = sqliteTable(ShipmentNames.sources.primary.table, { + id: integer(ShipmentNames.fields.id.column).primaryKey({ autoIncrement: true }), +}); + +export const shipmentsRelations = relations(shipments, ({ many }) => ({ + carriers: many(legs), +})); + +export type Shipment = InferSelectModel; +export type ShipmentInsert = InferInsertModel; +export type ShipmentUpdate = Partial; + +export const ShipmentInsertSchema = z.object({}); + +export const ShipmentUpdateSchema = z.object({}); + +/** + * Typed create shape for Shipment: the insert schema's INPUT (pre-transform) type. A + * renamed/dropped/misspelt field is a compile error at every `createShipment` call site; + * the schema still validates at runtime. + */ +export type ShipmentCreate = z.input; + +/** + * Typed patch shape for Shipment: every settable field, optional (FR-035 PATCH). A + * renamed/dropped field is a compile error at every `updateShipment` call site. + */ +export type ShipmentPatch = z.input; + +/** + * Metadata constants for Shipment. + * + * Use these instead of magic strings so TS catches typos and refactors stay + * coherent. Each non-dollar-prefixed key is a per-field object carrying + * name, label, view, an htmlType where the field's view maps to one, and the + * RHF-shaped validation rules derived from the field's validator children. + * + * placeholder and helpText are NOT emitted — no provider registers an attribute + * for them, so nothing here could derive one. (htmlType is emitted, but derived + * from the view subtype; the @htmlType override was removed for the same reason.) + * useEntityForm still honours placeholder if you add it: this file is generated, + * hand edits inside it survive regeneration through the three-way merge, and the + * consumers read this const rather than the metadata. That is the intended way + * to set it. + * + * Typical usage with the metaobjects React form helper: + * + * import { useEntityForm } from '@metaobjectsdev/react'; + * const form = useEntityForm(Shipment, ShipmentInsertSchema); + * + */ +export const Shipment = { + $entity: "Shipment", + $table: ShipmentNames.sources.primary.table, + $path: "/shipments", + id: { + name: "id", + label: "Id", + view: "number", + htmlType: "number", + }, +} as const; + +export const ShipmentFilterAllowlist = {} as const satisfies FilterAllowlist; + +export const ShipmentSortAllowlist = {} as const satisfies SortAllowlist; + +export type ShipmentFilter = { + limit?: number; + offset?: number; + sort?: string; + or?: ShipmentFilter[]; + and?: ShipmentFilter[]; +}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/index.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/index.ts new file mode 100644 index 0000000000..ade411d2f1 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/index.ts @@ -0,0 +1,8 @@ +// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +export * from "./Broker.js"; +export * from "./Carrier.js"; +export * from "./Depot.js"; +export * from "./Leg.js"; +export * from "./Organization.js"; +export * from "./Party.js"; +export * from "./Shipment.js"; From 54b1688e8a28ecefbf18943582a2d7a3113dc3a1 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 5 Dec 2026 02:41:40 -0500 Subject: [PATCH 09/10] no-mistakes(test): apply changes made during test validation --- server/rust/metaobjects/src/validate/rules.rs | 19 +- .../AllTypes.names.ts | 39 -- .../AllTypes.queries.ts | 50 -- .../AllTypes.ts | 552 ------------------ .../AllTypesBreakdown.names.ts | 26 - .../AllTypesBreakdown.queries.ts | 19 - .../AllTypesBreakdown.ts | 88 --- .../ArchivedLedgerEntry.names.ts | 19 - .../ArchivedLedgerEntry.queries.ts | 56 -- .../ArchivedLedgerEntry.ts | 86 --- .../Asset.names.ts | 25 - .../Asset.queries.ts | 50 -- .../Asset.ts | 164 ------ .../AssetActivity.names.ts | 18 - .../AssetActivity.queries.ts | 19 - .../AssetActivity.ts | 42 -- .../AssetDays.names.ts | 22 - .../AssetDays.queries.ts | 19 - .../AssetDays.ts | 58 -- .../Auth.names.ts | 20 - .../Auth.queries.ts | 175 ------ .../Auth.ts | 143 ----- .../AuthsByKind.names.ts | 18 - .../AuthsByKind.queries.ts | 19 - .../AuthsByKind.ts | 42 -- .../BridgeAuth.names.ts | 23 - .../BridgeAuth.ts | 113 ---- .../CouponAuth.names.ts | 23 - .../CouponAuth.ts | 151 ----- .../Entry.names.ts | 21 - .../Entry.queries.ts | 50 -- .../Entry.ts | 145 ----- .../EntryTotals.names.ts | 23 - .../EntryTotals.queries.ts | 19 - .../EntryTotals.ts | 62 -- .../FitnessTotals.names.ts | 18 - .../FitnessTotals.queries.ts | 19 - .../FitnessTotals.ts | 42 -- .../FitnessTotalsFilled.names.ts | 18 - .../FitnessTotalsFilled.queries.ts | 19 - .../FitnessTotalsFilled.ts | 42 -- .../Follow.names.ts | 21 - .../Follow.queries.ts | 72 --- .../Follow.ts | 92 --- .../Friendship.names.ts | 21 - .../Friendship.queries.ts | 78 --- .../Friendship.ts | 92 --- .../Gadget.names.ts | 23 - .../Gadget.queries.ts | 50 -- .../Gadget.ts | 86 --- .../GadgetEvent.names.ts | 20 - .../GadgetEvent.queries.ts | 67 --- .../GadgetEvent.ts | 87 --- .../GadgetEventsByLabel.names.ts | 17 - .../GadgetEventsByLabel.queries.ts | 19 - .../GadgetEventsByLabel.ts | 38 -- .../IntEnumArray.names.ts | 20 - .../IntEnumArray.queries.ts | 56 -- .../IntEnumArray.ts | 134 ----- .../Label.ts | 35 -- .../Labeled.names.ts | 17 - .../Labeled.ts | 14 - .../LedgerEntry.names.ts | 19 - .../LedgerEntry.queries.ts | 56 -- .../LedgerEntry.ts | 86 --- .../LiveIntroPrograms.names.ts | 19 - .../LiveIntroPrograms.queries.ts | 19 - .../LiveIntroPrograms.ts | 46 -- .../Measurement.names.ts | 21 - .../Measurement.queries.ts | 56 -- .../Measurement.ts | 147 ----- .../MeasurementStats.names.ts | 24 - .../MeasurementStats.queries.ts | 19 - .../MeasurementStats.ts | 66 --- .../MeasurementStatsFilled.names.ts | 18 - .../MeasurementStatsFilled.queries.ts | 19 - .../MeasurementStatsFilled.ts | 42 -- .../Node.names.ts | 21 - .../Node.queries.ts | 61 -- .../Node.ts | 95 --- .../NodesByParent.names.ts | 17 - .../NodesByParent.queries.ts | 19 - .../NodesByParent.ts | 38 -- .../PermitAuth.names.ts | 23 - .../PermitAuth.ts | 113 ---- .../Person.names.ts | 19 - .../Person.queries.ts | 50 -- .../Person.ts | 93 --- .../Post.names.ts | 19 - .../Post.queries.ts | 50 -- .../Post.ts | 93 --- .../PostReferral.names.ts | 21 - .../PostReferral.queries.ts | 78 --- .../PostReferral.ts | 93 --- .../PostTag.names.ts | 21 - .../PostTag.queries.ts | 72 --- .../PostTag.ts | 93 --- .../Program.names.ts | 25 - .../Program.queries.ts | 50 -- .../Program.ts | 124 ---- .../ProgramBrief.ts | 45 -- .../ProgramFlagRoster.names.ts | 20 - .../ProgramFlagRoster.queries.ts | 19 - .../ProgramFlagRoster.ts | 50 -- .../ProgramFlags.names.ts | 20 - .../ProgramFlags.queries.ts | 19 - .../ProgramFlags.ts | 50 -- .../ProgramLongWeeks.names.ts | 18 - .../ProgramLongWeeks.queries.ts | 19 - .../ProgramLongWeeks.ts | 42 -- .../ProgramMinutes.names.ts | 26 - .../ProgramMinutes.queries.ts | 19 - .../ProgramMinutes.ts | 74 --- .../ProgramRoster.names.ts | 22 - .../ProgramRoster.queries.ts | 19 - .../ProgramRoster.ts | 58 -- .../ProgramSessions.names.ts | 20 - .../ProgramSessions.queries.ts | 19 - .../ProgramSessions.ts | 50 -- .../ProgramStat.names.ts | 23 - .../ProgramStat.queries.ts | 25 - .../ProgramStat.ts | 48 -- .../ProgramVerdict.ts | 40 -- .../ProgramView.names.ts | 20 - .../ProgramView.queries.ts | 25 - .../ProgramView.ts | 39 -- .../ProgramsByMonth.names.ts | 19 - .../ProgramsByMonth.queries.ts | 19 - .../ProgramsByMonth.ts | 46 -- .../ProgramsByWeek.names.ts | 17 - .../ProgramsByWeek.queries.ts | 19 - .../ProgramsByWeek.ts | 38 -- .../ProgramsEmptyScope.names.ts | 17 - .../ProgramsEmptyScope.queries.ts | 19 - .../ProgramsEmptyScope.ts | 38 -- .../ProgramsOverTime.names.ts | 22 - .../ProgramsOverTime.queries.ts | 19 - .../ProgramsOverTime.ts | 58 -- .../RecentPrograms.names.ts | 16 - .../RecentPrograms.queries.ts | 19 - .../RecentPrograms.ts | 34 -- .../ReferralAuth.names.ts | 23 - .../ReferralAuth.ts | 113 ---- .../Session.names.ts | 21 - .../Session.queries.ts | 61 -- .../Session.ts | 97 --- .../SessionsByProgram.names.ts | 19 - .../SessionsByProgram.queries.ts | 19 - .../SessionsByProgram.ts | 46 -- .../Settings.ts | 43 -- .../Tag.names.ts | 19 - .../Tag.queries.ts | 50 -- .../Tag.ts | 86 --- .../Week.names.ts | 23 - .../Week.queries.ts | 61 -- .../Week.ts | 116 ---- .../WeekLabel.ts | 28 - .../WeekShapes.names.ts | 22 - .../WeekShapes.queries.ts | 19 - .../WeekShapes.ts | 58 -- .../coachNote.extractor.ts | 45 -- .../coachNote.response.ts | 103 ---- .../coachNote.responseFormat.ts | 20 - .../enums.ts | 7 - .../index.ts | 59 -- .../package.json | 1 - .../prompts.ts | 8 - .../WorkItem.queries.ts | 56 -- .../tmp-db-schema-generic-sAIph4/WorkItem.ts | 86 --- .../tmp-db-schema-generic-sAIph4/consumer.ts | 12 - .../tmp-tph-ref-sqlite-YoKZOH/Broker.names.ts | 23 - .../test/tmp-tph-ref-sqlite-YoKZOH/Broker.ts | 103 ---- .../Carrier.names.ts | 24 - .../test/tmp-tph-ref-sqlite-YoKZOH/Carrier.ts | 112 ---- .../tmp-tph-ref-sqlite-YoKZOH/Depot.names.ts | 18 - .../Depot.queries.ts | 50 -- .../test/tmp-tph-ref-sqlite-YoKZOH/Depot.ts | 80 --- .../tmp-tph-ref-sqlite-YoKZOH/Leg.names.ts | 22 - .../tmp-tph-ref-sqlite-YoKZOH/Leg.queries.ts | 72 --- .../test/tmp-tph-ref-sqlite-YoKZOH/Leg.ts | 110 ---- .../Organization.names.ts | 24 - .../tmp-tph-ref-sqlite-YoKZOH/Organization.ts | 19 - .../tmp-tph-ref-sqlite-YoKZOH/Party.names.ts | 19 - .../Party.queries.ts | 101 ---- .../test/tmp-tph-ref-sqlite-YoKZOH/Party.ts | 130 ----- .../Shipment.names.ts | 18 - .../Shipment.queries.ts | 56 -- .../tmp-tph-ref-sqlite-YoKZOH/Shipment.ts | 85 --- .../test/tmp-tph-ref-sqlite-YoKZOH/index.ts | 8 - 189 files changed, 9 insertions(+), 9195 deletions(-) delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Label.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramBrief.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramVerdict.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Settings.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekLabel.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.extractor.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.response.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.responseFormat.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/enums.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/index.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/package.json delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/prompts.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/consumer.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.names.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.queries.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.ts delete mode 100644 server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/index.ts diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs index 48b3aae251..94232f87d4 100644 --- a/server/rust/metaobjects/src/validate/rules.rs +++ b/server/rust/metaobjects/src/validate/rules.rs @@ -916,17 +916,16 @@ fn file_name_placeholder_problem(file_name: &str) -> Option { let bytes = file_name.as_bytes(); // Scan for `{[^{}]*}` the way the reference's /\{([^{}]*)\}/g does. while i < bytes.len() { - if bytes[i] == b'{' { - if let Some(len) = file_name[i + 1..].find(['{', '}']) { - if bytes[i + 1 + len] == b'}' { - let name = &file_name[i + 1..i + 1 + len]; - if !FILE_NAME_PLACEHOLDERS.contains(&name) { - return Some(format!("holds the placeholder {{{name}}}")); - } - i += len + 2; - continue; - } + if bytes[i] == b'{' + && let Some(len) = file_name[i + 1..].find(['{', '}']) + && bytes[i + 1 + len] == b'}' + { + let name = &file_name[i + 1..i + 1 + len]; + if !FILE_NAME_PLACEHOLDERS.contains(&name) { + return Some(format!("holds the placeholder {{{name}}}")); } + i += len + 2; + continue; } let ch = file_name[i..].chars().next().unwrap_or(' '); rest.push(ch); diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.names.ts deleted file mode 100644 index dd73c208d5..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.names.ts +++ /dev/null @@ -1,39 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AllTypes - -export const AllTypesNames = { - type: "object", - subType: "entity", - name: "AllTypes", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "all_types" }, - }, - fields: { - bVal: { name: "bVal", column: "b_val" }, - dVal: { name: "dVal", column: "d_val" }, - dateVal: { name: "dateVal", column: "date_val" }, - decVal: { name: "decVal", column: "dec_val" }, - durationVal: { name: "durationVal", column: "duration_val" }, - enumVal: { name: "enumVal", column: "enum_val" }, - fVal: { name: "fVal", column: "f_val" }, - iVal: { name: "iVal", column: "i_val" }, - id: { name: "id", column: "id" }, - inet6Val: { name: "inet6Val", column: "inet6_val" }, - inetVal: { name: "inetVal", column: "inet_val" }, - intEnumVal: { name: "intEnumVal", column: "int_enum_val" }, - lVal: { name: "lVal", column: "l_val" }, - labels: { name: "labels", column: "labels" }, - moneyVal: { name: "moneyVal", column: "money_val" }, - sVal: { name: "sVal", column: "s_val" }, - settings: { name: "settings", column: "settings" }, - timeVal: { name: "timeVal", column: "time_val" }, - tsTzVal: { name: "tsTzVal", column: "ts_tz_val" }, - tsVal: { name: "tsVal", column: "ts_val" }, - uriVal: { name: "uriVal", column: "uri_val" }, - uuidVal: { name: "uuidVal", column: "uuid_val" }, - }, - identities: { - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.queries.ts deleted file mode 100644 index b6fb3cab28..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.queries.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AllTypes (AllTypes) -// Extend in your own module (e.g. AllTypes.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { type AllTypes, AllTypesInsertSchema, type AllTypesPatch, AllTypesUpdateSchema, allTypes } from "./AllTypes.js"; - -type Db = PgDatabase>; - -export async function findAllTypesById(db: Db, id: string): Promise { - const [allTypesRow] = await db.select().from(allTypes).where(eq(allTypes.id, id)).limit(1); - return allTypesRow ?? null; -} - -export async function listAllTypes(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(allTypes).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createAllTypes(db: Db, data: z.input): Promise { - const validated = AllTypesInsertSchema.parse(data); - const [allTypesRow] = await db.insert(allTypes).values(validated).returning(); - return allTypesRow!; -} - -export async function updateAllTypes(db: Db, id: string, patch: AllTypesPatch): Promise { - const validated = AllTypesUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findAllTypesById(db, id); - } - const [allTypesRow] = await db.update(allTypes).set(validated).where(eq(allTypes.id, id)).returning(); - return allTypesRow ?? null; -} - -export async function deleteAllTypesById(db: Db, id: string): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(allTypes).where(eq(allTypes.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.ts deleted file mode 100644 index 425354ba28..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypes.ts +++ /dev/null @@ -1,552 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AllTypes (AllTypes) -// Extend in your own module (e.g. AllTypes.extra.ts) — nothing imports it for you. - -import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; -import { - bigint, - boolean, - check, - customType, - date, - doublePrecision, - inet, - integer, - jsonb, - numeric, - pgTable, - real, - text, - time, - timestamp, - uuid, - varchar, -} from "drizzle-orm/pg-core"; -import { z } from "zod"; -import { type Label, LabelInsertSchema } from "./Label.js"; -import { type Settings, SettingsInsertSchema } from "./Settings.js"; - -/** A field.duration column. Binds the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration); - * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month - * part. Counted in bigint microseconds, so the column is the only limit. Generated. */ -const durationColumn = (() => { - const ZERO = BigInt(0); - const SECOND = BigInt(1000000); - const MINUTE = BigInt(60000000); - const HOUR = BigInt(3600000000); - const DAY = BigInt(86400000000); - const WEEK = BigInt(604800000000); - const INT64_MAX = BigInt("9223372036854775807"); - const parseIso = (text: string): bigint | undefined => { - const p = /^([-+])?P(?!$)(?:(\d+)W)?(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d+))?S)?)?$/.exec(text); - if (p === null) { - return undefined; - } - const mag = BigInt(p[2] ?? 0) * WEEK + BigInt(p[3] ?? 0) * DAY + BigInt(p[4] ?? 0) * HOUR - + BigInt(p[5] ?? 0) * MINUTE + BigInt(p[6] ?? 0) * SECOND + BigInt((p[7] ?? "").padEnd(6, "0").slice(0, 6)); - return p[1] === "-" ? -mag : mag; - }; - const isoText = (micros: bigint): string => { - const neg = micros < ZERO; - let rest = neg ? -micros : micros; - const h = rest / HOUR; - rest %= HOUR; - const m = rest / MINUTE; - rest %= MINUTE; - const s = rest / SECOND; - const f = rest % SECOND; - let out = "PT"; - if (h > ZERO) { - out += String(h) + "H"; - } - if (m > ZERO) { - out += String(m) + "M"; - } - if (s > ZERO || f > ZERO) { - out += String(s) + (f > ZERO ? "." + String(f).padStart(6, "0").replace(/0+$/, "") : "") + "S"; - } - if (out === "PT") { - return "PT0S"; - } - return neg ? "-" + out : out; - }; - const pgText = (micros: bigint): string => { - const neg = micros < ZERO; - let rest = neg ? -micros : micros; - const two = (n: bigint): string => String(n).padStart(2, "0"); - const h = rest / HOUR; - rest %= HOUR; - const m = rest / MINUTE; - rest %= MINUTE; - let out = two(h) + ":" + two(m) + ":" + two(rest / SECOND); - const f = rest % SECOND; - if (f > ZERO) { - out += "." + String(f).padStart(6, "0").replace(/0+$/, ""); - } - return neg ? "-" + out : out; - }; - const stored = (micros: bigint): number | bigint => { - if (micros > INT64_MAX || micros < -INT64_MAX - BigInt(1)) { - throw new Error("the span " + isoText(micros) + " does not fit the 64-bit microsecond column a field.duration is stored in"); - } - const n = Number(micros); - return Number.isSafeInteger(n) ? n : micros; - }; - const notFixed = (v: unknown): Error => - new Error("the interval " + JSON.stringify(v) + " has a year or month part, so it is not a fixed-length field.duration"); - const read = (v: unknown): bigint => { - if (typeof v === "bigint") { - return v; - } - if (typeof v === "number" && Number.isInteger(v)) { - return BigInt(v); - } - if (typeof v === "string") { - if (/^-?\d+$/.test(v)) { - return BigInt(v); - } - const iso = parseIso(v); - if (iso !== undefined) { - return iso; - } - const p = v.length === 0 ? null : /^(?:([-+]?\d+) years? ?)?(?:([-+]?\d+) mons? ?)?(?:([-+]?\d+) days? ?)?(?:([-+])?(\d+):(\d{2}):(\d{2})(?:\.(\d{1,6}))?)?$/.exec(v); - if (p === null) { - throw new Error("not a field.duration value: " + JSON.stringify(v)); - } - if (Number(p[1] ?? 0) !== 0 || Number(p[2] ?? 0) !== 0) { - throw notFixed(v); - } - let time = ZERO; - if (p[5] !== undefined) { - time = BigInt(p[5]) * HOUR + BigInt(p[6] ?? 0) * MINUTE + BigInt(p[7] ?? 0) * SECOND + BigInt((p[8] ?? "").padEnd(6, "0")); - if (p[4] === "-") { - time = -time; - } - } - return BigInt(p[3] ?? 0) * DAY + time; - } - if (v !== null && typeof v === "object") { - const o = v as Record; - if ((o.years ?? 0) !== 0 || (o.months ?? 0) !== 0) { - throw notFixed(v); - } - const whole = (n: number | undefined): bigint => BigInt(Math.trunc(n ?? 0)); - // postgres-interval carries microseconds as a fractional millisecond count. - return whole(o.days) * DAY + whole(o.hours) * HOUR + whole(o.minutes) * MINUTE + whole(o.seconds) * SECOND - + BigInt(Math.round((o.milliseconds ?? 0) * 1000)); - } - throw new Error("not a field.duration value: " + JSON.stringify(v)); - }; - return customType<{ data: string; driverData: string }>({ - dataType: () => "interval", - toDriver: (value) => pgText(read(value)), - fromDriver: (value) => isoText(read(value)), - }); -})(); - -const INT_ENUM_VAL_TO_INT = { "DRAFT": 0, "PUBLISHED": 5, "ARCHIVED": 9 } as const satisfies Record<"DRAFT" | "PUBLISHED" | "ARCHIVED", number>; -const INT_ENUM_VAL_FROM_INT: Record = { 0: "DRAFT", 5: "PUBLISHED", 9: "ARCHIVED" }; -const intEnumValIntEnum = customType<{ data: "DRAFT" | "PUBLISHED" | "ARCHIVED"; driverData: number }>({ - dataType: () => "integer", - toDriver: (value) => INT_ENUM_VAL_TO_INT[value], - fromDriver: (value) => { - const member = INT_ENUM_VAL_FROM_INT[value]; - if (member === undefined) { - throw new Error(`unmapped intEnumValIntEnum value: ${value}`); - } - return member; - }, -}); - -export const allTypes = pgTable("all_types", { - id: uuid("id").primaryKey().defaultRandom(), - sVal: varchar("s_val", { length: 200 }).notNull(), - iVal: integer("i_val").notNull(), - lVal: bigint("l_val", { mode: "number" }).notNull(), - dVal: doublePrecision("d_val").notNull(), - fVal: real("f_val").notNull(), - decVal: numeric("dec_val", { precision: 18, scale: 6 }).notNull(), - bVal: boolean("b_val").notNull(), - dateVal: date("date_val").notNull(), - timeVal: time("time_val").notNull(), - tsVal: timestamp("ts_val", { mode: "string", withTimezone: false }).notNull(), - tsTzVal: timestamp("ts_tz_val", { mode: "string", withTimezone: true }).notNull(), - moneyVal: bigint("money_val", { mode: "number" }).notNull(), - enumVal: text("enum_val", { enum: ["LOW", "MEDIUM", "HIGH"] as const }).notNull(), - intEnumVal: intEnumValIntEnum("int_enum_val"), - uuidVal: uuid("uuid_val").notNull(), - uriVal: text("uri_val").notNull(), - inetVal: inet("inet_val").notNull(), - inet6Val: inet("inet6_val").notNull(), - durationVal: durationColumn("duration_val"), - settings: jsonb("settings").$type(), - labels: jsonb("labels").$type(), -}, (table) => [ - check("all_types_enum_val_chk", sql`enum_val IN ('LOW', 'MEDIUM', 'HIGH')`), - check("all_types_int_enum_val_chk", sql`int_enum_val IN (0, 5, 9)`), -]); - -export type AllTypes = InferSelectModel; -export type AllTypesInsert = InferInsertModel; -export type AllTypesUpdate = Partial; - -export type AllTypesEnumVal = "LOW" | "MEDIUM" | "HIGH"; -export const AllTypesEnumValEnum = z.enum(["LOW", "MEDIUM", "HIGH"]); -export type AllTypesIntEnumVal = "DRAFT" | "PUBLISHED" | "ARCHIVED"; -export const AllTypesIntEnumValEnum = z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]); - -/** A field.timestamp instant in UTC (`YYYY-MM-DDTHH:MM:SS[.fff]Z`): a value already spelled so is kept - * as sent, an offset is applied, a zoneless value is UTC and a date alone is midnight UTC. - * SQLite/D1 compare timestamps as text, so instants are stored in UTC. Generated. */ -function utcIsoTimestamp(v: string): string { - if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { - return v; - } - const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ - .exec(v); - if (m === null) { - return v; - } - const t = Date.parse( - `${m[1]}T${m[2] ?? "00:00"}:${m[3] ?? "00"}.${(m[4] ?? "").slice(0, 3).padEnd(3, "0")}${ - m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` - }`, - ); - return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); -} - -/** A field.decimal on the wire: a string in the JSON-number grammar (an exponent is allowed) or a JSON - * number, rewritten to its canonical string (plain notation, no trailing fraction zeros, zero as "0"). - * Garbage, or a value the column cannot hold without rounding, is a validation issue. Generated. */ -function decimalWrite(v: string | number, ctx: z.RefinementCtx, precision?: number, scale = 0): string { - if (typeof v === "number" && Number.isFinite(v) && !Number.isSafeInteger(v) && Number(v.toPrecision(15)) !== v) { - ctx.addIssue({ code: "custom", message: "Decimal number cannot be read exactly as a JSON number; send it as a string" }); - return z.NEVER; - } - const text = typeof v === "number" ? (Number.isFinite(v) ? String(v) : "") : v; - const m = /^(-?)(0|[1-9][0-9]*)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/.exec(text); - const e = m === null || m[4] === undefined ? 0 : Number(m[4]); - if (m === null || !Number.isSafeInteger(e) || Math.abs(e) > 1000) { - ctx.addIssue({ code: "custom", message: "Not a decimal number" }); - return z.NEVER; - } - const whole = m[2] ?? ""; - let digits = whole + (m[3] ?? ""); - let point = whole.length + e; - const lead = digits.length - digits.replace(/^0+/, "").length; - digits = digits.slice(lead).replace(/0+$/, ""); - point -= lead; - if (digits.length === 0) { - return "0"; - } - const plain = point <= 0 - ? `0.${"0".repeat(-point)}${digits}` - : point >= digits.length - ? digits + "0".repeat(point - digits.length) - : `${digits.slice(0, point)}.${digits.slice(point)}`; - const fraction = point >= digits.length ? 0 : digits.length - Math.max(point, 0) + Math.max(-point, 0); - const integer = Math.max(point, 0); - if (plain.length > 1000 || (precision !== undefined && (fraction > scale || integer > precision - scale))) { - ctx.addIssue({ code: "custom", message: "Decimal out of range for the column" }); - return z.NEVER; - } - return m[1] === "-" ? `-${plain}` : plain; -} - -/** A field.duration on the wire: an ISO-8601 duration (weeks, days, hours, minutes, seconds) rewritten - * to its canonical form — hours never folded into days, zero components left out, zero as PT0S, one - * leading "-" for a negative span. Counted in bigint microseconds, so any length is exact and a - * fraction past six digits is truncated toward zero. Generated. */ -function durationWrite(text: string): string { - const ZERO = BigInt(0); - const SECOND = BigInt(1000000); - const MINUTE = BigInt(60000000); - const HOUR = BigInt(3600000000); - const DAY = BigInt(86400000000); - const WEEK = BigInt(604800000000); - const parseIso = (text: string): bigint | undefined => { - const p = /^([-+])?P(?!$)(?:(\d+)W)?(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d+))?S)?)?$/.exec(text); - if (p === null) { - return undefined; - } - const mag = BigInt(p[2] ?? 0) * WEEK + BigInt(p[3] ?? 0) * DAY + BigInt(p[4] ?? 0) * HOUR - + BigInt(p[5] ?? 0) * MINUTE + BigInt(p[6] ?? 0) * SECOND + BigInt((p[7] ?? "").padEnd(6, "0").slice(0, 6)); - return p[1] === "-" ? -mag : mag; - }; - const isoText = (micros: bigint): string => { - const neg = micros < ZERO; - let rest = neg ? -micros : micros; - const h = rest / HOUR; - rest %= HOUR; - const m = rest / MINUTE; - rest %= MINUTE; - const s = rest / SECOND; - const f = rest % SECOND; - let out = "PT"; - if (h > ZERO) { - out += String(h) + "H"; - } - if (m > ZERO) { - out += String(m) + "M"; - } - if (s > ZERO || f > ZERO) { - out += String(s) + (f > ZERO ? "." + String(f).padStart(6, "0").replace(/0+$/, "") : "") + "S"; - } - if (out === "PT") { - return "PT0S"; - } - return neg ? "-" + out : out; - }; - const micros = parseIso(text); - return micros === undefined ? text : isoText(micros); -} - -export const AllTypesInsertSchema = z.object({ - sVal: z.string().min(1).max(200), - iVal: z.number().int(), - lVal: z.number().int(), - dVal: z.number(), - fVal: z.number(), - decVal: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 18, 6)), - bVal: z.boolean(), - dateVal: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)$/, "must be an ISO date (YYYY-MM-DD)"), - timeVal: z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?$/, "must be a time of day (HH:MM[:SS[.fff]], optional offset)"), - tsVal: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])"), - tsTzVal: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])").transform(utcIsoTimestamp), - moneyVal: z.number().int(), - enumVal: z.enum(["LOW", "MEDIUM", "HIGH"]), - intEnumVal: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]).optional(), - uuidVal: z.string().regex(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, "Invalid uuid"), - uriVal: z.string().url(), - inetVal: z.string().regex(/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/).or(z.string().regex(/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9]))$/)), - inet6Val: z.string().regex(/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/).or(z.string().regex(/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9]))$/)), - durationVal: z.string().regex(/^[-+]?P(?!$)(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+(\.\d+)?S)?)?$/).transform(durationWrite).optional(), - settings: SettingsInsertSchema.optional(), - labels: z.array(LabelInsertSchema).optional(), -}); - -export const AllTypesUpdateSchema = z.object({ - sVal: z.string().min(1).max(200).optional(), - iVal: z.number().int().optional(), - lVal: z.number().int().optional(), - dVal: z.number().optional(), - fVal: z.number().optional(), - decVal: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 18, 6)).optional(), - bVal: z.boolean().optional(), - dateVal: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)$/, "must be an ISO date (YYYY-MM-DD)").optional(), - timeVal: z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?$/, "must be a time of day (HH:MM[:SS[.fff]], optional offset)").optional(), - tsVal: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])").optional(), - tsTzVal: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])").transform(utcIsoTimestamp).optional(), - moneyVal: z.number().int().optional(), - enumVal: z.enum(["LOW", "MEDIUM", "HIGH"]).optional(), - intEnumVal: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]).optional().nullable(), - uuidVal: z.string().regex(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, "Invalid uuid").optional(), - uriVal: z.string().url().optional(), - inetVal: z.string().regex(/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/).or(z.string().regex(/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9]))$/)).optional(), - inet6Val: z.string().regex(/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/).or(z.string().regex(/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9]))$/)).optional(), - durationVal: z.string().regex(/^[-+]?P(?!$)(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+(\.\d+)?S)?)?$/).transform(durationWrite).optional().nullable(), - settings: SettingsInsertSchema.optional().nullable(), - labels: z.array(LabelInsertSchema).optional().nullable(), -}); - -/** - * Typed create shape for AllTypes: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createAllTypes` call site; - * the schema still validates at runtime. - */ -export type AllTypesCreate = z.input; - -/** - * Typed patch shape for AllTypes: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateAllTypes` call site. - */ -export type AllTypesPatch = z.input; - -/** - * Metadata constants for AllTypes. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(AllTypes, AllTypesInsertSchema); - * - */ -export const AllTypes = { - $entity: "AllTypes", - $table: "all_types", - $path: "/all_types", - id: { - name: "id", - label: "Id", - view: "text", - htmlType: "text", - }, - sVal: { - name: "sVal", - label: "S Val", - view: "text", - htmlType: "text", - rules: { required: "S Val is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, - }, - iVal: { - name: "iVal", - label: "I Val", - view: "number", - htmlType: "number", - rules: { required: "I Val is required" }, - }, - lVal: { - name: "lVal", - label: "L Val", - view: "number", - htmlType: "number", - rules: { required: "L Val is required" }, - }, - dVal: { - name: "dVal", - label: "D Val", - view: "number", - htmlType: "number", - step: "any", - rules: { required: "D Val is required" }, - }, - fVal: { - name: "fVal", - label: "F Val", - view: "number", - htmlType: "number", - step: "any", - rules: { required: "F Val is required" }, - }, - decVal: { - name: "decVal", - label: "Dec Val", - view: "number", - htmlType: "text", - inputMode: "decimal", - rules: { required: "Dec Val is required" }, - }, - bVal: { - name: "bVal", - label: "B Val", - view: "checkbox", - htmlType: "checkbox", - rules: { required: "B Val is required" }, - }, - dateVal: { - name: "dateVal", - label: "Date Val", - view: "date", - htmlType: "date", - rules: { required: "Date Val is required" }, - }, - timeVal: { - name: "timeVal", - label: "Time Val", - view: "date", - htmlType: "time", - rules: { required: "Time Val is required" }, - }, - tsVal: { - name: "tsVal", - label: "Ts Val", - view: "date", - htmlType: "datetime-local", - rules: { required: "Ts Val is required" }, - }, - tsTzVal: { - name: "tsTzVal", - label: "Ts Tz Val", - view: "date", - htmlType: "datetime-local", - rules: { required: "Ts Tz Val is required" }, - }, - moneyVal: { - name: "moneyVal", - label: "Money Val", - view: "currency", - rules: { required: "Money Val is required" }, - currency: "USD", - locale: "en-US", - }, - enumVal: { - name: "enumVal", - label: "Enum Val", - view: "dropdown", - rules: { required: "Enum Val is required" }, - options: ["LOW", "MEDIUM", "HIGH"] as const, - }, - intEnumVal: { - name: "intEnumVal", - label: "Int Enum Val", - view: "dropdown", - options: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const, - }, - uuidVal: { - name: "uuidVal", - label: "Uuid Val", - view: "text", - htmlType: "text", - rules: { required: "Uuid Val is required" }, - }, - uriVal: { - name: "uriVal", - label: "Uri Val", - view: "text", - htmlType: "text", - rules: { required: "Uri Val is required" }, - }, - inetVal: { - name: "inetVal", - label: "Inet Val", - view: "text", - htmlType: "text", - rules: { required: "Inet Val is required" }, - }, - inet6Val: { - name: "inet6Val", - label: "Inet6Val", - view: "text", - htmlType: "text", - rules: { required: "Inet6Val is required" }, - }, - durationVal: { - name: "durationVal", - label: "Duration Val", - view: "text", - htmlType: "text", - }, - settings: { - name: "settings", - label: "Settings", - view: "text", - htmlType: "text", - }, - labels: { - name: "labels", - label: "Labels", - view: "text", - htmlType: "text", - }, -} as const; - -export type AllTypesFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: AllTypesFilter[]; - and?: AllTypesFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.names.ts deleted file mode 100644 index 0bdf425a02..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.names.ts +++ /dev/null @@ -1,26 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AllTypesBreakdown - -export const AllTypesBreakdownNames = { - type: "object", - subType: "report", - name: "AllTypesBreakdown", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_all_types_breakdown" }, - }, - fields: { - allRows: { name: "allRows", column: "all_rows" }, - avgDec: { name: "avgDec", column: "avg_dec" }, - dateKey: { name: "dateKey", column: "date_key" }, - flag: { name: "flag", column: "flag" }, - highRows: { name: "highRows", column: "high_rows" }, - legacyStatus: { name: "legacyStatus", column: "legacy_status" }, - level: { name: "level", column: "level" }, - maxMoney: { name: "maxMoney", column: "max_money" }, - minLong: { name: "minLong", column: "min_long" }, - totalInts: { name: "totalInts", column: "total_ints" }, - uuidKey: { name: "uuidKey", column: "uuid_key" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.queries.ts deleted file mode 100644 index d6c781b655..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AllTypesBreakdown (AllTypesBreakdown) — report (read-only) -// Extend in your own module (e.g. AllTypesBreakdown.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type AllTypesBreakdown, allTypesBreakdownView } from "./AllTypesBreakdown.js"; - -type Db = PgDatabase>; - -export async function listAllTypesBreakdowns(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(allTypesBreakdownView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.ts deleted file mode 100644 index a02efa6888..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AllTypesBreakdown.ts +++ /dev/null @@ -1,88 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AllTypesBreakdown (AllTypesBreakdown) - -import { bigint, boolean, customType, date, numeric, pgView, text, uuid } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -const LEGACY_STATUS_TO_INT = { "DRAFT": 0, "PUBLISHED": 5, "ARCHIVED": 9 } as const satisfies Record<"DRAFT" | "PUBLISHED" | "ARCHIVED", number>; -const LEGACY_STATUS_FROM_INT: Record = { 0: "DRAFT", 5: "PUBLISHED", 9: "ARCHIVED" }; -const legacyStatusIntEnum = customType<{ data: "DRAFT" | "PUBLISHED" | "ARCHIVED"; driverData: number }>({ - dataType: () => "integer", - toDriver: (value) => LEGACY_STATUS_TO_INT[value], - fromDriver: (value) => { - const member = LEGACY_STATUS_FROM_INT[value]; - if (member === undefined) { - throw new Error(`unmapped legacyStatusIntEnum value: ${value}`); - } - return member; - }, -}); - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const allTypesBreakdownView = pgView("v_all_types_breakdown", { - flag: boolean("flag").notNull(), - level: text("level", { enum: ["LOW", "MEDIUM", "HIGH"] as const }).notNull(), - legacyStatus: legacyStatusIntEnum("legacy_status"), - dateKey: date("date_key").notNull(), - uuidKey: uuid("uuid_key").notNull(), - allRows: bigint("all_rows", { mode: "number" }).notNull(), - totalInts: bigint("total_ints", { mode: "number" }), - avgDec: numeric("avg_dec", { precision: 19, scale: 4 }), - maxMoney: bigint("max_money", { mode: "number" }), - minLong: bigint("min_long", { mode: "number" }), - highRows: bigint("high_rows", { mode: "number" }).notNull(), -}).existing(); - -export const AllTypesBreakdownSchema = z.object({ - flag: z.boolean(), - level: z.enum(["LOW", "MEDIUM", "HIGH"]), - legacyStatus: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]).nullable(), - dateKey: z.string(), - uuidKey: z.string(), - allRows: z.number().int(), - totalInts: z.number().int().nullable(), - avgDec: z.string().nullable(), - maxMoney: z.number().int().nullable(), - minLong: z.number().int().nullable(), - highRows: z.number().int(), -}); - -export type AllTypesBreakdown = z.infer; - -export const AllTypesBreakdown = { - $entity: "AllTypesBreakdown", - $view: "v_all_types_breakdown", - $path: "/all_types_breakdowns", - flag: { name: "flag", label: "Flag", view: "checkbox", dbCol: "flag" }, - level: { name: "level", label: "Level", view: "dropdown", dbCol: "level" }, - legacyStatus: { name: "legacyStatus", label: "Legacy Status", view: "dropdown", dbCol: "legacy_status" }, - dateKey: { name: "dateKey", label: "Date Key", view: "date", dbCol: "date_key" }, - uuidKey: { name: "uuidKey", label: "Uuid Key", view: "text", dbCol: "uuid_key" }, - allRows: { name: "allRows", label: "All Rows", view: "number", dbCol: "all_rows" }, - totalInts: { name: "totalInts", label: "Total Ints", view: "number", dbCol: "total_ints" }, - avgDec: { name: "avgDec", label: "Avg Dec", view: "number", dbCol: "avg_dec" }, - maxMoney: { name: "maxMoney", label: "Max Money", view: "currency", dbCol: "max_money", currency: "USD", locale: "en-US" }, - minLong: { name: "minLong", label: "Min Long", view: "number", dbCol: "min_long" }, - highRows: { name: "highRows", label: "High Rows", view: "number", dbCol: "high_rows" }, -} as const; - -export type AllTypesBreakdownFilter = { - limit?: number; - offset?: number; - sort?: `${"flag" | "level" | "legacyStatus" | "dateKey" | "uuidKey" | "allRows" | "totalInts" | "avgDec" | "maxMoney" | "minLong" | "highRows"}:${"asc" | "desc"}` | "flag" | "level" | "legacyStatus" | "dateKey" | "uuidKey" | "allRows" | "totalInts" | "avgDec" | "maxMoney" | "minLong" | "highRows"; - flag?: boolean | { eq?: boolean; isNull?: boolean }; - level?: "LOW" | "MEDIUM" | "HIGH" | { eq?: "LOW" | "MEDIUM" | "HIGH"; ne?: "LOW" | "MEDIUM" | "HIGH"; in?: ("LOW" | "MEDIUM" | "HIGH")[]; like?: string; isNull?: boolean }; - legacyStatus?: "DRAFT" | "PUBLISHED" | "ARCHIVED" | { eq?: "DRAFT" | "PUBLISHED" | "ARCHIVED"; ne?: "DRAFT" | "PUBLISHED" | "ARCHIVED"; in?: ("DRAFT" | "PUBLISHED" | "ARCHIVED")[]; isNull?: boolean }; - dateKey?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - uuidKey?: string | { eq?: string; ne?: string; in?: string[]; isNull?: boolean }; - allRows?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - totalInts?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - avgDec?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - maxMoney?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - minLong?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - highRows?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: AllTypesBreakdownFilter[]; - and?: AllTypesBreakdownFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.names.ts deleted file mode 100644 index c6a45c0069..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.names.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ArchivedLedgerEntry - -export const ArchivedLedgerEntryNames = { - type: "object", - subType: "entity", - name: "ArchivedLedgerEntry", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", schema: "archive", table: "ledger_entries" }, - }, - fields: { - id: { name: "id", column: "id" }, - memo: { name: "memo", column: "memo" }, - }, - identities: { - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.queries.ts deleted file mode 100644 index 546d797a24..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.queries.ts +++ /dev/null @@ -1,56 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ArchivedLedgerEntry (ArchivedLedgerEntry) -// Extend in your own module (e.g. ArchivedLedgerEntry.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { - type ArchivedLedgerEntry, - ArchivedLedgerEntryInsertSchema, - type ArchivedLedgerEntryPatch, - ArchivedLedgerEntryUpdateSchema, - archivedLedgerEntries, -} from "./ArchivedLedgerEntry.js"; - -type Db = PgDatabase>; - -export async function findArchivedLedgerEntryById(db: Db, id: number): Promise { - const [archivedLedgerEntry] = await db.select().from(archivedLedgerEntries).where(eq(archivedLedgerEntries.id, id)).limit(1); - return archivedLedgerEntry ?? null; -} - -export async function listArchivedLedgerEntries(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(archivedLedgerEntries).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createArchivedLedgerEntry(db: Db, data: z.input): Promise { - const validated = ArchivedLedgerEntryInsertSchema.parse(data); - const [archivedLedgerEntry] = await db.insert(archivedLedgerEntries).values(validated).returning(); - return archivedLedgerEntry!; -} - -export async function updateArchivedLedgerEntry(db: Db, id: number, patch: ArchivedLedgerEntryPatch): Promise { - const validated = ArchivedLedgerEntryUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findArchivedLedgerEntryById(db, id); - } - const [archivedLedgerEntry] = await db.update(archivedLedgerEntries).set(validated).where(eq(archivedLedgerEntries.id, id)).returning(); - return archivedLedgerEntry ?? null; -} - -export async function deleteArchivedLedgerEntryById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(archivedLedgerEntries).where(eq(archivedLedgerEntries.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.ts deleted file mode 100644 index 3110cc4c61..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ArchivedLedgerEntry.ts +++ /dev/null @@ -1,86 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ArchivedLedgerEntry (ArchivedLedgerEntry) -// Extend in your own module (e.g. ArchivedLedgerEntry.extra.ts) — nothing imports it for you. - -import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { bigint, pgSchema, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -export const archivedLedgerEntries = pgSchema("archive").table("ledger_entries", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - memo: varchar("memo", { length: 40 }), -}); - -export type ArchivedLedgerEntry = InferSelectModel; -export type ArchivedLedgerEntryInsert = InferInsertModel; -export type ArchivedLedgerEntryUpdate = Partial; - -export const ArchivedLedgerEntryInsertSchema = z.object({ - memo: z.string().max(40).optional(), -}); - -export const ArchivedLedgerEntryUpdateSchema = z.object({ - memo: z.string().max(40).optional().nullable(), -}); - -/** - * Typed create shape for ArchivedLedgerEntry: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createArchivedLedgerEntry` call site; - * the schema still validates at runtime. - */ -export type ArchivedLedgerEntryCreate = z.input; - -/** - * Typed patch shape for ArchivedLedgerEntry: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateArchivedLedgerEntry` call site. - */ -export type ArchivedLedgerEntryPatch = z.input; - -/** - * Metadata constants for ArchivedLedgerEntry. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(ArchivedLedgerEntry, ArchivedLedgerEntryInsertSchema); - * - */ -export const ArchivedLedgerEntry = { - $entity: "ArchivedLedgerEntry", - $table: "ledger_entries", - $path: "/archived_ledger_entries", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - memo: { - name: "memo", - label: "Memo", - view: "text", - htmlType: "text", - rules: { maxLength: { value: 40, message: "Must be 40 characters or fewer" } }, - }, -} as const; - -export type ArchivedLedgerEntryFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: ArchivedLedgerEntryFilter[]; - and?: ArchivedLedgerEntryFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.names.ts deleted file mode 100644 index 88ef6e4b4b..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.names.ts +++ /dev/null @@ -1,25 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Asset - -export const AssetNames = { - type: "object", - subType: "entity", - name: "Asset", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "assets" }, - }, - fields: { - asOfDate: { name: "asOfDate", column: "as_of_date" }, - atTime: { name: "atTime", column: "at_time" }, - externalId: { name: "externalId", column: "external_id" }, - id: { name: "id", column: "id" }, - observedAt: { name: "observedAt", column: "observed_at" }, - ownerId: { name: "ownerId", column: "owner_id" }, - payload: { name: "payload", column: "payload" }, - recordedAt: { name: "recordedAt", column: "recorded_at" }, - }, - identities: { - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.queries.ts deleted file mode 100644 index 799989ac65..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.queries.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Asset (Asset) -// Extend in your own module (e.g. Asset.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { type Asset, AssetInsertSchema, type AssetPatch, AssetUpdateSchema, assets } from "./Asset.js"; - -type Db = PgDatabase>; - -export async function findAssetById(db: Db, id: string): Promise { - const [asset] = await db.select().from(assets).where(eq(assets.id, id)).limit(1); - return asset ?? null; -} - -export async function listAssets(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(assets).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createAsset(db: Db, data: z.input): Promise { - const validated = AssetInsertSchema.parse(data); - const [asset] = await db.insert(assets).values(validated).returning(); - return asset!; -} - -export async function updateAsset(db: Db, id: string, patch: AssetPatch): Promise { - const validated = AssetUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findAssetById(db, id); - } - const [asset] = await db.update(assets).set(validated).where(eq(assets.id, id)).returning(); - return asset ?? null; -} - -export async function deleteAssetById(db: Db, id: string): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(assets).where(eq(assets.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.ts deleted file mode 100644 index 374eba6365..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Asset.ts +++ /dev/null @@ -1,164 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Asset (Asset) -// Extend in your own module (e.g. Asset.extra.ts) — nothing imports it for you. - -import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { date, jsonb, pgTable, time, timestamp, uuid } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -export const assets = pgTable("assets", { - id: uuid("id").primaryKey().defaultRandom(), - ownerId: uuid("owner_id").notNull(), - externalId: uuid("external_id"), - payload: jsonb("payload"), - recordedAt: timestamp("recorded_at", { mode: "string", withTimezone: true }).notNull(), - observedAt: timestamp("observed_at", { mode: "string", withTimezone: false }).notNull(), - asOfDate: date("as_of_date").notNull(), - atTime: time("at_time").notNull(), -}); - -export type Asset = InferSelectModel; -export type AssetInsert = InferInsertModel; -export type AssetUpdate = Partial; - -/** A field.timestamp instant in UTC (`YYYY-MM-DDTHH:MM:SS[.fff]Z`): a value already spelled so is kept - * as sent, an offset is applied, a zoneless value is UTC and a date alone is midnight UTC. - * SQLite/D1 compare timestamps as text, so instants are stored in UTC. Generated. */ -function utcIsoTimestamp(v: string): string { - if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { - return v; - } - const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ - .exec(v); - if (m === null) { - return v; - } - const t = Date.parse( - `${m[1]}T${m[2] ?? "00:00"}:${m[3] ?? "00"}.${(m[4] ?? "").slice(0, 3).padEnd(3, "0")}${ - m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` - }`, - ); - return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); -} - -export const AssetInsertSchema = z.object({ - ownerId: z.string().regex(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, "Invalid uuid"), - externalId: z.string().optional(), - payload: z.unknown().optional(), - recordedAt: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])").transform(utcIsoTimestamp), - observedAt: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])"), - asOfDate: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)$/, "must be an ISO date (YYYY-MM-DD)"), - atTime: z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?$/, "must be a time of day (HH:MM[:SS[.fff]], optional offset)"), -}); - -export const AssetUpdateSchema = z.object({ - ownerId: z.string().regex(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, "Invalid uuid").optional(), - externalId: z.string().optional().nullable(), - payload: z.unknown().optional().nullable(), - recordedAt: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])").transform(utcIsoTimestamp).optional(), - observedAt: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])").optional(), - asOfDate: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)$/, "must be an ISO date (YYYY-MM-DD)").optional(), - atTime: z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?$/, "must be a time of day (HH:MM[:SS[.fff]], optional offset)").optional(), -}); - -/** - * Typed create shape for Asset: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createAsset` call site; - * the schema still validates at runtime. - */ -export type AssetCreate = z.input; - -/** - * Typed patch shape for Asset: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateAsset` call site. - */ -export type AssetPatch = z.input; - -/** - * Metadata constants for Asset. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Asset, AssetInsertSchema); - * - */ -export const Asset = { - $entity: "Asset", - $table: "assets", - $path: "/assets", - id: { - name: "id", - label: "Id", - view: "text", - htmlType: "text", - }, - ownerId: { - name: "ownerId", - label: "Owner Id", - view: "text", - htmlType: "text", - rules: { required: "Owner Id is required" }, - }, - externalId: { - name: "externalId", - label: "External Id", - view: "text", - htmlType: "text", - }, - payload: { - name: "payload", - label: "Payload", - view: "text", - htmlType: "text", - }, - recordedAt: { - name: "recordedAt", - label: "Recorded At", - view: "date", - htmlType: "datetime-local", - rules: { required: "Recorded At is required" }, - }, - observedAt: { - name: "observedAt", - label: "Observed At", - view: "date", - htmlType: "datetime-local", - rules: { required: "Observed At is required" }, - }, - asOfDate: { - name: "asOfDate", - label: "As Of Date", - view: "date", - htmlType: "date", - rules: { required: "As Of Date is required" }, - }, - atTime: { - name: "atTime", - label: "At Time", - view: "date", - htmlType: "time", - rules: { required: "At Time is required" }, - }, -} as const; - -export type AssetFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: AssetFilter[]; - and?: AssetFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.names.ts deleted file mode 100644 index 6b593ceabc..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.names.ts +++ /dev/null @@ -1,18 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AssetActivity - -export const AssetActivityNames = { - type: "object", - subType: "report", - name: "AssetActivity", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_asset_activity" }, - }, - fields: { - asOfDateWeek: { name: "asOfDateWeek", column: "as_of_date_week" }, - assets: { name: "assets", column: "assets" }, - recordedAtHour: { name: "recordedAtHour", column: "recorded_at_hour" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.queries.ts deleted file mode 100644 index e8a825d5a2..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AssetActivity (AssetActivity) — report (read-only) -// Extend in your own module (e.g. AssetActivity.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type AssetActivity, assetActivityView } from "./AssetActivity.js"; - -type Db = PgDatabase>; - -export async function listAssetActivities(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(assetActivityView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.ts deleted file mode 100644 index c4e9cb5bec..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetActivity.ts +++ /dev/null @@ -1,42 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AssetActivity (AssetActivity) - -import { bigint, date, pgView, timestamp } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const assetActivityView = pgView("v_asset_activity", { - recordedAtHour: timestamp("recorded_at_hour", { mode: "string", withTimezone: true }).notNull(), - asOfDateWeek: date("as_of_date_week").notNull(), - assets: bigint("assets", { mode: "number" }).notNull(), -}).existing(); - -export const AssetActivitySchema = z.object({ - recordedAtHour: z.string(), - asOfDateWeek: z.string(), - assets: z.number().int(), -}); - -export type AssetActivity = z.infer; - -export const AssetActivity = { - $entity: "AssetActivity", - $view: "v_asset_activity", - $path: "/asset_activities", - recordedAtHour: { name: "recordedAtHour", label: "Recorded At Hour", view: "date", dbCol: "recorded_at_hour" }, - asOfDateWeek: { name: "asOfDateWeek", label: "As Of Date Week", view: "date", dbCol: "as_of_date_week" }, - assets: { name: "assets", label: "Assets", view: "number", dbCol: "assets" }, -} as const; - -export type AssetActivityFilter = { - limit?: number; - offset?: number; - sort?: `${"recordedAtHour" | "asOfDateWeek" | "assets"}:${"asc" | "desc"}` | "recordedAtHour" | "asOfDateWeek" | "assets"; - recordedAtHour?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - asOfDateWeek?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - assets?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: AssetActivityFilter[]; - and?: AssetActivityFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.names.ts deleted file mode 100644 index c052c495a9..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.names.ts +++ /dev/null @@ -1,22 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AssetDays - -export const AssetDaysNames = { - type: "object", - subType: "report", - name: "AssetDays", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_asset_days" }, - }, - fields: { - asOfDateMonth: { name: "asOfDateMonth", column: "as_of_date_month" }, - assets: { name: "assets", column: "assets" }, - firstRecorded: { name: "firstRecorded", column: "first_recorded" }, - lastAsOf: { name: "lastAsOf", column: "last_as_of" }, - lastObserved: { name: "lastObserved", column: "last_observed" }, - owners: { name: "owners", column: "owners" }, - recordedAtDay: { name: "recordedAtDay", column: "recorded_at_day" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.queries.ts deleted file mode 100644 index 2ba90b5003..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AssetDays (AssetDays) — report (read-only) -// Extend in your own module (e.g. AssetDays.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type AssetDays, assetDaysView } from "./AssetDays.js"; - -type Db = PgDatabase>; - -export async function listAssetDays(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(assetDaysView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.ts deleted file mode 100644 index 3a5f42f544..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AssetDays.ts +++ /dev/null @@ -1,58 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AssetDays (AssetDays) - -import { bigint, date, pgView, timestamp } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const assetDaysView = pgView("v_asset_days", { - recordedAtDay: date("recorded_at_day").notNull(), - asOfDateMonth: date("as_of_date_month").notNull(), - assets: bigint("assets", { mode: "number" }).notNull(), - owners: bigint("owners", { mode: "number" }).notNull(), - firstRecorded: timestamp("first_recorded", { mode: "string", withTimezone: true }), - lastObserved: timestamp("last_observed", { mode: "string", withTimezone: false }), - lastAsOf: date("last_as_of"), -}).existing(); - -export const AssetDaysSchema = z.object({ - recordedAtDay: z.string(), - asOfDateMonth: z.string(), - assets: z.number().int(), - owners: z.number().int(), - firstRecorded: z.string().nullable(), - lastObserved: z.string().nullable(), - lastAsOf: z.string().nullable(), -}); - -export type AssetDays = z.infer; - -export const AssetDays = { - $entity: "AssetDays", - $view: "v_asset_days", - $path: "/asset_days", - recordedAtDay: { name: "recordedAtDay", label: "Recorded At Day", view: "date", dbCol: "recorded_at_day" }, - asOfDateMonth: { name: "asOfDateMonth", label: "As Of Date Month", view: "date", dbCol: "as_of_date_month" }, - assets: { name: "assets", label: "Assets", view: "number", dbCol: "assets" }, - owners: { name: "owners", label: "Owners", view: "number", dbCol: "owners" }, - firstRecorded: { name: "firstRecorded", label: "First Recorded", view: "date", dbCol: "first_recorded" }, - lastObserved: { name: "lastObserved", label: "Last Observed", view: "date", dbCol: "last_observed" }, - lastAsOf: { name: "lastAsOf", label: "Last As Of", view: "date", dbCol: "last_as_of" }, -} as const; - -export type AssetDaysFilter = { - limit?: number; - offset?: number; - sort?: `${"recordedAtDay" | "asOfDateMonth" | "assets" | "owners" | "firstRecorded" | "lastObserved" | "lastAsOf"}:${"asc" | "desc"}` | "recordedAtDay" | "asOfDateMonth" | "assets" | "owners" | "firstRecorded" | "lastObserved" | "lastAsOf"; - recordedAtDay?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - asOfDateMonth?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - assets?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - owners?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - firstRecorded?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - lastObserved?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - lastAsOf?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - or?: AssetDaysFilter[]; - and?: AssetDaysFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.names.ts deleted file mode 100644 index f697de41f3..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.names.ts +++ /dev/null @@ -1,20 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Auth - -export const AuthNames = { - type: "object", - subType: "entity", - name: "Auth", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "auths" }, - }, - fields: { - id: { name: "id", column: "id" }, - reference: { name: "reference", column: "reference" }, - type: { name: "type", column: "type" }, - }, - identities: { - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.queries.ts deleted file mode 100644 index fd8a18a0b6..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.queries.ts +++ /dev/null @@ -1,175 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Auth (Auth) — TPH discriminator base -// Extend in your own module (e.g. Auth.extra.ts) — nothing imports it for you. - -import { and, eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { type Auth, auths, parseAuth } from "./Auth.js"; -import { type BridgeAuth, BridgeAuthInsertSchema, BridgeAuthSchema } from "./BridgeAuth.js"; -import { type CouponAuth, CouponAuthInsertSchema, CouponAuthSchema } from "./CouponAuth.js"; -import { type PermitAuth, PermitAuthInsertSchema, PermitAuthSchema } from "./PermitAuth.js"; -import { type ReferralAuth, ReferralAuthInsertSchema, ReferralAuthSchema } from "./ReferralAuth.js"; - -type Db = PgDatabase>; - -export async function findAuthById(db: Db, id: number): Promise { - const [row] = await db.select().from(auths).where(eq(auths.id, id)).limit(1); - return row ? parseAuth(row) : null; -} - -export async function listAuths(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(auths).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - const rows = await q; - return rows.map((r) => parseAuth(r)); -} - -export async function listBridgeAuths(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(auths).where(eq(auths.type, "Bridge")).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - const rows = await q; - return rows.map((r) => BridgeAuthSchema.parse(r)); -} - -export async function findBridgeAuthById(db: Db, id: number): Promise { - const [row] = await db.select().from(auths).where(and(eq(auths.id, id), eq(auths.type, "Bridge"))).limit(1); - return row ? BridgeAuthSchema.parse(row) : null; -} - -export async function createBridgeAuth(db: Db, data: z.input): Promise { - const validated = BridgeAuthInsertSchema.parse(data); - const [row] = await db.insert(auths).values({ ...validated, type: "Bridge" }).returning(); - return BridgeAuthSchema.parse(row!); -} - -export async function updateBridgeAuthById(db: Db, id: number, data: Partial>): Promise { - const validated = BridgeAuthInsertSchema.partial().parse(data) as Record; - // The discriminator is immutable — a BridgeAuth can never become another subtype. - const { ["type"]: _disc, ...safe } = validated; - const [row] = await db.update(auths).set(safe).where(and(eq(auths.id, id), eq(auths.type, "Bridge"))).returning(); - return row ? BridgeAuthSchema.parse(row) : null; -} - -export async function deleteBridgeAuthById(db: Db, id: number): Promise { - const deleted = await db.delete(auths).where(and(eq(auths.id, id), eq(auths.type, "Bridge"))).returning(); - return deleted.length > 0; -} - -export async function listCouponAuths(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(auths).where(eq(auths.type, "Coupon")).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - const rows = await q; - return rows.map((r) => CouponAuthSchema.parse(r)); -} - -export async function findCouponAuthById(db: Db, id: number): Promise { - const [row] = await db.select().from(auths).where(and(eq(auths.id, id), eq(auths.type, "Coupon"))).limit(1); - return row ? CouponAuthSchema.parse(row) : null; -} - -export async function createCouponAuth(db: Db, data: z.input): Promise { - const validated = CouponAuthInsertSchema.parse(data); - const [row] = await db.insert(auths).values({ ...validated, type: "Coupon" }).returning(); - return CouponAuthSchema.parse(row!); -} - -export async function updateCouponAuthById(db: Db, id: number, data: Partial>): Promise { - const validated = CouponAuthInsertSchema.partial().parse(data) as Record; - // The discriminator is immutable — a CouponAuth can never become another subtype. - const { ["type"]: _disc, ...safe } = validated; - const [row] = await db.update(auths).set(safe).where(and(eq(auths.id, id), eq(auths.type, "Coupon"))).returning(); - return row ? CouponAuthSchema.parse(row) : null; -} - -export async function deleteCouponAuthById(db: Db, id: number): Promise { - const deleted = await db.delete(auths).where(and(eq(auths.id, id), eq(auths.type, "Coupon"))).returning(); - return deleted.length > 0; -} - -export async function listPermitAuths(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(auths).where(eq(auths.type, "Permit")).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - const rows = await q; - return rows.map((r) => PermitAuthSchema.parse(r)); -} - -export async function findPermitAuthById(db: Db, id: number): Promise { - const [row] = await db.select().from(auths).where(and(eq(auths.id, id), eq(auths.type, "Permit"))).limit(1); - return row ? PermitAuthSchema.parse(row) : null; -} - -export async function createPermitAuth(db: Db, data: z.input): Promise { - const validated = PermitAuthInsertSchema.parse(data); - const [row] = await db.insert(auths).values({ ...validated, type: "Permit" }).returning(); - return PermitAuthSchema.parse(row!); -} - -export async function updatePermitAuthById(db: Db, id: number, data: Partial>): Promise { - const validated = PermitAuthInsertSchema.partial().parse(data) as Record; - // The discriminator is immutable — a PermitAuth can never become another subtype. - const { ["type"]: _disc, ...safe } = validated; - const [row] = await db.update(auths).set(safe).where(and(eq(auths.id, id), eq(auths.type, "Permit"))).returning(); - return row ? PermitAuthSchema.parse(row) : null; -} - -export async function deletePermitAuthById(db: Db, id: number): Promise { - const deleted = await db.delete(auths).where(and(eq(auths.id, id), eq(auths.type, "Permit"))).returning(); - return deleted.length > 0; -} - -export async function listReferralAuths(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(auths).where(eq(auths.type, "Referral")).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - const rows = await q; - return rows.map((r) => ReferralAuthSchema.parse(r)); -} - -export async function findReferralAuthById(db: Db, id: number): Promise { - const [row] = await db.select().from(auths).where(and(eq(auths.id, id), eq(auths.type, "Referral"))).limit(1); - return row ? ReferralAuthSchema.parse(row) : null; -} - -export async function createReferralAuth(db: Db, data: z.input): Promise { - const validated = ReferralAuthInsertSchema.parse(data); - const [row] = await db.insert(auths).values({ ...validated, type: "Referral" }).returning(); - return ReferralAuthSchema.parse(row!); -} - -export async function updateReferralAuthById(db: Db, id: number, data: Partial>): Promise { - const validated = ReferralAuthInsertSchema.partial().parse(data) as Record; - // The discriminator is immutable — a ReferralAuth can never become another subtype. - const { ["type"]: _disc, ...safe } = validated; - const [row] = await db.update(auths).set(safe).where(and(eq(auths.id, id), eq(auths.type, "Referral"))).returning(); - return row ? ReferralAuthSchema.parse(row) : null; -} - -export async function deleteReferralAuthById(db: Db, id: number): Promise { - const deleted = await db.delete(auths).where(and(eq(auths.id, id), eq(auths.type, "Referral"))).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.ts deleted file mode 100644 index 825e2d9a1e..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Auth.ts +++ /dev/null @@ -1,143 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Auth (Auth) -// Extend in your own module (e.g. Auth.extra.ts) — nothing imports it for you. - -import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; -import { bigint, check, integer, numeric, pgTable, text, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; -import { type BridgeAuth, BridgeAuthSchema } from "./BridgeAuth.js"; -import { type CouponAuth, CouponAuthSchema } from "./CouponAuth.js"; -import { type PermitAuth, PermitAuthSchema } from "./PermitAuth.js"; -import { type ReferralAuth, ReferralAuthSchema } from "./ReferralAuth.js"; - -export const auths = pgTable("auths", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - type: text("type", { enum: ["Bridge", "Coupon", "Permit", "Referral"] as const }), - reference: varchar("reference", { length: 80 }).notNull(), - quantity: integer("quantity"), - couponAmount: numeric("coupon_amount", { precision: 10, scale: 2 }), - approver: varchar("approver", { length: 80 }), - urgency: varchar("urgency", { length: 16 }), -}, (table) => [check("auths_type_chk", sql`type IN ('Bridge', 'Coupon', 'Permit', 'Referral')`)]); - -export type AuthRow = InferSelectModel; -export type AuthInsert = InferInsertModel; -export type AuthUpdate = Partial; - -export type AuthType = "Bridge" | "Coupon" | "Permit" | "Referral"; -export const AuthTypeEnum = z.enum(["Bridge", "Coupon", "Permit", "Referral"]); - -export const AuthInsertSchema = z.object({ - type: z.enum(["Bridge", "Coupon", "Permit", "Referral"]).optional(), - reference: z.string().min(1).max(80), -}); - -export const AuthUpdateSchema = z.object({ - type: z.enum(["Bridge", "Coupon", "Permit", "Referral"]).optional().nullable(), - reference: z.string().min(1).max(80).optional(), -}); - -/** - * Typed create shape for Auth: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createAuth` call site; - * the schema still validates at runtime. - */ -export type AuthCreate = z.input; - -/** - * Typed patch shape for Auth: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateAuth` call site. - */ -export type AuthPatch = z.input; - -/** - * Metadata constants for Auth. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Auth, AuthInsertSchema); - * - */ -export const Auth = { - $entity: "Auth", - $table: "auths", - $path: "/auths", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - type: { - name: "type", - label: "Type", - view: "dropdown", - options: ["Bridge", "Coupon", "Permit", "Referral"] as const, - }, - reference: { - name: "reference", - label: "Reference", - view: "text", - htmlType: "text", - rules: { required: "Reference is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, - }, -} as const; - -export type AuthFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: AuthFilter[]; - and?: AuthFilter[]; -}; - -export type Auth = BridgeAuth | CouponAuth | PermitAuth | ReferralAuth; - -/** True when value is a BridgeAuth (discriminated by type === "Bridge"). */ -export function isBridgeAuth(value: Auth): value is BridgeAuth { - return value.type === "Bridge"; -} - -/** True when value is a CouponAuth (discriminated by type === "Coupon"). */ -export function isCouponAuth(value: Auth): value is CouponAuth { - return value.type === "Coupon"; -} - -/** True when value is a PermitAuth (discriminated by type === "Permit"). */ -export function isPermitAuth(value: Auth): value is PermitAuth { - return value.type === "Permit"; -} - -/** True when value is a ReferralAuth (discriminated by type === "Referral"). */ -export function isReferralAuth(value: Auth): value is ReferralAuth { - return value.type === "Referral"; -} - -/** - * Parse a row from the Auth table, dispatching by the - * `type` discriminator value to the matching subtype's - * Zod schema. Throws on unknown discriminator values. - */ -export function parseAuth(row: unknown): Auth { - const head = z.object({ type: z.enum(["Bridge", "Coupon", "Permit", "Referral"]) }).parse(row); - switch (head.type) { - case "Bridge": return BridgeAuthSchema.parse(row); - case "Coupon": return CouponAuthSchema.parse(row); - case "Permit": return PermitAuthSchema.parse(row); - case "Referral": return ReferralAuthSchema.parse(row); - } -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.names.ts deleted file mode 100644 index e9f026d125..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.names.ts +++ /dev/null @@ -1,18 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AuthsByKind - -export const AuthsByKindNames = { - type: "object", - subType: "report", - name: "AuthsByKind", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_auths_by_kind" }, - }, - fields: { - auths: { name: "auths", column: "auths" }, - distinctRefs: { name: "distinctRefs", column: "distinct_refs" }, - kind: { name: "kind", column: "kind" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.queries.ts deleted file mode 100644 index cc02874029..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AuthsByKind (AuthsByKind) — report (read-only) -// Extend in your own module (e.g. AuthsByKind.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type AuthsByKind, authsByKindView } from "./AuthsByKind.js"; - -type Db = PgDatabase>; - -export async function listAuthsByKinds(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(authsByKindView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.ts deleted file mode 100644 index 6e9c1bcd5d..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/AuthsByKind.ts +++ /dev/null @@ -1,42 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: AuthsByKind (AuthsByKind) - -import { bigint, pgView, text } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const authsByKindView = pgView("v_auths_by_kind", { - kind: text("kind", { enum: ["Bridge", "Coupon", "Permit", "Referral"] as const }), - auths: bigint("auths", { mode: "number" }).notNull(), - distinctRefs: bigint("distinct_refs", { mode: "number" }).notNull(), -}).existing(); - -export const AuthsByKindSchema = z.object({ - kind: z.enum(["Bridge", "Coupon", "Permit", "Referral"]).nullable(), - auths: z.number().int(), - distinctRefs: z.number().int(), -}); - -export type AuthsByKind = z.infer; - -export const AuthsByKind = { - $entity: "AuthsByKind", - $view: "v_auths_by_kind", - $path: "/auths_by_kinds", - kind: { name: "kind", label: "Kind", view: "dropdown", dbCol: "kind" }, - auths: { name: "auths", label: "Auths", view: "number", dbCol: "auths" }, - distinctRefs: { name: "distinctRefs", label: "Distinct Refs", view: "number", dbCol: "distinct_refs" }, -} as const; - -export type AuthsByKindFilter = { - limit?: number; - offset?: number; - sort?: `${"kind" | "auths" | "distinctRefs"}:${"asc" | "desc"}` | "kind" | "auths" | "distinctRefs"; - kind?: "Bridge" | "Coupon" | "Permit" | "Referral" | { eq?: "Bridge" | "Coupon" | "Permit" | "Referral"; ne?: "Bridge" | "Coupon" | "Permit" | "Referral"; in?: ("Bridge" | "Coupon" | "Permit" | "Referral")[]; like?: string; isNull?: boolean }; - auths?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - distinctRefs?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: AuthsByKindFilter[]; - and?: AuthsByKindFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.names.ts deleted file mode 100644 index 50cce25f69..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.names.ts +++ /dev/null @@ -1,23 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: BridgeAuth - -import { AuthNames } from "./Auth.names.js"; - -export const BridgeAuthNames = { - type: "object", - subType: "entity", - name: "BridgeAuth", - sources: { - ...AuthNames.sources, - }, - fields: { - ...AuthNames.fields, - quantity: { name: "quantity", column: "quantity" }, - }, - identities: { - ...AuthNames.identities, - }, - indexes: { - ...AuthNames.indexes, - }, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.ts deleted file mode 100644 index c99e85cae0..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/BridgeAuth.ts +++ /dev/null @@ -1,113 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: BridgeAuth (BridgeAuth) -// Extend in your own module (e.g. BridgeAuth.extra.ts) — nothing imports it for you. - -import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; -import { z } from "zod"; - -export interface BridgeAuth { - id?: number | undefined; - type?: BridgeAuthType | null | undefined; - reference: string; - quantity: number | null; -} - -export type BridgeAuthType = "Bridge" | "Coupon" | "Permit" | "Referral"; -export const BridgeAuthTypeEnum = z.enum(["Bridge", "Coupon", "Permit", "Referral"]); - -export const BridgeAuthSchema = z.object({ - id: z.number().int(), - type: z.literal("Bridge"), - reference: z.string().min(1).max(80), - quantity: z.number().int().nullable(), -}); - -export const BridgeAuthInsertSchema = z.object({ - type: z.literal("Bridge"), - reference: z.string().min(1).max(80), - quantity: z.number().int(), -}); - -export const BridgeAuthUpdateSchema = z.object({ - reference: z.string().min(1).max(80).optional(), - quantity: z.number().int().optional(), -}); - -/** - * Typed create shape for BridgeAuth: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createBridgeAuth` call site; - * the schema still validates at runtime. - */ -export type BridgeAuthCreate = z.input; - -/** - * Typed patch shape for BridgeAuth: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateBridgeAuth` call site. - */ -export type BridgeAuthPatch = z.input; - -/** - * Metadata constants for BridgeAuth. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(BridgeAuth, BridgeAuthInsertSchema); - * - */ -export const BridgeAuth = { - $entity: "BridgeAuth", - $table: "auths", - $path: "/auths/bridge", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - type: { - name: "type", - label: "Type", - view: "dropdown", - options: ["Bridge", "Coupon", "Permit", "Referral"] as const, - }, - reference: { - name: "reference", - label: "Reference", - view: "text", - htmlType: "text", - rules: { required: "Reference is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, - }, - quantity: { - name: "quantity", - label: "Quantity", - view: "number", - htmlType: "number", - rules: { required: "Quantity is required" }, - }, -} as const; - -export const BridgeAuthFilterAllowlist = {} as const satisfies FilterAllowlist; - -export const BridgeAuthSortAllowlist = {} as const satisfies SortAllowlist; - -export type BridgeAuthFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: BridgeAuthFilter[]; - and?: BridgeAuthFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.names.ts deleted file mode 100644 index e5bcb0fbb7..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.names.ts +++ /dev/null @@ -1,23 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: CouponAuth - -import { AuthNames } from "./Auth.names.js"; - -export const CouponAuthNames = { - type: "object", - subType: "entity", - name: "CouponAuth", - sources: { - ...AuthNames.sources, - }, - fields: { - ...AuthNames.fields, - couponAmount: { name: "couponAmount", column: "coupon_amount" }, - }, - identities: { - ...AuthNames.identities, - }, - indexes: { - ...AuthNames.indexes, - }, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.ts deleted file mode 100644 index a426a9cb77..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/CouponAuth.ts +++ /dev/null @@ -1,151 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: CouponAuth (CouponAuth) -// Extend in your own module (e.g. CouponAuth.extra.ts) — nothing imports it for you. - -import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; -import { z } from "zod"; - -export interface CouponAuth { - id?: number | undefined; - type?: CouponAuthType | null | undefined; - reference: string; - couponAmount?: string | null | undefined; -} - -export type CouponAuthType = "Bridge" | "Coupon" | "Permit" | "Referral"; -export const CouponAuthTypeEnum = z.enum(["Bridge", "Coupon", "Permit", "Referral"]); - -export const CouponAuthSchema = z.object({ - id: z.number().int(), - type: z.literal("Coupon"), - reference: z.string().min(1).max(80), - couponAmount: z.string().nullable(), -}); - -/** A field.decimal on the wire: a string in the JSON-number grammar (an exponent is allowed) or a JSON - * number, rewritten to its canonical string (plain notation, no trailing fraction zeros, zero as "0"). - * Garbage, or a value the column cannot hold without rounding, is a validation issue. Generated. */ -function decimalWrite(v: string | number, ctx: z.RefinementCtx, precision?: number, scale = 0): string { - if (typeof v === "number" && Number.isFinite(v) && !Number.isSafeInteger(v) && Number(v.toPrecision(15)) !== v) { - ctx.addIssue({ code: "custom", message: "Decimal number cannot be read exactly as a JSON number; send it as a string" }); - return z.NEVER; - } - const text = typeof v === "number" ? (Number.isFinite(v) ? String(v) : "") : v; - const m = /^(-?)(0|[1-9][0-9]*)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/.exec(text); - const e = m === null || m[4] === undefined ? 0 : Number(m[4]); - if (m === null || !Number.isSafeInteger(e) || Math.abs(e) > 1000) { - ctx.addIssue({ code: "custom", message: "Not a decimal number" }); - return z.NEVER; - } - const whole = m[2] ?? ""; - let digits = whole + (m[3] ?? ""); - let point = whole.length + e; - const lead = digits.length - digits.replace(/^0+/, "").length; - digits = digits.slice(lead).replace(/0+$/, ""); - point -= lead; - if (digits.length === 0) { - return "0"; - } - const plain = point <= 0 - ? `0.${"0".repeat(-point)}${digits}` - : point >= digits.length - ? digits + "0".repeat(point - digits.length) - : `${digits.slice(0, point)}.${digits.slice(point)}`; - const fraction = point >= digits.length ? 0 : digits.length - Math.max(point, 0) + Math.max(-point, 0); - const integer = Math.max(point, 0); - if (plain.length > 1000 || (precision !== undefined && (fraction > scale || integer > precision - scale))) { - ctx.addIssue({ code: "custom", message: "Decimal out of range for the column" }); - return z.NEVER; - } - return m[1] === "-" ? `-${plain}` : plain; -} - -export const CouponAuthInsertSchema = z.object({ - type: z.literal("Coupon"), - reference: z.string().min(1).max(80), - couponAmount: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 10, 2)).optional(), -}); - -export const CouponAuthUpdateSchema = z.object({ - reference: z.string().min(1).max(80).optional(), - couponAmount: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 10, 2)).optional().nullable(), -}); - -/** - * Typed create shape for CouponAuth: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createCouponAuth` call site; - * the schema still validates at runtime. - */ -export type CouponAuthCreate = z.input; - -/** - * Typed patch shape for CouponAuth: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateCouponAuth` call site. - */ -export type CouponAuthPatch = z.input; - -/** - * Metadata constants for CouponAuth. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(CouponAuth, CouponAuthInsertSchema); - * - */ -export const CouponAuth = { - $entity: "CouponAuth", - $table: "auths", - $path: "/auths/coupon", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - type: { - name: "type", - label: "Type", - view: "dropdown", - options: ["Bridge", "Coupon", "Permit", "Referral"] as const, - }, - reference: { - name: "reference", - label: "Reference", - view: "text", - htmlType: "text", - rules: { required: "Reference is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, - }, - couponAmount: { - name: "couponAmount", - label: "Coupon Amount", - view: "number", - htmlType: "text", - inputMode: "decimal", - }, -} as const; - -export const CouponAuthFilterAllowlist = {} as const satisfies FilterAllowlist; - -export const CouponAuthSortAllowlist = {} as const satisfies SortAllowlist; - -export type CouponAuthFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: CouponAuthFilter[]; - and?: CouponAuthFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.names.ts deleted file mode 100644 index c1bcc078cd..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.names.ts +++ /dev/null @@ -1,21 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Entry - -export const EntryNames = { - type: "object", - subType: "entity", - name: "Entry", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "entries" }, - }, - fields: { - amount: { name: "amount", column: "amount" }, - bucket: { name: "bucket", column: "bucket" }, - flagged: { name: "flagged", column: "flagged" }, - id: { name: "id", column: "id" }, - }, - identities: { - pk: { type: "identity", subType: "primary", name: "pk" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.queries.ts deleted file mode 100644 index 2476e693ea..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.queries.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Entry (Entry) -// Extend in your own module (e.g. Entry.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { type Entry, EntryInsertSchema, type EntryPatch, EntryUpdateSchema, entries } from "./Entry.js"; - -type Db = PgDatabase>; - -export async function findEntryById(db: Db, id: number): Promise { - const [entry] = await db.select().from(entries).where(eq(entries.id, id)).limit(1); - return entry ?? null; -} - -export async function listEntries(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(entries).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createEntry(db: Db, data: z.input): Promise { - const validated = EntryInsertSchema.parse(data); - const [entry] = await db.insert(entries).values(validated).returning(); - return entry!; -} - -export async function updateEntry(db: Db, id: number, patch: EntryPatch): Promise { - const validated = EntryUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findEntryById(db, id); - } - const [entry] = await db.update(entries).set(validated).where(eq(entries.id, id)).returning(); - return entry ?? null; -} - -export async function deleteEntryById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(entries).where(eq(entries.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.ts deleted file mode 100644 index 0a054f4ba0..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Entry.ts +++ /dev/null @@ -1,145 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Entry (Entry) -// Extend in your own module (e.g. Entry.extra.ts) — nothing imports it for you. - -import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { bigint, boolean, numeric, pgTable, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -export const entries = pgTable("entries", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - bucket: varchar("bucket", { length: 8 }).notNull(), - amount: numeric("amount", { precision: 28, scale: 10 }), - flagged: boolean("flagged").notNull(), -}); - -export type Entry = InferSelectModel; -export type EntryInsert = InferInsertModel; -export type EntryUpdate = Partial; - -/** A field.decimal on the wire: a string in the JSON-number grammar (an exponent is allowed) or a JSON - * number, rewritten to its canonical string (plain notation, no trailing fraction zeros, zero as "0"). - * Garbage, or a value the column cannot hold without rounding, is a validation issue. Generated. */ -function decimalWrite(v: string | number, ctx: z.RefinementCtx, precision?: number, scale = 0): string { - if (typeof v === "number" && Number.isFinite(v) && !Number.isSafeInteger(v) && Number(v.toPrecision(15)) !== v) { - ctx.addIssue({ code: "custom", message: "Decimal number cannot be read exactly as a JSON number; send it as a string" }); - return z.NEVER; - } - const text = typeof v === "number" ? (Number.isFinite(v) ? String(v) : "") : v; - const m = /^(-?)(0|[1-9][0-9]*)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/.exec(text); - const e = m === null || m[4] === undefined ? 0 : Number(m[4]); - if (m === null || !Number.isSafeInteger(e) || Math.abs(e) > 1000) { - ctx.addIssue({ code: "custom", message: "Not a decimal number" }); - return z.NEVER; - } - const whole = m[2] ?? ""; - let digits = whole + (m[3] ?? ""); - let point = whole.length + e; - const lead = digits.length - digits.replace(/^0+/, "").length; - digits = digits.slice(lead).replace(/0+$/, ""); - point -= lead; - if (digits.length === 0) { - return "0"; - } - const plain = point <= 0 - ? `0.${"0".repeat(-point)}${digits}` - : point >= digits.length - ? digits + "0".repeat(point - digits.length) - : `${digits.slice(0, point)}.${digits.slice(point)}`; - const fraction = point >= digits.length ? 0 : digits.length - Math.max(point, 0) + Math.max(-point, 0); - const integer = Math.max(point, 0); - if (plain.length > 1000 || (precision !== undefined && (fraction > scale || integer > precision - scale))) { - ctx.addIssue({ code: "custom", message: "Decimal out of range for the column" }); - return z.NEVER; - } - return m[1] === "-" ? `-${plain}` : plain; -} - -export const EntryInsertSchema = z.object({ - bucket: z.string().min(1).max(8), - amount: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 28, 10)).optional(), - flagged: z.boolean(), -}); - -export const EntryUpdateSchema = z.object({ - bucket: z.string().min(1).max(8).optional(), - amount: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 28, 10)).optional().nullable(), - flagged: z.boolean().optional(), -}); - -/** - * Typed create shape for Entry: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createEntry` call site; - * the schema still validates at runtime. - */ -export type EntryCreate = z.input; - -/** - * Typed patch shape for Entry: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateEntry` call site. - */ -export type EntryPatch = z.input; - -/** - * Metadata constants for Entry. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Entry, EntryInsertSchema); - * - */ -export const Entry = { - $entity: "Entry", - $table: "entries", - $path: "/entries", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - bucket: { - name: "bucket", - label: "Bucket", - view: "text", - htmlType: "text", - rules: { required: "Bucket is required", maxLength: { value: 8, message: "Must be 8 characters or fewer" } }, - }, - amount: { - name: "amount", - label: "Amount", - view: "number", - htmlType: "text", - inputMode: "decimal", - }, - flagged: { - name: "flagged", - label: "Flagged", - view: "checkbox", - htmlType: "checkbox", - rules: { required: "Flagged is required" }, - }, -} as const; - -export type EntryFilter = { - limit?: number; - offset?: number; - sort?: `${"amount"}:${"asc" | "desc"}` | "amount"; - amount?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - or?: EntryFilter[]; - and?: EntryFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.names.ts deleted file mode 100644 index 0a6596155c..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.names.ts +++ /dev/null @@ -1,23 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: EntryTotals - -export const EntryTotalsNames = { - type: "object", - subType: "report", - name: "EntryTotals", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_entry_totals" }, - }, - fields: { - bucket: { name: "bucket", column: "bucket" }, - entries: { name: "entries", column: "entries" }, - flaggedShare: { name: "flaggedShare", column: "flagged_share" }, - mean: { name: "mean", column: "mean" }, - perFlagged: { name: "perFlagged", column: "per_flagged" }, - top: { name: "top", column: "top" }, - total: { name: "total", column: "total" }, - totalOrZero: { name: "totalOrZero", column: "total_or_zero" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.queries.ts deleted file mode 100644 index 7d98ec8664..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: EntryTotals (EntryTotals) — report (read-only) -// Extend in your own module (e.g. EntryTotals.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type EntryTotals, entryTotalsView } from "./EntryTotals.js"; - -type Db = PgDatabase>; - -export async function listEntryTotals(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(entryTotalsView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.ts deleted file mode 100644 index 8652f8fa1c..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/EntryTotals.ts +++ /dev/null @@ -1,62 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: EntryTotals (EntryTotals) - -import { bigint, numeric, pgView, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const entryTotalsView = pgView("v_entry_totals", { - bucket: varchar("bucket", { length: 8 }).notNull(), - entries: bigint("entries", { mode: "number" }).notNull(), - total: numeric("total", { precision: 19, scale: 4 }), - totalOrZero: numeric("total_or_zero", { precision: 19, scale: 4 }).notNull(), - mean: numeric("mean", { precision: 19, scale: 4 }), - top: numeric("top", { precision: 28, scale: 10 }), - flaggedShare: numeric("flagged_share", { precision: 19, scale: 4 }), - perFlagged: numeric("per_flagged", { precision: 19, scale: 4 }), -}).existing(); - -export const EntryTotalsSchema = z.object({ - bucket: z.string(), - entries: z.number().int(), - total: z.string().nullable(), - totalOrZero: z.string(), - mean: z.string().nullable(), - top: z.string().nullable(), - flaggedShare: z.string().nullable(), - perFlagged: z.string().nullable(), -}); - -export type EntryTotals = z.infer; - -export const EntryTotals = { - $entity: "EntryTotals", - $view: "v_entry_totals", - $path: "/entry_totals", - bucket: { name: "bucket", label: "Bucket", view: "text", dbCol: "bucket" }, - entries: { name: "entries", label: "Entries", view: "number", dbCol: "entries" }, - total: { name: "total", label: "Total", view: "number", dbCol: "total" }, - totalOrZero: { name: "totalOrZero", label: "Total Or Zero", view: "number", dbCol: "total_or_zero" }, - mean: { name: "mean", label: "Mean", view: "number", dbCol: "mean" }, - top: { name: "top", label: "Top", view: "number", dbCol: "top" }, - flaggedShare: { name: "flaggedShare", label: "Flagged Share", view: "number", dbCol: "flagged_share" }, - perFlagged: { name: "perFlagged", label: "Per Flagged", view: "number", dbCol: "per_flagged" }, -} as const; - -export type EntryTotalsFilter = { - limit?: number; - offset?: number; - sort?: `${"bucket" | "entries" | "total" | "totalOrZero" | "mean" | "top" | "flaggedShare" | "perFlagged"}:${"asc" | "desc"}` | "bucket" | "entries" | "total" | "totalOrZero" | "mean" | "top" | "flaggedShare" | "perFlagged"; - bucket?: string | { eq?: string; ne?: string; in?: string[]; like?: string; isNull?: boolean }; - entries?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - total?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - totalOrZero?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - mean?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - top?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - flaggedShare?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - perFlagged?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - or?: EntryTotalsFilter[]; - and?: EntryTotalsFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.names.ts deleted file mode 100644 index 905a3db475..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.names.ts +++ /dev/null @@ -1,18 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: FitnessTotals - -export const FitnessTotalsNames = { - type: "object", - subType: "report", - name: "FitnessTotals", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_fitness_totals" }, - }, - fields: { - longShare: { name: "longShare", column: "long_share" }, - totalMinutes: { name: "totalMinutes", column: "total_minutes" }, - weeks: { name: "weeks", column: "weeks" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.queries.ts deleted file mode 100644 index 851b00c13c..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: FitnessTotals (FitnessTotals) — report (read-only) -// Extend in your own module (e.g. FitnessTotals.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type FitnessTotals, fitnessTotalsView } from "./FitnessTotals.js"; - -type Db = PgDatabase>; - -export async function listFitnessTotals(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(fitnessTotalsView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.ts deleted file mode 100644 index 9053045feb..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotals.ts +++ /dev/null @@ -1,42 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: FitnessTotals (FitnessTotals) - -import { bigint, numeric, pgView } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const fitnessTotalsView = pgView("v_fitness_totals", { - weeks: bigint("weeks", { mode: "number" }).notNull(), - totalMinutes: bigint("total_minutes", { mode: "number" }), - longShare: numeric("long_share", { precision: 19, scale: 4 }), -}).existing(); - -export const FitnessTotalsSchema = z.object({ - weeks: z.number().int(), - totalMinutes: z.number().int().nullable(), - longShare: z.string().nullable(), -}); - -export type FitnessTotals = z.infer; - -export const FitnessTotals = { - $entity: "FitnessTotals", - $view: "v_fitness_totals", - $path: "/fitness_totals", - weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, - totalMinutes: { name: "totalMinutes", label: "Total Minutes", view: "number", dbCol: "total_minutes" }, - longShare: { name: "longShare", label: "Long Share", view: "number", dbCol: "long_share" }, -} as const; - -export type FitnessTotalsFilter = { - limit?: number; - offset?: number; - sort?: `${"weeks" | "totalMinutes" | "longShare"}:${"asc" | "desc"}` | "weeks" | "totalMinutes" | "longShare"; - weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - totalMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - longShare?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - or?: FitnessTotalsFilter[]; - and?: FitnessTotalsFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.names.ts deleted file mode 100644 index 1a5bb1faf1..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.names.ts +++ /dev/null @@ -1,18 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: FitnessTotalsFilled - -export const FitnessTotalsFilledNames = { - type: "object", - subType: "report", - name: "FitnessTotalsFilled", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_fitness_totals_filled" }, - }, - fields: { - longShareOrZero: { name: "longShareOrZero", column: "long_share_or_zero" }, - totalMinutesOrZero: { name: "totalMinutesOrZero", column: "total_minutes_or_zero" }, - weeks: { name: "weeks", column: "weeks" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.queries.ts deleted file mode 100644 index f19012360d..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: FitnessTotalsFilled (FitnessTotalsFilled) — report (read-only) -// Extend in your own module (e.g. FitnessTotalsFilled.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type FitnessTotalsFilled, fitnessTotalsFilledView } from "./FitnessTotalsFilled.js"; - -type Db = PgDatabase>; - -export async function listFitnessTotalsFilleds(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(fitnessTotalsFilledView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.ts deleted file mode 100644 index cb0d6b45c2..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/FitnessTotalsFilled.ts +++ /dev/null @@ -1,42 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: FitnessTotalsFilled (FitnessTotalsFilled) - -import { bigint, numeric, pgView } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const fitnessTotalsFilledView = pgView("v_fitness_totals_filled", { - weeks: bigint("weeks", { mode: "number" }).notNull(), - totalMinutesOrZero: bigint("total_minutes_or_zero", { mode: "number" }).notNull(), - longShareOrZero: numeric("long_share_or_zero", { precision: 19, scale: 4 }).notNull(), -}).existing(); - -export const FitnessTotalsFilledSchema = z.object({ - weeks: z.number().int(), - totalMinutesOrZero: z.number().int(), - longShareOrZero: z.string(), -}); - -export type FitnessTotalsFilled = z.infer; - -export const FitnessTotalsFilled = { - $entity: "FitnessTotalsFilled", - $view: "v_fitness_totals_filled", - $path: "/fitness_totals_filleds", - weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, - totalMinutesOrZero: { name: "totalMinutesOrZero", label: "Total Minutes Or Zero", view: "number", dbCol: "total_minutes_or_zero" }, - longShareOrZero: { name: "longShareOrZero", label: "Long Share Or Zero", view: "number", dbCol: "long_share_or_zero" }, -} as const; - -export type FitnessTotalsFilledFilter = { - limit?: number; - offset?: number; - sort?: `${"weeks" | "totalMinutesOrZero" | "longShareOrZero"}:${"asc" | "desc"}` | "weeks" | "totalMinutesOrZero" | "longShareOrZero"; - weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - totalMinutesOrZero?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - longShareOrZero?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - or?: FitnessTotalsFilledFilter[]; - and?: FitnessTotalsFilledFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.names.ts deleted file mode 100644 index ada76da34c..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.names.ts +++ /dev/null @@ -1,21 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Follow - -export const FollowNames = { - type: "object", - subType: "entity", - name: "Follow", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "follows" }, - }, - fields: { - followeeId: { name: "followeeId", column: "followee_id" }, - followerId: { name: "followerId", column: "follower_id" }, - }, - identities: { - fkFollowee: { type: "identity", subType: "reference", name: "fkFollowee" }, - fkFollower: { type: "identity", subType: "reference", name: "fkFollower" }, - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.queries.ts deleted file mode 100644 index 1a9d7990ee..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.queries.ts +++ /dev/null @@ -1,72 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Follow (Follow) -// Extend in your own module (e.g. Follow.extra.ts) — nothing imports it for you. - -import { eq, inArray } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { type Follow, FollowInsertSchema, type FollowPatch, FollowUpdateSchema, follows } from "./Follow.js"; - -type Db = PgDatabase>; - -export async function findFollowById(db: Db, followerId: number): Promise { - const [follow] = await db.select().from(follows).where(eq(follows.followerId, followerId)).limit(1); - return follow ?? null; -} - -export async function listFollows(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(follows).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createFollow(db: Db, data: z.input): Promise { - const validated = FollowInsertSchema.parse(data); - const [follow] = await db.insert(follows).values(validated).returning(); - return follow!; -} - -export async function updateFollow(db: Db, followerId: number, patch: FollowPatch): Promise { - const validated = FollowUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findFollowById(db, followerId); - } - const [follow] = await db.update(follows).set(validated).where(eq(follows.followerId, followerId)).returning(); - return follow ?? null; -} - -export async function deleteFollowById(db: Db, followerId: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(follows).where(eq(follows.followerId, followerId)).returning(); - return deleted.length > 0; -} - -export async function findFollowsByFollower(db: Db, followerId: number): Promise { - return db.select().from(follows).where(eq(follows.followerId, followerId)); -} - -export async function findFollowsByFollowerIn(db: Db, followerIds: number[]): Promise { - if (followerIds.length === 0) { - return []; - } - return db.select().from(follows).where(inArray(follows.followerId, followerIds)); -} - -export async function findFollowsByFollowee(db: Db, followeeId: number): Promise { - return db.select().from(follows).where(eq(follows.followeeId, followeeId)); -} - -export async function findFollowsByFolloweeIn(db: Db, followeeIds: number[]): Promise { - if (followeeIds.length === 0) { - return []; - } - return db.select().from(follows).where(inArray(follows.followeeId, followeeIds)); -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.ts deleted file mode 100644 index 1d28088137..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Follow.ts +++ /dev/null @@ -1,92 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Follow (Follow) -// Extend in your own module (e.g. Follow.extra.ts) — nothing imports it for you. - -import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; -import { bigint, pgTable, primaryKey } from "drizzle-orm/pg-core"; -import { z } from "zod"; -import { persons } from "./Person.js"; - -export const follows = pgTable("follows", { - followerId: bigint("follower_id", { mode: "number" }).notNull(), - followeeId: bigint("followee_id", { mode: "number" }).notNull(), -}, (table) => [primaryKey({ columns: [table.followerId, table.followeeId] })]); - -export const followsRelations = relations(follows, ({ one }) => ({ - fkFollower: one(persons, { fields: [follows.followerId], references: [persons.id] }), - fkFollowee: one(persons, { fields: [follows.followeeId], references: [persons.id] }), -})); - -export type Follow = InferSelectModel; -export type FollowInsert = InferInsertModel; -export type FollowUpdate = Partial; - -export const FollowInsertSchema = z.object({ - followerId: z.number().int(), - followeeId: z.number().int(), -}); - -export const FollowUpdateSchema = z.object({}); - -/** - * Typed create shape for Follow: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createFollow` call site; - * the schema still validates at runtime. - */ -export type FollowCreate = z.input; - -/** - * Typed patch shape for Follow: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateFollow` call site. - */ -export type FollowPatch = z.input; - -/** - * Metadata constants for Follow. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Follow, FollowInsertSchema); - * - */ -export const Follow = { - $entity: "Follow", - $table: "follows", - $path: "/follows", - followerId: { - name: "followerId", - label: "Follower Id", - view: "number", - htmlType: "number", - rules: { required: "Follower Id is required" }, - }, - followeeId: { - name: "followeeId", - label: "Followee Id", - view: "number", - htmlType: "number", - rules: { required: "Followee Id is required" }, - }, -} as const; - -export type FollowFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: FollowFilter[]; - and?: FollowFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.names.ts deleted file mode 100644 index ea1532290b..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.names.ts +++ /dev/null @@ -1,21 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Friendship - -export const FriendshipNames = { - type: "object", - subType: "entity", - name: "Friendship", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "friendships" }, - }, - fields: { - personAId: { name: "personAId", column: "person_a_id" }, - personBId: { name: "personBId", column: "person_b_id" }, - }, - identities: { - fkPersonA: { type: "identity", subType: "reference", name: "fkPersonA" }, - fkPersonB: { type: "identity", subType: "reference", name: "fkPersonB" }, - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.queries.ts deleted file mode 100644 index f74e318f7b..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.queries.ts +++ /dev/null @@ -1,78 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Friendship (Friendship) -// Extend in your own module (e.g. Friendship.extra.ts) — nothing imports it for you. - -import { eq, inArray } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { - type Friendship, - FriendshipInsertSchema, - type FriendshipPatch, - FriendshipUpdateSchema, - friendships, -} from "./Friendship.js"; - -type Db = PgDatabase>; - -export async function findFriendshipById(db: Db, personAId: number): Promise { - const [friendship] = await db.select().from(friendships).where(eq(friendships.personAId, personAId)).limit(1); - return friendship ?? null; -} - -export async function listFriendships(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(friendships).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createFriendship(db: Db, data: z.input): Promise { - const validated = FriendshipInsertSchema.parse(data); - const [friendship] = await db.insert(friendships).values(validated).returning(); - return friendship!; -} - -export async function updateFriendship(db: Db, personAId: number, patch: FriendshipPatch): Promise { - const validated = FriendshipUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findFriendshipById(db, personAId); - } - const [friendship] = await db.update(friendships).set(validated).where(eq(friendships.personAId, personAId)).returning(); - return friendship ?? null; -} - -export async function deleteFriendshipById(db: Db, personAId: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(friendships).where(eq(friendships.personAId, personAId)).returning(); - return deleted.length > 0; -} - -export async function findFriendshipsByPersonA(db: Db, personAId: number): Promise { - return db.select().from(friendships).where(eq(friendships.personAId, personAId)); -} - -export async function findFriendshipsByPersonAIn(db: Db, personAIds: number[]): Promise { - if (personAIds.length === 0) { - return []; - } - return db.select().from(friendships).where(inArray(friendships.personAId, personAIds)); -} - -export async function findFriendshipsByPersonB(db: Db, personBId: number): Promise { - return db.select().from(friendships).where(eq(friendships.personBId, personBId)); -} - -export async function findFriendshipsByPersonBIn(db: Db, personBIds: number[]): Promise { - if (personBIds.length === 0) { - return []; - } - return db.select().from(friendships).where(inArray(friendships.personBId, personBIds)); -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.ts deleted file mode 100644 index 49629badd1..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Friendship.ts +++ /dev/null @@ -1,92 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Friendship (Friendship) -// Extend in your own module (e.g. Friendship.extra.ts) — nothing imports it for you. - -import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; -import { bigint, pgTable, primaryKey } from "drizzle-orm/pg-core"; -import { z } from "zod"; -import { persons } from "./Person.js"; - -export const friendships = pgTable("friendships", { - personAId: bigint("person_a_id", { mode: "number" }).notNull(), - personBId: bigint("person_b_id", { mode: "number" }).notNull(), -}, (table) => [primaryKey({ columns: [table.personAId, table.personBId] })]); - -export const friendshipsRelations = relations(friendships, ({ one }) => ({ - fkPersonA: one(persons, { fields: [friendships.personAId], references: [persons.id] }), - fkPersonB: one(persons, { fields: [friendships.personBId], references: [persons.id] }), -})); - -export type Friendship = InferSelectModel; -export type FriendshipInsert = InferInsertModel; -export type FriendshipUpdate = Partial; - -export const FriendshipInsertSchema = z.object({ - personAId: z.number().int(), - personBId: z.number().int(), -}); - -export const FriendshipUpdateSchema = z.object({}); - -/** - * Typed create shape for Friendship: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createFriendship` call site; - * the schema still validates at runtime. - */ -export type FriendshipCreate = z.input; - -/** - * Typed patch shape for Friendship: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateFriendship` call site. - */ -export type FriendshipPatch = z.input; - -/** - * Metadata constants for Friendship. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Friendship, FriendshipInsertSchema); - * - */ -export const Friendship = { - $entity: "Friendship", - $table: "friendships", - $path: "/friendships", - personAId: { - name: "personAId", - label: "Person AId", - view: "number", - htmlType: "number", - rules: { required: "Person AId is required" }, - }, - personBId: { - name: "personBId", - label: "Person BId", - view: "number", - htmlType: "number", - rules: { required: "Person BId is required" }, - }, -} as const; - -export type FriendshipFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: FriendshipFilter[]; - and?: FriendshipFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.names.ts deleted file mode 100644 index c63d5dab15..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.names.ts +++ /dev/null @@ -1,23 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Gadget - -import { LabeledNames } from "./Labeled.names.js"; - -export const GadgetNames = { - type: "object", - subType: "entity", - name: "Gadget", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "gadgets" }, - }, - fields: { - ...LabeledNames.fields, - label: { name: "label", column: "gadget_code" }, - }, - identities: { - ...LabeledNames.identities, - }, - indexes: { - ...LabeledNames.indexes, - }, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.queries.ts deleted file mode 100644 index b4a6ff1389..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.queries.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Gadget (Gadget) -// Extend in your own module (e.g. Gadget.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { type Gadget, GadgetInsertSchema, type GadgetPatch, GadgetUpdateSchema, gadgets } from "./Gadget.js"; - -type Db = PgDatabase>; - -export async function findGadgetById(db: Db, id: number): Promise { - const [gadget] = await db.select().from(gadgets).where(eq(gadgets.id, id)).limit(1); - return gadget ?? null; -} - -export async function listGadgets(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(gadgets).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createGadget(db: Db, data: z.input): Promise { - const validated = GadgetInsertSchema.parse(data); - const [gadget] = await db.insert(gadgets).values(validated).returning(); - return gadget!; -} - -export async function updateGadget(db: Db, id: number, patch: GadgetPatch): Promise { - const validated = GadgetUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findGadgetById(db, id); - } - const [gadget] = await db.update(gadgets).set(validated).where(eq(gadgets.id, id)).returning(); - return gadget ?? null; -} - -export async function deleteGadgetById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(gadgets).where(eq(gadgets.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.ts deleted file mode 100644 index 5a05b8fcbe..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Gadget.ts +++ /dev/null @@ -1,86 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Gadget (Gadget) -// Extend in your own module (e.g. Gadget.extra.ts) — nothing imports it for you. - -import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { bigint, integer, pgTable } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -export const gadgets = pgTable("gadgets", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - label: integer("gadget_code").notNull(), -}); - -export type Gadget = InferSelectModel; -export type GadgetInsert = InferInsertModel; -export type GadgetUpdate = Partial; - -export const GadgetInsertSchema = z.object({ - label: z.number().int(), -}); - -export const GadgetUpdateSchema = z.object({ - label: z.number().int().optional(), -}); - -/** - * Typed create shape for Gadget: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createGadget` call site; - * the schema still validates at runtime. - */ -export type GadgetCreate = z.input; - -/** - * Typed patch shape for Gadget: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateGadget` call site. - */ -export type GadgetPatch = z.input; - -/** - * Metadata constants for Gadget. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Gadget, GadgetInsertSchema); - * - */ -export const Gadget = { - $entity: "Gadget", - $table: "gadgets", - $path: "/gadgets", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - label: { - name: "label", - label: "Label", - view: "number", - htmlType: "number", - rules: { required: "Label is required" }, - }, -} as const; - -export type GadgetFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: GadgetFilter[]; - and?: GadgetFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.names.ts deleted file mode 100644 index 292c3c9a2e..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.names.ts +++ /dev/null @@ -1,20 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: GadgetEvent - -export const GadgetEventNames = { - type: "object", - subType: "entity", - name: "GadgetEvent", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "gadget_events" }, - }, - fields: { - gadgetId: { name: "gadgetId", column: "gadget_id" }, - id: { name: "id", column: "id" }, - }, - identities: { - fkGadget: { type: "identity", subType: "reference", name: "fkGadget" }, - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.queries.ts deleted file mode 100644 index f811fc3bf7..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.queries.ts +++ /dev/null @@ -1,67 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: GadgetEvent (GadgetEvent) -// Extend in your own module (e.g. GadgetEvent.extra.ts) — nothing imports it for you. - -import { eq, inArray } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { - type GadgetEvent, - GadgetEventInsertSchema, - type GadgetEventPatch, - GadgetEventUpdateSchema, - gadgetEvents, -} from "./GadgetEvent.js"; - -type Db = PgDatabase>; - -export async function findGadgetEventById(db: Db, id: number): Promise { - const [gadgetEvent] = await db.select().from(gadgetEvents).where(eq(gadgetEvents.id, id)).limit(1); - return gadgetEvent ?? null; -} - -export async function listGadgetEvents(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(gadgetEvents).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createGadgetEvent(db: Db, data: z.input): Promise { - const validated = GadgetEventInsertSchema.parse(data); - const [gadgetEvent] = await db.insert(gadgetEvents).values(validated).returning(); - return gadgetEvent!; -} - -export async function updateGadgetEvent(db: Db, id: number, patch: GadgetEventPatch): Promise { - const validated = GadgetEventUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findGadgetEventById(db, id); - } - const [gadgetEvent] = await db.update(gadgetEvents).set(validated).where(eq(gadgetEvents.id, id)).returning(); - return gadgetEvent ?? null; -} - -export async function deleteGadgetEventById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(gadgetEvents).where(eq(gadgetEvents.id, id)).returning(); - return deleted.length > 0; -} - -export async function findGadgetEventsByGadget(db: Db, gadgetId: number): Promise { - return db.select().from(gadgetEvents).where(eq(gadgetEvents.gadgetId, gadgetId)); -} - -export async function findGadgetEventsByGadgetIn(db: Db, gadgetIds: number[]): Promise { - if (gadgetIds.length === 0) { - return []; - } - return db.select().from(gadgetEvents).where(inArray(gadgetEvents.gadgetId, gadgetIds)); -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.ts deleted file mode 100644 index e86a8d357c..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEvent.ts +++ /dev/null @@ -1,87 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: GadgetEvent (GadgetEvent) -// Extend in your own module (e.g. GadgetEvent.extra.ts) — nothing imports it for you. - -import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { type AnyPgColumn, bigint, pgTable } from "drizzle-orm/pg-core"; -import { z } from "zod"; -import { gadgets } from "./Gadget.js"; - -export const gadgetEvents = pgTable("gadget_events", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - gadgetId: bigint("gadget_id", { mode: "number" }).notNull().references((): AnyPgColumn => gadgets.id), -}); - -export type GadgetEvent = InferSelectModel; -export type GadgetEventInsert = InferInsertModel; -export type GadgetEventUpdate = Partial; - -export const GadgetEventInsertSchema = z.object({ - gadgetId: z.number().int(), -}); - -export const GadgetEventUpdateSchema = z.object({ - gadgetId: z.number().int().optional(), -}); - -/** - * Typed create shape for GadgetEvent: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createGadgetEvent` call site; - * the schema still validates at runtime. - */ -export type GadgetEventCreate = z.input; - -/** - * Typed patch shape for GadgetEvent: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateGadgetEvent` call site. - */ -export type GadgetEventPatch = z.input; - -/** - * Metadata constants for GadgetEvent. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(GadgetEvent, GadgetEventInsertSchema); - * - */ -export const GadgetEvent = { - $entity: "GadgetEvent", - $table: "gadget_events", - $path: "/gadget_events", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - gadgetId: { - name: "gadgetId", - label: "Gadget Id", - view: "number", - htmlType: "number", - rules: { required: "Gadget Id is required" }, - }, -} as const; - -export type GadgetEventFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: GadgetEventFilter[]; - and?: GadgetEventFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.names.ts deleted file mode 100644 index 8eb2408f81..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.names.ts +++ /dev/null @@ -1,17 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: GadgetEventsByLabel - -export const GadgetEventsByLabelNames = { - type: "object", - subType: "report", - name: "GadgetEventsByLabel", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_gadget_events_by_label" }, - }, - fields: { - gadgetEvents: { name: "gadgetEvents", column: "gadget_events" }, - gadgetLabel: { name: "gadgetLabel", column: "gadget_label" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.queries.ts deleted file mode 100644 index 2e9124f5ce..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: GadgetEventsByLabel (GadgetEventsByLabel) — report (read-only) -// Extend in your own module (e.g. GadgetEventsByLabel.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type GadgetEventsByLabel, gadgetEventsByLabelView } from "./GadgetEventsByLabel.js"; - -type Db = PgDatabase>; - -export async function listGadgetEventsByLabels(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(gadgetEventsByLabelView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.ts deleted file mode 100644 index bddd2f961a..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/GadgetEventsByLabel.ts +++ /dev/null @@ -1,38 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: GadgetEventsByLabel (GadgetEventsByLabel) - -import { bigint, integer, pgView } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const gadgetEventsByLabelView = pgView("v_gadget_events_by_label", { - gadgetLabel: integer("gadget_label").notNull(), - gadgetEvents: bigint("gadget_events", { mode: "number" }).notNull(), -}).existing(); - -export const GadgetEventsByLabelSchema = z.object({ - gadgetLabel: z.number().int(), - gadgetEvents: z.number().int(), -}); - -export type GadgetEventsByLabel = z.infer; - -export const GadgetEventsByLabel = { - $entity: "GadgetEventsByLabel", - $view: "v_gadget_events_by_label", - $path: "/gadget_events_by_labels", - gadgetLabel: { name: "gadgetLabel", label: "Gadget Label", view: "number", dbCol: "gadget_label" }, - gadgetEvents: { name: "gadgetEvents", label: "Gadget Events", view: "number", dbCol: "gadget_events" }, -} as const; - -export type GadgetEventsByLabelFilter = { - limit?: number; - offset?: number; - sort?: `${"gadgetLabel" | "gadgetEvents"}:${"asc" | "desc"}` | "gadgetLabel" | "gadgetEvents"; - gadgetLabel?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - gadgetEvents?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: GadgetEventsByLabelFilter[]; - and?: GadgetEventsByLabelFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.names.ts deleted file mode 100644 index f6d70cb4df..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.names.ts +++ /dev/null @@ -1,20 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: IntEnumArray - -export const IntEnumArrayNames = { - type: "object", - subType: "entity", - name: "IntEnumArray", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "int_enum_arrays" }, - }, - fields: { - history: { name: "history", column: "history" }, - id: { name: "id", column: "id" }, - state: { name: "state", column: "state" }, - }, - identities: { - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.queries.ts deleted file mode 100644 index 4c91e9b867..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.queries.ts +++ /dev/null @@ -1,56 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: IntEnumArray (IntEnumArray) -// Extend in your own module (e.g. IntEnumArray.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { - type IntEnumArray, - IntEnumArrayInsertSchema, - type IntEnumArrayPatch, - IntEnumArrayUpdateSchema, - intEnumArrays, -} from "./IntEnumArray.js"; - -type Db = PgDatabase>; - -export async function findIntEnumArrayById(db: Db, id: number): Promise { - const [intEnumArray] = await db.select().from(intEnumArrays).where(eq(intEnumArrays.id, id)).limit(1); - return intEnumArray ?? null; -} - -export async function listIntEnumArrays(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(intEnumArrays).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createIntEnumArray(db: Db, data: z.input): Promise { - const validated = IntEnumArrayInsertSchema.parse(data); - const [intEnumArray] = await db.insert(intEnumArrays).values(validated).returning(); - return intEnumArray!; -} - -export async function updateIntEnumArray(db: Db, id: number, patch: IntEnumArrayPatch): Promise { - const validated = IntEnumArrayUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findIntEnumArrayById(db, id); - } - const [intEnumArray] = await db.update(intEnumArrays).set(validated).where(eq(intEnumArrays.id, id)).returning(); - return intEnumArray ?? null; -} - -export async function deleteIntEnumArrayById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(intEnumArrays).where(eq(intEnumArrays.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.ts deleted file mode 100644 index 9f17ba4cb0..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/IntEnumArray.ts +++ /dev/null @@ -1,134 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: IntEnumArray (IntEnumArray) -// Extend in your own module (e.g. IntEnumArray.extra.ts) — nothing imports it for you. - -import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; -import { bigint, check, customType, pgTable } from "drizzle-orm/pg-core"; -import { z } from "zod"; -import { PublishStateEnum } from "./enums.js"; - -const HISTORY_TO_INT = { "DRAFT": 0, "PUBLISHED": 5, "ARCHIVED": 9 } as const satisfies Record<"DRAFT" | "PUBLISHED" | "ARCHIVED", number>; -const HISTORY_FROM_INT: Record = { 0: "DRAFT", 5: "PUBLISHED", 9: "ARCHIVED" }; -const historyIntEnum = customType<{ data: "DRAFT" | "PUBLISHED" | "ARCHIVED"; driverData: number }>({ - dataType: () => "integer", - toDriver: (value) => { - const stored = HISTORY_TO_INT[value]; - if (stored === undefined) { - throw new Error(`unmapped historyIntEnum member: ${String(value)}`); - } - return stored; - }, - fromDriver: (value) => { - if (value === null) { - return value as never; - } - const member = HISTORY_FROM_INT[value]; - if (member === undefined) { - throw new Error(`unmapped historyIntEnum value: ${value}`); - } - return member; - }, -}); - -const STATE_TO_INT = { "DRAFT": 0, "PUBLISHED": 5, "ARCHIVED": 9 } as const satisfies Record<"DRAFT" | "PUBLISHED" | "ARCHIVED", number>; -const STATE_FROM_INT: Record = { 0: "DRAFT", 5: "PUBLISHED", 9: "ARCHIVED" }; -const stateIntEnum = customType<{ data: "DRAFT" | "PUBLISHED" | "ARCHIVED"; driverData: number }>({ - dataType: () => "integer", - toDriver: (value) => STATE_TO_INT[value], - fromDriver: (value) => { - const member = STATE_FROM_INT[value]; - if (member === undefined) { - throw new Error(`unmapped stateIntEnum value: ${value}`); - } - return member; - }, -}); - -export const intEnumArrays = pgTable("int_enum_arrays", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - state: stateIntEnum("state"), - history: historyIntEnum("history").array(), -}, (table) => [check("int_enum_arrays_state_chk", sql`state IN (0, 5, 9)`)]); - -export type IntEnumArray = InferSelectModel; -export type IntEnumArrayInsert = InferInsertModel; -export type IntEnumArrayUpdate = Partial; - -export { type PublishState, PublishStateEnum } from "./enums.js"; - -export const IntEnumArrayInsertSchema = z.object({ - state: PublishStateEnum.optional(), - history: z.array(PublishStateEnum).optional(), -}); - -export const IntEnumArrayUpdateSchema = z.object({ - state: PublishStateEnum.optional().nullable(), - history: z.array(PublishStateEnum).optional().nullable(), -}); - -/** - * Typed create shape for IntEnumArray: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createIntEnumArray` call site; - * the schema still validates at runtime. - */ -export type IntEnumArrayCreate = z.input; - -/** - * Typed patch shape for IntEnumArray: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateIntEnumArray` call site. - */ -export type IntEnumArrayPatch = z.input; - -/** - * Metadata constants for IntEnumArray. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(IntEnumArray, IntEnumArrayInsertSchema); - * - */ -export const IntEnumArray = { - $entity: "IntEnumArray", - $table: "int_enum_arrays", - $path: "/int_enum_arrays", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - state: { - name: "state", - label: "State", - view: "dropdown", - options: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const, - }, - history: { - name: "history", - label: "History", - view: "dropdown", - options: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const, - }, -} as const; - -export type IntEnumArrayFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: IntEnumArrayFilter[]; - and?: IntEnumArrayFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Label.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Label.ts deleted file mode 100644 index d260f4aa66..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Label.ts +++ /dev/null @@ -1,35 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Label (Label) -// Extend in your own module (e.g. Label.extra.ts) — nothing imports it for you. - -import { z } from "zod"; - -export interface Label { - key?: string | undefined; - weight?: number | undefined; -} - -export const LabelInsertSchema = z.object({ - key: z.string().optional(), - weight: z.number().int().optional(), -}); - -/** - * Metadata constants for the value object Label: each field's name, label, view and the - * validation rules derived from its validator children (e.g. `Label..rules.maxLength.value`). - */ -export const Label = { - $entity: "Label", - key: { - name: "key", - label: "Key", - view: "text", - htmlType: "text", - }, - weight: { - name: "weight", - label: "Weight", - view: "number", - htmlType: "number", - }, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.names.ts deleted file mode 100644 index 000d862737..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.names.ts +++ /dev/null @@ -1,17 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Labeled - -export const LabeledNames = { - type: "object", - subType: "entity", - name: "Labeled", - sources: {}, - fields: { - id: { name: "id", column: "id" }, - label: { name: "label", column: "label_text" }, - }, - identities: { - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.ts deleted file mode 100644 index 4d431113e0..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Labeled.ts +++ /dev/null @@ -1,14 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Labeled (Labeled) -// Extend in your own module (e.g. Labeled.extra.ts) — nothing imports it for you. - -import { z } from "zod"; - -export interface Labeled { - id?: number | undefined; - label?: string | undefined; -} - -export const LabeledInsertSchema = z.object({ - label: z.string().optional(), -}); diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.names.ts deleted file mode 100644 index 4cd394e8f9..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.names.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: LedgerEntry - -export const LedgerEntryNames = { - type: "object", - subType: "entity", - name: "LedgerEntry", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "ledger_entries" }, - }, - fields: { - id: { name: "id", column: "id" }, - memo: { name: "memo", column: "memo" }, - }, - identities: { - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.queries.ts deleted file mode 100644 index 22ca30e8a4..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.queries.ts +++ /dev/null @@ -1,56 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: LedgerEntry (LedgerEntry) -// Extend in your own module (e.g. LedgerEntry.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { - type LedgerEntry, - LedgerEntryInsertSchema, - type LedgerEntryPatch, - LedgerEntryUpdateSchema, - ledgerEntries, -} from "./LedgerEntry.js"; - -type Db = PgDatabase>; - -export async function findLedgerEntryById(db: Db, id: number): Promise { - const [ledgerEntry] = await db.select().from(ledgerEntries).where(eq(ledgerEntries.id, id)).limit(1); - return ledgerEntry ?? null; -} - -export async function listLedgerEntries(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(ledgerEntries).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createLedgerEntry(db: Db, data: z.input): Promise { - const validated = LedgerEntryInsertSchema.parse(data); - const [ledgerEntry] = await db.insert(ledgerEntries).values(validated).returning(); - return ledgerEntry!; -} - -export async function updateLedgerEntry(db: Db, id: number, patch: LedgerEntryPatch): Promise { - const validated = LedgerEntryUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findLedgerEntryById(db, id); - } - const [ledgerEntry] = await db.update(ledgerEntries).set(validated).where(eq(ledgerEntries.id, id)).returning(); - return ledgerEntry ?? null; -} - -export async function deleteLedgerEntryById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(ledgerEntries).where(eq(ledgerEntries.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.ts deleted file mode 100644 index 1aa1b4e46d..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LedgerEntry.ts +++ /dev/null @@ -1,86 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: LedgerEntry (LedgerEntry) -// Extend in your own module (e.g. LedgerEntry.extra.ts) — nothing imports it for you. - -import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { bigint, pgTable, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -export const ledgerEntries = pgTable("ledger_entries", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - memo: varchar("memo", { length: 40 }), -}); - -export type LedgerEntry = InferSelectModel; -export type LedgerEntryInsert = InferInsertModel; -export type LedgerEntryUpdate = Partial; - -export const LedgerEntryInsertSchema = z.object({ - memo: z.string().max(40).optional(), -}); - -export const LedgerEntryUpdateSchema = z.object({ - memo: z.string().max(40).optional().nullable(), -}); - -/** - * Typed create shape for LedgerEntry: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createLedgerEntry` call site; - * the schema still validates at runtime. - */ -export type LedgerEntryCreate = z.input; - -/** - * Typed patch shape for LedgerEntry: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateLedgerEntry` call site. - */ -export type LedgerEntryPatch = z.input; - -/** - * Metadata constants for LedgerEntry. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(LedgerEntry, LedgerEntryInsertSchema); - * - */ -export const LedgerEntry = { - $entity: "LedgerEntry", - $table: "ledger_entries", - $path: "/ledger_entries", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - memo: { - name: "memo", - label: "Memo", - view: "text", - htmlType: "text", - rules: { maxLength: { value: 40, message: "Must be 40 characters or fewer" } }, - }, -} as const; - -export type LedgerEntryFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: LedgerEntryFilter[]; - and?: LedgerEntryFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.names.ts deleted file mode 100644 index 9d7691a78d..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.names.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: LiveIntroPrograms - -export const LiveIntroProgramsNames = { - type: "object", - subType: "report", - name: "LiveIntroPrograms", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_live_intro_programs" }, - }, - fields: { - listValue: { name: "listValue", column: "list_value" }, - notDrafts: { name: "notDrafts", column: "not_drafts" }, - programs: { name: "programs", column: "programs" }, - status: { name: "status", column: "status" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.queries.ts deleted file mode 100644 index 4c729465bc..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: LiveIntroPrograms (LiveIntroPrograms) — report (read-only) -// Extend in your own module (e.g. LiveIntroPrograms.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type LiveIntroPrograms, liveIntroProgramsView } from "./LiveIntroPrograms.js"; - -type Db = PgDatabase>; - -export async function listLiveIntroPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(liveIntroProgramsView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.ts deleted file mode 100644 index 5369c4527d..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/LiveIntroPrograms.ts +++ /dev/null @@ -1,46 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: LiveIntroPrograms (LiveIntroPrograms) - -import { bigint, pgView, text } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const liveIntroProgramsView = pgView("v_live_intro_programs", { - status: text("status", { enum: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const }).notNull(), - programs: bigint("programs", { mode: "number" }).notNull(), - notDrafts: bigint("not_drafts", { mode: "number" }).notNull(), - listValue: bigint("list_value", { mode: "number" }), -}).existing(); - -export const LiveIntroProgramsSchema = z.object({ - status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]), - programs: z.number().int(), - notDrafts: z.number().int(), - listValue: z.number().int().nullable(), -}); - -export type LiveIntroPrograms = z.infer; - -export const LiveIntroPrograms = { - $entity: "LiveIntroPrograms", - $view: "v_live_intro_programs", - $path: "/live_intro_programs", - status: { name: "status", label: "Status", view: "dropdown", dbCol: "status" }, - programs: { name: "programs", label: "Programs", view: "number", dbCol: "programs" }, - notDrafts: { name: "notDrafts", label: "Not Drafts", view: "number", dbCol: "not_drafts" }, - listValue: { name: "listValue", label: "List Value", view: "currency", dbCol: "list_value", currency: "USD", locale: "en-US" }, -} as const; - -export type LiveIntroProgramsFilter = { - limit?: number; - offset?: number; - sort?: `${"status" | "programs" | "notDrafts" | "listValue"}:${"asc" | "desc"}` | "status" | "programs" | "notDrafts" | "listValue"; - status?: "DRAFT" | "PUBLISHED" | "ARCHIVED" | { eq?: "DRAFT" | "PUBLISHED" | "ARCHIVED"; ne?: "DRAFT" | "PUBLISHED" | "ARCHIVED"; in?: ("DRAFT" | "PUBLISHED" | "ARCHIVED")[]; like?: string; isNull?: boolean }; - programs?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - notDrafts?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - listValue?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: LiveIntroProgramsFilter[]; - and?: LiveIntroProgramsFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.names.ts deleted file mode 100644 index 988cd2a37e..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.names.ts +++ /dev/null @@ -1,21 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Measurement - -export const MeasurementNames = { - type: "object", - subType: "entity", - name: "Measurement", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "measurements" }, - }, - fields: { - id: { name: "id", column: "id" }, - massKg: { name: "massKg", column: "mass_kg" }, - preciseKg: { name: "preciseKg", column: "precise_kg" }, - tempC: { name: "tempC", column: "temp_c" }, - }, - identities: { - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.queries.ts deleted file mode 100644 index bc5bf38237..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.queries.ts +++ /dev/null @@ -1,56 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Measurement (Measurement) -// Extend in your own module (e.g. Measurement.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { - type Measurement, - MeasurementInsertSchema, - type MeasurementPatch, - MeasurementUpdateSchema, - measurements, -} from "./Measurement.js"; - -type Db = PgDatabase>; - -export async function findMeasurementById(db: Db, id: number): Promise { - const [measurement] = await db.select().from(measurements).where(eq(measurements.id, id)).limit(1); - return measurement ?? null; -} - -export async function listMeasurements(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(measurements).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createMeasurement(db: Db, data: z.input): Promise { - const validated = MeasurementInsertSchema.parse(data); - const [measurement] = await db.insert(measurements).values(validated).returning(); - return measurement!; -} - -export async function updateMeasurement(db: Db, id: number, patch: MeasurementPatch): Promise { - const validated = MeasurementUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findMeasurementById(db, id); - } - const [measurement] = await db.update(measurements).set(validated).where(eq(measurements.id, id)).returning(); - return measurement ?? null; -} - -export async function deleteMeasurementById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(measurements).where(eq(measurements.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.ts deleted file mode 100644 index 0379236267..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Measurement.ts +++ /dev/null @@ -1,147 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Measurement (Measurement) -// Extend in your own module (e.g. Measurement.extra.ts) — nothing imports it for you. - -import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { bigint, doublePrecision, numeric, pgTable, real } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -export const measurements = pgTable("measurements", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - tempC: real("temp_c").notNull(), - massKg: doublePrecision("mass_kg").notNull(), - preciseKg: numeric("precise_kg", { precision: 9, scale: 4 }).notNull(), -}); - -export type Measurement = InferSelectModel; -export type MeasurementInsert = InferInsertModel; -export type MeasurementUpdate = Partial; - -/** A field.decimal on the wire: a string in the JSON-number grammar (an exponent is allowed) or a JSON - * number, rewritten to its canonical string (plain notation, no trailing fraction zeros, zero as "0"). - * Garbage, or a value the column cannot hold without rounding, is a validation issue. Generated. */ -function decimalWrite(v: string | number, ctx: z.RefinementCtx, precision?: number, scale = 0): string { - if (typeof v === "number" && Number.isFinite(v) && !Number.isSafeInteger(v) && Number(v.toPrecision(15)) !== v) { - ctx.addIssue({ code: "custom", message: "Decimal number cannot be read exactly as a JSON number; send it as a string" }); - return z.NEVER; - } - const text = typeof v === "number" ? (Number.isFinite(v) ? String(v) : "") : v; - const m = /^(-?)(0|[1-9][0-9]*)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/.exec(text); - const e = m === null || m[4] === undefined ? 0 : Number(m[4]); - if (m === null || !Number.isSafeInteger(e) || Math.abs(e) > 1000) { - ctx.addIssue({ code: "custom", message: "Not a decimal number" }); - return z.NEVER; - } - const whole = m[2] ?? ""; - let digits = whole + (m[3] ?? ""); - let point = whole.length + e; - const lead = digits.length - digits.replace(/^0+/, "").length; - digits = digits.slice(lead).replace(/0+$/, ""); - point -= lead; - if (digits.length === 0) { - return "0"; - } - const plain = point <= 0 - ? `0.${"0".repeat(-point)}${digits}` - : point >= digits.length - ? digits + "0".repeat(point - digits.length) - : `${digits.slice(0, point)}.${digits.slice(point)}`; - const fraction = point >= digits.length ? 0 : digits.length - Math.max(point, 0) + Math.max(-point, 0); - const integer = Math.max(point, 0); - if (plain.length > 1000 || (precision !== undefined && (fraction > scale || integer > precision - scale))) { - ctx.addIssue({ code: "custom", message: "Decimal out of range for the column" }); - return z.NEVER; - } - return m[1] === "-" ? `-${plain}` : plain; -} - -export const MeasurementInsertSchema = z.object({ - tempC: z.number(), - massKg: z.number(), - preciseKg: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 9, 4)), -}); - -export const MeasurementUpdateSchema = z.object({ - tempC: z.number().optional(), - massKg: z.number().optional(), - preciseKg: z.union([z.string(), z.number()]).transform((v, ctx) => decimalWrite(v, ctx, 9, 4)).optional(), -}); - -/** - * Typed create shape for Measurement: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createMeasurement` call site; - * the schema still validates at runtime. - */ -export type MeasurementCreate = z.input; - -/** - * Typed patch shape for Measurement: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateMeasurement` call site. - */ -export type MeasurementPatch = z.input; - -/** - * Metadata constants for Measurement. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Measurement, MeasurementInsertSchema); - * - */ -export const Measurement = { - $entity: "Measurement", - $table: "measurements", - $path: "/measurements", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - tempC: { - name: "tempC", - label: "Temp C", - view: "number", - htmlType: "number", - step: "any", - rules: { required: "Temp C is required" }, - }, - massKg: { - name: "massKg", - label: "Mass Kg", - view: "number", - htmlType: "number", - step: "any", - rules: { required: "Mass Kg is required" }, - }, - preciseKg: { - name: "preciseKg", - label: "Precise Kg", - view: "number", - htmlType: "text", - inputMode: "decimal", - rules: { required: "Precise Kg is required" }, - }, -} as const; - -export type MeasurementFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: MeasurementFilter[]; - and?: MeasurementFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.names.ts deleted file mode 100644 index 0243315d28..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.names.ts +++ /dev/null @@ -1,24 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: MeasurementStats - -export const MeasurementStatsNames = { - type: "object", - subType: "report", - name: "MeasurementStats", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_measurement_stats" }, - }, - fields: { - avgMassKg: { name: "avgMassKg", column: "avg_mass_kg" }, - avgPreciseKg: { name: "avgPreciseKg", column: "avg_precise_kg" }, - heavyReadings: { name: "heavyReadings", column: "heavy_readings" }, - maxPreciseKg: { name: "maxPreciseKg", column: "max_precise_kg" }, - maxTempC: { name: "maxTempC", column: "max_temp_c" }, - minTempC: { name: "minTempC", column: "min_temp_c" }, - readings: { name: "readings", column: "readings" }, - totalMassKg: { name: "totalMassKg", column: "total_mass_kg" }, - totalPreciseKg: { name: "totalPreciseKg", column: "total_precise_kg" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.queries.ts deleted file mode 100644 index 40a3c32447..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: MeasurementStats (MeasurementStats) — report (read-only) -// Extend in your own module (e.g. MeasurementStats.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type MeasurementStats, measurementStatsView } from "./MeasurementStats.js"; - -type Db = PgDatabase>; - -export async function listMeasurementStats(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(measurementStatsView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.ts deleted file mode 100644 index 247e2aa778..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStats.ts +++ /dev/null @@ -1,66 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: MeasurementStats (MeasurementStats) - -import { bigint, doublePrecision, numeric, pgView, real } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const measurementStatsView = pgView("v_measurement_stats", { - readings: bigint("readings", { mode: "number" }).notNull(), - totalMassKg: doublePrecision("total_mass_kg"), - avgMassKg: doublePrecision("avg_mass_kg"), - maxTempC: real("max_temp_c"), - minTempC: real("min_temp_c"), - totalPreciseKg: numeric("total_precise_kg", { precision: 19, scale: 4 }), - avgPreciseKg: numeric("avg_precise_kg", { precision: 19, scale: 4 }), - maxPreciseKg: numeric("max_precise_kg", { precision: 9, scale: 4 }), - heavyReadings: bigint("heavy_readings", { mode: "number" }).notNull(), -}).existing(); - -export const MeasurementStatsSchema = z.object({ - readings: z.number().int(), - totalMassKg: z.number().nullable(), - avgMassKg: z.number().nullable(), - maxTempC: z.number().nullable(), - minTempC: z.number().nullable(), - totalPreciseKg: z.string().nullable(), - avgPreciseKg: z.string().nullable(), - maxPreciseKg: z.string().nullable(), - heavyReadings: z.number().int(), -}); - -export type MeasurementStats = z.infer; - -export const MeasurementStats = { - $entity: "MeasurementStats", - $view: "v_measurement_stats", - $path: "/measurement_stats", - readings: { name: "readings", label: "Readings", view: "number", dbCol: "readings" }, - totalMassKg: { name: "totalMassKg", label: "Total Mass Kg", view: "number", dbCol: "total_mass_kg" }, - avgMassKg: { name: "avgMassKg", label: "Avg Mass Kg", view: "number", dbCol: "avg_mass_kg" }, - maxTempC: { name: "maxTempC", label: "Max Temp C", view: "number", dbCol: "max_temp_c" }, - minTempC: { name: "minTempC", label: "Min Temp C", view: "number", dbCol: "min_temp_c" }, - totalPreciseKg: { name: "totalPreciseKg", label: "Total Precise Kg", view: "number", dbCol: "total_precise_kg" }, - avgPreciseKg: { name: "avgPreciseKg", label: "Avg Precise Kg", view: "number", dbCol: "avg_precise_kg" }, - maxPreciseKg: { name: "maxPreciseKg", label: "Max Precise Kg", view: "number", dbCol: "max_precise_kg" }, - heavyReadings: { name: "heavyReadings", label: "Heavy Readings", view: "number", dbCol: "heavy_readings" }, -} as const; - -export type MeasurementStatsFilter = { - limit?: number; - offset?: number; - sort?: `${"readings" | "totalMassKg" | "avgMassKg" | "maxTempC" | "minTempC" | "totalPreciseKg" | "avgPreciseKg" | "maxPreciseKg" | "heavyReadings"}:${"asc" | "desc"}` | "readings" | "totalMassKg" | "avgMassKg" | "maxTempC" | "minTempC" | "totalPreciseKg" | "avgPreciseKg" | "maxPreciseKg" | "heavyReadings"; - readings?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - totalMassKg?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - avgMassKg?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - maxTempC?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - minTempC?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - totalPreciseKg?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - avgPreciseKg?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - maxPreciseKg?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - heavyReadings?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: MeasurementStatsFilter[]; - and?: MeasurementStatsFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.names.ts deleted file mode 100644 index 4ba14cc02c..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.names.ts +++ /dev/null @@ -1,18 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: MeasurementStatsFilled - -export const MeasurementStatsFilledNames = { - type: "object", - subType: "report", - name: "MeasurementStatsFilled", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_measurement_stats_filled" }, - }, - fields: { - avgPreciseKgOrMinusOne: { name: "avgPreciseKgOrMinusOne", column: "avg_precise_kg_or_minus_one" }, - maxPreciseKgOrZero: { name: "maxPreciseKgOrZero", column: "max_precise_kg_or_zero" }, - readings: { name: "readings", column: "readings" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.queries.ts deleted file mode 100644 index afbc518d35..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: MeasurementStatsFilled (MeasurementStatsFilled) — report (read-only) -// Extend in your own module (e.g. MeasurementStatsFilled.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type MeasurementStatsFilled, measurementStatsFilledView } from "./MeasurementStatsFilled.js"; - -type Db = PgDatabase>; - -export async function listMeasurementStatsFilleds(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(measurementStatsFilledView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.ts deleted file mode 100644 index ba7e616ce3..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/MeasurementStatsFilled.ts +++ /dev/null @@ -1,42 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: MeasurementStatsFilled (MeasurementStatsFilled) - -import { bigint, numeric, pgView } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const measurementStatsFilledView = pgView("v_measurement_stats_filled", { - readings: bigint("readings", { mode: "number" }).notNull(), - avgPreciseKgOrMinusOne: numeric("avg_precise_kg_or_minus_one", { precision: 19, scale: 4 }).notNull(), - maxPreciseKgOrZero: numeric("max_precise_kg_or_zero", { precision: 9, scale: 4 }).notNull(), -}).existing(); - -export const MeasurementStatsFilledSchema = z.object({ - readings: z.number().int(), - avgPreciseKgOrMinusOne: z.string(), - maxPreciseKgOrZero: z.string(), -}); - -export type MeasurementStatsFilled = z.infer; - -export const MeasurementStatsFilled = { - $entity: "MeasurementStatsFilled", - $view: "v_measurement_stats_filled", - $path: "/measurement_stats_filleds", - readings: { name: "readings", label: "Readings", view: "number", dbCol: "readings" }, - avgPreciseKgOrMinusOne: { name: "avgPreciseKgOrMinusOne", label: "Avg Precise Kg Or Minus One", view: "number", dbCol: "avg_precise_kg_or_minus_one" }, - maxPreciseKgOrZero: { name: "maxPreciseKgOrZero", label: "Max Precise Kg Or Zero", view: "number", dbCol: "max_precise_kg_or_zero" }, -} as const; - -export type MeasurementStatsFilledFilter = { - limit?: number; - offset?: number; - sort?: `${"readings" | "avgPreciseKgOrMinusOne" | "maxPreciseKgOrZero"}:${"asc" | "desc"}` | "readings" | "avgPreciseKgOrMinusOne" | "maxPreciseKgOrZero"; - readings?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - avgPreciseKgOrMinusOne?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - maxPreciseKgOrZero?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - or?: MeasurementStatsFilledFilter[]; - and?: MeasurementStatsFilledFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.names.ts deleted file mode 100644 index 8d8d7779d0..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.names.ts +++ /dev/null @@ -1,21 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Node - -export const NodeNames = { - type: "object", - subType: "entity", - name: "Node", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "nodes" }, - }, - fields: { - id: { name: "id", column: "id" }, - label: { name: "label", column: "label" }, - parentId: { name: "parentId", column: "parent_id" }, - }, - identities: { - fkParent: { type: "identity", subType: "reference", name: "fkParent" }, - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.queries.ts deleted file mode 100644 index a431a58f6e..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.queries.ts +++ /dev/null @@ -1,61 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Node (Node) -// Extend in your own module (e.g. Node.extra.ts) — nothing imports it for you. - -import { eq, inArray } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { type Node, NodeInsertSchema, type NodePatch, NodeUpdateSchema, nodes } from "./Node.js"; - -type Db = PgDatabase>; - -export async function findNodeById(db: Db, id: number): Promise { - const [node] = await db.select().from(nodes).where(eq(nodes.id, id)).limit(1); - return node ?? null; -} - -export async function listNodes(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(nodes).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createNode(db: Db, data: z.input): Promise { - const validated = NodeInsertSchema.parse(data); - const [node] = await db.insert(nodes).values(validated).returning(); - return node!; -} - -export async function updateNode(db: Db, id: number, patch: NodePatch): Promise { - const validated = NodeUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findNodeById(db, id); - } - const [node] = await db.update(nodes).set(validated).where(eq(nodes.id, id)).returning(); - return node ?? null; -} - -export async function deleteNodeById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(nodes).where(eq(nodes.id, id)).returning(); - return deleted.length > 0; -} - -export async function findNodesByParent(db: Db, parentId: number): Promise { - return db.select().from(nodes).where(eq(nodes.parentId, parentId)); -} - -export async function findNodesByParentIn(db: Db, parentIds: number[]): Promise { - if (parentIds.length === 0) { - return []; - } - return db.select().from(nodes).where(inArray(nodes.parentId, parentIds)); -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.ts deleted file mode 100644 index 1a6317c444..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Node.ts +++ /dev/null @@ -1,95 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Node (Node) -// Extend in your own module (e.g. Node.extra.ts) — nothing imports it for you. - -import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { type AnyPgColumn, bigint, pgTable, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -export const nodes = pgTable("nodes", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - label: varchar("label", { length: 80 }).notNull(), - parentId: bigint("parent_id", { mode: "number" }).references((): AnyPgColumn => nodes.id), -}); - -export type Node = InferSelectModel; -export type NodeInsert = InferInsertModel; -export type NodeUpdate = Partial; - -export const NodeInsertSchema = z.object({ - label: z.string().min(1).max(80), - parentId: z.number().int().optional(), -}); - -export const NodeUpdateSchema = z.object({ - label: z.string().min(1).max(80).optional(), - parentId: z.number().int().optional().nullable(), -}); - -/** - * Typed create shape for Node: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createNode` call site; - * the schema still validates at runtime. - */ -export type NodeCreate = z.input; - -/** - * Typed patch shape for Node: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateNode` call site. - */ -export type NodePatch = z.input; - -/** - * Metadata constants for Node. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Node, NodeInsertSchema); - * - */ -export const Node = { - $entity: "Node", - $table: "nodes", - $path: "/nodes", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - label: { - name: "label", - label: "Label", - view: "text", - htmlType: "text", - rules: { required: "Label is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, - }, - parentId: { - name: "parentId", - label: "Parent Id", - view: "number", - htmlType: "number", - }, -} as const; - -export type NodeFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: NodeFilter[]; - and?: NodeFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.names.ts deleted file mode 100644 index 93d1ee8ba3..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.names.ts +++ /dev/null @@ -1,17 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: NodesByParent - -export const NodesByParentNames = { - type: "object", - subType: "report", - name: "NodesByParent", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_nodes_by_parent" }, - }, - fields: { - nodes: { name: "nodes", column: "nodes" }, - parentLabel: { name: "parentLabel", column: "parent_label" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.queries.ts deleted file mode 100644 index f5596b3fad..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: NodesByParent (NodesByParent) — report (read-only) -// Extend in your own module (e.g. NodesByParent.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type NodesByParent, nodesByParentView } from "./NodesByParent.js"; - -type Db = PgDatabase>; - -export async function listNodesByParents(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(nodesByParentView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.ts deleted file mode 100644 index 2fbf0e9a6e..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/NodesByParent.ts +++ /dev/null @@ -1,38 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: NodesByParent (NodesByParent) - -import { bigint, pgView, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const nodesByParentView = pgView("v_nodes_by_parent", { - parentLabel: varchar("parent_label", { length: 80 }), - nodes: bigint("nodes", { mode: "number" }).notNull(), -}).existing(); - -export const NodesByParentSchema = z.object({ - parentLabel: z.string().nullable(), - nodes: z.number().int(), -}); - -export type NodesByParent = z.infer; - -export const NodesByParent = { - $entity: "NodesByParent", - $view: "v_nodes_by_parent", - $path: "/nodes_by_parents", - parentLabel: { name: "parentLabel", label: "Parent Label", view: "text", dbCol: "parent_label" }, - nodes: { name: "nodes", label: "Nodes", view: "number", dbCol: "nodes" }, -} as const; - -export type NodesByParentFilter = { - limit?: number; - offset?: number; - sort?: `${"parentLabel" | "nodes"}:${"asc" | "desc"}` | "parentLabel" | "nodes"; - parentLabel?: string | { eq?: string; ne?: string; in?: string[]; like?: string; isNull?: boolean }; - nodes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: NodesByParentFilter[]; - and?: NodesByParentFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.names.ts deleted file mode 100644 index 97302c7aa0..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.names.ts +++ /dev/null @@ -1,23 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: PermitAuth - -import { AuthNames } from "./Auth.names.js"; - -export const PermitAuthNames = { - type: "object", - subType: "entity", - name: "PermitAuth", - sources: { - ...AuthNames.sources, - }, - fields: { - ...AuthNames.fields, - approver: { name: "approver", column: "approver" }, - }, - identities: { - ...AuthNames.identities, - }, - indexes: { - ...AuthNames.indexes, - }, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.ts deleted file mode 100644 index 11954c4bdc..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PermitAuth.ts +++ /dev/null @@ -1,113 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: PermitAuth (PermitAuth) -// Extend in your own module (e.g. PermitAuth.extra.ts) — nothing imports it for you. - -import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; -import { z } from "zod"; - -export interface PermitAuth { - id?: number | undefined; - type?: PermitAuthType | null | undefined; - reference: string; - approver?: string | null | undefined; -} - -export type PermitAuthType = "Bridge" | "Coupon" | "Permit" | "Referral"; -export const PermitAuthTypeEnum = z.enum(["Bridge", "Coupon", "Permit", "Referral"]); - -export const PermitAuthSchema = z.object({ - id: z.number().int(), - type: z.literal("Permit"), - reference: z.string().min(1).max(80), - approver: z.string().max(80).nullable(), -}); - -export const PermitAuthInsertSchema = z.object({ - type: z.literal("Permit"), - reference: z.string().min(1).max(80), - approver: z.string().max(80).optional(), -}); - -export const PermitAuthUpdateSchema = z.object({ - reference: z.string().min(1).max(80).optional(), - approver: z.string().max(80).optional().nullable(), -}); - -/** - * Typed create shape for PermitAuth: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createPermitAuth` call site; - * the schema still validates at runtime. - */ -export type PermitAuthCreate = z.input; - -/** - * Typed patch shape for PermitAuth: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updatePermitAuth` call site. - */ -export type PermitAuthPatch = z.input; - -/** - * Metadata constants for PermitAuth. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(PermitAuth, PermitAuthInsertSchema); - * - */ -export const PermitAuth = { - $entity: "PermitAuth", - $table: "auths", - $path: "/auths/permit", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - type: { - name: "type", - label: "Type", - view: "dropdown", - options: ["Bridge", "Coupon", "Permit", "Referral"] as const, - }, - reference: { - name: "reference", - label: "Reference", - view: "text", - htmlType: "text", - rules: { required: "Reference is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, - }, - approver: { - name: "approver", - label: "Approver", - view: "text", - htmlType: "text", - rules: { maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, - }, -} as const; - -export const PermitAuthFilterAllowlist = {} as const satisfies FilterAllowlist; - -export const PermitAuthSortAllowlist = {} as const satisfies SortAllowlist; - -export type PermitAuthFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: PermitAuthFilter[]; - and?: PermitAuthFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.names.ts deleted file mode 100644 index 138ab13434..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.names.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Person - -export const PersonNames = { - type: "object", - subType: "entity", - name: "Person", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "people" }, - }, - fields: { - id: { name: "id", column: "id" }, - name: { name: "name", column: "name" }, - }, - identities: { - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.queries.ts deleted file mode 100644 index c7560e9dc0..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.queries.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Person (Person) -// Extend in your own module (e.g. Person.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { type Person, PersonInsertSchema, type PersonPatch, PersonUpdateSchema, persons } from "./Person.js"; - -type Db = PgDatabase>; - -export async function findPersonById(db: Db, id: number): Promise { - const [person] = await db.select().from(persons).where(eq(persons.id, id)).limit(1); - return person ?? null; -} - -export async function listPersons(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(persons).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createPerson(db: Db, data: z.input): Promise { - const validated = PersonInsertSchema.parse(data); - const [person] = await db.insert(persons).values(validated).returning(); - return person!; -} - -export async function updatePerson(db: Db, id: number, patch: PersonPatch): Promise { - const validated = PersonUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findPersonById(db, id); - } - const [person] = await db.update(persons).set(validated).where(eq(persons.id, id)).returning(); - return person ?? null; -} - -export async function deletePersonById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(persons).where(eq(persons.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.ts deleted file mode 100644 index 8620411a71..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Person.ts +++ /dev/null @@ -1,93 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Person (Person) -// Extend in your own module (e.g. Person.extra.ts) — nothing imports it for you. - -import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; -import { bigint, pgTable, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; -import { follows } from "./Follow.js"; -import { friendships } from "./Friendship.js"; - -export const persons = pgTable("people", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - name: varchar("name", { length: 80 }).notNull(), -}); - -export const personsRelations = relations(persons, ({ many }) => ({ - following: many(follows), - friends: many(friendships), -})); - -export type Person = InferSelectModel; -export type PersonInsert = InferInsertModel; -export type PersonUpdate = Partial; - -export const PersonInsertSchema = z.object({ - name: z.string().min(1).max(80), -}); - -export const PersonUpdateSchema = z.object({ - name: z.string().min(1).max(80).optional(), -}); - -/** - * Typed create shape for Person: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createPerson` call site; - * the schema still validates at runtime. - */ -export type PersonCreate = z.input; - -/** - * Typed patch shape for Person: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updatePerson` call site. - */ -export type PersonPatch = z.input; - -/** - * Metadata constants for Person. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Person, PersonInsertSchema); - * - */ -export const Person = { - $entity: "Person", - $table: "people", - $path: "/persons", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - name: { - name: "name", - label: "Name", - view: "text", - htmlType: "text", - rules: { required: "Name is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, - }, -} as const; - -export type PersonFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: PersonFilter[]; - and?: PersonFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.names.ts deleted file mode 100644 index b84c96f3eb..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.names.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Post - -export const PostNames = { - type: "object", - subType: "entity", - name: "Post", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "posts" }, - }, - fields: { - id: { name: "id", column: "id" }, - title: { name: "title", column: "title" }, - }, - identities: { - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.queries.ts deleted file mode 100644 index 768993bbca..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.queries.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Post (Post) -// Extend in your own module (e.g. Post.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { type Post, PostInsertSchema, type PostPatch, PostUpdateSchema, posts } from "./Post.js"; - -type Db = PgDatabase>; - -export async function findPostById(db: Db, id: number): Promise { - const [post] = await db.select().from(posts).where(eq(posts.id, id)).limit(1); - return post ?? null; -} - -export async function listPosts(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(posts).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createPost(db: Db, data: z.input): Promise { - const validated = PostInsertSchema.parse(data); - const [post] = await db.insert(posts).values(validated).returning(); - return post!; -} - -export async function updatePost(db: Db, id: number, patch: PostPatch): Promise { - const validated = PostUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findPostById(db, id); - } - const [post] = await db.update(posts).set(validated).where(eq(posts.id, id)).returning(); - return post ?? null; -} - -export async function deletePostById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(posts).where(eq(posts.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.ts deleted file mode 100644 index 3248b4557e..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Post.ts +++ /dev/null @@ -1,93 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Post (Post) -// Extend in your own module (e.g. Post.extra.ts) — nothing imports it for you. - -import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; -import { bigint, pgTable, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; -import { postReferrals } from "./PostReferral.js"; -import { postTags } from "./PostTag.js"; - -export const posts = pgTable("posts", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - title: varchar("title", { length: 200 }).notNull(), -}); - -export const postsRelations = relations(posts, ({ many }) => ({ - tags: many(postTags), - referrals: many(postReferrals), -})); - -export type Post = InferSelectModel; -export type PostInsert = InferInsertModel; -export type PostUpdate = Partial; - -export const PostInsertSchema = z.object({ - title: z.string().min(1).max(200), -}); - -export const PostUpdateSchema = z.object({ - title: z.string().min(1).max(200).optional(), -}); - -/** - * Typed create shape for Post: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createPost` call site; - * the schema still validates at runtime. - */ -export type PostCreate = z.input; - -/** - * Typed patch shape for Post: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updatePost` call site. - */ -export type PostPatch = z.input; - -/** - * Metadata constants for Post. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Post, PostInsertSchema); - * - */ -export const Post = { - $entity: "Post", - $table: "posts", - $path: "/posts", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - title: { - name: "title", - label: "Title", - view: "text", - htmlType: "text", - rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, - }, -} as const; - -export type PostFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: PostFilter[]; - and?: PostFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.names.ts deleted file mode 100644 index cb4d68b72b..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.names.ts +++ /dev/null @@ -1,21 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: PostReferral - -export const PostReferralNames = { - type: "object", - subType: "entity", - name: "PostReferral", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "post_referrals" }, - }, - fields: { - postId: { name: "postId", column: "post_id" }, - referralId: { name: "referralId", column: "referral_id" }, - }, - identities: { - fkPost: { type: "identity", subType: "reference", name: "fkPost" }, - fkReferral: { type: "identity", subType: "reference", name: "fkReferral" }, - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.queries.ts deleted file mode 100644 index e29690bf2b..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.queries.ts +++ /dev/null @@ -1,78 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: PostReferral (PostReferral) -// Extend in your own module (e.g. PostReferral.extra.ts) — nothing imports it for you. - -import { eq, inArray } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { - type PostReferral, - PostReferralInsertSchema, - type PostReferralPatch, - PostReferralUpdateSchema, - postReferrals, -} from "./PostReferral.js"; - -type Db = PgDatabase>; - -export async function findPostReferralById(db: Db, postId: number): Promise { - const [postReferral] = await db.select().from(postReferrals).where(eq(postReferrals.postId, postId)).limit(1); - return postReferral ?? null; -} - -export async function listPostReferrals(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(postReferrals).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createPostReferral(db: Db, data: z.input): Promise { - const validated = PostReferralInsertSchema.parse(data); - const [postReferral] = await db.insert(postReferrals).values(validated).returning(); - return postReferral!; -} - -export async function updatePostReferral(db: Db, postId: number, patch: PostReferralPatch): Promise { - const validated = PostReferralUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findPostReferralById(db, postId); - } - const [postReferral] = await db.update(postReferrals).set(validated).where(eq(postReferrals.postId, postId)).returning(); - return postReferral ?? null; -} - -export async function deletePostReferralById(db: Db, postId: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(postReferrals).where(eq(postReferrals.postId, postId)).returning(); - return deleted.length > 0; -} - -export async function findPostReferralsByPost(db: Db, postId: number): Promise { - return db.select().from(postReferrals).where(eq(postReferrals.postId, postId)); -} - -export async function findPostReferralsByPostIn(db: Db, postIds: number[]): Promise { - if (postIds.length === 0) { - return []; - } - return db.select().from(postReferrals).where(inArray(postReferrals.postId, postIds)); -} - -export async function findPostReferralsByReferral(db: Db, referralId: number): Promise { - return db.select().from(postReferrals).where(eq(postReferrals.referralId, referralId)); -} - -export async function findPostReferralsByReferralIn(db: Db, referralIds: number[]): Promise { - if (referralIds.length === 0) { - return []; - } - return db.select().from(postReferrals).where(inArray(postReferrals.referralId, referralIds)); -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.ts deleted file mode 100644 index 5fc57699fa..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostReferral.ts +++ /dev/null @@ -1,93 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: PostReferral (PostReferral) -// Extend in your own module (e.g. PostReferral.extra.ts) — nothing imports it for you. - -import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; -import { bigint, pgTable, primaryKey } from "drizzle-orm/pg-core"; -import { z } from "zod"; -import { auths } from "./Auth.js"; -import { posts } from "./Post.js"; - -export const postReferrals = pgTable("post_referrals", { - postId: bigint("post_id", { mode: "number" }).notNull(), - referralId: bigint("referral_id", { mode: "number" }).notNull(), -}, (table) => [primaryKey({ columns: [table.postId, table.referralId] })]); - -export const postReferralsRelations = relations(postReferrals, ({ one }) => ({ - fkPost: one(posts, { fields: [postReferrals.postId], references: [posts.id] }), - fkReferral: one(auths, { fields: [postReferrals.referralId], references: [auths.id] }), -})); - -export type PostReferral = InferSelectModel; -export type PostReferralInsert = InferInsertModel; -export type PostReferralUpdate = Partial; - -export const PostReferralInsertSchema = z.object({ - postId: z.number().int(), - referralId: z.number().int(), -}); - -export const PostReferralUpdateSchema = z.object({}); - -/** - * Typed create shape for PostReferral: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createPostReferral` call site; - * the schema still validates at runtime. - */ -export type PostReferralCreate = z.input; - -/** - * Typed patch shape for PostReferral: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updatePostReferral` call site. - */ -export type PostReferralPatch = z.input; - -/** - * Metadata constants for PostReferral. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(PostReferral, PostReferralInsertSchema); - * - */ -export const PostReferral = { - $entity: "PostReferral", - $table: "post_referrals", - $path: "/post_referrals", - postId: { - name: "postId", - label: "Post Id", - view: "number", - htmlType: "number", - rules: { required: "Post Id is required" }, - }, - referralId: { - name: "referralId", - label: "Referral Id", - view: "number", - htmlType: "number", - rules: { required: "Referral Id is required" }, - }, -} as const; - -export type PostReferralFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: PostReferralFilter[]; - and?: PostReferralFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.names.ts deleted file mode 100644 index fc30da83a2..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.names.ts +++ /dev/null @@ -1,21 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: PostTag - -export const PostTagNames = { - type: "object", - subType: "entity", - name: "PostTag", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "post_tags" }, - }, - fields: { - postId: { name: "postId", column: "post_id" }, - tagId: { name: "tagId", column: "tag_id" }, - }, - identities: { - fkPost: { type: "identity", subType: "reference", name: "fkPost" }, - fkTag: { type: "identity", subType: "reference", name: "fkTag" }, - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.queries.ts deleted file mode 100644 index 21d7bd1ece..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.queries.ts +++ /dev/null @@ -1,72 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: PostTag (PostTag) -// Extend in your own module (e.g. PostTag.extra.ts) — nothing imports it for you. - -import { eq, inArray } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { type PostTag, PostTagInsertSchema, type PostTagPatch, PostTagUpdateSchema, postTags } from "./PostTag.js"; - -type Db = PgDatabase>; - -export async function findPostTagById(db: Db, postId: number): Promise { - const [postTag] = await db.select().from(postTags).where(eq(postTags.postId, postId)).limit(1); - return postTag ?? null; -} - -export async function listPostTags(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(postTags).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createPostTag(db: Db, data: z.input): Promise { - const validated = PostTagInsertSchema.parse(data); - const [postTag] = await db.insert(postTags).values(validated).returning(); - return postTag!; -} - -export async function updatePostTag(db: Db, postId: number, patch: PostTagPatch): Promise { - const validated = PostTagUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findPostTagById(db, postId); - } - const [postTag] = await db.update(postTags).set(validated).where(eq(postTags.postId, postId)).returning(); - return postTag ?? null; -} - -export async function deletePostTagById(db: Db, postId: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(postTags).where(eq(postTags.postId, postId)).returning(); - return deleted.length > 0; -} - -export async function findPostTagsByPost(db: Db, postId: number): Promise { - return db.select().from(postTags).where(eq(postTags.postId, postId)); -} - -export async function findPostTagsByPostIn(db: Db, postIds: number[]): Promise { - if (postIds.length === 0) { - return []; - } - return db.select().from(postTags).where(inArray(postTags.postId, postIds)); -} - -export async function findPostTagsByTag(db: Db, tagId: number): Promise { - return db.select().from(postTags).where(eq(postTags.tagId, tagId)); -} - -export async function findPostTagsByTagIn(db: Db, tagIds: number[]): Promise { - if (tagIds.length === 0) { - return []; - } - return db.select().from(postTags).where(inArray(postTags.tagId, tagIds)); -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.ts deleted file mode 100644 index 0838e0bff3..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/PostTag.ts +++ /dev/null @@ -1,93 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: PostTag (PostTag) -// Extend in your own module (e.g. PostTag.extra.ts) — nothing imports it for you. - -import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; -import { bigint, pgTable, primaryKey } from "drizzle-orm/pg-core"; -import { z } from "zod"; -import { posts } from "./Post.js"; -import { tags } from "./Tag.js"; - -export const postTags = pgTable("post_tags", { - postId: bigint("post_id", { mode: "number" }).notNull(), - tagId: bigint("tag_id", { mode: "number" }).notNull(), -}, (table) => [primaryKey({ columns: [table.postId, table.tagId] })]); - -export const postTagsRelations = relations(postTags, ({ one }) => ({ - fkPost: one(posts, { fields: [postTags.postId], references: [posts.id] }), - fkTag: one(tags, { fields: [postTags.tagId], references: [tags.id] }), -})); - -export type PostTag = InferSelectModel; -export type PostTagInsert = InferInsertModel; -export type PostTagUpdate = Partial; - -export const PostTagInsertSchema = z.object({ - postId: z.number().int(), - tagId: z.number().int(), -}); - -export const PostTagUpdateSchema = z.object({}); - -/** - * Typed create shape for PostTag: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createPostTag` call site; - * the schema still validates at runtime. - */ -export type PostTagCreate = z.input; - -/** - * Typed patch shape for PostTag: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updatePostTag` call site. - */ -export type PostTagPatch = z.input; - -/** - * Metadata constants for PostTag. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(PostTag, PostTagInsertSchema); - * - */ -export const PostTag = { - $entity: "PostTag", - $table: "post_tags", - $path: "/post_tags", - postId: { - name: "postId", - label: "Post Id", - view: "number", - htmlType: "number", - rules: { required: "Post Id is required" }, - }, - tagId: { - name: "tagId", - label: "Tag Id", - view: "number", - htmlType: "number", - rules: { required: "Tag Id is required" }, - }, -} as const; - -export type PostTagFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: PostTagFilter[]; - and?: PostTagFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.names.ts deleted file mode 100644 index 61dec41559..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.names.ts +++ /dev/null @@ -1,25 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Program - -export const ProgramNames = { - type: "object", - subType: "entity", - name: "Program", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "programs" }, - }, - fields: { - createdAt: { name: "createdAt", column: "created_ts" }, - id: { name: "id", column: "id" }, - priceCents: { name: "priceCents", column: "price_cents" }, - status: { name: "status", column: "status" }, - title: { name: "title", column: "title" }, - }, - identities: { - byTitle: { type: "identity", subType: "secondary", name: "byTitle", index: "byTitle" }, - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: { - idx_programs_title_status: { type: "index", subType: "lookup", name: "idx_programs_title_status", index: "idx_programs_title_status" }, - }, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.queries.ts deleted file mode 100644 index b32fcbda13..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.queries.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Program (Program) -// Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { type Program, ProgramInsertSchema, type ProgramPatch, ProgramUpdateSchema, programs } from "./Program.js"; - -type Db = PgDatabase>; - -export async function findProgramById(db: Db, id: number): Promise { - const [program] = await db.select().from(programs).where(eq(programs.id, id)).limit(1); - return program ?? null; -} - -export async function listPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(programs).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createProgram(db: Db, data: z.input): Promise { - const validated = ProgramInsertSchema.parse(data); - const [program] = await db.insert(programs).values(validated).returning(); - return program!; -} - -export async function updateProgram(db: Db, id: number, patch: ProgramPatch): Promise { - const validated = ProgramUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findProgramById(db, id); - } - const [program] = await db.update(programs).set(validated).where(eq(programs.id, id)).returning(); - return program ?? null; -} - -export async function deleteProgramById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(programs).where(eq(programs.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.ts deleted file mode 100644 index f616babddb..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Program.ts +++ /dev/null @@ -1,124 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Program (Program) -// Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you. - -import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; -import { bigint, check, index, pgTable, text, timestamp, uniqueIndex, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -export const programs = pgTable("programs", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - title: varchar("title", { length: 200 }).notNull(), - priceCents: bigint("price_cents", { mode: "number" }).notNull(), - status: text("status", { enum: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const }).notNull(), - createdAt: timestamp("created_ts", { mode: "string", withTimezone: false }).notNull(), -}, (table) => [ - uniqueIndex("byTitle").on(table.title), - index("idx_programs_title_status").on(table.title, table.status), - check("programs_status_chk", sql`status IN ('DRAFT', 'PUBLISHED', 'ARCHIVED')`), -]); - -export type Program = InferSelectModel; -export type ProgramInsert = InferInsertModel; -export type ProgramUpdate = Partial; - -export type ProgramStatus = "DRAFT" | "PUBLISHED" | "ARCHIVED"; -export const ProgramStatusEnum = z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]); - -export const ProgramInsertSchema = z.object({ - title: z.string().min(1).max(200), - priceCents: z.number().int(), - status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]), - createdAt: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])"), -}); - -export const ProgramUpdateSchema = z.object({ - title: z.string().min(1).max(200).optional(), - priceCents: z.number().int().optional(), - status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]).optional(), - createdAt: z.string().regex(/^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])").optional(), -}); - -/** - * Typed create shape for Program: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createProgram` call site; - * the schema still validates at runtime. - */ -export type ProgramCreate = z.input; - -/** - * Typed patch shape for Program: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateProgram` call site. - */ -export type ProgramPatch = z.input; - -/** - * Metadata constants for Program. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Program, ProgramInsertSchema); - * - */ -export const Program = { - $entity: "Program", - $table: "programs", - $path: "/programs", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - title: { - name: "title", - label: "Title", - view: "text", - htmlType: "text", - rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, - }, - priceCents: { - name: "priceCents", - label: "Price Cents", - view: "currency", - rules: { required: "Price Cents is required" }, - currency: "USD", - locale: "en-US", - }, - status: { - name: "status", - label: "Status", - view: "dropdown", - rules: { required: "Status is required" }, - options: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const, - }, - createdAt: { - name: "createdAt", - label: "Created At", - view: "date", - htmlType: "datetime-local", - rules: { required: "Created At is required" }, - }, -} as const; - -export type ProgramFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: ProgramFilter[]; - and?: ProgramFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramBrief.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramBrief.ts deleted file mode 100644 index 533fdcbfa5..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramBrief.ts +++ /dev/null @@ -1,45 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramBrief (ProgramBrief) -// Extend in your own module (e.g. ProgramBrief.extra.ts) — nothing imports it for you. - -import { z } from "zod"; -import { type WeekLabel, WeekLabelInsertSchema } from "./WeekLabel.js"; - -export interface ProgramBrief { - title: string; - weekCount?: number | undefined; - weekLabels?: WeekLabel[] | undefined; -} - -export const ProgramBriefInsertSchema = z.object({ - title: z.string().min(1).max(200), - weekCount: z.number().int().optional(), - weekLabels: z.array(WeekLabelInsertSchema).optional(), -}); - -/** - * Metadata constants for the value object ProgramBrief: each field's name, label, view and the - * validation rules derived from its validator children (e.g. `ProgramBrief..rules.maxLength.value`). - */ -export const ProgramBrief = { - $entity: "ProgramBrief", - title: { - name: "title", - label: "Title", - view: "text", - htmlType: "text", - rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, - }, - weekCount: { - name: "weekCount", - label: "Week Count", - view: "number", - htmlType: "number", - }, - weekLabels: { - name: "weekLabels", - label: "Week Labels", - view: "text", - htmlType: "text", - }, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.names.ts deleted file mode 100644 index b2a87d8146..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.names.ts +++ /dev/null @@ -1,20 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramFlagRoster - -export const ProgramFlagRosterNames = { - type: "object", - subType: "report", - name: "ProgramFlagRoster", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_program_flag_roster" }, - }, - fields: { - allDeloadOrTrue: { name: "allDeloadOrTrue", column: "all_deload_or_true" }, - anyDeload: { name: "anyDeload", column: "any_deload" }, - anyDeloadOrFalse: { name: "anyDeloadOrFalse", column: "any_deload_or_false" }, - programKey: { name: "programKey", column: "program_key" }, - weeks: { name: "weeks", column: "weeks" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.queries.ts deleted file mode 100644 index 7048403892..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramFlagRoster (ProgramFlagRoster) — report (read-only) -// Extend in your own module (e.g. ProgramFlagRoster.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type ProgramFlagRoster, programFlagRosterView } from "./ProgramFlagRoster.js"; - -type Db = PgDatabase>; - -export async function listProgramFlagRosters(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(programFlagRosterView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.ts deleted file mode 100644 index 9459af4d1b..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlagRoster.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramFlagRoster (ProgramFlagRoster) - -import { bigint, boolean, pgView } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const programFlagRosterView = pgView("v_program_flag_roster", { - programKey: bigint("program_key", { mode: "number" }).notNull(), - weeks: bigint("weeks", { mode: "number" }).notNull(), - anyDeload: boolean("any_deload"), - anyDeloadOrFalse: boolean("any_deload_or_false").notNull(), - allDeloadOrTrue: boolean("all_deload_or_true").notNull(), -}).existing(); - -export const ProgramFlagRosterSchema = z.object({ - programKey: z.number().int(), - weeks: z.number().int(), - anyDeload: z.boolean().nullable(), - anyDeloadOrFalse: z.boolean(), - allDeloadOrTrue: z.boolean(), -}); - -export type ProgramFlagRoster = z.infer; - -export const ProgramFlagRoster = { - $entity: "ProgramFlagRoster", - $view: "v_program_flag_roster", - $path: "/program_flag_rosters", - programKey: { name: "programKey", label: "Program Key", view: "number", dbCol: "program_key" }, - weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, - anyDeload: { name: "anyDeload", label: "Any Deload", view: "checkbox", dbCol: "any_deload" }, - anyDeloadOrFalse: { name: "anyDeloadOrFalse", label: "Any Deload Or False", view: "checkbox", dbCol: "any_deload_or_false" }, - allDeloadOrTrue: { name: "allDeloadOrTrue", label: "All Deload Or True", view: "checkbox", dbCol: "all_deload_or_true" }, -} as const; - -export type ProgramFlagRosterFilter = { - limit?: number; - offset?: number; - sort?: `${"programKey" | "weeks" | "anyDeload" | "anyDeloadOrFalse" | "allDeloadOrTrue"}:${"asc" | "desc"}` | "programKey" | "weeks" | "anyDeload" | "anyDeloadOrFalse" | "allDeloadOrTrue"; - programKey?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - anyDeload?: boolean | { eq?: boolean; isNull?: boolean }; - anyDeloadOrFalse?: boolean | { eq?: boolean; isNull?: boolean }; - allDeloadOrTrue?: boolean | { eq?: boolean; isNull?: boolean }; - or?: ProgramFlagRosterFilter[]; - and?: ProgramFlagRosterFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.names.ts deleted file mode 100644 index 926963d744..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.names.ts +++ /dev/null @@ -1,20 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramFlags - -export const ProgramFlagsNames = { - type: "object", - subType: "report", - name: "ProgramFlags", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_program_flags" }, - }, - fields: { - allDeload: { name: "allDeload", column: "all_deload" }, - anyDeload: { name: "anyDeload", column: "any_deload" }, - anyLongDeload: { name: "anyLongDeload", column: "any_long_deload" }, - program: { name: "program", column: "program" }, - weeks: { name: "weeks", column: "weeks" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.queries.ts deleted file mode 100644 index 1ad321b9e9..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramFlags (ProgramFlags) — report (read-only) -// Extend in your own module (e.g. ProgramFlags.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type ProgramFlags, programFlagsView } from "./ProgramFlags.js"; - -type Db = PgDatabase>; - -export async function listProgramFlags(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(programFlagsView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.ts deleted file mode 100644 index d2689d2306..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramFlags.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramFlags (ProgramFlags) - -import { bigint, boolean, pgView } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const programFlagsView = pgView("v_program_flags", { - program: bigint("program", { mode: "number" }).notNull(), - weeks: bigint("weeks", { mode: "number" }).notNull(), - anyDeload: boolean("any_deload"), - allDeload: boolean("all_deload"), - anyLongDeload: boolean("any_long_deload"), -}).existing(); - -export const ProgramFlagsSchema = z.object({ - program: z.number().int(), - weeks: z.number().int(), - anyDeload: z.boolean().nullable(), - allDeload: z.boolean().nullable(), - anyLongDeload: z.boolean().nullable(), -}); - -export type ProgramFlags = z.infer; - -export const ProgramFlags = { - $entity: "ProgramFlags", - $view: "v_program_flags", - $path: "/program_flags", - program: { name: "program", label: "Program", view: "number", dbCol: "program" }, - weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, - anyDeload: { name: "anyDeload", label: "Any Deload", view: "checkbox", dbCol: "any_deload" }, - allDeload: { name: "allDeload", label: "All Deload", view: "checkbox", dbCol: "all_deload" }, - anyLongDeload: { name: "anyLongDeload", label: "Any Long Deload", view: "checkbox", dbCol: "any_long_deload" }, -} as const; - -export type ProgramFlagsFilter = { - limit?: number; - offset?: number; - sort?: `${"program" | "weeks" | "anyDeload" | "allDeload" | "anyLongDeload"}:${"asc" | "desc"}` | "program" | "weeks" | "anyDeload" | "allDeload" | "anyLongDeload"; - program?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - anyDeload?: boolean | { eq?: boolean; isNull?: boolean }; - allDeload?: boolean | { eq?: boolean; isNull?: boolean }; - anyLongDeload?: boolean | { eq?: boolean; isNull?: boolean }; - or?: ProgramFlagsFilter[]; - and?: ProgramFlagsFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.names.ts deleted file mode 100644 index fd33a3e5c5..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.names.ts +++ /dev/null @@ -1,18 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramLongWeeks - -export const ProgramLongWeeksNames = { - type: "object", - subType: "report", - name: "ProgramLongWeeks", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_program_long_weeks" }, - }, - fields: { - programKey: { name: "programKey", column: "program_key" }, - totalMinutesOrZero: { name: "totalMinutesOrZero", column: "total_minutes_or_zero" }, - weeks: { name: "weeks", column: "weeks" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.queries.ts deleted file mode 100644 index f5ef2a3ec2..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramLongWeeks (ProgramLongWeeks) — report (read-only) -// Extend in your own module (e.g. ProgramLongWeeks.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type ProgramLongWeeks, programLongWeeksView } from "./ProgramLongWeeks.js"; - -type Db = PgDatabase>; - -export async function listProgramLongWeeks(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(programLongWeeksView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.ts deleted file mode 100644 index 03e3caf294..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramLongWeeks.ts +++ /dev/null @@ -1,42 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramLongWeeks (ProgramLongWeeks) - -import { bigint, pgView } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const programLongWeeksView = pgView("v_program_long_weeks", { - programKey: bigint("program_key", { mode: "number" }).notNull(), - weeks: bigint("weeks", { mode: "number" }).notNull(), - totalMinutesOrZero: bigint("total_minutes_or_zero", { mode: "number" }).notNull(), -}).existing(); - -export const ProgramLongWeeksSchema = z.object({ - programKey: z.number().int(), - weeks: z.number().int(), - totalMinutesOrZero: z.number().int(), -}); - -export type ProgramLongWeeks = z.infer; - -export const ProgramLongWeeks = { - $entity: "ProgramLongWeeks", - $view: "v_program_long_weeks", - $path: "/program_long_weeks", - programKey: { name: "programKey", label: "Program Key", view: "number", dbCol: "program_key" }, - weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, - totalMinutesOrZero: { name: "totalMinutesOrZero", label: "Total Minutes Or Zero", view: "number", dbCol: "total_minutes_or_zero" }, -} as const; - -export type ProgramLongWeeksFilter = { - limit?: number; - offset?: number; - sort?: `${"programKey" | "weeks" | "totalMinutesOrZero"}:${"asc" | "desc"}` | "programKey" | "weeks" | "totalMinutesOrZero"; - programKey?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - totalMinutesOrZero?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: ProgramLongWeeksFilter[]; - and?: ProgramLongWeeksFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.names.ts deleted file mode 100644 index 53689e016d..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.names.ts +++ /dev/null @@ -1,26 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramMinutes - -export const ProgramMinutesNames = { - type: "object", - subType: "report", - name: "ProgramMinutes", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_program_minutes" }, - }, - fields: { - avgMinutes: { name: "avgMinutes", column: "avg_minutes" }, - labels: { name: "labels", column: "labels" }, - longShare: { name: "longShare", column: "long_share" }, - longWeeks: { name: "longWeeks", column: "long_weeks" }, - maxMinutes: { name: "maxMinutes", column: "max_minutes" }, - minMinutes: { name: "minMinutes", column: "min_minutes" }, - program: { name: "program", column: "program" }, - programTitle: { name: "programTitle", column: "program_title" }, - slots: { name: "slots", column: "slots" }, - totalMinutes: { name: "totalMinutes", column: "total_minutes" }, - weeks: { name: "weeks", column: "weeks" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.queries.ts deleted file mode 100644 index e275488ade..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramMinutes (ProgramMinutes) — report (read-only) -// Extend in your own module (e.g. ProgramMinutes.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type ProgramMinutes, programMinutesView } from "./ProgramMinutes.js"; - -type Db = PgDatabase>; - -export async function listProgramMinutes(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(programMinutesView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.ts deleted file mode 100644 index 0190230434..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramMinutes.ts +++ /dev/null @@ -1,74 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramMinutes (ProgramMinutes) - -import { bigint, integer, numeric, pgView, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const programMinutesView = pgView("v_program_minutes", { - program: bigint("program", { mode: "number" }).notNull(), - programTitle: varchar("program_title", { length: 200 }).notNull(), - weeks: bigint("weeks", { mode: "number" }).notNull(), - longWeeks: bigint("long_weeks", { mode: "number" }).notNull(), - labels: bigint("labels", { mode: "number" }).notNull(), - slots: bigint("slots", { mode: "number" }).notNull(), - totalMinutes: bigint("total_minutes", { mode: "number" }), - avgMinutes: numeric("avg_minutes", { precision: 19, scale: 4 }), - minMinutes: integer("min_minutes"), - maxMinutes: integer("max_minutes"), - longShare: numeric("long_share", { precision: 19, scale: 4 }), -}).existing(); - -export const ProgramMinutesSchema = z.object({ - program: z.number().int(), - programTitle: z.string(), - weeks: z.number().int(), - longWeeks: z.number().int(), - labels: z.number().int(), - slots: z.number().int(), - totalMinutes: z.number().int().nullable(), - avgMinutes: z.string().nullable(), - minMinutes: z.number().int().nullable(), - maxMinutes: z.number().int().nullable(), - longShare: z.string().nullable(), -}); - -export type ProgramMinutes = z.infer; - -export const ProgramMinutes = { - $entity: "ProgramMinutes", - $view: "v_program_minutes", - $path: "/program_minutes", - program: { name: "program", label: "Program", view: "number", dbCol: "program" }, - programTitle: { name: "programTitle", label: "Program Title", view: "text", dbCol: "program_title" }, - weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, - longWeeks: { name: "longWeeks", label: "Long Weeks", view: "number", dbCol: "long_weeks" }, - labels: { name: "labels", label: "Labels", view: "number", dbCol: "labels" }, - slots: { name: "slots", label: "Slots", view: "number", dbCol: "slots" }, - totalMinutes: { name: "totalMinutes", label: "Total Minutes", view: "number", dbCol: "total_minutes" }, - avgMinutes: { name: "avgMinutes", label: "Avg Minutes", view: "number", dbCol: "avg_minutes" }, - minMinutes: { name: "minMinutes", label: "Min Minutes", view: "number", dbCol: "min_minutes" }, - maxMinutes: { name: "maxMinutes", label: "Max Minutes", view: "number", dbCol: "max_minutes" }, - longShare: { name: "longShare", label: "Long Share", view: "number", dbCol: "long_share" }, -} as const; - -export type ProgramMinutesFilter = { - limit?: number; - offset?: number; - sort?: `${"program" | "programTitle" | "weeks" | "longWeeks" | "labels" | "slots" | "totalMinutes" | "avgMinutes" | "minMinutes" | "maxMinutes" | "longShare"}:${"asc" | "desc"}` | "program" | "programTitle" | "weeks" | "longWeeks" | "labels" | "slots" | "totalMinutes" | "avgMinutes" | "minMinutes" | "maxMinutes" | "longShare"; - program?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - programTitle?: string | { eq?: string; ne?: string; in?: string[]; like?: string; isNull?: boolean }; - weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - longWeeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - labels?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - slots?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - totalMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - avgMinutes?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - minMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - maxMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - longShare?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - or?: ProgramMinutesFilter[]; - and?: ProgramMinutesFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.names.ts deleted file mode 100644 index f615f4c15f..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.names.ts +++ /dev/null @@ -1,22 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramRoster - -export const ProgramRosterNames = { - type: "object", - subType: "report", - name: "ProgramRoster", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_program_roster" }, - }, - fields: { - longShare: { name: "longShare", column: "long_share" }, - longShareOrZero: { name: "longShareOrZero", column: "long_share_or_zero" }, - programKey: { name: "programKey", column: "program_key" }, - programTitle: { name: "programTitle", column: "program_title" }, - totalMinutes: { name: "totalMinutes", column: "total_minutes" }, - totalMinutesOrZero: { name: "totalMinutesOrZero", column: "total_minutes_or_zero" }, - weeks: { name: "weeks", column: "weeks" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.queries.ts deleted file mode 100644 index beba376f0b..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramRoster (ProgramRoster) — report (read-only) -// Extend in your own module (e.g. ProgramRoster.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type ProgramRoster, programRosterView } from "./ProgramRoster.js"; - -type Db = PgDatabase>; - -export async function listProgramRosters(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(programRosterView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.ts deleted file mode 100644 index 2fa6f4dbe6..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramRoster.ts +++ /dev/null @@ -1,58 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramRoster (ProgramRoster) - -import { bigint, numeric, pgView, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const programRosterView = pgView("v_program_roster", { - programKey: bigint("program_key", { mode: "number" }).notNull(), - programTitle: varchar("program_title", { length: 200 }).notNull(), - weeks: bigint("weeks", { mode: "number" }).notNull(), - totalMinutes: bigint("total_minutes", { mode: "number" }), - totalMinutesOrZero: bigint("total_minutes_or_zero", { mode: "number" }).notNull(), - longShare: numeric("long_share", { precision: 19, scale: 4 }), - longShareOrZero: numeric("long_share_or_zero", { precision: 19, scale: 4 }).notNull(), -}).existing(); - -export const ProgramRosterSchema = z.object({ - programKey: z.number().int(), - programTitle: z.string(), - weeks: z.number().int(), - totalMinutes: z.number().int().nullable(), - totalMinutesOrZero: z.number().int(), - longShare: z.string().nullable(), - longShareOrZero: z.string(), -}); - -export type ProgramRoster = z.infer; - -export const ProgramRoster = { - $entity: "ProgramRoster", - $view: "v_program_roster", - $path: "/program_rosters", - programKey: { name: "programKey", label: "Program Key", view: "number", dbCol: "program_key" }, - programTitle: { name: "programTitle", label: "Program Title", view: "text", dbCol: "program_title" }, - weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, - totalMinutes: { name: "totalMinutes", label: "Total Minutes", view: "number", dbCol: "total_minutes" }, - totalMinutesOrZero: { name: "totalMinutesOrZero", label: "Total Minutes Or Zero", view: "number", dbCol: "total_minutes_or_zero" }, - longShare: { name: "longShare", label: "Long Share", view: "number", dbCol: "long_share" }, - longShareOrZero: { name: "longShareOrZero", label: "Long Share Or Zero", view: "number", dbCol: "long_share_or_zero" }, -} as const; - -export type ProgramRosterFilter = { - limit?: number; - offset?: number; - sort?: `${"programKey" | "programTitle" | "weeks" | "totalMinutes" | "totalMinutesOrZero" | "longShare" | "longShareOrZero"}:${"asc" | "desc"}` | "programKey" | "programTitle" | "weeks" | "totalMinutes" | "totalMinutesOrZero" | "longShare" | "longShareOrZero"; - programKey?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - programTitle?: string | { eq?: string; ne?: string; in?: string[]; like?: string; isNull?: boolean }; - weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - totalMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - totalMinutesOrZero?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - longShare?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - longShareOrZero?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - or?: ProgramRosterFilter[]; - and?: ProgramRosterFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.names.ts deleted file mode 100644 index 22e0cb4f4f..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.names.ts +++ /dev/null @@ -1,20 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramSessions - -export const ProgramSessionsNames = { - type: "object", - subType: "report", - name: "ProgramSessions", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_program_sessions" }, - }, - fields: { - programKey: { name: "programKey", column: "program_key" }, - programTitle: { name: "programTitle", column: "program_title" }, - sessionMinutes: { name: "sessionMinutes", column: "session_minutes" }, - sessionMinutesOrZero: { name: "sessionMinutesOrZero", column: "session_minutes_or_zero" }, - sessions: { name: "sessions", column: "sessions" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.queries.ts deleted file mode 100644 index bfd8d94b31..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramSessions (ProgramSessions) — report (read-only) -// Extend in your own module (e.g. ProgramSessions.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type ProgramSessions, programSessionsView } from "./ProgramSessions.js"; - -type Db = PgDatabase>; - -export async function listProgramSessions(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(programSessionsView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.ts deleted file mode 100644 index b9cbe855f1..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramSessions.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramSessions (ProgramSessions) - -import { bigint, pgView, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const programSessionsView = pgView("v_program_sessions", { - programKey: bigint("program_key", { mode: "number" }).notNull(), - programTitle: varchar("program_title", { length: 200 }).notNull(), - sessions: bigint("sessions", { mode: "number" }).notNull(), - sessionMinutes: bigint("session_minutes", { mode: "number" }), - sessionMinutesOrZero: bigint("session_minutes_or_zero", { mode: "number" }).notNull(), -}).existing(); - -export const ProgramSessionsSchema = z.object({ - programKey: z.number().int(), - programTitle: z.string(), - sessions: z.number().int(), - sessionMinutes: z.number().int().nullable(), - sessionMinutesOrZero: z.number().int(), -}); - -export type ProgramSessions = z.infer; - -export const ProgramSessions = { - $entity: "ProgramSessions", - $view: "v_program_sessions", - $path: "/program_sessions", - programKey: { name: "programKey", label: "Program Key", view: "number", dbCol: "program_key" }, - programTitle: { name: "programTitle", label: "Program Title", view: "text", dbCol: "program_title" }, - sessions: { name: "sessions", label: "Sessions", view: "number", dbCol: "sessions" }, - sessionMinutes: { name: "sessionMinutes", label: "Session Minutes", view: "number", dbCol: "session_minutes" }, - sessionMinutesOrZero: { name: "sessionMinutesOrZero", label: "Session Minutes Or Zero", view: "number", dbCol: "session_minutes_or_zero" }, -} as const; - -export type ProgramSessionsFilter = { - limit?: number; - offset?: number; - sort?: `${"programKey" | "programTitle" | "sessions" | "sessionMinutes" | "sessionMinutesOrZero"}:${"asc" | "desc"}` | "programKey" | "programTitle" | "sessions" | "sessionMinutes" | "sessionMinutesOrZero"; - programKey?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - programTitle?: string | { eq?: string; ne?: string; in?: string[]; like?: string; isNull?: boolean }; - sessions?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - sessionMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - sessionMinutesOrZero?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: ProgramSessionsFilter[]; - and?: ProgramSessionsFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.names.ts deleted file mode 100644 index 1d42dd8bd9..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.names.ts +++ /dev/null @@ -1,23 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramStat - -export const ProgramStatNames = { - type: "object", - subType: "projection", - name: "ProgramStat", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_program_stat" }, - }, - fields: { - avgMinutes: { name: "avgMinutes", column: "avg_minutes" }, - maxMinutes: { name: "maxMinutes", column: "max_minutes" }, - minMinutes: { name: "minMinutes", column: "min_minutes" }, - programId: { name: "programId", column: "program_id" }, - totalMinutes: { name: "totalMinutes", column: "total_minutes" }, - weekCount: { name: "weekCount", column: "week_count" }, - }, - identities: { - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.queries.ts deleted file mode 100644 index 8522a3b790..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.queries.ts +++ /dev/null @@ -1,25 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramStat (ProgramStat) — projection (read-only) -// Extend in your own module (e.g. ProgramStat.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type ProgramStat, programStatView } from "./ProgramStat.js"; - -type Db = PgDatabase>; - -export async function findProgramStatById(db: Db, programId: number): Promise { - const [row] = await db.select().from(programStatView).where(eq(programStatView.programId, programId)).limit(1); - return row ?? null; -} - -export async function listProgramStats(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(programStatView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.ts deleted file mode 100644 index 2196035227..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramStat.ts +++ /dev/null @@ -1,48 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramStat (ProgramStat) - -import { bigint, doublePrecision, pgView } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const programStatView = pgView("v_program_stat", { - programId: bigint("program_id", { mode: "number" }).notNull(), - weekCount: bigint("week_count", { mode: "number" }), - totalMinutes: bigint("total_minutes", { mode: "number" }), - avgMinutes: doublePrecision("avg_minutes"), - minMinutes: bigint("min_minutes", { mode: "number" }), - maxMinutes: bigint("max_minutes", { mode: "number" }), -}).existing(); - -export const ProgramStatSchema = z.object({ - programId: z.number().int(), - weekCount: z.number().int().nullable(), - totalMinutes: z.number().int().nullable(), - avgMinutes: z.number().nullable(), - minMinutes: z.number().int().nullable(), - maxMinutes: z.number().int().nullable(), -}); - -export type ProgramStat = z.infer; - -export const ProgramStat = { - $entity: "ProgramStat", - $view: "v_program_stat", - $path: "/program_stats", - programId: { name: "programId", label: "Program Id", view: "number", dbCol: "program_id" }, - weekCount: { name: "weekCount", label: "Week Count", view: "number", dbCol: "week_count" }, - totalMinutes: { name: "totalMinutes", label: "Total Minutes", view: "number", dbCol: "total_minutes" }, - avgMinutes: { name: "avgMinutes", label: "Avg Minutes", view: "number", dbCol: "avg_minutes" }, - minMinutes: { name: "minMinutes", label: "Min Minutes", view: "number", dbCol: "min_minutes" }, - maxMinutes: { name: "maxMinutes", label: "Max Minutes", view: "number", dbCol: "max_minutes" }, -} as const; - -export type ProgramStatFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: ProgramStatFilter[]; - and?: ProgramStatFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramVerdict.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramVerdict.ts deleted file mode 100644 index 0ad48890f2..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramVerdict.ts +++ /dev/null @@ -1,40 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramVerdict (ProgramVerdict) -// Extend in your own module (e.g. ProgramVerdict.extra.ts) — nothing imports it for you. - -import { z } from "zod"; - -export interface ProgramVerdict { - verdict: ProgramVerdictVerdict; - rationale: string; -} - -export type ProgramVerdictVerdict = "GOOD" | "OK" | "POOR"; -export const ProgramVerdictVerdictEnum = z.enum(["GOOD", "OK", "POOR"]); - -export const ProgramVerdictInsertSchema = z.object({ - verdict: z.enum(["GOOD", "OK", "POOR"]), - rationale: z.string().min(1).max(480), -}); - -/** - * Metadata constants for the value object ProgramVerdict: each field's name, label, view and the - * validation rules derived from its validator children (e.g. `ProgramVerdict..rules.maxLength.value`). - */ -export const ProgramVerdict = { - $entity: "ProgramVerdict", - verdict: { - name: "verdict", - label: "Verdict", - view: "dropdown", - rules: { required: "Verdict is required" }, - options: ["GOOD", "OK", "POOR"] as const, - }, - rationale: { - name: "rationale", - label: "Rationale", - view: "text", - htmlType: "text", - rules: { required: "Rationale is required", maxLength: { value: 480, message: "Must be 480 characters or fewer" } }, - }, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.names.ts deleted file mode 100644 index 9f1809cefe..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.names.ts +++ /dev/null @@ -1,20 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramView - -export const ProgramViewNames = { - type: "object", - subType: "projection", - name: "ProgramView", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_program" }, - }, - fields: { - id: { name: "id", column: "id" }, - status: { name: "status", column: "status" }, - title: { name: "title", column: "title" }, - }, - identities: { - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.queries.ts deleted file mode 100644 index ce44872ece..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.queries.ts +++ /dev/null @@ -1,25 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramView (ProgramView) — projection (read-only) -// Extend in your own module (e.g. ProgramView.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type ProgramView, programViewView } from "./ProgramView.js"; - -type Db = PgDatabase>; - -export async function findProgramViewById(db: Db, id: number): Promise { - const [row] = await db.select().from(programViewView).where(eq(programViewView.id, id)).limit(1); - return row ?? null; -} - -export async function listProgramViews(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(programViewView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.ts deleted file mode 100644 index 73210ded6f..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramView.ts +++ /dev/null @@ -1,39 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramView (ProgramView) - -import { bigint, pgView, text } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const programViewView = pgView("v_program", { - id: bigint("id", { mode: "number" }).notNull(), - title: text("title"), - status: text("status", { enum: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const }).notNull(), -}).existing(); - -export const ProgramViewSchema = z.object({ - id: z.number().int(), - title: z.string().nullable(), - status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]), -}); - -export type ProgramView = z.infer; - -export const ProgramView = { - $entity: "ProgramView", - $view: "v_program", - $path: "/program_views", - id: { name: "id", label: "Id", view: "number", dbCol: "id" }, - title: { name: "title", label: "Title", view: "text", dbCol: "title" }, - status: { name: "status", label: "Status", view: "dropdown", dbCol: "status" }, -} as const; - -export type ProgramViewFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: ProgramViewFilter[]; - and?: ProgramViewFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.names.ts deleted file mode 100644 index add5c32e81..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.names.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramsByMonth - -export const ProgramsByMonthNames = { - type: "object", - subType: "report", - name: "ProgramsByMonth", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_programs_by_month" }, - }, - fields: { - createdAtMonth: { name: "createdAtMonth", column: "created_at_month" }, - listValue: { name: "listValue", column: "list_value" }, - programs: { name: "programs", column: "programs" }, - status: { name: "status", column: "status" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.queries.ts deleted file mode 100644 index e971f3e1b4..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramsByMonth (ProgramsByMonth) — report (read-only) -// Extend in your own module (e.g. ProgramsByMonth.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type ProgramsByMonth, programsByMonthView } from "./ProgramsByMonth.js"; - -type Db = PgDatabase>; - -export async function listProgramsByMonths(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(programsByMonthView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.ts deleted file mode 100644 index fdbecc8eb9..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByMonth.ts +++ /dev/null @@ -1,46 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramsByMonth (ProgramsByMonth) - -import { bigint, date, pgView, text } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const programsByMonthView = pgView("v_programs_by_month", { - createdAtMonth: date("created_at_month").notNull(), - status: text("status", { enum: ["DRAFT", "PUBLISHED", "ARCHIVED"] as const }).notNull(), - programs: bigint("programs", { mode: "number" }).notNull(), - listValue: bigint("list_value", { mode: "number" }), -}).existing(); - -export const ProgramsByMonthSchema = z.object({ - createdAtMonth: z.string(), - status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]), - programs: z.number().int(), - listValue: z.number().int().nullable(), -}); - -export type ProgramsByMonth = z.infer; - -export const ProgramsByMonth = { - $entity: "ProgramsByMonth", - $view: "v_programs_by_month", - $path: "/programs_by_months", - createdAtMonth: { name: "createdAtMonth", label: "Created At Month", view: "date", dbCol: "created_at_month" }, - status: { name: "status", label: "Status", view: "dropdown", dbCol: "status" }, - programs: { name: "programs", label: "Programs", view: "number", dbCol: "programs" }, - listValue: { name: "listValue", label: "List Value", view: "currency", dbCol: "list_value", currency: "USD", locale: "en-US" }, -} as const; - -export type ProgramsByMonthFilter = { - limit?: number; - offset?: number; - sort?: `${"createdAtMonth" | "status" | "programs" | "listValue"}:${"asc" | "desc"}` | "createdAtMonth" | "status" | "programs" | "listValue"; - createdAtMonth?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - status?: "DRAFT" | "PUBLISHED" | "ARCHIVED" | { eq?: "DRAFT" | "PUBLISHED" | "ARCHIVED"; ne?: "DRAFT" | "PUBLISHED" | "ARCHIVED"; in?: ("DRAFT" | "PUBLISHED" | "ARCHIVED")[]; like?: string; isNull?: boolean }; - programs?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - listValue?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: ProgramsByMonthFilter[]; - and?: ProgramsByMonthFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.names.ts deleted file mode 100644 index 07ac1e1a05..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.names.ts +++ /dev/null @@ -1,17 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramsByWeek - -export const ProgramsByWeekNames = { - type: "object", - subType: "report", - name: "ProgramsByWeek", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_programs_by_week" }, - }, - fields: { - createdAtWeek: { name: "createdAtWeek", column: "created_at_week" }, - programs: { name: "programs", column: "programs" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.queries.ts deleted file mode 100644 index 793f304e59..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramsByWeek (ProgramsByWeek) — report (read-only) -// Extend in your own module (e.g. ProgramsByWeek.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type ProgramsByWeek, programsByWeekView } from "./ProgramsByWeek.js"; - -type Db = PgDatabase>; - -export async function listProgramsByWeeks(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(programsByWeekView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.ts deleted file mode 100644 index ea3ad67232..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsByWeek.ts +++ /dev/null @@ -1,38 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramsByWeek (ProgramsByWeek) - -import { bigint, date, pgView } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const programsByWeekView = pgView("v_programs_by_week", { - createdAtWeek: date("created_at_week").notNull(), - programs: bigint("programs", { mode: "number" }).notNull(), -}).existing(); - -export const ProgramsByWeekSchema = z.object({ - createdAtWeek: z.string(), - programs: z.number().int(), -}); - -export type ProgramsByWeek = z.infer; - -export const ProgramsByWeek = { - $entity: "ProgramsByWeek", - $view: "v_programs_by_week", - $path: "/programs_by_weeks", - createdAtWeek: { name: "createdAtWeek", label: "Created At Week", view: "date", dbCol: "created_at_week" }, - programs: { name: "programs", label: "Programs", view: "number", dbCol: "programs" }, -} as const; - -export type ProgramsByWeekFilter = { - limit?: number; - offset?: number; - sort?: `${"createdAtWeek" | "programs"}:${"asc" | "desc"}` | "createdAtWeek" | "programs"; - createdAtWeek?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - programs?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: ProgramsByWeekFilter[]; - and?: ProgramsByWeekFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.names.ts deleted file mode 100644 index 74a01da315..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.names.ts +++ /dev/null @@ -1,17 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramsEmptyScope - -export const ProgramsEmptyScopeNames = { - type: "object", - subType: "report", - name: "ProgramsEmptyScope", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_programs_empty_scope" }, - }, - fields: { - avgPriceOrMinusOne: { name: "avgPriceOrMinusOne", column: "avg_price_or_minus_one" }, - programs: { name: "programs", column: "programs" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.queries.ts deleted file mode 100644 index b60a0b1afc..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramsEmptyScope (ProgramsEmptyScope) — report (read-only) -// Extend in your own module (e.g. ProgramsEmptyScope.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type ProgramsEmptyScope, programsEmptyScopeView } from "./ProgramsEmptyScope.js"; - -type Db = PgDatabase>; - -export async function listProgramsEmptyScopes(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(programsEmptyScopeView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.ts deleted file mode 100644 index 6fa5498102..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsEmptyScope.ts +++ /dev/null @@ -1,38 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramsEmptyScope (ProgramsEmptyScope) - -import { bigint, numeric, pgView } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const programsEmptyScopeView = pgView("v_programs_empty_scope", { - programs: bigint("programs", { mode: "number" }).notNull(), - avgPriceOrMinusOne: numeric("avg_price_or_minus_one", { precision: 19, scale: 4 }).notNull(), -}).existing(); - -export const ProgramsEmptyScopeSchema = z.object({ - programs: z.number().int(), - avgPriceOrMinusOne: z.string(), -}); - -export type ProgramsEmptyScope = z.infer; - -export const ProgramsEmptyScope = { - $entity: "ProgramsEmptyScope", - $view: "v_programs_empty_scope", - $path: "/programs_empty_scopes", - programs: { name: "programs", label: "Programs", view: "number", dbCol: "programs" }, - avgPriceOrMinusOne: { name: "avgPriceOrMinusOne", label: "Avg Price Or Minus One", view: "number", dbCol: "avg_price_or_minus_one" }, -} as const; - -export type ProgramsEmptyScopeFilter = { - limit?: number; - offset?: number; - sort?: `${"programs" | "avgPriceOrMinusOne"}:${"asc" | "desc"}` | "programs" | "avgPriceOrMinusOne"; - programs?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - avgPriceOrMinusOne?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - or?: ProgramsEmptyScopeFilter[]; - and?: ProgramsEmptyScopeFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.names.ts deleted file mode 100644 index d8bd5d7b53..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.names.ts +++ /dev/null @@ -1,22 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramsOverTime - -export const ProgramsOverTimeNames = { - type: "object", - subType: "report", - name: "ProgramsOverTime", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_programs_over_time" }, - }, - fields: { - avgPrice: { name: "avgPrice", column: "avg_price" }, - cheapest: { name: "cheapest", column: "cheapest" }, - createdAtDay: { name: "createdAtDay", column: "created_at_day" }, - createdAtQuarter: { name: "createdAtQuarter", column: "created_at_quarter" }, - createdAtYear: { name: "createdAtYear", column: "created_at_year" }, - priciest: { name: "priciest", column: "priciest" }, - programs: { name: "programs", column: "programs" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.queries.ts deleted file mode 100644 index c28356adf3..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramsOverTime (ProgramsOverTime) — report (read-only) -// Extend in your own module (e.g. ProgramsOverTime.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type ProgramsOverTime, programsOverTimeView } from "./ProgramsOverTime.js"; - -type Db = PgDatabase>; - -export async function listProgramsOverTimes(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(programsOverTimeView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.ts deleted file mode 100644 index e041e1b49d..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ProgramsOverTime.ts +++ /dev/null @@ -1,58 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ProgramsOverTime (ProgramsOverTime) - -import { bigint, date, numeric, pgView } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const programsOverTimeView = pgView("v_programs_over_time", { - createdAtDay: date("created_at_day").notNull(), - createdAtQuarter: date("created_at_quarter").notNull(), - createdAtYear: date("created_at_year").notNull(), - programs: bigint("programs", { mode: "number" }).notNull(), - avgPrice: numeric("avg_price", { precision: 19, scale: 4 }), - cheapest: bigint("cheapest", { mode: "number" }), - priciest: bigint("priciest", { mode: "number" }), -}).existing(); - -export const ProgramsOverTimeSchema = z.object({ - createdAtDay: z.string(), - createdAtQuarter: z.string(), - createdAtYear: z.string(), - programs: z.number().int(), - avgPrice: z.string().nullable(), - cheapest: z.number().int().nullable(), - priciest: z.number().int().nullable(), -}); - -export type ProgramsOverTime = z.infer; - -export const ProgramsOverTime = { - $entity: "ProgramsOverTime", - $view: "v_programs_over_time", - $path: "/programs_over_times", - createdAtDay: { name: "createdAtDay", label: "Created At Day", view: "date", dbCol: "created_at_day" }, - createdAtQuarter: { name: "createdAtQuarter", label: "Created At Quarter", view: "date", dbCol: "created_at_quarter" }, - createdAtYear: { name: "createdAtYear", label: "Created At Year", view: "date", dbCol: "created_at_year" }, - programs: { name: "programs", label: "Programs", view: "number", dbCol: "programs" }, - avgPrice: { name: "avgPrice", label: "Avg Price", view: "number", dbCol: "avg_price" }, - cheapest: { name: "cheapest", label: "Cheapest", view: "currency", dbCol: "cheapest", currency: "USD", locale: "en-US" }, - priciest: { name: "priciest", label: "Priciest", view: "currency", dbCol: "priciest", currency: "USD", locale: "en-US" }, -} as const; - -export type ProgramsOverTimeFilter = { - limit?: number; - offset?: number; - sort?: `${"createdAtDay" | "createdAtQuarter" | "createdAtYear" | "programs" | "avgPrice" | "cheapest" | "priciest"}:${"asc" | "desc"}` | "createdAtDay" | "createdAtQuarter" | "createdAtYear" | "programs" | "avgPrice" | "cheapest" | "priciest"; - createdAtDay?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - createdAtQuarter?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - createdAtYear?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - programs?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - avgPrice?: string | { eq?: string; ne?: string; gt?: string; gte?: string; lt?: string; lte?: string; in?: string[]; isNull?: boolean }; - cheapest?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - priciest?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: ProgramsOverTimeFilter[]; - and?: ProgramsOverTimeFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.names.ts deleted file mode 100644 index 5deef7de69..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.names.ts +++ /dev/null @@ -1,16 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: RecentPrograms - -export const RecentProgramsNames = { - type: "object", - subType: "report", - name: "RecentPrograms", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_recent_programs" }, - }, - fields: { - programs: { name: "programs", column: "programs" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.queries.ts deleted file mode 100644 index 10b246de52..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: RecentPrograms (RecentPrograms) — report (read-only) -// Extend in your own module (e.g. RecentPrograms.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type RecentPrograms, recentProgramsView } from "./RecentPrograms.js"; - -type Db = PgDatabase>; - -export async function listRecentPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(recentProgramsView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.ts deleted file mode 100644 index 82a19fee3b..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/RecentPrograms.ts +++ /dev/null @@ -1,34 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: RecentPrograms (RecentPrograms) - -import { bigint, pgView } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const recentProgramsView = pgView("v_recent_programs", { - programs: bigint("programs", { mode: "number" }).notNull(), -}).existing(); - -export const RecentProgramsSchema = z.object({ - programs: z.number().int(), -}); - -export type RecentPrograms = z.infer; - -export const RecentPrograms = { - $entity: "RecentPrograms", - $view: "v_recent_programs", - $path: "/recent_programs", - programs: { name: "programs", label: "Programs", view: "number", dbCol: "programs" }, -} as const; - -export type RecentProgramsFilter = { - limit?: number; - offset?: number; - sort?: `${"programs"}:${"asc" | "desc"}` | "programs"; - programs?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: RecentProgramsFilter[]; - and?: RecentProgramsFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.names.ts deleted file mode 100644 index 44ba951928..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.names.ts +++ /dev/null @@ -1,23 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ReferralAuth - -import { AuthNames } from "./Auth.names.js"; - -export const ReferralAuthNames = { - type: "object", - subType: "entity", - name: "ReferralAuth", - sources: { - ...AuthNames.sources, - }, - fields: { - ...AuthNames.fields, - urgency: { name: "urgency", column: "urgency" }, - }, - identities: { - ...AuthNames.identities, - }, - indexes: { - ...AuthNames.indexes, - }, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.ts deleted file mode 100644 index 1109fb75d1..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/ReferralAuth.ts +++ /dev/null @@ -1,113 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: ReferralAuth (ReferralAuth) -// Extend in your own module (e.g. ReferralAuth.extra.ts) — nothing imports it for you. - -import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; -import { z } from "zod"; - -export interface ReferralAuth { - id?: number | undefined; - type?: ReferralAuthType | null | undefined; - reference: string; - urgency: string | null; -} - -export type ReferralAuthType = "Bridge" | "Coupon" | "Permit" | "Referral"; -export const ReferralAuthTypeEnum = z.enum(["Bridge", "Coupon", "Permit", "Referral"]); - -export const ReferralAuthSchema = z.object({ - id: z.number().int(), - type: z.literal("Referral"), - reference: z.string().min(1).max(80), - urgency: z.string().min(1).max(16).nullable(), -}); - -export const ReferralAuthInsertSchema = z.object({ - type: z.literal("Referral"), - reference: z.string().min(1).max(80), - urgency: z.string().min(1).max(16).optional(), -}); - -export const ReferralAuthUpdateSchema = z.object({ - reference: z.string().min(1).max(80).optional(), - urgency: z.string().min(1).max(16).optional(), -}); - -/** - * Typed create shape for ReferralAuth: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createReferralAuth` call site; - * the schema still validates at runtime. - */ -export type ReferralAuthCreate = z.input; - -/** - * Typed patch shape for ReferralAuth: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateReferralAuth` call site. - */ -export type ReferralAuthPatch = z.input; - -/** - * Metadata constants for ReferralAuth. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(ReferralAuth, ReferralAuthInsertSchema); - * - */ -export const ReferralAuth = { - $entity: "ReferralAuth", - $table: "auths", - $path: "/auths/referral", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - type: { - name: "type", - label: "Type", - view: "dropdown", - options: ["Bridge", "Coupon", "Permit", "Referral"] as const, - }, - reference: { - name: "reference", - label: "Reference", - view: "text", - htmlType: "text", - rules: { required: "Reference is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, - }, - urgency: { - name: "urgency", - label: "Urgency", - view: "text", - htmlType: "text", - rules: { required: "Urgency is required", maxLength: { value: 16, message: "Must be 16 characters or fewer" } }, - }, -} as const; - -export const ReferralAuthFilterAllowlist = {} as const satisfies FilterAllowlist; - -export const ReferralAuthSortAllowlist = {} as const satisfies SortAllowlist; - -export type ReferralAuthFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: ReferralAuthFilter[]; - and?: ReferralAuthFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.names.ts deleted file mode 100644 index 9d59d90620..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.names.ts +++ /dev/null @@ -1,21 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Session - -export const SessionNames = { - type: "object", - subType: "entity", - name: "Session", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "sessions" }, - }, - fields: { - id: { name: "id", column: "id" }, - minutes: { name: "minutes", column: "minutes" }, - weekId: { name: "weekId", column: "week_id" }, - }, - identities: { - fkWeek: { type: "identity", subType: "reference", name: "fkWeek" }, - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.queries.ts deleted file mode 100644 index cb8545afa8..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.queries.ts +++ /dev/null @@ -1,61 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Session (Session) -// Extend in your own module (e.g. Session.extra.ts) — nothing imports it for you. - -import { eq, inArray } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { type Session, SessionInsertSchema, type SessionPatch, SessionUpdateSchema, sessions } from "./Session.js"; - -type Db = PgDatabase>; - -export async function findSessionById(db: Db, id: number): Promise { - const [session] = await db.select().from(sessions).where(eq(sessions.id, id)).limit(1); - return session ?? null; -} - -export async function listSessions(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(sessions).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createSession(db: Db, data: z.input): Promise { - const validated = SessionInsertSchema.parse(data); - const [session] = await db.insert(sessions).values(validated).returning(); - return session!; -} - -export async function updateSession(db: Db, id: number, patch: SessionPatch): Promise { - const validated = SessionUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findSessionById(db, id); - } - const [session] = await db.update(sessions).set(validated).where(eq(sessions.id, id)).returning(); - return session ?? null; -} - -export async function deleteSessionById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(sessions).where(eq(sessions.id, id)).returning(); - return deleted.length > 0; -} - -export async function findSessionsByWeek(db: Db, weekId: number): Promise { - return db.select().from(sessions).where(eq(sessions.weekId, weekId)); -} - -export async function findSessionsByWeekIn(db: Db, weekIds: number[]): Promise { - if (weekIds.length === 0) { - return []; - } - return db.select().from(sessions).where(inArray(sessions.weekId, weekIds)); -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.ts deleted file mode 100644 index 35258fb418..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Session.ts +++ /dev/null @@ -1,97 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Session (Session) -// Extend in your own module (e.g. Session.extra.ts) — nothing imports it for you. - -import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { type AnyPgColumn, bigint, integer, pgTable } from "drizzle-orm/pg-core"; -import { z } from "zod"; -import { weeks } from "./Week.js"; - -export const sessions = pgTable("sessions", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - weekId: bigint("week_id", { mode: "number" }).notNull().references((): AnyPgColumn => weeks.id), - minutes: integer("minutes").notNull(), -}); - -export type Session = InferSelectModel; -export type SessionInsert = InferInsertModel; -export type SessionUpdate = Partial; - -export const SessionInsertSchema = z.object({ - weekId: z.number().int(), - minutes: z.number().int(), -}); - -export const SessionUpdateSchema = z.object({ - weekId: z.number().int().optional(), - minutes: z.number().int().optional(), -}); - -/** - * Typed create shape for Session: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createSession` call site; - * the schema still validates at runtime. - */ -export type SessionCreate = z.input; - -/** - * Typed patch shape for Session: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateSession` call site. - */ -export type SessionPatch = z.input; - -/** - * Metadata constants for Session. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Session, SessionInsertSchema); - * - */ -export const Session = { - $entity: "Session", - $table: "sessions", - $path: "/sessions", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - weekId: { - name: "weekId", - label: "Week Id", - view: "number", - htmlType: "number", - rules: { required: "Week Id is required" }, - }, - minutes: { - name: "minutes", - label: "Minutes", - view: "number", - htmlType: "number", - rules: { required: "Minutes is required" }, - }, -} as const; - -export type SessionFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: SessionFilter[]; - and?: SessionFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.names.ts deleted file mode 100644 index 69db72de97..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.names.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: SessionsByProgram - -export const SessionsByProgramNames = { - type: "object", - subType: "report", - name: "SessionsByProgram", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_sessions_by_program" }, - }, - fields: { - programTitle: { name: "programTitle", column: "program_title" }, - sessionMinutes: { name: "sessionMinutes", column: "session_minutes" }, - sessions: { name: "sessions", column: "sessions" }, - weekKey: { name: "weekKey", column: "week_key" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.queries.ts deleted file mode 100644 index d441835946..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: SessionsByProgram (SessionsByProgram) — report (read-only) -// Extend in your own module (e.g. SessionsByProgram.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type SessionsByProgram, sessionsByProgramView } from "./SessionsByProgram.js"; - -type Db = PgDatabase>; - -export async function listSessionsByPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(sessionsByProgramView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.ts deleted file mode 100644 index a74a352d1a..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/SessionsByProgram.ts +++ /dev/null @@ -1,46 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: SessionsByProgram (SessionsByProgram) - -import { bigint, pgView, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const sessionsByProgramView = pgView("v_sessions_by_program", { - programTitle: varchar("program_title", { length: 200 }).notNull(), - weekKey: bigint("week_key", { mode: "number" }), - sessions: bigint("sessions", { mode: "number" }).notNull(), - sessionMinutes: bigint("session_minutes", { mode: "number" }), -}).existing(); - -export const SessionsByProgramSchema = z.object({ - programTitle: z.string(), - weekKey: z.number().int().nullable(), - sessions: z.number().int(), - sessionMinutes: z.number().int().nullable(), -}); - -export type SessionsByProgram = z.infer; - -export const SessionsByProgram = { - $entity: "SessionsByProgram", - $view: "v_sessions_by_program", - $path: "/sessions_by_programs", - programTitle: { name: "programTitle", label: "Program Title", view: "text", dbCol: "program_title" }, - weekKey: { name: "weekKey", label: "Week Key", view: "number", dbCol: "week_key" }, - sessions: { name: "sessions", label: "Sessions", view: "number", dbCol: "sessions" }, - sessionMinutes: { name: "sessionMinutes", label: "Session Minutes", view: "number", dbCol: "session_minutes" }, -} as const; - -export type SessionsByProgramFilter = { - limit?: number; - offset?: number; - sort?: `${"programTitle" | "weekKey" | "sessions" | "sessionMinutes"}:${"asc" | "desc"}` | "programTitle" | "weekKey" | "sessions" | "sessionMinutes"; - programTitle?: string | { eq?: string; ne?: string; in?: string[]; like?: string; isNull?: boolean }; - weekKey?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - sessions?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - sessionMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: SessionsByProgramFilter[]; - and?: SessionsByProgramFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Settings.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Settings.ts deleted file mode 100644 index 3ceee3f004..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Settings.ts +++ /dev/null @@ -1,43 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Settings (Settings) -// Extend in your own module (e.g. Settings.extra.ts) — nothing imports it for you. - -import { z } from "zod"; - -export interface Settings { - theme?: string | undefined; - notify?: boolean | undefined; - retries?: number | undefined; -} - -export const SettingsInsertSchema = z.object({ - theme: z.string().optional(), - notify: z.boolean().optional(), - retries: z.number().int().optional(), -}); - -/** - * Metadata constants for the value object Settings: each field's name, label, view and the - * validation rules derived from its validator children (e.g. `Settings..rules.maxLength.value`). - */ -export const Settings = { - $entity: "Settings", - theme: { - name: "theme", - label: "Theme", - view: "text", - htmlType: "text", - }, - notify: { - name: "notify", - label: "Notify", - view: "checkbox", - htmlType: "checkbox", - }, - retries: { - name: "retries", - label: "Retries", - view: "number", - htmlType: "number", - }, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.names.ts deleted file mode 100644 index 5fbeb7660c..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.names.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Tag - -export const TagNames = { - type: "object", - subType: "entity", - name: "Tag", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "tags" }, - }, - fields: { - id: { name: "id", column: "id" }, - name: { name: "name", column: "name" }, - }, - identities: { - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.queries.ts deleted file mode 100644 index 50e299aec8..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.queries.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Tag (Tag) -// Extend in your own module (e.g. Tag.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { type Tag, TagInsertSchema, type TagPatch, TagUpdateSchema, tags } from "./Tag.js"; - -type Db = PgDatabase>; - -export async function findTagById(db: Db, id: number): Promise { - const [tag] = await db.select().from(tags).where(eq(tags.id, id)).limit(1); - return tag ?? null; -} - -export async function listTags(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(tags).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createTag(db: Db, data: z.input): Promise { - const validated = TagInsertSchema.parse(data); - const [tag] = await db.insert(tags).values(validated).returning(); - return tag!; -} - -export async function updateTag(db: Db, id: number, patch: TagPatch): Promise { - const validated = TagUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findTagById(db, id); - } - const [tag] = await db.update(tags).set(validated).where(eq(tags.id, id)).returning(); - return tag ?? null; -} - -export async function deleteTagById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(tags).where(eq(tags.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.ts deleted file mode 100644 index d4489e4189..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Tag.ts +++ /dev/null @@ -1,86 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Tag (Tag) -// Extend in your own module (e.g. Tag.extra.ts) — nothing imports it for you. - -import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { bigint, pgTable, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -export const tags = pgTable("tags", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - name: varchar("name", { length: 80 }).notNull(), -}); - -export type Tag = InferSelectModel; -export type TagInsert = InferInsertModel; -export type TagUpdate = Partial; - -export const TagInsertSchema = z.object({ - name: z.string().min(1).max(80), -}); - -export const TagUpdateSchema = z.object({ - name: z.string().min(1).max(80).optional(), -}); - -/** - * Typed create shape for Tag: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createTag` call site; - * the schema still validates at runtime. - */ -export type TagCreate = z.input; - -/** - * Typed patch shape for Tag: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateTag` call site. - */ -export type TagPatch = z.input; - -/** - * Metadata constants for Tag. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Tag, TagInsertSchema); - * - */ -export const Tag = { - $entity: "Tag", - $table: "tags", - $path: "/tags", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - name: { - name: "name", - label: "Name", - view: "text", - htmlType: "text", - rules: { required: "Name is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, - }, -} as const; - -export type TagFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: TagFilter[]; - and?: TagFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.names.ts deleted file mode 100644 index 277f662361..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.names.ts +++ /dev/null @@ -1,23 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Week - -export const WeekNames = { - type: "object", - subType: "entity", - name: "Week", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "weeks" }, - }, - fields: { - deload: { name: "deload", column: "deload" }, - durationMinutes: { name: "durationMinutes", column: "duration_minutes" }, - id: { name: "id", column: "id" }, - label: { name: "label", column: "label" }, - programId: { name: "programId", column: "program_id" }, - }, - identities: { - fkProgram: { type: "identity", subType: "reference", name: "fkProgram" }, - id: { type: "identity", subType: "primary", name: "id" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.queries.ts deleted file mode 100644 index 8c89fc4b9a..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.queries.ts +++ /dev/null @@ -1,61 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Week (Week) -// Extend in your own module (e.g. Week.extra.ts) — nothing imports it for you. - -import { eq, inArray } from "drizzle-orm"; -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import type { z } from "zod"; -import { type Week, WeekInsertSchema, type WeekPatch, WeekUpdateSchema, weeks } from "./Week.js"; - -type Db = PgDatabase>; - -export async function findWeekById(db: Db, id: number): Promise { - const [week] = await db.select().from(weeks).where(eq(weeks.id, id)).limit(1); - return week ?? null; -} - -export async function listWeeks(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(weeks).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createWeek(db: Db, data: z.input): Promise { - const validated = WeekInsertSchema.parse(data); - const [week] = await db.insert(weeks).values(validated).returning(); - return week!; -} - -export async function updateWeek(db: Db, id: number, patch: WeekPatch): Promise { - const validated = WeekUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findWeekById(db, id); - } - const [week] = await db.update(weeks).set(validated).where(eq(weeks.id, id)).returning(); - return week ?? null; -} - -export async function deleteWeekById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(weeks).where(eq(weeks.id, id)).returning(); - return deleted.length > 0; -} - -export async function findWeeksByProgram(db: Db, programId: number): Promise { - return db.select().from(weeks).where(eq(weeks.programId, programId)); -} - -export async function findWeeksByProgramIn(db: Db, programIds: number[]): Promise { - if (programIds.length === 0) { - return []; - } - return db.select().from(weeks).where(inArray(weeks.programId, programIds)); -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.ts deleted file mode 100644 index 11fa7bc792..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/Week.ts +++ /dev/null @@ -1,116 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Week (Week) -// Extend in your own module (e.g. Week.extra.ts) — nothing imports it for you. - -import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { type AnyPgColumn, bigint, boolean, integer, pgTable, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; -import { programs } from "./Program.js"; - -export const weeks = pgTable("weeks", { - id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), - programId: bigint("program_id", { mode: "number" }).notNull().references((): AnyPgColumn => programs.id), - label: varchar("label", { length: 80 }), - durationMinutes: integer("duration_minutes").notNull(), - deload: boolean("deload"), -}); - -export type Week = InferSelectModel; -export type WeekInsert = InferInsertModel; -export type WeekUpdate = Partial; - -export const WeekInsertSchema = z.object({ - programId: z.number().int(), - label: z.string().max(80).optional(), - durationMinutes: z.number().int(), - deload: z.boolean().optional(), -}); - -export const WeekUpdateSchema = z.object({ - programId: z.number().int().optional(), - label: z.string().max(80).optional().nullable(), - durationMinutes: z.number().int().optional(), - deload: z.boolean().optional().nullable(), -}); - -/** - * Typed create shape for Week: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createWeek` call site; - * the schema still validates at runtime. - */ -export type WeekCreate = z.input; - -/** - * Typed patch shape for Week: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateWeek` call site. - */ -export type WeekPatch = z.input; - -/** - * Metadata constants for Week. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Week, WeekInsertSchema); - * - */ -export const Week = { - $entity: "Week", - $table: "weeks", - $path: "/weeks", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - programId: { - name: "programId", - label: "Program Id", - view: "number", - htmlType: "number", - rules: { required: "Program Id is required" }, - }, - label: { - name: "label", - label: "Label", - view: "text", - htmlType: "text", - rules: { maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, - }, - durationMinutes: { - name: "durationMinutes", - label: "Duration Minutes", - view: "number", - htmlType: "number", - rules: { required: "Duration Minutes is required" }, - }, - deload: { - name: "deload", - label: "Deload", - view: "checkbox", - htmlType: "checkbox", - }, -} as const; - -export type WeekFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: WeekFilter[]; - and?: WeekFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekLabel.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekLabel.ts deleted file mode 100644 index 98ba4a8ea4..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekLabel.ts +++ /dev/null @@ -1,28 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: WeekLabel (WeekLabel) -// Extend in your own module (e.g. WeekLabel.extra.ts) — nothing imports it for you. - -import { z } from "zod"; - -export interface WeekLabel { - label: string; -} - -export const WeekLabelInsertSchema = z.object({ - label: z.string().min(1).max(80), -}); - -/** - * Metadata constants for the value object WeekLabel: each field's name, label, view and the - * validation rules derived from its validator children (e.g. `WeekLabel..rules.maxLength.value`). - */ -export const WeekLabel = { - $entity: "WeekLabel", - label: { - name: "label", - label: "Label", - view: "text", - htmlType: "text", - rules: { required: "Label is required", maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, - }, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.names.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.names.ts deleted file mode 100644 index 16bbc3bef0..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.names.ts +++ /dev/null @@ -1,22 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: WeekShapes - -export const WeekShapesNames = { - type: "object", - subType: "report", - name: "WeekShapes", - sources: { - primary: { type: "source", subType: "rdb", kind: "view", view: "v_week_shapes" }, - }, - fields: { - labelledMinutes: { name: "labelledMinutes", column: "labelled_minutes" }, - longWMinutes: { name: "longWMinutes", column: "long_w_minutes" }, - midWeeks: { name: "midWeeks", column: "mid_weeks" }, - programTitle: { name: "programTitle", column: "program_title" }, - shortWeeks: { name: "shortWeeks", column: "short_weeks" }, - unlabelled: { name: "unlabelled", column: "unlabelled" }, - weeks: { name: "weeks", column: "weeks" }, - }, - identities: {}, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.queries.ts deleted file mode 100644 index f10a0dd379..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: WeekShapes (WeekShapes) — report (read-only) -// Extend in your own module (e.g. WeekShapes.extra.ts) — nothing imports it for you. - -import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -import { type WeekShapes, weekShapesView } from "./WeekShapes.js"; - -type Db = PgDatabase>; - -export async function listWeekShapes(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(weekShapesView).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.ts deleted file mode 100644 index bd221cff2c..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/WeekShapes.ts +++ /dev/null @@ -1,58 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: WeekShapes (WeekShapes) - -import { bigint, pgView, varchar } from "drizzle-orm/pg-core"; -import { z } from "zod"; - -// View declaration — Drizzle uses this for typed SELECT queries. -// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle -// not to attempt DDL for this declaration. -export const weekShapesView = pgView("v_week_shapes", { - programTitle: varchar("program_title", { length: 200 }).notNull(), - weeks: bigint("weeks", { mode: "number" }).notNull(), - unlabelled: bigint("unlabelled", { mode: "number" }).notNull(), - labelledMinutes: bigint("labelled_minutes", { mode: "number" }), - shortWeeks: bigint("short_weeks", { mode: "number" }).notNull(), - midWeeks: bigint("mid_weeks", { mode: "number" }).notNull(), - longWMinutes: bigint("long_w_minutes", { mode: "number" }), -}).existing(); - -export const WeekShapesSchema = z.object({ - programTitle: z.string(), - weeks: z.number().int(), - unlabelled: z.number().int(), - labelledMinutes: z.number().int().nullable(), - shortWeeks: z.number().int(), - midWeeks: z.number().int(), - longWMinutes: z.number().int().nullable(), -}); - -export type WeekShapes = z.infer; - -export const WeekShapes = { - $entity: "WeekShapes", - $view: "v_week_shapes", - $path: "/week_shapes", - programTitle: { name: "programTitle", label: "Program Title", view: "text", dbCol: "program_title" }, - weeks: { name: "weeks", label: "Weeks", view: "number", dbCol: "weeks" }, - unlabelled: { name: "unlabelled", label: "Unlabelled", view: "number", dbCol: "unlabelled" }, - labelledMinutes: { name: "labelledMinutes", label: "Labelled Minutes", view: "number", dbCol: "labelled_minutes" }, - shortWeeks: { name: "shortWeeks", label: "Short Weeks", view: "number", dbCol: "short_weeks" }, - midWeeks: { name: "midWeeks", label: "Mid Weeks", view: "number", dbCol: "mid_weeks" }, - longWMinutes: { name: "longWMinutes", label: "Long WMinutes", view: "number", dbCol: "long_w_minutes" }, -} as const; - -export type WeekShapesFilter = { - limit?: number; - offset?: number; - sort?: `${"programTitle" | "weeks" | "unlabelled" | "labelledMinutes" | "shortWeeks" | "midWeeks" | "longWMinutes"}:${"asc" | "desc"}` | "programTitle" | "weeks" | "unlabelled" | "labelledMinutes" | "shortWeeks" | "midWeeks" | "longWMinutes"; - programTitle?: string | { eq?: string; ne?: string; in?: string[]; like?: string; isNull?: boolean }; - weeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - unlabelled?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - labelledMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - shortWeeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - midWeeks?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - longWMinutes?: number | { eq?: number; ne?: number; gt?: number; gte?: number; lt?: number; lte?: number; in?: number[]; isNull?: boolean }; - or?: WeekShapesFilter[]; - and?: WeekShapesFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.extractor.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.extractor.ts deleted file mode 100644 index 4d899beb2b..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.extractor.ts +++ /dev/null @@ -1,45 +0,0 @@ -// GENERATED — extractor for "coachNote". -// -// Turns dirty LLM text into a fully-typed `ProgramVerdict` graph (nested objects + -// arrays-of-objects populated) in one call, by delegating to the nested-capable extract and -// mapping the all-nullable mirror onto the strict payload. No registry / binding / factory. - -import type { MetaRoot } from "@metaobjectsdev/metadata"; -import type { ExtractionResult } from "@metaobjectsdev/render"; -import type { ProgramVerdict, ProgramVerdictVerdict } from "./ProgramVerdict.js"; -import { type ProgramVerdictExtracted, extractLenientCoachNoteWithLoader } from "./coachNote.response.js"; - -/** - * Extract a fully-typed `ProgramVerdict` from dirty `text` using the loaded `root` (which must - * declare the "ProgramVerdict" payload value-object). Runs the tolerant extract, then maps the - * extracted mirror onto the strict payload. - * - * @throws Error iff a `@required` field was lost, or was present but unusable (MALFORMED — - * an undeclared enum member, text where a number belongs): the strict opt-in gate. - */ -export function extractCoachNote(root: MetaRoot, text: string): ProgramVerdict { - const r = extractLenientCoachNoteWithLoader(root, text); - if (r.report.hasLostRequired() || r.report.hasMalformedRequired()) { - const unusable: string[] = []; - if (r.report.hasLostRequired()) unusable.push("lost required field(s): " + r.report.lostRequired().join(", ")); - if (r.report.hasMalformedRequired()) unusable.push("malformed required field(s): " + r.report.malformedRequired().join(", ")); - throw new Error("extractCoachNote: " + unusable.join("; ")); - } - return toStrictProgramVerdict(r.data!); -} - -/** - * Extract a `ProgramVerdict` from dirty `text` using the loaded `root`, never throwing. - * Re-exposes the nested-capable extract; inspect `report` for lost/malformed/defaulted fields. - */ -export function extractLenientCoachNote(root: MetaRoot, text: string): ExtractionResult { - return extractLenientCoachNoteWithLoader(root, text); -} - -/** Map the all-nullable `ProgramVerdictExtracted` mirror onto the strict `ProgramVerdict` payload. Generated. */ -function toStrictProgramVerdict(m: ProgramVerdictExtracted): ProgramVerdict { - return { - verdict: m.verdict! as ProgramVerdictVerdict, - rationale: m.rationale!, - }; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.response.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.response.ts deleted file mode 100644 index 86b99de2ae..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.response.ts +++ /dev/null @@ -1,103 +0,0 @@ -import type { MetaRoot } from "@metaobjectsdev/metadata"; -import { type ExtractOptions, type ExtractionResult, Format } from "@metaobjectsdev/render"; -import { extractObject } from "@metaobjectsdev/runtime-ts"; -import { z } from "zod"; -import type { ProgramVerdict } from "./ProgramVerdict.js"; - -const CoachNoteSchema = z.object({ - verdict: z.enum(["GOOD", "OK", "POOR"]), - rationale: z.string(), -}); - -export type CoachNoteValidationError = z.ZodError; - -/** - * Parse an LLM response into a typed ProgramVerdict. The reply must BE the JSON document (a - * structured-output / JSON-mode reply); prose or a code fence around it fails. For a raw - * model reply use `extractLenientCoachNoteWithLoader`. - * @throws ZodError on validation failure. - */ -export function parseCoachNote(text: string): ProgramVerdict { - return CoachNoteSchema.parse(JSON.parse(text)); -} - -/** - * Parse an LLM response with explicit error handling (Result-style). - * Does not throw on validation failure. - */ -export function safeParseCoachNote( - text: string, -): { success: true; data: ProgramVerdict } | { success: false; error: CoachNoteValidationError } { - let parsed: unknown; - try { - parsed = JSON.parse(text); - } catch (err) { - return { - success: false, - error: new z.ZodError([{ code: "custom", path: [], message: `invalid JSON: ${(err as Error).message}` }]), - }; - } - const result = CoachNoteSchema.safeParse(parsed); - return result.success - ? { success: true, data: result.data } - : { success: false, error: result.error }; -} - -/** Payload value-object name this parser extracts — resolved against a loaded MetaRoot at runtime. */ -export const COACHNOTE_PAYLOAD_NAME = "ProgramVerdict"; - -/** Best-effort extracted twin of `ProgramVerdict` — every field nullable (null where lost/malformed). */ -export interface ProgramVerdictExtracted { - verdict: string | null; - rationale: string | null; -} - -/** Map an assembled ValueObject graph into a typed `ProgramVerdictExtracted` mirror. Generated; null-tolerant. */ -function fromProgramVerdictExtracted(o: unknown): ProgramVerdictExtracted | null { - if (o == null) return null; - return { - verdict: dlgString(readProp(o, "verdict")), - rationale: dlgString(readProp(o, "rationale")), - }; -} - -// ---- runtime-delegating extract helpers (generated) ---- - -/** Read a property from an assembled backing object, mirroring the MetaField getValue SPI. */ -function readProp(o: unknown, name: string): unknown { - if (o == null) return undefined; - const vo = o as { get?: (n: string) => unknown }; - if (typeof vo.get === "function") return vo.get(name); - return (o as Record)[name]; -} - -function dlgString(v: unknown): string | null { - return v == null ? null : String(v); -} - -/** - * Runtime-delegating tolerant best-effort extraction for a RAW model reply (prose, code - * fences, a truncated or mis-typed field): a bad reply never throws — each field is classified - * in `report` and `data` carries what was recovered (`orThrow` from the render package - * makes a lost @required field an error). Throws only when `root` does not declare the payload - * value object — a setup error, not a reply error. FULLY populates - * nested-object and array-of-object components by delegating to the metadata-driven runtime - * `extractObject` (which assembles the whole graph reflection-free via the Phase A object - * model, reading the live metadata directly), then maps the assembled graph into the typed - * `ProgramVerdictExtracted` mirror. - * - * @param root a loaded MetaRoot (e.g. `(await new MetaDataLoader().load(...)).root`) that declares - * the `ProgramVerdict` value-object. - */ -export function extractLenientCoachNoteWithLoader( - root: MetaRoot, - text: string, - opts?: Partial | null, -): ExtractionResult { - const mo = root.findObject(COACHNOTE_PAYLOAD_NAME); - if (mo === undefined) { - throw new Error(`extractLenientCoachNoteWithLoader: payload "${COACHNOTE_PAYLOAD_NAME}" not found in the supplied MetaRoot`); - } - const outcome = extractObject(mo, text, Format.JSON, opts); - return { data: fromProgramVerdictExtracted(outcome.data), report: outcome.report }; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.responseFormat.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.responseFormat.ts deleted file mode 100644 index 977cdfd801..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/coachNote.responseFormat.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { - FieldKind, - Format, - type OutputFormatSpec, - type PromptOverrides, - PromptStyle, - renderOutputFormat, -} from "@metaobjectsdev/render"; - -const CoachNoteFormatSpec: OutputFormatSpec = { format: Format.JSON, rootName: "ProgramVerdict", style: PromptStyle.GUIDE, fields: [{ name: "verdict", kind: FieldKind.ENUM, required: true, array: false, enumValues: ["GOOD", "OK", "POOR"], enumDoc: null, example: null, instruction: null, nested: null }, { name: "rationale", kind: FieldKind.STRING, required: true, array: false, enumValues: null, enumDoc: null, example: null, instruction: null, nested: null }] } satisfies OutputFormatSpec; - -/** - * The response-format instruction fragment for the coachNote template.prompt - * ("produce your answer like this"). Comment-free — guidance lives in prose / - * inline placeholders / a filled skeleton. Pass `overrides` to override the style - * or per-field example/instruction at render time. - */ -export function renderCoachNoteFormat(overrides?: PromptOverrides): string { - return renderOutputFormat(CoachNoteFormatSpec, overrides ?? {}); -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/enums.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/enums.ts deleted file mode 100644 index 00be4df9d6..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/enums.ts +++ /dev/null @@ -1,7 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Shared enum types (FR-019): one declaration per reused package-level enum. - -import { z } from "zod"; - -export type PublishState = "DRAFT" | "PUBLISHED" | "ARCHIVED"; -export const PublishStateEnum = z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]); diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/index.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/index.ts deleted file mode 100644 index 24785da990..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/index.ts +++ /dev/null @@ -1,59 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -export * from "./AllTypes.js"; -export * from "./AllTypesBreakdown.js"; -export * from "./ArchivedLedgerEntry.js"; -export * from "./Asset.js"; -export * from "./AssetActivity.js"; -export * from "./AssetDays.js"; -export * from "./Auth.js"; -export * from "./AuthsByKind.js"; -export * from "./BridgeAuth.js"; -export * from "./CouponAuth.js"; -export * from "./Entry.js"; -export * from "./EntryTotals.js"; -export * from "./FitnessTotals.js"; -export * from "./FitnessTotalsFilled.js"; -export * from "./Follow.js"; -export * from "./Friendship.js"; -export * from "./Gadget.js"; -export * from "./GadgetEvent.js"; -export * from "./GadgetEventsByLabel.js"; -export * from "./IntEnumArray.js"; -export * from "./Label.js"; -export * from "./Labeled.js"; -export * from "./LedgerEntry.js"; -export * from "./LiveIntroPrograms.js"; -export * from "./Measurement.js"; -export * from "./MeasurementStats.js"; -export * from "./MeasurementStatsFilled.js"; -export * from "./Node.js"; -export * from "./NodesByParent.js"; -export * from "./PermitAuth.js"; -export * from "./Person.js"; -export * from "./Post.js"; -export * from "./PostReferral.js"; -export * from "./PostTag.js"; -export * from "./Program.js"; -export * from "./ProgramBrief.js"; -export * from "./ProgramFlagRoster.js"; -export * from "./ProgramFlags.js"; -export * from "./ProgramLongWeeks.js"; -export * from "./ProgramMinutes.js"; -export * from "./ProgramRoster.js"; -export * from "./ProgramsByMonth.js"; -export * from "./ProgramsByWeek.js"; -export * from "./ProgramsEmptyScope.js"; -export * from "./ProgramSessions.js"; -export * from "./ProgramsOverTime.js"; -export * from "./ProgramStat.js"; -export * from "./ProgramVerdict.js"; -export * from "./ProgramView.js"; -export * from "./RecentPrograms.js"; -export * from "./ReferralAuth.js"; -export * from "./Session.js"; -export * from "./SessionsByProgram.js"; -export * from "./Settings.js"; -export * from "./Tag.js"; -export * from "./Week.js"; -export * from "./WeekLabel.js"; -export * from "./WeekShapes.js"; diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/package.json b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/package.json deleted file mode 100644 index 7c34deb583..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/package.json +++ /dev/null @@ -1 +0,0 @@ -{"type":"module"} \ No newline at end of file diff --git a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/prompts.ts b/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/prompts.ts deleted file mode 100644 index ec13c286dd..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-codegen-compile-postgres-Rca6RO/prompts.ts +++ /dev/null @@ -1,8 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. - -import { type Provider, render } from "@metaobjectsdev/render"; -import type { ProgramBrief } from "./ProgramBrief.js"; - -export function renderCoachNote(payload: ProgramBrief, provider: Provider): string { - return render({ ref: "fitness/coach-note", payload, format: "text", provider, verify: [{"name":"title"},{"name":"weekCount"},{"name":"weekLabels","fields":[{"name":"label"}],"isArray":true}] }); -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.queries.ts deleted file mode 100644 index 0bd045862b..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.queries.ts +++ /dev/null @@ -1,56 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: WorkItem (WorkItem) -// Extend in your own module (e.g. WorkItem.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -import type { z } from "zod"; -import { - type WorkItem, - WorkItemInsertSchema, - type WorkItemPatch, - WorkItemUpdateSchema, - workItems, -} from "./WorkItem.js"; - -type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; - -export async function findWorkItemById(db: Db, id: number): Promise { - const [workItem] = await db.select().from(workItems).where(eq(workItems.id, id)).limit(1); - return workItem ?? null; -} - -export async function listWorkItems(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(workItems).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createWorkItem(db: Db, data: z.input): Promise { - const validated = WorkItemInsertSchema.parse(data); - const [workItem] = await db.insert(workItems).values(validated).returning(); - return workItem!; -} - -export async function updateWorkItem(db: Db, id: number, patch: WorkItemPatch): Promise { - const validated = WorkItemUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findWorkItemById(db, id); - } - const [workItem] = await db.update(workItems).set(validated).where(eq(workItems.id, id)).returning(); - return workItem ?? null; -} - -export async function deleteWorkItemById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(workItems).where(eq(workItems.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.ts b/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.ts deleted file mode 100644 index 1e59f0a338..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/WorkItem.ts +++ /dev/null @@ -1,86 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: WorkItem (WorkItem) -// Extend in your own module (e.g. WorkItem.extra.ts) — nothing imports it for you. - -import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; -import { z } from "zod"; - -export const workItems = sqliteTable("work_item", { - id: integer("id").primaryKey({ autoIncrement: true }), - title: text("title").notNull(), -}); - -export type WorkItem = InferSelectModel; -export type WorkItemInsert = InferInsertModel; -export type WorkItemUpdate = Partial; - -export const WorkItemInsertSchema = z.object({ - title: z.string().min(1), -}); - -export const WorkItemUpdateSchema = z.object({ - title: z.string().min(1).optional(), -}); - -/** - * Typed create shape for WorkItem: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createWorkItem` call site; - * the schema still validates at runtime. - */ -export type WorkItemCreate = z.input; - -/** - * Typed patch shape for WorkItem: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateWorkItem` call site. - */ -export type WorkItemPatch = z.input; - -/** - * Metadata constants for WorkItem. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(WorkItem, WorkItemInsertSchema); - * - */ -export const WorkItem = { - $entity: "WorkItem", - $table: "work_item", - $path: "/work_items", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - title: { - name: "title", - label: "Title", - view: "text", - htmlType: "text", - rules: { required: "Title is required" }, - }, -} as const; - -export type WorkItemFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: WorkItemFilter[]; - and?: WorkItemFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/consumer.ts b/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/consumer.ts deleted file mode 100644 index 803e8f0b08..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-db-schema-generic-sAIph4/consumer.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { drizzle } from "drizzle-orm/sqlite-proxy"; -import * as schema from "./WorkItem"; -import { findWorkItemById, listWorkItems } from "./WorkItem.queries"; - -// eslint-disable-next-line @typescript-eslint/no-unused-vars -const callback = async () => ({ rows: [] as never[] }); - -export const db = drizzle(callback, { schema }); - -export const one = await findWorkItemById(db, 1); -export const many = await listWorkItems(db, { limit: 10 }); -// `schema` is referenced above; keep the namespace import load-bearing. diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.names.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.names.ts deleted file mode 100644 index 99a0df1b33..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.names.ts +++ /dev/null @@ -1,23 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Broker - -import { PartyNames } from "./Party.names"; - -export const BrokerNames = { - type: "object", - subType: "entity", - name: "Broker", - sources: { - ...PartyNames.sources, - }, - fields: { - ...PartyNames.fields, - mcNumber: { name: "mcNumber", column: "mc_number" }, - }, - identities: { - ...PartyNames.identities, - }, - indexes: { - ...PartyNames.indexes, - }, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.ts deleted file mode 100644 index ff45aaa541..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Broker.ts +++ /dev/null @@ -1,103 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Broker (Broker) -// Extend in your own module (e.g. Broker.extra.ts) — nothing imports it for you. - -import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; -import { z } from "zod"; -import { BrokerNames } from "./Broker.names.js"; - -export interface Broker { - id?: number | undefined; - partyType?: BrokerPartyType | null | undefined; - mcNumber?: string | null | undefined; -} - -export type BrokerPartyType = "Carrier" | "Broker"; -export const BrokerPartyTypeEnum = z.enum(["Carrier", "Broker"]); - -export const BrokerSchema = z.object({ - id: z.number().int(), - partyType: z.literal("Broker"), - mcNumber: z.string().max(20).nullable(), -}); - -export const BrokerInsertSchema = z.object({ - partyType: z.literal("Broker"), - mcNumber: z.string().max(20).optional(), -}); - -export const BrokerUpdateSchema = z.object({ - mcNumber: z.string().max(20).optional().nullable(), -}); - -/** - * Typed create shape for Broker: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createBroker` call site; - * the schema still validates at runtime. - */ -export type BrokerCreate = z.input; - -/** - * Typed patch shape for Broker: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateBroker` call site. - */ -export type BrokerPatch = z.input; - -/** - * Metadata constants for Broker. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Broker, BrokerInsertSchema); - * - */ -export const Broker = { - $entity: "Broker", - $table: BrokerNames.sources.primary.table, - $path: "/parties/broker", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - partyType: { - name: "partyType", - label: "Party Type", - view: "dropdown", - options: ["Carrier", "Broker"] as const, - }, - mcNumber: { - name: "mcNumber", - label: "Mc Number", - view: "text", - htmlType: "text", - rules: { maxLength: { value: 20, message: "Must be 20 characters or fewer" } }, - }, -} as const; - -export const BrokerFilterAllowlist = {} as const satisfies FilterAllowlist; - -export const BrokerSortAllowlist = {} as const satisfies SortAllowlist; - -export type BrokerFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: BrokerFilter[]; - and?: BrokerFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.names.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.names.ts deleted file mode 100644 index a4dd94d375..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.names.ts +++ /dev/null @@ -1,24 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Carrier - -import { OrganizationNames } from "./Organization.names"; - -export const CarrierNames = { - type: "object", - subType: "entity", - name: "Carrier", - sources: { - ...OrganizationNames.sources, - }, - fields: { - ...OrganizationNames.fields, - homeDepotId: { name: "homeDepotId", column: "home_depot_id" }, - }, - identities: { - ...OrganizationNames.identities, - fkHomeDepot: { type: "identity", subType: "reference", name: "fkHomeDepot" }, - }, - indexes: { - ...OrganizationNames.indexes, - }, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.ts deleted file mode 100644 index a9bbbfd3f7..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Carrier.ts +++ /dev/null @@ -1,112 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Carrier (Carrier) -// Extend in your own module (e.g. Carrier.extra.ts) — nothing imports it for you. - -import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; -import { z } from "zod"; -import { CarrierNames } from "./Carrier.names.js"; - -export interface Carrier { - id?: number | undefined; - partyType?: CarrierPartyType | null | undefined; - hqDepotId?: number | null | undefined; - homeDepotId?: number | null | undefined; -} - -export type CarrierPartyType = "Carrier" | "Broker"; -export const CarrierPartyTypeEnum = z.enum(["Carrier", "Broker"]); - -export const CarrierSchema = z.object({ - id: z.number().int(), - partyType: z.literal("Carrier"), - hqDepotId: z.number().int().nullable(), - homeDepotId: z.number().int().nullable(), -}); - -export const CarrierInsertSchema = z.object({ - partyType: z.literal("Carrier"), - hqDepotId: z.number().int().optional(), - homeDepotId: z.number().int().optional(), -}); - -export const CarrierUpdateSchema = z.object({ - hqDepotId: z.number().int().optional().nullable(), - homeDepotId: z.number().int().optional().nullable(), -}); - -/** - * Typed create shape for Carrier: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createCarrier` call site; - * the schema still validates at runtime. - */ -export type CarrierCreate = z.input; - -/** - * Typed patch shape for Carrier: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateCarrier` call site. - */ -export type CarrierPatch = z.input; - -/** - * Metadata constants for Carrier. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Carrier, CarrierInsertSchema); - * - */ -export const Carrier = { - $entity: "Carrier", - $table: CarrierNames.sources.primary.table, - $path: "/parties/carrier", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - partyType: { - name: "partyType", - label: "Party Type", - view: "dropdown", - options: ["Carrier", "Broker"] as const, - }, - hqDepotId: { - name: "hqDepotId", - label: "Hq Depot Id", - view: "number", - htmlType: "number", - }, - homeDepotId: { - name: "homeDepotId", - label: "Home Depot Id", - view: "number", - htmlType: "number", - }, -} as const; - -export const CarrierFilterAllowlist = {} as const satisfies FilterAllowlist; - -export const CarrierSortAllowlist = {} as const satisfies SortAllowlist; - -export type CarrierFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: CarrierFilter[]; - and?: CarrierFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.names.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.names.ts deleted file mode 100644 index 738bb586b0..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.names.ts +++ /dev/null @@ -1,18 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Depot - -export const DepotNames = { - type: "object", - subType: "entity", - name: "Depot", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "depots" }, - }, - fields: { - id: { name: "id", column: "id" }, - }, - identities: { - pk: { type: "identity", subType: "primary", name: "pk" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.queries.ts deleted file mode 100644 index 2a32c4f2ad..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.queries.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Depot (Depot) -// Extend in your own module (e.g. Depot.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -import type { z } from "zod"; -import { type Depot, DepotInsertSchema, type DepotPatch, DepotUpdateSchema, depots } from "./Depot.js"; - -type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; - -export async function findDepotById(db: Db, id: number): Promise { - const [depot] = await db.select().from(depots).where(eq(depots.id, id)).limit(1); - return depot ?? null; -} - -export async function listDepots(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(depots).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createDepot(db: Db, data: z.input): Promise { - const validated = DepotInsertSchema.parse(data); - const [depot] = await db.insert(depots).values(validated).returning(); - return depot!; -} - -export async function updateDepot(db: Db, id: number, patch: DepotPatch): Promise { - const validated = DepotUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findDepotById(db, id); - } - const [depot] = await db.update(depots).set(validated).where(eq(depots.id, id)).returning(); - return depot ?? null; -} - -export async function deleteDepotById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(depots).where(eq(depots.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.ts deleted file mode 100644 index 889457300c..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Depot.ts +++ /dev/null @@ -1,80 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Depot (Depot) -// Extend in your own module (e.g. Depot.extra.ts) — nothing imports it for you. - -import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; -import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { integer, sqliteTable } from "drizzle-orm/sqlite-core"; -import { z } from "zod"; -import { DepotNames } from "./Depot.names.js"; - -export const depots = sqliteTable(DepotNames.sources.primary.table, { - id: integer(DepotNames.fields.id.column).primaryKey({ autoIncrement: true }), -}); - -export type Depot = InferSelectModel; -export type DepotInsert = InferInsertModel; -export type DepotUpdate = Partial; - -export const DepotInsertSchema = z.object({}); - -export const DepotUpdateSchema = z.object({}); - -/** - * Typed create shape for Depot: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createDepot` call site; - * the schema still validates at runtime. - */ -export type DepotCreate = z.input; - -/** - * Typed patch shape for Depot: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateDepot` call site. - */ -export type DepotPatch = z.input; - -/** - * Metadata constants for Depot. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Depot, DepotInsertSchema); - * - */ -export const Depot = { - $entity: "Depot", - $table: DepotNames.sources.primary.table, - $path: "/depots", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, -} as const; - -export const DepotFilterAllowlist = {} as const satisfies FilterAllowlist; - -export const DepotSortAllowlist = {} as const satisfies SortAllowlist; - -export type DepotFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: DepotFilter[]; - and?: DepotFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.names.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.names.ts deleted file mode 100644 index 252e7039cd..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.names.ts +++ /dev/null @@ -1,22 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Leg - -export const LegNames = { - type: "object", - subType: "entity", - name: "Leg", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "legs" }, - }, - fields: { - carrierId: { name: "carrierId", column: "carrier_id" }, - id: { name: "id", column: "id" }, - shipmentId: { name: "shipmentId", column: "shipment_id" }, - }, - identities: { - fkCarrier: { type: "identity", subType: "reference", name: "fkCarrier" }, - fkShipment: { type: "identity", subType: "reference", name: "fkShipment" }, - pk: { type: "identity", subType: "primary", name: "pk" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.queries.ts deleted file mode 100644 index 8b1534c9e1..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.queries.ts +++ /dev/null @@ -1,72 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Leg (Leg) -// Extend in your own module (e.g. Leg.extra.ts) — nothing imports it for you. - -import { eq, inArray } from "drizzle-orm"; -import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -import type { z } from "zod"; -import { type Leg, LegInsertSchema, type LegPatch, LegUpdateSchema, legs } from "./Leg.js"; - -type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; - -export async function findLegById(db: Db, id: number): Promise { - const [leg] = await db.select().from(legs).where(eq(legs.id, id)).limit(1); - return leg ?? null; -} - -export async function listLegs(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(legs).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createLeg(db: Db, data: z.input): Promise { - const validated = LegInsertSchema.parse(data); - const [leg] = await db.insert(legs).values(validated).returning(); - return leg!; -} - -export async function updateLeg(db: Db, id: number, patch: LegPatch): Promise { - const validated = LegUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findLegById(db, id); - } - const [leg] = await db.update(legs).set(validated).where(eq(legs.id, id)).returning(); - return leg ?? null; -} - -export async function deleteLegById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(legs).where(eq(legs.id, id)).returning(); - return deleted.length > 0; -} - -export async function findLegsByShipment(db: Db, shipmentId: number): Promise { - return db.select().from(legs).where(eq(legs.shipmentId, shipmentId)); -} - -export async function findLegsByShipmentIn(db: Db, shipmentIds: number[]): Promise { - if (shipmentIds.length === 0) { - return []; - } - return db.select().from(legs).where(inArray(legs.shipmentId, shipmentIds)); -} - -export async function findLegsByCarrier(db: Db, carrierId: number): Promise { - return db.select().from(legs).where(eq(legs.carrierId, carrierId)); -} - -export async function findLegsByCarrierIn(db: Db, carrierIds: number[]): Promise { - if (carrierIds.length === 0) { - return []; - } - return db.select().from(legs).where(inArray(legs.carrierId, carrierIds)); -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.ts deleted file mode 100644 index 7aaa547ee3..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Leg.ts +++ /dev/null @@ -1,110 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Leg (Leg) -// Extend in your own module (e.g. Leg.extra.ts) — nothing imports it for you. - -import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; -import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; -import { type AnySQLiteColumn, integer, sqliteTable } from "drizzle-orm/sqlite-core"; -import { z } from "zod"; -import { LegNames } from "./Leg.names.js"; -import { parties } from "./Party.js"; -import { shipments } from "./Shipment.js"; - -export const legs = sqliteTable(LegNames.sources.primary.table, { - id: integer(LegNames.fields.id.column).primaryKey({ autoIncrement: true }), - shipmentId: integer(LegNames.fields.shipmentId.column).notNull().references((): AnySQLiteColumn => shipments.id), - carrierId: integer(LegNames.fields.carrierId.column).notNull().references((): AnySQLiteColumn => parties.id), -}); - -export const legsRelations = relations(legs, ({ one }) => ({ - carrier: one(parties, { fields: [legs.carrierId], references: [parties.id] }), - fkShipment: one(shipments, { fields: [legs.shipmentId], references: [shipments.id] }), - fkCarrier: one(parties, { fields: [legs.carrierId], references: [parties.id] }), -})); - -export type Leg = InferSelectModel; -export type LegInsert = InferInsertModel; -export type LegUpdate = Partial; - -export const LegInsertSchema = z.object({ - shipmentId: z.number().int(), - carrierId: z.number().int(), -}); - -export const LegUpdateSchema = z.object({ - shipmentId: z.number().int().optional(), - carrierId: z.number().int().optional(), -}); - -/** - * Typed create shape for Leg: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createLeg` call site; - * the schema still validates at runtime. - */ -export type LegCreate = z.input; - -/** - * Typed patch shape for Leg: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateLeg` call site. - */ -export type LegPatch = z.input; - -/** - * Metadata constants for Leg. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Leg, LegInsertSchema); - * - */ -export const Leg = { - $entity: "Leg", - $table: LegNames.sources.primary.table, - $path: "/legs", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - shipmentId: { - name: "shipmentId", - label: "Shipment Id", - view: "number", - htmlType: "number", - rules: { required: "Shipment Id is required" }, - }, - carrierId: { - name: "carrierId", - label: "Carrier Id", - view: "number", - htmlType: "number", - rules: { required: "Carrier Id is required" }, - }, -} as const; - -export const LegFilterAllowlist = {} as const satisfies FilterAllowlist; - -export const LegSortAllowlist = {} as const satisfies SortAllowlist; - -export type LegFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: LegFilter[]; - and?: LegFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.names.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.names.ts deleted file mode 100644 index 18b9f52811..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.names.ts +++ /dev/null @@ -1,24 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Organization - -import { PartyNames } from "./Party.names"; - -export const OrganizationNames = { - type: "object", - subType: "entity", - name: "Organization", - sources: { - ...PartyNames.sources, - }, - fields: { - ...PartyNames.fields, - hqDepotId: { name: "hqDepotId", column: "hq_depot_id" }, - }, - identities: { - ...PartyNames.identities, - fkHqDepot: { type: "identity", subType: "reference", name: "fkHqDepot" }, - }, - indexes: { - ...PartyNames.indexes, - }, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.ts deleted file mode 100644 index bd588c7c22..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Organization.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Organization (Organization) -// Extend in your own module (e.g. Organization.extra.ts) — nothing imports it for you. - -import { z } from "zod"; - -export interface Organization { - id?: number | undefined; - partyType?: OrganizationPartyType | undefined; - hqDepotId?: number | undefined; -} - -export type OrganizationPartyType = "Carrier" | "Broker"; -export const OrganizationPartyTypeEnum = z.enum(["Carrier", "Broker"]); - -export const OrganizationInsertSchema = z.object({ - partyType: z.enum(["Carrier", "Broker"]).optional(), - hqDepotId: z.number().int().optional(), -}); diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.names.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.names.ts deleted file mode 100644 index 2b664d73fb..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.names.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Party - -export const PartyNames = { - type: "object", - subType: "entity", - name: "Party", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "parties" }, - }, - fields: { - id: { name: "id", column: "id" }, - partyType: { name: "partyType", column: "party_type" }, - }, - identities: { - pk: { type: "identity", subType: "primary", name: "pk" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.queries.ts deleted file mode 100644 index ff7615bd07..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.queries.ts +++ /dev/null @@ -1,101 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Party (Party) — TPH discriminator base -// Extend in your own module (e.g. Party.extra.ts) — nothing imports it for you. - -import { and, eq } from "drizzle-orm"; -import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -import type { z } from "zod"; -import { type Broker, BrokerInsertSchema, BrokerSchema } from "./Broker.js"; -import { type Carrier, CarrierInsertSchema, CarrierSchema } from "./Carrier.js"; -import { type Party, parseParty, parties } from "./Party.js"; - -type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; - -export async function findPartyById(db: Db, id: number): Promise { - const [row] = await db.select().from(parties).where(eq(parties.id, id)).limit(1); - return row ? parseParty(row) : null; -} - -export async function listParties(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(parties).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - const rows = await q; - return rows.map((r) => parseParty(r)); -} - -export async function listBrokers(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(parties).where(eq(parties.partyType, "Broker")).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - const rows = await q; - return rows.map((r) => BrokerSchema.parse(r)); -} - -export async function findBrokerById(db: Db, id: number): Promise { - const [row] = await db.select().from(parties).where(and(eq(parties.id, id), eq(parties.partyType, "Broker"))).limit(1); - return row ? BrokerSchema.parse(row) : null; -} - -export async function createBroker(db: Db, data: z.input): Promise { - const validated = BrokerInsertSchema.parse(data); - const [row] = await db.insert(parties).values({ ...validated, partyType: "Broker" }).returning(); - return BrokerSchema.parse(row!); -} - -export async function updateBrokerById(db: Db, id: number, data: Partial>): Promise { - const validated = BrokerInsertSchema.partial().parse(data) as Record; - // The discriminator is immutable — a Broker can never become another subtype. - const { ["partyType"]: _disc, ...safe } = validated; - const [row] = await db.update(parties).set(safe).where(and(eq(parties.id, id), eq(parties.partyType, "Broker"))).returning(); - return row ? BrokerSchema.parse(row) : null; -} - -export async function deleteBrokerById(db: Db, id: number): Promise { - const deleted = await db.delete(parties).where(and(eq(parties.id, id), eq(parties.partyType, "Broker"))).returning(); - return deleted.length > 0; -} - -export async function listCarriers(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(parties).where(eq(parties.partyType, "Carrier")).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - const rows = await q; - return rows.map((r) => CarrierSchema.parse(r)); -} - -export async function findCarrierById(db: Db, id: number): Promise { - const [row] = await db.select().from(parties).where(and(eq(parties.id, id), eq(parties.partyType, "Carrier"))).limit(1); - return row ? CarrierSchema.parse(row) : null; -} - -export async function createCarrier(db: Db, data: z.input): Promise { - const validated = CarrierInsertSchema.parse(data); - const [row] = await db.insert(parties).values({ ...validated, partyType: "Carrier" }).returning(); - return CarrierSchema.parse(row!); -} - -export async function updateCarrierById(db: Db, id: number, data: Partial>): Promise { - const validated = CarrierInsertSchema.partial().parse(data) as Record; - // The discriminator is immutable — a Carrier can never become another subtype. - const { ["partyType"]: _disc, ...safe } = validated; - const [row] = await db.update(parties).set(safe).where(and(eq(parties.id, id), eq(parties.partyType, "Carrier"))).returning(); - return row ? CarrierSchema.parse(row) : null; -} - -export async function deleteCarrierById(db: Db, id: number): Promise { - const deleted = await db.delete(parties).where(and(eq(parties.id, id), eq(parties.partyType, "Carrier"))).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.ts deleted file mode 100644 index 4f2d8abe6c..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Party.ts +++ /dev/null @@ -1,130 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Party (Party) -// Extend in your own module (e.g. Party.extra.ts) — nothing imports it for you. - -import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; -import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; -import { type AnySQLiteColumn, check, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; -import { z } from "zod"; -import { type Broker, BrokerSchema } from "./Broker.js"; -import { BrokerNames } from "./Broker.names.js"; -import { type Carrier, CarrierSchema } from "./Carrier.js"; -import { CarrierNames } from "./Carrier.names.js"; -import { depots } from "./Depot.js"; -import { OrganizationNames } from "./Organization.names.js"; -import { PartyNames } from "./Party.names.js"; - -export const parties = sqliteTable(PartyNames.sources.primary.table, { - id: integer(PartyNames.fields.id.column).primaryKey({ autoIncrement: true }), - partyType: text(PartyNames.fields.partyType.column, { enum: ["Carrier", "Broker"] as const }), - mcNumber: text(BrokerNames.fields.mcNumber.column), - hqDepotId: integer(OrganizationNames.fields.hqDepotId.column).references((): AnySQLiteColumn => depots.id), - homeDepotId: integer(CarrierNames.fields.homeDepotId.column).references((): AnySQLiteColumn => depots.id), -}, (table) => [ - check(`${PartyNames.sources.primary.table}_${PartyNames.fields.partyType.column}_chk`, sql`${sql.raw(PartyNames.fields.partyType.column)} IN ('Carrier', 'Broker')`), -]); - -export type PartyRow = InferSelectModel; -export type PartyInsert = InferInsertModel; -export type PartyUpdate = Partial; - -export type PartyPartyType = "Carrier" | "Broker"; -export const PartyPartyTypeEnum = z.enum(["Carrier", "Broker"]); - -export const PartyInsertSchema = z.object({ - partyType: z.enum(["Carrier", "Broker"]).optional(), -}); - -export const PartyUpdateSchema = z.object({ - partyType: z.enum(["Carrier", "Broker"]).optional().nullable(), -}); - -/** - * Typed create shape for Party: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createParty` call site; - * the schema still validates at runtime. - */ -export type PartyCreate = z.input; - -/** - * Typed patch shape for Party: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateParty` call site. - */ -export type PartyPatch = z.input; - -/** - * Metadata constants for Party. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Party, PartyInsertSchema); - * - */ -export const Party = { - $entity: "Party", - $table: PartyNames.sources.primary.table, - $path: "/parties", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, - partyType: { - name: "partyType", - label: "Party Type", - view: "dropdown", - options: ["Carrier", "Broker"] as const, - }, -} as const; - -export const PartyFilterAllowlist = {} as const satisfies FilterAllowlist; - -export const PartySortAllowlist = {} as const satisfies SortAllowlist; - -export type PartyFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: PartyFilter[]; - and?: PartyFilter[]; -}; - -export type Party = Broker | Carrier; - -/** True when value is a Broker (discriminated by partyType === "Broker"). */ -export function isBroker(value: Party): value is Broker { - return value.partyType === "Broker"; -} - -/** True when value is a Carrier (discriminated by partyType === "Carrier"). */ -export function isCarrier(value: Party): value is Carrier { - return value.partyType === "Carrier"; -} - -/** - * Parse a row from the Party table, dispatching by the - * `partyType` discriminator value to the matching subtype's - * Zod schema. Throws on unknown discriminator values. - */ -export function parseParty(row: unknown): Party { - const head = z.object({ partyType: z.enum(["Broker", "Carrier"]) }).parse(row); - switch (head.partyType) { - case "Broker": return BrokerSchema.parse(row); - case "Carrier": return CarrierSchema.parse(row); - } -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.names.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.names.ts deleted file mode 100644 index 0a9f4af871..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.names.ts +++ /dev/null @@ -1,18 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Shipment - -export const ShipmentNames = { - type: "object", - subType: "entity", - name: "Shipment", - sources: { - primary: { type: "source", subType: "rdb", kind: "table", table: "shipments" }, - }, - fields: { - id: { name: "id", column: "id" }, - }, - identities: { - pk: { type: "identity", subType: "primary", name: "pk" }, - }, - indexes: {}, -} as const; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.queries.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.queries.ts deleted file mode 100644 index 058c2a82fb..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.queries.ts +++ /dev/null @@ -1,56 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Shipment (Shipment) -// Extend in your own module (e.g. Shipment.extra.ts) — nothing imports it for you. - -import { eq } from "drizzle-orm"; -import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -import type { z } from "zod"; -import { - type Shipment, - ShipmentInsertSchema, - type ShipmentPatch, - ShipmentUpdateSchema, - shipments, -} from "./Shipment.js"; - -type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; - -export async function findShipmentById(db: Db, id: number): Promise { - const [shipment] = await db.select().from(shipments).where(eq(shipments.id, id)).limit(1); - return shipment ?? null; -} - -export async function listShipments(db: Db, opts?: { limit?: number; offset?: number }): Promise { - let q = db.select().from(shipments).$dynamic(); - if (opts?.limit !== undefined) { - q = q.limit(opts.limit); - } - if (opts?.offset !== undefined) { - q = q.offset(opts.offset); - } - return q; -} - -export async function createShipment(db: Db, data: z.input): Promise { - const validated = ShipmentInsertSchema.parse(data); - const [shipment] = await db.insert(shipments).values(validated).returning(); - return shipment!; -} - -export async function updateShipment(db: Db, id: number, patch: ShipmentPatch): Promise { - const validated = ShipmentUpdateSchema.parse(patch); - // PATCH-5: an empty patch is a no-op — return the current row rather than let - // Drizzle throw on an empty SET clause. - if (Object.keys(validated).length === 0) { - return findShipmentById(db, id); - } - const [shipment] = await db.update(shipments).set(validated).where(eq(shipments.id, id)).returning(); - return shipment ?? null; -} - -export async function deleteShipmentById(db: Db, id: number): Promise { - // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) - // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db.delete(shipments).where(eq(shipments.id, id)).returning(); - return deleted.length > 0; -} diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.ts deleted file mode 100644 index fb10eb0dc1..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/Shipment.ts +++ /dev/null @@ -1,85 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -// Source metadata: Shipment (Shipment) -// Extend in your own module (e.g. Shipment.extra.ts) — nothing imports it for you. - -import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; -import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; -import { integer, sqliteTable } from "drizzle-orm/sqlite-core"; -import { z } from "zod"; -import { legs } from "./Leg.js"; -import { ShipmentNames } from "./Shipment.names.js"; - -export const shipments = sqliteTable(ShipmentNames.sources.primary.table, { - id: integer(ShipmentNames.fields.id.column).primaryKey({ autoIncrement: true }), -}); - -export const shipmentsRelations = relations(shipments, ({ many }) => ({ - carriers: many(legs), -})); - -export type Shipment = InferSelectModel; -export type ShipmentInsert = InferInsertModel; -export type ShipmentUpdate = Partial; - -export const ShipmentInsertSchema = z.object({}); - -export const ShipmentUpdateSchema = z.object({}); - -/** - * Typed create shape for Shipment: the insert schema's INPUT (pre-transform) type. A - * renamed/dropped/misspelt field is a compile error at every `createShipment` call site; - * the schema still validates at runtime. - */ -export type ShipmentCreate = z.input; - -/** - * Typed patch shape for Shipment: every settable field, optional (FR-035 PATCH). A - * renamed/dropped field is a compile error at every `updateShipment` call site. - */ -export type ShipmentPatch = z.input; - -/** - * Metadata constants for Shipment. - * - * Use these instead of magic strings so TS catches typos and refactors stay - * coherent. Each non-dollar-prefixed key is a per-field object carrying - * name, label, view, an htmlType where the field's view maps to one, and the - * RHF-shaped validation rules derived from the field's validator children. - * - * placeholder and helpText are NOT emitted — no provider registers an attribute - * for them, so nothing here could derive one. (htmlType is emitted, but derived - * from the view subtype; the @htmlType override was removed for the same reason.) - * useEntityForm still honours placeholder if you add it: this file is generated, - * hand edits inside it survive regeneration through the three-way merge, and the - * consumers read this const rather than the metadata. That is the intended way - * to set it. - * - * Typical usage with the metaobjects React form helper: - * - * import { useEntityForm } from '@metaobjectsdev/react'; - * const form = useEntityForm(Shipment, ShipmentInsertSchema); - * - */ -export const Shipment = { - $entity: "Shipment", - $table: ShipmentNames.sources.primary.table, - $path: "/shipments", - id: { - name: "id", - label: "Id", - view: "number", - htmlType: "number", - }, -} as const; - -export const ShipmentFilterAllowlist = {} as const satisfies FilterAllowlist; - -export const ShipmentSortAllowlist = {} as const satisfies SortAllowlist; - -export type ShipmentFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: ShipmentFilter[]; - and?: ShipmentFilter[]; -}; diff --git a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/index.ts b/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/index.ts deleted file mode 100644 index ade411d2f1..0000000000 --- a/server/typescript/packages/codegen-ts/test/tmp-tph-ref-sqlite-YoKZOH/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -export * from "./Broker.js"; -export * from "./Carrier.js"; -export * from "./Depot.js"; -export * from "./Leg.js"; -export * from "./Organization.js"; -export * from "./Party.js"; -export * from "./Shipment.js"; From 30ffcbb6f1e0a2d4f28e1867a9efb4c2e817a765 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 5 Dec 2026 03:15:33 -0500 Subject: [PATCH 10/10] no-mistakes(document): Retire event sibling reserved name in docs --- docs/compatibility-policy.md | 4 ++-- docs/features/stability-labels.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/compatibility-policy.md b/docs/compatibility-policy.md index 53e1c9f4c7..ae3fd0b65d 100644 --- a/docs/compatibility-policy.md +++ b/docs/compatibility-policy.md @@ -88,8 +88,8 @@ work*. A release can move one without the other, and most releases move neither. [own-your-codegen](features/own-your-codegen.md). - **Runtime-library helper internals.** Idiomatic per port; best-effort, not promised. - **Anything explicitly marked experimental or reserved** and not yet in the registry - (e.g. the reserved lifecycle subtype `transition.timed`, the reserved event and streaming - sibling of `api.operational`, and reserved index subtypes `index.fulltext`/`vector`/`spatial`). + (e.g. the reserved lifecycle subtype `transition.timed` and reserved index subtypes + `index.fulltext`/`vector`/`spatial`). - **The business-rules vocabulary, which is experimental.** `api.*`, `operation.*`, `binding.*`, lifecycles (`transition.action` and what it derives) and the permission points (`@permission`, `@public`) are registered since 1.3.0 (ADR-0066), together with their loader diff --git a/docs/features/stability-labels.md b/docs/features/stability-labels.md index d71df1683c..aaed28e6e1 100644 --- a/docs/features/stability-labels.md +++ b/docs/features/stability-labels.md @@ -25,7 +25,7 @@ the [compatibility policy](../compatibility-policy.md), which stands as written. | Library `iam` | preview | [Libraries](libraries.md) | | Angular packages | source-only, on their own `0.6` line, not published | ADR-0048 | | Business-rules vocabulary: `api.*`, `operation.*`, `binding.*`, `transition.*`, `@permission`, `@public`, and the `rules` and `verify.lifecycle` settings | experimental | [Business rules](business-rules.md), ADR-0066 | -| Reserved names (`transition.timed`, the event and streaming sibling of `api.operational`, `index.fulltext`, `index.vector`, `index.spatial`) | reserved: not in the registry | [Compatibility policy](../compatibility-policy.md) | +| Reserved names (`transition.timed`, `index.fulltext`, `index.vector`, `index.spatial`) | reserved: not in the registry | [Compatibility policy](../compatibility-policy.md) | ## What is not here yet